Skip to content

Commit c6baa45

Browse files
committed
Replace WatchEventProvider with chain::Notify
WatchEventProvider served as a means for replacing ChainWatchInterface. However, it requires users to explicitly fetch WatchEvents, even if not interested in them. Replace WatchEventProvider by chain::Notify, which is an optional member of ChainMonitor. If set, interesting transactions and output spends are registered such that blocks containing them can be retrieved from a chain source in an efficient manner. This is useful when the chain source is not a full node. For Electrum, it allows for pre-filtered blocks. For BIP157/158, it serves as a means to match against compact filters.
1 parent 13a3323 commit c6baa45

File tree

9 files changed

+125
-103
lines changed

9 files changed

+125
-103
lines changed

ARCH.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ At a high level, some of the common interfaces fit together as follows:
5454
| ----------------- \ _---------------- / /
5555
| | chain::Access | \ / | ChainMonitor |---------------
5656
| ----------------- \ / ----------------
57-
| | \ /
58-
(as RoutingMessageHandler) v v
59-
\ -------------------- ---------
60-
-----------------> | NetGraphMsgHandler | | Event |
61-
-------------------- ---------
57+
| | \ / |
58+
(as RoutingMessageHandler) v v v
59+
\ -------------------- --------- -----------------
60+
-----------------> | NetGraphMsgHandler | | Event | | chain::Notify |
61+
-------------------- --------- -----------------
6262
```

fuzz/src/chanmon_consistency.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl Writer for VecWriter {
7575

7676
struct TestChainMonitor {
7777
pub logger: Arc<dyn Logger>,
78-
pub chain_monitor: Arc<channelmonitor::ChainMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
78+
pub chain_monitor: Arc<channelmonitor::ChainMonitor<OutPoint, EnforcingChannelKeys, Arc<dyn chain::Notify>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
7979
pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
8080
// If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
8181
// logic will automatically force-close our channels for us (as we don't have an up-to-date
@@ -88,7 +88,7 @@ struct TestChainMonitor {
8888
impl TestChainMonitor {
8989
pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>) -> Self {
9090
Self {
91-
chain_monitor: Arc::new(channelmonitor::ChainMonitor::new(broadcaster, logger.clone(), feeest)),
91+
chain_monitor: Arc::new(channelmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest)),
9292
logger,
9393
update_ret: Mutex::new(Ok(())),
9494
latest_monitors: Mutex::new(HashMap::new()),

fuzz/src/full_stack.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,14 +137,14 @@ impl<'a> std::hash::Hash for Peer<'a> {
137137

138138
type ChannelMan = ChannelManager<
139139
EnforcingChannelKeys,
140-
Arc<channelmonitor::ChainMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
140+
Arc<channelmonitor::ChainMonitor<OutPoint, EnforcingChannelKeys, Arc<dyn chain::Notify>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
141141
Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
142142
type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
143143

144144
struct MoneyLossDetector<'a> {
145145
manager: Arc<ChannelMan>,
146146
monitor: Arc<channelmonitor::ChainMonitor<
147-
OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
147+
OutPoint, EnforcingChannelKeys, Arc<dyn chain::Notify>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
148148
handler: PeerMan<'a>,
149149

150150
peers: &'a RefCell<[bool; 256]>,
@@ -158,7 +158,7 @@ struct MoneyLossDetector<'a> {
158158
impl<'a> MoneyLossDetector<'a> {
159159
pub fn new(peers: &'a RefCell<[bool; 256]>,
160160
manager: Arc<ChannelMan>,
161-
monitor: Arc<channelmonitor::ChainMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
161+
monitor: Arc<channelmonitor::ChainMonitor<OutPoint, EnforcingChannelKeys, Arc<dyn chain::Notify>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
162162
handler: PeerMan<'a>) -> Self {
163163
MoneyLossDetector {
164164
manager,
@@ -332,7 +332,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
332332
};
333333

334334
let broadcast = Arc::new(TestBroadcaster{});
335-
let monitor = Arc::new(channelmonitor::ChainMonitor::new(broadcast.clone(), Arc::clone(&logger), fee_est.clone()));
335+
let monitor = Arc::new(channelmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone()));
336336

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

lightning-net-tokio/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
//! type FeeEstimator = dyn lightning::chain::chaininterface::FeeEstimator;
2727
//! type Logger = dyn lightning::util::logger::Logger;
2828
//! type ChainAccess = dyn lightning::chain::Access;
29-
//! type ChainMonitor = lightning::ln::channelmonitor::ChainMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>>;
29+
//! type ChainNotify = dyn lightning::chain::Notify;
30+
//! type ChainMonitor = lightning::ln::channelmonitor::ChainMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<ChainNotify>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>>;
3031
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor, TxBroadcaster, FeeEstimator, Logger>;
3132
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChainMonitor, TxBroadcaster, FeeEstimator, ChainAccess, Logger>;
3233
//!

lightning/src/chain/mod.rs

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -79,32 +79,22 @@ pub trait Watch: Send + Sync {
7979
fn release_pending_htlc_updates(&self) -> Vec<HTLCUpdate>;
8080
}
8181

82-
/// An interface for providing [`WatchEvent`]s.
82+
/// The `Notify` trait defines behavior for indicating chain activity of interest pertaining to
83+
/// channels.
8384
///
84-
/// [`WatchEvent`]: enum.WatchEvent.html
85-
pub trait WatchEventProvider {
86-
/// Releases events produced since the last call. Subsequent calls must only return new events.
87-
fn release_pending_watch_events(&self) -> Vec<WatchEvent>;
88-
}
89-
90-
/// An event indicating on-chain activity to watch for pertaining to a channel.
91-
pub enum WatchEvent {
92-
/// Watch for a transaction with `txid` and having an output with `script_pubkey` as a spending
93-
/// condition.
94-
WatchTransaction {
95-
/// Identifier of the transaction.
96-
txid: Txid,
97-
98-
/// Spending condition for an output of the transaction.
99-
script_pubkey: Script,
100-
},
101-
/// Watch for spends of a transaction output identified by `outpoint` having `script_pubkey` as
102-
/// the spending condition.
103-
WatchOutput {
104-
/// Identifier for the output.
105-
outpoint: OutPoint,
85+
/// This is useful in order to have a [`Watch`] implementation convey to a chain source which
86+
/// transactions to be notified of. This may take the form of pre-filtering blocks or, in the case
87+
/// of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches.
88+
///
89+
/// [`Watch`]: trait.Watch.html
90+
/// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
91+
/// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
92+
pub trait Notify: Send + Sync {
93+
/// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
94+
/// a spending condition.
95+
fn register_tx(&self, txid: Txid, script_pubkey: Script);
10696

107-
/// Spending condition for the output.
108-
script_pubkey: Script,
109-
}
97+
/// Registers interest in spends of a transaction output identified by `outpoint` having
98+
/// `script_pubkey` as the spending condition.
99+
fn register_output(&self, outpoint: OutPoint, script_pubkey: Script);
110100
}

lightning/src/ln/channelmonitor.rs

Lines changed: 77 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, Loca
3535
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
3636
use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
3737
use chain;
38+
use chain::Notify;
3839
use chain::chaininterface::{ChainWatchedUtil, BroadcasterInterface, FeeEstimator};
3940
use chain::transaction::OutPoint;
4041
use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
@@ -167,27 +168,51 @@ impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
167168
/// `OutPoint` as the key, which will give you a [`chain::Watch`] implementation.
168169
///
169170
/// [`chain::Watch`]: ../../chain/trait.Watch.html
170-
pub struct ChainMonitor<Key, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref>
171-
where T::Target: BroadcasterInterface,
171+
pub struct ChainMonitor<Key, ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref>
172+
where C::Target: chain::Notify,
173+
T::Target: BroadcasterInterface,
172174
F::Target: FeeEstimator,
173175
L::Target: Logger,
174176
{
175177
#[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
176178
pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
177179
#[cfg(not(test))]
178180
monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
179-
watch_events: Mutex<WatchEventQueue>,
181+
watch_events: Mutex<WatchEventCache>,
182+
chain_source: Option<C>,
180183
broadcaster: T,
181184
logger: L,
182185
fee_estimator: F
183186
}
184187

185-
struct WatchEventQueue {
188+
struct WatchEventCache {
186189
watched: ChainWatchedUtil,
187-
events: Vec<chain::WatchEvent>,
190+
events: Vec<WatchEvent>,
188191
}
189192

190-
impl WatchEventQueue {
193+
/// An event indicating on-chain activity to watch for pertaining to a channel.
194+
enum WatchEvent {
195+
/// Watch for a transaction with `txid` and having an output with `script_pubkey` as a spending
196+
/// condition.
197+
WatchTransaction {
198+
/// Identifier of the transaction.
199+
txid: Txid,
200+
201+
/// Spending condition for an output of the transaction.
202+
script_pubkey: Script,
203+
},
204+
/// Watch for spends of a transaction output identified by `outpoint` having `script_pubkey` as
205+
/// the spending condition.
206+
WatchOutput {
207+
/// Identifier for the output.
208+
outpoint: OutPoint,
209+
210+
/// Spending condition for the output.
211+
script_pubkey: Script,
212+
}
213+
}
214+
215+
impl WatchEventCache {
191216
fn new() -> Self {
192217
Self {
193218
watched: ChainWatchedUtil::new(),
@@ -197,7 +222,7 @@ impl WatchEventQueue {
197222

198223
fn watch_tx(&mut self, txid: &Txid, script_pubkey: &Script) {
199224
if self.watched.register_tx(txid, script_pubkey) {
200-
self.events.push(chain::WatchEvent::WatchTransaction {
225+
self.events.push(WatchEvent::WatchTransaction {
201226
txid: *txid,
202227
script_pubkey: script_pubkey.clone()
203228
});
@@ -207,7 +232,7 @@ impl WatchEventQueue {
207232
fn watch_output(&mut self, outpoint: (&Txid, usize), script_pubkey: &Script) {
208233
let (txid, index) = outpoint;
209234
if self.watched.register_outpoint((*txid, index as u32), script_pubkey) {
210-
self.events.push(chain::WatchEvent::WatchOutput {
235+
self.events.push(WatchEvent::WatchOutput {
211236
outpoint: OutPoint {
212237
txid: *txid,
213238
index: index as u16,
@@ -217,24 +242,43 @@ impl WatchEventQueue {
217242
}
218243
}
219244

220-
fn dequeue_events(&mut self) -> Vec<chain::WatchEvent> {
221-
let mut pending_events = Vec::with_capacity(self.events.len());
222-
pending_events.append(&mut self.events);
223-
pending_events
245+
fn flush_events<C: Deref>(&mut self, chain_source: &Option<C>) -> bool where C::Target: chain::Notify {
246+
let num_events = self.events.len();
247+
match chain_source {
248+
&None => self.events.clear(),
249+
&Some(ref chain_source) => {
250+
for event in self.events.drain(..) {
251+
match event {
252+
WatchEvent::WatchTransaction { txid, script_pubkey } => {
253+
chain_source.register_tx(txid, script_pubkey)
254+
},
255+
WatchEvent::WatchOutput { outpoint, script_pubkey } => {
256+
chain_source.register_output(outpoint, script_pubkey)
257+
},
258+
}
259+
}
260+
}
261+
}
262+
num_events > 0
224263
}
225264
}
226265

227-
impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, ChanSigner, T, F, L>
228-
where T::Target: BroadcasterInterface,
266+
impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, ChanSigner, C, T, F, L>
267+
where C::Target: chain::Notify,
268+
T::Target: BroadcasterInterface,
229269
F::Target: FeeEstimator,
230270
L::Target: Logger,
231271
{
232272
/// Delegates to [`ChannelMonitor::block_connected`] for each watched channel. Any HTLCs that
233273
/// were resolved on chain will be retuned by [`chain::Watch::release_pending_htlc_updates`].
234274
///
275+
/// Calls back to [`chain::Notify`] if any monitor indicated new outputs to watch, returning
276+
/// `true` if so.
277+
///
235278
/// [`ChannelMonitor::block_connected`]: struct.ChannelMonitor.html#method.block_connected
236279
/// [`chain::Watch::release_pending_htlc_updates`]: ../../chain/trait.Watch.html#tymethod.release_pending_htlc_updates
237-
pub fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32) {
280+
/// [`chain::Notify`]: ../../chain/trait.Notify.html
281+
pub fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32) -> bool {
238282
let mut watch_events = self.watch_events.lock().unwrap();
239283
let matched_txn: Vec<_> = txdata.iter().filter(|&&(_, tx)| watch_events.watched.does_match_tx(tx)).map(|e| *e).collect();
240284
{
@@ -249,6 +293,7 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: De
249293
}
250294
}
251295
}
296+
watch_events.flush_events(&self.chain_source)
252297
}
253298

254299
/// Delegates to [`ChannelMonitor::block_disconnected`] for each watched channel.
@@ -262,24 +307,30 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: De
262307
}
263308
}
264309

265-
impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, ChanSigner, T, F, L>
266-
where T::Target: BroadcasterInterface,
310+
impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, ChanSigner, C, T, F, L>
311+
where C::Target: chain::Notify,
312+
T::Target: BroadcasterInterface,
267313
F::Target: FeeEstimator,
268314
L::Target: Logger,
269315
{
270316
/// Creates a new object which can be used to monitor several channels given the chain
271317
/// interface with which to register to receive notifications.
272-
pub fn new(broadcaster: T, logger: L, feeest: F) -> ChainMonitor<Key, ChanSigner, T, F, L> {
318+
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F) -> ChainMonitor<Key, ChanSigner, C, T, F, L> {
273319
Self {
274320
monitors: Mutex::new(HashMap::new()),
275-
watch_events: Mutex::new(WatchEventQueue::new()),
321+
watch_events: Mutex::new(WatchEventCache::new()),
322+
chain_source,
276323
broadcaster,
277324
logger,
278325
fee_estimator: feeest,
279326
}
280327
}
281328

282329
/// Adds or updates the monitor which monitors the channel referred to by the given key.
330+
///
331+
/// Calls back to [`chain::Notify`] with the funding transaction and outputs to watch.
332+
///
333+
/// [`chain::Notify`]: ../../chain/trait.Notify.html
283334
pub fn add_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
284335
let mut watch_events = self.watch_events.lock().unwrap();
285336
let mut monitors = self.monitors.lock().unwrap();
@@ -299,6 +350,7 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: De
299350
}
300351
}
301352
entry.insert(monitor);
353+
watch_events.flush_events(&self.chain_source);
302354
Ok(())
303355
}
304356

@@ -315,8 +367,9 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: De
315367
}
316368
}
317369

318-
impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send> chain::Watch for ChainMonitor<OutPoint, ChanSigner, T, F, L>
319-
where T::Target: BroadcasterInterface,
370+
impl<ChanSigner: ChannelKeys, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send> chain::Watch for ChainMonitor<OutPoint, ChanSigner, C, T, F, L>
371+
where C::Target: chain::Notify,
372+
T::Target: BroadcasterInterface,
320373
F::Target: FeeEstimator,
321374
L::Target: Logger,
322375
{
@@ -345,8 +398,9 @@ impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L:
345398
}
346399
}
347400

348-
impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<Key, ChanSigner, T, F, L>
349-
where T::Target: BroadcasterInterface,
401+
impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<Key, ChanSigner, C, T, F, L>
402+
where C::Target: chain::Notify,
403+
T::Target: BroadcasterInterface,
350404
F::Target: FeeEstimator,
351405
L::Target: Logger,
352406
{
@@ -359,16 +413,6 @@ impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: De
359413
}
360414
}
361415

362-
impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> chain::WatchEventProvider for ChainMonitor<Key, ChanSigner, T, F, L>
363-
where T::Target: BroadcasterInterface,
364-
F::Target: FeeEstimator,
365-
L::Target: Logger,
366-
{
367-
fn release_pending_watch_events(&self) -> Vec<chain::WatchEvent> {
368-
self.watch_events.lock().unwrap().dequeue_events()
369-
}
370-
}
371-
372416
/// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
373417
/// instead claiming it in its own individual transaction.
374418
pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;

0 commit comments

Comments
 (0)