Skip to content

Commit 06cbb0b

Browse files
Update BlockNotifier to accept Derefs as registered listeners.
1 parent 117a3ae commit 06cbb0b

File tree

3 files changed

+21
-31
lines changed

3 files changed

+21
-31
lines changed

lightning/src/chain/chaininterface.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@ use bitcoin::network::constants::Network;
1414

1515
use util::logger::Logger;
1616

17-
use std::sync::{Mutex,Weak,MutexGuard,Arc};
17+
use std::sync::{Mutex, MutexGuard, Arc};
1818
use std::sync::atomic::{AtomicUsize, Ordering};
1919
use std::collections::HashSet;
20+
use std::ops::Deref;
21+
use std::marker::Sized;
2022

2123
/// Used to give chain error details upstream
2224
pub enum ChainError {
@@ -207,24 +209,23 @@ impl ChainWatchedUtil {
207209

208210
/// Utility for notifying listeners about new blocks, and handling block rescans if new watch
209211
/// data is registered.
210-
pub struct BlockNotifier {
211-
listeners: Mutex<Vec<Weak<ChainListener>>>, //TODO(vmw): try removing Weak
212+
pub struct BlockNotifier<CL: Deref<Target = ChainListener> + Sized + Clone> {
213+
listeners: Mutex<Vec<CL>>,
212214
chain_monitor: Arc<ChainWatchInterface>,
213215
}
214216

215-
impl BlockNotifier {
217+
impl<CL: Deref<Target = ChainListener> + Sized + Clone> BlockNotifier<CL> {
216218
/// Constructs a new BlockNotifier without any listeners.
217-
pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> BlockNotifier {
219+
pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> BlockNotifier<CL> {
218220
BlockNotifier {
219221
listeners: Mutex::new(Vec::new()),
220222
chain_monitor,
221223
}
222224
}
223225

224-
/// Register the given listener to receive events. Only a weak pointer is provided and
225-
/// the registration should be freed once that pointer expires.
226+
/// Register the given listener to receive events.
226227
// TODO: unregister
227-
pub fn register_listener(&self, listener: Weak<ChainListener>) {
228+
pub fn register_listener(&self, listener: CL) {
228229
let mut vec = self.listeners.lock().unwrap();
229230
vec.push(listener);
230231
}
@@ -252,10 +253,7 @@ impl BlockNotifier {
252253

253254
let listeners = self.listeners.lock().unwrap().clone();
254255
for listener in listeners.iter() {
255-
match listener.upgrade() {
256-
Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
257-
None => ()
258-
}
256+
listener.block_connected(header, height, txn_matched, indexes_of_txn_matched)
259257
}
260258
return last_seen != self.chain_monitor.reentered();
261259
}
@@ -265,10 +263,7 @@ impl BlockNotifier {
265263
pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
266264
let listeners = self.listeners.lock().unwrap().clone();
267265
for listener in listeners.iter() {
268-
match listener.upgrade() {
269-
Some(arc) => arc.block_disconnected(&header, disconnected_height),
270-
None => ()
271-
}
266+
listener.block_disconnected(&header, disconnected_height);
272267
}
273268
}
274269

lightning/src/ln/functional_test_utils.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@ use std::rc::Rc;
3535
use std::sync::{Arc, Mutex};
3636
use std::mem;
3737
use std::ops::Deref;
38-
use std::marker::Sized;
3938

4039
pub const CHAN_CONFIRM_DEPTH: u32 = 100;
41-
pub fn confirm_transaction(notifier: &chaininterface::BlockNotifier, chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
40+
pub fn confirm_transaction<CL: Deref<Target = chaininterface::ChainListener> + Clone>(notifier: &chaininterface::BlockNotifier<CL>, chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
4241
assert!(chain.does_match_tx(tx));
4342
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4443
notifier.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
@@ -48,7 +47,7 @@ pub fn confirm_transaction(notifier: &chaininterface::BlockNotifier, chain: &cha
4847
}
4948
}
5049

51-
pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
50+
pub fn connect_blocks<CL: Deref<Target = chaininterface::ChainListener> + Clone>(notifier: &chaininterface::BlockNotifier<CL>, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
5251
let mut header = BlockHeader { version: 0x2000000, prev_blockhash: if parent { prev_blockhash } else { Default::default() }, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5352
notifier.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
5453
for i in 2..depth + 1 {
@@ -59,7 +58,7 @@ pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, depth: u32, heig
5958
}
6059

6160
pub struct Node {
62-
pub block_notifier: Arc<chaininterface::BlockNotifier>,
61+
pub block_notifier: Arc<chaininterface::BlockNotifier<Arc<chaininterface::ChainListener>>>,
6362
pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
6463
pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
6564
pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
@@ -858,14 +857,12 @@ pub fn create_network(node_count: usize, node_config: &[Option<UserConfig>]) ->
858857
rng.fill_bytes(&mut seed);
859858
let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
860859
let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
861-
let weak_res = Arc::downgrade(&chan_monitor.simple_monitor);
862-
block_notifier.register_listener(weak_res);
860+
block_notifier.register_listener(chan_monitor.simple_monitor.clone() as Arc<chaininterface::ChainListener>);
863861
let mut default_config = UserConfig::default();
864862
default_config.channel_options.announced_channel = true;
865863
default_config.peer_channel_config_limits.force_announced_channel_preference = false;
866864
let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone() as Arc<ManyChannelMonitor>, tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0).unwrap();
867-
let weak_res = Arc::downgrade(&node);
868-
block_notifier.register_listener(weak_res);
865+
block_notifier.register_listener(node.clone());
869866
let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
870867
nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
871868
network_payment_count: payment_count.clone(),

lightning/src/ln/functional_tests.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! claim outputs on-chain.
44
55
use chain::transaction::OutPoint;
6-
use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil};
6+
use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
77
use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
88
use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
99
use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
@@ -44,7 +44,6 @@ use std::default::Default;
4444
use std::sync::{Arc, Mutex};
4545
use std::sync::atomic::Ordering;
4646
use std::mem;
47-
use std::ops::Deref;
4847

4948
use rand::{thread_rng, Rng};
5049

@@ -3447,7 +3446,7 @@ fn test_no_txn_manager_serialize_deserialize() {
34473446
assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
34483447
nodes[0].node = Arc::new(nodes_0_deserialized);
34493448
let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3450-
nodes[0].block_notifier.register_listener(Arc::downgrade(&nodes_0_as_listener));
3449+
nodes[0].block_notifier.register_listener(nodes_0_as_listener);
34513450
assert_eq!(nodes[0].node.list_channels().len(), 1);
34523451
check_added_monitors!(nodes[0], 1);
34533452

@@ -6147,11 +6146,10 @@ fn test_data_loss_protect() {
61476146
assert!(monitor.add_update_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor.clone()).is_ok());
61486147
nodes[0].chan_monitor = monitor;
61496148
nodes[0].chain_monitor = chain_monitor;
6149+
nodes[0].block_notifier = Arc::new(BlockNotifier::new(nodes[0].chain_monitor.clone()));
61506150

6151-
let weak_res = Arc::downgrade(&nodes[0].chan_monitor.simple_monitor);
6152-
nodes[0].block_notifier.register_listener(weak_res);
6153-
let weak_res = Arc::downgrade(&nodes[0].node);
6154-
nodes[0].block_notifier.register_listener(weak_res);
6151+
nodes[0].block_notifier.register_listener(nodes[0].chan_monitor.simple_monitor.clone());
6152+
nodes[0].block_notifier.register_listener(nodes[0].node.clone());
61556153

61566154
check_added_monitors!(nodes[0], 1);
61576155

0 commit comments

Comments
 (0)