From 51a5a1a50f59ecdddece6e0baeb0ac0ec48d168a Mon Sep 17 00:00:00 2001 From: Jeffrey Czyz Date: Thu, 1 Oct 2020 08:50:15 -0700 Subject: [PATCH] Move ln/channelmonitor.rs to chain/chainmonitor.rs --- fuzz/src/chanmon_consistency.rs | 16 +++++------ fuzz/src/chanmon_deser.rs | 6 ++-- fuzz/src/full_stack.rs | 12 ++++---- lightning-net-tokio/src/lib.rs | 2 +- .../chainmonitor.rs} | 28 +++++++++---------- lightning/src/chain/mod.rs | 21 +++++++------- lightning/src/ln/chan_utils.rs | 10 +++---- lightning/src/ln/chanmon_update_fail_tests.rs | 2 +- lightning/src/ln/channel.rs | 2 +- lightning/src/ln/channelmanager.rs | 6 ++-- lightning/src/ln/functional_test_utils.rs | 2 +- lightning/src/ln/functional_tests.rs | 10 +++---- lightning/src/ln/mod.rs | 1 - lightning/src/ln/onchaintx.rs | 18 ++++++------ lightning/src/ln/onion_route_tests.rs | 2 +- lightning/src/ln/reorg_tests.rs | 2 +- lightning/src/util/test_utils.rs | 24 ++++++++-------- 17 files changed, 82 insertions(+), 82 deletions(-) rename lightning/src/{ln/channelmonitor.rs => chain/chainmonitor.rs} (99%) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index b16e9fac7..86265dfe3 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -29,11 +29,11 @@ use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hash_types::{BlockHash, WPubkeyHash}; use lightning::chain; +use lightning::chain::chainmonitor; +use lightning::chain::chainmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent}; use lightning::chain::transaction::OutPoint; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys}; -use lightning::ln::channelmonitor; -use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent}; use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, ChannelManagerReadArgs}; use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, UpdateAddHTLC, Init}; @@ -83,8 +83,8 @@ impl Writer for VecWriter { struct TestChainMonitor { pub logger: Arc, - pub chain_monitor: Arc, Arc, Arc, Arc>>, - pub update_ret: Mutex>, + pub chain_monitor: Arc, Arc, Arc, Arc>>, + pub update_ret: Mutex>, // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization // logic will automatically force-close our channels for us (as we don't have an up-to-date // monitor implying we are not able to punish misbehaving counterparties). Because this test @@ -96,7 +96,7 @@ struct TestChainMonitor { impl TestChainMonitor { pub fn new(broadcaster: Arc, logger: Arc, feeest: Arc) -> Self { Self { - chain_monitor: Arc::new(channelmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest)), + chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest)), logger, update_ret: Mutex::new(Ok(())), latest_monitors: Mutex::new(HashMap::new()), @@ -107,7 +107,7 @@ impl TestChainMonitor { impl chain::Watch for TestChainMonitor { type Keys = EnforcingChannelKeys; - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn watch_channel(&self, funding_txo: OutPoint, monitor: chainmonitor::ChannelMonitor) -> Result<(), chainmonitor::ChannelMonitorUpdateErr> { let mut ser = VecWriter(Vec::new()); monitor.write_for_disk(&mut ser).unwrap(); if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) { @@ -118,13 +118,13 @@ impl chain::Watch for TestChainMonitor { self.update_ret.lock().unwrap().clone() } - fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn update_channel(&self, funding_txo: OutPoint, update: chainmonitor::ChannelMonitorUpdate) -> Result<(), chainmonitor::ChannelMonitorUpdateErr> { let mut map_lock = self.latest_monitors.lock().unwrap(); let mut map_entry = match map_lock.entry(funding_txo) { hash_map::Entry::Occupied(entry) => entry, hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"), }; - let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>:: + let mut deserialized_monitor = <(BlockHash, chainmonitor::ChannelMonitor)>:: read(&mut Cursor::new(&map_entry.get().1)).unwrap().1; deserialized_monitor.update_monitor(update.clone(), &&TestBroadcaster {}, &self.logger).unwrap(); let mut ser = VecWriter(Vec::new()); diff --git a/fuzz/src/chanmon_deser.rs b/fuzz/src/chanmon_deser.rs index 3f4ff5ad0..0f8fc9f60 100644 --- a/fuzz/src/chanmon_deser.rs +++ b/fuzz/src/chanmon_deser.rs @@ -3,8 +3,8 @@ use bitcoin::hash_types::BlockHash; +use lightning::chain::chainmonitor; use lightning::util::enforcing_trait_impls::EnforcingChannelKeys; -use lightning::ln::channelmonitor; use lightning::util::ser::{Readable, Writer}; use utils::test_logger; @@ -24,10 +24,10 @@ impl Writer for VecWriter { #[inline] pub fn do_test(data: &[u8], _out: Out) { - if let Ok((latest_block_hash, monitor)) = <(BlockHash, channelmonitor::ChannelMonitor)>::read(&mut Cursor::new(data)) { + if let Ok((latest_block_hash, monitor)) = <(BlockHash, chainmonitor::ChannelMonitor)>::read(&mut Cursor::new(data)) { let mut w = VecWriter(Vec::new()); monitor.write_for_disk(&mut w).unwrap(); - let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor)>::read(&mut Cursor::new(&w.0)).unwrap(); + let deserialized_copy = <(BlockHash, chainmonitor::ChannelMonitor)>::read(&mut Cursor::new(&w.0)).unwrap(); assert!(latest_block_hash == deserialized_copy.0); assert!(monitor == deserialized_copy.1); } diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index 6b878fa43..1ad79e2ed 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -29,7 +29,7 @@ use lightning::chain; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; use lightning::chain::transaction::OutPoint; use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysInterface}; -use lightning::ln::channelmonitor; +use lightning::chain::chainmonitor; use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor}; use lightning::routing::router::get_route; @@ -145,13 +145,13 @@ impl<'a> std::hash::Hash for Peer<'a> { type ChannelMan = ChannelManager< EnforcingChannelKeys, - Arc, Arc, Arc, Arc>>, + Arc, Arc, Arc, Arc>>, Arc, Arc, Arc, Arc>; type PeerMan<'a> = PeerManager, Arc, Arc, Arc>>, Arc>; struct MoneyLossDetector<'a> { manager: Arc, - monitor: Arc, Arc, Arc, Arc>>, + monitor: Arc, Arc, Arc, Arc>>, handler: PeerMan<'a>, peers: &'a RefCell<[bool; 256]>, @@ -165,7 +165,7 @@ struct MoneyLossDetector<'a> { impl<'a> MoneyLossDetector<'a> { pub fn new(peers: &'a RefCell<[bool; 256]>, manager: Arc, - monitor: Arc, Arc, Arc, Arc>>, + monitor: Arc, Arc, Arc, Arc>>, handler: PeerMan<'a>) -> Self { MoneyLossDetector { manager, @@ -333,7 +333,7 @@ pub fn do_test(data: &[u8], logger: &Arc) { }; let broadcast = Arc::new(TestBroadcaster{}); - let monitor = Arc::new(channelmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone())); + let monitor = Arc::new(chainmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone())); let keys_manager = Arc::new(KeyProvider { node_secret: our_network_key.clone(), counter: AtomicU64::new(0) }); let mut config = UserConfig::default(); @@ -900,6 +900,6 @@ mod tests { assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 with 1 adds, 0 fulfills, 0 fails for channel 3900000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 7 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 with 0 adds, 1 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 8 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 with 0 adds, 0 fulfills, 1 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&2)); // 9 - assert_eq!(log_entries.get(&("lightning::ln::channelmonitor".to_string(), "Input spending counterparty commitment tx (00000000000000000000000000000000000000000000000000000000000000a1:0) in 0000000000000000000000000000000000000000000000000000000000000018 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); // 10 + assert_eq!(log_entries.get(&("lightning::chain::chainmonitor".to_string(), "Input spending counterparty commitment tx (00000000000000000000000000000000000000000000000000000000000000a1:0) in 0000000000000000000000000000000000000000000000000000000000000018 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); // 10 } } diff --git a/lightning-net-tokio/src/lib.rs b/lightning-net-tokio/src/lib.rs index beaafcac0..e84ee7622 100644 --- a/lightning-net-tokio/src/lib.rs +++ b/lightning-net-tokio/src/lib.rs @@ -36,7 +36,7 @@ //! type Logger = dyn lightning::util::logger::Logger; //! type ChainAccess = dyn lightning::chain::Access; //! type ChainFilter = dyn lightning::chain::Filter; -//! type ChainMonitor = lightning::ln::channelmonitor::ChainMonitor, Arc, Arc, Arc>; +//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor, Arc, Arc, Arc>; //! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager; //! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager; //! diff --git a/lightning/src/ln/channelmonitor.rs b/lightning/src/chain/chainmonitor.rs similarity index 99% rename from lightning/src/ln/channelmonitor.rs rename to lightning/src/chain/chainmonitor.rs index 166c7fcfd..8578b9f1c 100644 --- a/lightning/src/ln/channelmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -64,7 +64,7 @@ use std::io::Error; #[derive(Clone)] #[must_use] pub struct ChannelMonitorUpdate { - pub(super) updates: Vec, + pub(crate) updates: Vec, /// The sequence number of this update. Updates *must* be replayed in-order according to this /// sequence number (and updates may panic if they are not). The update_id values are strictly /// increasing and increase by one for each new update. @@ -183,9 +183,9 @@ pub enum MonitorEvent { /// [`chain::Watch`]: ../../chain/trait.Watch.html #[derive(Clone, PartialEq)] pub struct HTLCUpdate { - pub(super) payment_hash: PaymentHash, - pub(super) payment_preimage: Option, - pub(super) source: HTLCSource + pub(crate) payment_hash: PaymentHash, + pub(crate) payment_preimage: Option, + pub(crate) source: HTLCSource } impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source }); @@ -654,7 +654,7 @@ const MIN_SERIALIZATION_VERSION: u8 = 1; #[cfg_attr(test, derive(PartialEq))] #[derive(Clone)] -pub(super) enum ChannelMonitorUpdateStep { +pub(crate) enum ChannelMonitorUpdateStep { LatestHolderCommitmentTXInfo { commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, @@ -1117,7 +1117,7 @@ impl ChannelMonitor { } impl ChannelMonitor { - pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey, + pub(crate) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey, on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script), counterparty_htlc_base_key: &PublicKey, counterparty_delayed_payment_base_key: &PublicKey, on_holder_tx_csv: u16, funding_redeemscript: Script, channel_value_satoshis: u64, @@ -1254,7 +1254,7 @@ impl ChannelMonitor { /// The monitor watches for it to be broadcasted and then uses the HTLC information (and /// possibly future revocation/preimage information) to claim outputs where possible. /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers. - pub(super) fn provide_latest_counterparty_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger { + pub(crate) fn provide_latest_counterparty_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger { // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction // so that a remote monitor doesn't learn anything unless there is a malicious close. // (only maybe, sadly we cant do the same for local info, as we need to be aware of @@ -1329,11 +1329,11 @@ impl ChannelMonitor { /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all /// commitment_tx_infos which contain the payment hash have been revoked. - pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) { + pub(crate) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) { self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone()); } - pub(super) fn broadcast_latest_holder_commitment_txn(&mut self, broadcaster: &B, logger: &L) + pub(crate) fn broadcast_latest_holder_commitment_txn(&mut self, broadcaster: &B, logger: &L) where B::Target: BroadcasterInterface, L::Target: Logger, { @@ -1438,19 +1438,19 @@ impl ChannelMonitor { } /// Can only fail if idx is < get_min_seen_secret - pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> { + pub(crate) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> { self.commitment_secrets.get_secret(idx) } - pub(super) fn get_min_seen_secret(&self) -> u64 { + pub(crate) fn get_min_seen_secret(&self) -> u64 { self.commitment_secrets.get_min_seen_secret() } - pub(super) fn get_cur_counterparty_commitment_number(&self) -> u64 { + pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 { self.current_counterparty_commitment_number } - pub(super) fn get_cur_holder_commitment_number(&self) -> u64 { + pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 { self.current_holder_commitment_number } @@ -2595,9 +2595,9 @@ mod tests { use bitcoin::hashes::hex::FromHex; use bitcoin::hash_types::Txid; use hex; + use chain::chainmonitor::ChannelMonitor; use chain::transaction::OutPoint; use ln::channelmanager::{PaymentPreimage, PaymentHash}; - use ln::channelmonitor::ChannelMonitor; use ln::onchaintx::{OnchainTxHandler, InputDescriptors}; use ln::chan_utils; use ln::chan_utils::{HTLCOutputInCommitment, HolderCommitmentTransaction}; diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index 9333c4ef7..b95863074 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -15,9 +15,10 @@ use bitcoin::hash_types::{BlockHash, Txid}; use chain::keysinterface::ChannelKeys; use chain::transaction::OutPoint; -use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent}; +use chain::chainmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent}; pub mod chaininterface; +pub mod chainmonitor; pub mod transaction; pub mod keysinterface; @@ -62,9 +63,9 @@ pub enum AccessError { /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle /// multiple instances. /// -/// [`ChannelMonitor`]: ../ln/channelmonitor/struct.ChannelMonitor.html -/// [`ChannelMonitorUpdateErr`]: ../ln/channelmonitor/enum.ChannelMonitorUpdateErr.html -/// [`PermanentFailure`]: ../ln/channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure +/// [`ChannelMonitor`]: chainmonitor/struct.ChannelMonitor.html +/// [`ChannelMonitorUpdateErr`]: chainmonitor/enum.ChannelMonitorUpdateErr.html +/// [`PermanentFailure`]: chainmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure pub trait Watch: Send + Sync { /// Keys needed by monitors for creating and signing transactions. type Keys: ChannelKeys; @@ -75,9 +76,9 @@ pub trait Watch: Send + Sync { /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means /// calling [`block_connected`] and [`block_disconnected`] on the monitor. /// - /// [`get_outputs_to_watch`]: ../ln/channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch - /// [`block_connected`]: ../ln/channelmonitor/struct.ChannelMonitor.html#method.block_connected - /// [`block_disconnected`]: ../ln/channelmonitor/struct.ChannelMonitor.html#method.block_disconnected + /// [`get_outputs_to_watch`]: chainmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch + /// [`block_connected`]: chainmonitor/struct.ChannelMonitor.html#method.block_connected + /// [`block_disconnected`]: chainmonitor/struct.ChannelMonitor.html#method.block_disconnected fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; /// Updates a channel identified by `funding_txo` by applying `update` to its monitor. @@ -85,8 +86,8 @@ pub trait Watch: Send + Sync { /// Implementations must call [`update_monitor`] with the given update. See /// [`ChannelMonitorUpdateErr`] for invariants around returning an error. /// - /// [`update_monitor`]: ../ln/channelmonitor/struct.ChannelMonitor.html#method.update_monitor - /// [`ChannelMonitorUpdateErr`]: ../ln/channelmonitor/enum.ChannelMonitorUpdateErr.html + /// [`update_monitor`]: chainmonitor/struct.ChannelMonitor.html#method.update_monitor + /// [`ChannelMonitorUpdateErr`]: chainmonitor/enum.ChannelMonitorUpdateErr.html fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>; /// Returns any monitor events since the last call. Subsequent calls must only return new @@ -112,7 +113,7 @@ pub trait Watch: Send + Sync { /// invocation that has called the `Filter` must return [`TemporaryFailure`]. /// /// [`Watch`]: trait.Watch.html -/// [`TemporaryFailure`]: ../ln/channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.TemporaryFailure +/// [`TemporaryFailure`]: chainmonitor/enum.ChannelMonitorUpdateErr.html#variant.TemporaryFailure /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki pub trait Filter: Send + Sync { diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 8133c1a59..a9be581b8 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -81,7 +81,7 @@ pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes /// or so. #[derive(Clone)] -pub(super) struct CounterpartyCommitmentSecrets { +pub(crate) struct CounterpartyCommitmentSecrets { old_secrets: [([u8; 32], u64); 49], } @@ -97,7 +97,7 @@ impl PartialEq for CounterpartyCommitmentSecrets { } impl CounterpartyCommitmentSecrets { - pub(super) fn new() -> Self { + pub(crate) fn new() -> Self { Self { old_secrets: [([0; 32], 1 << 48); 49], } } @@ -111,7 +111,7 @@ impl CounterpartyCommitmentSecrets { 48 } - pub(super) fn get_min_seen_secret(&self) -> u64 { + pub(crate) fn get_min_seen_secret(&self) -> u64 { //TODO This can be optimized? let mut min = 1 << 48; for &(_, idx) in self.old_secrets.iter() { @@ -135,7 +135,7 @@ impl CounterpartyCommitmentSecrets { res } - pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> { + pub(crate) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> { let pos = Self::place_secret(idx); for i in 0..pos { let (old_secret, old_idx) = self.old_secrets[i as usize]; @@ -151,7 +151,7 @@ impl CounterpartyCommitmentSecrets { } /// Can only fail if idx is < get_min_seen_secret - pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> { + pub(crate) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> { for i in 0..self.old_secrets.len() { if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 { return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx)) diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index e99dca78b..0b9bdf536 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -12,9 +12,9 @@ //! There are a bunch of these as their handling is relatively error-prone so they are split out //! here. See also the chanmon_fail_consistency fuzz test. +use chain::chainmonitor::ChannelMonitorUpdateErr; use chain::transaction::OutPoint; use ln::channelmanager::{RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure}; -use ln::channelmonitor::ChannelMonitorUpdateErr; use ln::features::InitFeatures; use ln::msgs; use ln::msgs::{ChannelMessageHandler, ErrorAction, RoutingMessageHandler}; diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index ac331f31e..1c75ae3a4 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -25,11 +25,11 @@ use bitcoin::secp256k1; use ln::features::{ChannelFeatures, InitFeatures}; use ln::msgs; use ln::msgs::{DecodeError, OptionalField, DataLossProtect}; -use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER}; use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT}; use ln::chan_utils::{CounterpartyCommitmentSecrets, HolderCommitmentTransaction, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, PreCalculatedTxCreationKeys}; use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; +use chain::chainmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER}; use chain::transaction::{OutPoint, TransactionData}; use chain::keysinterface::{ChannelKeys, KeysInterface}; use util::transaction_utils; diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 488dc75fa..14e9d1f31 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -36,9 +36,9 @@ use bitcoin::secp256k1; use chain; use chain::Watch; use chain::chaininterface::{BroadcasterInterface, FeeEstimator}; +use chain::chainmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent}; use chain::transaction::{OutPoint, TransactionData}; use ln::channel::{Channel, ChannelError}; -use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent}; use ln::features::{InitFeatures, NodeFeatures}; use routing::router::{Route, RouteHop}; use ln::msgs; @@ -129,7 +129,7 @@ pub(super) enum HTLCForwardInfo { /// Tracks the inbound corresponding to an outbound HTLC #[derive(Clone, PartialEq)] -pub(super) struct HTLCPreviousHopData { +pub(crate) struct HTLCPreviousHopData { short_channel_id: u64, htlc_id: u64, incoming_packet_shared_secret: [u8; 32], @@ -148,7 +148,7 @@ struct ClaimableHTLC { /// Tracks the inbound corresponding to an outbound HTLC #[derive(Clone, PartialEq)] -pub(super) enum HTLCSource { +pub(crate) enum HTLCSource { PreviousHopData(HTLCPreviousHopData), OutboundRoute { path: Vec, diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index aad56ff3c..7f8094331 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -11,9 +11,9 @@ //! nodes for functional tests. use chain::Watch; +use chain::chainmonitor::ChannelMonitor; use chain::transaction::OutPoint; use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure}; -use ln::channelmonitor::ChannelMonitor; use routing::router::{Route, get_route}; use routing::network_graph::{NetGraphMsgHandler, NetworkGraph}; use ln::features::InitFeatures; diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index 93a09b079..2174851d2 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -12,12 +12,12 @@ //! claim outputs on-chain. use chain::Watch; +use chain::chainmonitor; +use chain::chainmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY}; use chain::transaction::OutPoint; use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor}; use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC}; use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT}; -use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY}; -use ln::channelmonitor; use ln::channel::{Channel, ChannelError}; use ln::{chan_utils, onion_utils}; use routing::router::{Route, RouteHop, get_route}; @@ -8360,7 +8360,7 @@ fn test_update_err_monitor_lockdown() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write_for_disk(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, chainmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0)).unwrap().1; assert!(new_monitor == *monitor); let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator); @@ -8418,7 +8418,7 @@ fn test_concurrent_monitor_claim() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write_for_disk(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, chainmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0)).unwrap().1; assert!(new_monitor == *monitor); let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator); @@ -8443,7 +8443,7 @@ fn test_concurrent_monitor_claim() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write_for_disk(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, chainmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0)).unwrap().1; assert!(new_monitor == *monitor); let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator); diff --git a/lightning/src/ln/mod.rs b/lightning/src/ln/mod.rs index 9bb8438f2..cd959a74d 100644 --- a/lightning/src/ln/mod.rs +++ b/lightning/src/ln/mod.rs @@ -19,7 +19,6 @@ //! call into your NetGraphMsgHandler. pub mod channelmanager; -pub mod channelmonitor; pub mod msgs; pub mod peer_handler; pub mod chan_utils; diff --git a/lightning/src/ln/onchaintx.rs b/lightning/src/ln/onchaintx.rs index dbe86c869..8b04434b3 100644 --- a/lightning/src/ln/onchaintx.rs +++ b/lightning/src/ln/onchaintx.rs @@ -22,11 +22,11 @@ use bitcoin::secp256k1::{Secp256k1, Signature}; use bitcoin::secp256k1; use ln::msgs::DecodeError; -use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest}; use ln::channelmanager::PaymentPreimage; use ln::chan_utils; use ln::chan_utils::{TxCreationKeys, HolderCommitmentTransaction}; use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT}; +use chain::chainmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest}; use chain::keysinterface::ChannelKeys; use util::logger::Logger; use util::ser::{Readable, Writer, Writeable}; @@ -405,7 +405,7 @@ impl Readable for OnchainTxHandler OnchainTxHandler { - pub(super) fn new(destination_script: Script, keys: ChanSigner, on_holder_tx_csv: u16) -> Self { + pub(crate) fn new(destination_script: Script, keys: ChanSigner, on_holder_tx_csv: u16) -> Self { let key_storage = keys; @@ -425,7 +425,7 @@ impl OnchainTxHandler { } } - pub(super) fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize { + pub(crate) fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize { let mut tx_weight = 2; // count segwit flags for inp in inputs { // We use expected weight (and not actual) as signatures and time lock delays may vary @@ -829,7 +829,7 @@ impl OnchainTxHandler { } } - pub(super) fn block_disconnected(&mut self, height: u32, broadcaster: B, fee_estimator: F, logger: L) + pub(crate) fn block_disconnected(&mut self, height: u32, broadcaster: B, fee_estimator: F, logger: L) where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, @@ -877,7 +877,7 @@ impl OnchainTxHandler { } } - pub(super) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) { + pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) { self.prev_holder_commitment = self.holder_commitment.take(); self.holder_commitment = Some(tx); } @@ -919,7 +919,7 @@ impl OnchainTxHandler { // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created, // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing // to monitor before. - pub(super) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Option { + pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Option { if let Some(ref mut holder_commitment) = self.holder_commitment { match self.key_storage.sign_holder_commitment(holder_commitment, &self.secp_ctx) { Ok(sig) => Some(holder_commitment.add_holder_sig(funding_redeemscript, sig)), @@ -931,7 +931,7 @@ impl OnchainTxHandler { } #[cfg(any(test, feature="unsafe_revoked_tx_signing"))] - pub(super) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Option { + pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Option { if let Some(ref mut holder_commitment) = self.holder_commitment { let holder_commitment = holder_commitment.clone(); match self.key_storage.sign_holder_commitment(&holder_commitment, &self.secp_ctx) { @@ -943,7 +943,7 @@ impl OnchainTxHandler { } } - pub(super) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option) -> Option { + pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option) -> Option { let mut htlc_tx = None; if self.holder_commitment.is_some() { let commitment_txid = self.holder_commitment.as_ref().unwrap().txid(); @@ -971,7 +971,7 @@ impl OnchainTxHandler { } #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))] - pub(super) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option) -> Option { + pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option) -> Option { let latest_had_sigs = self.holder_htlc_sigs.is_some(); let prev_had_sigs = self.prev_holder_htlc_sigs.is_some(); let ret = self.get_fully_signed_htlc_tx(outp, preimage); diff --git a/lightning/src/ln/onion_route_tests.rs b/lightning/src/ln/onion_route_tests.rs index f4ad80903..e579cc1fb 100644 --- a/lightning/src/ln/onion_route_tests.rs +++ b/lightning/src/ln/onion_route_tests.rs @@ -11,8 +11,8 @@ //! These tests work by standing up full nodes and route payments across the network, checking the //! returned errors decode to the correct thing. +use chain::chainmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS}; use ln::channelmanager::{HTLCForwardInfo, PaymentPreimage, PaymentHash}; -use ln::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS}; use ln::onion_utils; use routing::router::{Route, get_route}; use ln::features::InitFeatures; diff --git a/lightning/src/ln/reorg_tests.rs b/lightning/src/ln/reorg_tests.rs index 4c51e9ff7..f907ab1ed 100644 --- a/lightning/src/ln/reorg_tests.rs +++ b/lightning/src/ln/reorg_tests.rs @@ -9,7 +9,7 @@ //! Further functional tests which test blockchain reorganizations. -use ln::channelmonitor::ANTI_REORG_DELAY; +use chain::chainmonitor::ANTI_REORG_DELAY; use ln::features::InitFeatures; use ln::msgs::{ChannelMessageHandler, ErrorAction, HTLCFailChannelUpdate}; use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider}; diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 210d62485..eb637e3c9 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -10,13 +10,13 @@ use chain; use chain::chaininterface; use chain::chaininterface::ConfirmationTarget; +use chain::chainmonitor; +use chain::chainmonitor::MonitorEvent; use chain::transaction::OutPoint; use chain::keysinterface; -use ln::channelmonitor; use ln::features::{ChannelFeatures, InitFeatures}; use ln::msgs; use ln::msgs::OptionalField; -use ln::channelmonitor::MonitorEvent; use util::enforcing_trait_impls::EnforcingChannelKeys; use util::events; use util::logger::{Logger, Level, Record}; @@ -60,20 +60,20 @@ impl chaininterface::FeeEstimator for TestFeeEstimator { } pub struct TestChainMonitor<'a> { - pub added_monitors: Mutex)>>, + pub added_monitors: Mutex)>>, pub latest_monitor_update_id: Mutex>, - pub chain_monitor: channelmonitor::ChainMonitor, - pub update_ret: Mutex>, + pub chain_monitor: chainmonitor::ChainMonitor, + pub update_ret: Mutex>, // If this is set to Some(), after the next return, we'll always return this until update_ret // is changed: - pub next_update_ret: Mutex>>, + pub next_update_ret: Mutex>>, } impl<'a> TestChainMonitor<'a> { pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator) -> Self { Self { added_monitors: Mutex::new(Vec::new()), latest_monitor_update_id: Mutex::new(HashMap::new()), - chain_monitor: channelmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator), + chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator), update_ret: Mutex::new(Ok(())), next_update_ret: Mutex::new(None), } @@ -82,12 +82,12 @@ impl<'a> TestChainMonitor<'a> { impl<'a> chain::Watch for TestChainMonitor<'a> { type Keys = EnforcingChannelKeys; - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn watch_channel(&self, funding_txo: OutPoint, monitor: chainmonitor::ChannelMonitor) -> Result<(), chainmonitor::ChannelMonitorUpdateErr> { // At every point where we get a monitor update, we should be able to send a useful monitor // to a watchtower and disk... let mut w = TestVecWriter(Vec::new()); monitor.write_for_disk(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, chainmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0)).unwrap().1; assert!(new_monitor == monitor); self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id())); @@ -101,11 +101,11 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { ret } - fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn update_channel(&self, funding_txo: OutPoint, update: chainmonitor::ChannelMonitorUpdate) -> Result<(), chainmonitor::ChannelMonitorUpdateErr> { // Every monitor update should survive roundtrip let mut w = TestVecWriter(Vec::new()); update.write(&mut w).unwrap(); - assert!(channelmonitor::ChannelMonitorUpdate::read( + assert!(chainmonitor::ChannelMonitorUpdate::read( &mut ::std::io::Cursor::new(&w.0)).unwrap() == update); self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id)); @@ -116,7 +116,7 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { let monitor = monitors.get(&funding_txo).unwrap(); w.0.clear(); monitor.write_for_disk(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, chainmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0)).unwrap().1; assert!(new_monitor == *monitor); self.added_monitors.lock().unwrap().push((funding_txo, new_monitor)); -- 2.39.5