Randomize initial onion packet data.
[rust-lightning] / fuzz / fuzz_targets / chanmon_fail_consistency.rs
index e45857443b4df163cde0bb061ca4c007c3a81c3e..0af9083b5a96dca89c7ffbf1d12cd01cf629768f 100644 (file)
@@ -37,7 +37,7 @@ use lightning::ln::channelmonitor;
 use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, HTLCUpdate};
 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, ChannelManagerReadArgs};
 use lightning::ln::router::{Route, RouteHop};
-use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, HandleError, UpdateAddHTLC, LocalFeatures};
+use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, LightningError, UpdateAddHTLC, LocalFeatures};
 use lightning::util::events;
 use lightning::util::logger::Logger;
 use lightning::util::config::UserConfig;
@@ -52,7 +52,7 @@ use secp256k1::Secp256k1;
 
 use std::mem;
 use std::cmp::Ordering;
-use std::collections::{HashSet, HashMap};
+use std::collections::{HashSet, hash_map, HashMap};
 use std::sync::{Arc,Mutex};
 use std::sync::atomic;
 use std::io::Cursor;
@@ -80,6 +80,7 @@ impl Writer for VecWriter {
        }
 }
 
+static mut IN_RESTORE: bool = false;
 pub struct TestChannelMonitor {
        pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
        pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
@@ -89,7 +90,7 @@ pub struct TestChannelMonitor {
        pub should_update_manager: atomic::AtomicBool,
 }
 impl TestChannelMonitor {
-       pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: Arc<chaininterface::BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<chaininterface::FeeEstimator>) -> Self {
+       pub fn new(chain_monitor: Arc<dyn chaininterface::ChainWatchInterface>, broadcaster: Arc<dyn chaininterface::BroadcasterInterface>, logger: Arc<dyn Logger>, feeest: Arc<dyn chaininterface::FeeEstimator>) -> Self {
                Self {
                        simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, feeest),
                        update_ret: Mutex::new(Ok(())),
@@ -107,7 +108,18 @@ impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
                        let mut ser = VecWriter(Vec::new());
                        monitor.write_for_disk(&mut ser).unwrap();
                        self.latest_good_update.lock().unwrap().insert(funding_txo, ser.0);
-                       self.latest_update_good.lock().unwrap().insert(funding_txo, true);
+                       match self.latest_update_good.lock().unwrap().entry(funding_txo) {
+                               hash_map::Entry::Vacant(e) => { e.insert(true); },
+                               hash_map::Entry::Occupied(mut e) => {
+                                       if !e.get() && unsafe { IN_RESTORE } {
+                                               // Technically we can't consider an update to be "good" unless we're doing
+                                               // it in response to a test_restore_channel_monitor as the channel may
+                                               // still be waiting on such a call, so only set us to good if we're in the
+                                               // middle of a restore call.
+                                               e.insert(true);
+                                       }
+                               },
+                       }
                        self.should_update_manager.store(true, atomic::Ordering::Relaxed);
                } else {
                        self.latest_update_good.lock().unwrap().insert(funding_txo, false);
@@ -154,9 +166,10 @@ impl KeysInterface for KeyProvider {
                }
        }
 
-       fn get_session_key(&self) -> SecretKey {
+       fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
                let id = self.session_id.fetch_add(1, atomic::Ordering::Relaxed);
-               SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 10, self.node_id]).unwrap()
+               (SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 10, self.node_id]).unwrap(),
+               [0; 32])
        }
 
        fn get_channel_id(&self) -> [u8; 32] {
@@ -172,7 +185,7 @@ pub fn do_test(data: &[u8]) {
 
        macro_rules! make_node {
                ($node_id: expr) => { {
-                       let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
+                       let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
                        let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
                        let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
 
@@ -181,14 +194,14 @@ pub fn do_test(data: &[u8]) {
                        config.channel_options.fee_proportional_millionths = 0;
                        config.channel_options.announced_channel = true;
                        config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
-                       (ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config).unwrap(),
+                       (ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0).unwrap(),
                        monitor)
                } }
        }
 
        macro_rules! reload_node {
                ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
-                       let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
+                       let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
                        let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
                        let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
 
@@ -213,7 +226,6 @@ pub fn do_test(data: &[u8]) {
                                keys_manager,
                                fee_estimator: fee_est.clone(),
                                monitor: monitor.clone(),
-                               chain_monitor: watch,
                                tx_broadcaster: broadcast.clone(),
                                logger,
                                default_config: config,
@@ -234,7 +246,6 @@ pub fn do_test(data: &[u8]) {
                } }
        }
 
-
        let mut channel_txn = Vec::new();
        macro_rules! make_channel {
                ($source: expr, $dest: expr, $chan_id: expr) => { {
@@ -380,7 +391,7 @@ pub fn do_test(data: &[u8]) {
                ($res: expr) => {
                        match $res {
                                Ok(()) => {},
-                               Err(HandleError { action: Some(ErrorAction::IgnoreError), .. }) => { },
+                               Err(LightningError { action: ErrorAction::IgnoreError, .. }) => { },
                                _ => { $res.unwrap() },
                        }
                }
@@ -597,7 +608,7 @@ pub fn do_test(data: &[u8]) {
                                                                if $fail {
                                                                        assert!(nodes[$node].fail_htlc_backwards(&payment_hash));
                                                                } else {
-                                                                       assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0)));
+                                                                       assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), 5_000_000));
                                                                }
                                                        }
                                                },
@@ -619,9 +630,9 @@ pub fn do_test(data: &[u8]) {
                        0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
                        0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
                        0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
-                       0x06 => nodes[0].test_restore_channel_monitor(),
-                       0x07 => nodes[1].test_restore_channel_monitor(),
-                       0x08 => nodes[2].test_restore_channel_monitor(),
+                       0x06 => { unsafe { IN_RESTORE = true }; nodes[0].test_restore_channel_monitor(); unsafe { IN_RESTORE = false }; },
+                       0x07 => { unsafe { IN_RESTORE = true }; nodes[1].test_restore_channel_monitor(); unsafe { IN_RESTORE = false }; },
+                       0x08 => { unsafe { IN_RESTORE = true }; nodes[2].test_restore_channel_monitor(); unsafe { IN_RESTORE = false }; },
                        0x09 => send_payment!(nodes[0], (&nodes[1], chan_a)),
                        0x0a => send_payment!(nodes[1], (&nodes[0], chan_a)),
                        0x0b => send_payment!(nodes[1], (&nodes[2], chan_b)),