From: Matt Corallo Date: Tue, 16 Feb 2021 21:30:08 +0000 (-0500) Subject: Rename ChannelKeys -> Sign and generic it consistently X-Git-Tag: v0.0.13~23^2~6 X-Git-Url: http://git.bitcoin.ninja/?a=commitdiff_plain;h=ff00f6f8861419b73269e6c51d75ac9de75f1d1f;p=rust-lightning Rename ChannelKeys -> Sign and generic it consistently The `ChannelKeys` object really isn't about keys at all anymore, its all about signing. At the same time, we rename the type aliases used in traits from both `ChanKeySigner` and `Keys` to just `Signer` (or, in contexts where Channel isnt clear, `ChanSigner`). --- diff --git a/background-processor/src/lib.rs b/background-processor/src/lib.rs index 63b9ef311..06a2c00e2 100644 --- a/background-processor/src/lib.rs +++ b/background-processor/src/lib.rs @@ -2,10 +2,9 @@ use lightning::chain; use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; -use lightning::chain::keysinterface::{ChannelKeys, KeysInterface}; +use lightning::chain::keysinterface::{Sign, KeysInterface}; use lightning::ln::channelmanager::ChannelManager; use lightning::util::logger::Logger; -use lightning::util::ser::Writeable; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; @@ -53,14 +52,14 @@ impl BackgroundProcessor { /// [`thread_handle`]: struct.BackgroundProcessor.html#structfield.thread_handle /// [`ChannelManager::write`]: ../lightning/ln/channelmanager/struct.ChannelManager.html#method.write /// [`FilesystemPersister::persist_manager`]: ../lightning_persister/struct.FilesystemPersister.html#impl - pub fn start(persist_manager: PM, manager: Arc, Arc, Arc, Arc, Arc>>, logger: Arc) -> Self - where ChanSigner: 'static + ChannelKeys + Writeable, - M: 'static + chain::Watch, + pub fn start(persist_manager: PM, manager: Arc, Arc, Arc, Arc, Arc>>, logger: Arc) -> Self + where Signer: 'static + Sign, + M: 'static + chain::Watch, T: 'static + BroadcasterInterface, - K: 'static + KeysInterface, + K: 'static + KeysInterface, F: 'static + FeeEstimator, L: 'static + Logger, - PM: 'static + Send + Fn(&ChannelManager, Arc, Arc, Arc, Arc>) -> Result<(), std::io::Error>, + PM: 'static + Send + Fn(&ChannelManager, Arc, Arc, Arc, Arc>) -> Result<(), std::io::Error>, { let stop_thread = Arc::new(AtomicBool::new(false)); let stop_thread_clone = stop_thread.clone(); @@ -104,7 +103,7 @@ mod tests { use lightning::chain; use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use lightning::chain::chainmonitor; - use lightning::chain::keysinterface::{ChannelKeys, InMemoryChannelKeys, KeysInterface, KeysManager}; + use lightning::chain::keysinterface::{Sign, InMemorySigner, KeysInterface, KeysManager}; use lightning::chain::transaction::OutPoint; use lightning::get_event_msg; use lightning::ln::channelmanager::{ChannelManager, SimpleArcChannelManager}; @@ -122,7 +121,7 @@ mod tests { use std::time::Duration; use super::BackgroundProcessor; - type ChainMonitor = chainmonitor::ChainMonitor, Arc, Arc, Arc, Arc>; + type ChainMonitor = chainmonitor::ChainMonitor, Arc, Arc, Arc, Arc>; struct Node { node: SimpleArcChannelManager, @@ -203,7 +202,7 @@ mod tests { // Initiate the background processors to watch each node. let data_dir = nodes[0].persister.get_data_dir(); - let callback = move |node: &ChannelManager, Arc, Arc, Arc, Arc>| FilesystemPersister::persist_manager(data_dir.clone(), node); + let callback = move |node: &ChannelManager, Arc, Arc, Arc, Arc>| FilesystemPersister::persist_manager(data_dir.clone(), node); let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone()); // Go through the channel creation process until each node should have something persisted. @@ -258,7 +257,7 @@ mod tests { // `CHAN_FRESHNESS_TIMER`. let nodes = create_nodes(1, "test_chan_freshness_called".to_string()); let data_dir = nodes[0].persister.get_data_dir(); - let callback = move |node: &ChannelManager, Arc, Arc, Arc, Arc>| FilesystemPersister::persist_manager(data_dir.clone(), node); + let callback = move |node: &ChannelManager, Arc, Arc, Arc, Arc>| FilesystemPersister::persist_manager(data_dir.clone(), node); let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone()); loop { let log_entries = nodes[0].logger.lines.lock().unwrap(); @@ -274,11 +273,11 @@ mod tests { #[test] fn test_persist_error() { // Test that if we encounter an error during manager persistence, the thread panics. - fn persist_manager(_data: &ChannelManager, Arc, Arc, Arc, Arc>) -> Result<(), std::io::Error> - where ChanSigner: 'static + ChannelKeys + Writeable, - M: 'static + chain::Watch, + fn persist_manager(_data: &ChannelManager, Arc, Arc, Arc, Arc>) -> Result<(), std::io::Error> + where Signer: 'static + Sign, + M: 'static + chain::Watch, T: 'static + BroadcasterInterface, - K: 'static + KeysInterface, + K: 'static + KeysInterface, F: 'static + FeeEstimator, L: 'static + Logger, { diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index 4cf90b1dc..24b7bf90c 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -34,11 +34,11 @@ use lightning::chain::channelmonitor; use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent}; use lightning::chain::transaction::OutPoint; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; -use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys}; +use lightning::chain::keysinterface::{KeysInterface, InMemorySigner}; use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, PaymentSendFailure, ChannelManagerReadArgs}; use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, DecodeError, ErrorAction, UpdateAddHTLC, Init}; -use lightning::util::enforcing_trait_impls::{EnforcingChannelKeys, INITIAL_REVOKED_COMMITMENT_NUMBER}; +use lightning::util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER}; use lightning::util::errors::APIError; use lightning::util::events; use lightning::util::logger::Logger; @@ -87,7 +87,7 @@ impl Writer for VecWriter { struct TestChainMonitor { pub logger: Arc, - pub chain_monitor: Arc, Arc, Arc, Arc, Arc>>, + pub chain_monitor: Arc, 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 @@ -109,9 +109,9 @@ impl TestChainMonitor { } } impl chain::Watch for TestChainMonitor { - type Keys = EnforcingChannelKeys; + type ChanSigner = EnforcingSigner; - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { let mut ser = VecWriter(Vec::new()); monitor.write(&mut ser).unwrap(); if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) { @@ -128,7 +128,7 @@ impl chain::Watch for TestChainMonitor { 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, channelmonitor::ChannelMonitor)>:: read(&mut Cursor::new(&map_entry.get().1), &OnlyReadsKeysInterface {}).unwrap().1; deserialized_monitor.update_monitor(&update, &&TestBroadcaster{}, &&FuzzEstimator{}, &self.logger).unwrap(); let mut ser = VecWriter(Vec::new()); @@ -149,7 +149,7 @@ struct KeyProvider { revoked_commitments: Mutex>>>, } impl KeysInterface for KeyProvider { - type ChanKeySigner = EnforcingChannelKeys; + type Signer = EnforcingSigner; fn get_node_secret(&self) -> SecretKey { 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, 0, 1, self.node_id]).unwrap() @@ -167,10 +167,10 @@ impl KeysInterface for KeyProvider { PublicKey::from_secret_key(&secp_ctx, &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, 0, 3, self.node_id]).unwrap()) } - fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys { + fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner { let secp_ctx = Secp256k1::signing_only(); let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed); - let keys = InMemoryChannelKeys::new( + let keys = InMemorySigner::new( &secp_ctx, 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, 0, 4, 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, 0, 5, self.node_id]).unwrap(), @@ -182,7 +182,7 @@ impl KeysInterface for KeyProvider { [0; 32], ); let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed); - EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, false) + EnforcingSigner::new_with_revoked(keys, revoked_commitment, false) } fn get_secure_random_bytes(&self) -> [u8; 32] { @@ -190,15 +190,15 @@ impl KeysInterface for KeyProvider { [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, 11, self.node_id] } - fn read_chan_signer(&self, buffer: &[u8]) -> Result { + fn read_chan_signer(&self, buffer: &[u8]) -> Result { let mut reader = std::io::Cursor::new(buffer); - let inner: InMemoryChannelKeys = Readable::read(&mut reader)?; + let inner: InMemorySigner = Readable::read(&mut reader)?; let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed); let last_commitment_number = Readable::read(&mut reader)?; - Ok(EnforcingChannelKeys { + Ok(EnforcingSigner { inner, last_commitment_number: Arc::new(Mutex::new(last_commitment_number)), revoked_commitment, @@ -259,7 +259,7 @@ fn check_payment_err(send_err: PaymentSendFailure) { } } -type ChanMan = ChannelManager, Arc, Arc, Arc, Arc>; +type ChanMan = ChannelManager, Arc, Arc, Arc, Arc>; #[inline] fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8) -> bool { @@ -339,7 +339,7 @@ pub fn do_test(data: &[u8], out: Out) { let mut monitors = HashMap::new(); let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap(); for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() { - monitors.insert(outpoint, <(BlockHash, ChannelMonitor)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1); + monitors.insert(outpoint, <(BlockHash, ChannelMonitor)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1); chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser)); } let mut monitor_refs = HashMap::new(); diff --git a/fuzz/src/chanmon_deser.rs b/fuzz/src/chanmon_deser.rs index 596ff275b..933930cf6 100644 --- a/fuzz/src/chanmon_deser.rs +++ b/fuzz/src/chanmon_deser.rs @@ -4,7 +4,7 @@ use bitcoin::hash_types::BlockHash; use lightning::chain::channelmonitor; -use lightning::util::enforcing_trait_impls::EnforcingChannelKeys; +use lightning::util::enforcing_trait_impls::EnforcingSigner; use lightning::util::ser::{ReadableArgs, Writer, Writeable}; use lightning::util::test_utils::OnlyReadsKeysInterface; @@ -25,10 +25,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), &OnlyReadsKeysInterface {}) { + if let Ok((latest_block_hash, monitor)) = <(BlockHash, channelmonitor::ChannelMonitor)>::read(&mut Cursor::new(data), &OnlyReadsKeysInterface {}) { let mut w = VecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).unwrap(); + let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).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 a1e1b7599..7f301fa35 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -30,7 +30,7 @@ use lightning::chain; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; use lightning::chain::chainmonitor; use lightning::chain::transaction::OutPoint; -use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysInterface}; +use lightning::chain::keysinterface::{InMemorySigner, KeysInterface}; use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor}; use lightning::ln::msgs::DecodeError; @@ -38,7 +38,7 @@ use lightning::routing::router::get_route; use lightning::routing::network_graph::NetGraphMsgHandler; use lightning::util::config::UserConfig; use lightning::util::events::{EventsProvider,Event}; -use lightning::util::enforcing_trait_impls::EnforcingChannelKeys; +use lightning::util::enforcing_trait_impls::EnforcingSigner; use lightning::util::logger::Logger; use lightning::util::ser::Readable; @@ -148,14 +148,14 @@ impl<'a> std::hash::Hash for Peer<'a> { } type ChannelMan = ChannelManager< - EnforcingChannelKeys, - Arc, Arc, Arc, Arc, Arc>>, + EnforcingSigner, + 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, Arc>>, + monitor: Arc, Arc, Arc, Arc, Arc>>, handler: PeerMan<'a>, peers: &'a RefCell<[bool; 256]>, @@ -169,7 +169,7 @@ struct MoneyLossDetector<'a> { impl<'a> MoneyLossDetector<'a> { pub fn new(peers: &'a RefCell<[bool; 256]>, manager: Arc, - monitor: Arc, Arc, Arc, Arc, Arc>>, + monitor: Arc, Arc, Arc, Arc, Arc>>, handler: PeerMan<'a>) -> Self { MoneyLossDetector { manager, @@ -248,7 +248,7 @@ struct KeyProvider { counter: AtomicU64, } impl KeysInterface for KeyProvider { - type ChanKeySigner = EnforcingChannelKeys; + type Signer = EnforcingSigner; fn get_node_secret(&self) -> SecretKey { self.node_secret.clone() @@ -266,11 +266,11 @@ impl KeysInterface for KeyProvider { PublicKey::from_secret_key(&secp_ctx, &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, 0, 0, 0]).unwrap()) } - fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys { + fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner { let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8; let secp_ctx = Secp256k1::signing_only(); - EnforcingChannelKeys::new(if inbound { - InMemoryChannelKeys::new( + EnforcingSigner::new(if inbound { + InMemorySigner::new( &secp_ctx, 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, 0, 1, ctr]).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, 0, 2, ctr]).unwrap(), @@ -282,7 +282,7 @@ impl KeysInterface for KeyProvider { [0; 32] ) } else { - InMemoryChannelKeys::new( + InMemorySigner::new( &secp_ctx, 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, 0, 7, ctr]).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, 0, 8, ctr]).unwrap(), @@ -302,8 +302,8 @@ impl KeysInterface for KeyProvider { (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8] } - fn read_chan_signer(&self, data: &[u8]) -> Result { - EnforcingChannelKeys::read(&mut std::io::Cursor::new(data)) + fn read_chan_signer(&self, data: &[u8]) -> Result { + EnforcingSigner::read(&mut std::io::Cursor::new(data)) } } diff --git a/fuzz/src/utils/test_persister.rs b/fuzz/src/utils/test_persister.rs index 0bd60911e..9cb5b60b6 100644 --- a/fuzz/src/utils/test_persister.rs +++ b/fuzz/src/utils/test_persister.rs @@ -1,14 +1,14 @@ use lightning::chain::channelmonitor; use lightning::chain::transaction::OutPoint; -use lightning::util::enforcing_trait_impls::EnforcingChannelKeys; +use lightning::util::enforcing_trait_impls::EnforcingSigner; pub struct TestPersister {} -impl channelmonitor::Persist for TestPersister { - fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { +impl channelmonitor::Persist for TestPersister { + fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { Ok(()) } - fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { Ok(()) } } diff --git a/lightning-net-tokio/src/lib.rs b/lightning-net-tokio/src/lib.rs index 80f7e0552..f15f271e4 100644 --- a/lightning-net-tokio/src/lib.rs +++ b/lightning-net-tokio/src/lib.rs @@ -36,8 +36,8 @@ //! type Logger = dyn lightning::util::logger::Logger; //! type ChainAccess = dyn lightning::chain::Access; //! type ChainFilter = dyn lightning::chain::Filter; -//! type DataPersister = dyn lightning::chain::channelmonitor::Persist; -//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor, Arc, Arc, Arc, Arc>; +//! type DataPersister = dyn lightning::chain::channelmonitor::Persist; +//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor, Arc, Arc, Arc, Arc>; //! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager; //! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager; //! diff --git a/lightning-persister/src/lib.rs b/lightning-persister/src/lib.rs index 0257eb50e..218366e7d 100644 --- a/lightning-persister/src/lib.rs +++ b/lightning-persister/src/lib.rs @@ -10,7 +10,7 @@ use lightning::chain; use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr}; use lightning::chain::channelmonitor; -use lightning::chain::keysinterface::{ChannelKeys, KeysInterface}; +use lightning::chain::keysinterface::{Sign, KeysInterface}; use lightning::chain::transaction::OutPoint; use lightning::ln::channelmanager::ChannelManager; use lightning::util::logger::Logger; @@ -44,19 +44,18 @@ pub struct FilesystemPersister { path_to_channel_data: String, } -impl DiskWriteable for ChannelMonitor { +impl DiskWriteable for ChannelMonitor { fn write_to_file(&self, writer: &mut fs::File) -> Result<(), Error> { self.write(writer) } } -impl DiskWriteable for ChannelManager, Arc, Arc, Arc, Arc> -where ChanSigner: ChannelKeys + Writeable, - M: chain::Watch, - T: BroadcasterInterface, - K: KeysInterface, - F: FeeEstimator, - L: Logger, +impl DiskWriteable for ChannelManager, Arc, Arc, Arc, Arc> +where M: chain::Watch, + T: BroadcasterInterface, + K: KeysInterface, + F: FeeEstimator, + L: Logger, { fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error> { self.write(writer) @@ -78,23 +77,23 @@ impl FilesystemPersister { /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister` /// initialization, within a file called "manager". - pub fn persist_manager( + pub fn persist_manager( data_dir: String, - manager: &ChannelManager, Arc, Arc, Arc, Arc> + manager: &ChannelManager, Arc, Arc, Arc, Arc> ) -> Result<(), std::io::Error> - where ChanSigner: ChannelKeys + Writeable, - M: chain::Watch, - T: BroadcasterInterface, - K: KeysInterface, - F: FeeEstimator, - L: Logger + where Signer: Sign, + M: chain::Watch, + T: BroadcasterInterface, + K: KeysInterface, + F: FeeEstimator, + L: Logger { util::write_to_file(data_dir, "manager".to_string(), manager) } #[cfg(test)] fn load_channel_data(&self, keys: &Keys) -> - Result>, ChannelMonitorUpdateErr> { + Result>, ChannelMonitorUpdateErr> { if let Err(_) = fs::create_dir_all(&self.path_to_channel_data) { return Err(ChannelMonitorUpdateErr::PermanentFailure); } @@ -117,7 +116,7 @@ impl FilesystemPersister { if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); } if let Ok((_, loaded_monitor)) = - <(BlockHash, ChannelMonitor)>::read(&mut Cursor::new(&contents.unwrap()), keys) { + <(BlockHash, ChannelMonitor)>::read(&mut Cursor::new(&contents.unwrap()), keys) { res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor); } else { return Err(ChannelMonitorUpdateErr::PermanentFailure); @@ -127,7 +126,7 @@ impl FilesystemPersister { } } -impl channelmonitor::Persist for FilesystemPersister { +impl channelmonitor::Persist for FilesystemPersister { fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> { let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index); util::write_to_file(self.path_to_channel_data.clone(), filename, monitor) diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index 13a0a8831..cb2d4b47b 100644 --- a/lightning/src/chain/chainmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -37,7 +37,7 @@ use chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use chain::channelmonitor; use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist}; use chain::transaction::{OutPoint, TransactionData}; -use chain::keysinterface::ChannelKeys; +use chain::keysinterface::Sign; use util::logger::Logger; use util::events; use util::events::Event; @@ -56,7 +56,7 @@ use std::ops::Deref; /// [`chain::Watch`]: ../trait.Watch.html /// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html /// [module-level documentation]: index.html -pub struct ChainMonitor +pub struct ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, F::Target: FeeEstimator, @@ -72,7 +72,7 @@ pub struct ChainMonitor ChainMonitor +impl ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, F::Target: FeeEstimator, @@ -140,14 +140,14 @@ where C::Target: chain::Filter, } } -impl chain::Watch for ChainMonitor +impl chain::Watch for ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, P::Target: channelmonitor::Persist, { - type Keys = ChanSigner; + type ChanSigner = ChanSigner; /// Adds the monitor that watches the channel referred to by the given outpoint. /// @@ -233,7 +233,7 @@ where C::Target: chain::Filter, } } -impl events::EventsProvider for ChainMonitor +impl events::EventsProvider for ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, F::Target: FeeEstimator, diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 83b57c8e5..0266f31e2 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -43,7 +43,7 @@ use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash}; use ln::onchaintx::{OnchainTxHandler, InputDescriptors}; use chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use chain::transaction::{OutPoint, TransactionData}; -use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ChannelKeys, KeysInterface}; +use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface}; use util::logger::Logger; use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48}; use util::byte_utils; @@ -623,7 +623,7 @@ impl Readable for ChannelMonitorUpdateStep { /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the /// returned block hash and the the current chain and then reconnecting blocks to get to the /// best chain) upon deserializing the object! -pub struct ChannelMonitor { +pub struct ChannelMonitor { latest_update_id: u64, commitment_transaction_number_obscure_factor: u64, @@ -691,9 +691,9 @@ pub struct ChannelMonitor { outputs_to_watch: HashMap>, #[cfg(test)] - pub onchain_tx_handler: OnchainTxHandler, + pub onchain_tx_handler: OnchainTxHandler, #[cfg(not(test))] - onchain_tx_handler: OnchainTxHandler, + onchain_tx_handler: OnchainTxHandler, // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the // channel has been force-closed. After this is set, no further holder commitment transaction @@ -721,7 +721,7 @@ pub struct ChannelMonitor { #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))] /// Used only in testing and fuzztarget to check serialization roundtrips don't change the /// underlying object -impl PartialEq for ChannelMonitor { +impl PartialEq for ChannelMonitor { fn eq(&self, other: &Self) -> bool { if self.latest_update_id != other.latest_update_id || self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor || @@ -761,7 +761,7 @@ impl PartialEq for ChannelMonitor { } } -impl Writeable for ChannelMonitor { +impl Writeable for ChannelMonitor { fn write(&self, writer: &mut W) -> Result<(), Error> { //TODO: We still write out all the serialization here manually instead of using the fancy //serialization framework we have, we should migrate things over to it. @@ -948,13 +948,13 @@ impl Writeable for ChannelMonitor { } } -impl ChannelMonitor { - pub(crate) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey, +impl ChannelMonitor { + pub(crate) fn new(keys: Signer, shutdown_pubkey: &PublicKey, on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script), channel_parameters: &ChannelTransactionParameters, funding_redeemscript: Script, channel_value_satoshis: u64, commitment_transaction_number_obscure_factor: u64, - initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor { + initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor { assert!(commitment_transaction_number_obscure_factor <= (1 << 48)); let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize()); @@ -2253,7 +2253,7 @@ impl ChannelMonitor { /// transaction and losing money. This is a risk because previous channel states /// are toxic, so it's important that whatever channel state is persisted is /// kept up-to-date. -pub trait Persist: Send + Sync { +pub trait Persist: Send + Sync { /// Persist a new channel's data. The data can be stored any way you want, but /// the identifier provided by Rust-Lightning is the channel's outpoint (and /// it is up to you to maintain a correct mapping between the outpoint and the @@ -2265,7 +2265,7 @@ pub trait Persist: Send + Sync { /// /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html - fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; + fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; /// Update one channel's data. The provided `ChannelMonitor` has already /// applied the given update. @@ -2294,13 +2294,13 @@ pub trait Persist: Send + Sync { /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk /// [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html - fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; + fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; } const MAX_ALLOC_SIZE: usize = 64*1024; -impl<'a, ChanSigner: ChannelKeys, K: KeysInterface> ReadableArgs<&'a K> - for (BlockHash, ChannelMonitor) { +impl<'a, Signer: Sign, K: KeysInterface> ReadableArgs<&'a K> + for (BlockHash, ChannelMonitor) { fn read(reader: &mut R, keys_manager: &'a K) -> Result { macro_rules! unwrap_obj { ($key: expr) => { @@ -2612,7 +2612,7 @@ mod tests { use bitcoin::secp256k1::key::{SecretKey,PublicKey}; use bitcoin::secp256k1::Secp256k1; use std::sync::{Arc, Mutex}; - use chain::keysinterface::InMemoryChannelKeys; + use chain::keysinterface::InMemorySigner; #[test] fn test_prune_preimages() { @@ -2668,7 +2668,7 @@ mod tests { } } - let keys = InMemoryChannelKeys::new( + let keys = InMemorySigner::new( &secp_ctx, SecretKey::from_slice(&[41; 32]).unwrap(), SecretKey::from_slice(&[41; 32]).unwrap(), @@ -2818,7 +2818,7 @@ mod tests { sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs); } } - assert_eq!(base_weight + OnchainTxHandler::::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs)); + assert_eq!(base_weight + OnchainTxHandler::::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs)); // Claim tx with 1 offered HTLCs, 3 received HTLCs claim_tx.input.clear(); @@ -2842,7 +2842,7 @@ mod tests { sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs); } } - assert_eq!(base_weight + OnchainTxHandler::::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs)); + assert_eq!(base_weight + OnchainTxHandler::::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs)); // Justice tx with 1 revoked HTLC-Success tx output claim_tx.input.clear(); @@ -2864,7 +2864,7 @@ mod tests { sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs); } } - assert_eq!(base_weight + OnchainTxHandler::::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs)); + assert_eq!(base_weight + OnchainTxHandler::::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs)); } // Further testing is done in the ChannelManager integration tests. diff --git a/lightning/src/chain/keysinterface.rs b/lightning/src/chain/keysinterface.rs index 37d4c744c..9d3b95586 100644 --- a/lightning/src/chain/keysinterface.rs +++ b/lightning/src/chain/keysinterface.rs @@ -58,7 +58,7 @@ pub struct DelayedPaymentOutputDescriptor { /// derive the witnessScript for this output. pub revocation_pubkey: PublicKey, /// Arbitrary identification information returned by a call to - /// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in + /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in /// the channel to spend the output. pub channel_keys_id: [u8; 32], /// The value of the channel which this output originated from, possibly indirectly. @@ -80,7 +80,7 @@ pub struct StaticPaymentOutputDescriptor { /// The output which is referenced by the given outpoint pub output: TxOut, /// Arbitrary identification information returned by a call to - /// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in + /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in /// the channel to spend the output. pub channel_keys_id: [u8; 32], /// The value of the channel which this transactions spends. @@ -125,14 +125,14 @@ pub enum SpendableOutputDescriptor { /// /// To derive the delayed_payment key which is used to sign for this input, you must pass the /// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in - /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to + /// Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to /// chan_utils::derive_private_key. The public key can be generated without the secret key /// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in - /// ChannelKeys::pubkeys(). + /// Sign::pubkeys(). /// /// To derive the revocation_pubkey provided here (which is used in the witness /// script generation), you must pass the counterparty revocation_basepoint (which appears in the - /// call to ChannelKeys::ready_channel) and the provided per_commitment point + /// call to Sign::ready_channel) and the provided per_commitment point /// to chan_utils::derive_public_revocation_key. /// /// The witness script which is hashed and included in the output script_pubkey may be @@ -141,7 +141,7 @@ pub enum SpendableOutputDescriptor { /// chan_utils::get_revokeable_redeemscript. DelayedPaymentOutput(DelayedPaymentOutputDescriptor), /// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which - /// corresponds to the public key in ChannelKeys::pubkeys().payment_point). + /// corresponds to the public key in Sign::pubkeys().payment_point). /// The witness in the spending input, is, thus, simply: /// /// @@ -207,10 +207,10 @@ impl Readable for SpendableOutputDescriptor { } } -/// Set of lightning keys needed to operate a channel as described in BOLT 3. +/// A trait to sign lightning channel transactions as described in BOLT 3. /// /// Signing services could be implemented on a hardware wallet. In this case, -/// the current ChannelKeys would be a front-end on top of a communication +/// the current Sign would be a front-end on top of a communication /// channel connected to your secure device and lightning key material wouldn't /// reside on a hot server. Nevertheless, a this deployment would still need /// to trust the ChannelManager to avoid loss of funds as this latest component @@ -224,9 +224,9 @@ impl Readable for SpendableOutputDescriptor { /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted /// to act, as liveness and breach reply correctness are always going to be hard requirements /// of LN security model, orthogonal of key management issues. -// TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create +// TODO: We should remove Clone by instead requesting a new Sign copy when we create // ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors. -pub trait ChannelKeys : Send+Clone + Writeable { +pub trait Sign : Send+Clone + Writeable { /// Gets the per-commitment point for a specific commitment number /// /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards. @@ -245,7 +245,7 @@ pub trait ChannelKeys : Send+Clone + Writeable { fn pubkeys(&self) -> &ChannelPublicKeys; /// Gets an arbitrary identifier describing the set of keys which are provided back to you in /// some SpendableOutputDescriptor types. This should be sufficient to identify this - /// ChannelKeys object uniquely and lookup or re-derive its keys. + /// Sign object uniquely and lookup or re-derive its keys. fn channel_keys_id(&self) -> [u8; 32]; /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions. @@ -346,8 +346,8 @@ pub trait ChannelKeys : Send+Clone + Writeable { /// A trait to describe an object which can get user secrets and key material. pub trait KeysInterface: Send + Sync { - /// A type which implements ChannelKeys which will be returned by get_channel_keys. - type ChanKeySigner : ChannelKeys; + /// A type which implements Sign which will be returned by get_channel_signer. + type Signer : Sign; /// Get node secret key (aka node_id or network_key). /// @@ -364,11 +364,11 @@ pub trait KeysInterface: Send + Sync { /// This method should return a different value each time it is called, to avoid linking /// on-chain funds across channels as controlled to the same user. fn get_shutdown_pubkey(&self) -> PublicKey; - /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you + /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you /// restarted with some stale data! /// /// This method must return a different value each time it is called. - fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner; + fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer; /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting /// onion packets and for temporary channel IDs. There is no requirement that these be /// persisted anywhere, though they must be unique across restarts. @@ -376,21 +376,21 @@ pub trait KeysInterface: Send + Sync { /// This method must return a different value each time it is called. fn get_secure_random_bytes(&self) -> [u8; 32]; - /// Reads a `ChanKeySigner` for this `KeysInterface` from the given input stream. + /// Reads a `Signer` for this `KeysInterface` from the given input stream. /// This is only called during deserialization of other objects which contain - /// `ChannelKeys`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s). - /// The bytes are exactly those which `::write()` writes, and + /// `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s). + /// The bytes are exactly those which `::write()` writes, and /// contain no versioning scheme. You may wish to include your own version prefix and ensure /// you've read all of the provided bytes to ensure no corruption occurred. - fn read_chan_signer(&self, reader: &[u8]) -> Result; + fn read_chan_signer(&self, reader: &[u8]) -> Result; } #[derive(Clone)] -/// A simple implementation of ChannelKeys that just keeps the private keys in memory. +/// A simple implementation of Sign that just keeps the private keys in memory. /// /// This implementation performs no policy checks and is insufficient by itself as /// a secure external signer. -pub struct InMemoryChannelKeys { +pub struct InMemorySigner { /// Private key of anchor tx pub funding_key: SecretKey, /// Holder secret key for blinded revocation pubkey @@ -413,8 +413,8 @@ pub struct InMemoryChannelKeys { channel_keys_id: [u8; 32], } -impl InMemoryChannelKeys { - /// Create a new InMemoryChannelKeys +impl InMemorySigner { + /// Create a new InMemorySigner pub fn new( secp_ctx: &Secp256k1, funding_key: SecretKey, @@ -424,12 +424,12 @@ impl InMemoryChannelKeys { htlc_base_key: SecretKey, commitment_seed: [u8; 32], channel_value_satoshis: u64, - channel_keys_id: [u8; 32]) -> InMemoryChannelKeys { + channel_keys_id: [u8; 32]) -> InMemorySigner { let holder_channel_pubkeys = - InMemoryChannelKeys::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key, + InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key, &payment_key, &delayed_payment_base_key, &htlc_base_key); - InMemoryChannelKeys { + InMemorySigner { funding_key, revocation_base_key, payment_key, @@ -549,7 +549,7 @@ impl InMemoryChannelKeys { } } -impl ChannelKeys for InMemoryChannelKeys { +impl Sign for InMemorySigner { fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1) -> PublicKey { let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap(); PublicKey::from_secret_key(secp_ctx, &commitment_secret) @@ -682,7 +682,7 @@ impl ChannelKeys for InMemoryChannelKeys { } } -impl Writeable for InMemoryChannelKeys { +impl Writeable for InMemorySigner { fn write(&self, writer: &mut W) -> Result<(), Error> { self.funding_key.write(writer)?; self.revocation_base_key.write(writer)?; @@ -698,7 +698,7 @@ impl Writeable for InMemoryChannelKeys { } } -impl Readable for InMemoryChannelKeys { +impl Readable for InMemorySigner { fn read(reader: &mut R) -> Result { let funding_key = Readable::read(reader)?; let revocation_base_key = Readable::read(reader)?; @@ -710,12 +710,12 @@ impl Readable for InMemoryChannelKeys { let channel_value_satoshis = Readable::read(reader)?; let secp_ctx = Secp256k1::signing_only(); let holder_channel_pubkeys = - InMemoryChannelKeys::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key, + InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key, &payment_key, &delayed_payment_base_key, &htlc_base_key); let keys_id = Readable::read(reader)?; - Ok(InMemoryChannelKeys { + Ok(InMemorySigner { funding_key, revocation_base_key, payment_key, @@ -819,12 +819,12 @@ impl KeysManager { unique_start.input(&self.seed); unique_start } - /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation + /// Derive an old set of Sign for per-channel secrets based on a key derivation /// parameters. /// Key derivation parameters are accessible through a per-channel secrets - /// ChannelKeys::channel_keys_id and is provided inside DynamicOuputP2WSH in case of + /// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of /// onchain output detection for which a corresponding delayed_payment_key must be derived. - pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemoryChannelKeys { + pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner { let chan_id = byte_utils::slice_to_be64(¶ms[0..8]); assert!(chan_id <= std::u32::MAX as u64); // Otherwise the params field wasn't created by us let mut unique_start = Sha256::engine(); @@ -860,7 +860,7 @@ impl KeysManager { let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key); let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key); - InMemoryChannelKeys::new( + InMemorySigner::new( &self.secp_ctx, funding_key, revocation_base_key, @@ -883,7 +883,7 @@ impl KeysManager { /// We do not enforce that outputs meet the dust limit or that any output scripts are standard. /// /// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used - /// this KeysManager or one of the `InMemoryChannelKeys` created by this KeysManager. + /// this KeysManager or one of the `InMemorySigner` created by this KeysManager. pub fn spend_spendable_outputs(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1) -> Result { let mut input = Vec::new(); let mut input_value = 0; @@ -935,7 +935,7 @@ impl KeysManager { }; transaction_utils::maybe_add_change_output(&mut spend_tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?; - let mut keys_cache: Option<(InMemoryChannelKeys, [u8; 32])> = None; + let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None; let mut input_idx = 0; for outp in descriptors { match outp { @@ -992,7 +992,7 @@ impl KeysManager { } impl KeysInterface for KeysManager { - type ChanKeySigner = InMemoryChannelKeys; + type Signer = InMemorySigner; fn get_node_secret(&self) -> SecretKey { self.node_secret.clone() @@ -1006,7 +1006,7 @@ impl KeysInterface for KeysManager { self.shutdown_pubkey.clone() } - fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner { + fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer { let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel); assert!(child_ix <= std::u32::MAX as usize); let mut id = [0; 32]; @@ -1027,7 +1027,7 @@ impl KeysInterface for KeysManager { Sha256::from_engine(sha).into_inner() } - fn read_chan_signer(&self, reader: &[u8]) -> Result { - InMemoryChannelKeys::read(&mut std::io::Cursor::new(reader)) + fn read_chan_signer(&self, reader: &[u8]) -> Result { + InMemorySigner::read(&mut std::io::Cursor::new(reader)) } } diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index af3fbea44..98fc857e9 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -14,7 +14,7 @@ use bitcoin::blockdata::transaction::TxOut; use bitcoin::hash_types::{BlockHash, Txid}; use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent}; -use chain::keysinterface::ChannelKeys; +use chain::keysinterface::Sign; use chain::transaction::OutPoint; pub mod chaininterface; @@ -69,7 +69,7 @@ pub trait Access: Send + Sync { /// [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure pub trait Watch: Send + Sync { /// Keys needed by monitors for creating and signing transactions. - type Keys: ChannelKeys; + type ChanSigner: Sign; /// Watches a channel identified by `funding_txo` using `monitor`. /// @@ -80,7 +80,7 @@ pub trait Watch: Send + Sync { /// [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch /// [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected /// [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected - fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; + fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; /// Updates a channel identified by `funding_txo` by applying `update` to its monitor. /// diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index f86c53bc3..647fc3238 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -8,8 +8,7 @@ // licenses. //! Various utilities for building scripts and deriving keys related to channels. These are -//! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing -//! by hand. +//! largely of interest for those implementing chain::keysinterface::Sign message signing by hand. use bitcoin::blockdata::script::{Script,Builder}; use bitcoin::blockdata::opcodes; diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index 04fff34cd..8fc773f68 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -23,7 +23,7 @@ use ln::features::InitFeatures; use ln::msgs; use ln::msgs::{ChannelMessageHandler, ErrorAction, RoutingMessageHandler}; use routing::router::get_route; -use util::enforcing_trait_impls::EnforcingChannelKeys; +use util::enforcing_trait_impls::EnforcingSigner; use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider}; use util::errors::APIError; use util::ser::{ReadableArgs, Writeable}; @@ -106,7 +106,7 @@ fn test_monitor_and_persister_update_fail() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, ChannelMonitor)>::read( + let new_monitor = <(BlockHash, ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; assert!(new_monitor == *monitor); let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager); diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index d3a372e47..2617bec03 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -31,7 +31,7 @@ use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER}; use chain::transaction::{OutPoint, TransactionData}; -use chain::keysinterface::{ChannelKeys, KeysInterface}; +use chain::keysinterface::{Sign, KeysInterface}; use util::transaction_utils; use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter}; use util::logger::Logger; @@ -288,7 +288,7 @@ impl HTLCCandidate { // // Holder designates channel data owned for the benefice of the user client. // Counterparty designates channel data owned by the another channel participant entity. -pub(super) struct Channel { +pub(super) struct Channel { config: ChannelConfig, user_id: u64, @@ -301,9 +301,9 @@ pub(super) struct Channel { latest_monitor_update_id: u64, #[cfg(not(test))] - holder_keys: ChanSigner, + holder_keys: Signer, #[cfg(test)] - pub(super) holder_keys: ChanSigner, + pub(super) holder_keys: Signer, shutdown_pubkey: PublicKey, destination_script: Script, @@ -478,7 +478,7 @@ macro_rules! secp_check { }; } -impl Channel { +impl Channel { // Convert constants + channel value to limits: fn get_holder_max_htlc_value_in_flight_msat(channel_value_satoshis: u64) -> u64 { channel_value_satoshis * 1000 / 10 //TODO @@ -498,12 +498,12 @@ impl Channel { } // Constructors: - pub fn new_outbound(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, config: &UserConfig) -> Result, APIError> - where K::Target: KeysInterface, + pub fn new_outbound(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, config: &UserConfig) -> Result, APIError> + where K::Target: KeysInterface, F::Target: FeeEstimator, { let holder_selected_contest_delay = config.own_channel_config.our_to_self_delay; - let chan_keys = keys_provider.get_channel_keys(false, channel_value_satoshis); + let chan_keys = keys_provider.get_channel_signer(false, channel_value_satoshis); let pubkeys = chan_keys.pubkeys().clone(); if channel_value_satoshis >= MAX_FUNDING_SATOSHIS { @@ -517,7 +517,7 @@ impl Channel { return Err(APIError::APIMisuseError {err: format!("Configured with an unreasonable our_to_self_delay ({}) putting user funds at risks", holder_selected_contest_delay)}); } let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); - if Channel::::get_holder_selected_channel_reserve_satoshis(channel_value_satoshis) < Channel::::derive_holder_dust_limit_satoshis(background_feerate) { + if Channel::::get_holder_selected_channel_reserve_satoshis(channel_value_satoshis) < Channel::::derive_holder_dust_limit_satoshis(background_feerate) { return Err(APIError::FeeRateTooHigh{err: format!("Not enough reserve above dust limit can be found at current fee rate({})", background_feerate), feerate: background_feerate}); } @@ -573,7 +573,7 @@ impl Channel { feerate_per_kw: feerate, counterparty_dust_limit_satoshis: 0, - holder_dust_limit_satoshis: Channel::::derive_holder_dust_limit_satoshis(background_feerate), + holder_dust_limit_satoshis: Channel::::derive_holder_dust_limit_satoshis(background_feerate), counterparty_max_htlc_value_in_flight_msat: 0, counterparty_selected_channel_reserve_satoshis: 0, counterparty_htlc_minimum_msat: 0, @@ -622,11 +622,11 @@ impl Channel { /// Creates a new channel from a remote sides' request for one. /// Assumes chain_hash has already been checked and corresponds with what we expect! - pub fn new_from_req(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, config: &UserConfig) -> Result, ChannelError> - where K::Target: KeysInterface, + pub fn new_from_req(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, config: &UserConfig) -> Result, ChannelError> + where K::Target: KeysInterface, F::Target: FeeEstimator { - let chan_keys = keys_provider.get_channel_keys(true, msg.funding_satoshis); + let chan_keys = keys_provider.get_channel_signer(true, msg.funding_satoshis); let pubkeys = chan_keys.pubkeys().clone(); let counterparty_pubkeys = ChannelPublicKeys { funding_pubkey: msg.funding_pubkey, @@ -662,7 +662,7 @@ impl Channel { if msg.htlc_minimum_msat >= full_channel_value_msat { return Err(ChannelError::Close(format!("Minimum htlc value ({}) was larger than full channel value ({})", msg.htlc_minimum_msat, full_channel_value_msat))); } - Channel::::check_remote_fee(fee_estimator, msg.feerate_per_kw)?; + Channel::::check_remote_fee(fee_estimator, msg.feerate_per_kw)?; let max_counterparty_selected_contest_delay = u16::min(config.peer_channel_config_limits.their_to_self_delay, MAX_LOCAL_BREAKDOWN_TIMEOUT); if msg.to_self_delay > max_counterparty_selected_contest_delay { @@ -711,8 +711,8 @@ impl Channel { let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); - let holder_dust_limit_satoshis = Channel::::derive_holder_dust_limit_satoshis(background_feerate); - let holder_selected_channel_reserve_satoshis = Channel::::get_holder_selected_channel_reserve_satoshis(msg.funding_satoshis); + let holder_dust_limit_satoshis = Channel::::derive_holder_dust_limit_satoshis(background_feerate); + let holder_selected_channel_reserve_satoshis = Channel::::get_holder_selected_channel_reserve_satoshis(msg.funding_satoshis); if holder_selected_channel_reserve_satoshis < holder_dust_limit_satoshis { return Err(ChannelError::Close(format!("Suitable channel reserve not found. remote_channel_reserve was ({}). dust_limit_satoshis is ({}).", holder_selected_channel_reserve_satoshis, holder_dust_limit_satoshis))); } @@ -987,7 +987,7 @@ impl Channel { }; debug_assert!(broadcaster_max_commitment_tx_output.0 <= value_to_self_msat as u64 || value_to_self_msat / 1000 >= self.counterparty_selected_channel_reserve_satoshis as i64); broadcaster_max_commitment_tx_output.0 = cmp::max(broadcaster_max_commitment_tx_output.0, value_to_self_msat as u64); - debug_assert!(broadcaster_max_commitment_tx_output.1 <= value_to_remote_msat as u64 || value_to_remote_msat / 1000 >= Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) as i64); + debug_assert!(broadcaster_max_commitment_tx_output.1 <= value_to_remote_msat as u64 || value_to_remote_msat / 1000 >= Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) as i64); broadcaster_max_commitment_tx_output.1 = cmp::max(broadcaster_max_commitment_tx_output.1, value_to_remote_msat as u64); } @@ -1397,7 +1397,7 @@ impl Channel { if msg.channel_reserve_satoshis < self.holder_dust_limit_satoshis { return Err(ChannelError::Close(format!("Peer never wants payout outputs? channel_reserve_satoshis was ({}). dust_limit is ({})", msg.channel_reserve_satoshis, self.holder_dust_limit_satoshis))); } - let remote_reserve = Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis); + let remote_reserve = Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis); if msg.dust_limit_satoshis > remote_reserve { return Err(ChannelError::Close(format!("Dust limit ({}) is bigger than our channel reserve ({})", msg.dust_limit_satoshis, remote_reserve))); } @@ -1520,7 +1520,7 @@ impl Channel { &self.get_counterparty_pubkeys().funding_pubkey } - pub fn funding_created(&mut self, msg: &msgs::FundingCreated, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor), ChannelError> where L::Target: Logger { + pub fn funding_created(&mut self, msg: &msgs::FundingCreated, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor), ChannelError> where L::Target: Logger { if self.is_outbound() { return Err(ChannelError::Close("Received funding_created for an outbound channel?".to_owned())); } @@ -1591,7 +1591,7 @@ impl Channel { /// Handles a funding_signed message from the remote end. /// If this call is successful, broadcast the funding transaction (and not before!) - pub fn funding_signed(&mut self, msg: &msgs::FundingSigned, logger: &L) -> Result, ChannelError> where L::Target: Logger { + pub fn funding_signed(&mut self, msg: &msgs::FundingSigned, logger: &L) -> Result, ChannelError> where L::Target: Logger { if !self.is_outbound() { return Err(ChannelError::Close("Received funding_signed for an inbound channel?".to_owned())); } @@ -1932,7 +1932,7 @@ impl Channel { if inbound_htlc_count + 1 > OUR_MAX_HTLCS as u32 { return Err(ChannelError::Close(format!("Remote tried to push more than our max accepted HTLCs ({})", OUR_MAX_HTLCS))); } - let holder_max_htlc_value_in_flight_msat = Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis); + let holder_max_htlc_value_in_flight_msat = Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis); if htlc_inbound_value_msat + msg.amount_msat > holder_max_htlc_value_in_flight_msat { return Err(ChannelError::Close(format!("Remote HTLC add would put them over our max HTLC value ({})", holder_max_htlc_value_in_flight_msat))); } @@ -1976,7 +1976,7 @@ impl Channel { }; let chan_reserve_msat = - Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) * 1000; + Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) * 1000; if pending_remote_value_msat - msg.amount_msat - remote_commit_tx_fee_msat < chan_reserve_msat { return Err(ChannelError::Close("Remote HTLC add would put them under remote reserve value".to_owned())); } @@ -2140,7 +2140,7 @@ impl Channel { let total_fee = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000; //If channel fee was updated by funder confirm funder can afford the new fee rate when applied to the current local commitment transaction if update_fee { - let counterparty_reserve_we_require = Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis); + let counterparty_reserve_we_require = Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis); if self.channel_value_satoshis - self.value_to_self_msat / 1000 < total_fee + counterparty_reserve_we_require { return Err((None, ChannelError::Close("Funding remote cannot afford proposed new fee".to_owned()))); } @@ -2814,7 +2814,7 @@ impl Channel { if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { return Err(ChannelError::Close("Peer sent update_fee when we needed a channel_reestablish".to_owned())); } - Channel::::check_remote_fee(fee_estimator, msg.feerate_per_kw)?; + Channel::::check_remote_fee(fee_estimator, msg.feerate_per_kw)?; self.pending_update_fee = Some(msg.feerate_per_kw); self.update_time_counter += 1; Ok(()) @@ -3332,7 +3332,7 @@ impl Channel { // channel might have been used to route very small values (either by honest users or as DoS). self.channel_value_satoshis * 9 / 10, - Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis) + Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis) ); } @@ -3367,7 +3367,7 @@ impl Channel { } #[cfg(test)] - pub fn get_keys(&self) -> &ChanSigner { + pub fn get_keys(&self) -> &Signer { &self.holder_keys } @@ -3661,8 +3661,8 @@ impl Channel { funding_satoshis: self.channel_value_satoshis, push_msat: self.channel_value_satoshis * 1000 - self.value_to_self_msat, dust_limit_satoshis: self.holder_dust_limit_satoshis, - max_htlc_value_in_flight_msat: Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis), - channel_reserve_satoshis: Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis), + max_htlc_value_in_flight_msat: Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis), + channel_reserve_satoshis: Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis), htlc_minimum_msat: self.holder_htlc_minimum_msat, feerate_per_kw: self.feerate_per_kw as u32, to_self_delay: self.get_holder_selected_contest_delay(), @@ -3695,8 +3695,8 @@ impl Channel { msgs::AcceptChannel { temporary_channel_id: self.channel_id, dust_limit_satoshis: self.holder_dust_limit_satoshis, - max_htlc_value_in_flight_msat: Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis), - channel_reserve_satoshis: Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis), + max_htlc_value_in_flight_msat: Channel::::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis), + channel_reserve_satoshis: Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis), htlc_minimum_msat: self.holder_htlc_minimum_msat, minimum_depth: self.minimum_depth, to_self_delay: self.get_holder_selected_contest_delay(), @@ -3904,7 +3904,7 @@ impl Channel { if !self.is_outbound() { // Check that we won't violate the remote channel reserve by adding this HTLC. let counterparty_balance_msat = self.channel_value_satoshis * 1000 - self.value_to_self_msat; - let holder_selected_chan_reserve_msat = Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis); + let holder_selected_chan_reserve_msat = Channel::::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis); let htlc_candidate = HTLCCandidate::new(amount_msat, HTLCInitiator::LocalOffered); let counterparty_commit_tx_fee_msat = self.next_remote_commit_tx_fee_msat(htlc_candidate, None); if counterparty_balance_msat < holder_selected_chan_reserve_msat + counterparty_commit_tx_fee_msat { @@ -4255,7 +4255,7 @@ impl Readable for InboundHTLCRemovalReason { } } -impl Writeable for Channel { +impl Writeable for Channel { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { // Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been // called but include holding cell updates (and obviously we don't modify self). @@ -4444,8 +4444,8 @@ impl Writeable for Channel { } const MAX_ALLOC_SIZE: usize = 64*1024; -impl<'a, ChanSigner: ChannelKeys, K: Deref> ReadableArgs<&'a K> for Channel - where K::Target: KeysInterface { +impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel + where K::Target: KeysInterface { fn read(reader: &mut R, keys_source: &'a K) -> Result { let _ver: u8 = Readable::read(reader)?; let min_ver: u8 = Readable::read(reader)?; @@ -4692,17 +4692,17 @@ mod tests { use bitcoin::hashes::hex::FromHex; use hex; use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash}; - use ln::channel::{Channel,ChannelKeys,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys}; + use ln::channel::{Channel,Sign,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys}; use ln::channel::MAX_FUNDING_SATOSHIS; use ln::features::InitFeatures; use ln::msgs::{OptionalField, DataLossProtect, DecodeError}; use ln::chan_utils; use ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT}; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; - use chain::keysinterface::{InMemoryChannelKeys, KeysInterface}; + use chain::keysinterface::{InMemorySigner, KeysInterface}; use chain::transaction::OutPoint; use util::config::UserConfig; - use util::enforcing_trait_impls::EnforcingChannelKeys; + use util::enforcing_trait_impls::EnforcingSigner; use util::test_utils; use util::logger::Logger; use bitcoin::secp256k1::{Secp256k1, Message, Signature, All}; @@ -4728,10 +4728,10 @@ mod tests { } struct Keys { - chan_keys: InMemoryChannelKeys, + chan_keys: InMemorySigner, } impl KeysInterface for Keys { - type ChanKeySigner = InMemoryChannelKeys; + type Signer = InMemorySigner; fn get_node_secret(&self) -> SecretKey { panic!(); } fn get_destination_script(&self) -> Script { @@ -4747,11 +4747,11 @@ mod tests { PublicKey::from_secret_key(&secp_ctx, &channel_close_key) } - fn get_channel_keys(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemoryChannelKeys { + fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemorySigner { self.chan_keys.clone() } fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] } - fn read_chan_signer(&self, _data: &[u8]) -> Result { panic!(); } + fn read_chan_signer(&self, _data: &[u8]) -> Result { panic!(); } } fn public_from_secret_hex(secp_ctx: &Secp256k1, hex: &str) -> PublicKey { @@ -4771,7 +4771,7 @@ mod tests { let node_a_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let config = UserConfig::default(); - let node_a_chan = Channel::::new_outbound(&&fee_est, &&keys_provider, node_a_node_id, 10000000, 100000, 42, &config).unwrap(); + let node_a_chan = Channel::::new_outbound(&&fee_est, &&keys_provider, node_a_node_id, 10000000, 100000, 42, &config).unwrap(); // Now change the fee so we can check that the fee in the open_channel message is the // same as the old fee. @@ -4796,14 +4796,14 @@ mod tests { // Create Node A's channel pointing to Node B's pubkey let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let config = UserConfig::default(); - let mut node_a_chan = Channel::::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap(); + let mut node_a_chan = Channel::::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap(); // Create Node B's channel by receiving Node A's open_channel message // Make sure A's dust limit is as we expect. let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash()); assert_eq!(open_channel_msg.dust_limit_satoshis, 1560); let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap()); - let node_b_chan = Channel::::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap(); + let node_b_chan = Channel::::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap(); // Node B --> Node A: accept channel, explicitly setting B's dust limit. let mut accept_channel_msg = node_b_chan.get_accept_channel(); @@ -4863,7 +4863,7 @@ mod tests { let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let config = UserConfig::default(); - let mut chan = Channel::::new_outbound(&&fee_est, &&keys_provider, node_id, 10000000, 100000, 42, &config).unwrap(); + let mut chan = Channel::::new_outbound(&&fee_est, &&keys_provider, node_id, 10000000, 100000, 42, &config).unwrap(); let commitment_tx_fee_0_htlcs = chan.commit_tx_fee_msat(0); let commitment_tx_fee_1_htlc = chan.commit_tx_fee_msat(1); @@ -4910,12 +4910,12 @@ mod tests { // Create Node A's channel pointing to Node B's pubkey let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let config = UserConfig::default(); - let mut node_a_chan = Channel::::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap(); + let mut node_a_chan = Channel::::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap(); // Create Node B's channel by receiving Node A's open_channel message let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash()); let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap()); - let mut node_b_chan = Channel::::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap(); + let mut node_b_chan = Channel::::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap(); // Node B --> Node A: accept channel let accept_channel_msg = node_b_chan.get_accept_channel(); @@ -4967,7 +4967,7 @@ mod tests { let logger : Arc = Arc::new(test_utils::TestLogger::new()); let secp_ctx = Secp256k1::new(); - let mut chan_keys = InMemoryChannelKeys::new( + let mut chan_keys = InMemorySigner::new( &secp_ctx, SecretKey::from_slice(&hex::decode("30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749").unwrap()[..]).unwrap(), SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(), @@ -4988,7 +4988,7 @@ mod tests { let counterparty_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let mut config = UserConfig::default(); config.channel_options.announced_channel = false; - let mut chan = Channel::::new_outbound(&&feeest, &&keys_provider, counterparty_node_id, 10_000_000, 100000, 42, &config).unwrap(); // Nothing uses their network key in this test + let mut chan = Channel::::new_outbound(&&feeest, &&keys_provider, counterparty_node_id, 10_000_000, 100000, 42, &config).unwrap(); // Nothing uses their network key in this test chan.holder_dust_limit_satoshis = 546; let funding_info = OutPoint{ txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), index: 0 }; diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 84dc486c9..21ee32b0f 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -46,7 +46,7 @@ use ln::msgs; use ln::msgs::NetAddress; use ln::onion_utils; use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField}; -use chain::keysinterface::{ChannelKeys, KeysInterface, KeysManager, InMemoryChannelKeys}; +use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner}; use util::config::UserConfig; use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider}; use util::{byte_utils, events}; @@ -314,8 +314,8 @@ pub(super) enum RAACommitmentOrder { } // Note this is only exposed in cfg(test): -pub(super) struct ChannelHolder { - pub(super) by_id: HashMap<[u8; 32], Channel>, +pub(super) struct ChannelHolder { + pub(super) by_id: HashMap<[u8; 32], Channel>, pub(super) short_to_id: HashMap, /// short channel id -> forward infos. Key of 0 means payments received /// Note that while this is held in the same mutex as the channels themselves, no consistency @@ -349,7 +349,7 @@ const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assum /// issues such as overly long function definitions. Note that the ChannelManager can take any /// type that implements KeysInterface for its keys manager, but this type alias chooses the /// concrete type of the KeysManager. -pub type SimpleArcChannelManager = Arc, Arc, Arc, Arc, Arc>>; +pub type SimpleArcChannelManager = Arc, Arc, Arc, Arc, Arc>>; /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't @@ -359,7 +359,7 @@ pub type SimpleArcChannelManager = Arc = ChannelManager; +pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager; /// Manager which keeps track of a number of channels and sends messages to the appropriate /// channel, also tracking HTLC preimages and forwarding onion packets appropriately. @@ -397,10 +397,10 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage /// essentially you should default to using a SimpleRefChannelManager, and use a /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when /// you're using lightning-net-tokio. -pub struct ChannelManager - where M::Target: chain::Watch, +pub struct ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -418,9 +418,9 @@ pub struct ChannelManager, #[cfg(any(test, feature = "_test_utils"))] - pub(super) channel_state: Mutex>, + pub(super) channel_state: Mutex>, #[cfg(not(any(test, feature = "_test_utils")))] - channel_state: Mutex>, + channel_state: Mutex>, our_network_key: SecretKey, /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this @@ -744,10 +744,10 @@ macro_rules! maybe_break_monitor_err { } } -impl ChannelManager - where M::Target: chain::Watch, +impl ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -845,7 +845,7 @@ impl Ok(()) } - fn list_channels_with_filter)) -> bool>(&self, f: Fn) -> Vec { + fn list_channels_with_filter)) -> bool>(&self, f: Fn) -> Vec { let mut res = Vec::new(); { let channel_state = self.channel_state.lock().unwrap(); @@ -1002,7 +1002,7 @@ impl } } - fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard>) { + fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard>) { macro_rules! return_malformed_err { ($msg: expr, $err_code: expr) => { { @@ -1274,7 +1274,7 @@ impl /// only fails if the channel does not yet have an assigned short_id /// May be called with channel_state already locked! - fn get_channel_update(&self, chan: &Channel) -> Result { + fn get_channel_update(&self, chan: &Channel) -> Result { let short_channel_id = match chan.get_short_channel_id() { None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}), Some(id) => id, @@ -1522,7 +1522,7 @@ impl } } - fn get_announcement_sigs(&self, chan: &Channel) -> Option { + fn get_announcement_sigs(&self, chan: &Channel) -> Option { if !chan.should_announce() { log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id())); return None @@ -1947,7 +1947,7 @@ impl /// to fail and take the channel_state lock for each iteration (as we take ownership and may /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to /// still-available channels. - fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) { + fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) { //TODO: There is a timing attack here where if a node fails an HTLC back to us they can //identify whether we sent it or not based on the (I presume) very different runtime //between the branches here. We should make this async and move it into the forward HTLCs @@ -2141,7 +2141,7 @@ impl } else { false } } - fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> { + fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> { //TODO: Delay the claimed_funds relaying just like we do outbound relay! let channel_state = &mut **channel_state_lock; let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) { @@ -2194,7 +2194,7 @@ impl } else { unreachable!(); } } - fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_preimage: PaymentPreimage) { + fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_preimage: PaymentPreimage) { match source { HTLCSource::OutboundRoute { .. } => { mem::drop(channel_state_lock); @@ -2619,7 +2619,7 @@ impl return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id)); } - let create_pending_htlc_status = |chan: &Channel, pending_forward_info: PendingHTLCStatus, error_code: u16| { + let create_pending_htlc_status = |chan: &Channel, pending_forward_info: PendingHTLCStatus, error_code: u16| { // Ensure error_code has the UPDATE flag set, since by default we send a // channel update along as part of failing the HTLC. assert!((error_code & 0x1000) != 0); @@ -3101,10 +3101,10 @@ impl } } -impl MessageSendEventsProvider for ChannelManager - where M::Target: chain::Watch, +impl MessageSendEventsProvider for ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3120,10 +3120,10 @@ impl } } -impl EventsProvider for ChannelManager - where M::Target: chain::Watch, +impl EventsProvider for ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3139,10 +3139,10 @@ impl } } -impl ChannelManager - where M::Target: chain::Watch, +impl ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3318,11 +3318,11 @@ impl } } -impl - ChannelMessageHandler for ChannelManager - where M::Target: chain::Watch, +impl + ChannelMessageHandler for ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3832,10 +3832,10 @@ impl Readable for HTLCForwardInfo { } } -impl Writeable for ChannelManager - where M::Target: chain::Watch, +impl Writeable for ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3915,10 +3915,10 @@ impl /// 4) Reconnect blocks on your ChannelMonitors. /// 5) Move the ChannelMonitors into your local chain::Watch. /// 6) Disconnect/connect blocks on the ChannelManager. -pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> - where M::Target: chain::Watch, +pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3961,14 +3961,14 @@ pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: /// this struct. /// /// (C-not exported) because we have no HashMap bindings - pub channel_monitors: HashMap>, + pub channel_monitors: HashMap>, } -impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> - ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L> - where M::Target: chain::Watch, +impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> + ChannelManagerReadArgs<'a, Signer, M, T, K, F, L> + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -3976,7 +3976,7 @@ impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L /// HashMap for you. This is primarily useful for C bindings where it is not practical to /// populate a HashMap directly from C. pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig, - mut channel_monitors: Vec<&'a mut ChannelMonitor>) -> Self { + mut channel_monitors: Vec<&'a mut ChannelMonitor>) -> Self { Self { keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config, channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect() @@ -3986,29 +3986,29 @@ impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the // SipmleArcChannelManager type: -impl<'a, ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> - ReadableArgs> for (BlockHash, Arc>) - where M::Target: chain::Watch, +impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> + ReadableArgs> for (BlockHash, Arc>) + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { - fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result { - let (blockhash, chan_manager) = <(BlockHash, ChannelManager)>::read(reader, args)?; + fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { + let (blockhash, chan_manager) = <(BlockHash, ChannelManager)>::read(reader, args)?; Ok((blockhash, Arc::new(chan_manager))) } } -impl<'a, ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> - ReadableArgs> for (BlockHash, ChannelManager) - where M::Target: chain::Watch, +impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> + ReadableArgs> for (BlockHash, ChannelManager) + where M::Target: chain::Watch, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { - fn read(reader: &mut R, mut args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result { + fn read(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { let _ver: u8 = Readable::read(reader)?; let min_ver: u8 = Readable::read(reader)?; if min_ver > SERIALIZATION_VERSION { @@ -4026,7 +4026,7 @@ impl<'a, ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Der let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128)); let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128)); for _ in 0..channel_count { - let mut channel: Channel = Channel::read(reader, &args.keys_manager)?; + let mut channel: Channel = Channel::read(reader, &args.keys_manager)?; if channel.last_block_connected != Default::default() && channel.last_block_connected != last_block_hash { return Err(DecodeError::InvalidValue); } diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index a7394a84b..19802e431 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -19,7 +19,7 @@ use routing::network_graph::{NetGraphMsgHandler, NetworkGraph}; use ln::features::InitFeatures; use ln::msgs; use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler}; -use util::enforcing_trait_impls::EnforcingChannelKeys; +use util::enforcing_trait_impls::EnforcingSigner; use util::test_utils; use util::test_utils::TestChainMonitor; use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider}; @@ -114,7 +114,7 @@ pub struct Node<'a, 'b: 'a, 'c: 'b> { pub tx_broadcaster: &'c test_utils::TestBroadcaster, pub chain_monitor: &'b test_utils::TestChainMonitor<'c>, pub keys_manager: &'b test_utils::TestKeysInterface, - pub node: &'a ChannelManager, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>, + pub node: &'a ChannelManager, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>, pub net_graph_msg_handler: NetGraphMsgHandler<&'c test_utils::TestChainSource, &'c test_utils::TestLogger>, pub node_seed: [u8; 32], pub network_payment_count: Rc>, @@ -172,7 +172,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { for (_, old_monitor) in old_monitors.iter() { let mut w = test_utils::TestVecWriter(Vec::new()); old_monitor.write(&mut w).unwrap(); - let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor)>::read( + let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap(); deserialized_monitors.push(deserialized_monitor); } @@ -188,7 +188,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mut w = test_utils::TestVecWriter(Vec::new()); self.node.write(&mut w).unwrap(); - <(BlockHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager: self.keys_manager, fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: 253 }, @@ -1154,7 +1154,7 @@ pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec(node_count: usize, cfgs: &'a Vec>, node_config: &[Option]) -> Vec, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> { +pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec>, node_config: &[Option]) -> Vec, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> { let mut chanmgrs = Vec::new(); for i in 0..node_count { let mut default_config = UserConfig::default(); @@ -1168,7 +1168,7 @@ pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec chanmgrs } -pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec>, chan_mgrs: &'a Vec, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec> { +pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec>, chan_mgrs: &'a Vec, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec> { let mut nodes = Vec::new(); let chan_count = Rc::new(RefCell::new(0)); let payment_count = Rc::new(RefCell::new(0)); diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index f49112083..bfab34511 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -15,7 +15,7 @@ use chain::Watch; use chain::channelmonitor; use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY}; use chain::transaction::OutPoint; -use chain::keysinterface::{ChannelKeys, KeysInterface}; +use chain::keysinterface::{Sign, KeysInterface}; 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::channel::{Channel, ChannelError}; @@ -24,7 +24,7 @@ use routing::router::{Route, RouteHop, get_route}; use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; use ln::msgs; use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction}; -use util::enforcing_trait_impls::EnforcingChannelKeys; +use util::enforcing_trait_impls::EnforcingSigner; use util::{byte_utils, test_utils}; use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider}; use util::errors::APIError; @@ -67,7 +67,7 @@ fn test_insane_channel_opens() { // Instantiate channel parameters where we push the maximum msats given our // funding satoshis let channel_value_sat = 31337; // same as funding satoshis - let channel_reserve_satoshis = Channel::::get_holder_selected_channel_reserve_satoshis(channel_value_sat); + let channel_reserve_satoshis = Channel::::get_holder_selected_channel_reserve_satoshis(channel_value_sat); let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000; // Have node0 initiate a channel to node1 with aforementioned parameters @@ -1610,7 +1610,7 @@ fn test_fee_spike_violation_fails_htlc() { const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1; - // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys + // Get the EnforcingSigner for each channel, which will be used to (1) get the keys // needed to sign the new commitment tx and (2) sign the new commitment tx. let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = { let chan_lock = nodes[0].node.channel_state.lock().unwrap(); @@ -4304,7 +4304,7 @@ fn test_no_txn_manager_serialize_deserialize() { let fee_estimator: test_utils::TestFeeEstimator; let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known()); @@ -4322,7 +4322,7 @@ fn test_no_txn_manager_serialize_deserialize() { new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager); nodes[0].chain_monitor = &new_chain_monitor; let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..]; - let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor)>::read( + let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor)>::read( &mut chan_0_monitor_read, keys_manager).unwrap(); assert!(chan_0_monitor_read.is_empty()); @@ -4331,7 +4331,7 @@ fn test_no_txn_manager_serialize_deserialize() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: &fee_estimator, @@ -4380,7 +4380,7 @@ fn test_manager_serialize_deserialize_events() { let persister: test_utils::TestPersister; let logger: test_utils::TestLogger; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe @@ -4431,7 +4431,7 @@ fn test_manager_serialize_deserialize_events() { new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager); nodes[0].chain_monitor = &new_chain_monitor; let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..]; - let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor)>::read( + let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor)>::read( &mut chan_0_monitor_read, keys_manager).unwrap(); assert!(chan_0_monitor_read.is_empty()); @@ -4440,7 +4440,7 @@ fn test_manager_serialize_deserialize_events() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: &fee_estimator, @@ -4503,7 +4503,7 @@ fn test_simple_manager_serialize_deserialize() { let fee_estimator: test_utils::TestFeeEstimator; let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()); @@ -4523,7 +4523,7 @@ fn test_simple_manager_serialize_deserialize() { new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager); nodes[0].chain_monitor = &new_chain_monitor; let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..]; - let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor)>::read( + let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor)>::read( &mut chan_0_monitor_read, keys_manager).unwrap(); assert!(chan_0_monitor_read.is_empty()); @@ -4531,7 +4531,7 @@ fn test_simple_manager_serialize_deserialize() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: &fee_estimator, @@ -4564,7 +4564,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let fee_estimator: test_utils::TestFeeEstimator; let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager; let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()); create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()); @@ -4607,7 +4607,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut node_0_stale_monitors = Vec::new(); for serialized in node_0_stale_monitors_serialized.iter() { let mut read = &serialized[..]; - let (_, monitor) = <(BlockHash, ChannelMonitor)>::read(&mut read, keys_manager).unwrap(); + let (_, monitor) = <(BlockHash, ChannelMonitor)>::read(&mut read, keys_manager).unwrap(); assert!(read.is_empty()); node_0_stale_monitors.push(monitor); } @@ -4615,14 +4615,14 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut node_0_monitors = Vec::new(); for serialized in node_0_monitors_serialized.iter() { let mut read = &serialized[..]; - let (_, monitor) = <(BlockHash, ChannelMonitor)>::read(&mut read, keys_manager).unwrap(); + let (_, monitor) = <(BlockHash, ChannelMonitor)>::read(&mut read, keys_manager).unwrap(); assert!(read.is_empty()); node_0_monitors.push(monitor); } let mut nodes_0_read = &nodes_0_serialized[..]; if let Err(msgs::DecodeError::InvalidValue) = - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: &fee_estimator, @@ -4636,7 +4636,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut nodes_0_read = &nodes_0_serialized[..]; let (_, nodes_0_deserialized_tmp) = - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: &fee_estimator, @@ -7358,7 +7358,7 @@ fn test_data_loss_protect() { // Restore node A from previous state logger = test_utils::TestLogger::with_id(format!("node {}", 0)); - let mut chain_monitor = <(BlockHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1; + let mut chain_monitor = <(BlockHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1; chain_source = test_utils::TestChainSource::new(Network::Testnet); tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())}; fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 }; @@ -7367,7 +7367,7 @@ fn test_data_loss_protect() { node_state_0 = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor); - <(BlockHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs { keys_manager: keys_manager, fee_estimator: &fee_estimator, chain_monitor: &monitor, @@ -8026,7 +8026,7 @@ fn test_counterparty_raa_skip_no_crash() { // commitment transaction, we would have happily carried on and provided them the next // commitment transaction based on one RAA forward. This would probably eventually have led to // channel closure, but it would not have resulted in funds loss. Still, our - // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we + // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we // check simply that the channel is closed in response to such an RAA, but don't check whether // we decide to punish our counterparty for revoking their funds (as we don't currently // implement that). @@ -8233,7 +8233,7 @@ fn test_update_err_monitor_lockdown() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).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, &persister, &node_cfgs[0].keys_manager); @@ -8292,7 +8292,7 @@ fn test_concurrent_monitor_claim() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).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, &persister, &node_cfgs[0].keys_manager); @@ -8318,7 +8318,7 @@ fn test_concurrent_monitor_claim() { let monitor = monitors.get(&outpoint).unwrap(); let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).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, &persister, &node_cfgs[0].keys_manager); diff --git a/lightning/src/ln/onchaintx.rs b/lightning/src/ln/onchaintx.rs index 2d7d417d2..9d5d2e00b 100644 --- a/lightning/src/ln/onchaintx.rs +++ b/lightning/src/ln/onchaintx.rs @@ -27,7 +27,7 @@ use ln::chan_utils; use ln::chan_utils::{TxCreationKeys, ChannelTransactionParameters, HolderCommitmentTransaction}; use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT}; use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest}; -use chain::keysinterface::{ChannelKeys, KeysInterface}; +use chain::keysinterface::{Sign, KeysInterface}; use util::logger::Logger; use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter}; use util::byte_utils; @@ -240,7 +240,7 @@ impl Writeable for Option>> { /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and /// do RBF bumping if possible. -pub struct OnchainTxHandler { +pub struct OnchainTxHandler { destination_script: Script, holder_commitment: HolderCommitmentTransaction, // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment @@ -287,7 +287,7 @@ pub struct OnchainTxHandler { secp_ctx: Secp256k1, } -impl OnchainTxHandler { +impl OnchainTxHandler { pub(crate) fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { self.destination_script.write(writer)?; self.holder_commitment.write(writer)?; @@ -340,7 +340,7 @@ impl OnchainTxHandler { } } -impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { +impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { fn read(reader: &mut R, keys_manager: &'a K) -> Result { let destination_script = Readable::read(reader)?; @@ -423,7 +423,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler OnchainTxHandler { +impl OnchainTxHandler { pub(crate) fn new(destination_script: Script, keys: ChanSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction) -> Self { let key_storage = keys; diff --git a/lightning/src/util/enforcing_trait_impls.rs b/lightning/src/util/enforcing_trait_impls.rs index f5d531ca3..2e9e793bd 100644 --- a/lightning/src/util/enforcing_trait_impls.rs +++ b/lightning/src/util/enforcing_trait_impls.rs @@ -9,7 +9,7 @@ use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction}; use ln::{chan_utils, msgs}; -use chain::keysinterface::{ChannelKeys, InMemoryChannelKeys}; +use chain::keysinterface::{Sign, InMemorySigner}; use std::cmp; use std::sync::{Mutex, Arc}; @@ -27,7 +27,7 @@ use ln::msgs::DecodeError; /// Initial value for revoked commitment downward counter pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48; -/// An implementation of ChannelKeys that enforces some policy checks. The current checks +/// An implementation of Sign that enforces some policy checks. The current checks /// are an incomplete set. They include: /// /// - When signing, the holder transaction has not been revoked @@ -39,8 +39,8 @@ pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48; /// Eventually we will probably want to expose a variant of this which would essentially /// be what you'd want to run on a hardware wallet. #[derive(Clone)] -pub struct EnforcingChannelKeys { - pub inner: InMemoryChannelKeys, +pub struct EnforcingSigner { + pub inner: InMemorySigner, /// The last counterparty commitment number we signed, backwards counting pub last_commitment_number: Arc>>, /// The last holder commitment number we revoked, backwards counting @@ -48,9 +48,9 @@ pub struct EnforcingChannelKeys { pub disable_revocation_policy_check: bool, } -impl EnforcingChannelKeys { - /// Construct an EnforcingChannelKeys - pub fn new(inner: InMemoryChannelKeys) -> Self { +impl EnforcingSigner { + /// Construct an EnforcingSigner + pub fn new(inner: InMemorySigner) -> Self { Self { inner, last_commitment_number: Arc::new(Mutex::new(None)), @@ -59,12 +59,12 @@ impl EnforcingChannelKeys { } } - /// Construct an EnforcingChannelKeys with externally managed storage + /// Construct an EnforcingSigner with externally managed storage /// /// Since there are multiple copies of this struct for each channel, some coordination is needed /// so that all copies are aware of revocations. A pointer to this state is provided here, usually /// by an implementation of KeysInterface. - pub fn new_with_revoked(inner: InMemoryChannelKeys, revoked_commitment: Arc>, disable_revocation_policy_check: bool) -> Self { + pub fn new_with_revoked(inner: InMemorySigner, revoked_commitment: Arc>, disable_revocation_policy_check: bool) -> Self { Self { inner, last_commitment_number: Arc::new(Mutex::new(None)), @@ -74,7 +74,7 @@ impl EnforcingChannelKeys { } } -impl ChannelKeys for EnforcingChannelKeys { +impl Sign for EnforcingSigner { fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1) -> PublicKey { self.inner.get_per_commitment_point(idx, secp_ctx) } @@ -162,7 +162,7 @@ impl ChannelKeys for EnforcingChannelKeys { } -impl Writeable for EnforcingChannelKeys { +impl Writeable for EnforcingSigner { fn write(&self, writer: &mut W) -> Result<(), Error> { self.inner.write(writer)?; let last = *self.last_commitment_number.lock().unwrap(); @@ -171,11 +171,11 @@ impl Writeable for EnforcingChannelKeys { } } -impl Readable for EnforcingChannelKeys { +impl Readable for EnforcingSigner { fn read(reader: &mut R) -> Result { let inner = Readable::read(reader)?; let last_commitment_number = Readable::read(reader)?; - Ok(EnforcingChannelKeys { + Ok(EnforcingSigner { inner, last_commitment_number: Arc::new(Mutex::new(last_commitment_number)), revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)), @@ -184,7 +184,7 @@ impl Readable for EnforcingChannelKeys { } } -impl EnforcingChannelKeys { +impl EnforcingSigner { fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1) -> TrustedCommitmentTransaction<'a> { commitment_tx.verify(&self.inner.get_channel_parameters().as_counterparty_broadcastable(), self.inner.counterparty_pubkeys(), self.inner.pubkeys(), secp_ctx) diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 74cc13cc0..4b4012343 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -18,7 +18,7 @@ use chain::keysinterface; use ln::features::{ChannelFeatures, InitFeatures}; use ln::msgs; use ln::msgs::OptionalField; -use util::enforcing_trait_impls::{EnforcingChannelKeys, INITIAL_REVOKED_COMMITMENT_NUMBER}; +use util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER}; use util::events; use util::logger::{Logger, Level, Record}; use util::ser::{Readable, ReadableArgs, Writer, Writeable}; @@ -39,7 +39,7 @@ use std::sync::{Mutex, Arc}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::{cmp, mem}; use std::collections::{HashMap, HashSet}; -use chain::keysinterface::InMemoryChannelKeys; +use chain::keysinterface::InMemorySigner; pub struct TestVecWriter(pub Vec); impl Writer for TestVecWriter { @@ -63,23 +63,23 @@ impl chaininterface::FeeEstimator for TestFeeEstimator { pub struct OnlyReadsKeysInterface {} impl keysinterface::KeysInterface for OnlyReadsKeysInterface { - type ChanKeySigner = EnforcingChannelKeys; + type Signer = EnforcingSigner; fn get_node_secret(&self) -> SecretKey { unreachable!(); } fn get_destination_script(&self) -> Script { unreachable!(); } fn get_shutdown_pubkey(&self) -> PublicKey { unreachable!(); } - fn get_channel_keys(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingChannelKeys { unreachable!(); } + fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); } fn get_secure_random_bytes(&self) -> [u8; 32] { unreachable!(); } - fn read_chan_signer(&self, reader: &[u8]) -> Result { - EnforcingChannelKeys::read(&mut std::io::Cursor::new(reader)) + fn read_chan_signer(&self, reader: &[u8]) -> Result { + EnforcingSigner::read(&mut std::io::Cursor::new(reader)) } } pub struct TestChainMonitor<'a> { - pub added_monitors: Mutex)>>, + pub added_monitors: Mutex)>>, pub latest_monitor_update_id: Mutex>, - pub chain_monitor: chainmonitor::ChainMonitor>, + pub chain_monitor: chainmonitor::ChainMonitor>, pub keys_manager: &'a TestKeysInterface, pub update_ret: Mutex>>, // If this is set to Some(), after the next return, we'll always return this until update_ret @@ -87,7 +87,7 @@ pub struct TestChainMonitor<'a> { 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, persister: &'a channelmonitor::Persist, keys_manager: &'a TestKeysInterface) -> Self { + pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a channelmonitor::Persist, keys_manager: &'a TestKeysInterface) -> Self { Self { added_monitors: Mutex::new(Vec::new()), latest_monitor_update_id: Mutex::new(HashMap::new()), @@ -99,14 +99,14 @@ impl<'a> TestChainMonitor<'a> { } } impl<'a> chain::Watch for TestChainMonitor<'a> { - type Keys = EnforcingChannelKeys; + type ChanSigner = EnforcingSigner; - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::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(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), self.keys_manager).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())); @@ -139,7 +139,7 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { let monitor = monitors.get(&funding_txo).unwrap(); w.0.clear(); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1; assert!(new_monitor == *monitor); self.added_monitors.lock().unwrap().push((funding_txo, new_monitor)); @@ -174,12 +174,12 @@ impl TestPersister { *self.update_ret.lock().unwrap() = ret; } } -impl channelmonitor::Persist for TestPersister { - fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { +impl channelmonitor::Persist for TestPersister { + fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { self.update_ret.lock().unwrap().clone() } - fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { self.update_ret.lock().unwrap().clone() } } @@ -427,15 +427,15 @@ pub struct TestKeysInterface { } impl keysinterface::KeysInterface for TestKeysInterface { - type ChanKeySigner = EnforcingChannelKeys; + type Signer = EnforcingSigner; fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() } fn get_destination_script(&self) -> Script { self.backing.get_destination_script() } fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() } - fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys { - let keys = self.backing.get_channel_keys(inbound, channel_value_satoshis); + fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner { + let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis); let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed); - EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check) + EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check) } fn get_secure_random_bytes(&self) -> [u8; 32] { @@ -453,15 +453,15 @@ impl keysinterface::KeysInterface for TestKeysInterface { self.backing.get_secure_random_bytes() } - fn read_chan_signer(&self, buffer: &[u8]) -> Result { + fn read_chan_signer(&self, buffer: &[u8]) -> Result { let mut reader = std::io::Cursor::new(buffer); - let inner: InMemoryChannelKeys = Readable::read(&mut reader)?; + let inner: InMemorySigner = Readable::read(&mut reader)?; let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed); let last_commitment_number = Readable::read(&mut reader)?; - Ok(EnforcingChannelKeys { + Ok(EnforcingSigner { inner, last_commitment_number: Arc::new(Mutex::new(last_commitment_number)), revoked_commitment, @@ -482,10 +482,10 @@ impl TestKeysInterface { revoked_commitments: Mutex::new(HashMap::new()), } } - pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingChannelKeys { + pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner { let keys = self.backing.derive_channel_keys(channel_value_satoshis, id); let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed); - EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check) + EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check) } fn make_revoked_commitment_cell(&self, commitment_seed: [u8; 32]) -> Arc> {