Skip to content

Commit b5c49d0

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 893844d commit b5c49d0

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
@@ -587,7 +587,7 @@ impl ChannelManager {
587587
///
588588
/// User must provide the current blockchain height from which to track onchain channel
589589
/// funding outpoints and send payments with reliable timelocks.
590-
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> {
590+
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> {
591591
let secp_ctx = Secp256k1::new();
592592

593593
let res = Arc::new(ChannelManager {
@@ -2502,7 +2502,7 @@ impl ChannelManager {
25022502
}
25032503
}
25042504

2505-
impl events::MessageSendEventsProvider for ChannelManager {
2505+
impl<'a> events::MessageSendEventsProvider for ChannelManager<'a> {
25062506
fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
25072507
// TODO: Event release to users and serialization is currently race-y: it's very easy for a
25082508
// user to serialize a ChannelManager with pending events in it and lose those events on
@@ -2527,7 +2527,7 @@ impl events::MessageSendEventsProvider for ChannelManager {
25272527
}
25282528
}
25292529

2530-
impl events::EventsProvider for ChannelManager {
2530+
impl<'a> events::EventsProvider for ChannelManager<'a> {
25312531
fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
25322532
// TODO: Event release to users and serialization is currently race-y: it's very easy for a
25332533
// user to serialize a ChannelManager with pending events in it and lose those events on
@@ -2552,7 +2552,7 @@ impl events::EventsProvider for ChannelManager {
25522552
}
25532553
}
25542554

2555-
impl ChainListener for ChannelManager {
2555+
impl<'a> ChainListener for ChannelManager<'a> {
25562556
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
25572557
let header_hash = header.bitcoin_hash();
25582558
log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
@@ -2666,7 +2666,7 @@ impl ChainListener for ChannelManager {
26662666
}
26672667
}
26682668

2669-
impl ChannelMessageHandler for ChannelManager {
2669+
impl<'a> ChannelMessageHandler for ChannelManager<'a> {
26702670
//TODO: Handle errors and close channel (or so)
26712671
fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), LightningError> {
26722672
let _ = self.total_consistency_lock.read().unwrap();
@@ -3051,7 +3051,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
30513051
}
30523052
}
30533053

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

@@ -3115,7 +3115,7 @@ impl Writeable for ChannelManager {
31153115
/// 6) Disconnect/connect blocks on the ChannelManager.
31163116
/// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
31173117
/// automatically as it does in ChannelManager::new()).
3118-
pub struct ChannelManagerReadArgs<'a> {
3118+
pub struct ChannelManagerReadArgs<'a, 'b> {
31193119
/// The keys provider which will give us relevant keys. Some keys will be loaded during
31203120
/// deserialization.
31213121
pub keys_manager: Arc<KeysInterface>,
@@ -3129,7 +3129,7 @@ pub struct ChannelManagerReadArgs<'a> {
31293129
/// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
31303130
/// you have deserialized ChannelMonitors separately and will add them to your
31313131
/// ManyChannelMonitor after deserializing this ChannelManager.
3132-
pub monitor: Arc<ManyChannelMonitor>,
3132+
pub monitor: Arc<ManyChannelMonitor + 'b>,
31333133

31343134
/// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
31353135
/// used to broadcast the latest local commitment transactions of channels which must be
@@ -3155,8 +3155,8 @@ pub struct ChannelManagerReadArgs<'a> {
31553155
pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
31563156
}
31573157

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

lightning/src/ln/channelmonitor.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,8 @@ pub struct SimpleManyChannelMonitor<Key> {
146146
fee_estimator: Arc<FeeEstimator>
147147
}
148148

149-
impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
149+
impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
150+
150151
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
151152
let block_hash = header.bitcoin_hash();
152153
let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
@@ -2137,14 +2138,14 @@ impl ChannelMonitor {
21372138
};
21382139
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) {
21392140
if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2140-
let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height, fee_estimator);
2141+
let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
21412142
txn = remote_txn;
21422143
spendable_outputs.append(&mut spendable_output);
21432144
if !new_outputs.1.is_empty() {
21442145
watch_outputs.push(new_outputs);
21452146
}
21462147
if txn.is_empty() {
2147-
let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
2148+
let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
21482149
spendable_outputs.append(&mut spendable_output);
21492150
txn = local_txn;
21502151
if !new_outputs.1.is_empty() {
@@ -2153,13 +2154,13 @@ impl ChannelMonitor {
21532154
}
21542155
}
21552156
if !funding_txo.is_none() && txn.is_empty() {
2156-
if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
2157+
if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
21572158
spendable_outputs.push(spendable_output);
21582159
}
21592160
}
21602161
} else {
21612162
if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2162-
let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number, height, fee_estimator);
2163+
let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
21632164
if let Some(tx) = tx {
21642165
txn.push(tx);
21652166
}
@@ -2175,7 +2176,7 @@ impl ChannelMonitor {
21752176
// While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
21762177
// can also be resolved in a few other ways which can have more than one output. Thus,
21772178
// we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2178-
let mut updated = self.is_resolving_htlc_output(tx, height);
2179+
let mut updated = self.is_resolving_htlc_output(&tx, height);
21792180
if updated.len() > 0 {
21802181
htlc_updated.append(&mut updated);
21812182
}

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)