Skip to content

Commit 5d5095e

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 cb7bada commit 5d5095e

File tree

9 files changed

+125
-104
lines changed

9 files changed

+125
-104
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<EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
78+
pub chain_monitor: Arc<channelmonitor::ChainMonitor<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,13 +137,13 @@ impl<'a> std::hash::Hash for Peer<'a> {
137137

138138
type ChannelMan = ChannelManager<
139139
EnforcingChannelKeys,
140-
Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
140+
Arc<channelmonitor::ChainMonitor<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>,
146-
monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
146+
monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Notify>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
147147
handler: PeerMan<'a>,
148148

149149
peers: &'a RefCell<[bool; 256]>,
@@ -157,7 +157,7 @@ struct MoneyLossDetector<'a> {
157157
impl<'a> MoneyLossDetector<'a> {
158158
pub fn new(peers: &'a RefCell<[bool; 256]>,
159159
manager: Arc<ChannelMan>,
160-
monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
160+
monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Notify>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
161161
handler: PeerMan<'a>) -> Self {
162162
MoneyLossDetector {
163163
manager,
@@ -331,7 +331,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
331331
};
332332

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

336336
let keys_manager = Arc::new(KeyProvider { node_secret: our_network_key.clone(), counter: AtomicU64::new(0) });
337337
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::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>>;
29+
//! type ChainNotify = dyn lightning::chain::Notify;
30+
//! type ChainMonitor = lightning::ln::channelmonitor::ChainMonitor<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 & 34 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};
@@ -160,28 +161,51 @@ impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
160161
/// independently to monitor channels remotely.
161162
///
162163
/// [`chain::Watch`]: ../../chain/trait.Watch.html
163-
/// [`ChannelManager`]: ../channelmanager/struct.ChannelManager.html
164-
pub struct ChainMonitor<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref>
165-
where T::Target: BroadcasterInterface,
164+
pub struct ChainMonitor<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref>
165+
where C::Target: chain::Notify,
166+
T::Target: BroadcasterInterface,
166167
F::Target: FeeEstimator,
167168
L::Target: Logger,
168169
{
169170
#[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
170171
pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
171172
#[cfg(not(test))]
172173
monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
173-
watch_events: Mutex<WatchEventQueue>,
174+
watch_events: Mutex<WatchEventCache>,
175+
chain_source: Option<C>,
174176
broadcaster: T,
175177
logger: L,
176178
fee_estimator: F
177179
}
178180

179-
struct WatchEventQueue {
181+
struct WatchEventCache {
180182
watched: ChainWatchedUtil,
181-
events: Vec<chain::WatchEvent>,
183+
events: Vec<WatchEvent>,
182184
}
183185

184-
impl WatchEventQueue {
186+
/// An event indicating on-chain activity to watch for pertaining to a channel.
187+
enum WatchEvent {
188+
/// Watch for a transaction with `txid` and having an output with `script_pubkey` as a spending
189+
/// condition.
190+
WatchTransaction {
191+
/// Identifier of the transaction.
192+
txid: Txid,
193+
194+
/// Spending condition for an output of the transaction.
195+
script_pubkey: Script,
196+
},
197+
/// Watch for spends of a transaction output identified by `outpoint` having `script_pubkey` as
198+
/// the spending condition.
199+
WatchOutput {
200+
/// Identifier for the output.
201+
outpoint: OutPoint,
202+
203+
/// Spending condition for the output.
204+
script_pubkey: Script,
205+
}
206+
}
207+
208+
impl WatchEventCache {
185209
fn new() -> Self {
186210
Self {
187211
watched: ChainWatchedUtil::new(),
@@ -191,7 +215,7 @@ impl WatchEventQueue {
191215

192216
fn watch_tx(&mut self, txid: &Txid, script_pubkey: &Script) {
193217
if self.watched.register_tx(txid, script_pubkey) {
194-
self.events.push(chain::WatchEvent::WatchTransaction {
218+
self.events.push(WatchEvent::WatchTransaction {
195219
txid: *txid,
196220
script_pubkey: script_pubkey.clone()
197221
});
@@ -201,7 +225,7 @@ impl WatchEventQueue {
201225
fn watch_output(&mut self, outpoint: (&Txid, usize), script_pubkey: &Script) {
202226
let (txid, index) = outpoint;
203227
if self.watched.register_outpoint((*txid, index as u32), script_pubkey) {
204-
self.events.push(chain::WatchEvent::WatchOutput {
228+
self.events.push(WatchEvent::WatchOutput {
205229
outpoint: OutPoint {
206230
txid: *txid,
207231
index: index as u16,
@@ -211,24 +235,43 @@ impl WatchEventQueue {
211235
}
212236
}
213237

214-
fn dequeue_events(&mut self) -> Vec<chain::WatchEvent> {
215-
let mut pending_events = Vec::with_capacity(self.events.len());
216-
pending_events.append(&mut self.events);
217-
pending_events
238+
fn flush_events<C: Deref>(&mut self, chain_source: &Option<C>) -> bool where C::Target: chain::Notify {
239+
let num_events = self.events.len();
240+
match chain_source {
241+
&None => self.events.clear(),
242+
&Some(ref chain_source) => {
243+
for event in self.events.drain(..) {
244+
match event {
245+
WatchEvent::WatchTransaction { txid, script_pubkey } => {
246+
chain_source.register_tx(txid, script_pubkey)
247+
},
248+
WatchEvent::WatchOutput { outpoint, script_pubkey } => {
249+
chain_source.register_output(outpoint, script_pubkey)
250+
},
251+
}
252+
}
253+
}
254+
}
255+
num_events > 0
218256
}
219257
}
220258

221-
impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, ChanSigner, T, F, L>
222-
where T::Target: BroadcasterInterface,
259+
impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSigner, C, T, F, L>
260+
where C::Target: chain::Notify,
261+
T::Target: BroadcasterInterface,
223262
F::Target: FeeEstimator,
224263
L::Target: Logger,
225264
{
226265
/// Delegates to [`ChannelMonitor::block_connected`] for each watched channel. Any HTLCs that
227266
/// were resolved on chain will be retuned by [`chain::Watch::release_pending_htlc_updates`].
228267
///
268+
/// Calls back to [`chain::Notify`] if any monitor indicated new outputs to watch, returning
269+
/// `true` if so.
270+
///
229271
/// [`ChannelMonitor::block_connected`]: struct.ChannelMonitor.html#method.block_connected
230272
/// [`chain::Watch::release_pending_htlc_updates`]: ../../chain/trait.Watch.html#tymethod.release_pending_htlc_updates
231-
pub fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32) {
273+
/// [`chain::Notify`]: ../../chain/trait.Notify.html
274+
pub fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32) -> bool {
232275
let mut watch_events = self.watch_events.lock().unwrap();
233276
let matched_txn: Vec<_> = txdata.iter().filter(|&&(_, tx)| watch_events.watched.does_match_tx(tx)).map(|e| *e).collect();
234277
{
@@ -243,6 +286,7 @@ impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, Ch
243286
}
244287
}
245288
}
289+
watch_events.flush_events(&self.chain_source)
246290
}
247291

248292
/// Delegates to [`ChannelMonitor::block_disconnected`] for each watched channel.
@@ -256,24 +300,30 @@ impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<Key, Ch
256300
}
257301
}
258302

259-
impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSigner, T, F, L>
260-
where T::Target: BroadcasterInterface,
303+
impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSigner, C, T, F, L>
304+
where C::Target: chain::Notify,
305+
T::Target: BroadcasterInterface,
261306
F::Target: FeeEstimator,
262307
L::Target: Logger,
263308
{
264309
/// Creates a new object which can be used to monitor several channels given the chain
265310
/// interface with which to register to receive notifications.
266-
pub fn new(broadcaster: T, logger: L, feeest: F) -> Self {
311+
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F) -> Self {
267312
Self {
268313
monitors: Mutex::new(HashMap::new()),
269-
watch_events: Mutex::new(WatchEventQueue::new()),
314+
watch_events: Mutex::new(WatchEventCache::new()),
315+
chain_source,
270316
broadcaster,
271317
logger,
272318
fee_estimator: feeest,
273319
}
274320
}
275321

276322
/// Adds or updates the monitor which monitors the channel referred to by the given outpoint.
323+
///
324+
/// Calls back to [`chain::Notify`] with the funding transaction and outputs to watch.
325+
///
326+
/// [`chain::Notify`]: ../../chain/trait.Notify.html
277327
pub fn add_monitor(&self, outpoint: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
278328
let mut watch_events = self.watch_events.lock().unwrap();
279329
let mut monitors = self.monitors.lock().unwrap();
@@ -293,6 +343,7 @@ impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSig
293343
}
294344
}
295345
entry.insert(monitor);
346+
watch_events.flush_events(&self.chain_source);
296347
Ok(())
297348
}
298349

@@ -309,8 +360,9 @@ impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSig
309360
}
310361
}
311362

312-
impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send> chain::Watch for ChainMonitor<ChanSigner, T, F, L>
313-
where T::Target: BroadcasterInterface,
363+
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>
364+
where C::Target: chain::Notify,
365+
T::Target: BroadcasterInterface,
314366
F::Target: FeeEstimator,
315367
L::Target: Logger,
316368
{
@@ -339,8 +391,9 @@ impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L:
339391
}
340392
}
341393

342-
impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<ChanSigner, T, F, L>
343-
where T::Target: BroadcasterInterface,
394+
impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<ChanSigner, C, T, F, L>
395+
where C::Target: chain::Notify,
396+
T::Target: BroadcasterInterface,
344397
F::Target: FeeEstimator,
345398
L::Target: Logger,
346399
{
@@ -353,16 +406,6 @@ impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> events::EventsProvid
353406
}
354407
}
355408

356-
impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> chain::WatchEventProvider for ChainMonitor<ChanSigner, T, F, L>
357-
where T::Target: BroadcasterInterface,
358-
F::Target: FeeEstimator,
359-
L::Target: Logger,
360-
{
361-
fn release_pending_watch_events(&self) -> Vec<chain::WatchEvent> {
362-
self.watch_events.lock().unwrap().dequeue_events()
363-
}
364-
}
365-
366409
/// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
367410
/// instead claiming it in its own individual transaction.
368411
pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;

0 commit comments

Comments
 (0)