Skip to content

Commit f715183

Browse files
chaininterface+multi: add filter_block and reentered to ChainWatchInterface
Because filter_block takes a and returns a list of s , we must add a lifetime to the ChainWatchInterface, which bubbles up in a lot of places. These places include adding a lifetime to the Node struct, which causes a lot of rearranging tests so that variables don't go out of scope before the Node that owns them does.
1 parent 969f863 commit f715183

File tree

7 files changed

+70
-38
lines changed

7 files changed

+70
-38
lines changed

lightning/fuzz/fuzz_targets/chanmon_fail_consistency.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,6 @@ pub fn do_test(data: &[u8]) {
225225
keys_manager,
226226
fee_estimator: fee_est.clone(),
227227
monitor: monitor.clone(),
228-
chain_monitor: watch,
229228
tx_broadcaster: broadcast.clone(),
230229
logger,
231230
default_config: config,
@@ -246,7 +245,6 @@ pub fn do_test(data: &[u8]) {
246245
} }
247246
}
248247

249-
250248
let mut channel_txn = Vec::new();
251249
macro_rules! make_channel {
252250
($source: expr, $dest: expr, $chan_id: expr) => { {

lightning/fuzz/fuzz_targets/full_stack_target.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,8 @@ impl<'a> Hash for Peer<'a> {
144144
}
145145
}
146146

147-
struct MoneyLossDetector<'a> {
148-
manager: Arc<ChannelManager>,
147+
struct MoneyLossDetector<'a, 'b> {
148+
manager: Arc<ChannelManager<'b>>,
149149
monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
150150
handler: PeerManager<Peer<'a>>,
151151

@@ -157,8 +157,8 @@ struct MoneyLossDetector<'a> {
157157
max_height: usize,
158158
blocks_connected: u32,
159159
}
160-
impl<'a> MoneyLossDetector<'a> {
161-
pub fn new(peers: &'a RefCell<[bool; 256]>, manager: Arc<ChannelManager>, monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>, handler: PeerManager<Peer<'a>>) -> Self {
160+
impl<'a, 'b> MoneyLossDetector<'a, 'b> {
161+
pub fn new(peers: &'a RefCell<[bool; 256]>, manager: Arc<ChannelManager<'b>>, monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>, handler: PeerManager<Peer<'a>>) -> Self {
162162
MoneyLossDetector {
163163
manager,
164164
monitor,
@@ -217,7 +217,7 @@ impl<'a> MoneyLossDetector<'a> {
217217
}
218218
}
219219

220-
impl<'a> Drop for MoneyLossDetector<'a> {
220+
impl<'a, 'b> Drop for MoneyLossDetector<'a, 'b> {
221221
fn drop(&mut self) {
222222
if !::std::thread::panicking() {
223223
// Disconnect all peers

lightning/fuzz/fuzz_targets/router_target.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ extern crate secp256k1;
55

66
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
77
use bitcoin::blockdata::script::{Script, Builder};
8+
use bitcoin::blockdata::block::Block;
9+
use bitcoin::blockdata::transaction::Transaction;
810

9-
use lightning::chain::chaininterface::{ChainError,ChainWatchInterface, ChainListener};
11+
use lightning::chain::chaininterface::{ChainError,ChainWatchInterface};
1012
use lightning::ln::channelmanager::ChannelDetails;
1113
use lightning::ln::msgs;
1214
use lightning::ln::msgs::{RoutingMessageHandler};
@@ -20,7 +22,7 @@ mod utils;
2022

2123
use utils::test_logger;
2224

23-
use std::sync::{Weak, Arc};
25+
use std::sync::Arc;
2426
use std::sync::atomic::{AtomicUsize, Ordering};
2527

2628
#[inline]
@@ -79,7 +81,10 @@ impl ChainWatchInterface for DummyChainWatcher {
7981
fn install_watch_tx(&self, _txid: &Sha256dHash, _script_pub_key: &Script) { }
8082
fn install_watch_outpoint(&self, _outpoint: (Sha256dHash, u32), _out_script: &Script) { }
8183
fn watch_all_txn(&self) { }
82-
fn register_listener(&self, _listener: Weak<ChainListener>) { }
84+
fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
85+
(Vec::new(), Vec::new())
86+
}
87+
fn reentered(&self) -> usize { 0 }
8388

8489
fn get_chain_utxo(&self, _genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
8590
match self.input.get_slice(2) {

lightning/src/chain/chaininterface.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,15 @@ pub trait ChainWatchInterface: Sync + Send {
5050
/// bytes are the block height, the next 3 the transaction index within the block, and the
5151
/// final two the output within the transaction.
5252
fn get_chain_utxo(&self, genesis_hash: Sha256dHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
53+
54+
/// Gets the list of transactions and transaction indices that the ChainWatchInterface is
55+
/// watching for.
56+
fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>);
57+
58+
/// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
59+
/// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
60+
/// determine whether they need to re-filter a given block.
61+
fn reentered(&self) -> usize;
5362
}
5463

5564
/// An interface to send a transaction to the Bitcoin network.
@@ -301,6 +310,25 @@ impl ChainWatchInterface for ChainWatchInterfaceUtil {
301310
}
302311
Err(ChainError::NotSupported)
303312
}
313+
314+
fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
315+
let mut matched = Vec::new();
316+
let mut matched_index = Vec::new();
317+
{
318+
let watched = self.watched.lock().unwrap();
319+
for (index, transaction) in block.txdata.iter().enumerate() {
320+
if self.does_match_tx_unguarded(transaction, &watched) {
321+
matched.push(transaction);
322+
matched_index.push(index as u32);
323+
}
324+
}
325+
}
326+
(matched, matched_index)
327+
}
328+
329+
fn reentered(&self) -> usize {
330+
self.reentered.load(Ordering::Relaxed)
331+
}
304332
}
305333

306334
impl ChainWatchInterfaceUtil {

lightning/src/ln/channelmanager.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -318,11 +318,11 @@ const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assum
318318
/// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
319319
/// block_connected() to step towards your best block) upon deserialization before using the
320320
/// object!
321-
pub struct ChannelManager {
321+
pub struct ChannelManager<'a> {
322322
default_configuration: UserConfig,
323323
genesis_hash: Sha256dHash,
324324
fee_estimator: Arc<FeeEstimator>,
325-
monitor: Arc<ManyChannelMonitor>,
325+
monitor: Arc<ManyChannelMonitor + 'a>,
326326
tx_broadcaster: Arc<BroadcasterInterface>,
327327

328328
#[cfg(test)]
@@ -575,7 +575,7 @@ macro_rules! maybe_break_monitor_err {
575575
}
576576
}
577577

578-
impl ChannelManager {
578+
impl<'a> ChannelManager<'a> {
579579
/// Constructs a new ChannelManager to hold several channels and route between them.
580580
///
581581
/// This is the main "logic hub" for all channel-related actions, and implements
@@ -594,7 +594,7 @@ impl ChannelManager {
594594
/// the ChannelManager as a listener to the BlockNotifier and call the BlockNotifier's
595595
/// `block_(dis)connected` methods, which will notify all registered listeners in one
596596
/// go.
597-
pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig, current_blockchain_height: usize) -> Result<Arc<ChannelManager>, secp256k1::Error> {
597+
pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor + 'a>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig, current_blockchain_height: usize) -> Result<Arc<ChannelManager<'a>>, secp256k1::Error> {
598598
let secp_ctx = Secp256k1::new();
599599

600600
let res = Arc::new(ChannelManager {
@@ -2518,7 +2518,7 @@ impl ChannelManager {
25182518
}
25192519
}
25202520

2521-
impl events::MessageSendEventsProvider for ChannelManager {
2521+
impl<'a> events::MessageSendEventsProvider for ChannelManager<'a> {
25222522
fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
25232523
// TODO: Event release to users and serialization is currently race-y: it's very easy for a
25242524
// user to serialize a ChannelManager with pending events in it and lose those events on
@@ -2543,7 +2543,7 @@ impl events::MessageSendEventsProvider for ChannelManager {
25432543
}
25442544
}
25452545

2546-
impl events::EventsProvider for ChannelManager {
2546+
impl<'a> events::EventsProvider for ChannelManager<'a> {
25472547
fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
25482548
// TODO: Event release to users and serialization is currently race-y: it's very easy for a
25492549
// user to serialize a ChannelManager with pending events in it and lose those events on
@@ -2568,7 +2568,7 @@ impl events::EventsProvider for ChannelManager {
25682568
}
25692569
}
25702570

2571-
impl ChainListener for ChannelManager {
2571+
impl<'a> ChainListener for ChannelManager<'a> {
25722572
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
25732573
let header_hash = header.bitcoin_hash();
25742574
log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
@@ -2682,7 +2682,7 @@ impl ChainListener for ChannelManager {
26822682
}
26832683
}
26842684

2685-
impl ChannelMessageHandler for ChannelManager {
2685+
impl<'a> ChannelMessageHandler for ChannelManager<'a> {
26862686
//TODO: Handle errors and close channel (or so)
26872687
fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), LightningError> {
26882688
let _ = self.total_consistency_lock.read().unwrap();
@@ -3067,7 +3067,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
30673067
}
30683068
}
30693069

3070-
impl Writeable for ChannelManager {
3070+
impl<'a> Writeable for ChannelManager<'a> {
30713071
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
30723072
let _ = self.total_consistency_lock.write().unwrap();
30733073

@@ -3130,7 +3130,7 @@ impl Writeable for ChannelManager {
31303130
/// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
31313131
/// 6) Disconnect/connect blocks on the ChannelManager.
31323132
/// 7) Register the new ChannelManager with your ChainWatchInterface.
3133-
pub struct ChannelManagerReadArgs<'a> {
3133+
pub struct ChannelManagerReadArgs<'a, 'b> {
31343134
/// The keys provider which will give us relevant keys. Some keys will be loaded during
31353135
/// deserialization.
31363136
pub keys_manager: Arc<KeysInterface>,
@@ -3144,7 +3144,7 @@ pub struct ChannelManagerReadArgs<'a> {
31443144
/// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
31453145
/// you have deserialized ChannelMonitors separately and will add them to your
31463146
/// ManyChannelMonitor after deserializing this ChannelManager.
3147-
pub monitor: Arc<ManyChannelMonitor>,
3147+
pub monitor: Arc<ManyChannelMonitor + 'b>,
31483148

31493149
/// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
31503150
/// used to broadcast the latest local commitment transactions of channels which must be
@@ -3170,8 +3170,8 @@ pub struct ChannelManagerReadArgs<'a> {
31703170
pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
31713171
}
31723172

3173-
impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3174-
fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3173+
impl<'a, 'b, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a, 'b>> for (Sha256dHash, ChannelManager<'b>) {
3174+
fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, 'b>) -> Result<Self, DecodeError> {
31753175
let _ver: u8 = Readable::read(reader)?;
31763176
let min_ver: u8 = Readable::read(reader)?;
31773177
if min_ver > SERIALIZATION_VERSION {

lightning/src/ln/channelmonitor.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@ pub struct SimpleManyChannelMonitor<Key> {
152152
fee_estimator: Arc<FeeEstimator>
153153
}
154154

155-
impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
155+
impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
156+
156157
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
157158
let block_hash = header.bitcoin_hash();
158159
let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
@@ -2143,14 +2144,14 @@ impl ChannelMonitor {
21432144
};
21442145
if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
21452146
if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2146-
let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height, fee_estimator);
2147+
let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
21472148
txn = remote_txn;
21482149
spendable_outputs.append(&mut spendable_output);
21492150
if !new_outputs.1.is_empty() {
21502151
watch_outputs.push(new_outputs);
21512152
}
21522153
if txn.is_empty() {
2153-
let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
2154+
let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
21542155
spendable_outputs.append(&mut spendable_output);
21552156
txn = local_txn;
21562157
if !new_outputs.1.is_empty() {
@@ -2159,13 +2160,13 @@ impl ChannelMonitor {
21592160
}
21602161
}
21612162
if !funding_txo.is_none() && txn.is_empty() {
2162-
if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
2163+
if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
21632164
spendable_outputs.push(spendable_output);
21642165
}
21652166
}
21662167
} else {
21672168
if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2168-
let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number, height, fee_estimator);
2169+
let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
21692170
if let Some(tx) = tx {
21702171
txn.push(tx);
21712172
}
@@ -2181,7 +2182,7 @@ impl ChannelMonitor {
21812182
// While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
21822183
// can also be resolved in a few other ways which can have more than one output. Thus,
21832184
// we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2184-
let mut updated = self.is_resolving_htlc_output(tx, height);
2185+
let mut updated = self.is_resolving_htlc_output(&tx, height);
21852186
if updated.len() > 0 {
21862187
htlc_updated.append(&mut updated);
21872188
}

lightning/src/ln/functional_test_utils.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,19 +54,19 @@ pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, depth: u32, heig
5454
header.bitcoin_hash()
5555
}
5656

57-
pub struct Node {
58-
pub block_notifier: Arc<chaininterface::BlockNotifier<'a, 'b>>,
57+
pub struct Node<'a, 'b: 'a> {
58+
pub block_notifier: Arc<chaininterface::BlockNotifier<'a>>,
5959
pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
6060
pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
6161
pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
6262
pub keys_manager: Arc<test_utils::TestKeysInterface>,
63-
pub node: Arc<ChannelManager>,
63+
pub node: Arc<ChannelManager<'b>>,
6464
pub router: Router,
6565
pub node_seed: [u8; 32],
6666
pub network_payment_count: Rc<RefCell<u8>>,
6767
pub network_chan_count: Rc<RefCell<u32>>,
6868
}
69-
impl Drop for Node {
69+
impl<'a, 'b> Drop for Node<'a, 'b> {
7070
fn drop(&mut self) {
7171
if !::std::thread::panicking() {
7272
// Check that we processed all pending events
@@ -354,7 +354,7 @@ macro_rules! check_closed_broadcast {
354354
}}
355355
}
356356

357-
pub fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
357+
pub fn close_channel<'a, 'b>(outbound_node: &Node<'a, 'b>, inbound_node: &Node<'a, 'b>, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
358358
let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
359359
let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
360360
let (tx_a, tx_b);
@@ -589,7 +589,7 @@ macro_rules! expect_payment_sent {
589589
}
590590
}
591591

592-
pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
592+
pub fn send_along_route_with_hash<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_route: &[&Node<'a, 'b>], recv_value: u64, our_payment_hash: PaymentHash) {
593593
let mut payment_event = {
594594
origin_node.node.send_payment(route, our_payment_hash).unwrap();
595595
check_added_monitors!(origin_node, 1);
@@ -631,7 +631,7 @@ pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_rou
631631
}
632632
}
633633

634-
pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
634+
pub fn send_along_route<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
635635
let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
636636
send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
637637
(our_payment_preimage, our_payment_hash)
@@ -721,7 +721,7 @@ pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_p
721721

722722
pub const TEST_FINAL_CLTV: u32 = 32;
723723

724-
pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
724+
pub fn route_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
725725
let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
726726
assert_eq!(route.hops.len(), expected_route.len());
727727
for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
@@ -747,7 +747,7 @@ pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value
747747
};
748748
}
749749

750-
pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64, expected_value: u64) {
750+
pub fn send_payment<'a, 'b>(origin: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64, expected_value: u64) {
751751
let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
752752
claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
753753
}

0 commit comments

Comments
 (0)