From b0ed084e21f64f917c8fe986ace7bd9564b52615 Mon Sep 17 00:00:00 2001 From: Valentine Wallace Date: Mon, 6 Jan 2020 16:27:08 -0500 Subject: [PATCH] rustfmt: apply 'visual' indent style config change --- fuzz/src/chanmon_consistency.rs | 623 +- fuzz/src/full_stack.rs | 411 +- fuzz/src/router.rs | 68 +- fuzz/src/utils/test_logger.rs | 20 +- lightning-net-tokio/src/lib.rs | 229 +- lightning/src/chain/chaininterface.rs | 67 +- lightning/src/chain/keysinterface.rs | 237 +- lightning/src/chain/transaction.rs | 24 +- lightning/src/ln/chan_utils.rs | 349 +- lightning/src/ln/chanmon_update_fail_tests.rs | 1497 ++- lightning/src/ln/channel.rs | 3214 +++---- lightning/src/ln/channelmanager.rs | 1986 ++-- lightning/src/ln/channelmonitor.rs | 2624 +++--- lightning/src/ln/functional_test_utils.rs | 827 +- lightning/src/ln/functional_tests.rs | 8229 ++++++++--------- lightning/src/ln/msgs.rs | 1004 +- lightning/src/ln/onion_utils.rs | 441 +- lightning/src/ln/peer_channel_encryptor.rs | 413 +- lightning/src/ln/peer_handler.rs | 629 +- lightning/src/ln/router.rs | 1161 ++- lightning/src/util/chacha20.rs | 406 +- lightning/src/util/chacha20poly1305rfc.rs | 12 +- lightning/src/util/config.rs | 44 +- lightning/src/util/enforcing_trait_impls.rs | 93 +- lightning/src/util/logger.rs | 12 +- lightning/src/util/macro_logger.rs | 26 +- lightning/src/util/poly1305.rs | 70 +- lightning/src/util/ser.rs | 27 +- lightning/src/util/test_utils.rs | 157 +- lightning/src/util/transaction_utils.rs | 45 +- 30 files changed, 11266 insertions(+), 13679 deletions(-) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index eeceececefa..05e0d447527 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -80,28 +80,29 @@ pub struct TestChannelMonitor { pub should_update_manager: atomic::AtomicBool, } impl TestChannelMonitor { - pub fn new( - chain_monitor: Arc, - broadcaster: Arc, - logger: Arc, - feeest: Arc, - ) -> Self { - Self { - simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, feeest), - update_ret: Mutex::new(Ok(())), - latest_good_update: Mutex::new(HashMap::new()), - latest_update_good: Mutex::new(HashMap::new()), - latest_updates_good_at_last_ser: Mutex::new(HashMap::new()), - should_update_manager: atomic::AtomicBool::new(false), - } + pub fn new(chain_monitor: Arc, + broadcaster: Arc, + logger: Arc, + feeest: Arc) + -> Self { + Self { simple_monitor: channelmonitor::SimpleManyChannelMonitor::new( + chain_monitor, + broadcaster, + logger, + feeest, + ), + update_ret: Mutex::new(Ok(())), + latest_good_update: Mutex::new(HashMap::new()), + latest_update_good: Mutex::new(HashMap::new()), + latest_updates_good_at_last_ser: Mutex::new(HashMap::new()), + should_update_manager: atomic::AtomicBool::new(false) } } } impl channelmonitor::ManyChannelMonitor for TestChannelMonitor { - fn add_update_monitor( - &self, - funding_txo: OutPoint, - monitor: channelmonitor::ChannelMonitor, - ) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn add_update_monitor(&self, + funding_txo: OutPoint, + monitor: channelmonitor::ChannelMonitor) + -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { let ret = self.update_ret.lock().unwrap().clone(); if let Ok(()) = ret { let mut ser = VecWriter(Vec::new()); @@ -174,8 +175,7 @@ impl KeysInterface for KeyProvider { 0, 1, self.node_id, - ]) - .unwrap() + ]).unwrap() } fn get_destination_script(&self) -> Script { @@ -213,317 +213,265 @@ impl KeysInterface for KeyProvider { 0, 2, self.node_id, - ]) - .unwrap(); + ]).unwrap(); let our_channel_monitor_claim_key_hash = Hash160::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize()); - Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&our_channel_monitor_claim_key_hash[..]) - .into_script() + Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&our_channel_monitor_claim_key_hash[..]) + .into_script() } fn get_shutdown_pubkey(&self) -> PublicKey { let secp_ctx = Secp256k1::signing_only(); 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(), + &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) -> EnforcingChannelKeys { - EnforcingChannelKeys::new(InMemoryChannelKeys { - funding_key: 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(), - revocation_base_key: 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(), - payment_base_key: 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, - 6, - self.node_id, - ]) - .unwrap(), - delayed_payment_base_key: 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, - self.node_id, - ]) - .unwrap(), - htlc_base_key: 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, - self.node_id, - ]) - .unwrap(), - commitment_seed: [ - 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, - 9, - self.node_id, - ], - }) + EnforcingChannelKeys::new(InMemoryChannelKeys { funding_key: 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(), + revocation_base_key: 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(), + payment_base_key: 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, + 6, + self.node_id, + ]).unwrap(), + delayed_payment_base_key: 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, + self.node_id, + ]).unwrap(), + htlc_base_key: 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, + self.node_id, + ]).unwrap(), + commitment_seed: [ + 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, + 9, + self.node_id, + ], }) } fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) { let id = self.session_id.fetch_add(1, atomic::Ordering::Relaxed); - ( - SecretKey::from_slice(&[ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - id, - 10, - self.node_id, - ]) - .unwrap(), - [0; 32], - ) - } - - fn get_channel_id(&self) -> [u8; 32] { - let id = self.channel_id.fetch_add(1, atomic::Ordering::Relaxed); - [ + (SecretKey::from_slice(&[ 0, 0, 0, @@ -554,8 +502,47 @@ impl KeysInterface for KeyProvider { 0, 0, id, - 11, + 10, self.node_id, + ]).unwrap(), + [0; 32]) + } + + fn get_channel_id(&self) -> [u8; 32] { + let id = self.channel_id.fetch_add(1, atomic::Ordering::Relaxed); + [ + 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, ] } } diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index 01a972374f9..8bf11ecf92a 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -148,24 +148,21 @@ struct MoneyLossDetector<'a> { blocks_connected: u32, } impl<'a> MoneyLossDetector<'a> { - pub fn new( - peers: &'a RefCell<[bool; 256]>, - manager: Arc>, - monitor: Arc>, - handler: PeerManager>, - ) -> Self { - MoneyLossDetector { - manager, - monitor, - handler, - peers, - funding_txn: Vec::new(), - txids_confirmed: HashMap::new(), - header_hashes: vec![Default::default()], - height: 0, - max_height: 0, - blocks_connected: 0, - } + pub fn new(peers: &'a RefCell<[bool; 256]>, + manager: Arc>, + monitor: Arc>, + handler: PeerManager>) + -> Self { + MoneyLossDetector { manager, + monitor, + handler, + peers, + funding_txn: Vec::new(), + txids_confirmed: HashMap::new(), + header_hashes: vec![Default::default()], + height: 0, + max_height: 0, + blocks_connected: 0 } } fn connect_block(&mut self, all_txn: &[Transaction]) { @@ -183,18 +180,16 @@ impl<'a> MoneyLossDetector<'a> { } } - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: self.header_hashes[self.height], - merkle_root: Default::default(), - time: self.blocks_connected, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: self.header_hashes[self.height], + merkle_root: Default::default(), + time: self.blocks_connected, + bits: 42, + nonce: 42 }; self.height += 1; self.blocks_connected += 1; self.manager - .block_connected(&header, self.height as u32, &txn[..], &txn_idxs[..]); + .block_connected(&header, self.height as u32, &txn[..], &txn_idxs[..]); (*self.monitor).block_connected(&header, self.height as u32, &txn[..], &txn_idxs[..]); if self.header_hashes.len() > self.height { self.header_hashes[self.height] = header.bitcoin_hash(); @@ -208,14 +203,12 @@ impl<'a> MoneyLossDetector<'a> { fn disconnect_block(&mut self) { if self.height > 0 && (self.max_height < 6 || self.height >= self.max_height - 6) { self.height -= 1; - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: self.header_hashes[self.height], - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: self.header_hashes[self.height], + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; self.manager.block_disconnected(&header, self.height as u32); self.monitor.block_disconnected(&header, self.height as u32); let removal_height = self.height; @@ -230,10 +223,8 @@ impl<'a> Drop for MoneyLossDetector<'a> { // Disconnect all peers for (idx, peer) in self.peers.borrow().iter().enumerate() { if *peer { - self.handler.disconnect_event(&Peer { - id: idx as u8, - peers_connected: &self.peers, - }); + self.handler.disconnect_event(&Peer { id: idx as u8, + peers_connected: &self.peers, }); } } @@ -261,136 +252,117 @@ impl KeysInterface for KeyProvider { let our_channel_monitor_claim_key_hash = ::hash( &PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize(), ); - Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&our_channel_monitor_claim_key_hash[..]) - .into_script() + Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&our_channel_monitor_claim_key_hash[..]) + .into_script() } fn get_shutdown_pubkey(&self) -> PublicKey { let secp_ctx = Secp256k1::signing_only(); 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(), + &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) -> EnforcingChannelKeys { let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8; EnforcingChannelKeys::new(if inbound { - InMemoryChannelKeys { - funding_key: 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(), - revocation_base_key: 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(), - payment_base_key: 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, ctr, - ]) - .unwrap(), - delayed_payment_base_key: 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, ctr, - ]) - .unwrap(), - htlc_base_key: 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, ctr, - ]) - .unwrap(), - commitment_seed: [ - 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, 6, ctr, - ], - } + InMemoryChannelKeys { funding_key: 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(), + revocation_base_key: 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(), + payment_base_key: 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, ctr, + ]).unwrap(), + delayed_payment_base_key: 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, ctr, + ]).unwrap(), + htlc_base_key: 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, ctr, + ]).unwrap(), + commitment_seed: [ + 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, 6, ctr, + ] } } else { - InMemoryChannelKeys { - funding_key: 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(), - revocation_base_key: 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(), - payment_base_key: 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, 9, ctr, - ]) - .unwrap(), - delayed_payment_base_key: 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, 10, ctr, - ]) - .unwrap(), - htlc_base_key: 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, 11, ctr, - ]) - .unwrap(), - commitment_seed: [ - 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, 12, ctr, - ], - } + InMemoryChannelKeys { funding_key: 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(), + revocation_base_key: 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(), + payment_base_key: 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, 9, ctr, + ]).unwrap(), + delayed_payment_base_key: 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, 10, ctr, + ]).unwrap(), + htlc_base_key: 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, 11, ctr, + ]).unwrap(), + commitment_seed: [ + 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, 12, ctr, + ] } }) } fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) { let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8; - ( - 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, 13, ctr, - ]) - .unwrap(), - [0; 32], - ) + (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, 13, ctr, + ]).unwrap(), + [0; 32]) } fn get_channel_id(&self) -> [u8; 32] { let ctr = self.counter.fetch_add(1, Ordering::Relaxed); [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - (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, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + (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, ] } } #[inline] pub fn do_test(data: &[u8], logger: &Arc) { - let input = Arc::new(InputData { - data: data.to_vec(), - read_pos: AtomicUsize::new(0), - }); + let input = Arc::new(InputData { data: data.to_vec(), + read_pos: AtomicUsize::new(0) }); let fee_est = Arc::new(FuzzEstimator { input: input.clone() }); macro_rules! get_slice { @@ -419,31 +391,28 @@ pub fn do_test(data: &[u8], logger: &Arc) { let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger))); let broadcast = Arc::new(TestBroadcaster {}); let monitor = channelmonitor::SimpleManyChannelMonitor::new( - watch.clone(), - broadcast.clone(), - Arc::clone(&logger), - fee_est.clone(), + watch.clone(), + broadcast.clone(), + Arc::clone(&logger), + fee_est.clone(), ); - let keys_manager = Arc::new(KeyProvider { - node_secret: our_network_key.clone(), - counter: AtomicU64::new(0), - }); + let keys_manager = Arc::new(KeyProvider { node_secret: our_network_key.clone(), + counter: AtomicU64::new(0) }); let mut config = UserConfig::default(); config.channel_options.fee_proportional_millionths = slice_to_be32(get_slice!(4)); config.channel_options.announced_channel = get_slice!(1)[0] != 0; config.peer_channel_config_limits.min_dust_limit_satoshis = 0; let channelmanager = ChannelManager::new( - Network::Bitcoin, - fee_est.clone(), - monitor.clone(), - broadcast.clone(), - Arc::clone(&logger), - keys_manager.clone(), - config, - 0, - ) - .unwrap(); + Network::Bitcoin, + fee_est.clone(), + monitor.clone(), + broadcast.clone(), + Arc::clone(&logger), + keys_manager.clone(), + config, + 0, + ).unwrap(); let router = Arc::new(Router::new( PublicKey::from_secret_key(&Secp256k1::signing_only(), &keys_manager.get_node_secret()), watch.clone(), @@ -452,20 +421,18 @@ pub fn do_test(data: &[u8], logger: &Arc) { let peers = RefCell::new([false; 256]); let mut loss_detector = MoneyLossDetector::new( - &peers, - channelmanager.clone(), - monitor.clone(), - PeerManager::new( - MessageHandler { - chan_handler: channelmanager.clone(), - route_handler: router.clone(), - }, - our_network_key, - &[ - 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, 15, 0, - ], - Arc::clone(&logger), - ), + &peers, + channelmanager.clone(), + monitor.clone(), + PeerManager::new( + MessageHandler { chan_handler: channelmanager.clone(), + route_handler: router.clone(), }, + our_network_key, + &[ + 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, 15, 0, + ], + Arc::clone(&logger), + ), ); let mut should_forward = false; @@ -488,16 +455,13 @@ pub fn do_test(data: &[u8], logger: &Arc) { if new_id == 0 { return; } - loss_detector - .handler - .new_outbound_connection( - get_pubkey!(), - Peer { - id: (new_id - 1) as u8, - peers_connected: &peers, - }, - ) - .unwrap(); + loss_detector.handler + .new_outbound_connection( + get_pubkey!(), + Peer { id: (new_id - 1) as u8, + peers_connected: &peers, }, + ) + .unwrap(); peers.borrow_mut()[new_id - 1] = true; }, 1 => { @@ -511,13 +475,10 @@ pub fn do_test(data: &[u8], logger: &Arc) { if new_id == 0 { return; } - loss_detector - .handler - .new_inbound_connection(Peer { - id: (new_id - 1) as u8, - peers_connected: &peers, - }) - .unwrap(); + loss_detector.handler + .new_inbound_connection(Peer { id: (new_id - 1) as u8, + peers_connected: &peers, }) + .unwrap(); peers.borrow_mut()[new_id - 1] = true; }, 2 => { @@ -525,10 +486,8 @@ pub fn do_test(data: &[u8], logger: &Arc) { if !peers.borrow()[peer_id as usize] { return; } - loss_detector.handler.disconnect_event(&Peer { - id: peer_id, - peers_connected: &peers, - }); + loss_detector.handler.disconnect_event(&Peer { id: peer_id, + peers_connected: &peers, }); peers.borrow_mut()[peer_id as usize] = false; }, 3 => { @@ -537,11 +496,9 @@ pub fn do_test(data: &[u8], logger: &Arc) { return; } match loss_detector.handler.read_event( - &mut Peer { - id: peer_id, - peers_connected: &peers, - }, - get_slice!(get_slice!(1)[0]).to_vec(), + &mut Peer { id: peer_id, + peers_connected: &peers, }, + get_slice!(get_slice!(1)[0]).to_vec(), ) { Ok(res) => assert!(!res), Err(_) => { @@ -574,9 +531,8 @@ pub fn do_test(data: &[u8], logger: &Arc) { let their_key = get_pubkey!(); let chan_value = slice_to_be24(get_slice!(3)) as u64; let push_msat_value = slice_to_be24(get_slice!(3)) as u64; - if channelmanager - .create_channel(their_key, chan_value, push_msat_value, 0) - .is_err() + if channelmanager.create_channel(their_key, chan_value, push_msat_value, 0) + .is_err() { return; } @@ -620,15 +576,11 @@ pub fn do_test(data: &[u8], logger: &Arc) { }, 10 => { 'outer_loop: for funding_generation in pending_funding_generation.drain(..) { - let mut tx = Transaction { - version: 0, - lock_time: 0, - input: Vec::new(), - output: vec![TxOut { - value: funding_generation.1, - script_pubkey: funding_generation.2, - }], - }; + let mut tx = Transaction { version: 0, + lock_time: 0, + input: Vec::new(), + output: vec![TxOut { value: funding_generation.1, + script_pubkey: funding_generation.2, }] }; let funding_output = 'search_loop: loop { let funding_txid = tx.txid(); if let None = loss_detector.txids_confirmed.get(&funding_txid) { @@ -691,12 +643,10 @@ pub fn do_test(data: &[u8], logger: &Arc) { loss_detector.handler.process_events(); for event in loss_detector.manager.get_and_clear_pending_events() { match event { - Event::FundingGenerationReady { - temporary_channel_id, - channel_value_satoshis, - output_script, - .. - } => { + Event::FundingGenerationReady { temporary_channel_id, + channel_value_satoshis, + output_script, + .. } => { pending_funding_generation.push((temporary_channel_id, channel_value_satoshis, output_script)); }, Event::FundingBroadcastSafe { funding_txo, .. } => { @@ -742,19 +692,18 @@ mod tests { } impl Logger for TrackingLogger { fn log(&self, record: &Record) { - *self - .lines - .lock() - .unwrap() - .entry((record.module_path.to_string(), format!("{}", record.args))) - .or_insert(0) += 1; + *self.lines + .lock() + .unwrap() + .entry((record.module_path.to_string(), format!("{}", record.args))) + .or_insert(0) += 1; println!( - "{:<5} [{} : {}, {}] {}", - record.level.to_string(), - record.module_path, - record.file, - record.line, - record.args + "{:<5} [{} : {}, {}] {}", + record.level.to_string(), + record.module_path, + record.file, + record.line, + record.args ); } } @@ -1050,9 +999,7 @@ mod tests { // 07 - process the now-pending HTLC forward // - client now fails the HTLC backwards as it was unable to extract the payment preimage (CHECK 9 duplicate and CHECK 10) - let logger = Arc::new(TrackingLogger { - lines: Mutex::new(HashMap::new()), - }); + let logger = Arc::new(TrackingLogger { lines: Mutex::new(HashMap::new()) }); super::do_test(&::hex::decode("00000000000000000000000000000000000000000000000000000000000000000000000001000300000000000000000000000000000000000000000000000000000000000000000300320003000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000030012000603000000000000000000000000000000030016001000000000030000000000000000000000000000000300120141030000000000000000000000000000000300fe00207500000000000000000000000000000000000000000000000000000000000000ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679000000000000c35000000000000000000000000000000222ffffffffffffffff00000000000002220000000000000000000000fd000601e3030000000000000000000000000000000000000000000000000000000000000001030000000000000000000000000000000000000000000000000000000000000002030000000000000000000000000000000000000000000000000000000000000003030000000000000000000000000000000000000000000000000000000000000004030053030000000000000000000000000000000000000000000000000000000000000005030000000000000000000000000000000000000000000000000000000000000000010300000000000000000000000000000000fd00fd00fd0300120084030000000000000000000000000000000300940022ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb1819096793d0000000000000000000000000000000000000000000000000000000000000000005c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001030000000000000000000000000000000c005e020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020ae00000000000000000000000000000000000000000000000000000000000000000000000c00000c00000c00000c00000c00000c00000c00000c00000c00000c00000c00000c000003001200430300000000000000000000000000000003005300243d000000000000000000000000000000000000000000000000000000000000000301000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001030132000300000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003014200030200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000300000000000000000000000000000003011200060100000000000000000000000000000003011600100000000001000000000000000000000000000000050103020000000000000000000000000000000000000000000000000000000000000000c3500003e800fd00fd00fd0301120110010000000000000000000000000000000301ff00210000000000000000000000000000000000000000000000000000000000000e02000000000000001a00000000004c4b4000000000000003e800000000000003e80000000203f00005030000000000000000000000000000000000000000000000000000000000000100030000000000000000000000000000000000000000000000000000000000000200030000000000000000000000000000000000000000000000000000000000000300030000000000000000000000000000000000000000000000000000000000000400030000000000000000000000000000000000000000000000000000000000000500030000000000000000000000000000000301210000000000000000000000000000000000010000000000000000000000000000000a03011200620100000000000000000000000000000003017200233900000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100010000000000000000000000000000000b030112004301000000000000000000000000000000030153002439000000000000000000000000000000000000000000000000000000000000000301000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e80ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e000001000000000000000003e8000000010000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200640300000000000000000000000000000003007400843d000000000000000000000000000000000000000000000000000000000000004d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000703011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000f100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003020000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000030112004a0100000000000000000000000000000003015a008239000000000000000000000000000000000000000000000000000000000000000000000000000000ff008888888888888888888888888888888888888888888888888888888888880100000000000000000000000000000003011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000fd0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000000000000000000000000000000301120063010000000000000000000000000000000301730085390000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000303000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d0000000000000000000000000000000000000000000000000000000000000000000000000000010000000000003e80ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e000001000000000000000003e8000000010000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200630300000000000000000000000000000003007300853d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000303000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200640300000000000000000000000000000003007400843d00000000000000000000000000000000000000000000000000000000000000be00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030400000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000703011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000fc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003040000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000030112002c0100000000000000000000000000000003013c00833900000000000000000000000000000000000000000000000000000000000000000000000000000100000100000000000000000000000000000003011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000fb000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000001000000000000000000000000000000030112006301000000000000000000000000000000030173008539000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000030500000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000703001200630300000000000000000000000000000003007300853d0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000305000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200640300000000000000000000000000000003007400843d000000000000000000000000000000000000000000000000000000000000004f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000300000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d00000000000000000000000000000000000000000000000000000000000000000000000000000200000000000b0838ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e0000010000000000000003e800000000010000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200a4030000000000000000000000000000000300b400843d00000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001c8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f000000000000000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000003060000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000070c007d0200000001390000000000000000000000000000000000000000000000000000000000000000000000000000008002000100000000000022002090000000000000000000000000000000000000000000000000000000000000006cc10000000000001600145c000000000000000000000000000000000000000500002000fd00fd0c005e0200000001fd00000000000000000000000000000000000000000000000000000000000000000000000000000000014f00000000000000220020f6000000000000000000000000000000000000000000000000000000000000000000000000fd0c000000fd0c00000c00000c00000c000007").unwrap(), &(Arc::clone(&logger) as Arc)); let log_entries = logger.lines.lock().unwrap(); diff --git a/fuzz/src/router.rs b/fuzz/src/router.rs index 4cde114944a..ed84b1e63ce 100644 --- a/fuzz/src/router.rs +++ b/fuzz/src/router.rs @@ -79,11 +79,10 @@ impl ChainWatchInterface for DummyChainWatcher { fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec) { (Vec::new(), Vec::new()) } fn reentered(&self) -> usize { 0 } - fn get_chain_utxo( - &self, - _genesis_hash: Sha256dHash, - _unspent_tx_output_identifier: u64, - ) -> Result<(Script, u64), ChainError> { + fn get_chain_utxo(&self, + _genesis_hash: Sha256dHash, + _unspent_tx_output_identifier: u64) + -> Result<(Script, u64), ChainError> { match self.input.get_slice(2) { Some(&[0, _]) => Err(ChainError::NotSupported), Some(&[1, _]) => Err(ChainError::NotWatched), @@ -97,10 +96,8 @@ impl ChainWatchInterface for DummyChainWatcher { #[inline] pub fn do_test(data: &[u8]) { - let input = Arc::new(InputData { - data: data.to_vec(), - read_pos: AtomicUsize::new(0), - }); + let input = Arc::new(InputData { data: data.to_vec(), + read_pos: AtomicUsize::new(0) }); macro_rules! get_slice_nonadvancing { ($len: expr) => { match input.get_slice_nonadvancing($len as usize) { @@ -155,9 +152,7 @@ pub fn do_test(data: &[u8]) { } let logger: Arc = Arc::new(test_logger::TestLogger::new("".to_owned())); - let chain_monitor = Arc::new(DummyChainWatcher { - input: Arc::clone(&input), - }); + let chain_monitor = Arc::new(DummyChainWatcher { input: Arc::clone(&input) }); let our_pubkey = get_pubkey!(); let router = Router::new(our_pubkey.clone(), chain_monitor, Arc::clone(&logger)); @@ -167,7 +162,8 @@ pub fn do_test(data: &[u8]) { 0 => { let start_len = slice_to_be16(&get_slice_nonadvancing!(64 + 2)[64..64 + 2]) as usize; let addr_len = slice_to_be16( - &get_slice_nonadvancing!(64 + start_len + 2 + 74)[64 + start_len + 2 + 72..64 + start_len + 2 + 74], + &get_slice_nonadvancing!(64 + start_len + 2 + 74) + [64 + start_len + 2 + 72..64 + start_len + 2 + 74], ); if addr_len > (37 + 1) * 4 { return; @@ -207,16 +203,18 @@ pub fn do_test(data: &[u8]) { 1 => { let count = slice_to_be16(get_slice!(2)); for _ in 0..count { - first_hops_vec.push(ChannelDetails { - channel_id: [0; 32], - short_channel_id: Some(slice_to_be64(get_slice!(8))), - remote_network_id: get_pubkey!(), - channel_value_satoshis: slice_to_be64(get_slice!(8)), - user_id: 0, - inbound_capacity_msat: 0, - is_live: true, - outbound_capacity_msat: 0, - }); + first_hops_vec.push(ChannelDetails { channel_id: [0; 32], + short_channel_id: Some(slice_to_be64(get_slice!( + 8 + ))), + remote_network_id: get_pubkey!(), + channel_value_satoshis: slice_to_be64(get_slice!( + 8 + )), + user_id: 0, + inbound_capacity_msat: 0, + is_live: true, + outbound_capacity_msat: 0, }); } Some(&first_hops_vec[..]) }, @@ -226,23 +224,21 @@ pub fn do_test(data: &[u8]) { let last_hops = { let count = slice_to_be16(get_slice!(2)); for _ in 0..count { - last_hops_vec.push(RouteHint { - src_node_id: get_pubkey!(), - short_channel_id: slice_to_be64(get_slice!(8)), - fee_base_msat: slice_to_be32(get_slice!(4)), - fee_proportional_millionths: slice_to_be32(get_slice!(4)), - cltv_expiry_delta: slice_to_be16(get_slice!(2)), - htlc_minimum_msat: slice_to_be64(get_slice!(8)), - }); + last_hops_vec.push(RouteHint { src_node_id: get_pubkey!(), + short_channel_id: slice_to_be64(get_slice!(8)), + fee_base_msat: slice_to_be32(get_slice!(4)), + fee_proportional_millionths: slice_to_be32(get_slice!(4)), + cltv_expiry_delta: slice_to_be16(get_slice!(2)), + htlc_minimum_msat: slice_to_be64(get_slice!(8)), }); } &last_hops_vec[..] }; let _ = router.get_route( - &target, - first_hops, - last_hops, - slice_to_be64(get_slice!(8)), - slice_to_be32(get_slice!(4)), + &target, + first_hops, + last_hops, + slice_to_be64(get_slice!(8)), + slice_to_be32(get_slice!(4)), ); }, _ => return, diff --git a/fuzz/src/utils/test_logger.rs b/fuzz/src/utils/test_logger.rs index 44712a169b7..0a7acff4526 100644 --- a/fuzz/src/utils/test_logger.rs +++ b/fuzz/src/utils/test_logger.rs @@ -6,10 +6,8 @@ pub struct TestLogger { impl TestLogger { pub fn new(_id: String) -> TestLogger { - TestLogger { - #[cfg(test)] - id: _id, - } + TestLogger { #[cfg(test)] + id: _id } } } @@ -17,13 +15,13 @@ impl Logger for TestLogger { fn log(&self, record: &Record) { #[cfg(test)] println!( - "{:<5} {} [{} : {}, {}] {}", - record.level.to_string(), - self.id, - record.module_path, - record.file, - record.line, - record.args + "{:<5} {} [{} : {}, {}] {}", + record.level.to_string(), + self.id, + record.module_path, + record.file, + record.line, + record.args ); #[cfg(not(test))] let _ = format!("{}", record.args); diff --git a/lightning-net-tokio/src/lib.rs b/lightning-net-tokio/src/lib.rs index 69b6882a7da..f8307228d47 100644 --- a/lightning-net-tokio/src/lib.rs +++ b/lightning-net-tokio/src/lib.rs @@ -42,96 +42,90 @@ pub struct Connection { id: u64, } impl Connection { - fn schedule_read( - peer_manager: Arc>, - us: Arc>, - reader: futures::stream::SplitStream>, - ) { + fn schedule_read(peer_manager: Arc>, + us: Arc>, + reader: futures::stream::SplitStream>) { let us_ref = us.clone(); let us_close_ref = us.clone(); let peer_manager_ref = peer_manager.clone(); tokio::spawn( - reader - .for_each(move |b| { - let pending_read = b.to_vec(); - { - let mut lock = us_ref.lock().unwrap(); - assert!(lock.pending_read.is_empty()); - if lock.read_paused { - lock.pending_read = pending_read; - let (sender, blocker) = futures::sync::oneshot::channel(); - lock.read_blocker = Some(sender); - return future::Either::A(blocker.then(|_| Ok(()))); - } - } - //TODO: There's a race where we don't meet the requirements of disconnect_socket if its - //called right here, after we release the us_ref lock in the scope above, but before we - //call read_event! - match peer_manager.read_event( - &mut SocketDescriptor::new(us_ref.clone(), peer_manager.clone()), - pending_read, - ) { - Ok(pause_read) => { - if pause_read { - let mut lock = us_ref.lock().unwrap(); - lock.read_paused = true; - } - }, - Err(e) => { - us_ref.lock().unwrap().need_disconnect = false; - return future::Either::B(future::result(Err(std::io::Error::new( + reader.for_each(move |b| { + let pending_read = b.to_vec(); + { + let mut lock = us_ref.lock().unwrap(); + assert!(lock.pending_read.is_empty()); + if lock.read_paused { + lock.pending_read = pending_read; + let (sender, blocker) = futures::sync::oneshot::channel(); + lock.read_blocker = Some(sender); + return future::Either::A(blocker.then(|_| Ok(()))); + } + } + //TODO: There's a race where we don't meet the requirements of disconnect_socket if its + //called right here, after we release the us_ref lock in the scope above, but before we + //call read_event! + match peer_manager.read_event( + &mut SocketDescriptor::new( + us_ref.clone(), + peer_manager.clone(), + ), + pending_read, + ) { + Ok(pause_read) => { + if pause_read { + let mut lock = us_ref.lock().unwrap(); + lock.read_paused = true; + } + }, + Err(e) => { + us_ref.lock().unwrap().need_disconnect = false; + return future::Either::B(future::result(Err(std::io::Error::new( std::io::ErrorKind::InvalidData, e, )))); - }, - } + }, + } - if let Err(e) = us_ref.lock().unwrap().event_notify.try_send(()) { - // Ignore full errors as we just need them to poll after this point, so if the user - // hasn't received the last send yet, it doesn't matter. - assert!(e.is_full()); - } + if let Err(e) = us_ref.lock().unwrap().event_notify.try_send(()) { + // Ignore full errors as we just need them to poll after this point, so if the user + // hasn't received the last send yet, it doesn't matter. + assert!(e.is_full()); + } - future::Either::B(future::result(Ok(()))) - }) - .then(move |_| { - if us_close_ref.lock().unwrap().need_disconnect { - peer_manager_ref - .disconnect_event(&SocketDescriptor::new(us_close_ref, peer_manager_ref.clone())); - println!("Peer disconnected!"); - } else { - println!("We disconnected peer!"); - } - Ok(()) - }), + future::Either::B(future::result(Ok(()))) + }) + .then(move |_| { + if us_close_ref.lock().unwrap().need_disconnect { + peer_manager_ref.disconnect_event(&SocketDescriptor::new( + us_close_ref, + peer_manager_ref.clone(), + )); + println!("Peer disconnected!"); + } else { + println!("We disconnected peer!"); + } + Ok(()) + }), ); } fn new( event_notify: mpsc::Sender<()>, - stream: TcpStream, - ) -> ( - futures::stream::SplitStream>, - Arc>, - ) { + stream: TcpStream) + -> (futures::stream::SplitStream>, Arc>) { let (writer, reader) = tokio_codec::Framed::new(stream, tokio_codec::BytesCodec::new()).split(); let (send_sink, send_stream) = mpsc::channel(3); - tokio::spawn( - writer - .send_all(send_stream.map_err(|_| -> std::io::Error { - unreachable!(); - })) - .then(|_| future::result(Ok(()))), - ); - let us = Arc::new(Mutex::new(Self { - writer: Some(send_sink), - event_notify, - pending_read: Vec::new(), - read_blocker: None, - read_paused: false, - need_disconnect: true, - id: ID_COUNTER.fetch_add(1, Ordering::AcqRel), - })); + tokio::spawn(writer.send_all(send_stream.map_err(|_| -> std::io::Error { + unreachable!(); + })) + .then(|_| future::result(Ok(())))); + let us = Arc::new(Mutex::new(Self { writer: Some(send_sink), + event_notify, + pending_read: Vec::new(), + read_blocker: None, + read_paused: false, + need_disconnect: true, + id: ID_COUNTER.fetch_add(1, Ordering::AcqRel) })); (reader, us) } @@ -141,11 +135,9 @@ impl Connection { /// /// You should poll the Receive end of event_notify and call get_and_clear_pending_events() on /// ChannelManager and ChannelMonitor objects. - pub fn setup_inbound( - peer_manager: Arc>, - event_notify: mpsc::Sender<()>, - stream: TcpStream, - ) { + pub fn setup_inbound(peer_manager: Arc>, + event_notify: mpsc::Sender<()>, + stream: TcpStream) { let (reader, us) = Self::new(event_notify, stream); if let Ok(_) = peer_manager.new_inbound_connection(SocketDescriptor::new(us.clone(), peer_manager.clone())) { @@ -159,19 +151,17 @@ impl Connection { /// /// You should poll the Receive end of event_notify and call get_and_clear_pending_events() on /// ChannelManager and ChannelMonitor objects. - pub fn setup_outbound( - peer_manager: Arc>, - event_notify: mpsc::Sender<()>, - their_node_id: PublicKey, - stream: TcpStream, - ) { + pub fn setup_outbound(peer_manager: Arc>, + event_notify: mpsc::Sender<()>, + their_node_id: PublicKey, + stream: TcpStream) { let (reader, us) = Self::new(event_notify, stream); if let Ok(initial_send) = peer_manager.new_outbound_connection(their_node_id, SocketDescriptor::new(us.clone(), peer_manager.clone())) { if SocketDescriptor::new(us.clone(), peer_manager.clone()).send_data(&initial_send, true) - == initial_send.len() + == initial_send.len() { Self::schedule_read(peer_manager, us, reader); } else { @@ -186,25 +176,28 @@ impl Connection { /// /// You should poll the Receive end of event_notify and call get_and_clear_pending_events() on /// ChannelManager and ChannelMonitor objects. - pub fn connect_outbound( - peer_manager: Arc>, - event_notify: mpsc::Sender<()>, - their_node_id: PublicKey, - addr: SocketAddr, - ) { - let connect_timeout = Delay::new(Instant::now() + Duration::from_secs(10)) - .then(|_| future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))); + pub fn connect_outbound(peer_manager: Arc>, + event_notify: mpsc::Sender<()>, + their_node_id: PublicKey, + addr: SocketAddr) { + let connect_timeout = Delay::new(Instant::now() + Duration::from_secs(10)).then(|_| { + future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached")) + }); tokio::spawn( - TcpStream::connect(&addr) - .select(connect_timeout) - .and_then(move |stream| { - Connection::setup_outbound(peer_manager, event_notify, their_node_id, stream.0); - future::ok(()) - }) - .or_else(|_| { - //TODO: return errors somehow - future::ok(()) - }), + TcpStream::connect(&addr).select(connect_timeout) + .and_then(move |stream| { + Connection::setup_outbound( + peer_manager, + event_notify, + their_node_id, + stream.0, + ); + future::ok(()) + }) + .or_else(|_| { + //TODO: return errors somehow + future::ok(()) + }), ); } } @@ -284,20 +277,20 @@ impl peer_handler::SocketDescriptor for SocketDescriptor { us.read_paused = true; let us_ref = self.clone(); tokio::spawn( - us.writer - .take() - .unwrap() - .flush() - .then(move |writer_res| -> Result<(), ()> { - if let Ok(writer) = writer_res { - { - let mut us = us_ref.conn.lock().unwrap(); - us.writer = Some(writer); - } - schedule_read!(us_ref); - } // we'll fire the disconnect event on the socket reader end - Ok(()) - }), + us.writer + .take() + .unwrap() + .flush() + .then(move |writer_res| -> Result<(), ()> { + if let Ok(writer) = writer_res { + { + let mut us = us_ref.conn.lock().unwrap(); + us.writer = Some(writer); + } + schedule_read!(us_ref); + } // we'll fire the disconnect event on the socket reader end + Ok(()) + }), ); 0 }, diff --git a/lightning/src/chain/chaininterface.rs b/lightning/src/chain/chaininterface.rs index 058fc649cc3..45fe3fed0e8 100644 --- a/lightning/src/chain/chaininterface.rs +++ b/lightning/src/chain/chaininterface.rs @@ -49,11 +49,10 @@ pub trait ChainWatchInterface: Sync + Send { /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three /// bytes are the block height, the next 3 the transaction index within the block, and the /// final two the output within the transaction. - fn get_chain_utxo( - &self, - genesis_hash: Sha256dHash, - unspent_tx_output_identifier: u64, - ) -> Result<(Script, u64), ChainError>; + fn get_chain_utxo(&self, + genesis_hash: Sha256dHash, + unspent_tx_output_identifier: u64) + -> Result<(Script, u64), ChainError>; /// Gets the list of transactions and transaction indices that the ChainWatchInterface is /// watching for. @@ -83,13 +82,11 @@ pub trait ChainListener: Sync + Send { /// /// This also means those counting confirmations using block_connected callbacks should watch /// for duplicate headers and not count them towards confirmations! - fn block_connected( - &self, - header: &BlockHeader, - height: u32, - txn_matched: &[&Transaction], - indexes_of_txn_matched: &[u32], - ); + fn block_connected(&self, + header: &BlockHeader, + height: u32, + txn_matched: &[&Transaction], + indexes_of_txn_matched: &[u32]); /// Notifies a listener that a block was disconnected. /// Unlike block_connected, this *must* never be called twice for the same disconnect event. /// Height must be the one of the block which was disconnected (not new height of the best chain) @@ -145,11 +142,9 @@ pub struct ChainWatchedUtil { impl ChainWatchedUtil { /// Constructs an empty (watches nothing) ChainWatchedUtil pub fn new() -> Self { - Self { - watch_all: false, - watched_txn: HashSet::new(), - watched_outpoints: HashSet::new(), - } + Self { watch_all: false, + watched_txn: HashSet::new(), + watched_outpoints: HashSet::new() } } /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already @@ -231,10 +226,8 @@ pub struct BlockNotifier { impl BlockNotifier { /// Constructs a new BlockNotifier without any listeners. pub fn new(chain_monitor: Arc) -> BlockNotifier { - BlockNotifier { - listeners: Mutex::new(Vec::new()), - chain_monitor, - } + BlockNotifier { listeners: Mutex::new(Vec::new()), + chain_monitor } } /// Register the given listener to receive events. Only a weak pointer is provided and @@ -264,13 +257,12 @@ impl BlockNotifier { /// Returns true if notified listeners registered additional watch data (implying that the /// block must be re-scanned and this function called again prior to further block_connected /// calls, see ChainListener::block_connected for more info). - pub fn block_connected_checked( - &self, - header: &BlockHeader, - height: u32, - txn_matched: &[&Transaction], - indexes_of_txn_matched: &[u32], - ) -> bool { + pub fn block_connected_checked(&self, + header: &BlockHeader, + height: u32, + txn_matched: &[&Transaction], + indexes_of_txn_matched: &[u32]) + -> bool { let last_seen = self.chain_monitor.reentered(); let listeners = self.listeners.lock().unwrap().clone(); @@ -328,11 +320,10 @@ impl ChainWatchInterface for ChainWatchInterfaceUtil { } } - fn get_chain_utxo( - &self, - genesis_hash: Sha256dHash, - _unspent_tx_output_identifier: u64, - ) -> Result<(Script, u64), ChainError> { + fn get_chain_utxo(&self, + genesis_hash: Sha256dHash, + _unspent_tx_output_identifier: u64) + -> Result<(Script, u64), ChainError> { if genesis_hash != genesis_block(self.network).header.bitcoin_hash() { return Err(ChainError::NotWatched); } @@ -360,12 +351,10 @@ impl ChainWatchInterface for ChainWatchInterfaceUtil { impl ChainWatchInterfaceUtil { /// Creates a new ChainWatchInterfaceUtil for the given network pub fn new(network: Network, logger: Arc) -> ChainWatchInterfaceUtil { - ChainWatchInterfaceUtil { - network, - watched: Mutex::new(ChainWatchedUtil::new()), - reentered: AtomicUsize::new(1), - logger, - } + ChainWatchInterfaceUtil { network, + watched: Mutex::new(ChainWatchedUtil::new()), + reentered: AtomicUsize::new(1), + logger } } /// Checks if a given transaction matches the current filter. diff --git a/lightning/src/chain/keysinterface.rs b/lightning/src/chain/keysinterface.rs index f16f5b912d3..609f9aa6350 100644 --- a/lightning/src/chain/keysinterface.rs +++ b/lightning/src/chain/keysinterface.rs @@ -142,29 +142,27 @@ pub trait ChannelKeys: Send { /// TODO: Document the things someone using this interface should enforce before signing. /// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and /// making the callee generate it via some util function we expose)! - fn sign_remote_commitment( - &self, - channel_value_satoshis: u64, - channel_funding_redeemscript: &Script, - feerate_per_kw: u64, - commitment_tx: &Transaction, - keys: &TxCreationKeys, - htlcs: &[&HTLCOutputInCommitment], - to_self_delay: u16, - secp_ctx: &Secp256k1, - ) -> Result<(Signature, Vec), ()>; + fn sign_remote_commitment(&self, + channel_value_satoshis: u64, + channel_funding_redeemscript: &Script, + feerate_per_kw: u64, + commitment_tx: &Transaction, + keys: &TxCreationKeys, + htlcs: &[&HTLCOutputInCommitment], + to_self_delay: u16, + secp_ctx: &Secp256k1) + -> Result<(Signature, Vec), ()>; /// Create a signature for a (proposed) closing transaction. /// /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have /// chosen to forgo their output as dust. - fn sign_closing_transaction( - &self, - channel_value_satoshis: u64, - channel_funding_redeemscript: &Script, - closing_tx: &Transaction, - secp_ctx: &Secp256k1, - ) -> Result; + fn sign_closing_transaction(&self, + channel_value_satoshis: u64, + channel_funding_redeemscript: &Script, + closing_tx: &Transaction, + secp_ctx: &Secp256k1) + -> Result; /// Signs a channel announcement message with our funding key, proving it comes from one /// of the channel participants. @@ -172,11 +170,10 @@ pub trait ChannelKeys: Send { /// Note that if this fails or is rejected, the channel will not be publicly announced and /// our counterparty may (though likely will not) close the channel on us for violating the /// protocol. - fn sign_channel_announcement( - &self, - msg: &msgs::UnsignedChannelAnnouncement, - secp_ctx: &Secp256k1, - ) -> Result; + fn sign_channel_announcement(&self, + msg: &msgs::UnsignedChannelAnnouncement, + secp_ctx: &Secp256k1) + -> Result; } #[derive(Clone)] @@ -204,17 +201,16 @@ impl ChannelKeys for InMemoryChannelKeys { fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key } fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed } - fn sign_remote_commitment( - &self, - channel_value_satoshis: u64, - channel_funding_redeemscript: &Script, - feerate_per_kw: u64, - commitment_tx: &Transaction, - keys: &TxCreationKeys, - htlcs: &[&HTLCOutputInCommitment], - to_self_delay: u16, - secp_ctx: &Secp256k1, - ) -> Result<(Signature, Vec), ()> { + fn sign_remote_commitment(&self, + channel_value_satoshis: u64, + channel_funding_redeemscript: &Script, + feerate_per_kw: u64, + commitment_tx: &Transaction, + keys: &TxCreationKeys, + htlcs: &[&HTLCOutputInCommitment], + to_self_delay: u16, + secp_ctx: &Secp256k1) + -> Result<(Signature, Vec), ()> { if commitment_tx.input.len() != 1 { return Err(()); } @@ -233,12 +229,12 @@ impl ChannelKeys for InMemoryChannelKeys { for ref htlc in htlcs { if let Some(_) = htlc.transaction_output_index { let htlc_tx = chan_utils::build_htlc_transaction( - &commitment_txid, - feerate_per_kw, - to_self_delay, - htlc, - &keys.a_delayed_payment_key, - &keys.revocation_key, + &commitment_txid, + feerate_per_kw, + to_self_delay, + htlc, + &keys.a_delayed_payment_key, + &keys.revocation_key, ); let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys); let htlc_sighash = hash_to_message!( @@ -260,13 +256,12 @@ impl ChannelKeys for InMemoryChannelKeys { Ok((commitment_sig, htlc_sigs)) } - fn sign_closing_transaction( - &self, - channel_value_satoshis: u64, - channel_funding_redeemscript: &Script, - closing_tx: &Transaction, - secp_ctx: &Secp256k1, - ) -> Result { + fn sign_closing_transaction(&self, + channel_value_satoshis: u64, + channel_funding_redeemscript: &Script, + closing_tx: &Transaction, + secp_ctx: &Secp256k1) + -> Result { if closing_tx.input.len() != 1 { return Err(()); } @@ -287,11 +282,10 @@ impl ChannelKeys for InMemoryChannelKeys { Ok(secp_ctx.sign(&sighash, &self.funding_key)) } - fn sign_channel_announcement( - &self, - msg: &msgs::UnsignedChannelAnnouncement, - secp_ctx: &Secp256k1, - ) -> Result { + fn sign_channel_announcement(&self, + msg: &msgs::UnsignedChannelAnnouncement, + secp_ctx: &Secp256k1) + -> Result { let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]); Ok(secp_ctx.sign(&msghash, &self.funding_key)) } @@ -349,34 +343,29 @@ impl KeysManager { /// Note that until the 0.1 release there is no guarantee of backward compatibility between /// versions. Once the library is more fully supported, the docs will be updated to include a /// detailed description of the guarantee. - pub fn new( - seed: &[u8; 32], - network: Network, - logger: Arc, - starting_time_secs: u64, - starting_time_nanos: u32, - ) -> KeysManager { + pub fn new(seed: &[u8; 32], + network: Network, + logger: Arc, + starting_time_secs: u64, + starting_time_nanos: u32) + -> KeysManager { let secp_ctx = Secp256k1::signing_only(); match ExtendedPrivKey::new_master(network.clone(), seed) { Ok(master_key) => { - let node_secret = master_key - .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()) - .expect("Your RNG is busted") - .private_key - .key; + let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()) + .expect("Your RNG is busted") + .private_key + .key; let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) { Ok(destination_key) => { - let pubkey_hash160 = Hash160::hash( - &ExtendedPubKey::from_private(&secp_ctx, &destination_key) - .public_key - .key - .serialize()[..], - ); - Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&pubkey_hash160.into_inner()) - .into_script() + let pubkey_hash160 = + Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key + .key + .serialize()[..]); + Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&pubkey_hash160.into_inner()) + .into_script() }, Err(_) => panic!("Your RNG is busted"), }; @@ -384,35 +373,30 @@ impl KeysManager { Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key, Err(_) => panic!("Your RNG is busted"), }; - let channel_master_key = master_key - .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()) - .expect("Your RNG is busted"); - let session_master_key = master_key - .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()) - .expect("Your RNG is busted"); - let channel_id_master_key = master_key - .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()) - .expect("Your RNG is busted"); + let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()) + .expect("Your RNG is busted"); + let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()) + .expect("Your RNG is busted"); + let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()) + .expect("Your RNG is busted"); let mut unique_start = Sha256::engine(); unique_start.input(&byte_utils::be64_to_array(starting_time_secs)); unique_start.input(&byte_utils::be32_to_array(starting_time_nanos)); unique_start.input(seed); - KeysManager { - secp_ctx, - node_secret, - destination_script, - shutdown_pubkey, - channel_master_key, - channel_child_index: AtomicUsize::new(0), - session_master_key, - session_child_index: AtomicUsize::new(0), - channel_id_master_key, - channel_id_child_index: AtomicUsize::new(0), - unique_start, - logger, - } + KeysManager { secp_ctx, + node_secret, + destination_script, + shutdown_pubkey, + channel_master_key, + channel_child_index: AtomicUsize::new(0), + session_master_key, + session_child_index: AtomicUsize::new(0), + channel_id_master_key, + channel_id_child_index: AtomicUsize::new(0), + unique_start, + logger } }, Err(_) => panic!("Your rng is busted"), } @@ -435,13 +419,12 @@ impl KeysInterface for KeysManager { let mut sha = self.unique_start.clone(); let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel); - let child_privkey = self - .channel_master_key - .ckd_priv( - &self.secp_ctx, - ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted"), - ) - .expect("Your RNG is busted"); + let child_privkey = self.channel_master_key + .ckd_priv( + &self.secp_ctx, + ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted"), + ) + .expect("Your RNG is busted"); sha.input(&child_privkey.private_key.key[..]); let seed = Sha256::from_engine(sha).into_inner(); @@ -467,27 +450,24 @@ impl KeysInterface for KeysManager { let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key); let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key); - InMemoryChannelKeys { - funding_key, - revocation_base_key, - payment_base_key, - delayed_payment_base_key, - htlc_base_key, - commitment_seed, - } + InMemoryChannelKeys { funding_key, + revocation_base_key, + payment_base_key, + delayed_payment_base_key, + htlc_base_key, + commitment_seed } } fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) { let mut sha = self.unique_start.clone(); let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel); - let child_privkey = self - .session_master_key - .ckd_priv( - &self.secp_ctx, - ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted"), - ) - .expect("Your RNG is busted"); + let child_privkey = self.session_master_key + .ckd_priv( + &self.secp_ctx, + ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted"), + ) + .expect("Your RNG is busted"); sha.input(&child_privkey.private_key.key[..]); let mut rng_seed = sha.clone(); @@ -495,23 +475,20 @@ impl KeysInterface for KeysManager { // ChaCha so it is another step harder to break. rng_seed.input(b"RNG Seed Salt"); sha.input(b"Session Key Salt"); - ( - SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"), - Sha256::from_engine(rng_seed).into_inner(), - ) + (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"), + Sha256::from_engine(rng_seed).into_inner()) } fn get_channel_id(&self) -> [u8; 32] { let mut sha = self.unique_start.clone(); let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel); - let child_privkey = self - .channel_id_master_key - .ckd_priv( - &self.secp_ctx, - ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted"), - ) - .expect("Your RNG is busted"); + let child_privkey = self.channel_id_master_key + .ckd_priv( + &self.secp_ctx, + ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted"), + ) + .expect("Your RNG is busted"); sha.input(&child_privkey.private_key.key[..]); (Sha256::from_engine(sha).into_inner()) diff --git a/lightning/src/chain/transaction.rs b/lightning/src/chain/transaction.rs index feab1ce868a..6d7b3b1d615 100644 --- a/lightning/src/chain/transaction.rs +++ b/lightning/src/chain/transaction.rs @@ -30,10 +30,8 @@ impl OutPoint { /// Converts this OutPoint into the OutPoint field as used by rust-bitcoin pub fn into_bitcoin_outpoint(self) -> BitcoinOutPoint { - BitcoinOutPoint { - txid: self.txid, - vout: self.index as u32, - } + BitcoinOutPoint { txid: self.txid, + vout: self.index as u32 } } } @@ -50,20 +48,14 @@ mod tests { fn test_channel_id_calculation() { let tx: Transaction = encode::deserialize(&hex::decode("020000000001010e0adef48412e4361325ac1c6e36411299ab09d4f083b9d8ddb55fbc06e1b0c00000000000feffffff0220a1070000000000220020f81d95e040bd0a493e38bae27bff52fe2bb58b93b293eb579c01c31b05c5af1dc072cfee54a3000016001434b1d6211af5551905dc2642d05f5b04d25a8fe80247304402207f570e3f0de50546aad25a872e3df059d277e776dda4269fa0d2cc8c2ee6ec9a022054e7fae5ca94d47534c86705857c24ceea3ad51c69dd6051c5850304880fc43a012103cb11a1bacc223d98d91f1946c6752e358a5eb1a1c983b3e6fb15378f453b76bd00000000").unwrap()[..]).unwrap(); assert_eq!( - &OutPoint { - txid: tx.txid(), - index: 0 - } - .to_channel_id(), - &hex::decode("3e88dd7165faf7be58b3c5bb2c9c452aebef682807ea57080f62e6f6e113c25e").unwrap()[..] + &OutPoint { txid: tx.txid(), + index: 0 }.to_channel_id(), + &hex::decode("3e88dd7165faf7be58b3c5bb2c9c452aebef682807ea57080f62e6f6e113c25e").unwrap()[..] ); assert_eq!( - &OutPoint { - txid: tx.txid(), - index: 1 - } - .to_channel_id(), - &hex::decode("3e88dd7165faf7be58b3c5bb2c9c452aebef682807ea57080f62e6f6e113c25f").unwrap()[..] + &OutPoint { txid: tx.txid(), + index: 1 }.to_channel_id(), + &hex::decode("3e88dd7165faf7be58b3c5bb2c9c452aebef682807ea57080f62e6f6e113c25f").unwrap()[..] ); } } diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 70373ed67c1..431e96e6340 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -42,11 +42,10 @@ pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [ /// Derives a per-commitment-transaction private key (eg an htlc key or payment key) from the base /// private key for that type of key and the per_commitment_point (available in TxCreationKeys) -pub fn derive_private_key( - secp_ctx: &Secp256k1, - per_commitment_point: &PublicKey, - base_secret: &SecretKey, -) -> Result { +pub fn derive_private_key(secp_ctx: &Secp256k1, + per_commitment_point: &PublicKey, + base_secret: &SecretKey) + -> Result { let mut sha = Sha256::engine(); sha.input(&per_commitment_point.serialize()); sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize()); @@ -57,11 +56,10 @@ pub fn derive_private_key( Ok(key) } -pub(super) fn derive_public_key( - secp_ctx: &Secp256k1, - per_commitment_point: &PublicKey, - base_point: &PublicKey, -) -> Result { +pub(super) fn derive_public_key(secp_ctx: &Secp256k1, + per_commitment_point: &PublicKey, + base_point: &PublicKey) + -> Result { let mut sha = Sha256::engine(); sha.input(&per_commitment_point.serialize()); sha.input(&base_point.serialize()); @@ -74,11 +72,10 @@ pub(super) fn derive_public_key( /// Derives a revocation key from its constituent parts. /// Note that this is infallible iff we trust that at least one of the two input keys are randomly /// generated (ie our own). -pub(super) fn derive_private_revocation_key( - secp_ctx: &Secp256k1, - per_commitment_secret: &SecretKey, - revocation_base_secret: &SecretKey, -) -> Result { +pub(super) fn derive_private_revocation_key(secp_ctx: &Secp256k1, + per_commitment_secret: &SecretKey, + revocation_base_secret: &SecretKey) + -> Result { let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret); let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret); @@ -105,11 +102,10 @@ pub(super) fn derive_private_revocation_key( Ok(part_a) } -pub(super) fn derive_public_revocation_key( - secp_ctx: &Secp256k1, - per_commitment_point: &PublicKey, - revocation_base_point: &PublicKey, -) -> Result { +pub(super) fn derive_public_revocation_key(secp_ctx: &Secp256k1, + per_commitment_point: &PublicKey, + revocation_base_point: &PublicKey) + -> Result { let rev_append_commit_hash_key = { let mut sha = Sha256::engine(); sha.input(&revocation_base_point.serialize()); @@ -151,44 +147,47 @@ pub struct TxCreationKeys { } impl TxCreationKeys { - pub(super) fn new( - secp_ctx: &Secp256k1, - per_commitment_point: &PublicKey, - a_delayed_payment_base: &PublicKey, - a_htlc_base: &PublicKey, - b_revocation_base: &PublicKey, - b_payment_base: &PublicKey, - b_htlc_base: &PublicKey, - ) -> Result { - Ok(TxCreationKeys { - per_commitment_point: per_commitment_point.clone(), - revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?, - a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?, - b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?, - a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?, - b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?, - }) + pub(super) fn new(secp_ctx: &Secp256k1, + per_commitment_point: &PublicKey, + a_delayed_payment_base: &PublicKey, + a_htlc_base: &PublicKey, + b_revocation_base: &PublicKey, + b_payment_base: &PublicKey, + b_htlc_base: &PublicKey) + -> Result { + Ok(TxCreationKeys { per_commitment_point: per_commitment_point.clone(), + revocation_key: derive_public_revocation_key( + &secp_ctx, + &per_commitment_point, + &b_revocation_base, + )?, + a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?, + b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?, + a_delayed_payment_key: derive_public_key( + &secp_ctx, + &per_commitment_point, + &a_delayed_payment_base, + )?, + b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)? }) } } /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by /// the revocation key -pub(super) fn get_revokeable_redeemscript( - revocation_key: &PublicKey, - to_self_delay: u16, - delayed_payment_key: &PublicKey, -) -> Script { - Builder::new() - .push_opcode(opcodes::all::OP_IF) - .push_slice(&revocation_key.serialize()) - .push_opcode(opcodes::all::OP_ELSE) - .push_int(to_self_delay as i64) - .push_opcode(opcodes::all::OP_CSV) - .push_opcode(opcodes::all::OP_DROP) - .push_slice(&delayed_payment_key.serialize()) - .push_opcode(opcodes::all::OP_ENDIF) - .push_opcode(opcodes::all::OP_CHECKSIG) - .into_script() +pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, + to_self_delay: u16, + delayed_payment_key: &PublicKey) + -> Script { + Builder::new().push_opcode(opcodes::all::OP_IF) + .push_slice(&revocation_key.serialize()) + .push_opcode(opcodes::all::OP_ELSE) + .push_int(to_self_delay as i64) + .push_opcode(opcodes::all::OP_CSV) + .push_opcode(opcodes::all::OP_DROP) + .push_slice(&delayed_payment_key.serialize()) + .push_opcode(opcodes::all::OP_ENDIF) + .push_opcode(opcodes::all::OP_CHECKSIG) + .into_script() } #[derive(Clone, PartialEq)] @@ -213,74 +212,71 @@ pub struct HTLCOutputInCommitment { } #[inline] -pub(super) fn get_htlc_redeemscript_with_explicit_keys( - htlc: &HTLCOutputInCommitment, - a_htlc_key: &PublicKey, - b_htlc_key: &PublicKey, - revocation_key: &PublicKey, -) -> Script { +pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, + a_htlc_key: &PublicKey, + b_htlc_key: &PublicKey, + revocation_key: &PublicKey) + -> Script { let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner(); if htlc.offered { - Builder::new() - .push_opcode(opcodes::all::OP_DUP) - .push_opcode(opcodes::all::OP_HASH160) - .push_slice(&Hash160::hash(&revocation_key.serialize())[..]) - .push_opcode(opcodes::all::OP_EQUAL) - .push_opcode(opcodes::all::OP_IF) - .push_opcode(opcodes::all::OP_CHECKSIG) - .push_opcode(opcodes::all::OP_ELSE) - .push_slice(&b_htlc_key.serialize()[..]) - .push_opcode(opcodes::all::OP_SWAP) - .push_opcode(opcodes::all::OP_SIZE) - .push_int(32) - .push_opcode(opcodes::all::OP_EQUAL) - .push_opcode(opcodes::all::OP_NOTIF) - .push_opcode(opcodes::all::OP_DROP) - .push_int(2) - .push_opcode(opcodes::all::OP_SWAP) - .push_slice(&a_htlc_key.serialize()[..]) - .push_int(2) - .push_opcode(opcodes::all::OP_CHECKMULTISIG) - .push_opcode(opcodes::all::OP_ELSE) - .push_opcode(opcodes::all::OP_HASH160) - .push_slice(&payment_hash160) - .push_opcode(opcodes::all::OP_EQUALVERIFY) - .push_opcode(opcodes::all::OP_CHECKSIG) - .push_opcode(opcodes::all::OP_ENDIF) - .push_opcode(opcodes::all::OP_ENDIF) - .into_script() + Builder::new().push_opcode(opcodes::all::OP_DUP) + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&Hash160::hash(&revocation_key.serialize())[..]) + .push_opcode(opcodes::all::OP_EQUAL) + .push_opcode(opcodes::all::OP_IF) + .push_opcode(opcodes::all::OP_CHECKSIG) + .push_opcode(opcodes::all::OP_ELSE) + .push_slice(&b_htlc_key.serialize()[..]) + .push_opcode(opcodes::all::OP_SWAP) + .push_opcode(opcodes::all::OP_SIZE) + .push_int(32) + .push_opcode(opcodes::all::OP_EQUAL) + .push_opcode(opcodes::all::OP_NOTIF) + .push_opcode(opcodes::all::OP_DROP) + .push_int(2) + .push_opcode(opcodes::all::OP_SWAP) + .push_slice(&a_htlc_key.serialize()[..]) + .push_int(2) + .push_opcode(opcodes::all::OP_CHECKMULTISIG) + .push_opcode(opcodes::all::OP_ELSE) + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&payment_hash160) + .push_opcode(opcodes::all::OP_EQUALVERIFY) + .push_opcode(opcodes::all::OP_CHECKSIG) + .push_opcode(opcodes::all::OP_ENDIF) + .push_opcode(opcodes::all::OP_ENDIF) + .into_script() } else { - Builder::new() - .push_opcode(opcodes::all::OP_DUP) - .push_opcode(opcodes::all::OP_HASH160) - .push_slice(&Hash160::hash(&revocation_key.serialize())[..]) - .push_opcode(opcodes::all::OP_EQUAL) - .push_opcode(opcodes::all::OP_IF) - .push_opcode(opcodes::all::OP_CHECKSIG) - .push_opcode(opcodes::all::OP_ELSE) - .push_slice(&b_htlc_key.serialize()[..]) - .push_opcode(opcodes::all::OP_SWAP) - .push_opcode(opcodes::all::OP_SIZE) - .push_int(32) - .push_opcode(opcodes::all::OP_EQUAL) - .push_opcode(opcodes::all::OP_IF) - .push_opcode(opcodes::all::OP_HASH160) - .push_slice(&payment_hash160) - .push_opcode(opcodes::all::OP_EQUALVERIFY) - .push_int(2) - .push_opcode(opcodes::all::OP_SWAP) - .push_slice(&a_htlc_key.serialize()[..]) - .push_int(2) - .push_opcode(opcodes::all::OP_CHECKMULTISIG) - .push_opcode(opcodes::all::OP_ELSE) - .push_opcode(opcodes::all::OP_DROP) - .push_int(htlc.cltv_expiry as i64) - .push_opcode(opcodes::all::OP_CLTV) - .push_opcode(opcodes::all::OP_DROP) - .push_opcode(opcodes::all::OP_CHECKSIG) - .push_opcode(opcodes::all::OP_ENDIF) - .push_opcode(opcodes::all::OP_ENDIF) - .into_script() + Builder::new().push_opcode(opcodes::all::OP_DUP) + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&Hash160::hash(&revocation_key.serialize())[..]) + .push_opcode(opcodes::all::OP_EQUAL) + .push_opcode(opcodes::all::OP_IF) + .push_opcode(opcodes::all::OP_CHECKSIG) + .push_opcode(opcodes::all::OP_ELSE) + .push_slice(&b_htlc_key.serialize()[..]) + .push_opcode(opcodes::all::OP_SWAP) + .push_opcode(opcodes::all::OP_SIZE) + .push_int(32) + .push_opcode(opcodes::all::OP_EQUAL) + .push_opcode(opcodes::all::OP_IF) + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&payment_hash160) + .push_opcode(opcodes::all::OP_EQUALVERIFY) + .push_int(2) + .push_opcode(opcodes::all::OP_SWAP) + .push_slice(&a_htlc_key.serialize()[..]) + .push_int(2) + .push_opcode(opcodes::all::OP_CHECKMULTISIG) + .push_opcode(opcodes::all::OP_ELSE) + .push_opcode(opcodes::all::OP_DROP) + .push_int(htlc.cltv_expiry as i64) + .push_opcode(opcodes::all::OP_CLTV) + .push_opcode(opcodes::all::OP_DROP) + .push_opcode(opcodes::all::OP_CHECKSIG) + .push_opcode(opcodes::all::OP_ENDIF) + .push_opcode(opcodes::all::OP_ENDIF) + .into_script() } } @@ -292,26 +288,21 @@ pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKey } /// panics if htlc.transaction_output_index.is_none()! -pub fn build_htlc_transaction( - prev_hash: &Sha256dHash, - feerate_per_kw: u64, - to_self_delay: u16, - htlc: &HTLCOutputInCommitment, - a_delayed_payment_key: &PublicKey, - revocation_key: &PublicKey, -) -> Transaction { +pub fn build_htlc_transaction(prev_hash: &Sha256dHash, + feerate_per_kw: u64, + to_self_delay: u16, + htlc: &HTLCOutputInCommitment, + a_delayed_payment_key: &PublicKey, + revocation_key: &PublicKey) + -> Transaction { let mut txins: Vec = Vec::new(); - txins.push(TxIn { - previous_output: OutPoint { - txid: prev_hash.clone(), - vout: htlc - .transaction_output_index - .expect("Can't build an HTLC transaction for a dust output"), - }, - script_sig: Script::new(), - sequence: 0, - witness: Vec::new(), - }); + txins.push(TxIn { previous_output: OutPoint { txid: prev_hash.clone(), + vout: + htlc.transaction_output_index + .expect("Can't build an HTLC transaction for a dust output") }, + script_sig: Script::new(), + sequence: 0, + witness: Vec::new() }); let total_fee = if htlc.offered { feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000 @@ -325,28 +316,25 @@ pub fn build_htlc_transaction( value: htlc.amount_msat / 1000 - total_fee, //TODO: BOLT 3 does not specify if we should add amount_msat before dividing or if we should divide by 1000 before subtracting (as we do here) }); - Transaction { - version: 2, - lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 }, - input: txins, - output: txouts, - } + Transaction { version: 2, + lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 }, + input: txins, + output: txouts } } /// Signs a transaction created by build_htlc_transaction. If the transaction is an /// HTLC-Success transaction (ie htlc.offered is false), preimage must be set! -pub(crate) fn sign_htlc_transaction( - tx: &mut Transaction, - their_sig: &Signature, - preimage: &Option, - htlc: &HTLCOutputInCommitment, - a_htlc_key: &PublicKey, - b_htlc_key: &PublicKey, - revocation_key: &PublicKey, - per_commitment_point: &PublicKey, - htlc_base_key: &SecretKey, - secp_ctx: &Secp256k1, -) -> Result<(Signature, Script), ()> { +pub(crate) fn sign_htlc_transaction(tx: &mut Transaction, + their_sig: &Signature, + preimage: &Option, + htlc: &HTLCOutputInCommitment, + a_htlc_key: &PublicKey, + b_htlc_key: &PublicKey, + revocation_key: &PublicKey, + per_commitment_point: &PublicKey, + htlc_base_key: &SecretKey, + secp_ctx: &Secp256k1) + -> Result<(Signature, Script), ()> { if tx.input.len() != 1 { return Err(()); } @@ -358,7 +346,11 @@ pub(crate) fn sign_htlc_transaction( let our_htlc_key = derive_private_key(secp_ctx, per_commitment_point, htlc_base_key).map_err(|_| ())?; let sighash = hash_to_message!( - &bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..] + &bip143::SighashComponents::new(&tx).sighash_all( + &tx.input[0], + &htlc_redeemscript, + htlc.amount_msat / 1000 + )[..] ); let local_tx = PublicKey::from_secret_key(&secp_ctx, &our_htlc_key) == *a_htlc_key; let our_sig = secp_ctx.sign(&sighash, &our_htlc_key); @@ -398,22 +390,17 @@ pub(crate) struct LocalCommitmentTransaction { impl LocalCommitmentTransaction { #[cfg(test)] pub fn dummy() -> Self { - Self { - tx: Transaction { - version: 2, - input: Vec::new(), - output: Vec::new(), - lock_time: 0, - }, - } + Self { tx: Transaction { version: 2, + input: Vec::new(), + output: Vec::new(), + lock_time: 0 } } } - pub fn new_missing_local_sig( - mut tx: Transaction, - their_sig: &Signature, - our_funding_key: &PublicKey, - their_funding_key: &PublicKey, - ) -> LocalCommitmentTransaction { + pub fn new_missing_local_sig(mut tx: Transaction, + their_sig: &Signature, + our_funding_key: &PublicKey, + their_funding_key: &PublicKey) + -> LocalCommitmentTransaction { if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); } @@ -454,22 +441,20 @@ impl LocalCommitmentTransaction { } } - pub fn add_local_sig( - &mut self, - funding_key: &SecretKey, - funding_redeemscript: &Script, - channel_value_satoshis: u64, - secp_ctx: &Secp256k1, - ) { + pub fn add_local_sig(&mut self, + funding_key: &SecretKey, + funding_redeemscript: &Script, + channel_value_satoshis: u64, + secp_ctx: &Secp256k1) { if self.has_local_sig() { return; } let sighash = hash_to_message!( - &bip143::SighashComponents::new(&self.tx).sighash_all( - &self.tx.input[0], - funding_redeemscript, - channel_value_satoshis - )[..] + &bip143::SighashComponents::new(&self.tx).sighash_all( + &self.tx.input[0], + funding_redeemscript, + channel_value_satoshis + )[..] ); let our_sig = secp_ctx.sign(&sighash, funding_key); diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index ec2fd669d47..ad511e7ba23 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -21,16 +21,15 @@ fn test_simple_monitor_permanent_update_fail() { let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure); @@ -63,16 +62,15 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) { let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); @@ -90,14 +88,14 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) { nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (true, true), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (true, true), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } @@ -109,9 +107,8 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) { assert_eq!(events_2.len(), 1); let payment_event = SendEvent::from_event(events_2.pop().unwrap()); assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); @@ -145,14 +142,14 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) { nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } @@ -200,16 +197,15 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000); // Now try to send a second payment which will fail to send - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); @@ -230,18 +226,14 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { let events_2 = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events_2.len(), 1); let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - ref commitment_signed, - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + ref commitment_signed, }, } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); assert!(update_add_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); @@ -250,9 +242,8 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { assert!(update_fee.is_none()); if (disconnect_count & 16) == 0 { - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]); let events_3 = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events_3.len(), 1); match events_3[0] { @@ -262,14 +253,13 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { _ => panic!("Unexpected event"), } - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Previous monitor update failure prevented generation of RAA".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Previous monitor update failure prevented generation of RAA".to_string(), + 1, ); } @@ -323,14 +313,12 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]); assert_eq!(reestablish_2.len(), 1); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); check_added_monitors!(nodes[0], 0); let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); check_added_monitors!(nodes[1], 0); let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]); @@ -355,8 +343,8 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { assert!(as_resp.1.is_none()); nodes[0].node.handle_update_fulfill_htlc( - &nodes[1].node.get_our_node_id(), - &bs_resp.2.as_ref().unwrap().update_fulfill_htlcs[0], + &nodes[1].node.get_our_node_id(), + &bs_resp.2.as_ref().unwrap().update_fulfill_htlcs[0], ); let events_3 = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events_3.len(), 1); @@ -368,13 +356,13 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { } nodes[0].node.handle_commitment_signed( - &nodes[1].node.get_our_node_id(), - &bs_resp.2.as_ref().unwrap().commitment_signed, + &nodes[1].node.get_our_node_id(), + &bs_resp.2.as_ref().unwrap().commitment_signed, ); let as_resp_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); @@ -395,37 +383,30 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { assert!(bs_resp == second_bs_resp); } - ( - SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), - as_resp.1.unwrap(), - ) + (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap()) } else { let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_4.len(), 2); - ( - SendEvent::from_event(events_4.remove(0)), - match events_4[0] { - MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => { - assert_eq!(*node_id, nodes[1].node.get_our_node_id()); - msg.clone() - }, - _ => panic!("Unexpected event"), - }, - ) + (SendEvent::from_event(events_4.remove(0)), + match events_4[0] { + MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => { + assert_eq!(*node_id, nodes[1].node.get_our_node_id()); + msg.clone() + }, + _ => panic!("Unexpected event"), + }) }; assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); let bs_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[1], 1); @@ -524,38 +505,36 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { } nodes[0].node.handle_commitment_signed( - &nodes[1].node.get_our_node_id(), - &bs_second_commitment_update.commitment_signed, + &nodes[1].node.get_our_node_id(), + &bs_second_commitment_update.commitment_signed, ); let as_revoke_and_ack = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); nodes[1].node.handle_commitment_signed( - &nodes[0].node.get_our_node_id(), - &as_commitment_update.commitment_signed, + &nodes[0].node.get_our_node_id(), + &as_commitment_update.commitment_signed, ); let bs_second_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); @@ -607,34 +586,31 @@ fn test_monitor_update_fail_cs() { let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0)); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event.commitment_msg); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event.commitment_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -648,18 +624,15 @@ fn test_monitor_update_fail_cs() { match responses[0] { MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg); check_added_monitors!(nodes[0], 1); }, _ => panic!("Unexpected event"), } match responses[1] { - MessageSendEvent::UpdateHTLCs { - ref updates, - ref node_id, - } => { + MessageSendEvent::UpdateHTLCs { ref updates, + ref node_id, } => { assert!(updates.update_add_htlcs.is_empty()); assert!(updates.update_fulfill_htlcs.is_empty()); assert!(updates.update_fail_htlcs.is_empty()); @@ -668,14 +641,13 @@ fn test_monitor_update_fail_cs() { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[0], 1); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); @@ -688,13 +660,12 @@ fn test_monitor_update_fail_cs() { check_added_monitors!(nodes[0], 1); let final_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); @@ -720,35 +691,32 @@ fn test_monitor_update_fail_no_rebroadcast() { let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0)); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); let bs_raa = commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true, false, true); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_raa); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); @@ -781,72 +749,65 @@ fn test_monitor_update_raa_while_paused() { send_payment(&nodes[0], &[&nodes[1]], 5000000, 5_000_000); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, our_payment_hash_1) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash_1).unwrap(); check_added_monitors!(nodes[0], 1); let send_event_1 = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0)); - let route = nodes[1] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, our_payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[1].node.send_payment(route, our_payment_hash_2).unwrap(); check_added_monitors!(nodes[1], 1); let send_event_2 = SendEvent::from_event(nodes[1].node.get_and_clear_pending_msg_events().remove(0)); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event_1.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event_1.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event_1.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event_1.commitment_msg); check_added_monitors!(nodes[1], 1); let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_2.msgs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_2.commitment_msg); + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_2.msgs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_2.commitment_msg); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Previous monitor update failure prevented responses to RAA".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Previous monitor update failure prevented responses to RAA".to_string(), + 1, ); check_added_monitors!(nodes[0], 1); @@ -855,42 +816,37 @@ fn test_monitor_update_raa_while_paused() { check_added_monitors!(nodes[0], 1); let as_update_raa = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_update_raa.0); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_update_raa.0); check_added_monitors!(nodes[1], 1); let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update_raa.1); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update_raa.1); check_added_monitors!(nodes[1], 1); let bs_second_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed); check_added_monitors!(nodes[0], 1); let as_second_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa); check_added_monitors!(nodes[0], 1); expect_pending_htlcs_forwardable!(nodes[0]); expect_payment_received!(nodes[0], our_payment_hash_2, 1000000); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); expect_payment_received!(nodes[1], our_payment_hash_1, 1000000); @@ -922,9 +878,8 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[1] - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[1].node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true); @@ -933,23 +888,21 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { // While the second channel is AwaitingRAA, forward a second payment to get it into the // holding cell. let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); - let route = nodes[0] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); nodes[0].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[0], 1); let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0)); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); @@ -958,14 +911,13 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { // Now fail monitor updating. *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -975,24 +927,22 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { // for forwarding. let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]); - let route = nodes[0] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); nodes[0].node.send_payment(route, payment_hash_3).unwrap(); check_added_monitors!(nodes[0], 1); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0)); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]); commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true); check_added_monitors!(nodes[1], 0); @@ -1007,9 +957,8 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { assert!(updates.update_add_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true); let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); @@ -1026,11 +975,9 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } = events[0] + if let Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } = events[0] { assert_eq!(payment_hash, payment_hash_3); assert!(!rejected_by_dest); @@ -1044,31 +991,28 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs { // Try to route another payment backwards from 2 to make sure 1 holds off on responding let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]); - let route = nodes[2] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[2].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); nodes[2].node.send_payment(route, payment_hash_4).unwrap(); check_added_monitors!(nodes[2], 1); send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0)); - nodes[1] - .node - .handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &send_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &send_event.commitment_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Previous monitor update failure prevented generation of RAA".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Previous monitor update failure prevented generation of RAA".to_string(), + 1, ); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); @@ -1122,17 +1066,14 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { // Now deliver the new messages... - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0); commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false); let events_4 = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events_4.len(), 1); - if let Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } = events_4[0] + if let Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } = events_4[0] { assert_eq!(payment_hash, payment_hash_1); assert!(rejected_by_dest); @@ -1140,22 +1081,19 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { panic!("Unexpected event!"); } - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]); if test_ignore_second_cs { - nodes[2] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg); + nodes[2].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg); check_added_monitors!(nodes[2], 1); let bs_revoke_and_ack = get_event_msg!( - nodes[2], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[2], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[2] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()); + nodes[2].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()); check_added_monitors!(nodes[2], 1); let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id()); assert!(bs_cs.update_add_htlcs.is_empty()); @@ -1164,9 +1102,8 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { assert!(bs_cs.update_fulfill_htlcs.is_empty()); assert!(bs_cs.update_fee.is_none()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); check_added_monitors!(nodes[1], 1); let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id()); assert!(as_cs.update_add_htlcs.is_empty()); @@ -1175,35 +1112,31 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { assert!(as_cs.update_fulfill_htlcs.is_empty()); assert!(as_cs.update_fee.is_none()); - nodes[1] - .node - .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed); check_added_monitors!(nodes[1], 1); let as_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[2].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[2].node.get_our_node_id() ); - nodes[2] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed); + nodes[2].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed); check_added_monitors!(nodes[2], 1); let bs_second_raa = get_event_msg!( - nodes[2], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[2], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[2] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); + nodes[2].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[2], 1); assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); } else { @@ -1228,9 +1161,8 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { send_event = SendEvent::from_node(&nodes[1]); assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id()); assert_eq!(send_event.msgs.len(), 1); - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]); + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]); commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[0]); @@ -1242,10 +1174,10 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { _ => panic!("Unexpected event"), }; claim_payment( - &nodes[2], - &[&nodes[1], &nodes[0]], - payment_preimage_4.unwrap(), - 1_000_000, + &nodes[2], + &[&nodes[1], &nodes[0]], + payment_preimage_4.unwrap(), + 1_000_000, ); } @@ -1280,9 +1212,8 @@ fn test_monitor_update_fail_reestablish() { assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); assert_eq!(updates.update_fulfill_htlcs.len(), 1); - nodes[1] - .node - .handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); + nodes[1].node + .handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false); @@ -1292,28 +1223,26 @@ fn test_monitor_update_fail_reestablish() { nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); let as_reestablish = get_event_msg!( - nodes[0], - MessageSendEvent::SendChannelReestablish, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendChannelReestablish, + nodes[1].node.get_our_node_id() ); let bs_reestablish = get_event_msg!( - nodes[1], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); @@ -1324,29 +1253,27 @@ fn test_monitor_update_fail_reestablish() { nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); assert!( - as_reestablish - == get_event_msg!( - nodes[0], - MessageSendEvent::SendChannelReestablish, - nodes[1].node.get_our_node_id() - ) + as_reestablish + == get_event_msg!( + nodes[0], + MessageSendEvent::SendChannelReestablish, + nodes[1].node.get_our_node_id() + ) ); assert!( - bs_reestablish - == get_event_msg!( - nodes[1], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() - ) + bs_reestablish + == get_event_msg!( + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() + ) ); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish); check_added_monitors!(nodes[1], 0); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -1360,9 +1287,8 @@ fn test_monitor_update_fail_reestablish() { assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); assert_eq!(updates.update_fulfill_htlcs.len(), 1); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false); let events = nodes[0].node.get_and_clear_pending_events(); @@ -1382,16 +1308,15 @@ fn raa_no_response_awaiting_raa_state() { let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]); @@ -1409,59 +1334,52 @@ fn raa_no_response_awaiting_raa_state() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); check_added_monitors!(nodes[1], 1); let bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // Now we have a CS queued up which adds a new HTLC (which will need a RAA/CS response from // nodes[1]) followed by an RAA. Fail the monitor updating prior to the CS, deliver the RAA, // then restore channel monitor updates. *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Previous monitor update failure prevented responses to RAA".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Previous monitor update failure prevented responses to RAA".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); @@ -1480,64 +1398,56 @@ fn raa_no_response_awaiting_raa_state() { check_added_monitors!(nodes[0], 0); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); check_added_monitors!(nodes[1], 1); let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // Finally deliver the RAA to nodes[1] which results in a CS response to the last update - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); expect_payment_received!(nodes[1], payment_hash_2, 1000000); let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); expect_payment_received!(nodes[1], payment_hash_3, 1000000); @@ -1571,65 +1481,60 @@ fn claim_while_disconnected_monitor_update_fail() { nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); let as_reconnect = get_event_msg!( - nodes[0], - MessageSendEvent::SendChannelReestablish, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendChannelReestablish, + nodes[1].node.get_our_node_id() ); let bs_reconnect = get_event_msg!( - nodes[1], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reconnect); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reconnect); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); // Now deliver a's reestablish, freeing the claim from the holding cell, but fail the monitor // update. *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reconnect); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reconnect); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); // Send a second payment from A to B, resulting in a commitment update that gets swallowed with // the monitor still failed - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[0], 1); let as_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.commitment_signed); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.commitment_signed); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Previous monitor update failure prevented generation of RAA".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Previous monitor update failure prevented generation of RAA".to_string(), + 1, ); // Note that nodes[1] not updating monitor here is OK - it wont take action on the new HTLC // until we've test_restore_channel_monitor'd and updated for the new commitment transaction. @@ -1644,27 +1549,22 @@ fn claim_while_disconnected_monitor_update_fail() { assert_eq!(bs_msgs.len(), 2); match bs_msgs[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - ref updates, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + ref updates, } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); }, _ => panic!("Unexpected event"), @@ -1673,9 +1573,8 @@ fn claim_while_disconnected_monitor_update_fail() { match bs_msgs[1] { MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), msg); check_added_monitors!(nodes[0], 1); }, _ => panic!("Unexpected event"), @@ -1684,36 +1583,32 @@ fn claim_while_disconnected_monitor_update_fail() { let as_commitment = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); let bs_commitment = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment.commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment.commitment_signed); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment.commitment_signed); check_added_monitors!(nodes[1], 1); let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); expect_payment_received!(nodes[1], payment_hash_2, 1000000); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); check_added_monitors!(nodes[0], 1); let events = nodes[0].node.get_and_clear_pending_events(); @@ -1739,16 +1634,15 @@ fn monitor_failed_no_reestablish_response() { // Route the payment and deliver the initial commitment_signed (with a monitor update failure // on receipt). - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash_1).unwrap(); check_added_monitors!(nodes[0], 1); @@ -1757,17 +1651,15 @@ fn monitor_failed_no_reestablish_response() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); @@ -1780,45 +1672,40 @@ fn monitor_failed_no_reestablish_response() { nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); let as_reconnect = get_event_msg!( - nodes[0], - MessageSendEvent::SendChannelReestablish, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendChannelReestablish, + nodes[1].node.get_our_node_id() ); let bs_reconnect = get_event_msg!( - nodes[1], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reconnect); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reconnect); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reconnect); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reconnect); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); nodes[1].node.test_restore_channel_monitor(); check_added_monitors!(nodes[1], 1); let bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); @@ -1844,16 +1731,15 @@ fn first_message_on_recv_ordering() { // Route the first payment outbound, holding the last RAA for B until we are set up so that we // can deliver it and fail the monitor update. - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash_1).unwrap(); check_added_monitors!(nodes[0], 1); @@ -1862,41 +1748,36 @@ fn first_message_on_recv_ordering() { assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); check_added_monitors!(nodes[1], 1); let bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // Route the second payment, generating an update_add_htlc/commitment_signed - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[0], 1); @@ -1910,31 +1791,28 @@ fn first_message_on_recv_ordering() { // Deliver the final RAA for the first payment, which does not require a response. RAAs // generally require a commitment_signed, so the fact that we're expecting an opposite response // to the next message also tests resetting the delivery order. - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[1], 1); // Now deliver the update_add_htlc/commitment_signed for the second payment, which does need an // RAA/CS response, which should be generated when we call test_restore_channel_monitor (with // the appropriate HTLC acceptance). - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Previous monitor update failure prevented generation of RAA".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Previous monitor update failure prevented generation of RAA".to_string(), + 1, ); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); @@ -1945,23 +1823,20 @@ fn first_message_on_recv_ordering() { expect_payment_received!(nodes[1], payment_hash_1, 1000000); let bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_responses.1); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); @@ -1991,16 +1866,15 @@ fn test_monitor_update_fail_claim() { assert!(nodes[1].node.claim_funds(payment_preimage_1, 1_000_000)); check_added_monitors!(nodes[1], 1); - let route = nodes[2] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[2].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[2].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[2], 1); @@ -2012,30 +1886,28 @@ fn test_monitor_update_fail_claim() { let mut events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]); let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 0); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); commitment_signed_dance!(nodes[1], nodes[2], payment_event.commitment_msg, false, true); let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id()); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]); + nodes[2].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]); commitment_signed_dance!(nodes[2], nodes[1], bs_fail_update.commitment_signed, false, true); let msg_events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1); match msg_events[0] { - MessageSendEvent::PaymentFailureNetworkUpdate { - update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }, - } => { + MessageSendEvent::PaymentFailureNetworkUpdate { update: + msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref + msg, }, } => { assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id); assert_eq!(msg.contents.flags & 2, 2); // temp disabled }, @@ -2044,11 +1916,9 @@ fn test_monitor_update_fail_claim() { let events = nodes[2].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } = events[0] + if let Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } = events[0] { assert_eq!(payment_hash, payment_hash_2); assert!(!rejected_by_dest); @@ -2062,8 +1932,8 @@ fn test_monitor_update_fail_claim() { let bs_fulfill_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fulfill_htlc( - &nodes[1].node.get_our_node_id(), - &bs_fulfill_update.update_fulfill_htlcs[0], + &nodes[1].node.get_our_node_id(), + &bs_fulfill_update.update_fulfill_htlcs[0], ); commitment_signed_dance!(nodes[0], nodes[1], bs_fulfill_update.commitment_signed, false); @@ -2095,22 +1965,20 @@ fn test_monitor_update_on_pending_forwards() { check_added_monitors!(nodes[2], 1); let cs_fail_update = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail_update.update_fail_htlcs[0]); + nodes[1].node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail_update.update_fail_htlcs[0]); commitment_signed_dance!(nodes[1], nodes[2], cs_fail_update.commitment_signed, true, true); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - let route = nodes[2] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[2].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[2].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[2], 1); @@ -2118,9 +1986,8 @@ fn test_monitor_update_on_pending_forwards() { let mut events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]); commitment_signed_dance!(nodes[1], nodes[2], payment_event.commitment_msg, false); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); @@ -2128,9 +1995,9 @@ fn test_monitor_update_on_pending_forwards() { check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); @@ -2138,21 +2005,17 @@ fn test_monitor_update_on_pending_forwards() { check_added_monitors!(nodes[1], 1); let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]); - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_add_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]); + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_add_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 2); - if let Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } = events[0] + if let Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } = events[0] { assert_eq!(payment_hash, payment_hash_1); assert!(rejected_by_dest); @@ -2182,16 +2045,15 @@ fn monitor_update_claim_fail_no_response() { let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000); // Now start forwarding a second payment, skipping the last RAA so B is in AwaitingRAA - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[0], 1); @@ -2199,17 +2061,16 @@ fn monitor_update_claim_fail_no_response() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let payment_event = SendEvent::from_event(events.pop().unwrap()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); let as_raa = commitment_signed_dance!( - nodes[1], - nodes[0], - payment_event.commitment_msg, - false, - true, - false, - true + nodes[1], + nodes[0], + payment_event.commitment_msg, + false, + true, + false, + true ); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); @@ -2218,9 +2079,9 @@ fn monitor_update_claim_fail_no_response() { let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 0); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); @@ -2228,17 +2089,15 @@ fn monitor_update_claim_fail_no_response() { check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); expect_payment_received!(nodes[1], payment_hash_2, 1000000); let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false); let events = nodes[0].node.get_and_clear_pending_events(); @@ -2258,38 +2117,35 @@ fn monitor_update_claim_fail_no_response() { // Finally, note that !fail_on_signed is not possible with fail_on_generate && !restore_between_fails // confirm_a_first and restore_b_before_conf are wholly unrelated to earlier bools and // restore_b_before_conf has no meaning if !confirm_a_first -fn do_during_funding_monitor_fail( - fail_on_generate: bool, - restore_between_fails: bool, - fail_on_signed: bool, - confirm_a_first: bool, - restore_b_before_conf: bool, -) { +fn do_during_funding_monitor_fail(fail_on_generate: bool, + restore_between_fails: bool, + fail_on_signed: bool, + confirm_a_first: bool, + restore_b_before_conf: bool) { // Test that if the monitor update generated by funding_transaction_generated fails we continue // the channel setup happily after the update is restored. let mut nodes = create_network(2, &[None, None]); - nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 43) - .unwrap(); + nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 43) + .unwrap(); nodes[1].node.handle_open_channel( - &nodes[0].node.get_our_node_id(), - LocalFeatures::new(), - &get_event_msg!( - nodes[0], - MessageSendEvent::SendOpenChannel, - nodes[1].node.get_our_node_id() - ), + &nodes[0].node.get_our_node_id(), + LocalFeatures::new(), + &get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ), ); nodes[0].node.handle_accept_channel( - &nodes[1].node.get_our_node_id(), - LocalFeatures::new(), - &get_event_msg!( - nodes[1], - MessageSendEvent::SendAcceptChannel, - nodes[0].node.get_our_node_id() - ), + &nodes[1].node.get_our_node_id(), + LocalFeatures::new(), + &get_event_msg!( + nodes[1], + MessageSendEvent::SendAcceptChannel, + nodes[0].node.get_our_node_id() + ), ); let (temporary_channel_id, funding_tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 43); @@ -2297,19 +2153,18 @@ fn do_during_funding_monitor_fail( if fail_on_generate { *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); } - nodes[0] - .node - .funding_transaction_generated(&temporary_channel_id, funding_output); + nodes[0].node + .funding_transaction_generated(&temporary_channel_id, funding_output); check_added_monitors!(nodes[0], 1); *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure); nodes[1].node.handle_funding_created( - &nodes[0].node.get_our_node_id(), - &get_event_msg!( - nodes[0], - MessageSendEvent::SendFundingCreated, - nodes[1].node.get_our_node_id() - ), + &nodes[0].node.get_our_node_id(), + &get_event_msg!( + nodes[0], + MessageSendEvent::SendFundingCreated, + nodes[1].node.get_our_node_id() + ), ); check_added_monitors!(nodes[1], 1); @@ -2329,12 +2184,12 @@ fn do_during_funding_monitor_fail( assert!(fail_on_generate); // Somebody has to fail } nodes[0].node.handle_funding_signed( - &nodes[1].node.get_our_node_id(), - &get_event_msg!( - nodes[1], - MessageSendEvent::SendFundingSigned, - nodes[0].node.get_our_node_id() - ), + &nodes[1].node.get_our_node_id(), + &get_event_msg!( + nodes[1], + MessageSendEvent::SendFundingSigned, + nodes[0].node.get_our_node_id() + ), ); if fail_on_signed || !restore_between_fails { assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); @@ -2347,9 +2202,9 @@ fn do_during_funding_monitor_fail( check_added_monitors!(nodes[0], 0); } else { nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Failed to update ChannelMonitor".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Failed to update ChannelMonitor".to_string(), + 1, ); check_added_monitors!(nodes[0], 1); } @@ -2363,10 +2218,8 @@ fn do_during_funding_monitor_fail( let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { - Event::FundingBroadcastSafe { - ref funding_txo, - user_channel_id, - } => { + Event::FundingBroadcastSafe { ref funding_txo, + user_channel_id, } => { assert_eq!(user_channel_id, 43); assert_eq!(*funding_txo, funding_output); }, @@ -2375,26 +2228,26 @@ fn do_during_funding_monitor_fail( if confirm_a_first { confirm_transaction( - &nodes[0].block_notifier, - &nodes[0].chain_monitor, - &funding_tx, - funding_tx.version, + &nodes[0].block_notifier, + &nodes[0].chain_monitor, + &funding_tx, + funding_tx.version, ); nodes[1].node.handle_funding_locked( - &nodes[0].node.get_our_node_id(), - &get_event_msg!( - nodes[0], - MessageSendEvent::SendFundingLocked, - nodes[1].node.get_our_node_id() - ), + &nodes[0].node.get_our_node_id(), + &get_event_msg!( + nodes[0], + MessageSendEvent::SendFundingLocked, + nodes[1].node.get_our_node_id() + ), ); } else { assert!(!restore_b_before_conf); confirm_transaction( - &nodes[1].block_notifier, - &nodes[1].chain_monitor, - &funding_tx, - funding_tx.version, + &nodes[1].block_notifier, + &nodes[1].chain_monitor, + &funding_tx, + funding_tx.version, ); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); } @@ -2403,24 +2256,24 @@ fn do_during_funding_monitor_fail( nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, confirm_a_first), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, confirm_a_first), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); if !restore_b_before_conf { confirm_transaction( - &nodes[1].block_notifier, - &nodes[1].chain_monitor, - &funding_tx, - funding_tx.version, + &nodes[1].block_notifier, + &nodes[1].chain_monitor, + &funding_tx, + funding_tx.version, ); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); @@ -2432,39 +2285,33 @@ fn do_during_funding_monitor_fail( let (channel_id, (announcement, as_update, bs_update)) = if !confirm_a_first { nodes[0].node.handle_funding_locked( - &nodes[1].node.get_our_node_id(), - &get_event_msg!( - nodes[1], - MessageSendEvent::SendFundingLocked, - nodes[0].node.get_our_node_id() - ), + &nodes[1].node.get_our_node_id(), + &get_event_msg!( + nodes[1], + MessageSendEvent::SendFundingLocked, + nodes[0].node.get_our_node_id() + ), ); confirm_transaction( - &nodes[0].block_notifier, - &nodes[0].chain_monitor, - &funding_tx, - funding_tx.version, + &nodes[0].block_notifier, + &nodes[0].chain_monitor, + &funding_tx, + funding_tx.version, ); let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]); - ( - channel_id, - create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked), - ) + (channel_id, create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked)) } else { if restore_b_before_conf { confirm_transaction( - &nodes[1].block_notifier, - &nodes[1].chain_monitor, - &funding_tx, - funding_tx.version, + &nodes[1].block_notifier, + &nodes[1].chain_monitor, + &funding_tx, + funding_tx.version, ); } let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]); - ( - channel_id, - create_chan_between_nodes_with_value_b(&nodes[1], &nodes[0], &funding_locked), - ) + (channel_id, create_chan_between_nodes_with_value_b(&nodes[1], &nodes[0], &funding_locked)) }; for node in nodes.iter() { assert!(node.router.handle_channel_announcement(&announcement).unwrap()); diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 07abac29522..02dd7f1acf1 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -427,8 +427,8 @@ impl Channel { fn derive_our_dust_limit_satoshis(at_open_background_feerate: u64) -> u64 { cmp::max( - at_open_background_feerate * B_OUTPUT_PLUS_SPENDING_INPUT_WEIGHT / 1000, - 546, + at_open_background_feerate * B_OUTPUT_PLUS_SPENDING_INPUT_WEIGHT / 1000, + 546, ) //TODO } @@ -438,28 +438,23 @@ impl Channel { } // Constructors: - pub fn new_outbound( - fee_estimator: &FeeEstimator, - keys_provider: &Arc>, - their_node_id: PublicKey, - channel_value_satoshis: u64, - push_msat: u64, - user_id: u64, - logger: Arc, - config: &UserConfig, - ) -> Result, APIError> { + pub fn new_outbound(fee_estimator: &FeeEstimator, + keys_provider: &Arc>, + their_node_id: PublicKey, + channel_value_satoshis: u64, + push_msat: u64, + user_id: u64, + logger: Arc, + config: &UserConfig) + -> Result, APIError> { let chan_keys = keys_provider.get_channel_keys(false); if channel_value_satoshis >= MAX_FUNDING_SATOSHIS { - return Err(APIError::APIMisuseError { - err: "funding value > 2^24", - }); + return Err(APIError::APIMisuseError { err: "funding value > 2^24" }); } if push_msat > channel_value_satoshis * 1000 { - return Err(APIError::APIMisuseError { - err: "push value > channel value", - }); + return Err(APIError::APIMisuseError { err: "push value > channel value" }); } if config.own_channel_config.our_to_self_delay < BREAKDOWN_TIMEOUT { return Err(APIError::APIMisuseError { @@ -469,113 +464,110 @@ impl Channel { let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); if Channel::::get_our_channel_reserve_satoshis(channel_value_satoshis) - < Channel::::derive_our_dust_limit_satoshis(background_feerate) + < Channel::::derive_our_dust_limit_satoshis(background_feerate) { - return Err(APIError::FeeRateTooHigh { - err: format!( + return Err(APIError::FeeRateTooHigh { err: format!( "Not enough reserve above dust limit can be found at current fee rate({})", background_feerate ), - feerate: background_feerate, - }); + feerate: background_feerate }); } let feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal); let secp_ctx = Secp256k1::new(); let channel_monitor = ChannelMonitor::new( - chan_keys.funding_key(), - chan_keys.revocation_base_key(), - chan_keys.delayed_payment_base_key(), - chan_keys.htlc_base_key(), - chan_keys.payment_base_key(), - &keys_provider.get_shutdown_pubkey(), - config.own_channel_config.our_to_self_delay, - keys_provider.get_destination_script(), - logger.clone(), + chan_keys.funding_key(), + chan_keys.revocation_base_key(), + chan_keys.delayed_payment_base_key(), + chan_keys.htlc_base_key(), + chan_keys.payment_base_key(), + &keys_provider.get_shutdown_pubkey(), + config.own_channel_config.our_to_self_delay, + keys_provider.get_destination_script(), + logger.clone(), ); - Ok(Channel { - user_id, - config: config.channel_options.clone(), - - channel_id: keys_provider.get_channel_id(), - channel_state: ChannelState::OurInitSent as u32, - channel_outbound: true, - secp_ctx, - channel_value_satoshis, - - local_keys: chan_keys, - shutdown_pubkey: keys_provider.get_shutdown_pubkey(), - cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, - cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, - value_to_self_msat: channel_value_satoshis * 1000 - push_msat, - - pending_inbound_htlcs: Vec::new(), - pending_outbound_htlcs: Vec::new(), - holding_cell_htlc_updates: Vec::new(), - pending_update_fee: None, - holding_cell_update_fee: None, - next_local_htlc_id: 0, - next_remote_htlc_id: 0, - channel_update_count: 1, - - resend_order: RAACommitmentOrder::CommitmentFirst, - - monitor_pending_funding_locked: false, - monitor_pending_revoke_and_ack: false, - monitor_pending_commitment_signed: false, - monitor_pending_forwards: Vec::new(), - monitor_pending_failures: Vec::new(), - - #[cfg(debug_assertions)] - max_commitment_tx_output_local: ::std::sync::Mutex::new(( - channel_value_satoshis * 1000 - push_msat, - push_msat, - )), - #[cfg(debug_assertions)] - max_commitment_tx_output_remote: ::std::sync::Mutex::new(( - channel_value_satoshis * 1000 - push_msat, - push_msat, - )), - - last_sent_closing_fee: None, - - funding_tx_confirmed_in: None, - short_channel_id: None, - last_block_connected: Default::default(), - funding_tx_confirmations: 0, - - feerate_per_kw: feerate, - their_dust_limit_satoshis: 0, - our_dust_limit_satoshis: Channel::::derive_our_dust_limit_satoshis(background_feerate), - their_max_htlc_value_in_flight_msat: 0, - their_channel_reserve_satoshis: 0, - their_htlc_minimum_msat: 0, - our_htlc_minimum_msat: Channel::::derive_our_htlc_minimum_msat(feerate), - their_to_self_delay: 0, - our_to_self_delay: config.own_channel_config.our_to_self_delay, - their_max_accepted_htlcs: 0, - minimum_depth: 0, // Filled in in accept_channel - - their_funding_pubkey: None, - their_revocation_basepoint: None, - their_payment_basepoint: None, - their_delayed_payment_basepoint: None, - their_htlc_basepoint: None, - their_cur_commitment_point: None, - - their_prev_commitment_point: None, - their_node_id, - - their_shutdown_scriptpubkey: None, - - channel_monitor, - - network_sync: UpdateStatus::Fresh, - - logger, - }) + Ok(Channel { user_id, + config: config.channel_options.clone(), + + channel_id: keys_provider.get_channel_id(), + channel_state: ChannelState::OurInitSent as u32, + channel_outbound: true, + secp_ctx, + channel_value_satoshis, + + local_keys: chan_keys, + shutdown_pubkey: keys_provider.get_shutdown_pubkey(), + cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, + cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, + value_to_self_msat: channel_value_satoshis * 1000 - push_msat, + + pending_inbound_htlcs: Vec::new(), + pending_outbound_htlcs: Vec::new(), + holding_cell_htlc_updates: Vec::new(), + pending_update_fee: None, + holding_cell_update_fee: None, + next_local_htlc_id: 0, + next_remote_htlc_id: 0, + channel_update_count: 1, + + resend_order: RAACommitmentOrder::CommitmentFirst, + + monitor_pending_funding_locked: false, + monitor_pending_revoke_and_ack: false, + monitor_pending_commitment_signed: false, + monitor_pending_forwards: Vec::new(), + monitor_pending_failures: Vec::new(), + + #[cfg(debug_assertions)] + max_commitment_tx_output_local: ::std::sync::Mutex::new(( + channel_value_satoshis * 1000 - push_msat, + push_msat, + )), + #[cfg(debug_assertions)] + max_commitment_tx_output_remote: ::std::sync::Mutex::new(( + channel_value_satoshis * 1000 - push_msat, + push_msat, + )), + + last_sent_closing_fee: None, + + funding_tx_confirmed_in: None, + short_channel_id: None, + last_block_connected: Default::default(), + funding_tx_confirmations: 0, + + feerate_per_kw: feerate, + their_dust_limit_satoshis: 0, + our_dust_limit_satoshis: + Channel::::derive_our_dust_limit_satoshis(background_feerate), + their_max_htlc_value_in_flight_msat: 0, + their_channel_reserve_satoshis: 0, + their_htlc_minimum_msat: 0, + our_htlc_minimum_msat: Channel::::derive_our_htlc_minimum_msat(feerate), + their_to_self_delay: 0, + our_to_self_delay: config.own_channel_config.our_to_self_delay, + their_max_accepted_htlcs: 0, + minimum_depth: 0, // Filled in in accept_channel + + their_funding_pubkey: None, + their_revocation_basepoint: None, + their_payment_basepoint: None, + their_delayed_payment_basepoint: None, + their_htlc_basepoint: None, + their_cur_commitment_point: None, + + their_prev_commitment_point: None, + their_node_id, + + their_shutdown_scriptpubkey: None, + + channel_monitor, + + network_sync: UpdateStatus::Fresh, + + logger }) } fn check_remote_fee(fee_estimator: &FeeEstimator, feerate_per_kw: u32) -> Result<(), ChannelError> { @@ -590,16 +582,15 @@ 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: &FeeEstimator, - keys_provider: &Arc>, - their_node_id: PublicKey, - their_local_features: LocalFeatures, - msg: &msgs::OpenChannel, - user_id: u64, - logger: Arc, - config: &UserConfig, - ) -> Result, ChannelError> { + pub fn new_from_req(fee_estimator: &FeeEstimator, + keys_provider: &Arc>, + their_node_id: PublicKey, + their_local_features: LocalFeatures, + msg: &msgs::OpenChannel, + user_id: u64, + logger: Arc, + config: &UserConfig) + -> Result, ChannelError> { let chan_keys = keys_provider.get_channel_keys(true); let mut local_config = (*config).channel_options.clone(); @@ -631,11 +622,9 @@ impl Channel { Channel::::check_remote_fee(fee_estimator, msg.feerate_per_kw)?; if msg.to_self_delay > config.peer_channel_config_limits.their_to_self_delay - || msg.to_self_delay > MAX_LOCAL_BREAKDOWN_TIMEOUT + || msg.to_self_delay > MAX_LOCAL_BREAKDOWN_TIMEOUT { - return Err(ChannelError::Close( - "They wanted our payments to be delayed by a needlessly long period", - )); + return Err(ChannelError::Close("They wanted our payments to be delayed by a needlessly long period")); } if msg.max_accepted_htlcs < 1 { return Err(ChannelError::Close("0 max_accpted_htlcs makes for a useless channel")); @@ -646,39 +635,25 @@ impl Channel { // Now check against optional parameters as set by config... if msg.funding_satoshis < config.peer_channel_config_limits.min_funding_satoshis { - return Err(ChannelError::Close( - "funding satoshis is less than the user specified limit", - )); + return Err(ChannelError::Close("funding satoshis is less than the user specified limit")); } if msg.htlc_minimum_msat > config.peer_channel_config_limits.max_htlc_minimum_msat { - return Err(ChannelError::Close( - "htlc minimum msat is higher than the user specified limit", - )); + return Err(ChannelError::Close("htlc minimum msat is higher than the user specified limit")); } if msg.max_htlc_value_in_flight_msat < config.peer_channel_config_limits.min_max_htlc_value_in_flight_msat { - return Err(ChannelError::Close( - "max htlc value in flight msat is less than the user specified limit", - )); + return Err(ChannelError::Close("max htlc value in flight msat is less than the user specified limit")); } if msg.channel_reserve_satoshis > config.peer_channel_config_limits.max_channel_reserve_satoshis { - return Err(ChannelError::Close( - "channel reserve satoshis is higher than the user specified limit", - )); + return Err(ChannelError::Close("channel reserve satoshis is higher than the user specified limit")); } if msg.max_accepted_htlcs < config.peer_channel_config_limits.min_max_accepted_htlcs { - return Err(ChannelError::Close( - "max accepted htlcs is less than the user specified limit", - )); + return Err(ChannelError::Close("max accepted htlcs is less than the user specified limit")); } if msg.dust_limit_satoshis < config.peer_channel_config_limits.min_dust_limit_satoshis { - return Err(ChannelError::Close( - "dust limit satoshis is less than the user specified limit", - )); + return Err(ChannelError::Close("dust limit satoshis is less than the user specified limit")); } if msg.dust_limit_satoshis > config.peer_channel_config_limits.max_dust_limit_satoshis { - return Err(ChannelError::Close( - "dust limit satoshis is greater than the user specified limit", - )); + return Err(ChannelError::Close("dust limit satoshis is greater than the user specified limit")); } // Convert things into internal flags and prep our state: @@ -713,31 +688,27 @@ impl Channel { // for full fee payment let funders_amount_msat = msg.funding_satoshis * 1000 - msg.push_msat; if funders_amount_msat < background_feerate * COMMITMENT_TX_BASE_WEIGHT { - return Err(ChannelError::Close( - "Insufficient funding amount for initial commitment", - )); + return Err(ChannelError::Close("Insufficient funding amount for initial commitment")); } let to_local_msat = msg.push_msat; let to_remote_msat = funders_amount_msat - background_feerate * COMMITMENT_TX_BASE_WEIGHT; if to_local_msat <= msg.channel_reserve_satoshis * 1000 && to_remote_msat <= our_channel_reserve_satoshis * 1000 { - return Err(ChannelError::Close( - "Insufficient funding amount for initial commitment", - )); + return Err(ChannelError::Close("Insufficient funding amount for initial commitment")); } let secp_ctx = Secp256k1::new(); let channel_monitor = ChannelMonitor::new( - chan_keys.funding_key(), - chan_keys.revocation_base_key(), - chan_keys.delayed_payment_base_key(), - chan_keys.htlc_base_key(), - chan_keys.payment_base_key(), - &keys_provider.get_shutdown_pubkey(), - config.own_channel_config.our_to_self_delay, - keys_provider.get_destination_script(), - logger.clone(), + chan_keys.funding_key(), + chan_keys.revocation_base_key(), + chan_keys.delayed_payment_base_key(), + chan_keys.htlc_base_key(), + chan_keys.payment_base_key(), + &keys_provider.get_shutdown_pubkey(), + config.own_channel_config.our_to_self_delay, + keys_provider.get_destination_script(), + logger.clone(), ); let their_shutdown_scriptpubkey = if their_local_features.supports_upfront_shutdown_script() { @@ -765,100 +736,100 @@ impl Channel { None }; - let mut chan = Channel { - user_id, - config: local_config, - - channel_id: msg.temporary_channel_id, - channel_state: (ChannelState::OurInitSent as u32) | (ChannelState::TheirInitSent as u32), - channel_outbound: false, - secp_ctx, - - local_keys: chan_keys, - shutdown_pubkey: keys_provider.get_shutdown_pubkey(), - cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, - cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, - value_to_self_msat: msg.push_msat, - - pending_inbound_htlcs: Vec::new(), - pending_outbound_htlcs: Vec::new(), - holding_cell_htlc_updates: Vec::new(), - pending_update_fee: None, - holding_cell_update_fee: None, - next_local_htlc_id: 0, - next_remote_htlc_id: 0, - channel_update_count: 1, - - resend_order: RAACommitmentOrder::CommitmentFirst, - - monitor_pending_funding_locked: false, - monitor_pending_revoke_and_ack: false, - monitor_pending_commitment_signed: false, - monitor_pending_forwards: Vec::new(), - monitor_pending_failures: Vec::new(), - - #[cfg(debug_assertions)] - max_commitment_tx_output_local: ::std::sync::Mutex::new(( - msg.push_msat, - msg.funding_satoshis * 1000 - msg.push_msat, - )), - #[cfg(debug_assertions)] - max_commitment_tx_output_remote: ::std::sync::Mutex::new(( - msg.push_msat, - msg.funding_satoshis * 1000 - msg.push_msat, - )), - - last_sent_closing_fee: None, - - funding_tx_confirmed_in: None, - short_channel_id: None, - last_block_connected: Default::default(), - funding_tx_confirmations: 0, - - feerate_per_kw: msg.feerate_per_kw as u64, - channel_value_satoshis: msg.funding_satoshis, - their_dust_limit_satoshis: msg.dust_limit_satoshis, - our_dust_limit_satoshis, - their_max_htlc_value_in_flight_msat: cmp::min( - msg.max_htlc_value_in_flight_msat, - msg.funding_satoshis * 1000, - ), - their_channel_reserve_satoshis: msg.channel_reserve_satoshis, - their_htlc_minimum_msat: msg.htlc_minimum_msat, - our_htlc_minimum_msat: Channel::::derive_our_htlc_minimum_msat(msg.feerate_per_kw as u64), - their_to_self_delay: msg.to_self_delay, - our_to_self_delay: config.own_channel_config.our_to_self_delay, - their_max_accepted_htlcs: msg.max_accepted_htlcs, - minimum_depth: config.own_channel_config.minimum_depth, + let mut chan = Channel { user_id, + config: local_config, + + channel_id: msg.temporary_channel_id, + channel_state: (ChannelState::OurInitSent as u32) + | (ChannelState::TheirInitSent as u32), + channel_outbound: false, + secp_ctx, + + local_keys: chan_keys, + shutdown_pubkey: keys_provider.get_shutdown_pubkey(), + cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, + cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER, + value_to_self_msat: msg.push_msat, + + pending_inbound_htlcs: Vec::new(), + pending_outbound_htlcs: Vec::new(), + holding_cell_htlc_updates: Vec::new(), + pending_update_fee: None, + holding_cell_update_fee: None, + next_local_htlc_id: 0, + next_remote_htlc_id: 0, + channel_update_count: 1, + + resend_order: RAACommitmentOrder::CommitmentFirst, + + monitor_pending_funding_locked: false, + monitor_pending_revoke_and_ack: false, + monitor_pending_commitment_signed: false, + monitor_pending_forwards: Vec::new(), + monitor_pending_failures: Vec::new(), + + #[cfg(debug_assertions)] + max_commitment_tx_output_local: ::std::sync::Mutex::new(( + msg.push_msat, + msg.funding_satoshis * 1000 - msg.push_msat, + )), + #[cfg(debug_assertions)] + max_commitment_tx_output_remote: ::std::sync::Mutex::new(( + msg.push_msat, + msg.funding_satoshis * 1000 - msg.push_msat, + )), + + last_sent_closing_fee: None, + + funding_tx_confirmed_in: None, + short_channel_id: None, + last_block_connected: Default::default(), + funding_tx_confirmations: 0, + + feerate_per_kw: msg.feerate_per_kw as u64, + channel_value_satoshis: msg.funding_satoshis, + their_dust_limit_satoshis: msg.dust_limit_satoshis, + our_dust_limit_satoshis, + their_max_htlc_value_in_flight_msat: cmp::min( + msg.max_htlc_value_in_flight_msat, + msg.funding_satoshis * 1000, + ), + their_channel_reserve_satoshis: msg.channel_reserve_satoshis, + their_htlc_minimum_msat: msg.htlc_minimum_msat, + our_htlc_minimum_msat: + Channel::::derive_our_htlc_minimum_msat(msg.feerate_per_kw as u64), + their_to_self_delay: msg.to_self_delay, + our_to_self_delay: config.own_channel_config.our_to_self_delay, + their_max_accepted_htlcs: msg.max_accepted_htlcs, + minimum_depth: config.own_channel_config.minimum_depth, - their_funding_pubkey: Some(msg.funding_pubkey), - their_revocation_basepoint: Some(msg.revocation_basepoint), - their_payment_basepoint: Some(msg.payment_basepoint), - their_delayed_payment_basepoint: Some(msg.delayed_payment_basepoint), - their_htlc_basepoint: Some(msg.htlc_basepoint), - their_cur_commitment_point: Some(msg.first_per_commitment_point), + their_funding_pubkey: Some(msg.funding_pubkey), + their_revocation_basepoint: Some(msg.revocation_basepoint), + their_payment_basepoint: Some(msg.payment_basepoint), + their_delayed_payment_basepoint: Some(msg.delayed_payment_basepoint), + their_htlc_basepoint: Some(msg.htlc_basepoint), + their_cur_commitment_point: Some(msg.first_per_commitment_point), - their_prev_commitment_point: None, - their_node_id, + their_prev_commitment_point: None, + their_node_id, - their_shutdown_scriptpubkey, + their_shutdown_scriptpubkey, - channel_monitor, + channel_monitor, - network_sync: UpdateStatus::Fresh, + network_sync: UpdateStatus::Fresh, - logger, - }; + logger }; let obscure_factor = chan.get_commitment_transaction_number_obscure_factor(); let funding_redeemscript = chan.get_funding_redeemscript(); chan.channel_monitor.set_basic_channel_info( - &msg.htlc_basepoint, - &msg.delayed_payment_basepoint, - msg.to_self_delay, - funding_redeemscript, - msg.funding_satoshis, - obscure_factor, + &msg.htlc_basepoint, + &msg.delayed_payment_basepoint, + msg.to_self_delay, + funding_redeemscript, + msg.funding_satoshis, + obscure_factor, ); Ok(chan) @@ -913,25 +884,26 @@ impl Channel { /// Note that below-dust HTLCs are included in the third return value, but not the second, and /// sources are provided only for outbound HTLCs in the third return value. #[inline] - fn build_commitment_transaction( - &self, - commitment_number: u64, - keys: &TxCreationKeys, - local: bool, - generated_by_local: bool, - feerate_per_kw: u64, - ) -> (Transaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) { + fn build_commitment_transaction(&self, + commitment_number: u64, + keys: &TxCreationKeys, + local: bool, + generated_by_local: bool, + feerate_per_kw: u64) + -> (Transaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) { let obscured_commitment_transaction_number = self.get_commitment_transaction_number_obscure_factor() ^ (INITIAL_COMMITMENT_NUMBER - commitment_number); let txins = { let mut ins: Vec = Vec::new(); - ins.push(TxIn { - previous_output: self.channel_monitor.get_funding_txo().unwrap().into_bitcoin_outpoint(), - script_sig: Script::new(), - sequence: ((0x80 as u32) << 8 * 3) | ((obscured_commitment_transaction_number >> 3 * 8) as u32), - witness: Vec::new(), - }); + ins.push(TxIn { previous_output: self.channel_monitor + .get_funding_txo() + .unwrap() + .into_bitcoin_outpoint(), + script_sig: Script::new(), + sequence: ((0x80 as u32) << 8 * 3) + | ((obscured_commitment_transaction_number >> 3 * 8) as u32), + witness: Vec::new(), }); ins }; @@ -1013,12 +985,12 @@ impl Channel { remote_htlc_total_msat += htlc.amount_msat; } else { log_trace!( - self, - " ...not including inbound HTLC {} (hash {}) with value {} due to state ({})", - htlc.htlc_id, - log_bytes!(htlc.payment_hash.0), - htlc.amount_msat, - state_name + self, + " ...not including inbound HTLC {} (hash {}) with value {} due to state ({})", + htlc.htlc_id, + log_bytes!(htlc.payment_hash.0), + htlc.amount_msat, + state_name ); match &htlc.state { &InboundHTLCState::LocalRemoved(ref reason) => { @@ -1049,12 +1021,12 @@ impl Channel { local_htlc_total_msat += htlc.amount_msat; } else { log_trace!( - self, - " ...not including outbound HTLC {} (hash {}) with value {} due to state ({})", - htlc.htlc_id, - log_bytes!(htlc.payment_hash.0), - htlc.amount_msat, - state_name + self, + " ...not including outbound HTLC {} (hash {}) with value {} due to state ({})", + htlc.htlc_id, + log_bytes!(htlc.payment_hash.0), + htlc.amount_msat, + state_name ); match htlc.state { OutboundHTLCState::AwaitingRemoteRevokeToRemove(None) @@ -1079,9 +1051,9 @@ impl Channel { // "violate" their reserve value by couting those against it. Thus, we have to convert // everything to i64 before subtracting as otherwise we can overflow. let value_to_remote_msat: i64 = (self.channel_value_satoshis * 1000) as i64 - - (self.value_to_self_msat as i64) - - (remote_htlc_total_msat as i64) - - value_to_self_msat_offset; + - (self.value_to_self_msat as i64) + - (remote_htlc_total_msat as i64) + - value_to_self_msat_offset; assert!(value_to_remote_msat >= 0); #[cfg(debug_assertions)] @@ -1094,14 +1066,15 @@ impl Channel { self.max_commitment_tx_output_remote.lock().unwrap() }; debug_assert!( - max_commitment_tx_output.0 <= value_to_self_msat as u64 - || value_to_self_msat / 1000 >= self.their_channel_reserve_satoshis as i64 + max_commitment_tx_output.0 <= value_to_self_msat as u64 + || value_to_self_msat / 1000 >= self.their_channel_reserve_satoshis as i64 ); max_commitment_tx_output.0 = cmp::max(max_commitment_tx_output.0, value_to_self_msat as u64); debug_assert!( - max_commitment_tx_output.1 <= value_to_remote_msat as u64 - || value_to_remote_msat / 1000 - >= Channel::::get_our_channel_reserve_satoshis(self.channel_value_satoshis) as i64 + max_commitment_tx_output.1 <= value_to_remote_msat as u64 + || value_to_remote_msat / 1000 + >= Channel::::get_our_channel_reserve_satoshis(self.channel_value_satoshis) + as i64 ); max_commitment_tx_output.1 = cmp::max(max_commitment_tx_output.1, value_to_remote_msat as u64); } @@ -1109,15 +1082,9 @@ impl Channel { let total_fee: u64 = feerate_per_kw * (COMMITMENT_TX_BASE_WEIGHT + (txouts.len() as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000; let (value_to_self, value_to_remote) = if self.channel_outbound { - ( - value_to_self_msat / 1000 - total_fee as i64, - value_to_remote_msat / 1000, - ) + (value_to_self_msat / 1000 - total_fee as i64, value_to_remote_msat / 1000) } else { - ( - value_to_self_msat / 1000, - value_to_remote_msat / 1000 - total_fee as i64, - ) + (value_to_self_msat / 1000, value_to_remote_msat / 1000 - total_fee as i64) }; let value_to_a = if local { value_to_self } else { value_to_remote }; @@ -1125,44 +1092,38 @@ impl Channel { if value_to_a >= (dust_limit_satoshis as i64) { log_trace!( - self, - " ...including {} output with value {}", - if local { "to_local" } else { "to_remote" }, - value_to_a + self, + " ...including {} output with value {}", + if local { "to_local" } else { "to_remote" }, + value_to_a ); txouts.push(( - TxOut { - script_pubkey: chan_utils::get_revokeable_redeemscript( - &keys.revocation_key, - if local { - self.their_to_self_delay - } else { - self.our_to_self_delay - }, - &keys.a_delayed_payment_key, - ) - .to_v0_p2wsh(), - value: value_to_a as u64, - }, + TxOut { script_pubkey: chan_utils::get_revokeable_redeemscript( + &keys.revocation_key, + if local { + self.their_to_self_delay + } else { + self.our_to_self_delay + }, + &keys.a_delayed_payment_key, + ).to_v0_p2wsh(), + value: value_to_a as u64, }, None, )); } if value_to_b >= (dust_limit_satoshis as i64) { log_trace!( - self, - " ...including {} output with value {}", - if local { "to_remote" } else { "to_local" }, - value_to_b + self, + " ...including {} output with value {}", + if local { "to_remote" } else { "to_local" }, + value_to_b ); txouts.push(( - TxOut { - script_pubkey: Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&Hash160::hash(&keys.b_payment_key.serialize())[..]) - .into_script(), - value: value_to_b as u64, - }, + TxOut { script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&Hash160::hash(&keys.b_payment_key.serialize())[..]) + .into_script(), + value: value_to_b as u64, }, None, )); } @@ -1170,14 +1131,13 @@ impl Channel { transaction_utils::sort_outputs(&mut txouts, |a, b| { if let &Some(ref a_htlc) = a { if let &Some(ref b_htlc) = b { - a_htlc - .0 - .cltv_expiry - .cmp(&b_htlc.0.cltv_expiry) - // Note that due to hash collisions, we have to have a fallback comparison - // here for fuzztarget mode (otherwise at least chanmon_fail_consistency - // may fail)! - .then(a_htlc.0.payment_hash.0.cmp(&b_htlc.0.payment_hash.0)) + a_htlc.0 + .cltv_expiry + .cmp(&b_htlc.0.cltv_expiry) + // Note that due to hash collisions, we have to have a fallback comparison + // here for fuzztarget mode (otherwise at least chanmon_fail_consistency + // may fail)! + .then(a_htlc.0.payment_hash.0.cmp(&b_htlc.0.payment_hash.0)) // For non-HTLC outputs, if they're copying our SPK we don't really care if we // close the channel due to mismatches - they're doing something dumb: } else { @@ -1201,47 +1161,44 @@ impl Channel { let non_dust_htlc_count = htlcs_included.len(); htlcs_included.append(&mut included_dust_htlcs); - ( - Transaction { - version: 2, - lock_time: ((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32), - input: txins, - output: outputs, - }, - non_dust_htlc_count, - htlcs_included, - ) + (Transaction { version: 2, + lock_time: ((0x20 as u32) << 8 * 3) + | ((obscured_commitment_transaction_number & 0xffffffu64) as u32), + input: txins, + output: outputs }, + non_dust_htlc_count, + htlcs_included) } #[inline] fn get_closing_scriptpubkey(&self) -> Script { let our_channel_close_key_hash = Hash160::hash(&self.shutdown_pubkey.serialize()); - Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&our_channel_close_key_hash[..]) - .into_script() + Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&our_channel_close_key_hash[..]) + .into_script() } #[inline] fn get_closing_transaction_weight(a_scriptpubkey: &Script, b_scriptpubkey: &Script) -> u64 { (4 + 1 + 36 + 4 + 1 + 1 + 2 * (8 + 1) + 4 + a_scriptpubkey.len() as u64 + b_scriptpubkey.len() as u64) * 4 - + 2 + 1 + 1 + 2 * (1 + 72) + + 2 + 1 + 1 + + 2 * (1 + 72) } #[inline] - fn build_closing_transaction( - &self, - proposed_total_fee_satoshis: u64, - skip_remote_output: bool, - ) -> (Transaction, u64) { + fn build_closing_transaction(&self, + proposed_total_fee_satoshis: u64, + skip_remote_output: bool) + -> (Transaction, u64) { let txins = { let mut ins: Vec = Vec::new(); - ins.push(TxIn { - previous_output: self.channel_monitor.get_funding_txo().unwrap().into_bitcoin_outpoint(), - script_sig: Script::new(), - sequence: 0xffffffff, - witness: Vec::new(), - }); + ins.push(TxIn { previous_output: self.channel_monitor + .get_funding_txo() + .unwrap() + .into_bitcoin_outpoint(), + script_sig: Script::new(), + sequence: 0xffffffff, + witness: Vec::new(), }); ins }; @@ -1251,17 +1208,17 @@ impl Channel { let mut total_fee_satoshis = proposed_total_fee_satoshis; let value_to_self: i64 = (self.value_to_self_msat as i64) / 1000 - - if self.channel_outbound { - total_fee_satoshis as i64 - } else { - 0 - }; + - if self.channel_outbound { + total_fee_satoshis as i64 + } else { + 0 + }; let value_to_remote: i64 = ((self.channel_value_satoshis * 1000 - self.value_to_self_msat) as i64 / 1000) - - if self.channel_outbound { - 0 - } else { - total_fee_satoshis as i64 - }; + - if self.channel_outbound { + 0 + } else { + total_fee_satoshis as i64 + }; if value_to_self < 0 { assert!(self.channel_outbound); @@ -1273,20 +1230,16 @@ impl Channel { if !skip_remote_output && value_to_remote as u64 > self.our_dust_limit_satoshis { txouts.push(( - TxOut { - script_pubkey: self.their_shutdown_scriptpubkey.clone().unwrap(), - value: value_to_remote as u64, - }, + TxOut { script_pubkey: self.their_shutdown_scriptpubkey.clone().unwrap(), + value: value_to_remote as u64, }, (), )); } if value_to_self as u64 > self.our_dust_limit_satoshis { txouts.push(( - TxOut { - script_pubkey: self.get_closing_scriptpubkey(), - value: value_to_self as u64, - }, + TxOut { script_pubkey: self.get_closing_scriptpubkey(), + value: value_to_self as u64, }, (), )); } @@ -1298,15 +1251,11 @@ impl Channel { outputs.push(out.0); } - ( - Transaction { - version: 2, - lock_time: 0, - input: txins, - output: outputs, - }, - total_fee_satoshis, - ) + (Transaction { version: 2, + lock_time: 0, + input: txins, + output: outputs }, + total_fee_satoshis) } #[inline] @@ -1323,16 +1272,16 @@ impl Channel { let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.htlc_base_key()); Ok(secp_check!( - TxCreationKeys::new( - &self.secp_ctx, - &per_commitment_point, - &delayed_payment_base, - &htlc_basepoint, - &self.their_revocation_basepoint.unwrap(), - &self.their_payment_basepoint.unwrap(), - &self.their_htlc_basepoint.unwrap() - ), - "Local tx keys generation got bogus keys" + TxCreationKeys::new( + &self.secp_ctx, + &per_commitment_point, + &delayed_payment_base, + &htlc_basepoint, + &self.their_revocation_basepoint.unwrap(), + &self.their_payment_basepoint.unwrap(), + &self.their_htlc_basepoint.unwrap() + ), + "Local tx keys generation got bogus keys" )) } @@ -1348,16 +1297,16 @@ impl Channel { let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.htlc_base_key()); Ok(secp_check!( - TxCreationKeys::new( - &self.secp_ctx, - &self.their_cur_commitment_point.unwrap(), - &self.their_delayed_payment_basepoint.unwrap(), - &self.their_htlc_basepoint.unwrap(), - &revocation_basepoint, - &payment_basepoint, - &htlc_basepoint - ), - "Remote tx keys generation got bogus keys" + TxCreationKeys::new( + &self.secp_ctx, + &self.their_cur_commitment_point.unwrap(), + &self.their_delayed_payment_basepoint.unwrap(), + &self.their_htlc_basepoint.unwrap(), + &revocation_basepoint, + &payment_basepoint, + &htlc_basepoint + ), + "Remote tx keys generation got bogus keys" )) } @@ -1367,16 +1316,14 @@ impl Channel { pub fn get_funding_redeemscript(&self) -> Script { let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2); let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()).serialize(); - let their_funding_key = self - .their_funding_pubkey - .expect("get_funding_redeemscript only allowed after accept_channel") - .serialize(); + let their_funding_key = self.their_funding_pubkey + .expect("get_funding_redeemscript only allowed after accept_channel") + .serialize(); if our_funding_key[..] < their_funding_key[..] { builder.push_slice(&our_funding_key).push_slice(&their_funding_key) } else { builder.push_slice(&their_funding_key).push_slice(&our_funding_key) - } - .push_opcode(opcodes::all::OP_PUSHNUM_2) + }.push_opcode(opcodes::all::OP_PUSHNUM_2) .push_opcode(opcodes::all::OP_CHECKMULTISIG) .into_script() } @@ -1384,36 +1331,34 @@ impl Channel { /// Builds the htlc-success or htlc-timeout transaction which spends a given HTLC output /// @local is used only to convert relevant internal structures which refer to remote vs local /// to decide value of outputs and direction of HTLCs. - fn build_htlc_transaction( - &self, - prev_hash: &Sha256dHash, - htlc: &HTLCOutputInCommitment, - local: bool, - keys: &TxCreationKeys, - feerate_per_kw: u64, - ) -> Transaction { + fn build_htlc_transaction(&self, + prev_hash: &Sha256dHash, + htlc: &HTLCOutputInCommitment, + local: bool, + keys: &TxCreationKeys, + feerate_per_kw: u64) + -> Transaction { chan_utils::build_htlc_transaction( - prev_hash, - feerate_per_kw, - if local { - self.their_to_self_delay - } else { - self.our_to_self_delay - }, - htlc, - &keys.a_delayed_payment_key, - &keys.revocation_key, + prev_hash, + feerate_per_kw, + if local { + self.their_to_self_delay + } else { + self.our_to_self_delay + }, + htlc, + &keys.a_delayed_payment_key, + &keys.revocation_key, ) } /// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made. /// In such cases we debug_assert!(false) and return an IgnoreError. Thus, will always return /// Ok(_) if debug assertions are turned on and preconditions are met. - fn get_update_fulfill_htlc( - &mut self, - htlc_id_arg: u64, - payment_preimage_arg: PaymentPreimage, - ) -> Result<(Option, Option), ChannelError> { + fn get_update_fulfill_htlc(&mut self, + htlc_id_arg: u64, + payment_preimage_arg: PaymentPreimage) + -> Result<(Option, Option), ChannelError> { // Either ChannelFunded got set (which means it won't be unset) or there is no way any // caller thought we could have something claimed (cause we wouldn't have accepted in an // incoming HTLC anyway). If we got to ShutdownComplete, callers aren't allowed to call us, @@ -1444,8 +1389,8 @@ impl Channel { }, _ => { debug_assert!( - false, - "Have an inbound HTLC we tried to claim before it was fully committed to" + false, + "Have an inbound HTLC we tried to claim before it was fully committed to" ); // Don't return in release mode here so that we can update channel_monitor }, @@ -1455,9 +1400,7 @@ impl Channel { } } if pending_idx == std::usize::MAX { - return Err(ChannelError::Ignore( - "Unable to find a pending HTLC which matched the given HTLC ID", - )); + return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID")); } // Now update local state: @@ -1465,13 +1408,13 @@ impl Channel { // We have to put the payment_preimage in the channel_monitor right away here to ensure we // can claim it even if the channel hits the chain before we see their next commitment. self.channel_monitor - .provide_payment_preimage(&payment_hash_calc, &payment_preimage_arg); + .provide_payment_preimage(&payment_hash_calc, &payment_preimage_arg); if (self.channel_state - & (ChannelState::AwaitingRemoteRevoke as u32 - | ChannelState::PeerDisconnected as u32 - | ChannelState::MonitorUpdateFailed as u32)) - != 0 + & (ChannelState::AwaitingRemoteRevoke as u32 + | ChannelState::PeerDisconnected as u32 + | ChannelState::MonitorUpdateFailed as u32)) + != 0 { for pending_update in self.holding_cell_htlc_updates.iter() { match pending_update { @@ -1483,9 +1426,9 @@ impl Channel { &HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => { if htlc_id_arg == htlc_id { log_warn!( - self, - "Have preimage and want to fulfill HTLC with pending failure against channel {}", - log_bytes!(self.channel_id()) + self, + "Have preimage and want to fulfill HTLC with pending failure against channel {}", + log_bytes!(self.channel_id()) ); // TODO: We may actually be able to switch to a fulfill here, though its // rare enough it may not be worth the complexity burden. @@ -1496,14 +1439,13 @@ impl Channel { } } log_trace!( - self, - "Adding HTLC claim to holding_cell! Current state: {}", - self.channel_state + self, + "Adding HTLC claim to holding_cell! Current state: {}", + self.channel_state ); - self.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::ClaimHTLC { - payment_preimage: payment_preimage_arg, - htlc_id: htlc_id_arg, - }); + self.holding_cell_htlc_updates + .push(HTLCUpdateAwaitingACK::ClaimHTLC { payment_preimage: payment_preimage_arg, + htlc_id: htlc_id_arg }); return Ok((None, Some(self.channel_monitor.clone()))); } @@ -1512,41 +1454,31 @@ impl Channel { if let InboundHTLCState::Committed = htlc.state { } else { debug_assert!( - false, - "Have an inbound HTLC we tried to claim before it was fully committed to" + false, + "Have an inbound HTLC we tried to claim before it was fully committed to" ); return Ok((None, Some(self.channel_monitor.clone()))); } log_trace!( - self, - "Upgrading HTLC {} to LocalRemoved with a Fulfill!", - log_bytes!(htlc.payment_hash.0) + self, + "Upgrading HTLC {} to LocalRemoved with a Fulfill!", + log_bytes!(htlc.payment_hash.0) ); htlc.state = InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill(payment_preimage_arg.clone())); } - Ok(( - Some(msgs::UpdateFulfillHTLC { - channel_id: self.channel_id(), - htlc_id: htlc_id_arg, - payment_preimage: payment_preimage_arg, - }), - Some(self.channel_monitor.clone()), - )) + Ok((Some(msgs::UpdateFulfillHTLC { channel_id: self.channel_id(), + htlc_id: htlc_id_arg, + payment_preimage: payment_preimage_arg }), + Some(self.channel_monitor.clone()))) } pub fn get_update_fulfill_htlc_and_commit( &mut self, htlc_id: u64, - payment_preimage: PaymentPreimage, - ) -> Result< - ( - Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)>, - Option, - ), - ChannelError, - > { + payment_preimage: PaymentPreimage) + -> Result<(Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)>, Option), ChannelError> { match self.get_update_fulfill_htlc(htlc_id, payment_preimage)? { (Some(update_fulfill_htlc), _) => { let (commitment, monitor_update) = self.send_commitment_no_status_check()?; @@ -1560,11 +1492,10 @@ impl Channel { /// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made. /// In such cases we debug_assert!(false) and return an IgnoreError. Thus, will always return /// Ok(_) if debug assertions are turned on and preconditions are met. - pub fn get_update_fail_htlc( - &mut self, - htlc_id_arg: u64, - err_packet: msgs::OnionErrorPacket, - ) -> Result, ChannelError> { + pub fn get_update_fail_htlc(&mut self, + htlc_id_arg: u64, + err_packet: msgs::OnionErrorPacket) + -> Result, ChannelError> { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { panic!("Was asked to fail an HTLC when channel was not in an operational state"); } @@ -1584,8 +1515,8 @@ impl Channel { }, _ => { debug_assert!( - false, - "Have an inbound HTLC we tried to claim before it was fully committed to" + false, + "Have an inbound HTLC we tried to claim before it was fully committed to" ); return Err(ChannelError::Ignore( "Unable to find a pending HTLC which matched the given HTLC ID", @@ -1596,17 +1527,15 @@ impl Channel { } } if pending_idx == std::usize::MAX { - return Err(ChannelError::Ignore( - "Unable to find a pending HTLC which matched the given HTLC ID", - )); + return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID")); } // Now update local state: if (self.channel_state - & (ChannelState::AwaitingRemoteRevoke as u32 - | ChannelState::PeerDisconnected as u32 - | ChannelState::MonitorUpdateFailed as u32)) - != 0 + & (ChannelState::AwaitingRemoteRevoke as u32 + | ChannelState::PeerDisconnected as u32 + | ChannelState::MonitorUpdateFailed as u32)) + != 0 { for pending_update in self.holding_cell_htlc_updates.iter() { match pending_update { @@ -1627,10 +1556,9 @@ impl Channel { _ => {}, } } - self.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::FailHTLC { - htlc_id: htlc_id_arg, - err_packet, - }); + self.holding_cell_htlc_updates + .push(HTLCUpdateAwaitingACK::FailHTLC { htlc_id: htlc_id_arg, + err_packet }); return Ok(None); } @@ -1639,26 +1567,21 @@ impl Channel { htlc.state = InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(err_packet.clone())); } - Ok(Some(msgs::UpdateFailHTLC { - channel_id: self.channel_id(), - htlc_id: htlc_id_arg, - reason: err_packet, - })) + Ok(Some(msgs::UpdateFailHTLC { channel_id: self.channel_id(), + htlc_id: htlc_id_arg, + reason: err_packet })) } // Message handlers: - pub fn accept_channel( - &mut self, - msg: &msgs::AcceptChannel, - config: &UserConfig, - their_local_features: LocalFeatures, - ) -> Result<(), ChannelError> { + pub fn accept_channel(&mut self, + msg: &msgs::AcceptChannel, + config: &UserConfig, + their_local_features: LocalFeatures) + -> Result<(), ChannelError> { // Check sanity of message fields: if !self.channel_outbound { - return Err(ChannelError::Close( - "Got an accept_channel message from an inbound peer", - )); + return Err(ChannelError::Close("Got an accept_channel message from an inbound peer")); } if self.channel_state != ChannelState::OurInitSent as u32 { return Err(ChannelError::Close("Got an accept_channel message at a strange time")); @@ -1676,7 +1599,7 @@ impl Channel { return Err(ChannelError::Close("Peer never wants payout outputs?")); } if msg.dust_limit_satoshis - > Channel::::get_our_channel_reserve_satoshis(self.channel_value_satoshis) + > Channel::::get_our_channel_reserve_satoshis(self.channel_value_satoshis) { return Err(ChannelError::Close("Dust limit is bigger than our channel reverse")); } @@ -1684,11 +1607,9 @@ impl Channel { return Err(ChannelError::Close("Minimum htlc value is full channel value")); } if msg.to_self_delay > config.peer_channel_config_limits.their_to_self_delay - || msg.to_self_delay > MAX_LOCAL_BREAKDOWN_TIMEOUT + || msg.to_self_delay > MAX_LOCAL_BREAKDOWN_TIMEOUT { - return Err(ChannelError::Close( - "They wanted our payments to be delayed by a needlessly long period", - )); + return Err(ChannelError::Close("They wanted our payments to be delayed by a needlessly long period")); } if msg.max_accepted_htlcs < 1 { return Err(ChannelError::Close("0 max_accepted_htlcs makes for a useless channel")); @@ -1699,39 +1620,25 @@ impl Channel { // Now check against optional parameters as set by config... if msg.htlc_minimum_msat > config.peer_channel_config_limits.max_htlc_minimum_msat { - return Err(ChannelError::Close( - "htlc minimum msat is higher than the user specified limit", - )); + return Err(ChannelError::Close("htlc minimum msat is higher than the user specified limit")); } if msg.max_htlc_value_in_flight_msat < config.peer_channel_config_limits.min_max_htlc_value_in_flight_msat { - return Err(ChannelError::Close( - "max htlc value in flight msat is less than the user specified limit", - )); + return Err(ChannelError::Close("max htlc value in flight msat is less than the user specified limit")); } if msg.channel_reserve_satoshis > config.peer_channel_config_limits.max_channel_reserve_satoshis { - return Err(ChannelError::Close( - "channel reserve satoshis is higher than the user specified limit", - )); + return Err(ChannelError::Close("channel reserve satoshis is higher than the user specified limit")); } if msg.max_accepted_htlcs < config.peer_channel_config_limits.min_max_accepted_htlcs { - return Err(ChannelError::Close( - "max accepted htlcs is less than the user specified limit", - )); + return Err(ChannelError::Close("max accepted htlcs is less than the user specified limit")); } if msg.dust_limit_satoshis < config.peer_channel_config_limits.min_dust_limit_satoshis { - return Err(ChannelError::Close( - "dust limit satoshis is less than the user specified limit", - )); + return Err(ChannelError::Close("dust limit satoshis is less than the user specified limit")); } if msg.dust_limit_satoshis > config.peer_channel_config_limits.max_dust_limit_satoshis { - return Err(ChannelError::Close( - "dust limit satoshis is greater than the user specified limit", - )); + return Err(ChannelError::Close("dust limit satoshis is greater than the user specified limit")); } if msg.minimum_depth > config.peer_channel_config_limits.max_minimum_depth { - return Err(ChannelError::Close( - "We consider the minimum depth to be unreasonably large", - )); + return Err(ChannelError::Close("We consider the minimum depth to be unreasonably large")); } let their_shutdown_scriptpubkey = if their_local_features.supports_upfront_shutdown_script() { @@ -1778,12 +1685,12 @@ impl Channel { let obscure_factor = self.get_commitment_transaction_number_obscure_factor(); let funding_redeemscript = self.get_funding_redeemscript(); self.channel_monitor.set_basic_channel_info( - &msg.htlc_basepoint, - &msg.delayed_payment_basepoint, - msg.to_self_delay, - funding_redeemscript, - self.channel_value_satoshis, - obscure_factor, + &msg.htlc_basepoint, + &msg.delayed_payment_basepoint, + msg.to_self_delay, + funding_redeemscript, + self.channel_value_satoshis, + obscure_factor, ); self.channel_state = ChannelState::OurInitSent as u32 | ChannelState::TheirInitSent as u32; @@ -1793,20 +1700,20 @@ impl Channel { fn funding_created_signature( &mut self, - sig: &Signature, - ) -> Result<(Transaction, LocalCommitmentTransaction, Signature, TxCreationKeys), ChannelError> { + sig: &Signature) + -> Result<(Transaction, LocalCommitmentTransaction, Signature, TxCreationKeys), ChannelError> { let funding_script = self.get_funding_redeemscript(); let local_keys = self.build_local_transaction_keys(self.cur_local_commitment_transaction_number)?; - let local_initial_commitment_tx = self - .build_commitment_transaction( - self.cur_local_commitment_transaction_number, - &local_keys, - true, - false, - self.feerate_per_kw, + let local_initial_commitment_tx = + self.build_commitment_transaction( + self.cur_local_commitment_transaction_number, + &local_keys, + true, + false, + self.feerate_per_kw, ) - .0; + .0; let local_sighash = hash_to_message!( &bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all( &local_initial_commitment_tx.input[0], @@ -1817,51 +1724,52 @@ impl Channel { // They sign the "local" commitment transaction... secp_check!( - self.secp_ctx - .verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), - "Invalid funding_created signature from peer" + self.secp_ctx + .verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), + "Invalid funding_created signature from peer" ); let localtx = LocalCommitmentTransaction::new_missing_local_sig( - local_initial_commitment_tx, - sig, - &PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()), - self.their_funding_pubkey.as_ref().unwrap(), + local_initial_commitment_tx, + sig, + &PublicKey::from_secret_key( + &self.secp_ctx, + self.local_keys.funding_key(), + ), + self.their_funding_pubkey.as_ref().unwrap(), ); let remote_keys = self.build_remote_transaction_keys()?; - let remote_initial_commitment_tx = self - .build_commitment_transaction( - self.cur_remote_commitment_transaction_number, - &remote_keys, - false, - false, - self.feerate_per_kw, - ) - .0; - let remote_signature = self - .local_keys - .sign_remote_commitment( - self.channel_value_satoshis, - &self.get_funding_redeemscript(), - self.feerate_per_kw, - &remote_initial_commitment_tx, - &remote_keys, - &Vec::new(), - self.our_to_self_delay, - &self.secp_ctx, + let remote_initial_commitment_tx = + self.build_commitment_transaction( + self.cur_remote_commitment_transaction_number, + &remote_keys, + false, + false, + self.feerate_per_kw, ) - .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed"))? - .0; + .0; + let remote_signature = self.local_keys + .sign_remote_commitment( + self.channel_value_satoshis, + &self.get_funding_redeemscript(), + self.feerate_per_kw, + &remote_initial_commitment_tx, + &remote_keys, + &Vec::new(), + self.our_to_self_delay, + &self.secp_ctx, + ) + .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed"))? + .0; // We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish. Ok((remote_initial_commitment_tx, localtx, remote_signature, local_keys)) } - pub fn funding_created( - &mut self, - msg: &msgs::FundingCreated, - ) -> Result<(msgs::FundingSigned, ChannelMonitor), ChannelError> { + pub fn funding_created(&mut self, + msg: &msgs::FundingCreated) + -> Result<(msgs::FundingSigned, ChannelMonitor), ChannelError> { if self.channel_outbound { return Err(ChannelError::Close("Received funding_created for an outbound channel?")); } @@ -1869,13 +1777,11 @@ impl Channel { // BOLT 2 says that if we disconnect before we send funding_signed we SHOULD NOT // remember the channel, so it's safe to just send an error_message here and drop the // channel. - return Err(ChannelError::Close( - "Received funding_created after we got the channel!", - )); + return Err(ChannelError::Close("Received funding_created after we got the channel!")); } if self.channel_monitor.get_min_seen_secret() != (1 << 48) - || self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER - || self.cur_local_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER + || self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER + || self.cur_local_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER { panic!("Should not have advanced channel commitment tx numbers prior to funding_created"); } @@ -1896,29 +1802,25 @@ impl Channel { // Now that we're past error-generating stuff, update our local state: self.channel_monitor.provide_latest_remote_commitment_tx_info( - &remote_initial_commitment_tx, - Vec::new(), - self.cur_remote_commitment_transaction_number, - self.their_cur_commitment_point.unwrap(), + &remote_initial_commitment_tx, + Vec::new(), + self.cur_remote_commitment_transaction_number, + self.their_cur_commitment_point.unwrap(), ); self.channel_monitor.provide_latest_local_commitment_tx_info( - local_initial_commitment_tx, - local_keys, - self.feerate_per_kw, - Vec::new(), + local_initial_commitment_tx, + local_keys, + self.feerate_per_kw, + Vec::new(), ); self.channel_state = ChannelState::FundingSent as u32; self.channel_id = funding_txo.to_channel_id(); self.cur_remote_commitment_transaction_number -= 1; self.cur_local_commitment_transaction_number -= 1; - Ok(( - msgs::FundingSigned { - channel_id: self.channel_id, - signature: our_signature, - }, - self.channel_monitor.clone(), - )) + Ok((msgs::FundingSigned { channel_id: self.channel_id, + signature: our_signature }, + self.channel_monitor.clone())) } /// Handles a funding_signed message from the remote end. @@ -1931,8 +1833,8 @@ impl Channel { return Err(ChannelError::Close("Received funding_signed in strange state!")); } if self.channel_monitor.get_min_seen_secret() != (1 << 48) - || self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER - 1 - || self.cur_local_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER + || self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER - 1 + || self.cur_local_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER { panic!("Should not have advanced channel commitment tx numbers prior to funding_created"); } @@ -1940,15 +1842,15 @@ impl Channel { let funding_script = self.get_funding_redeemscript(); let local_keys = self.build_local_transaction_keys(self.cur_local_commitment_transaction_number)?; - let local_initial_commitment_tx = self - .build_commitment_transaction( - self.cur_local_commitment_transaction_number, - &local_keys, - true, - false, - self.feerate_per_kw, + let local_initial_commitment_tx = + self.build_commitment_transaction( + self.cur_local_commitment_transaction_number, + &local_keys, + true, + false, + self.feerate_per_kw, ) - .0; + .0; let local_sighash = hash_to_message!( &bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all( &local_initial_commitment_tx.input[0], @@ -1959,9 +1861,9 @@ impl Channel { // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish. secp_check!( - self.secp_ctx - .verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), - "Invalid funding_signed signature from peer" + self.secp_ctx + .verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), + "Invalid funding_signed signature from peer" ); self.channel_monitor.provide_latest_local_commitment_tx_info( @@ -1990,9 +1892,7 @@ impl Channel { pub fn funding_locked(&mut self, msg: &msgs::FundingLocked) -> Result<(), ChannelError> { if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent funding_locked when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent funding_locked when we needed a channel_reestablish")); } let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS); @@ -2011,9 +1911,7 @@ impl Channel { (ChannelState::FundingSent as u32 | ChannelState::TheirFundingLocked as u32)) { if self.their_cur_commitment_point != Some(msg.next_per_commitment_point) { - return Err(ChannelError::Close( - "Peer sent a reconnect funding_locked with a different point", - )); + return Err(ChannelError::Close("Peer sent a reconnect funding_locked with a different point")); } // They probably disconnected/reconnected and re-sent the funding_locked, which is required return Ok(()); @@ -2060,61 +1958,46 @@ impl Channel { /// corner case properly. pub fn get_inbound_outbound_available_balance_msat(&self) -> (u64, u64) { // Note that we have to handle overflow due to the above case. - ( - cmp::min( - self.channel_value_satoshis as i64 * 1000 - - self.value_to_self_msat as i64 - - self.get_inbound_pending_htlc_stats().1 as i64, - 0, - ) as u64, - cmp::min( - self.value_to_self_msat as i64 - self.get_outbound_pending_htlc_stats().1 as i64, - 0, - ) as u64, - ) + (cmp::min( + self.channel_value_satoshis as i64 * 1000 + - self.value_to_self_msat as i64 + - self.get_inbound_pending_htlc_stats().1 as i64, + 0, + ) as u64, + cmp::min( + self.value_to_self_msat as i64 - self.get_outbound_pending_htlc_stats().1 as i64, + 0, + ) as u64) } - pub fn update_add_htlc( - &mut self, - msg: &msgs::UpdateAddHTLC, - pending_forward_state: PendingHTLCStatus, - ) -> Result<(), ChannelError> { + pub fn update_add_htlc(&mut self, + msg: &msgs::UpdateAddHTLC, + pending_forward_state: PendingHTLCStatus) + -> Result<(), ChannelError> { if (self.channel_state & (ChannelState::ChannelFunded as u32 | ChannelState::RemoteShutdownSent as u32)) - != (ChannelState::ChannelFunded as u32) + != (ChannelState::ChannelFunded as u32) { - return Err(ChannelError::Close( - "Got add HTLC message when channel was not in an operational state", - )); + return Err(ChannelError::Close("Got add HTLC message when channel was not in an operational state")); } if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent update_add_htlc when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent update_add_htlc when we needed a channel_reestablish")); } if msg.amount_msat > self.channel_value_satoshis * 1000 { - return Err(ChannelError::Close( - "Remote side tried to send more than the total value of the channel", - )); + return Err(ChannelError::Close("Remote side tried to send more than the total value of the channel")); } if msg.amount_msat < self.our_htlc_minimum_msat { - return Err(ChannelError::Close( - "Remote side tried to send less than our minimum HTLC value", - )); + return Err(ChannelError::Close("Remote side tried to send less than our minimum HTLC value")); } let (inbound_htlc_count, htlc_inbound_value_msat) = self.get_inbound_pending_htlc_stats(); if inbound_htlc_count + 1 > OUR_MAX_HTLCS as u32 { - return Err(ChannelError::Close( - "Remote tried to push more than our max accepted HTLCs", - )); + return Err(ChannelError::Close("Remote tried to push more than our max accepted HTLCs")); } // Check our_max_htlc_value_in_flight_msat if htlc_inbound_value_msat + msg.amount_msat - > Channel::::get_our_max_htlc_value_in_flight_msat(self.channel_value_satoshis) + > Channel::::get_our_max_htlc_value_in_flight_msat(self.channel_value_satoshis) { - return Err(ChannelError::Close( - "Remote HTLC add would put them over our max HTLC value", - )); + return Err(ChannelError::Close("Remote HTLC add would put them over our max HTLC value")); } // Check our_channel_reserve_satoshis (we're getting paid, so they have to at least meet // the reserve_satoshis we told them to always have as direct payment so that they lose @@ -2137,21 +2020,17 @@ impl Channel { } } if htlc_inbound_value_msat + msg.amount_msat + self.value_to_self_msat - > (self.channel_value_satoshis - - Channel::::get_our_channel_reserve_satoshis(self.channel_value_satoshis)) - * 1000 + removed_outbound_total_msat + > (self.channel_value_satoshis + - Channel::::get_our_channel_reserve_satoshis(self.channel_value_satoshis)) + * 1000 + removed_outbound_total_msat { - return Err(ChannelError::Close( - "Remote HTLC add would put them over their reserve value", - )); + return Err(ChannelError::Close("Remote HTLC add would put them over their reserve value")); } if self.next_remote_htlc_id != msg.htlc_id { return Err(ChannelError::Close("Remote skipped HTLC ID")); } if msg.cltv_expiry >= 500000000 { - return Err(ChannelError::Close( - "Remote provided CLTV expiry in seconds instead of block height", - )); + return Err(ChannelError::Close("Remote provided CLTV expiry in seconds instead of block height")); } //TODO: Check msg.cltv_expiry further? Do this in channel manager? @@ -2164,33 +2043,29 @@ impl Channel { // Now update local state: self.next_remote_htlc_id += 1; - self.pending_inbound_htlcs.push(InboundHTLCOutput { - htlc_id: msg.htlc_id, - amount_msat: msg.amount_msat, - payment_hash: msg.payment_hash, - cltv_expiry: msg.cltv_expiry, - state: InboundHTLCState::RemoteAnnounced(pending_forward_state), - }); + self.pending_inbound_htlcs + .push(InboundHTLCOutput { htlc_id: msg.htlc_id, + amount_msat: msg.amount_msat, + payment_hash: msg.payment_hash, + cltv_expiry: msg.cltv_expiry, + state: InboundHTLCState::RemoteAnnounced(pending_forward_state) }); Ok(()) } /// Marks an outbound HTLC which we have received update_fail/fulfill/malformed #[inline] - fn mark_outbound_htlc_removed( - &mut self, - htlc_id: u64, - check_preimage: Option, - fail_reason: Option, - ) -> Result<&HTLCSource, ChannelError> { + fn mark_outbound_htlc_removed(&mut self, + htlc_id: u64, + check_preimage: Option, + fail_reason: Option) + -> Result<&HTLCSource, ChannelError> { for htlc in self.pending_outbound_htlcs.iter_mut() { if htlc.htlc_id == htlc_id { match check_preimage { None => {}, Some(payment_hash) => { if payment_hash != htlc.payment_hash { - return Err(ChannelError::Close( - "Remote tried to fulfill HTLC with an incorrect preimage", - )); + return Err(ChannelError::Close("Remote tried to fulfill HTLC with an incorrect preimage")); } }, }; @@ -2214,53 +2089,41 @@ impl Channel { return Ok(&htlc.source); } } - Err(ChannelError::Close( - "Remote tried to fulfill/fail an HTLC we couldn't find", - )) + Err(ChannelError::Close("Remote tried to fulfill/fail an HTLC we couldn't find")) } pub fn update_fulfill_htlc(&mut self, msg: &msgs::UpdateFulfillHTLC) -> Result { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { - return Err(ChannelError::Close( - "Got fulfill HTLC message when channel was not in an operational state", - )); + return Err(ChannelError::Close("Got fulfill HTLC message when channel was not in an operational state")); } if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent update_fulfill_htlc when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent update_fulfill_htlc when we needed a channel_reestablish")); } let payment_hash = PaymentHash(Sha256::hash(&msg.payment_preimage.0[..]).into_inner()); self.mark_outbound_htlc_removed(msg.htlc_id, Some(payment_hash), None) - .map(|source| source.clone()) + .map(|source| source.clone()) } - pub fn update_fail_htlc( - &mut self, - msg: &msgs::UpdateFailHTLC, - fail_reason: HTLCFailReason, - ) -> Result<(), ChannelError> { + pub fn update_fail_htlc(&mut self, + msg: &msgs::UpdateFailHTLC, + fail_reason: HTLCFailReason) + -> Result<(), ChannelError> { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { - return Err(ChannelError::Close( - "Got fail HTLC message when channel was not in an operational state", - )); + return Err(ChannelError::Close("Got fail HTLC message when channel was not in an operational state")); } if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent update_fail_htlc when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent update_fail_htlc when we needed a channel_reestablish")); } self.mark_outbound_htlc_removed(msg.htlc_id, None, Some(fail_reason))?; Ok(()) } - pub fn update_fail_malformed_htlc<'a>( - &mut self, - msg: &msgs::UpdateFailMalformedHTLC, - fail_reason: HTLCFailReason, - ) -> Result<(), ChannelError> { + pub fn update_fail_malformed_htlc<'a>(&mut self, + msg: &msgs::UpdateFailMalformedHTLC, + fail_reason: HTLCFailReason) + -> Result<(), ChannelError> { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { return Err(ChannelError::Close( "Got fail malformed HTLC message when channel was not in an operational state", @@ -2279,28 +2142,26 @@ impl Channel { pub fn commitment_signed( &mut self, msg: &msgs::CommitmentSigned, - fee_estimator: &FeeEstimator, - ) -> Result< - ( + fee_estimator: &FeeEstimator) + -> Result< + ( msgs::RevokeAndACK, Option, Option, ChannelMonitor, ), - ChannelError, - > { + ChannelError, + > { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { return Err(ChannelError::Close( "Got commitment signed message when channel was not in an operational state", )); } if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent commitment_signed when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent commitment_signed when we needed a channel_reestablish")); } if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK == BOTH_SIDES_SHUTDOWN_MASK - && self.last_sent_closing_fee.is_some() + && self.last_sent_closing_fee.is_some() { return Err(ChannelError::Close( "Peer sent commitment_signed after we'd started exchanging closing_signeds", @@ -2321,17 +2182,16 @@ impl Channel { let mut local_commitment_tx = { let mut commitment_tx = self.build_commitment_transaction( - self.cur_local_commitment_transaction_number, - &local_keys, - true, - false, - feerate_per_kw, + self.cur_local_commitment_transaction_number, + &local_keys, + true, + false, + feerate_per_kw, ); - let htlcs_cloned: Vec<_> = commitment_tx - .2 - .drain(..) - .map(|htlc| (htlc.0, htlc.1.map(|h| h.clone()))) - .collect(); + let htlcs_cloned: Vec<_> = commitment_tx.2 + .drain(..) + .map(|htlc| (htlc.0, htlc.1.map(|h| h.clone()))) + .collect(); (commitment_tx.0, commitment_tx.1, htlcs_cloned) }; let local_commitment_txid = local_commitment_tx.0.txid(); @@ -2343,28 +2203,28 @@ impl Channel { )[..] ); log_trace!( - self, - "Checking commitment tx signature {} by key {} against tx {} with redeemscript {}", - log_bytes!(msg.signature.serialize_compact()[..]), - log_bytes!(self.their_funding_pubkey.unwrap().serialize()), - encode::serialize_hex(&local_commitment_tx.0), - encode::serialize_hex(&funding_script) + self, + "Checking commitment tx signature {} by key {} against tx {} with redeemscript {}", + log_bytes!(msg.signature.serialize_compact()[..]), + log_bytes!(self.their_funding_pubkey.unwrap().serialize()), + encode::serialize_hex(&local_commitment_tx.0), + encode::serialize_hex(&funding_script) ); secp_check!( - self.secp_ctx - .verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), - "Invalid commitment tx signature from peer" + self.secp_ctx + .verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), + "Invalid commitment tx signature from peer" ); //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 num_htlcs = local_commitment_tx.1; let total_fee: u64 = feerate_per_kw as u64 - * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) - / 1000; + * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) + / 1000; if self.channel_value_satoshis - self.value_to_self_msat / 1000 - < total_fee + self.their_channel_reserve_satoshis + < total_fee + self.their_channel_reserve_satoshis { return Err(ChannelError::Close("Funding remote cannot afford proposed new fee")); } @@ -2381,12 +2241,12 @@ impl Channel { self.build_htlc_transaction(&local_commitment_txid, &htlc, true, &local_keys, feerate_per_kw); let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys); log_trace!( - self, - "Checking HTLC tx signature {} by key {} against tx {} with redeemscript {}", - log_bytes!(msg.htlc_signatures[idx].serialize_compact()[..]), - log_bytes!(local_keys.b_htlc_key.serialize()), - encode::serialize_hex(&htlc_tx), - encode::serialize_hex(&htlc_redeemscript) + self, + "Checking HTLC tx signature {} by key {} against tx {} with redeemscript {}", + log_bytes!(msg.htlc_signatures[idx].serialize_compact()[..]), + log_bytes!(local_keys.b_htlc_key.serialize()), + encode::serialize_hex(&htlc_tx), + encode::serialize_hex(&htlc_redeemscript) ); let htlc_sighash = hash_to_message!( &bip143::SighashComponents::new(&htlc_tx).sighash_all( @@ -2396,9 +2256,9 @@ impl Channel { )[..] ); secp_check!( - self.secp_ctx - .verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), - "Invalid HTLC tx signature from peer" + self.secp_ctx + .verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), + "Invalid HTLC tx signature from peer" ); htlcs_and_sigs.push((htlc, Some(msg.htlc_signatures[idx]), source)); } else { @@ -2406,13 +2266,17 @@ impl Channel { } } - let next_per_commitment_point = PublicKey::from_secret_key( - &self.secp_ctx, - &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number - 1), - ); + let next_per_commitment_point = + PublicKey::from_secret_key( + &self.secp_ctx, + &self.build_local_commitment_secret( + self.cur_local_commitment_transaction_number - 1, + ), + ); let per_commitment_secret = chan_utils::build_commitment_secret( - self.local_keys.commitment_seed(), - self.cur_local_commitment_transaction_number + 1, + self.local_keys.commitment_seed(), + self.cur_local_commitment_transaction_number + + 1, ); // Update state now that we've passed all the can-fail calls... @@ -2486,9 +2350,7 @@ impl Channel { } // TODO: Call maybe_propose_first_closing_signed on restoration (or call it here and // re-send the message on restoration) - return Err(ChannelError::Ignore( - "Previous monitor update failure prevented generation of RAA", - )); + return Err(ChannelError::Ignore("Previous monitor update failure prevented generation of RAA")); } let (our_commitment_signed, monitor_update, closing_signed) = @@ -2499,25 +2361,17 @@ impl Channel { let (msg, monitor) = self.send_commitment_no_status_check()?; (Some(msg), monitor, None) } else if !need_our_commitment { - ( - None, - self.channel_monitor.clone(), - self.maybe_propose_first_closing_signed(fee_estimator), - ) + (None, self.channel_monitor.clone(), self.maybe_propose_first_closing_signed(fee_estimator)) } else { (None, self.channel_monitor.clone(), None) }; - Ok(( - msgs::RevokeAndACK { - channel_id: self.channel_id, - per_commitment_secret, - next_per_commitment_point, - }, - our_commitment_signed, - closing_signed, - monitor_update, - )) + Ok((msgs::RevokeAndACK { channel_id: self.channel_id, + per_commitment_secret, + next_per_commitment_point }, + our_commitment_signed, + closing_signed, + monitor_update)) } /// Used to fulfill holding_cell_htlcs when we get a remote ack (or implicitly get it by them @@ -2526,14 +2380,14 @@ impl Channel { assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, 0); if self.holding_cell_htlc_updates.len() != 0 || self.holding_cell_update_fee.is_some() { log_trace!( - self, - "Freeing holding cell with {} HTLC updates{}", - self.holding_cell_htlc_updates.len(), - if self.holding_cell_update_fee.is_some() { - " and a fee update" - } else { - "" - } + self, + "Freeing holding cell with {} HTLC updates{}", + self.holding_cell_htlc_updates.len(), + if self.holding_cell_update_fee.is_some() { + " and a fee update" + } else { + "" + } ); let mut htlc_updates = Vec::new(); @@ -2553,29 +2407,27 @@ impl Channel { self.holding_cell_htlc_updates.push(htlc_update); } else { match &htlc_update { - &HTLCUpdateAwaitingACK::AddHTLC { - amount_msat, - cltv_expiry, - ref payment_hash, - ref source, - ref onion_routing_packet, - .. - } => match self.send_htlc( - amount_msat, - *payment_hash, - cltv_expiry, - source.clone(), - onion_routing_packet.clone(), + &HTLCUpdateAwaitingACK::AddHTLC { amount_msat, + cltv_expiry, + ref payment_hash, + ref source, + ref onion_routing_packet, + .. } => match self.send_htlc( + amount_msat, + *payment_hash, + cltv_expiry, + source.clone(), + onion_routing_packet.clone(), ) { Ok(update_add_msg_option) => update_add_htlcs.push(update_add_msg_option.unwrap()), Err(e) => { match e { ChannelError::Ignore(ref msg) => { log_info!( - self, - "Failed to send HTLC with payment_hash {} due to {}", - log_bytes!(payment_hash.0), - msg + self, + "Failed to send HTLC with payment_hash {} due to {}", + log_bytes!(payment_hash.0), + msg ); }, _ => { @@ -2585,11 +2437,9 @@ impl Channel { err = Some(e); }, }, - &HTLCUpdateAwaitingACK::ClaimHTLC { - ref payment_preimage, - htlc_id, - .. - } => match self.get_update_fulfill_htlc(htlc_id, *payment_preimage) { + &HTLCUpdateAwaitingACK::ClaimHTLC { ref payment_preimage, + htlc_id, + .. } => match self.get_update_fulfill_htlc(htlc_id, *payment_preimage) { Ok(update_fulfill_msg_option) => { update_fulfill_htlcs.push(update_fulfill_msg_option.0.unwrap()) }, @@ -2600,17 +2450,17 @@ impl Channel { } }, }, - &HTLCUpdateAwaitingACK::FailHTLC { - htlc_id, - ref err_packet, - } => match self.get_update_fail_htlc(htlc_id, err_packet.clone()) { - Ok(update_fail_msg_option) => update_fail_htlcs.push(update_fail_msg_option.unwrap()), - Err(e) => { - if let ChannelError::Ignore(_) = e { - } else { - panic!("Got a non-IgnoreError action trying to fail holding cell HTLC"); - } - }, + &HTLCUpdateAwaitingACK::FailHTLC { htlc_id, + ref err_packet, } => { + match self.get_update_fail_htlc(htlc_id, err_packet.clone()) { + Ok(update_fail_msg_option) => update_fail_htlcs.push(update_fail_msg_option.unwrap()), + Err(e) => { + if let ChannelError::Ignore(_) = e { + } else { + panic!("Got a non-IgnoreError action trying to fail holding cell HTLC"); + } + }, + } }, } if err.is_some() { @@ -2628,9 +2478,9 @@ impl Channel { match err { None => { if update_add_htlcs.is_empty() - && update_fulfill_htlcs.is_empty() - && update_fail_htlcs.is_empty() - && self.holding_cell_update_fee.is_none() + && update_fulfill_htlcs.is_empty() + && update_fail_htlcs.is_empty() + && self.holding_cell_update_fee.is_none() { // This should never actually happen and indicates we got some Errs back // from update_fulfill_htlc/update_fail_htlc, but we handle it anyway in @@ -2639,23 +2489,19 @@ impl Channel { } let update_fee = if let Some(feerate) = self.holding_cell_update_fee { self.pending_update_fee = self.holding_cell_update_fee.take(); - Some(msgs::UpdateFee { - channel_id: self.channel_id, - feerate_per_kw: feerate as u32, - }) + Some(msgs::UpdateFee { channel_id: self.channel_id, + feerate_per_kw: feerate as u32 }) } else { None }; let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?; Ok(Some(( - msgs::CommitmentUpdate { - update_add_htlcs, - update_fulfill_htlcs, - update_fail_htlcs, - update_fail_malformed_htlcs: Vec::new(), - update_fee, - commitment_signed, - }, + msgs::CommitmentUpdate { update_add_htlcs, + update_fulfill_htlcs, + update_fail_htlcs, + update_fail_malformed_htlcs: Vec::new(), + update_fee, + commitment_signed, }, monitor_update, ))) }, @@ -2674,42 +2520,36 @@ impl Channel { pub fn revoke_and_ack( &mut self, msg: &msgs::RevokeAndACK, - fee_estimator: &FeeEstimator, - ) -> Result< - ( + fee_estimator: &FeeEstimator) + -> Result< + ( Option, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, Option, ChannelMonitor, ), - ChannelError, - > { + ChannelError, + > { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { - return Err(ChannelError::Close( - "Got revoke/ACK message when channel was not in an operational state", - )); + return Err(ChannelError::Close("Got revoke/ACK message when channel was not in an operational state")); } if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent revoke_and_ack when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent revoke_and_ack when we needed a channel_reestablish")); } if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK == BOTH_SIDES_SHUTDOWN_MASK - && self.last_sent_closing_fee.is_some() + && self.last_sent_closing_fee.is_some() { - return Err(ChannelError::Close( - "Peer sent revoke_and_ack after we'd started exchanging closing_signeds", - )); + return Err(ChannelError::Close("Peer sent revoke_and_ack after we'd started exchanging closing_signeds")); } if let Some(their_prev_commitment_point) = self.their_prev_commitment_point { if PublicKey::from_secret_key( - &self.secp_ctx, - &secp_check!( - SecretKey::from_slice(&msg.per_commitment_secret), - "Peer provided an invalid per_commitment_secret" - ), + &self.secp_ctx, + &secp_check!( + SecretKey::from_slice(&msg.per_commitment_secret), + "Peer provided an invalid per_commitment_secret" + ), ) != their_prev_commitment_point { return Err(ChannelError::Close( @@ -2718,11 +2558,11 @@ impl Channel { } } self.channel_monitor - .provide_secret( - self.cur_remote_commitment_transaction_number + 1, - msg.per_commitment_secret, - ) - .map_err(|e| ChannelError::Close(e.0))?; + .provide_secret( + self.cur_remote_commitment_transaction_number + 1, + msg.per_commitment_secret, + ) + .map_err(|e| ChannelError::Close(e.0))?; // Update state now that we've passed all the can-fail calls... // (note that we may still fail to generate the new commitment_signed message, but that's @@ -2749,52 +2589,54 @@ impl Channel { // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug) pending_inbound_htlcs.retain(|htlc| { - if let &InboundHTLCState::LocalRemoved(ref reason) = &htlc.state { - log_trace!( - logger, - " ...removing inbound LocalRemoved {}", - log_bytes!(htlc.payment_hash.0) + if let &InboundHTLCState::LocalRemoved(ref reason) = &htlc.state { + log_trace!( + logger, + " ...removing inbound LocalRemoved {}", + log_bytes!(htlc.payment_hash.0) ); - if let &InboundHTLCRemovalReason::Fulfill(_) = reason { - value_to_self_msat_diff += htlc.amount_msat as i64; - } - false - } else { - true - } - }); + if let &InboundHTLCRemovalReason::Fulfill(_) = reason { + value_to_self_msat_diff += htlc.amount_msat as i64; + } + false + } else { + true + } + }); pending_outbound_htlcs.retain(|htlc| { - if let &OutboundHTLCState::AwaitingRemovedRemoteRevoke(ref fail_reason) = &htlc.state { - log_trace!( - logger, - " ...removing outbound AwaitingRemovedRemoteRevoke {}", - log_bytes!(htlc.payment_hash.0) + if let &OutboundHTLCState::AwaitingRemovedRemoteRevoke(ref fail_reason) = + &htlc.state + { + log_trace!( + logger, + " ...removing outbound AwaitingRemovedRemoteRevoke {}", + log_bytes!(htlc.payment_hash.0) ); - if let Some(reason) = fail_reason.clone() { - // We really want take() here, but, again, non-mut ref :( - revoked_htlcs.push((htlc.source.clone(), htlc.payment_hash, reason)); - } else { - // They fulfilled, so we sent them money - value_to_self_msat_diff -= htlc.amount_msat as i64; - } - false - } else { - true - } - }); + if let Some(reason) = fail_reason.clone() { + // We really want take() here, but, again, non-mut ref :( + revoked_htlcs.push((htlc.source.clone(), htlc.payment_hash, reason)); + } else { + // They fulfilled, so we sent them money + value_to_self_msat_diff -= htlc.amount_msat as i64; + } + false + } else { + true + } + }); for htlc in pending_inbound_htlcs.iter_mut() { let swap = if let &InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) = &htlc.state { log_trace!( - logger, - " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to Committed", - log_bytes!(htlc.payment_hash.0) + logger, + " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to Committed", + log_bytes!(htlc.payment_hash.0) ); true } else if let &InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) = &htlc.state { log_trace!( - logger, - " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed", - log_bytes!(htlc.payment_hash.0) + logger, + " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed", + log_bytes!(htlc.payment_hash.0) ); true } else { @@ -2839,9 +2681,9 @@ impl Channel { for htlc in pending_outbound_htlcs.iter_mut() { if let OutboundHTLCState::LocalAnnounced(_) = htlc.state { log_trace!( - logger, - " ...promoting outbound LocalAnnounced {} to Committed", - log_bytes!(htlc.payment_hash.0) + logger, + " ...promoting outbound LocalAnnounced {} to Committed", + log_bytes!(htlc.payment_hash.0) ); htlc.state = OutboundHTLCState::Committed; } @@ -2852,9 +2694,9 @@ impl Channel { None } { log_trace!( - logger, - " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", - log_bytes!(htlc.payment_hash.0) + logger, + " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", + log_bytes!(htlc.payment_hash.0) ); htlc.state = OutboundHTLCState::AwaitingRemovedRemoteRevoke(fail_reason); require_commitment = true; @@ -2902,46 +2744,33 @@ impl Channel { for fail_msg in update_fail_htlcs.drain(..) { commitment_update.0.update_fail_htlcs.push(fail_msg); } - commitment_update - .0 - .update_fail_malformed_htlcs - .reserve(update_fail_malformed_htlcs.len()); + commitment_update.0 + .update_fail_malformed_htlcs + .reserve(update_fail_malformed_htlcs.len()); for fail_msg in update_fail_malformed_htlcs.drain(..) { commitment_update.0.update_fail_malformed_htlcs.push(fail_msg); } - Ok(( - Some(commitment_update.0), - to_forward_infos, - revoked_htlcs, - None, - commitment_update.1, - )) + Ok((Some(commitment_update.0), to_forward_infos, revoked_htlcs, None, commitment_update.1)) }, None => { if require_commitment { let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?; - Ok(( - Some(msgs::CommitmentUpdate { - update_add_htlcs: Vec::new(), - update_fulfill_htlcs: Vec::new(), - update_fail_htlcs, - update_fail_malformed_htlcs, - update_fee: None, - commitment_signed, - }), - to_forward_infos, - revoked_htlcs, - None, - monitor_update, - )) + Ok((Some(msgs::CommitmentUpdate { update_add_htlcs: Vec::new(), + update_fulfill_htlcs: Vec::new(), + update_fail_htlcs, + update_fail_malformed_htlcs, + update_fee: None, + commitment_signed }), + to_forward_infos, + revoked_htlcs, + None, + monitor_update)) } else { - Ok(( - None, - to_forward_infos, - revoked_htlcs, - self.maybe_propose_first_closing_signed(fee_estimator), - self.channel_monitor.clone(), - )) + Ok((None, + to_forward_infos, + revoked_htlcs, + self.maybe_propose_first_closing_signed(fee_estimator), + self.channel_monitor.clone())) } }, } @@ -2962,7 +2791,7 @@ impl Channel { } if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) - == (ChannelState::AwaitingRemoteRevoke as u32) + == (ChannelState::AwaitingRemoteRevoke as u32) { self.holding_cell_update_fee = Some(feerate_per_kw); return None; @@ -2971,16 +2800,14 @@ impl Channel { debug_assert!(self.pending_update_fee.is_none()); self.pending_update_fee = Some(feerate_per_kw); - Some(msgs::UpdateFee { - channel_id: self.channel_id, - feerate_per_kw: feerate_per_kw as u32, - }) + Some(msgs::UpdateFee { channel_id: self.channel_id, + feerate_per_kw: feerate_per_kw as u32 }) } pub fn send_update_fee_and_commit( &mut self, - feerate_per_kw: u64, - ) -> Result, ChannelError> { + feerate_per_kw: u64) + -> Result, ChannelError> { match self.send_update_fee(feerate_per_kw) { Some(update_fee) => { let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?; @@ -3010,31 +2837,31 @@ impl Channel { let mut inbound_drop_count = 0; self.pending_inbound_htlcs.retain(|htlc| { - match htlc.state { - InboundHTLCState::RemoteAnnounced(_) => { - // They sent us an update_add_htlc but we never got the commitment_signed. - // We'll tell them what commitment_signed we're expecting next and they'll drop - // this HTLC accordingly - inbound_drop_count += 1; - false - }, - InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) - | InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => { - // We received a commitment_signed updating this HTLC and (at least hopefully) - // sent a revoke_and_ack (which we can re-transmit) and have heard nothing - // in response to it yet, so don't touch it. - true - }, - InboundHTLCState::Committed => true, - InboundHTLCState::LocalRemoved(_) => { - // We (hopefully) sent a commitment_signed updating this HTLC (which we can - // re-transmit if needed) and they may have even sent a revoke_and_ack back - // (that we missed). Keep this around for now and if they tell us they missed - // the commitment_signed we can re-transmit the update then. - true - }, - } - }); + match htlc.state { + InboundHTLCState::RemoteAnnounced(_) => { + // They sent us an update_add_htlc but we never got the commitment_signed. + // We'll tell them what commitment_signed we're expecting next and they'll drop + // this HTLC accordingly + inbound_drop_count += 1; + false + }, + InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) + | InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => { + // We received a commitment_signed updating this HTLC and (at least hopefully) + // sent a revoke_and_ack (which we can re-transmit) and have heard nothing + // in response to it yet, so don't touch it. + true + }, + InboundHTLCState::Committed => true, + InboundHTLCState::LocalRemoved(_) => { + // We (hopefully) sent a commitment_signed updating this HTLC (which we can + // re-transmit if needed) and they may have even sent a revoke_and_ack back + // (that we missed). Keep this around for now and if they tell us they missed + // the commitment_signed we can re-transmit the update then. + true + }, + } + }); self.next_remote_htlc_id -= inbound_drop_count; for htlc in self.pending_outbound_htlcs.iter_mut() { @@ -3047,16 +2874,15 @@ impl Channel { } self.holding_cell_htlc_updates.retain(|htlc_update| match htlc_update { - &HTLCUpdateAwaitingACK::AddHTLC { - ref payment_hash, - ref source, - .. - } => { - outbound_drops.push((source.clone(), payment_hash.clone())); - false - }, - &HTLCUpdateAwaitingACK::ClaimHTLC { .. } | &HTLCUpdateAwaitingACK::FailHTLC { .. } => true, - }); + &HTLCUpdateAwaitingACK::AddHTLC { ref payment_hash, + ref source, + .. } => { + outbound_drops.push((source.clone(), payment_hash.clone())); + false + }, + &HTLCUpdateAwaitingACK::ClaimHTLC { .. } + | &HTLCUpdateAwaitingACK::FailHTLC { .. } => true, + }); self.channel_state |= ChannelState::PeerDisconnected as u32; log_debug!(self, "Peer disconnection resulted in {} remote-announced HTLC drops and {} waiting-to-locally-announced HTLC drops on channel {}", outbound_drops.len(), inbound_drop_count, log_bytes!(self.channel_id())); outbound_drops @@ -3068,13 +2894,11 @@ impl Channel { /// which failed. The messages which were generated from that call which generated the /// monitor update failure must *not* have been sent to the remote end, and must instead /// have been dropped. They will be regenerated when monitor_updating_restored is called. - pub fn monitor_update_failed( - &mut self, - resend_raa: bool, - resend_commitment: bool, - mut pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>, - mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, - ) { + pub fn monitor_update_failed(&mut self, + resend_raa: bool, + resend_commitment: bool, + mut pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>, + mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>) { assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, 0); self.monitor_pending_revoke_and_ack = resend_raa; self.monitor_pending_commitment_signed = resend_commitment; @@ -3089,19 +2913,17 @@ impl Channel { /// successfully and we should restore normal operation. Returns messages which should be sent /// to the remote side. pub fn monitor_updating_restored( - &mut self, - ) -> ( - Option, - Option, - RAACommitmentOrder, - Vec<(PendingForwardHTLCInfo, u64)>, - Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, - bool, - Option, - ) { + &mut self) + -> (Option, + Option, + RAACommitmentOrder, + Vec<(PendingForwardHTLCInfo, u64)>, + Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, + bool, + Option) { assert_eq!( - self.channel_state & ChannelState::MonitorUpdateFailed as u32, - ChannelState::MonitorUpdateFailed as u32 + self.channel_state & ChannelState::MonitorUpdateFailed as u32, + ChannelState::MonitorUpdateFailed as u32 ); self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32); @@ -3116,17 +2938,15 @@ impl Channel { // monitor was persisted. let funding_locked = if self.monitor_pending_funding_locked { assert!( - !self.channel_outbound, - "Funding transaction broadcast without FundingBroadcastSafe!" + !self.channel_outbound, + "Funding transaction broadcast without FundingBroadcastSafe!" ); self.monitor_pending_funding_locked = false; let next_per_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret); - Some(msgs::FundingLocked { - channel_id: self.channel_id(), - next_per_commitment_point, - }) + Some(msgs::FundingLocked { channel_id: self.channel_id(), + next_per_commitment_point }) } else { None }; @@ -3139,15 +2959,13 @@ impl Channel { if self.channel_state & (ChannelState::PeerDisconnected as u32) != 0 { self.monitor_pending_revoke_and_ack = false; self.monitor_pending_commitment_signed = false; - return ( - None, - None, - RAACommitmentOrder::RevokeAndACKFirst, - forwards, - failures, - needs_broadcast_safe, - funding_locked, - ); + return (None, + None, + RAACommitmentOrder::RevokeAndACKFirst, + forwards, + failures, + needs_broadcast_safe, + funding_locked); } let raa = if self.monitor_pending_revoke_and_ack { @@ -3165,29 +2983,21 @@ impl Channel { self.monitor_pending_commitment_signed = false; let order = self.resend_order.clone(); log_trace!( - self, - "Restored monitor updating resulting in {}{} commitment update and {} RAA, with {} first", - if needs_broadcast_safe { - "a funding broadcast safe, " - } else { - "" - }, - if commitment_update.is_some() { "a" } else { "no" }, - if raa.is_some() { "an" } else { "no" }, - match order { - RAACommitmentOrder::CommitmentFirst => "commitment", - RAACommitmentOrder::RevokeAndACKFirst => "RAA", - } + self, + "Restored monitor updating resulting in {}{} commitment update and {} RAA, with {} first", + if needs_broadcast_safe { + "a funding broadcast safe, " + } else { + "" + }, + if commitment_update.is_some() { "a" } else { "no" }, + if raa.is_some() { "an" } else { "no" }, + match order { + RAACommitmentOrder::CommitmentFirst => "commitment", + RAACommitmentOrder::RevokeAndACKFirst => "RAA", + } ); - ( - raa, - commitment_update, - order, - forwards, - failures, - needs_broadcast_safe, - funding_locked, - ) + (raa, commitment_update, order, forwards, failures, needs_broadcast_safe, funding_locked) } pub fn update_fee(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::UpdateFee) -> Result<(), ChannelError> { @@ -3195,9 +3005,7 @@ impl Channel { return Err(ChannelError::Close("Non-funding remote tried to update channel fee")); } 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", - )); + return Err(ChannelError::Close("Peer sent update_fee when we needed a channel_reestablish")); } Channel::::check_remote_fee(fee_estimator, msg.feerate_per_kw)?; self.pending_update_fee = Some(msg.feerate_per_kw as u64); @@ -3211,14 +3019,13 @@ impl Channel { &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number), ); let per_commitment_secret = chan_utils::build_commitment_secret( - self.local_keys.commitment_seed(), - self.cur_local_commitment_transaction_number + 2, + self.local_keys.commitment_seed(), + self.cur_local_commitment_transaction_number + + 2, ); - msgs::RevokeAndACK { - channel_id: self.channel_id, - per_commitment_secret, - next_per_commitment_point, - } + msgs::RevokeAndACK { channel_id: self.channel_id, + per_commitment_secret, + next_per_commitment_point } } fn get_last_commitment_update(&self) -> msgs::CommitmentUpdate { @@ -3229,14 +3036,12 @@ impl Channel { for htlc in self.pending_outbound_htlcs.iter() { if let &OutboundHTLCState::LocalAnnounced(ref onion_packet) = &htlc.state { - update_add_htlcs.push(msgs::UpdateAddHTLC { - channel_id: self.channel_id(), - htlc_id: htlc.htlc_id, - amount_msat: htlc.amount_msat, - payment_hash: htlc.payment_hash, - cltv_expiry: htlc.cltv_expiry, - onion_routing_packet: (**onion_packet).clone(), - }); + update_add_htlcs.push(msgs::UpdateAddHTLC { channel_id: self.channel_id(), + htlc_id: htlc.htlc_id, + amount_msat: htlc.amount_msat, + payment_hash: htlc.payment_hash, + cltv_expiry: htlc.cltv_expiry, + onion_routing_packet: (**onion_packet).clone() }); } } @@ -3244,26 +3049,24 @@ impl Channel { if let &InboundHTLCState::LocalRemoved(ref reason) = &htlc.state { match reason { &InboundHTLCRemovalReason::FailRelay(ref err_packet) => { - update_fail_htlcs.push(msgs::UpdateFailHTLC { - channel_id: self.channel_id(), - htlc_id: htlc.htlc_id, - reason: err_packet.clone(), - }); + update_fail_htlcs.push(msgs::UpdateFailHTLC { channel_id: self.channel_id(), + htlc_id: htlc.htlc_id, + reason: err_packet.clone() }); }, &InboundHTLCRemovalReason::FailMalformed((ref sha256_of_onion, ref failure_code)) => { - update_fail_malformed_htlcs.push(msgs::UpdateFailMalformedHTLC { - channel_id: self.channel_id(), - htlc_id: htlc.htlc_id, - sha256_of_onion: sha256_of_onion.clone(), - failure_code: failure_code.clone(), - }); + update_fail_malformed_htlcs.push(msgs::UpdateFailMalformedHTLC { channel_id: + self.channel_id(), + htlc_id: htlc.htlc_id, + sha256_of_onion: + sha256_of_onion.clone(), + failure_code: + failure_code.clone() }); }, &InboundHTLCRemovalReason::Fulfill(ref payment_preimage) => { - update_fulfill_htlcs.push(msgs::UpdateFulfillHTLC { - channel_id: self.channel_id(), - htlc_id: htlc.htlc_id, - payment_preimage: payment_preimage.clone(), - }); + update_fulfill_htlcs.push(msgs::UpdateFulfillHTLC { channel_id: self.channel_id(), + htlc_id: htlc.htlc_id, + payment_preimage: + payment_preimage.clone() }); }, } } @@ -3287,9 +3090,9 @@ impl Channel { /// have been called between remove_uncommitted_htlcs_and_mark_paused and this call. pub fn channel_reestablish( &mut self, - msg: &msgs::ChannelReestablish, - ) -> Result< - ( + msg: &msgs::ChannelReestablish) + -> Result< + ( Option, Option, Option, @@ -3297,20 +3100,18 @@ impl Channel { RAACommitmentOrder, Option, ), - ChannelError, - > { + ChannelError, + > { if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 { // While BOLT 2 doesn't indicate explicitly we should error this channel here, it // almost certainly indicates we are going to end up out-of-sync in some way, so we // just close here instead of trying to recover. - return Err(ChannelError::Close( - "Peer sent a loose channel_reestablish not after reconnect", - )); + return Err(ChannelError::Close("Peer sent a loose channel_reestablish not after reconnect")); } if msg.next_local_commitment_number >= INITIAL_COMMITMENT_NUMBER - || msg.next_remote_commitment_number >= INITIAL_COMMITMENT_NUMBER - || msg.next_local_commitment_number == 0 + || msg.next_remote_commitment_number >= INITIAL_COMMITMENT_NUMBER + || msg.next_local_commitment_number == 0 { return Err(ChannelError::Close("Peer sent a garbage channel_reestablish")); } @@ -3319,17 +3120,19 @@ impl Channel { match msg.data_loss_protect { OptionalField::Present(ref data_loss) => { if chan_utils::build_commitment_secret( - self.local_keys.commitment_seed(), - INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, + self.local_keys.commitment_seed(), + INITIAL_COMMITMENT_NUMBER + - msg.next_remote_commitment_number + + 1, ) != data_loss.your_last_per_commitment_secret { return Err(ChannelError::Close("Peer sent a garbage channel_reestablish with secret key not matching the commitment height provided")); } if msg.next_remote_commitment_number - > INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number + > INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number { self.channel_monitor - .provide_rescue_remote_commitment_tx_info(data_loss.my_current_per_commitment_point); + .provide_rescue_remote_commitment_tx_info(data_loss.my_current_per_commitment_point); return Err(ChannelError::CloseDelayBroadcast { msg: "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting", update: Some(self.channel_monitor.clone()) }); } }, @@ -3342,10 +3145,8 @@ impl Channel { self.channel_state &= !(ChannelState::PeerDisconnected as u32); let shutdown_msg = if self.channel_state & (ChannelState::LocalShutdownSent as u32) != 0 { - Some(msgs::Shutdown { - channel_id: self.channel_id, - scriptpubkey: self.get_closing_scriptpubkey(), - }) + Some(msgs::Shutdown { channel_id: self.channel_id, + scriptpubkey: self.get_closing_scriptpubkey() }) } else { None }; @@ -3353,7 +3154,7 @@ impl Channel { if self.channel_state & (ChannelState::FundingSent as u32) == ChannelState::FundingSent as u32 { // If we're waiting on a monitor update, we shouldn't re-send any funding_locked's. if self.channel_state & (ChannelState::OurFundingLocked as u32) == 0 - || self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 + || self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 { if msg.next_remote_commitment_number != 0 { return Err(ChannelError::Close( @@ -3361,41 +3162,30 @@ impl Channel { )); } // Short circuit the whole handler as there is nothing we can resend them - return Ok(( - None, - None, - None, - None, - RAACommitmentOrder::CommitmentFirst, - shutdown_msg, - )); + return Ok((None, None, None, None, RAACommitmentOrder::CommitmentFirst, shutdown_msg)); } // We have OurFundingLocked set! let next_per_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret); - return Ok(( - Some(msgs::FundingLocked { - channel_id: self.channel_id(), - next_per_commitment_point, - }), - None, - None, - None, - RAACommitmentOrder::CommitmentFirst, - shutdown_msg, - )); + return Ok((Some(msgs::FundingLocked { channel_id: self.channel_id(), + next_per_commitment_point }), + None, + None, + None, + RAACommitmentOrder::CommitmentFirst, + shutdown_msg)); } let required_revoke = if msg.next_remote_commitment_number + 1 - == INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number + == INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number { // Remote isn't waiting on any RevokeAndACK from us! // Note that if we need to repeat our FundingLocked we'll do that in the next if block. None } else if msg.next_remote_commitment_number + 1 - == (INITIAL_COMMITMENT_NUMBER - 1) - self.cur_local_commitment_transaction_number + == (INITIAL_COMMITMENT_NUMBER - 1) - self.cur_local_commitment_transaction_number { if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 { self.monitor_pending_revoke_and_ack = true; @@ -3413,8 +3203,8 @@ impl Channel { // revoke_and_ack, not on sending commitment_signed, so we add one if have // AwaitingRemoteRevoke set, which indicates we sent a commitment_signed but haven't gotten // the corresponding revoke_and_ack back yet. - let our_next_remote_commitment_number = INITIAL_COMMITMENT_NUMBER - - self.cur_remote_commitment_transaction_number + let our_next_remote_commitment_number = + INITIAL_COMMITMENT_NUMBER - self.cur_remote_commitment_transaction_number + if (self.channel_state & ChannelState::AwaitingRemoteRevoke as u32) != 0 { 1 } else { @@ -3422,16 +3212,14 @@ impl Channel { }; let resend_funding_locked = if msg.next_local_commitment_number == 1 - && INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number == 1 + && INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number == 1 { // We should never have to worry about MonitorUpdateFailed resending FundingLocked let next_per_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret); - Some(msgs::FundingLocked { - channel_id: self.channel_id(), - next_per_commitment_point, - }) + Some(msgs::FundingLocked { channel_id: self.channel_id(), + next_per_commitment_point }) } else { None }; @@ -3439,21 +3227,21 @@ impl Channel { if msg.next_local_commitment_number == our_next_remote_commitment_number { if required_revoke.is_some() { log_debug!( - self, - "Reconnected channel {} with only lost outbound RAA", - log_bytes!(self.channel_id()) + self, + "Reconnected channel {} with only lost outbound RAA", + log_bytes!(self.channel_id()) ); } else { log_debug!( - self, - "Reconnected channel {} with no loss", - log_bytes!(self.channel_id()) + self, + "Reconnected channel {} with no loss", + log_bytes!(self.channel_id()) ); } if (self.channel_state - & (ChannelState::AwaitingRemoteRevoke as u32 | ChannelState::MonitorUpdateFailed as u32)) - == 0 + & (ChannelState::AwaitingRemoteRevoke as u32 | ChannelState::MonitorUpdateFailed as u32)) + == 0 { // We're up-to-date and not waiting on a remote revoke (if we are our // channel_reestablish should result in them sending a revoke_and_ack), but we may @@ -3465,71 +3253,56 @@ impl Channel { panic!("Got non-channel-failing result from free_holding_cell_htlcs") }, Ok(Some((commitment_update, channel_monitor))) => { - return Ok(( - resend_funding_locked, - required_revoke, - Some(commitment_update), - Some(channel_monitor), - self.resend_order.clone(), - shutdown_msg, - )) + return Ok((resend_funding_locked, + required_revoke, + Some(commitment_update), + Some(channel_monitor), + self.resend_order.clone(), + shutdown_msg)) }, Ok(None) => { - return Ok(( - resend_funding_locked, - required_revoke, - None, - None, - self.resend_order.clone(), - shutdown_msg, - )) + return Ok((resend_funding_locked, + required_revoke, + None, + None, + self.resend_order.clone(), + shutdown_msg)) }, } } else { - return Ok(( - resend_funding_locked, - required_revoke, - None, - None, - self.resend_order.clone(), - shutdown_msg, - )); + return Ok((resend_funding_locked, + required_revoke, + None, + None, + self.resend_order.clone(), + shutdown_msg)); } } else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 { if required_revoke.is_some() { log_debug!( - self, - "Reconnected channel {} with lost outbound RAA and lost remote commitment tx", - log_bytes!(self.channel_id()) + self, + "Reconnected channel {} with lost outbound RAA and lost remote commitment tx", + log_bytes!(self.channel_id()) ); } else { log_debug!( - self, - "Reconnected channel {} with only lost remote commitment tx", - log_bytes!(self.channel_id()) + self, + "Reconnected channel {} with only lost remote commitment tx", + log_bytes!(self.channel_id()) ); } if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 { self.monitor_pending_commitment_signed = true; - return Ok(( - resend_funding_locked, - None, - None, - None, - self.resend_order.clone(), - shutdown_msg, - )); + return Ok((resend_funding_locked, None, None, None, self.resend_order.clone(), shutdown_msg)); } - return Ok(( - resend_funding_locked, - required_revoke, - Some(self.get_last_commitment_update()), - None, - self.resend_order.clone(), - shutdown_msg, - )); + return Ok((resend_funding_locked, + required_revoke, + Some(self.get_last_commitment_update()), + None, + self.resend_order.clone(), + shutdown_msg)); } else { return Err(ChannelError::Close( "Peer attempted to reestablish channel with a very old remote commitment transaction", @@ -3539,12 +3312,12 @@ impl Channel { fn maybe_propose_first_closing_signed(&mut self, fee_estimator: &FeeEstimator) -> Option { if !self.channel_outbound - || !self.pending_inbound_htlcs.is_empty() - || !self.pending_outbound_htlcs.is_empty() - || self.channel_state & (BOTH_SIDES_SHUTDOWN_MASK | ChannelState::AwaitingRemoteRevoke as u32) - != BOTH_SIDES_SHUTDOWN_MASK - || self.last_sent_closing_fee.is_some() - || self.pending_update_fee.is_some() + || !self.pending_inbound_htlcs.is_empty() + || !self.pending_outbound_htlcs.is_empty() + || self.channel_state & (BOTH_SIDES_SHUTDOWN_MASK | ChannelState::AwaitingRemoteRevoke as u32) + != BOTH_SIDES_SHUTDOWN_MASK + || self.last_sent_closing_fee.is_some() + || self.pending_update_fee.is_some() { return None; } @@ -3554,49 +3327,37 @@ impl Channel { proposed_feerate = self.feerate_per_kw; } let tx_weight = Self::get_closing_transaction_weight( - &self.get_closing_scriptpubkey(), - self.their_shutdown_scriptpubkey.as_ref().unwrap(), + &self.get_closing_scriptpubkey(), + self.their_shutdown_scriptpubkey.as_ref().unwrap(), ); let proposed_total_fee_satoshis = proposed_feerate * tx_weight / 1000; let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(proposed_total_fee_satoshis, false); - let our_sig = self - .local_keys - .sign_closing_transaction( - self.channel_value_satoshis, - &self.get_funding_redeemscript(), - &closing_tx, - &self.secp_ctx, - ) - .ok(); + let our_sig = self.local_keys + .sign_closing_transaction( + self.channel_value_satoshis, + &self.get_funding_redeemscript(), + &closing_tx, + &self.secp_ctx, + ) + .ok(); if our_sig.is_none() { return None; } self.last_sent_closing_fee = Some((proposed_feerate, total_fee_satoshis, our_sig.clone().unwrap())); - Some(msgs::ClosingSigned { - channel_id: self.channel_id, - fee_satoshis: total_fee_satoshis, - signature: our_sig.unwrap(), - }) + Some(msgs::ClosingSigned { channel_id: self.channel_id, + fee_satoshis: total_fee_satoshis, + signature: our_sig.unwrap() }) } pub fn shutdown( &mut self, fee_estimator: &FeeEstimator, - msg: &msgs::Shutdown, - ) -> Result< - ( - Option, - Option, - Vec<(HTLCSource, PaymentHash)>, - ), - ChannelError, - > { + msg: &msgs::Shutdown) + -> Result<(Option, Option, Vec<(HTLCSource, PaymentHash)>), ChannelError> { if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent shutdown when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent shutdown when we needed a channel_reestablish")); } if self.channel_state < ChannelState::FundingSent as u32 { // Spec says we should fail the connection, not the channel, but that's nonsense, there @@ -3614,16 +3375,14 @@ impl Channel { // BOLT 2 says we must only send a scriptpubkey of certain standard forms, which are up to // 34 bytes in length, so don't let the remote peer feed us some super fee-heavy script. if self.channel_outbound && msg.scriptpubkey.len() > 34 { - return Err(ChannelError::Close( - "Got shutdown_scriptpubkey of absurd length from remote peer", - )); + return Err(ChannelError::Close("Got shutdown_scriptpubkey of absurd length from remote peer")); } //Check shutdown_scriptpubkey form as BOLT says we must if !msg.scriptpubkey.is_p2pkh() - && !msg.scriptpubkey.is_p2sh() - && !msg.scriptpubkey.is_v0_p2wpkh() - && !msg.scriptpubkey.is_v0_p2wsh() + && !msg.scriptpubkey.is_p2sh() + && !msg.scriptpubkey.is_v0_p2wpkh() + && !msg.scriptpubkey.is_v0_p2wsh() { return Err(ChannelError::Close("Got a nonstandard scriptpubkey from remote peer")); } @@ -3649,38 +3408,30 @@ impl Channel { self.holding_cell_update_fee = None; let mut dropped_outbound_htlcs = Vec::with_capacity(self.holding_cell_htlc_updates.len()); self.holding_cell_htlc_updates.retain(|htlc_update| match htlc_update { - &HTLCUpdateAwaitingACK::AddHTLC { - ref payment_hash, - ref source, - .. - } => { - dropped_outbound_htlcs.push((source.clone(), payment_hash.clone())); - false - }, - _ => true, - }); + &HTLCUpdateAwaitingACK::AddHTLC { ref payment_hash, + ref source, + .. } => { + dropped_outbound_htlcs.push((source.clone(), payment_hash.clone())); + false + }, + _ => true, + }); // If we have any LocalAnnounced updates we'll probably just get back a update_fail_htlc // immediately after the commitment dance, but we can send a Shutdown cause we won't send // any further commitment updates after we set LocalShutdownSent. let our_shutdown = if (self.channel_state & ChannelState::LocalShutdownSent as u32) - == ChannelState::LocalShutdownSent as u32 + == ChannelState::LocalShutdownSent as u32 { None } else { - Some(msgs::Shutdown { - channel_id: self.channel_id, - scriptpubkey: self.get_closing_scriptpubkey(), - }) + Some(msgs::Shutdown { channel_id: self.channel_id, + scriptpubkey: self.get_closing_scriptpubkey() }) }; self.channel_state |= ChannelState::LocalShutdownSent as u32; self.channel_update_count += 1; - Ok(( - our_shutdown, - self.maybe_propose_first_closing_signed(fee_estimator), - dropped_outbound_htlcs, - )) + Ok((our_shutdown, self.maybe_propose_first_closing_signed(fee_estimator), dropped_outbound_htlcs)) } fn build_signed_closing_transaction(&self, tx: &mut Transaction, their_sig: &Signature, our_sig: &Signature) { @@ -3711,20 +3462,17 @@ impl Channel { tx.input[0].witness.push(self.get_funding_redeemscript().into_bytes()); } - pub fn closing_signed( - &mut self, - fee_estimator: &FeeEstimator, - msg: &msgs::ClosingSigned, - ) -> Result<(Option, Option), ChannelError> { + pub fn closing_signed(&mut self, + fee_estimator: &FeeEstimator, + msg: &msgs::ClosingSigned) + -> Result<(Option, Option), ChannelError> { if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK != BOTH_SIDES_SHUTDOWN_MASK { return Err(ChannelError::Close( "Remote end sent us a closing_signed before both sides provided a shutdown", )); } if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { - return Err(ChannelError::Close( - "Peer sent closing_signed when we needed a channel_reestablish", - )); + return Err(ChannelError::Close("Peer sent closing_signed when we needed a channel_reestablish")); } if !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() { return Err(ChannelError::Close( @@ -3733,9 +3481,7 @@ impl Channel { } if msg.fee_satoshis > 21000000 * 10000000 { //this is required to stop potential overflow in build_closing_transaction - return Err(ChannelError::Close( - "Remote tried to send us a closing tx with > 21 million BTC fee", - )); + return Err(ChannelError::Close("Remote tried to send us a closing tx with > 21 million BTC fee")); } let funding_redeemscript = self.get_funding_redeemscript(); @@ -3753,9 +3499,8 @@ impl Channel { )[..] ); - match self - .secp_ctx - .verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()) + match self.secp_ctx + .verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()) { Ok(_) => {}, Err(_e) => { @@ -3770,9 +3515,9 @@ impl Channel { )[..] ); secp_check!( - self.secp_ctx - .verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), - "Invalid closing tx signature from peer" + self.secp_ctx + .verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), + "Invalid closing tx signature from peer" ); }, }; @@ -3819,28 +3564,23 @@ impl Channel { } } - let our_sig = self - .local_keys - .sign_closing_transaction( - self.channel_value_satoshis, - &funding_redeemscript, - &closing_tx, - &self.secp_ctx, - ) - .map_err(|_| ChannelError::Close("External signer refused to sign closing transaction"))?; + let our_sig = self.local_keys + .sign_closing_transaction( + self.channel_value_satoshis, + &funding_redeemscript, + &closing_tx, + &self.secp_ctx, + ) + .map_err(|_| ChannelError::Close("External signer refused to sign closing transaction"))?; self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &our_sig); self.channel_state = ChannelState::ShutdownComplete as u32; self.channel_update_count += 1; - Ok(( - Some(msgs::ClosingSigned { - channel_id: self.channel_id, - fee_satoshis: msg.fee_satoshis, - signature: our_sig, - }), - Some(closing_tx), - )) + Ok((Some(msgs::ClosingSigned { channel_id: self.channel_id, + fee_satoshis: msg.fee_satoshis, + signature: our_sig }), + Some(closing_tx))) } // Public utilities: @@ -3890,11 +3630,11 @@ impl Channel { pub fn get_cur_remote_commitment_transaction_number(&self) -> u64 { self.cur_remote_commitment_transaction_number + 1 - - if self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32) != 0 { - 1 - } else { - 0 - } + - if self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32) != 0 { + 1 + } else { + 0 + } } pub fn get_revoked_remote_commitment_transaction_number(&self) -> u64 { @@ -3906,34 +3646,30 @@ impl Channel { #[cfg(test)] pub fn get_value_stat(&self) -> ChannelValueStat { - ChannelValueStat { - value_to_self_msat: self.value_to_self_msat, - channel_value_msat: self.channel_value_satoshis * 1000, - channel_reserve_msat: self.their_channel_reserve_satoshis * 1000, - pending_outbound_htlcs_amount_msat: self - .pending_outbound_htlcs - .iter() - .map(|ref h| h.amount_msat) - .sum::(), - pending_inbound_htlcs_amount_msat: self - .pending_inbound_htlcs - .iter() - .map(|ref h| h.amount_msat) - .sum::(), - holding_cell_outbound_amount_msat: { - let mut res = 0; - for h in self.holding_cell_htlc_updates.iter() { - match h { - &HTLCUpdateAwaitingACK::AddHTLC { amount_msat, .. } => { - res += amount_msat; - }, - _ => {}, - } - } - res - }, - their_max_htlc_value_in_flight_msat: self.their_max_htlc_value_in_flight_msat, - } + ChannelValueStat { value_to_self_msat: self.value_to_self_msat, + channel_value_msat: self.channel_value_satoshis * 1000, + channel_reserve_msat: self.their_channel_reserve_satoshis * 1000, + pending_outbound_htlcs_amount_msat: self.pending_outbound_htlcs + .iter() + .map(|ref h| h.amount_msat) + .sum::(), + pending_inbound_htlcs_amount_msat: self.pending_inbound_htlcs + .iter() + .map(|ref h| h.amount_msat) + .sum::(), + holding_cell_outbound_amount_msat: { + let mut res = 0; + for h in self.holding_cell_htlc_updates.iter() { + match h { + &HTLCUpdateAwaitingACK::AddHTLC { amount_msat, .. } => { + res += amount_msat; + }, + _ => {}, + } + } + res + }, + their_max_htlc_value_in_flight_msat: self.their_max_htlc_value_in_flight_msat } } /// Allowed in any state (including after shutdown) @@ -3959,8 +3695,8 @@ impl Channel { // + the marginal cost of an input which spends the HTLC-Success/HTLC-Timeout output: res += fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) - * SPENDING_INPUT_FOR_A_OUTPUT_WEIGHT - / 1000; + * SPENDING_INPUT_FOR_A_OUTPUT_WEIGHT + / 1000; res as u32 } @@ -3980,8 +3716,8 @@ impl Channel { /// Allowed in any state (including after shutdown) pub fn is_live(&self) -> bool { self.is_usable() - && (self.channel_state & (ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32) - == 0) + && (self.channel_state & (ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32) + == 0) } /// Returns true if this channel has been marked as awaiting a monitor update to move forward. @@ -4021,13 +3757,12 @@ impl Channel { /// In case of Err, the channel may have been closed, at which point the standard requirements /// apply - no calls may be made except those explicitly stated to be allowed post-shutdown. /// Only returns an ErrorAction of DisconnectPeer, if Err. - pub fn block_connected( - &mut self, - header: &BlockHeader, - height: u32, - txn_matched: &[&Transaction], - indexes_of_txn_matched: &[u32], - ) -> Result, msgs::ErrorMessage> { + pub fn block_connected(&mut self, + header: &BlockHeader, + height: u32, + txn_matched: &[&Transaction], + indexes_of_txn_matched: &[u32]) + -> Result, msgs::ErrorMessage> { let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS); if header.bitcoin_hash() != self.last_block_connected { self.last_block_connected = header.bitcoin_hash(); @@ -4039,22 +3774,22 @@ impl Channel { self.channel_state |= ChannelState::OurFundingLocked as u32; true } else if non_shutdown_state - == (ChannelState::FundingSent as u32 | ChannelState::TheirFundingLocked as u32) + == (ChannelState::FundingSent as u32 | ChannelState::TheirFundingLocked as u32) { self.channel_state = ChannelState::ChannelFunded as u32 | (self.channel_state & MULTI_STATE_FLAGS); self.channel_update_count += 1; true } else if non_shutdown_state - == (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) + == (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) { // We got a reorg but not enough to trigger a force close, just update // funding_tx_confirmed_in and return. false } else if self.channel_state < ChannelState::ChannelFunded as u32 { panic!( - "Started confirming a channel in a state pre-FundingSent?: {}", - self.channel_state + "Started confirming a channel in a state pre-FundingSent?: {}", + self.channel_state ); } else { // We got a reorg but not enough to trigger a force close, just update @@ -4073,10 +3808,8 @@ impl Channel { self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret); - return Ok(Some(msgs::FundingLocked { - channel_id: self.channel_id, - next_per_commitment_point, - })); + return Ok(Some(msgs::FundingLocked { channel_id: self.channel_id, + next_per_commitment_point })); } else { self.monitor_pending_funding_locked = true; return Ok(None); @@ -4090,8 +3823,8 @@ impl Channel { if tx.txid() == self.channel_monitor.get_funding_txo().unwrap().txid { let txo_idx = self.channel_monitor.get_funding_txo().unwrap().index as usize; if txo_idx >= tx.output.len() - || tx.output[txo_idx].script_pubkey != self.get_funding_redeemscript().to_v0_p2wsh() - || tx.output[txo_idx].value != self.channel_value_satoshis + || tx.output[txo_idx].script_pubkey != self.get_funding_redeemscript().to_v0_p2wsh() + || tx.output[txo_idx].value != self.channel_value_satoshis { if self.channel_outbound { // If we generated the funding transaction and it doesn't match what it @@ -4106,10 +3839,8 @@ impl Channel { } self.channel_state = ChannelState::ShutdownComplete as u32; self.channel_update_count += 1; - return Err(msgs::ErrorMessage { - channel_id: self.channel_id(), - data: "funding tx had wrong script/value".to_owned(), - }); + return Err(msgs::ErrorMessage { channel_id: self.channel_id(), + data: "funding tx had wrong script/value".to_owned() }); } else { if self.channel_outbound { for input in tx.input.iter() { @@ -4123,9 +3854,9 @@ impl Channel { } self.funding_tx_confirmations = 1; self.short_channel_id = Some( - ((height as u64) << (5 * 8)) - | ((*index_in_block as u64) << (2 * 8)) - | ((txo_idx as u64) << (0 * 8)), + ((height as u64) << (5 * 8)) + | ((*index_in_block as u64) << (2 * 8)) + | ((txo_idx as u64) << (0 * 8)), ); } } @@ -4249,31 +3980,29 @@ impl Channel { /// If an Err is returned, it is a ChannelError::Close (for get_outbound_funding_created) fn get_outbound_funding_created_signature(&mut self) -> Result<(Signature, Transaction), ChannelError> { let remote_keys = self.build_remote_transaction_keys()?; - let remote_initial_commitment_tx = self - .build_commitment_transaction( - self.cur_remote_commitment_transaction_number, - &remote_keys, - false, - false, - self.feerate_per_kw, + let remote_initial_commitment_tx = + self.build_commitment_transaction( + self.cur_remote_commitment_transaction_number, + &remote_keys, + false, + false, + self.feerate_per_kw, ) - .0; - Ok(( - self.local_keys - .sign_remote_commitment( - self.channel_value_satoshis, - &self.get_funding_redeemscript(), - self.feerate_per_kw, - &remote_initial_commitment_tx, - &remote_keys, - &Vec::new(), - self.our_to_self_delay, - &self.secp_ctx, - ) - .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed"))? - .0, - remote_initial_commitment_tx, - )) + .0; + Ok((self.local_keys + .sign_remote_commitment( + self.channel_value_satoshis, + &self.get_funding_redeemscript(), + self.feerate_per_kw, + &remote_initial_commitment_tx, + &remote_keys, + &Vec::new(), + self.our_to_self_delay, + &self.secp_ctx, + ) + .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed"))? + .0, + remote_initial_commitment_tx)) } /// Updates channel state with knowledge of the funding transaction's txid/index, and generates @@ -4283,10 +4012,9 @@ impl Channel { /// Note that channel_id changes during this call! /// Do NOT broadcast the funding transaction until after a successful funding_signed call! /// If an Err is returned, it is a ChannelError::Close. - pub fn get_outbound_funding_created( - &mut self, - funding_txo: OutPoint, - ) -> Result<(msgs::FundingCreated, ChannelMonitor), ChannelError> { + pub fn get_outbound_funding_created(&mut self, + funding_txo: OutPoint) + -> Result<(msgs::FundingCreated, ChannelMonitor), ChannelError> { if !self.channel_outbound { panic!("Tried to create outbound funding_created message on an inbound channel!"); } @@ -4294,8 +4022,8 @@ impl Channel { panic!("Tried to get a funding_created messsage at a time other than immediately after initial handshake completion (or tried to get funding_created twice)"); } if self.channel_monitor.get_min_seen_secret() != (1 << 48) - || self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER - || self.cur_local_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER + || self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER + || self.cur_local_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER { panic!("Should not have advanced channel commitment tx numbers prior to funding_created"); } @@ -4316,24 +4044,20 @@ impl Channel { // Now that we're past error-generating stuff, update our local state: self.channel_monitor.provide_latest_remote_commitment_tx_info( - &commitment_tx, - Vec::new(), - self.cur_remote_commitment_transaction_number, - self.their_cur_commitment_point.unwrap(), + &commitment_tx, + Vec::new(), + self.cur_remote_commitment_transaction_number, + self.their_cur_commitment_point.unwrap(), ); self.channel_state = ChannelState::FundingCreated as u32; self.channel_id = funding_txo.to_channel_id(); self.cur_remote_commitment_transaction_number -= 1; - Ok(( - msgs::FundingCreated { - temporary_channel_id, - funding_txid: funding_txo.txid, - funding_output_index: funding_txo.index, - signature: our_signature, - }, - self.channel_monitor.clone(), - )) + Ok((msgs::FundingCreated { temporary_channel_id, + funding_txid: funding_txo.txid, + funding_output_index: funding_txo.index, + signature: our_signature }, + self.channel_monitor.clone())) } /// Gets an UnsignedChannelAnnouncement, as well as a signature covering it using our @@ -4344,15 +4068,12 @@ impl Channel { /// closing). /// Note that the "channel must be funded" requirement is stricter than BOLT 7 requires - see /// https://github.com/lightningnetwork/lightning-rfc/issues/468 - pub fn get_channel_announcement( - &self, - our_node_id: PublicKey, - chain_hash: Sha256dHash, - ) -> Result<(msgs::UnsignedChannelAnnouncement, Signature), ChannelError> { + pub fn get_channel_announcement(&self, + our_node_id: PublicKey, + chain_hash: Sha256dHash) + -> Result<(msgs::UnsignedChannelAnnouncement, Signature), ChannelError> { if !self.config.announced_channel { - return Err(ChannelError::Ignore( - "Channel is not available for public announcements", - )); + return Err(ChannelError::Ignore("Channel is not available for public announcements")); } if self.channel_state & (ChannelState::ChannelFunded as u32) == 0 { return Err(ChannelError::Ignore( @@ -4361,45 +4082,40 @@ impl Channel { } if (self.channel_state & (ChannelState::LocalShutdownSent as u32 | ChannelState::ShutdownComplete as u32)) != 0 { - return Err(ChannelError::Ignore( - "Cannot get a ChannelAnnouncement once the channel is closing", - )); + return Err(ChannelError::Ignore("Cannot get a ChannelAnnouncement once the channel is closing")); } let were_node_one = our_node_id.serialize()[..] < self.their_node_id.serialize()[..]; let our_bitcoin_key = PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()); - let msg = msgs::UnsignedChannelAnnouncement { - features: msgs::GlobalFeatures::new(), - chain_hash, - short_channel_id: self.get_short_channel_id().unwrap(), - node_id_1: if were_node_one { - our_node_id - } else { - self.get_their_node_id() - }, - node_id_2: if were_node_one { - self.get_their_node_id() - } else { - our_node_id - }, - bitcoin_key_1: if were_node_one { - our_bitcoin_key - } else { - self.their_funding_pubkey.unwrap() - }, - bitcoin_key_2: if were_node_one { - self.their_funding_pubkey.unwrap() - } else { - our_bitcoin_key - }, - excess_data: Vec::new(), - }; - - let sig = self - .local_keys - .sign_channel_announcement(&msg, &self.secp_ctx) - .map_err(|_| ChannelError::Ignore("Signer rejected channel_announcement"))?; + let msg = msgs::UnsignedChannelAnnouncement { features: msgs::GlobalFeatures::new(), + chain_hash, + short_channel_id: self.get_short_channel_id().unwrap(), + node_id_1: if were_node_one { + our_node_id + } else { + self.get_their_node_id() + }, + node_id_2: if were_node_one { + self.get_their_node_id() + } else { + our_node_id + }, + bitcoin_key_1: if were_node_one { + our_bitcoin_key + } else { + self.their_funding_pubkey.unwrap() + }, + bitcoin_key_2: if were_node_one { + self.their_funding_pubkey.unwrap() + } else { + our_bitcoin_key + }, + excess_data: Vec::new() }; + + let sig = self.local_keys + .sign_channel_announcement(&msg, &self.secp_ctx) + .map_err(|_| ChannelError::Ignore("Signer rejected channel_announcement"))?; Ok((msg, sig)) } @@ -4408,19 +4124,18 @@ impl Channel { /// self.remove_uncommitted_htlcs_and_mark_paused()'d pub fn get_channel_reestablish(&self) -> msgs::ChannelReestablish { assert_eq!( - self.channel_state & ChannelState::PeerDisconnected as u32, - ChannelState::PeerDisconnected as u32 + self.channel_state & ChannelState::PeerDisconnected as u32, + ChannelState::PeerDisconnected as u32 ); assert_ne!(self.cur_remote_commitment_transaction_number, INITIAL_COMMITMENT_NUMBER); let data_loss_protect = if self.cur_remote_commitment_transaction_number + 1 < INITIAL_COMMITMENT_NUMBER { - let remote_last_secret = self - .channel_monitor - .get_secret(self.cur_remote_commitment_transaction_number + 2) - .unwrap(); + let remote_last_secret = self.channel_monitor + .get_secret(self.cur_remote_commitment_transaction_number + 2) + .unwrap(); log_trace!( - self, - "Enough info to generate a Data Loss Protect with per_commitment_secret {}", - log_bytes!(remote_last_secret) + self, + "Enough info to generate a Data Loss Protect with per_commitment_secret {}", + log_bytes!(remote_last_secret) ); OptionalField::Present(DataLossProtect { your_last_per_commitment_secret: remote_last_secret, @@ -4439,30 +4154,29 @@ impl Channel { ), }) }; - msgs::ChannelReestablish { - channel_id: self.channel_id(), - // The protocol has two different commitment number concepts - the "commitment - // transaction number", which starts from 0 and counts up, and the "revocation key - // index" which starts at INITIAL_COMMITMENT_NUMBER and counts down. We track - // commitment transaction numbers by the index which will be used to reveal the - // revocation key for that commitment transaction, which means we have to convert them - // to protocol-level commitment numbers here... - - // next_local_commitment_number is the next commitment_signed number we expect to - // receive (indicating if they need to resend one that we missed). - next_local_commitment_number: INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number, - // We have to set next_remote_commitment_number to the next revoke_and_ack we expect to - // receive, however we track it by the next commitment number for a remote transaction - // (which is one further, as they always revoke previous commitment transaction, not - // the one we send) so we have to decrement by 1. Note that if - // cur_remote_commitment_transaction_number is INITIAL_COMMITMENT_NUMBER we will have - // dropped this channel on disconnect as it hasn't yet reached FundingSent so we can't - // overflow here. - next_remote_commitment_number: INITIAL_COMMITMENT_NUMBER - - self.cur_remote_commitment_transaction_number - - 1, - data_loss_protect, - } + msgs::ChannelReestablish { channel_id: self.channel_id(), + // The protocol has two different commitment number concepts - the "commitment + // transaction number", which starts from 0 and counts up, and the "revocation key + // index" which starts at INITIAL_COMMITMENT_NUMBER and counts down. We track + // commitment transaction numbers by the index which will be used to reveal the + // revocation key for that commitment transaction, which means we have to convert them + // to protocol-level commitment numbers here... + + // next_local_commitment_number is the next commitment_signed number we expect to + // receive (indicating if they need to resend one that we missed). + next_local_commitment_number: INITIAL_COMMITMENT_NUMBER + - self.cur_local_commitment_transaction_number, + // We have to set next_remote_commitment_number to the next revoke_and_ack we expect to + // receive, however we track it by the next commitment number for a remote transaction + // (which is one further, as they always revoke previous commitment transaction, not + // the one we send) so we have to decrement by 1. Note that if + // cur_remote_commitment_transaction_number is INITIAL_COMMITMENT_NUMBER we will have + // dropped this channel on disconnect as it hasn't yet reached FundingSent so we can't + // overflow here. + next_remote_commitment_number: INITIAL_COMMITMENT_NUMBER + - self.cur_remote_commitment_transaction_number + - 1, + data_loss_protect } } // Send stuff to our remote peers: @@ -4474,16 +4188,15 @@ impl Channel { /// HTLCs on the wire or we wouldn't be able to determine what they actually ACK'ed. /// You MUST call send_commitment prior to any other calls on this Channel /// If an Err is returned, it's a ChannelError::Ignore! - pub fn send_htlc( - &mut self, - amount_msat: u64, - payment_hash: PaymentHash, - cltv_expiry: u32, - source: HTLCSource, - onion_routing_packet: msgs::OnionPacket, - ) -> Result, ChannelError> { + pub fn send_htlc(&mut self, + amount_msat: u64, + payment_hash: PaymentHash, + cltv_expiry: u32, + source: HTLCSource, + onion_routing_packet: msgs::OnionPacket) + -> Result, ChannelError> { if (self.channel_state & (ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK)) - != (ChannelState::ChannelFunded as u32) + != (ChannelState::ChannelFunded as u32) { return Err(ChannelError::Ignore( "Cannot send HTLC until channel is fully established and we haven't started shutting down", @@ -4491,16 +4204,14 @@ impl Channel { } if amount_msat > self.channel_value_satoshis * 1000 { - return Err(ChannelError::Ignore( - "Cannot send more than the total value of the channel", - )); + return Err(ChannelError::Ignore("Cannot send more than the total value of the channel")); } if amount_msat < self.their_htlc_minimum_msat { return Err(ChannelError::Ignore("Cannot send less than their minimum HTLC value")); } if (self.channel_state & (ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32)) - != 0 + != 0 { // Note that this should never really happen, if we're !is_live() on receipt of an // incoming HTLC for relay will result in us rejecting the HTLC and we won't allow @@ -4528,44 +4239,39 @@ impl Channel { // reserve for them to have something to claim if we misbehave) if self.value_to_self_msat < self.their_channel_reserve_satoshis * 1000 + amount_msat + htlc_outbound_value_msat { - return Err(ChannelError::Ignore( - "Cannot send value that would put us over their reserve value", - )); + return Err(ChannelError::Ignore("Cannot send value that would put us over their reserve value")); } //TODO: Check cltv_expiry? Do this in channel manager? // Now update local state: if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) - == (ChannelState::AwaitingRemoteRevoke as u32) + == (ChannelState::AwaitingRemoteRevoke as u32) { - self.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::AddHTLC { - amount_msat, - payment_hash, - cltv_expiry, - source, - onion_routing_packet, - }); + self.holding_cell_htlc_updates + .push(HTLCUpdateAwaitingACK::AddHTLC { amount_msat, + payment_hash, + cltv_expiry, + source, + onion_routing_packet }); return Ok(None); } - self.pending_outbound_htlcs.push(OutboundHTLCOutput { - htlc_id: self.next_local_htlc_id, - amount_msat, - payment_hash: payment_hash.clone(), - cltv_expiry, - state: OutboundHTLCState::LocalAnnounced(Box::new(onion_routing_packet.clone())), - source, - }); - - let res = msgs::UpdateAddHTLC { - channel_id: self.channel_id, - htlc_id: self.next_local_htlc_id, - amount_msat, - payment_hash, - cltv_expiry, - onion_routing_packet, - }; + self.pending_outbound_htlcs + .push(OutboundHTLCOutput { htlc_id: self.next_local_htlc_id, + amount_msat, + payment_hash: payment_hash.clone(), + cltv_expiry, + state: + OutboundHTLCState::LocalAnnounced(Box::new(onion_routing_packet.clone())), + source }); + + let res = msgs::UpdateAddHTLC { channel_id: self.channel_id, + htlc_id: self.next_local_htlc_id, + amount_msat, + payment_hash, + cltv_expiry, + onion_routing_packet }; self.next_local_htlc_id += 1; Ok(Some(res)) @@ -4580,7 +4286,7 @@ impl Channel { panic!("Cannot create commitment tx until channel is fully established"); } if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) - == (ChannelState::AwaitingRemoteRevoke as u32) + == (ChannelState::AwaitingRemoteRevoke as u32) { panic!("Cannot create commitment tx until remote revokes their previous commitment"); } @@ -4588,7 +4294,7 @@ impl Channel { panic!("Cannot create commitment tx while disconnected, as send_htlc will have returned an Err so a send_commitment precondition has been violated"); } if (self.channel_state & (ChannelState::MonitorUpdateFailed as u32)) - == (ChannelState::MonitorUpdateFailed as u32) + == (ChannelState::MonitorUpdateFailed as u32) { panic!("Cannot create commitment tx while awaiting monitor update unfreeze, as send_htlc will have returned an Err so a send_commitment precondition has been violated"); } @@ -4644,20 +4350,19 @@ impl Channel { let (res, remote_commitment_tx, htlcs) = match self.send_commitment_no_state_update() { Ok((res, (remote_commitment_tx, mut htlcs))) => { // Update state now that we've passed all the can-fail calls... - let htlcs_no_ref = htlcs - .drain(..) - .map(|(htlc, htlc_source)| (htlc, htlc_source.map(|source_ref| Box::new(source_ref.clone())))) - .collect(); + let htlcs_no_ref = htlcs.drain(..) + .map(|(htlc, htlc_source)| (htlc, htlc_source.map(|source_ref| Box::new(source_ref.clone())))) + .collect(); (res, remote_commitment_tx, htlcs_no_ref) }, Err(e) => return Err(e), }; self.channel_monitor.provide_latest_remote_commitment_tx_info( - &remote_commitment_tx, - htlcs, - self.cur_remote_commitment_transaction_number, - self.their_cur_commitment_point.unwrap(), + &remote_commitment_tx, + htlcs, + self.cur_remote_commitment_transaction_number, + self.their_cur_commitment_point.unwrap(), ); self.channel_state |= ChannelState::AwaitingRemoteRevoke as u32; Ok((res, self.channel_monitor.clone())) @@ -4666,14 +4371,14 @@ impl Channel { /// Only fails in case of bad keys. Used for channel_reestablish commitment_signed generation /// when we shouldn't change HTLC/channel state. fn send_commitment_no_state_update( - &self, - ) -> Result< - ( + &self) + -> Result< + ( msgs::CommitmentSigned, (Transaction, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>), ), - ChannelError, - > { + ChannelError, + > { let mut feerate_per_kw = self.feerate_per_kw; if let Some(feerate) = self.pending_update_fee { if self.channel_outbound { @@ -4683,11 +4388,11 @@ impl Channel { let remote_keys = self.build_remote_transaction_keys()?; let remote_commitment_tx = self.build_commitment_transaction( - self.cur_remote_commitment_transaction_number, - &remote_keys, - false, - true, - feerate_per_kw, + self.cur_remote_commitment_transaction_number, + &remote_keys, + false, + true, + feerate_per_kw, ); let (signature, htlc_signatures); @@ -4697,28 +4402,27 @@ impl Channel { htlcs.push(htlc); } - let res = self - .local_keys - .sign_remote_commitment( - self.channel_value_satoshis, - &self.get_funding_redeemscript(), - feerate_per_kw, - &remote_commitment_tx.0, - &remote_keys, - &htlcs, - self.our_to_self_delay, - &self.secp_ctx, - ) - .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed"))?; + let res = self.local_keys + .sign_remote_commitment( + self.channel_value_satoshis, + &self.get_funding_redeemscript(), + feerate_per_kw, + &remote_commitment_tx.0, + &remote_keys, + &htlcs, + self.our_to_self_delay, + &self.secp_ctx, + ) + .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed"))?; signature = res.0; htlc_signatures = res.1; log_trace!( - self, - "Signed remote commitment tx {} with redeemscript {} -> {}", - encode::serialize_hex(&remote_commitment_tx.0), - encode::serialize_hex(&self.get_funding_redeemscript()), - log_bytes!(signature.serialize_compact()[..]) + self, + "Signed remote commitment tx {} with redeemscript {} -> {}", + encode::serialize_hex(&remote_commitment_tx.0), + encode::serialize_hex(&self.get_funding_redeemscript()), + log_bytes!(signature.serialize_compact()[..]) ); for (ref htlc_sig, ref htlc) in htlc_signatures.iter().zip(htlcs) { @@ -4740,14 +4444,10 @@ impl Channel { } } - Ok(( - msgs::CommitmentSigned { - channel_id: self.channel_id, - signature, - htlc_signatures, - }, - (remote_commitment_tx.0, remote_commitment_tx.2), - )) + Ok((msgs::CommitmentSigned { channel_id: self.channel_id, + signature, + htlc_signatures }, + (remote_commitment_tx.0, remote_commitment_tx.2))) } /// Adds a pending outbound HTLC to this channel, and creates a signed commitment transaction @@ -4760,8 +4460,8 @@ impl Channel { payment_hash: PaymentHash, cltv_expiry: u32, source: HTLCSource, - onion_routing_packet: msgs::OnionPacket, - ) -> Result, ChannelError> { + onion_routing_packet: msgs::OnionPacket) + -> Result, ChannelError> { match self.send_htlc(amount_msat, payment_hash, cltv_expiry, source, onion_routing_packet)? { Some(update_add_htlc) => { let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?; @@ -4783,15 +4483,11 @@ impl Channel { } if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK != 0 { if (self.channel_state & ChannelState::LocalShutdownSent as u32) == ChannelState::LocalShutdownSent as u32 { - return Err(APIError::APIMisuseError { - err: "Shutdown already in progress", - }); + return Err(APIError::APIMisuseError { err: "Shutdown already in progress" }); } else if (self.channel_state & ChannelState::RemoteShutdownSent as u32) - == ChannelState::RemoteShutdownSent as u32 + == ChannelState::RemoteShutdownSent as u32 { - return Err(APIError::ChannelUnavailable { - err: "Shutdown already in progress by remote", - }); + return Err(APIError::ChannelUnavailable { err: "Shutdown already in progress by remote" }); } } assert_eq!(self.channel_state & ChannelState::ShutdownComplete as u32, 0); @@ -4815,24 +4511,18 @@ impl Channel { self.holding_cell_update_fee = None; let mut dropped_outbound_htlcs = Vec::with_capacity(self.holding_cell_htlc_updates.len()); self.holding_cell_htlc_updates.retain(|htlc_update| match htlc_update { - &HTLCUpdateAwaitingACK::AddHTLC { - ref payment_hash, - ref source, - .. - } => { - dropped_outbound_htlcs.push((source.clone(), payment_hash.clone())); - false - }, - _ => true, - }); - - Ok(( - msgs::Shutdown { - channel_id: self.channel_id, - scriptpubkey: our_closing_script, - }, - dropped_outbound_htlcs, - )) + &HTLCUpdateAwaitingACK::AddHTLC { ref payment_hash, + ref source, + .. } => { + dropped_outbound_htlcs.push((source.clone(), payment_hash.clone())); + false + }, + _ => true, + }); + + Ok((msgs::Shutdown { channel_id: self.channel_id, + scriptpubkey: our_closing_script }, + dropped_outbound_htlcs)) } /// Gets the latest commitment transaction and any dependent transactions for relay (forcing @@ -4848,9 +4538,7 @@ impl Channel { let mut dropped_outbound_htlcs = Vec::with_capacity(self.holding_cell_htlc_updates.len()); for htlc_update in self.holding_cell_htlc_updates.drain(..) { match htlc_update { - HTLCUpdateAwaitingACK::AddHTLC { - source, payment_hash, .. - } => { + HTLCUpdateAwaitingACK::AddHTLC { source, payment_hash, .. } => { dropped_outbound_htlcs.push((source, payment_hash)); }, _ => {}, @@ -4865,10 +4553,7 @@ impl Channel { self.channel_state = ChannelState::ShutdownComplete as u32; self.channel_update_count += 1; - ( - self.channel_monitor.get_latest_local_commitment_txn(), - dropped_outbound_htlcs, - ) + (self.channel_monitor.get_latest_local_commitment_txn(), dropped_outbound_htlcs) } } @@ -5007,13 +4692,11 @@ impl Writeable for Channel { (self.holding_cell_htlc_updates.len() as u64).write(writer)?; for update in self.holding_cell_htlc_updates.iter() { match update { - &HTLCUpdateAwaitingACK::AddHTLC { - ref amount_msat, - ref cltv_expiry, - ref payment_hash, - ref source, - ref onion_routing_packet, - } => { + &HTLCUpdateAwaitingACK::AddHTLC { ref amount_msat, + ref cltv_expiry, + ref payment_hash, + ref source, + ref onion_routing_packet, } => { 0u8.write(writer)?; amount_msat.write(writer)?; cltv_expiry.write(writer)?; @@ -5021,18 +4704,14 @@ impl Writeable for Channel { source.write(writer)?; onion_routing_packet.write(writer)?; }, - &HTLCUpdateAwaitingACK::ClaimHTLC { - ref payment_preimage, - ref htlc_id, - } => { + &HTLCUpdateAwaitingACK::ClaimHTLC { ref payment_preimage, + ref htlc_id, } => { 1u8.write(writer)?; payment_preimage.write(writer)?; htlc_id.write(writer)?; }, - &HTLCUpdateAwaitingACK::FailHTLC { - ref htlc_id, - ref err_packet, - } => { + &HTLCUpdateAwaitingACK::FailHTLC { ref htlc_id, + ref err_packet, } => { 2u8.write(writer)?; htlc_id.write(writer)?; err_packet.write(writer)?; @@ -5178,29 +4857,25 @@ impl> ReadableArgs>::read(reader)? { - 0 => HTLCUpdateAwaitingACK::AddHTLC { - amount_msat: Readable::read(reader)?, - cltv_expiry: Readable::read(reader)?, - payment_hash: Readable::read(reader)?, - source: Readable::read(reader)?, - onion_routing_packet: Readable::read(reader)?, - }, - 1 => HTLCUpdateAwaitingACK::ClaimHTLC { - payment_preimage: Readable::read(reader)?, - htlc_id: Readable::read(reader)?, - }, - 2 => HTLCUpdateAwaitingACK::FailHTLC { - htlc_id: Readable::read(reader)?, - err_packet: Readable::read(reader)?, - }, - _ => return Err(DecodeError::InvalidValue), - }); + 0 => HTLCUpdateAwaitingACK::AddHTLC { amount_msat: Readable::read(reader)?, + cltv_expiry: Readable::read(reader)?, + payment_hash: Readable::read(reader)?, + source: Readable::read(reader)?, + onion_routing_packet: Readable::read( + reader, + )?, }, + 1 => HTLCUpdateAwaitingACK::ClaimHTLC { payment_preimage: Readable::read( + reader, + )?, + htlc_id: Readable::read(reader)?, }, + 2 => HTLCUpdateAwaitingACK::FailHTLC { htlc_id: Readable::read(reader)?, + err_packet: Readable::read(reader)?, }, + _ => return Err(DecodeError::InvalidValue), + }); } let resend_order = match >::read(reader)? { @@ -5214,25 +4889,17 @@ impl> ReadableArgs> ReadableArgs>::read(reader)? { 0 => None, - 1 => Some(( - Readable::read(reader)?, - Readable::read(reader)?, - Readable::read(reader)?, - )), + 1 => Some((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?)), _ => return Err(DecodeError::InvalidValue), }; @@ -5288,83 +4951,81 @@ impl> ReadableArgs PublicKey { @@ -5489,8 +5149,8 @@ mod tests { ], }; assert_eq!( - PublicKey::from_secret_key(&secp_ctx, chan_keys.funding_key()).serialize()[..], - hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..] + PublicKey::from_secret_key(&secp_ctx, chan_keys.funding_key()).serialize()[..], + hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..] ); let keys_provider: Arc> = Arc::new(Keys { chan_keys }); @@ -5498,16 +5158,15 @@ mod tests { let mut config = UserConfig::default(); config.channel_options.announced_channel = false; let mut chan = Channel::::new_outbound( - &feeest, - &keys_provider, - their_node_id, - 10000000, - 100000, - 42, - Arc::clone(&logger), - &config, - ) - .unwrap(); // Nothing uses their network key in this test + &feeest, + &keys_provider, + their_node_id, + 10000000, + 100000, + 42, + Arc::clone(&logger), + &config, + ).unwrap(); // Nothing uses their network key in this test chan.their_to_self_delay = 144; chan.our_dust_limit_satoshis = 546; @@ -5525,8 +5184,8 @@ mod tests { .unwrap(), )); assert_eq!( - chan.their_payment_basepoint.unwrap().serialize()[..], - hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..] + chan.their_payment_basepoint.unwrap().serialize()[..], + hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..] ); chan.their_funding_pubkey = Some(PublicKey::from_secret_key( @@ -5537,8 +5196,8 @@ mod tests { .unwrap(), )); assert_eq!( - chan.their_funding_pubkey.unwrap().serialize()[..], - hex::decode("030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1").unwrap()[..] + chan.their_funding_pubkey.unwrap().serialize()[..], + hex::decode("030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1").unwrap()[..] ); chan.their_htlc_basepoint = Some(PublicKey::from_secret_key( @@ -5549,8 +5208,8 @@ mod tests { .unwrap(), )); assert_eq!( - chan.their_htlc_basepoint.unwrap().serialize()[..], - hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..] + chan.their_htlc_basepoint.unwrap().serialize()[..], + hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..] ); chan.their_revocation_basepoint = Some( @@ -5571,15 +5230,14 @@ mod tests { let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret); let htlc_basepoint = PublicKey::from_secret_key(&secp_ctx, chan.local_keys.htlc_base_key()); let keys = TxCreationKeys::new( - &secp_ctx, - &per_commitment_point, - &delayed_payment_base, - &htlc_basepoint, - &chan.their_revocation_basepoint.unwrap(), - &chan.their_payment_basepoint.unwrap(), - &chan.their_htlc_basepoint.unwrap(), - ) - .unwrap(); + &secp_ctx, + &per_commitment_point, + &delayed_payment_base, + &htlc_basepoint, + &chan.their_revocation_basepoint.unwrap(), + &chan.their_payment_basepoint.unwrap(), + &chan.their_htlc_basepoint.unwrap(), + ).unwrap(); let mut unsigned_tx: (Transaction, Vec); @@ -5637,72 +5295,62 @@ mod tests { } chan.pending_inbound_htlcs.push({ - let mut out = InboundHTLCOutput { - htlc_id: 0, - amount_msat: 1000000, - cltv_expiry: 500, - payment_hash: PaymentHash([0; 32]), - state: InboundHTLCState::Committed, - }; - out.payment_hash.0 = + let mut out = InboundHTLCOutput { htlc_id: 0, + amount_msat: 1000000, + cltv_expiry: 500, + payment_hash: PaymentHash([0; 32]), + state: InboundHTLCState::Committed }; + out.payment_hash.0 = Sha256::hash(&hex::decode("0000000000000000000000000000000000000000000000000000000000000000").unwrap()) .into_inner(); - out - }); + out + }); chan.pending_inbound_htlcs.push({ - let mut out = InboundHTLCOutput { - htlc_id: 1, - amount_msat: 2000000, - cltv_expiry: 501, - payment_hash: PaymentHash([0; 32]), - state: InboundHTLCState::Committed, - }; - out.payment_hash.0 = + let mut out = InboundHTLCOutput { htlc_id: 1, + amount_msat: 2000000, + cltv_expiry: 501, + payment_hash: PaymentHash([0; 32]), + state: InboundHTLCState::Committed }; + out.payment_hash.0 = Sha256::hash(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()) .into_inner(); - out - }); + out + }); chan.pending_outbound_htlcs.push({ - let mut out = OutboundHTLCOutput { - htlc_id: 2, - amount_msat: 2000000, - cltv_expiry: 502, - payment_hash: PaymentHash([0; 32]), - state: OutboundHTLCState::Committed, - source: HTLCSource::dummy(), - }; - out.payment_hash.0 = + let mut out = OutboundHTLCOutput { htlc_id: 2, + amount_msat: 2000000, + cltv_expiry: 502, + payment_hash: PaymentHash([0; 32]), + state: OutboundHTLCState::Committed, + source: HTLCSource::dummy() }; + out.payment_hash.0 = Sha256::hash(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()) .into_inner(); - out - }); + out + }); chan.pending_outbound_htlcs.push({ - let mut out = OutboundHTLCOutput { - htlc_id: 3, - amount_msat: 3000000, - cltv_expiry: 503, - payment_hash: PaymentHash([0; 32]), - state: OutboundHTLCState::Committed, - source: HTLCSource::dummy(), - }; - out.payment_hash.0 = + let mut out = OutboundHTLCOutput { htlc_id: 3, + amount_msat: 3000000, + cltv_expiry: 503, + payment_hash: PaymentHash([0; 32]), + state: OutboundHTLCState::Committed, + source: HTLCSource::dummy() }; + out.payment_hash.0 = Sha256::hash(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()) .into_inner(); - out - }); + out + }); chan.pending_inbound_htlcs.push({ - let mut out = InboundHTLCOutput { - htlc_id: 4, - amount_msat: 4000000, - cltv_expiry: 504, - payment_hash: PaymentHash([0; 32]), - state: InboundHTLCState::Committed, - }; - out.payment_hash.0 = + let mut out = InboundHTLCOutput { htlc_id: 4, + amount_msat: 4000000, + cltv_expiry: 504, + payment_hash: PaymentHash([0; 32]), + state: InboundHTLCState::Committed }; + out.payment_hash.0 = Sha256::hash(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()) .into_inner(); - out - }); + out + }); { // commitment tx with all five HTLCs untrimmed (minimum feerate) @@ -5914,34 +5562,34 @@ mod tests { &hex::decode("0000000000000000000000000000000000000000000000000000000000000000").unwrap(), ); assert_eq!( - chan_utils::build_commitment_secret(&seed, 281474976710655), - hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap()[..] + chan_utils::build_commitment_secret(&seed, 281474976710655), + hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap()[..] ); seed[0..32].clone_from_slice( &hex::decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(), ); assert_eq!( - chan_utils::build_commitment_secret(&seed, 281474976710655), - hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()[..] + chan_utils::build_commitment_secret(&seed, 281474976710655), + hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()[..] ); assert_eq!( - chan_utils::build_commitment_secret(&seed, 0xaaaaaaaaaaa), - hex::decode("56f4008fb007ca9acf0e15b054d5c9fd12ee06cea347914ddbaed70d1c13a528").unwrap()[..] + chan_utils::build_commitment_secret(&seed, 0xaaaaaaaaaaa), + hex::decode("56f4008fb007ca9acf0e15b054d5c9fd12ee06cea347914ddbaed70d1c13a528").unwrap()[..] ); assert_eq!( - chan_utils::build_commitment_secret(&seed, 0x555555555555), - hex::decode("9015daaeb06dba4ccc05b91b2f73bd54405f2be9f217fbacd3c5ac2e62327d31").unwrap()[..] + chan_utils::build_commitment_secret(&seed, 0x555555555555), + hex::decode("9015daaeb06dba4ccc05b91b2f73bd54405f2be9f217fbacd3c5ac2e62327d31").unwrap()[..] ); seed[0..32].clone_from_slice( &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap(), ); assert_eq!( - chan_utils::build_commitment_secret(&seed, 1), - hex::decode("915c75942a26bb3a433a8ce2cb0427c29ec6c1775cfc78328b57f6ba7bfeaa9c").unwrap()[..] + chan_utils::build_commitment_secret(&seed, 1), + hex::decode("915c75942a26bb3a433a8ce2cb0427c29ec6c1775cfc78328b57f6ba7bfeaa9c").unwrap()[..] ); } @@ -5961,21 +5609,20 @@ mod tests { let base_point = PublicKey::from_secret_key(&secp_ctx, &base_secret); assert_eq!( - base_point.serialize()[..], - hex::decode("036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2").unwrap()[..] + base_point.serialize()[..], + hex::decode("036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2").unwrap()[..] ); let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret); assert_eq!( - per_commitment_point.serialize()[..], - hex::decode("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486").unwrap()[..] + per_commitment_point.serialize()[..], + hex::decode("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486").unwrap()[..] ); assert_eq!( - chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &base_point) - .unwrap() - .serialize()[..], - hex::decode("0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5").unwrap()[..] + chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &base_point).unwrap() + .serialize()[..], + hex::decode("0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5").unwrap()[..] ); assert_eq!( @@ -5987,10 +5634,9 @@ mod tests { ); assert_eq!( - chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &base_point) - .unwrap() - .serialize()[..], - hex::decode("02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0").unwrap()[..] + chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &base_point).unwrap() + .serialize()[..], + hex::decode("02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0").unwrap()[..] ); assert_eq!( diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 5dba91230e4..604871bdddd 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -113,11 +113,9 @@ pub(super) enum HTLCSource { #[cfg(test)] impl HTLCSource { pub fn dummy() -> Self { - HTLCSource::OutboundRoute { - route: Route { hops: Vec::new() }, - session_priv: SecretKey::from_slice(&[1; 32]).unwrap(), - first_hop_htlc_msat: 0, - } + HTLCSource::OutboundRoute { route: Route { hops: Vec::new() }, + session_priv: SecretKey::from_slice(&[1; 32]).unwrap(), + first_hop_htlc_msat: 0 } } } @@ -164,28 +162,21 @@ impl MsgHandleErrInternal { } #[inline] fn ignore_no_close(err: &'static str) -> Self { - Self { - err: LightningError { - err, - action: msgs::ErrorAction::IgnoreError, - }, - shutdown_finish: None, - } + Self { err: LightningError { err, + action: msgs::ErrorAction::IgnoreError }, + shutdown_finish: None } } #[inline] fn from_no_close(err: msgs::LightningError) -> Self { - Self { - err, - shutdown_finish: None, - } + Self { err, + shutdown_finish: None } } #[inline] - fn from_finish_shutdown( - err: &'static str, - channel_id: [u8; 32], - shutdown_res: ShutdownResult, - channel_update: Option, - ) -> Self { + fn from_finish_shutdown(err: &'static str, + channel_id: [u8; 32], + shutdown_res: ShutdownResult, + channel_update: Option) + -> Self { Self { err: LightningError { err, @@ -289,13 +280,11 @@ pub(super) struct MutChannelHolder<'a, ChanSigner: ChannelKeys + 'a> { } impl ChannelHolder { pub(super) fn borrow_parts(&mut self) -> MutChannelHolder { - MutChannelHolder { - by_id: &mut self.by_id, - short_to_id: &mut self.short_to_id, - forward_htlcs: &mut self.forward_htlcs, - claimable_htlcs: &mut self.claimable_htlcs, - pending_msg_events: &mut self.pending_msg_events, - } + MutChannelHolder { by_id: &mut self.by_id, + short_to_id: &mut self.short_to_id, + forward_htlcs: &mut self.forward_htlcs, + claimable_htlcs: &mut self.claimable_htlcs, + pending_msg_events: &mut self.pending_msg_events } } } @@ -386,10 +375,10 @@ pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO? #[deny(const_err)] #[allow(dead_code)] const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - - LATENCY_GRACE_PERIOD_BLOCKS - - CLTV_CLAIM_BUFFER - - ANTI_REORG_DELAY - - LATENCY_GRACE_PERIOD_BLOCKS; + - LATENCY_GRACE_PERIOD_BLOCKS + - CLTV_CLAIM_BUFFER + - ANTI_REORG_DELAY + - LATENCY_GRACE_PERIOD_BLOCKS; // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See // ChannelMontior::would_broadcast_at_height for a description of why this is needed. @@ -620,40 +609,36 @@ impl ChannelManager { /// the ChannelManager as a listener to the BlockNotifier and call the BlockNotifier's /// `block_(dis)connected` methods, which will notify all registered listeners in one /// go. - pub fn new( - network: Network, - feeest: Arc, - monitor: Arc, - tx_broadcaster: Arc, - logger: Arc, - keys_manager: Arc>, - config: UserConfig, - current_blockchain_height: usize, - ) -> Result>, secp256k1::Error> { + pub fn new(network: Network, + feeest: Arc, + monitor: Arc, + tx_broadcaster: Arc, + logger: Arc, + keys_manager: Arc>, + config: UserConfig, + current_blockchain_height: usize) + -> Result>, secp256k1::Error> { let secp_ctx = Secp256k1::new(); - let res = Arc::new(ChannelManager { - default_configuration: config.clone(), - genesis_hash: genesis_block(network).header.bitcoin_hash(), - fee_estimator: feeest.clone(), - monitor: monitor.clone(), - tx_broadcaster, - latest_block_height: AtomicUsize::new(current_blockchain_height), - last_block_hash: Mutex::new(Default::default()), - secp_ctx, - channel_state: Mutex::new(ChannelHolder { - by_id: HashMap::new(), - short_to_id: HashMap::new(), - forward_htlcs: HashMap::new(), - claimable_htlcs: HashMap::new(), - pending_msg_events: Vec::new(), - }), - our_network_key: keys_manager.get_node_secret(), - pending_events: Mutex::new(Vec::new()), - total_consistency_lock: RwLock::new(()), - keys_manager, - logger, - }); + let res = + Arc::new(ChannelManager { default_configuration: config.clone(), + genesis_hash: genesis_block(network).header.bitcoin_hash(), + fee_estimator: feeest.clone(), + monitor: monitor.clone(), + tx_broadcaster, + latest_block_height: AtomicUsize::new(current_blockchain_height), + last_block_hash: Mutex::new(Default::default()), + secp_ctx, + channel_state: Mutex::new(ChannelHolder { by_id: HashMap::new(), + short_to_id: HashMap::new(), + forward_htlcs: HashMap::new(), + claimable_htlcs: HashMap::new(), + pending_msg_events: Vec::new() }), + our_network_key: keys_manager.get_node_secret(), + pending_events: Mutex::new(Vec::new()), + total_consistency_lock: RwLock::new(()), + keys_manager, + logger }); Ok(res) } @@ -670,28 +655,25 @@ impl ChannelManager { /// /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000. - pub fn create_channel( - &self, - their_network_key: PublicKey, - channel_value_satoshis: u64, - push_msat: u64, - user_id: u64, - ) -> Result<(), APIError> { + pub fn create_channel(&self, + their_network_key: PublicKey, + channel_value_satoshis: u64, + push_msat: u64, + user_id: u64) + -> Result<(), APIError> { if channel_value_satoshis < 1000 { - return Err(APIError::APIMisuseError { - err: "channel_value must be at least 1000 satoshis", - }); + return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" }); } let channel = Channel::new_outbound( - &*self.fee_estimator, - &self.keys_manager, - their_network_key, - channel_value_satoshis, - push_msat, - user_id, - Arc::clone(&self.logger), - &self.default_configuration, + &*self.fee_estimator, + &self.keys_manager, + their_network_key, + channel_value_satoshis, + push_msat, + user_id, + Arc::clone(&self.logger), + &self.default_configuration, )?; let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator); @@ -709,12 +691,9 @@ impl ChannelManager { entry.insert(channel); }, } - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendOpenChannel { - node_id: their_network_key, - msg: res, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendOpenChannel { node_id: their_network_key, + msg: res }); Ok(()) } @@ -725,16 +704,14 @@ impl ChannelManager { let mut res = Vec::with_capacity(channel_state.by_id.len()); for (channel_id, channel) in channel_state.by_id.iter() { let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat(); - res.push(ChannelDetails { - channel_id: (*channel_id).clone(), - short_channel_id: channel.get_short_channel_id(), - remote_network_id: channel.get_their_node_id(), - channel_value_satoshis: channel.get_value_satoshis(), - inbound_capacity_msat, - outbound_capacity_msat, - user_id: channel.get_user_id(), - is_live: channel.is_live(), - }); + res.push(ChannelDetails { channel_id: (*channel_id).clone(), + short_channel_id: channel.get_short_channel_id(), + remote_network_id: channel.get_their_node_id(), + channel_value_satoshis: channel.get_value_satoshis(), + inbound_capacity_msat, + outbound_capacity_msat, + user_id: channel.get_user_id(), + is_live: channel.is_live() }); } res } @@ -754,16 +731,14 @@ impl ChannelManager { if channel.is_live() { let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat(); - res.push(ChannelDetails { - channel_id: (*channel_id).clone(), - short_channel_id: channel.get_short_channel_id(), - remote_network_id: channel.get_their_node_id(), - channel_value_satoshis: channel.get_value_satoshis(), - inbound_capacity_msat, - outbound_capacity_msat, - user_id: channel.get_user_id(), - is_live: true, - }); + res.push(ChannelDetails { channel_id: (*channel_id).clone(), + short_channel_id: channel.get_short_channel_id(), + remote_network_id: channel.get_their_node_id(), + channel_value_satoshis: channel.get_value_satoshis(), + inbound_capacity_msat, + outbound_capacity_msat, + user_id: channel.get_user_id(), + is_live: true }); } } res @@ -783,12 +758,10 @@ impl ChannelManager { match channel_state.by_id.entry(channel_id.clone()) { hash_map::Entry::Occupied(mut chan_entry) => { let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?; - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendShutdown { - node_id: chan_entry.get().get_their_node_id(), - msg: shutdown_msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendShutdown { node_id: chan_entry.get() + .get_their_node_id(), + msg: shutdown_msg }); if chan_entry.get().is_shutdown() { if let Some(short_id) = chan_entry.get().get_short_channel_id() { channel_state.short_to_id.remove(&short_id); @@ -803,13 +776,11 @@ impl ChannelManager { }; for htlc_source in failed_htlcs.drain(..) { self.fail_htlc_backwards_internal( - self.channel_state.lock().unwrap(), - htlc_source.0, - &htlc_source.1, - HTLCFailReason::Reason { - failure_code: 0x4000 | 8, - data: Vec::new(), - }, + self.channel_state.lock().unwrap(), + htlc_source.0, + &htlc_source.1, + HTLCFailReason::Reason { failure_code: 0x4000 | 8, + data: Vec::new(), }, ); } let chan_update = if let Some(chan) = chan_option { @@ -824,9 +795,8 @@ impl ChannelManager { if let Some(update) = chan_update { let mut channel_state = self.channel_state.lock().unwrap(); - channel_state - .pending_msg_events - .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); } Ok(()) @@ -836,20 +806,18 @@ impl ChannelManager { fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) { let (local_txn, mut failed_htlcs) = shutdown_res; log_trace!( - self, - "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", - local_txn.len(), - failed_htlcs.len() + self, + "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", + local_txn.len(), + failed_htlcs.len() ); for htlc_source in failed_htlcs.drain(..) { self.fail_htlc_backwards_internal( - self.channel_state.lock().unwrap(), - htlc_source.0, - &htlc_source.1, - HTLCFailReason::Reason { - failure_code: 0x4000 | 8, - data: Vec::new(), - }, + self.channel_state.lock().unwrap(), + htlc_source.0, + &htlc_source.1, + HTLCFailReason::Reason { failure_code: 0x4000 | 8, + data: Vec::new(), }, ); } for tx in local_txn { @@ -879,9 +847,8 @@ impl ChannelManager { self.finish_force_close_channel(chan.force_shutdown()); if let Ok(update) = self.get_channel_update(&chan) { let mut channel_state = self.channel_state.lock().unwrap(); - channel_state - .pending_msg_events - .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); } } @@ -893,10 +860,9 @@ impl ChannelManager { } } - 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) => {{ log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg); @@ -911,7 +877,10 @@ impl ChannelManager { let shared_secret = { let mut arr = [0; 32]; arr.copy_from_slice( - &SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..], + &SharedSecret::new( + &msg.onion_routing_packet.public_key.unwrap(), + &self.our_network_key, + )[..], ); arr }; @@ -973,8 +942,8 @@ impl ChannelManager { // algorithms, but this fixes the most-obvious case. let mut new_packet_data = [0; 19 * 65]; chacha.process( - &msg.onion_routing_packet.hop_data[65..], - &mut new_packet_data[0..19 * 65], + &msg.onion_routing_packet.hop_data[65..], + &mut new_packet_data[0..19 * 65], ); assert_ne!(new_packet_data[0..65], [0; 65][..]); assert_ne!(new_packet_data[..], [0; 19 * 65][..]); @@ -983,25 +952,25 @@ impl ChannelManager { // OUR PAYMENT! // final_expiry_too_soon if (msg.cltv_expiry as u64) - < self.latest_block_height.load(Ordering::Acquire) as u64 - + (CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS) as u64 + < self.latest_block_height.load(Ordering::Acquire) as u64 + + (CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS) as u64 { return_err!("The final CLTV expiry is too soon to handle", 17, &[0; 0]); } // final_incorrect_htlc_amount if next_hop_data.data.amt_to_forward > msg.amount_msat { return_err!( - "Upstream node sent less than we were supposed to receive in payment", - 19, - &byte_utils::be64_to_array(msg.amount_msat) + "Upstream node sent less than we were supposed to receive in payment", + 19, + &byte_utils::be64_to_array(msg.amount_msat) ); } // final_incorrect_cltv_expiry if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry { return_err!( - "Upstream node set CLTV to the wrong value", - 18, - &byte_utils::be32_to_array(msg.cltv_expiry) + "Upstream node set CLTV to the wrong value", + 18, + &byte_utils::be32_to_array(msg.cltv_expiry) ); } @@ -1010,19 +979,18 @@ impl ChannelManager { // instead we stay symmetric with the forwarding case, only responding (after a // delay) once they've send us a commitment_signed! - PendingHTLCStatus::Forward(PendingForwardHTLCInfo { - onion_packet: None, - payment_hash: msg.payment_hash.clone(), - short_channel_id: 0, - incoming_shared_secret: shared_secret, - amt_to_forward: next_hop_data.data.amt_to_forward, - outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value, - }) + PendingHTLCStatus::Forward(PendingForwardHTLCInfo { onion_packet: None, + payment_hash: msg.payment_hash.clone(), + short_channel_id: 0, + incoming_shared_secret: shared_secret, + amt_to_forward: next_hop_data.data.amt_to_forward, + outgoing_cltv_value: next_hop_data.data + .outgoing_cltv_value }) } else { let mut new_packet_data = [0; 20 * 65]; chacha.process( - &msg.onion_routing_packet.hop_data[65..], - &mut new_packet_data[0..19 * 65], + &msg.onion_routing_packet.hop_data[65..], + &mut new_packet_data[0..19 * 65], ); chacha.process(&SIXTY_FIVE_ZEROS[..], &mut new_packet_data[19 * 65..]); @@ -1041,47 +1009,42 @@ impl ChannelManager { Ok(new_pubkey) }; - let outgoing_packet = msgs::OnionPacket { - version: 0, - public_key, - hop_data: new_packet_data, - hmac: next_hop_data.hmac.clone(), - }; - - PendingHTLCStatus::Forward(PendingForwardHTLCInfo { - onion_packet: Some(outgoing_packet), - payment_hash: msg.payment_hash.clone(), - short_channel_id: next_hop_data.data.short_channel_id, - incoming_shared_secret: shared_secret, - amt_to_forward: next_hop_data.data.amt_to_forward, - outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value, - }) + let outgoing_packet = msgs::OnionPacket { version: 0, + public_key, + hop_data: new_packet_data, + hmac: next_hop_data.hmac.clone() }; + + PendingHTLCStatus::Forward(PendingForwardHTLCInfo { onion_packet: Some(outgoing_packet), + payment_hash: msg.payment_hash.clone(), + short_channel_id: next_hop_data.data + .short_channel_id, + incoming_shared_secret: shared_secret, + amt_to_forward: next_hop_data.data.amt_to_forward, + outgoing_cltv_value: next_hop_data.data + .outgoing_cltv_value }) }; channel_state = Some(self.channel_state.lock().unwrap()); - if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { - ref onion_packet, - ref short_channel_id, - ref amt_to_forward, - ref outgoing_cltv_value, - .. - }) = &pending_forward_info + if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, + ref short_channel_id, + ref amt_to_forward, + ref outgoing_cltv_value, + .. }) = &pending_forward_info { if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here - let id_option = channel_state - .as_ref() - .unwrap() - .short_to_id - .get(&short_channel_id) - .cloned(); + let id_option = channel_state.as_ref() + .unwrap() + .short_to_id + .get(&short_channel_id) + .cloned(); let forwarding_id = match id_option { None => { // unknown_next_peer return_err!( - "Don't have available channel for forwarding as requested.", - 0x4000 | 10, - &[0; 0] + "Don't have available channel for forwarding as requested.", + 0x4000 | 10, + &[0; 0] ); }, Some(id) => id.clone(), @@ -1110,14 +1073,13 @@ impl ChannelManager { Some(self.get_channel_update(chan).unwrap()), )); } - let fee = amt_to_forward - .checked_mul(chan.get_fee_proportional_millionths() as u64) - .and_then(|prop_fee| { - (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) - }); + let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64) + .and_then(|prop_fee| { + (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) + }); if fee.is_none() - || msg.amount_msat < fee.unwrap() - || (msg.amount_msat - fee.unwrap()) < *amt_to_forward + || msg.amount_msat < fee.unwrap() + || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient break Some(( @@ -1170,38 +1132,32 @@ impl ChannelManager { 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", - action: msgs::ErrorAction::IgnoreError, - }) + return Err(LightningError { err: "Channel not yet established", + action: msgs::ErrorAction::IgnoreError }) }, Some(id) => id, }; let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] - < chan.get_their_node_id().serialize()[..]; - - let unsigned = msgs::UnsignedChannelUpdate { - chain_hash: self.genesis_hash, - short_channel_id, - timestamp: chan.get_channel_update_count(), - flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1), - cltv_expiry_delta: CLTV_EXPIRY_DELTA, - htlc_minimum_msat: chan.get_our_htlc_minimum_msat(), - fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator), - fee_proportional_millionths: chan.get_fee_proportional_millionths(), - excess_data: Vec::new(), - }; + < chan.get_their_node_id().serialize()[..]; + + let unsigned = + msgs::UnsignedChannelUpdate { chain_hash: self.genesis_hash, + short_channel_id, + timestamp: chan.get_channel_update_count(), + flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1), + cltv_expiry_delta: CLTV_EXPIRY_DELTA, + htlc_minimum_msat: chan.get_our_htlc_minimum_msat(), + fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator), + fee_proportional_millionths: chan.get_fee_proportional_millionths(), + excess_data: Vec::new() }; let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]); - let sig = self - .secp_ctx - .sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key); - - Ok(msgs::ChannelUpdate { - signature: sig, - contents: unsigned, - }) + let sig = self.secp_ctx + .sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key); + + Ok(msgs::ChannelUpdate { signature: sig, + contents: unsigned }) } /// Sends a payment along a given route. @@ -1232,16 +1188,13 @@ impl ChannelManager { /// the payment via a different route unless you intend to pay twice! pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> { if route.hops.len() < 1 || route.hops.len() > 20 { - return Err(APIError::RouteError { - err: "Route didn't go anywhere/had bogus size", - }); + return Err(APIError::RouteError { err: "Route didn't go anywhere/had bogus size" }); } let our_node_id = self.get_our_node_id(); for (idx, hop) in route.hops.iter().enumerate() { if idx != route.hops.len() - 1 && hop.pubkey == our_node_id { - return Err(APIError::RouteError { - err: "Route went through us but wasn't a simple rebalance loop to us", - }); + return Err(APIError::RouteError { err: + "Route went through us but wasn't a simple rebalance loop to us" }); } } @@ -1250,10 +1203,8 @@ impl ChannelManager { let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1; let onion_keys = secp_call!( - onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv), - APIError::RouteError { - err: "Pubkey along hop was maliciously selected" - } + onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv), + APIError::RouteError { err: "Pubkey along hop was maliciously selected" } ); let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height)?; let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, &payment_hash); @@ -1262,32 +1213,25 @@ impl ChannelManager { let mut channel_lock = self.channel_state.lock().unwrap(); let err: Result<(), _> = loop { - let id = match channel_lock - .short_to_id - .get(&route.hops.first().unwrap().short_channel_id) + let id = match channel_lock.short_to_id + .get(&route.hops.first().unwrap().short_channel_id) { - None => { - return Err(APIError::ChannelUnavailable { - err: "No channel available with first hop!", - }) - }, + None => return Err(APIError::ChannelUnavailable { err: "No channel available with first hop!" }), Some(id) => id.clone(), }; let channel_state = channel_lock.borrow_parts(); if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) { match { - if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey { - return Err(APIError::RouteError { - err: "Node ID mismatch on first hop!", - }); - } - if !chan.get().is_live() { - return Err(APIError::ChannelUnavailable { + if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey { + return Err(APIError::RouteError { err: "Node ID mismatch on first hop!" }); + } + if !chan.get().is_live() { + return Err(APIError::ChannelUnavailable { err: "Peer for first hop currently disconnected/pending monitor update!", }); - } - break_chan_entry!( + } + break_chan_entry!( self, chan.get_mut().send_htlc_and_commit( htlc_msat, @@ -1303,20 +1247,19 @@ impl ChannelManager { channel_state, chan ) - } { + } { Some((update_add, commitment_signed, chan_monitor)) => { - if let Err(e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + if let Err(e) = self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { maybe_break_monitor_err!( - self, - e, - channel_state, - chan, - RAACommitmentOrder::CommitmentFirst, - false, - true + self, + e, + channel_state, + chan, + RAACommitmentOrder::CommitmentFirst, + false, + true ); // Note that MonitorUpdateFailed here indicates (per function docs) // that we will resent the commitment update once we unfree monitor @@ -1368,21 +1311,20 @@ impl ChannelManager { let (mut chan, msg, chan_monitor) = { let mut channel_state = self.channel_state.lock().unwrap(); let (res, chan) = match channel_state.by_id.remove(temporary_channel_id) { - Some(mut chan) => ( - chan.get_outbound_funding_created(funding_txo).map_err(|e| { - if let ChannelError::Close(msg) = e { - MsgHandleErrInternal::from_finish_shutdown( + Some(mut chan) => (chan.get_outbound_funding_created(funding_txo).map_err(|e| { + if let ChannelError::Close(msg) = e + { + MsgHandleErrInternal::from_finish_shutdown( msg, chan.channel_id(), chan.force_shutdown(), None, ) - } else { - unreachable!(); - } - }), - chan, - ), + } else { + unreachable!(); + } + }), + chan), None => return, }; match handle_error!(self, res, chan.get_their_node_id(), channel_state) { @@ -1394,9 +1336,8 @@ impl ChannelManager { }; // Because we have exclusive ownership of the channel here we can release the channel_state // lock before add_update_monitor - if let Err(e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + if let Err(e) = self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { match e { ChannelMonitorUpdateErr::PermanentFailure => { @@ -1429,12 +1370,9 @@ impl ChannelManager { } let mut channel_state = self.channel_state.lock().unwrap(); - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendFundingCreated { - node_id: chan.get_their_node_id(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendFundingCreated { node_id: chan.get_their_node_id(), + msg }); match channel_state.by_id.entry(chan.channel_id()) { hash_map::Entry::Occupied(_) => { panic!("Generated duplicate funding txid?"); @@ -1458,12 +1396,10 @@ impl ChannelManager { let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]); let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key); - Some(msgs::AnnouncementSignatures { - channel_id: chan.channel_id(), - short_channel_id: chan.get_short_channel_id().unwrap(), - node_signature: our_node_sig, - bitcoin_signature: our_bitcoin_sig, - }) + Some(msgs::AnnouncementSignatures { channel_id: chan.channel_id(), + short_channel_id: chan.get_short_channel_id().unwrap(), + node_signature: our_node_sig, + bitcoin_signature: our_bitcoin_sig }) } /// Processes HTLCs which are pending waiting on random forward delay. @@ -1488,11 +1424,9 @@ impl ChannelManager { failed_forwards.reserve(pending_forwards.len()); for forward_info in pending_forwards.drain(..) { match forward_info { - HTLCForwardInfo::AddHTLC { - prev_short_channel_id, - prev_htlc_id, - forward_info, - } => { + HTLCForwardInfo::AddHTLC { prev_short_channel_id, + prev_htlc_id, + forward_info, } => { let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id: prev_short_channel_id, htlc_id: prev_htlc_id, @@ -1521,11 +1455,9 @@ impl ChannelManager { let mut fail_htlc_msgs = Vec::new(); for forward_info in pending_forwards.drain(..) { match forward_info { - HTLCForwardInfo::AddHTLC { - prev_short_channel_id, - prev_htlc_id, - forward_info, - } => { + HTLCForwardInfo::AddHTLC { prev_short_channel_id, + prev_htlc_id, + forward_info, } => { log_trace!(self, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", log_bytes!(forward_info.payment_hash.0), prev_short_channel_id, short_chan_id); let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id: prev_short_channel_id, @@ -1533,19 +1465,19 @@ impl ChannelManager { incoming_packet_shared_secret: forward_info.incoming_shared_secret, }); match chan.get_mut().send_htlc( - forward_info.amt_to_forward, - forward_info.payment_hash, - forward_info.outgoing_cltv_value, - htlc_source.clone(), - forward_info.onion_packet.unwrap(), + forward_info.amt_to_forward, + forward_info.payment_hash, + forward_info.outgoing_cltv_value, + htlc_source.clone(), + forward_info.onion_packet.unwrap(), ) { Err(e) => { if let ChannelError::Ignore(msg) = e { log_trace!( - self, - "Failed to forward HTLC with payment_hash {}: {}", - log_bytes!(forward_info.payment_hash.0), - msg + self, + "Failed to forward HTLC with payment_hash {}: {}", + log_bytes!(forward_info.payment_hash.0), + msg ); } else { panic!("Stated return value requirements in send_htlc() were not met"); @@ -1579,18 +1511,18 @@ impl ChannelManager { }, HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => { log_trace!( - self, - "Failing HTLC back to channel with short id {} after delay", - short_chan_id + self, + "Failing HTLC back to channel with short id {} after delay", + short_chan_id ); match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) { Err(e) => { if let ChannelError::Ignore(msg) = e { log_trace!( - self, - "Failed to fail backwards to short_id {}: {}", - short_chan_id, - msg + self, + "Failed to fail backwards to short_id {}: {}", + short_chan_id, + msg ); } else { panic!("Stated return value requirements in get_update_fail_htlc() were not met"); @@ -1633,10 +1565,10 @@ impl ChannelManager { }, ChannelError::Close(msg) => { log_trace!( - self, - "Closing channel {} due to Close-required error: {}", - log_bytes!(chan.key()[..]), - msg + self, + "Closing channel {} due to Close-required error: {}", + log_bytes!(chan.key()[..]), + msg ); let (channel_id, mut channel) = chan.remove_entry(); if let Some(short_id) = channel.get_short_channel_id() { @@ -1661,9 +1593,8 @@ impl ChannelManager { } }, }; - if let Err(e) = self - .monitor - .add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) + if let Err(e) = self.monitor + .add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) { handle_errors.push(( chan.get().get_their_node_id(), @@ -1699,16 +1630,13 @@ impl ChannelManager { } else { for forward_info in pending_forwards.drain(..) { match forward_info { - HTLCForwardInfo::AddHTLC { - prev_short_channel_id, - prev_htlc_id, - forward_info, - } => { - let prev_hop_data = HTLCPreviousHopData { - short_channel_id: prev_short_channel_id, - htlc_id: prev_htlc_id, - incoming_packet_shared_secret: forward_info.incoming_shared_secret, - }; + HTLCForwardInfo::AddHTLC { prev_short_channel_id, + prev_htlc_id, + forward_info, } => { + let prev_hop_data = HTLCPreviousHopData { short_channel_id: prev_short_channel_id, + htlc_id: prev_htlc_id, + incoming_packet_shared_secret: + forward_info.incoming_shared_secret }; match channel_state.claimable_htlcs.entry(forward_info.payment_hash) { hash_map::Entry::Occupied(mut entry) => { entry.get_mut().push((forward_info.amt_to_forward, prev_hop_data)) @@ -1717,10 +1645,9 @@ impl ChannelManager { entry.insert(vec![(forward_info.amt_to_forward, prev_hop_data)]); }, }; - new_events.push(events::Event::PaymentReceived { - payment_hash: forward_info.payment_hash, - amt: forward_info.amt_to_forward, - }); + new_events.push(events::Event::PaymentReceived { payment_hash: + forward_info.payment_hash, + amt: forward_info.amt_to_forward }); }, HTLCForwardInfo::FailHTLC { .. } => { panic!("Got pending fail of our own HTLC"); @@ -1734,23 +1661,21 @@ impl ChannelManager { for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) { match update { None => self.fail_htlc_backwards_internal( - self.channel_state.lock().unwrap(), - htlc_source, - &payment_hash, - HTLCFailReason::Reason { - failure_code, - data: Vec::new(), - }, - ), - Some(chan_update) => self.fail_htlc_backwards_internal( - self.channel_state.lock().unwrap(), - htlc_source, - &payment_hash, - HTLCFailReason::Reason { - failure_code, - data: chan_update.encode_with_len(), - }, + self.channel_state.lock().unwrap(), + htlc_source, + &payment_hash, + HTLCFailReason::Reason { failure_code, + data: Vec::new(), }, ), + Some(chan_update) => { + self.fail_htlc_backwards_internal( + self.channel_state.lock().unwrap(), + htlc_source, + &payment_hash, + HTLCFailReason::Reason { failure_code, + data: chan_update.encode_with_len(), }, + ) + }, }; } @@ -1780,9 +1705,8 @@ impl ChannelManager { for (_, chan) in channel_state.by_id { if chan.is_disabled_staged() && !chan.is_live() { if let Ok(update) = self.get_channel_update(&chan) { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); } chan.to_fresh(); } else if chan.is_disabled_staged() && chan.is_live() { @@ -1830,13 +1754,11 @@ impl ChannelManager { /// 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 @@ -1844,9 +1766,9 @@ impl ChannelManager { match source { HTLCSource::OutboundRoute { ref route, .. } => { log_trace!( - self, - "Failing outbound payment HTLC with payment_hash {}", - log_bytes!(payment_hash.0) + self, + "Failing outbound payment HTLC with payment_hash {}", + log_bytes!(payment_hash.0) ); mem::drop(channel_state_lock); match &onion_error { @@ -1862,23 +1784,22 @@ impl ChannelManager { // next-hop is needlessly blaming us! if let Some(update) = channel_update { self.channel_state - .lock() - .unwrap() - .pending_msg_events - .push(events::MessageSendEvent::PaymentFailureNetworkUpdate { update }); + .lock() + .unwrap() + .pending_msg_events + .push(events::MessageSendEvent::PaymentFailureNetworkUpdate { update }); } - self.pending_events.lock().unwrap().push(events::Event::PaymentFailed { - payment_hash: payment_hash.clone(), - rejected_by_dest: !payment_retryable, - #[cfg(test)] - error_code: onion_error_code, - }); + self.pending_events + .lock() + .unwrap() + .push(events::Event::PaymentFailed { payment_hash: payment_hash.clone(), + rejected_by_dest: !payment_retryable, + #[cfg(test)] + error_code: onion_error_code }); }, - &HTLCFailReason::Reason { - #[cfg(test)] - ref failure_code, - .. - } => { + &HTLCFailReason::Reason { #[cfg(test)] + ref failure_code, + .. } => { // we get a fail_malformed_htlc from the first hop // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary // failures here, but that would be insufficient as Router::get_route @@ -1886,38 +1807,39 @@ impl ChannelManager { // ChannelDetails. // TODO: For non-temporary failures, we really should be closing the // channel here as we apparently can't relay through them anyway. - self.pending_events.lock().unwrap().push(events::Event::PaymentFailed { - payment_hash: payment_hash.clone(), - rejected_by_dest: route.hops.len() == 1, - #[cfg(test)] - error_code: Some(*failure_code), - }); + self.pending_events + .lock() + .unwrap() + .push(events::Event::PaymentFailed { payment_hash: payment_hash.clone(), + rejected_by_dest: route.hops.len() == 1, + #[cfg(test)] + error_code: Some(*failure_code) }); }, } }, - HTLCSource::PreviousHopData(HTLCPreviousHopData { - short_channel_id, - htlc_id, - incoming_packet_shared_secret, - }) => { + HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, + htlc_id, + incoming_packet_shared_secret, }) => { let err_packet = match onion_error { HTLCFailReason::Reason { failure_code, data } => { log_trace!( - self, - "Failing HTLC with payment_hash {} backwards from us with code {}", - log_bytes!(payment_hash.0), - failure_code + self, + "Failing HTLC with payment_hash {} backwards from us with code {}", + log_bytes!(payment_hash.0), + failure_code ); - let packet = - onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]) - .encode(); + let packet = onion_utils::build_failure_packet( + &incoming_packet_shared_secret, + failure_code, + &data[..], + ).encode(); onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet) }, HTLCFailReason::LightningError { err } => { log_trace!( - self, - "Failing HTLC with payment_hash {} backwards with pre-built LightningError", - log_bytes!(payment_hash.0) + self, + "Failing HTLC with payment_hash {} backwards with pre-built LightningError", + log_bytes!(payment_hash.0) ); onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data) }, @@ -1974,19 +1896,17 @@ impl ChannelManager { byte_utils::be32_to_array(self.latest_block_height.load(Ordering::Acquire) as u32).to_vec(); htlc_msat_data.append(&mut height_data); self.fail_htlc_backwards_internal( - channel_state.take().unwrap(), - HTLCSource::PreviousHopData(htlc_with_hash), - &payment_hash, - HTLCFailReason::Reason { - failure_code: 0x4000 | 15, - data: htlc_msat_data, - }, + channel_state.take().unwrap(), + HTLCSource::PreviousHopData(htlc_with_hash), + &payment_hash, + HTLCFailReason::Reason { failure_code: 0x4000 | 15, + data: htlc_msat_data, }, ); } else { self.claim_funds_internal( - channel_state.take().unwrap(), - HTLCSource::PreviousHopData(htlc_with_hash), - payment_preimage, + channel_state.take().unwrap(), + HTLCSource::PreviousHopData(htlc_with_hash), + payment_preimage, ); } } @@ -1995,12 +1915,10 @@ impl ChannelManager { false } } - 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) { let (their_node_id, err) = loop { match source { HTLCSource::OutboundRoute { .. } => { @@ -2008,11 +1926,9 @@ impl ChannelManager { let mut pending_events = self.pending_events.lock().unwrap(); pending_events.push(events::Event::PaymentSent { payment_preimage }); }, - HTLCSource::PreviousHopData(HTLCPreviousHopData { - short_channel_id, - htlc_id, - .. - }) => { + HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, + htlc_id, + .. }) => { //TODO: Delay the claimed_funds relaying just like we do outbound relay! let channel_state = channel_state_lock.borrow_parts(); @@ -2028,31 +1944,28 @@ impl ChannelManager { if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) { let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update(); - match chan - .get_mut() - .get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) + match chan.get_mut() + .get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) { Ok((msgs, monitor_option)) => { if let Some(chan_monitor) = monitor_option { - if let Err(e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + if let Err(e) = + self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { if was_frozen_for_monitor { assert!(msgs.is_none()); } else { - break ( - chan.get().get_their_node_id(), - handle_monitor_err!( - self, - e, - channel_state, - chan, - RAACommitmentOrder::CommitmentFirst, - false, - msgs.is_some() - ), - ); + break (chan.get().get_their_node_id(), + handle_monitor_err!( + self, + e, + channel_state, + chan, + RAACommitmentOrder::CommitmentFirst, + false, + msgs.is_some() + )); } } } @@ -2193,12 +2106,11 @@ impl ChannelManager { } } - fn internal_open_channel( - &self, - their_node_id: &PublicKey, - their_local_features: LocalFeatures, - msg: &msgs::OpenChannel, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_open_channel(&self, + their_node_id: &PublicKey, + their_local_features: LocalFeatures, + msg: &msgs::OpenChannel) + -> Result<(), MsgHandleErrInternal> { if msg.chain_hash != self.genesis_hash { return Err(MsgHandleErrInternal::send_err_msg_no_close( "Unknown genesis block hash", @@ -2207,16 +2119,15 @@ impl ChannelManager { } let channel = Channel::new_from_req( - &*self.fee_estimator, - &self.keys_manager, - their_node_id.clone(), - their_local_features, - msg, - 0, - Arc::clone(&self.logger), - &self.default_configuration, - ) - .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?; + &*self.fee_estimator, + &self.keys_manager, + their_node_id.clone(), + their_local_features, + msg, + 0, + Arc::clone(&self.logger), + &self.default_configuration, + ).map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?; let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); match channel_state.by_id.entry(channel.channel_id()) { @@ -2227,24 +2138,20 @@ impl ChannelManager { )) }, hash_map::Entry::Vacant(entry) => { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendAcceptChannel { - node_id: their_node_id.clone(), - msg: channel.get_accept_channel(), - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendAcceptChannel { node_id: their_node_id.clone(), + msg: channel.get_accept_channel() }); entry.insert(channel); }, } Ok(()) } - fn internal_accept_channel( - &self, - their_node_id: &PublicKey, - their_local_features: LocalFeatures, - msg: &msgs::AcceptChannel, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_accept_channel(&self, + their_node_id: &PublicKey, + their_local_features: LocalFeatures, + msg: &msgs::AcceptChannel) + -> Result<(), MsgHandleErrInternal> { let (value, output_script, user_id) = { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = channel_lock.borrow_parts(); @@ -2257,17 +2164,18 @@ impl ChannelManager { )); } try_chan_entry!( - self, - chan.get_mut() - .accept_channel(&msg, &self.default_configuration, their_local_features), - channel_state, - chan + self, + chan.get_mut().accept_channel( + &msg, + &self.default_configuration, + their_local_features + ), + channel_state, + chan ); - ( - chan.get().get_value_satoshis(), - chan.get().get_funding_redeemscript().to_v0_p2wsh(), - chan.get().get_user_id(), - ) + (chan.get().get_value_satoshis(), + chan.get().get_funding_redeemscript().to_v0_p2wsh(), + chan.get().get_user_id()) }, hash_map::Entry::Vacant(_) => { return Err(MsgHandleErrInternal::send_err_msg_no_close( @@ -2278,20 +2186,17 @@ impl ChannelManager { } }; let mut pending_events = self.pending_events.lock().unwrap(); - pending_events.push(events::Event::FundingGenerationReady { - temporary_channel_id: msg.temporary_channel_id, - channel_value_satoshis: value, - output_script, - user_channel_id: user_id, - }); + pending_events.push(events::Event::FundingGenerationReady { temporary_channel_id: msg.temporary_channel_id, + channel_value_satoshis: value, + output_script, + user_channel_id: user_id }); Ok(()) } - fn internal_funding_created( - &self, - their_node_id: &PublicKey, - msg: &msgs::FundingCreated, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_funding_created(&self, + their_node_id: &PublicKey, + msg: &msgs::FundingCreated) + -> Result<(), MsgHandleErrInternal> { let ((funding_msg, monitor_update), mut chan) = { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = channel_lock.borrow_parts(); @@ -2303,10 +2208,7 @@ impl ChannelManager { msg.temporary_channel_id, )); } - ( - try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), - chan.remove(), - ) + (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove()) }, hash_map::Entry::Vacant(_) => { return Err(MsgHandleErrInternal::send_err_msg_no_close( @@ -2318,9 +2220,8 @@ impl ChannelManager { }; // Because we have exclusive ownership of the channel here we can release the channel_state // lock before add_update_monitor - if let Err(e) = self - .monitor - .add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) + if let Err(e) = self.monitor + .add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) { match e { ChannelMonitorUpdateErr::PermanentFailure => { @@ -2354,23 +2255,19 @@ impl ChannelManager { )) }, hash_map::Entry::Vacant(e) => { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendFundingSigned { - node_id: their_node_id.clone(), - msg: funding_msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendFundingSigned { node_id: their_node_id.clone(), + msg: funding_msg }); e.insert(chan); }, } Ok(()) } - fn internal_funding_signed( - &self, - their_node_id: &PublicKey, - msg: &msgs::FundingSigned, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_funding_signed(&self, + their_node_id: &PublicKey, + msg: &msgs::FundingSigned) + -> Result<(), MsgHandleErrInternal> { let (funding_txo, user_id) = { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = channel_lock.borrow_parts(); @@ -2383,18 +2280,17 @@ impl ChannelManager { )); } let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan); - if let Err(e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + if let Err(e) = self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { return_monitor_err!( - self, - e, - channel_state, - chan, - RAACommitmentOrder::RevokeAndACKFirst, - false, - false + self, + e, + channel_state, + chan, + RAACommitmentOrder::RevokeAndACKFirst, + false, + false ); } (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id()) @@ -2408,18 +2304,15 @@ impl ChannelManager { } }; let mut pending_events = self.pending_events.lock().unwrap(); - pending_events.push(events::Event::FundingBroadcastSafe { - funding_txo, - user_channel_id: user_id, - }); + pending_events.push(events::Event::FundingBroadcastSafe { funding_txo, + user_channel_id: user_id }); Ok(()) } - fn internal_funding_locked( - &self, - their_node_id: &PublicKey, - msg: &msgs::FundingLocked, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_funding_locked(&self, + their_node_id: &PublicKey, + msg: &msgs::FundingLocked) + -> Result<(), MsgHandleErrInternal> { let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); match channel_state.by_id.entry(msg.channel_id) { @@ -2441,19 +2334,17 @@ impl ChannelManager { // connection in the future if simultaneous misses by both peers due to network/hardware // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs // to be received, from then sigs are going to be flood to the whole network. - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendAnnouncementSignatures { - node_id: their_node_id.clone(), - msg: announcement_sigs, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendAnnouncementSignatures { node_id: + their_node_id.clone(), + msg: + announcement_sigs }); } Ok(()) }, - hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close( - "Failed to find corresponding channel", - msg.channel_id, - )), + hash_map::Entry::Vacant(_) => { + Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id)) + }, } } @@ -2477,20 +2368,15 @@ impl ChannelManager { chan_entry ); if let Some(msg) = shutdown { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendShutdown { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendShutdown { node_id: their_node_id.clone(), + msg }); } if let Some(msg) = closing_signed { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendClosingSigned { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendClosingSigned { node_id: + their_node_id.clone(), + msg }); } if chan_entry.get().is_shutdown() { if let Some(short_id) = chan_entry.get().get_short_channel_id() { @@ -2511,31 +2397,27 @@ impl ChannelManager { }; for htlc_source in dropped_htlcs.drain(..) { self.fail_htlc_backwards_internal( - self.channel_state.lock().unwrap(), - htlc_source.0, - &htlc_source.1, - HTLCFailReason::Reason { - failure_code: 0x4000 | 8, - data: Vec::new(), - }, + self.channel_state.lock().unwrap(), + htlc_source.0, + &htlc_source.1, + HTLCFailReason::Reason { failure_code: 0x4000 | 8, + data: Vec::new(), }, ); } if let Some(chan) = chan_option { if let Ok(update) = self.get_channel_update(&chan) { let mut channel_state = self.channel_state.lock().unwrap(); - channel_state - .pending_msg_events - .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); } } Ok(()) } - fn internal_closing_signed( - &self, - their_node_id: &PublicKey, - msg: &msgs::ClosingSigned, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_closing_signed(&self, + their_node_id: &PublicKey, + msg: &msgs::ClosingSigned) + -> Result<(), MsgHandleErrInternal> { let (tx, chan_option) = { let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); @@ -2548,18 +2430,17 @@ impl ChannelManager { )); } let (closing_signed, tx) = try_chan_entry!( - self, - chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), - channel_state, - chan_entry + self, + chan_entry.get_mut() + .closing_signed(&*self.fee_estimator, &msg), + channel_state, + chan_entry ); if let Some(msg) = closing_signed { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendClosingSigned { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendClosingSigned { node_id: + their_node_id.clone(), + msg }); } if tx.is_some() { // We're done with this channel, we've got a signed closing transaction and @@ -2590,19 +2471,17 @@ impl ChannelManager { if let Some(chan) = chan_option { if let Ok(update) = self.get_channel_update(&chan) { let mut channel_state = self.channel_state.lock().unwrap(); - channel_state - .pending_msg_events - .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); } } Ok(()) } - fn internal_update_add_htlc( - &self, - their_node_id: &PublicKey, - msg: &msgs::UpdateAddHTLC, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_update_add_htlc(&self, + their_node_id: &PublicKey, + msg: &msgs::UpdateAddHTLC) + -> Result<(), MsgHandleErrInternal> { //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and //determine the state of the payment based on our response/if we forward anything/the time //we take to respond. We should take care to avoid allowing such an attack. @@ -2627,21 +2506,25 @@ impl ChannelManager { // If the update_add is completely bogus, the call will Err and we will close, // but if we've sent a shutdown and they haven't acknowledged it yet, we just // want to reject the new HTLC and fail it backwards instead of forwarding. - if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { - incoming_shared_secret, .. - }) = pending_forward_info + if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = + pending_forward_info { let chan_update = self.get_channel_update(chan.get()); - pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { - channel_id: msg.channel_id, - htlc_id: msg.htlc_id, - reason: if let Ok(update) = chan_update { - // TODO: Note that |20 is defined as "channel FROM the processing - // node has been disabled" (emphasis mine), which seems to imply - // that we can't return |20 for an inbound channel being disabled. - // This probably needs a spec update but should definitely be - // allowed. - onion_utils::build_first_hop_failure_packet( + pending_forward_info = + PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id: + msg.channel_id, + htlc_id: + msg.htlc_id, + reason: if let Ok( + update, + ) = chan_update + { + // TODO: Note that |20 is defined as "channel FROM the processing + // node has been disabled" (emphasis mine), which seems to imply + // that we can't return |20 for an inbound channel being disabled. + // This probably needs a spec update but should definitely be + // allowed. + onion_utils::build_first_hop_failure_packet( &incoming_shared_secret, 0x1000 | 20, &{ @@ -2651,22 +2534,21 @@ impl ChannelManager { res }[..], ) - } else { - // This can only happen if the channel isn't in the fully-funded - // state yet, implying our counterparty is trying to route payments - // over the channel back to themselves (cause no one else should - // know the short_id is a lightning channel yet). We should have no - // problem just calling this unknown_next_peer - onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000 | 10, &[]) - }, - })); + } else { + // This can only happen if the channel isn't in the fully-funded + // state yet, implying our counterparty is trying to route payments + // over the channel back to themselves (cause no one else should + // know the short_id is a lightning channel yet). We should have no + // problem just calling this unknown_next_peer + onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000 | 10, &[]) + }, })); } } try_chan_entry!( - self, - chan.get_mut().update_add_htlc(&msg, pending_forward_info), - channel_state, - chan + self, + chan.get_mut().update_add_htlc(&msg, pending_forward_info), + channel_state, + chan ); }, hash_map::Entry::Vacant(_) => { @@ -2679,11 +2561,10 @@ impl ChannelManager { Ok(()) } - fn internal_update_fulfill_htlc( - &self, - their_node_id: &PublicKey, - msg: &msgs::UpdateFulfillHTLC, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_update_fulfill_htlc(&self, + their_node_id: &PublicKey, + msg: &msgs::UpdateFulfillHTLC) + -> Result<(), MsgHandleErrInternal> { let mut channel_lock = self.channel_state.lock().unwrap(); let htlc_source = { let channel_state = channel_lock.borrow_parts(); @@ -2709,11 +2590,10 @@ impl ChannelManager { Ok(()) } - fn internal_update_fail_htlc( - &self, - their_node_id: &PublicKey, - msg: &msgs::UpdateFailHTLC, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_update_fail_htlc(&self, + their_node_id: &PublicKey, + msg: &msgs::UpdateFailHTLC) + -> Result<(), MsgHandleErrInternal> { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = channel_lock.borrow_parts(); match channel_state.by_id.entry(msg.channel_id) { @@ -2725,15 +2605,13 @@ impl ChannelManager { )); } try_chan_entry!( - self, - chan.get_mut().update_fail_htlc( - &msg, - HTLCFailReason::LightningError { - err: msg.reason.clone() - } - ), - channel_state, - chan + self, + chan.get_mut().update_fail_htlc( + &msg, + HTLCFailReason::LightningError { err: msg.reason.clone() } + ), + channel_state, + chan ); }, hash_map::Entry::Vacant(_) => { @@ -2746,11 +2624,10 @@ impl ChannelManager { Ok(()) } - fn internal_update_fail_malformed_htlc( - &self, - their_node_id: &PublicKey, - msg: &msgs::UpdateFailMalformedHTLC, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_update_fail_malformed_htlc(&self, + their_node_id: &PublicKey, + msg: &msgs::UpdateFailMalformedHTLC) + -> Result<(), MsgHandleErrInternal> { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = channel_lock.borrow_parts(); match channel_state.by_id.entry(msg.channel_id) { @@ -2763,25 +2640,23 @@ impl ChannelManager { } if (msg.failure_code & 0x8000) == 0 { try_chan_entry!( - self, - Err(ChannelError::Close( - "Got update_fail_malformed_htlc with BADONION not set" - )), - channel_state, - chan + self, + Err(ChannelError::Close( + "Got update_fail_malformed_htlc with BADONION not set" + )), + channel_state, + chan ); } try_chan_entry!( - self, - chan.get_mut().update_fail_malformed_htlc( - &msg, - HTLCFailReason::Reason { - failure_code: msg.failure_code, - data: Vec::new() - } - ), - channel_state, - chan + self, + chan.get_mut().update_fail_malformed_htlc( + &msg, + HTLCFailReason::Reason { failure_code: msg.failure_code, + data: Vec::new() } + ), + channel_state, + chan ); Ok(()) }, @@ -2794,11 +2669,10 @@ impl ChannelManager { } } - fn internal_commitment_signed( - &self, - their_node_id: &PublicKey, - msg: &msgs::CommitmentSigned, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_commitment_signed(&self, + their_node_id: &PublicKey, + msg: &msgs::CommitmentSigned) + -> Result<(), MsgHandleErrInternal> { let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); match channel_state.by_id.entry(msg.channel_id) { @@ -2815,27 +2689,23 @@ impl ChannelManager { channel_state, chan ); - if let Err(e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + if let Err(e) = self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { return_monitor_err!( - self, - e, - channel_state, - chan, - RAACommitmentOrder::RevokeAndACKFirst, - true, - commitment_signed.is_some() + self, + e, + channel_state, + chan, + RAACommitmentOrder::RevokeAndACKFirst, + true, + commitment_signed.is_some() ); //TODO: Rebroadcast closing_signed if present on monitor update restoration } - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendRevokeAndACK { - node_id: their_node_id.clone(), - msg: revoke_and_ack, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendRevokeAndACK { node_id: their_node_id.clone(), + msg: revoke_and_ack }); if let Some(msg) = commitment_signed { channel_state .pending_msg_events @@ -2852,12 +2722,9 @@ impl ChannelManager { }); } if let Some(msg) = closing_signed { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendClosingSigned { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendClosingSigned { node_id: their_node_id.clone(), + msg }); } Ok(()) }, @@ -2882,18 +2749,14 @@ impl ChannelManager { for (forward_info, prev_htlc_id) in pending_forwards.drain(..) { match channel_state.forward_htlcs.entry(forward_info.short_channel_id) { hash_map::Entry::Occupied(mut entry) => { - entry.get_mut().push(HTLCForwardInfo::AddHTLC { - prev_short_channel_id, - prev_htlc_id, - forward_info, - }); + entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, + prev_htlc_id, + forward_info }); }, hash_map::Entry::Vacant(entry) => { - entry.insert(vec![HTLCForwardInfo::AddHTLC { - prev_short_channel_id, - prev_htlc_id, - forward_info, - }]); + entry.insert(vec![HTLCForwardInfo::AddHTLC { prev_short_channel_id, + prev_htlc_id, + forward_info }]); }, } } @@ -2908,11 +2771,10 @@ impl ChannelManager { } } - fn internal_revoke_and_ack( - &self, - their_node_id: &PublicKey, - msg: &msgs::RevokeAndACK, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_revoke_and_ack(&self, + their_node_id: &PublicKey, + msg: &msgs::RevokeAndACK) + -> Result<(), MsgHandleErrInternal> { let (pending_forwards, mut pending_failures, short_channel_id) = { let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); @@ -2925,62 +2787,55 @@ impl ChannelManager { )); } let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update(); - let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) = try_chan_entry!( - self, - chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), - channel_state, - chan - ); - if let Err(e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) = + try_chan_entry!( + self, + chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), + channel_state, + chan + ); + if let Err(e) = self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { if was_frozen_for_monitor { assert!( - commitment_update.is_none() - && closing_signed.is_none() && pending_forwards.is_empty() - && pending_failures.is_empty() + commitment_update.is_none() + && closing_signed.is_none() && pending_forwards.is_empty() + && pending_failures.is_empty() ); return Err(MsgHandleErrInternal::ignore_no_close( "Previous monitor update failure prevented responses to RAA", )); } else { return_monitor_err!( - self, - e, - channel_state, - chan, - RAACommitmentOrder::CommitmentFirst, - false, - commitment_update.is_some(), - pending_forwards, - pending_failures + self, + e, + channel_state, + chan, + RAACommitmentOrder::CommitmentFirst, + false, + commitment_update.is_some(), + pending_forwards, + pending_failures ); } } if let Some(updates) = commitment_update { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::UpdateHTLCs { - node_id: their_node_id.clone(), - updates, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::UpdateHTLCs { node_id: their_node_id.clone(), + updates }); } if let Some(msg) = closing_signed { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendClosingSigned { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendClosingSigned { node_id: + their_node_id.clone(), + msg }); } - ( - pending_forwards, - pending_failures, - chan.get() - .get_short_channel_id() - .expect("RAA should only work on a short-id-available channel"), - ) + (pending_forwards, + pending_failures, + chan.get() + .get_short_channel_id() + .expect("RAA should only work on a short-id-available channel")) }, hash_map::Entry::Vacant(_) => { return Err(MsgHandleErrInternal::send_err_msg_no_close( @@ -2998,11 +2853,10 @@ impl ChannelManager { Ok(()) } - fn internal_update_fee( - &self, - their_node_id: &PublicKey, - msg: &msgs::UpdateFee, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_update_fee(&self, + their_node_id: &PublicKey, + msg: &msgs::UpdateFee) + -> Result<(), MsgHandleErrInternal> { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = channel_lock.borrow_parts(); match channel_state.by_id.entry(msg.channel_id) { @@ -3014,10 +2868,10 @@ impl ChannelManager { )); } try_chan_entry!( - self, - chan.get_mut().update_fee(&*self.fee_estimator, &msg), - channel_state, - chan + self, + chan.get_mut().update_fee(&*self.fee_estimator, &msg), + channel_state, + chan ); }, hash_map::Entry::Vacant(_) => { @@ -3030,11 +2884,10 @@ impl ChannelManager { Ok(()) } - fn internal_announcement_signatures( - &self, - their_node_id: &PublicKey, - msg: &msgs::AnnouncementSignatures, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_announcement_signatures(&self, + their_node_id: &PublicKey, + msg: &msgs::AnnouncementSignatures) + -> Result<(), MsgHandleErrInternal> { let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); @@ -3064,35 +2917,33 @@ impl ChannelManager { let were_node_one = announcement.node_id_1 == our_node_id; let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]); - if self - .secp_ctx - .verify( - &msghash, - &msg.node_signature, - if were_node_one { - &announcement.node_id_2 - } else { - &announcement.node_id_1 - }, - ) - .is_err() || self - .secp_ctx - .verify( - &msghash, - &msg.bitcoin_signature, - if were_node_one { - &announcement.bitcoin_key_2 - } else { - &announcement.bitcoin_key_1 - }, - ) - .is_err() + if self.secp_ctx + .verify( + &msghash, + &msg.node_signature, + if were_node_one { + &announcement.node_id_2 + } else { + &announcement.node_id_1 + }, + ) + .is_err() || self.secp_ctx + .verify( + &msghash, + &msg.bitcoin_signature, + if were_node_one { + &announcement.bitcoin_key_2 + } else { + &announcement.bitcoin_key_1 + }, + ) + .is_err() { try_chan_entry!( - self, - Err(ChannelError::Close("Bad announcement_signatures node_signature")), - channel_state, - chan + self, + Err(ChannelError::Close("Bad announcement_signatures node_signature")), + channel_state, + chan ); } @@ -3137,11 +2988,10 @@ impl ChannelManager { Ok(()) } - fn internal_channel_reestablish( - &self, - their_node_id: &PublicKey, - msg: &msgs::ChannelReestablish, - ) -> Result<(), MsgHandleErrInternal> { + fn internal_channel_reestablish(&self, + their_node_id: &PublicKey, + msg: &msgs::ChannelReestablish) + -> Result<(), MsgHandleErrInternal> { let mut channel_state_lock = self.channel_state.lock().unwrap(); let channel_state = channel_state_lock.borrow_parts(); @@ -3156,9 +3006,8 @@ impl ChannelManager { let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) = try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan); if let Some(monitor) = channel_monitor { - if let Err(e) = self - .monitor - .add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) + if let Err(e) = self.monitor + .add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) { // channel_reestablish doesn't guarantee the order it returns is sensical // for the messages it returns, but if we're setting what messages to @@ -3170,24 +3019,21 @@ impl ChannelManager { order = RAACommitmentOrder::RevokeAndACKFirst; } return_monitor_err!( - self, - e, - channel_state, - chan, - order, - revoke_and_ack.is_some(), - commitment_update.is_some() + self, + e, + channel_state, + chan, + order, + revoke_and_ack.is_some(), + commitment_update.is_some() ); //TODO: Resend the funding_locked if needed once we get the monitor running again } } if let Some(msg) = funding_locked { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendFundingLocked { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendFundingLocked { node_id: their_node_id.clone(), + msg }); } macro_rules! send_raa { () => { @@ -3214,12 +3060,9 @@ impl ChannelManager { }, } if let Some(msg) = shutdown { - channel_state - .pending_msg_events - .push(events::MessageSendEvent::SendShutdown { - node_id: their_node_id.clone(), - msg, - }); + channel_state.pending_msg_events + .push(events::MessageSendEvent::SendShutdown { node_id: their_node_id.clone(), + msg }); } Ok(()) }, @@ -3246,15 +3089,12 @@ impl ChannelManager { match channel_state.by_id.entry(channel_id) { hash_map::Entry::Vacant(_) => { - return Err(APIError::APIMisuseError { - err: "Failed to find corresponding channel", - }) + return Err(APIError::APIMisuseError { err: "Failed to find corresponding channel" }) }, hash_map::Entry::Occupied(mut chan) => { if !chan.get().is_outbound() { - return Err(APIError::APIMisuseError { - err: "update_fee cannot be sent for an inbound channel", - }); + return Err(APIError::APIMisuseError { err: + "update_fee cannot be sent for an inbound channel" }); } if chan.get().is_awaiting_monitor_update() { return Err(APIError::MonitorUpdateFailed); @@ -3271,9 +3111,8 @@ impl ChannelManager { channel_state, chan ) { - if let Err(_e) = self - .monitor - .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) + if let Err(_e) = self.monitor + .add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) { unimplemented!(); } @@ -3313,25 +3152,23 @@ impl events::MessageSendEventsProvider for ChannelManag for htlc_update in self.monitor.fetch_pending_htlc_updated() { if let Some(preimage) = htlc_update.payment_preimage { log_trace!( - self, - "Claiming HTLC with preimage {} from our monitor", - log_bytes!(preimage.0) + self, + "Claiming HTLC with preimage {} from our monitor", + log_bytes!(preimage.0) ); self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage); } else { log_trace!( - self, - "Failing HTLC with hash {} from our monitor", - log_bytes!(htlc_update.payment_hash.0) + self, + "Failing HTLC with hash {} from our monitor", + log_bytes!(htlc_update.payment_hash.0) ); self.fail_htlc_backwards_internal( - self.channel_state.lock().unwrap(), - htlc_update.source, - &htlc_update.payment_hash, - HTLCFailReason::Reason { - failure_code: 0x4000 | 8, - data: Vec::new(), - }, + self.channel_state.lock().unwrap(), + htlc_update.source, + &htlc_update.payment_hash, + HTLCFailReason::Reason { failure_code: 0x4000 | 8, + data: Vec::new(), }, ); } } @@ -3354,25 +3191,23 @@ impl events::EventsProvider for ChannelManager events::EventsProvider for ChannelManager ChainListener for ChannelManager { - fn block_connected( - &self, - header: &BlockHeader, - height: u32, - txn_matched: &[&Transaction], - indexes_of_txn_matched: &[u32], - ) { + fn block_connected(&self, + header: &BlockHeader, + height: u32, + txn_matched: &[&Transaction], + indexes_of_txn_matched: &[u32]) { let header_hash = header.bitcoin_hash(); log_trace!( - self, - "Block {} at height {} connected with {} txn matched", - header_hash, - height, - txn_matched.len() + self, + "Block {} at height {} connected with {} txn matched", + header_hash, + height, + txn_matched.len() ); let _ = self.total_consistency_lock.read().unwrap(); let mut failed_channels = Vec::new(); @@ -3409,31 +3242,35 @@ impl ChainListener for ChannelManager { let short_to_id = channel_state.short_to_id; let pending_msg_events = channel_state.pending_msg_events; channel_state.by_id.retain(|_, channel| { - let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched); - if let Ok(Some(funding_locked)) = chan_res { - pending_msg_events.push(events::MessageSendEvent::SendFundingLocked { + let chan_res = + channel.block_connected(header, height, txn_matched, indexes_of_txn_matched); + if let Ok(Some(funding_locked)) = chan_res { + pending_msg_events.push(events::MessageSendEvent::SendFundingLocked { node_id: channel.get_their_node_id(), msg: funding_locked, }); - if let Some(announcement_sigs) = self.get_announcement_sigs(channel) { - pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures { + if let Some(announcement_sigs) = self.get_announcement_sigs(channel) { + pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures { node_id: channel.get_their_node_id(), msg: announcement_sigs, }); - } - short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id()); - } else if let Err(e) = chan_res { - pending_msg_events.push(events::MessageSendEvent::HandleError { + } + short_to_id.insert( + channel.get_short_channel_id().unwrap(), + channel.channel_id(), + ); + } else if let Err(e) = chan_res { + pending_msg_events.push(events::MessageSendEvent::HandleError { node_id: channel.get_their_node_id(), action: msgs::ErrorAction::SendErrorMessage { msg: e }, }); - return false; - } - if let Some(funding_txo) = channel.get_funding_txo() { - for tx in txn_matched { - for inp in tx.input.iter() { - if inp.previous_output == funding_txo.into_bitcoin_outpoint() { - log_trace!( + return false; + } + if let Some(funding_txo) = channel.get_funding_txo() { + for tx in txn_matched { + for inp in tx.input.iter() { + if inp.previous_output == funding_txo.into_bitcoin_outpoint() { + log_trace!( self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), @@ -3441,47 +3278,48 @@ impl ChainListener for ChannelManager { inp.previous_output.vout, log_bytes!(channel.channel_id()) ); - if let Some(short_id) = channel.get_short_channel_id() { - short_to_id.remove(&short_id); - } - // It looks like our counterparty went on-chain. We go ahead and - // broadcast our latest local state as well here, just in case its - // some kind of SPV attack, though we expect these to be dropped. - failed_channels.push(channel.force_shutdown()); - if let Ok(update) = self.get_channel_update(&channel) { - pending_msg_events + if let Some(short_id) = channel.get_short_channel_id() { + short_to_id.remove(&short_id); + } + // It looks like our counterparty went on-chain. We go ahead and + // broadcast our latest local state as well here, just in case its + // some kind of SPV attack, though we expect these to be dropped. + failed_channels.push(channel.force_shutdown()); + if let Ok(update) = self.get_channel_update(&channel) { + pending_msg_events .push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); - } - return false; - } - } - } - } - if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) { - if let Some(short_id) = channel.get_short_channel_id() { - short_to_id.remove(&short_id); - } - failed_channels.push(channel.force_shutdown()); - // If would_broadcast_at_height() is true, the channel_monitor will broadcast - // the latest local tx for us, so we should skip that here (it doesn't really - // hurt anything, but does make tests a bit simpler). - failed_channels.last_mut().unwrap().0 = Vec::new(); - if let Ok(update) = self.get_channel_update(&channel) { - pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); - } - return false; - } - true - }); + } + return false; + } + } + } + } + if channel.is_funding_initiated() + && channel.channel_monitor().would_broadcast_at_height(height) + { + if let Some(short_id) = channel.get_short_channel_id() { + short_to_id.remove(&short_id); + } + failed_channels.push(channel.force_shutdown()); + // If would_broadcast_at_height() is true, the channel_monitor will broadcast + // the latest local tx for us, so we should skip that here (it doesn't really + // hurt anything, but does make tests a bit simpler). + failed_channels.last_mut().unwrap().0 = Vec::new(); + if let Ok(update) = self.get_channel_update(&channel) { + pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + } + return false; + } + true + }); } for failure in failed_channels.drain(..) { self.finish_force_close_channel(failure); } self.latest_block_height.store(height as usize, Ordering::Release); - *self - .last_block_hash - .try_lock() - .expect("block_(dis)connected must not be called in parallel") = header_hash; + *self.last_block_hash + .try_lock() + .expect("block_(dis)connected must not be called in parallel") = header_hash; } /// We force-close the channel without letting our counterparty participate in the shutdown @@ -3494,38 +3332,35 @@ impl ChainListener for ChannelManager { let short_to_id = channel_state.short_to_id; let pending_msg_events = channel_state.pending_msg_events; channel_state.by_id.retain(|_, v| { - if v.block_disconnected(header) { - if let Some(short_id) = v.get_short_channel_id() { - short_to_id.remove(&short_id); - } - failed_channels.push(v.force_shutdown()); - if let Ok(update) = self.get_channel_update(&v) { - pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); - } - false - } else { - true - } - }); + if v.block_disconnected(header) { + if let Some(short_id) = v.get_short_channel_id() { + short_to_id.remove(&short_id); + } + failed_channels.push(v.force_shutdown()); + if let Ok(update) = self.get_channel_update(&v) { + pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg: update }); + } + false + } else { + true + } + }); } for failure in failed_channels.drain(..) { self.finish_force_close_channel(failure); } self.latest_block_height.fetch_sub(1, Ordering::AcqRel); - *self - .last_block_hash - .try_lock() - .expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash(); + *self.last_block_hash + .try_lock() + .expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash(); } } impl ChannelMessageHandler for ChannelManager { - fn handle_open_channel( - &self, - their_node_id: &PublicKey, - their_local_features: LocalFeatures, - msg: &msgs::OpenChannel, - ) { + fn handle_open_channel(&self, + their_node_id: &PublicKey, + their_local_features: LocalFeatures, + msg: &msgs::OpenChannel) { let _ = self.total_consistency_lock.read().unwrap(); let res = self.internal_open_channel(their_node_id, their_local_features, msg); if res.is_err() { @@ -3534,12 +3369,10 @@ impl ChannelMessageHandler for ChannelManager ChannelMessageHandler for ChannelManager node_id != their_node_id, - &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true, - &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true, - &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id, - &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true, - }); + &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendShutdown { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true, + &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true, + &events::MessageSendEvent::HandleError { ref node_id, .. } => { + node_id != their_node_id + }, + &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true, + }); } for failure in failed_channels.drain(..) { self.finish_force_close_channel(failure); @@ -3751,13 +3609,11 @@ impl ChannelMessageHandler for ChannelManager ChannelMessageHandler for ChannelManager ChannelMessageHandler for ChannelManager Readable for PendingForwardHTLCInfo { fn read(reader: &mut R) -> Result { - Ok(PendingForwardHTLCInfo { - onion_packet: Readable::read(reader)?, - incoming_shared_secret: Readable::read(reader)?, - payment_hash: Readable::read(reader)?, - short_channel_id: Readable::read(reader)?, - amt_to_forward: Readable::read(reader)?, - outgoing_cltv_value: Readable::read(reader)?, - }) + Ok(PendingForwardHTLCInfo { onion_packet: Readable::read(reader)?, + incoming_shared_secret: Readable::read(reader)?, + payment_hash: Readable::read(reader)?, + short_channel_id: Readable::read(reader)?, + amt_to_forward: Readable::read(reader)?, + outgoing_cltv_value: Readable::read(reader)? }) } } @@ -3904,11 +3758,9 @@ impl Writeable for HTLCSource { 0u8.write(writer)?; hop_data.write(writer)?; }, - &HTLCSource::OutboundRoute { - ref route, - ref session_priv, - ref first_hop_htlc_msat, - } => { + &HTLCSource::OutboundRoute { ref route, + ref session_priv, + ref first_hop_htlc_msat, } => { 1u8.write(writer)?; route.write(writer)?; session_priv.write(writer)?; @@ -3923,11 +3775,9 @@ impl Readable for HTLCSource { fn read(reader: &mut R) -> Result { match >::read(reader)? { 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)), - 1 => Ok(HTLCSource::OutboundRoute { - route: Readable::read(reader)?, - session_priv: Readable::read(reader)?, - first_hop_htlc_msat: Readable::read(reader)?, - }), + 1 => Ok(HTLCSource::OutboundRoute { route: Readable::read(reader)?, + session_priv: Readable::read(reader)?, + first_hop_htlc_msat: Readable::read(reader)? }), _ => Err(DecodeError::InvalidValue), } } @@ -3940,10 +3790,8 @@ impl Writeable for HTLCFailReason { 0u8.write(writer)?; err.write(writer)?; }, - &HTLCFailReason::Reason { - ref failure_code, - ref data, - } => { + &HTLCFailReason::Reason { ref failure_code, + ref data, } => { 1u8.write(writer)?; failure_code.write(writer)?; data.write(writer)?; @@ -3956,13 +3804,9 @@ impl Writeable for HTLCFailReason { impl Readable for HTLCFailReason { fn read(reader: &mut R) -> Result { match >::read(reader)? { - 0 => Ok(HTLCFailReason::LightningError { - err: Readable::read(reader)?, - }), - 1 => Ok(HTLCFailReason::Reason { - failure_code: Readable::read(reader)?, - data: Readable::read(reader)?, - }), + 0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }), + 1 => Ok(HTLCFailReason::Reason { failure_code: Readable::read(reader)?, + data: Readable::read(reader)? }), _ => Err(DecodeError::InvalidValue), } } @@ -3971,20 +3815,16 @@ impl Readable for HTLCFailReason { impl Writeable for HTLCForwardInfo { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { match self { - &HTLCForwardInfo::AddHTLC { - ref prev_short_channel_id, - ref prev_htlc_id, - ref forward_info, - } => { + &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, + ref prev_htlc_id, + ref forward_info, } => { 0u8.write(writer)?; prev_short_channel_id.write(writer)?; prev_htlc_id.write(writer)?; forward_info.write(writer)?; }, - &HTLCForwardInfo::FailHTLC { - ref htlc_id, - ref err_packet, - } => { + &HTLCForwardInfo::FailHTLC { ref htlc_id, + ref err_packet, } => { 1u8.write(writer)?; htlc_id.write(writer)?; err_packet.write(writer)?; @@ -3997,15 +3837,11 @@ impl Writeable for HTLCForwardInfo { impl Readable for HTLCForwardInfo { fn read(reader: &mut R) -> Result { match >::read(reader)? { - 0 => Ok(HTLCForwardInfo::AddHTLC { - prev_short_channel_id: Readable::read(reader)?, - prev_htlc_id: Readable::read(reader)?, - forward_info: Readable::read(reader)?, - }), - 1 => Ok(HTLCForwardInfo::FailHTLC { - htlc_id: Readable::read(reader)?, - err_packet: Readable::read(reader)?, - }), + 0 => Ok(HTLCForwardInfo::AddHTLC { prev_short_channel_id: Readable::read(reader)?, + prev_htlc_id: Readable::read(reader)?, + forward_info: Readable::read(reader)? }), + 1 => Ok(HTLCForwardInfo::FailHTLC { htlc_id: Readable::read(reader)?, + err_packet: Readable::read(reader)? }), _ => Err(DecodeError::InvalidValue), } } @@ -4140,16 +3976,15 @@ impl<'a, R: ::std::io::Read, ChanSigner: ChannelKeys + Readable> return Err(DecodeError::InvalidValue); } - let funding_txo = channel - .channel_monitor() - .get_funding_txo() - .ok_or(DecodeError::InvalidValue)?; + let funding_txo = channel.channel_monitor() + .get_funding_txo() + .ok_or(DecodeError::InvalidValue)?; funding_txo_set.insert(funding_txo.clone()); if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) { if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() - || channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() - || channel.get_cur_remote_commitment_transaction_number() - != monitor.get_cur_remote_commitment_number() + || channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() + || channel.get_cur_remote_commitment_transaction_number() + != monitor.get_cur_remote_commitment_number() { let mut force_close_res = channel.force_shutdown(); force_close_res.0 = monitor.get_latest_local_commitment_txn(); @@ -4195,28 +4030,25 @@ impl<'a, R: ::std::io::Read, ChanSigner: ChannelKeys + Readable> claimable_htlcs.insert(payment_hash, previous_hops); } - let channel_manager = ChannelManager { - genesis_hash, - fee_estimator: args.fee_estimator, - monitor: args.monitor, - tx_broadcaster: args.tx_broadcaster, - latest_block_height: AtomicUsize::new(latest_block_height as usize), - last_block_hash: Mutex::new(last_block_hash), - secp_ctx: Secp256k1::new(), - channel_state: Mutex::new(ChannelHolder { - by_id, - short_to_id, - forward_htlcs, - claimable_htlcs, - pending_msg_events: Vec::new(), - }), - our_network_key: args.keys_manager.get_node_secret(), - pending_events: Mutex::new(Vec::new()), - total_consistency_lock: RwLock::new(()), - keys_manager: args.keys_manager, - logger: args.logger, - default_configuration: args.default_config, - }; + let channel_manager = ChannelManager { genesis_hash, + fee_estimator: args.fee_estimator, + monitor: args.monitor, + tx_broadcaster: args.tx_broadcaster, + latest_block_height: AtomicUsize::new(latest_block_height as usize), + last_block_hash: Mutex::new(last_block_hash), + secp_ctx: Secp256k1::new(), + channel_state: Mutex::new(ChannelHolder { by_id, + short_to_id, + forward_htlcs, + claimable_htlcs, + pending_msg_events: + Vec::new() }), + our_network_key: args.keys_manager.get_node_secret(), + pending_events: Mutex::new(Vec::new()), + total_consistency_lock: RwLock::new(()), + keys_manager: args.keys_manager, + logger: args.logger, + default_configuration: args.default_config }; for close_res in closed_channels.drain(..) { channel_manager.finish_force_close_channel(close_res); diff --git a/lightning/src/ln/channelmonitor.rs b/lightning/src/ln/channelmonitor.rs index 28e502eaf72..a04f14dcf4b 100644 --- a/lightning/src/ln/channelmonitor.rs +++ b/lightning/src/ln/channelmonitor.rs @@ -125,7 +125,7 @@ pub trait ManyChannelMonitor: Send + Sync { /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with /// any spends of it. fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) - -> Result<(), ChannelMonitorUpdateErr>; + -> Result<(), ChannelMonitorUpdateErr>; /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated /// with success or failure backward @@ -157,13 +157,11 @@ pub struct SimpleManyChannelMonitor { } impl<'a, Key: Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor { - fn block_connected( - &self, - header: &BlockHeader, - height: u32, - txn_matched: &[&Transaction], - _indexes_of_txn_matched: &[u32], - ) { + fn block_connected(&self, + header: &BlockHeader, + height: u32, + txn_matched: &[&Transaction], + _indexes_of_txn_matched: &[u32]) { let block_hash = header.bitcoin_hash(); let mut new_events: Vec = Vec::with_capacity(0); let mut htlc_updated_infos = Vec::new(); @@ -171,22 +169,20 @@ impl<'a, Key: Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMo let mut monitors = self.monitors.lock().unwrap(); for monitor in monitors.values_mut() { let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected( - txn_matched, - height, - &block_hash, - &*self.broadcaster, - &*self.fee_estimator, + txn_matched, + height, + &block_hash, + &*self.broadcaster, + &*self.fee_estimator, ); if spendable_outputs.len() > 0 { - new_events.push(events::Event::SpendableOutputs { - outputs: spendable_outputs, - }); + new_events.push(events::Event::SpendableOutputs { outputs: spendable_outputs }); } for (ref txid, ref outputs) in txn_outputs { for (idx, output) in outputs.iter().enumerate() { self.chain_monitor - .install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey); + .install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey); } } htlc_updated_infos.append(&mut htlc_updated); @@ -203,17 +199,17 @@ impl<'a, Key: Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMo // (payment_hash, HTLCSource) pair. let mut existing_claim = false; e.get_mut().retain(|htlc_data| { - if htlc.0 == htlc_data.0 { - if htlc_data.1.is_some() { - existing_claim = true; - true - } else { - false - } - } else { - true - } - }); + if htlc.0 == htlc_data.0 { + if htlc_data.1.is_some() { + existing_claim = true; + true + } else { + false + } + } else { + true + } + }); if !existing_claim { e.get_mut().push((htlc.0, htlc.1)); } @@ -233,10 +229,10 @@ impl<'a, Key: Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMo let mut monitors = self.monitors.lock().unwrap(); for monitor in monitors.values_mut() { monitor.block_disconnected( - disconnected_height, - &block_hash, - &*self.broadcaster, - &*self.fee_estimator, + disconnected_height, + &block_hash, + &*self.broadcaster, + &*self.fee_estimator, ); } } @@ -245,21 +241,18 @@ impl<'a, Key: Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMo impl SimpleManyChannelMonitor { /// Creates a new object which can be used to monitor several channels given the chain /// interface with which to register to receive notifications. - pub fn new( - chain_monitor: Arc, - broadcaster: Arc, - logger: Arc, - feeest: Arc, - ) -> Arc> { - let res = Arc::new(SimpleManyChannelMonitor { - monitors: Mutex::new(HashMap::new()), - chain_monitor, - broadcaster, - pending_events: Mutex::new(Vec::new()), - pending_htlc_updated: Mutex::new(HashMap::new()), - logger, - fee_estimator: feeest, - }); + pub fn new(chain_monitor: Arc, + broadcaster: Arc, + logger: Arc, + feeest: Arc) + -> Arc> { + let res = Arc::new(SimpleManyChannelMonitor { monitors: Mutex::new(HashMap::new()), + chain_monitor, + broadcaster, + pending_events: Mutex::new(Vec::new()), + pending_htlc_updated: Mutex::new(HashMap::new()), + logger, + fee_estimator: feeest }); res } @@ -270,9 +263,9 @@ impl SimpleManyChannelMonitor { match monitors.get_mut(&key) { Some(orig_monitor) => { log_trace!( - self, - "Updating Channel Monitor for channel {}", - log_funding_info!(monitor.key_storage) + self, + "Updating Channel Monitor for channel {}", + log_funding_info!(monitor.key_storage) ); return orig_monitor.insert_combine(monitor); }, @@ -281,19 +274,17 @@ impl SimpleManyChannelMonitor { match monitor.key_storage { Storage::Local { ref funding_info, .. } => match funding_info { &None => { - return Err(MonitorUpdateError( - "Try to update a useless monitor without funding_txo !", - )); + return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !")); }, &Some((ref outpoint, ref script)) => { log_trace!( - self, - "Got new Channel Monitor for channel {}", - log_bytes!(outpoint.to_channel_id()[..]) + self, + "Got new Channel Monitor for channel {}", + log_bytes!(outpoint.to_channel_id()[..]) ); self.chain_monitor.install_watch_tx(&outpoint.txid, script); self.chain_monitor - .install_watch_outpoint((outpoint.txid, outpoint.index as u32), script); + .install_watch_outpoint((outpoint.txid, outpoint.index as u32), script); }, }, Storage::Watchtower { .. } => { @@ -306,11 +297,10 @@ impl SimpleManyChannelMonitor { } impl ManyChannelMonitor for SimpleManyChannelMonitor { - fn add_update_monitor( - &self, - funding_txo: OutPoint, - monitor: ChannelMonitor, - ) -> Result<(), ChannelMonitorUpdateErr> { + fn add_update_monitor(&self, + funding_txo: OutPoint, + monitor: ChannelMonitor) + -> Result<(), ChannelMonitorUpdateErr> { match self.add_update_monitor_by_key(funding_txo, monitor) { Ok(_) => Ok(()), Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure), @@ -322,11 +312,9 @@ impl ManyChannelMonitor for SimpleManyChannelMonitor { let mut pending_htlcs_updated = Vec::with_capacity(updated.len()); for (k, v) in updated.drain() { for htlc_data in v { - pending_htlcs_updated.push(HTLCUpdate { - payment_hash: k, - payment_preimage: htlc_data.1, - source: htlc_data.0, - }); + pending_htlcs_updated.push(HTLCUpdate { payment_hash: k, + payment_preimage: htlc_data.1, + source: htlc_data.0 }); } } pending_htlcs_updated @@ -443,13 +431,11 @@ enum InputMaterial { impl Writeable for InputMaterial { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { match self { - &InputMaterial::Revoked { - ref script, - ref pubkey, - ref key, - ref is_htlc, - ref amount, - } => { + &InputMaterial::Revoked { ref script, + ref pubkey, + ref key, + ref is_htlc, + ref amount, } => { writer.write_all(&[0; 1])?; script.write(writer)?; pubkey.write(writer)?; @@ -461,13 +447,11 @@ impl Writeable for InputMaterial { } writer.write_all(&byte_utils::be64_to_array(*amount))?; }, - &InputMaterial::RemoteHTLC { - ref script, - ref key, - ref preimage, - ref amount, - ref locktime, - } => { + &InputMaterial::RemoteHTLC { ref script, + ref key, + ref preimage, + ref amount, + ref locktime, } => { writer.write_all(&[1; 1])?; script.write(writer)?; key.write(writer)?; @@ -475,12 +459,10 @@ impl Writeable for InputMaterial { writer.write_all(&byte_utils::be64_to_array(*amount))?; writer.write_all(&byte_utils::be32_to_array(*locktime))?; }, - &InputMaterial::LocalHTLC { - ref script, - ref sigs, - ref preimage, - ref amount, - } => { + &InputMaterial::LocalHTLC { ref script, + ref sigs, + ref preimage, + ref amount, } => { writer.write_all(&[2; 1])?; script.write(writer)?; sigs.0.write(writer)?; @@ -506,13 +488,11 @@ impl Readable for InputMaterial { _ => return Err(DecodeError::InvalidValue), }; let amount = Readable::read(reader)?; - InputMaterial::Revoked { - script, - pubkey, - key, - is_htlc, - amount, - } + InputMaterial::Revoked { script, + pubkey, + key, + is_htlc, + amount } }, 1 => { let script = Readable::read(reader)?; @@ -520,13 +500,11 @@ impl Readable for InputMaterial { let preimage = Readable::read(reader)?; let amount = Readable::read(reader)?; let locktime = Readable::read(reader)?; - InputMaterial::RemoteHTLC { - script, - key, - preimage, - amount, - locktime, - } + InputMaterial::RemoteHTLC { script, + key, + preimage, + amount, + locktime } }, 2 => { let script = Readable::read(reader)?; @@ -534,12 +512,10 @@ impl Readable for InputMaterial { let our_sig = Readable::read(reader)?; let preimage = Readable::read(reader)?; let amount = Readable::read(reader)?; - InputMaterial::LocalHTLC { - script, - sigs: (their_sig, our_sig), - preimage, - amount, - } + InputMaterial::LocalHTLC { script, + sigs: (their_sig, our_sig), + preimage, + amount } }, _ => return Err(DecodeError::InvalidValue), }; @@ -609,12 +585,10 @@ impl Readable for ClaimTxBumpMaterial { let input_material = Readable::read(reader)?; per_input_material.insert(outpoint, input_material); } - Ok(Self { - height_timer, - feerate_previous, - soonest_timelock, - per_input_material, - }) + Ok(Self { height_timer, + feerate_previous, + soonest_timelock, + per_input_material }) } } @@ -752,26 +726,26 @@ macro_rules! subtract_high_prio_fee { impl PartialEq for ChannelMonitor { fn eq(&self, other: &Self) -> bool { if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor - || self.key_storage != other.key_storage - || self.their_htlc_base_key != other.their_htlc_base_key - || self.their_delayed_payment_base_key != other.their_delayed_payment_base_key - || self.funding_redeemscript != other.funding_redeemscript - || self.channel_value_satoshis != other.channel_value_satoshis - || self.their_cur_revocation_points != other.their_cur_revocation_points - || self.our_to_self_delay != other.our_to_self_delay - || self.their_to_self_delay != other.their_to_self_delay - || self.remote_claimable_outpoints != other.remote_claimable_outpoints - || self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain - || self.remote_hash_commitment_number != other.remote_hash_commitment_number - || self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx - || self.current_remote_commitment_number != other.current_remote_commitment_number - || self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx - || self.payment_preimages != other.payment_preimages - || self.destination_script != other.destination_script - || self.to_remote_rescue != other.to_remote_rescue - || self.pending_claim_requests != other.pending_claim_requests - || self.claimable_outpoints != other.claimable_outpoints - || self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf + || self.key_storage != other.key_storage + || self.their_htlc_base_key != other.their_htlc_base_key + || self.their_delayed_payment_base_key != other.their_delayed_payment_base_key + || self.funding_redeemscript != other.funding_redeemscript + || self.channel_value_satoshis != other.channel_value_satoshis + || self.their_cur_revocation_points != other.their_cur_revocation_points + || self.our_to_self_delay != other.our_to_self_delay + || self.their_to_self_delay != other.their_to_self_delay + || self.remote_claimable_outpoints != other.remote_claimable_outpoints + || self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain + || self.remote_hash_commitment_number != other.remote_hash_commitment_number + || self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx + || self.current_remote_commitment_number != other.current_remote_commitment_number + || self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx + || self.payment_preimages != other.payment_preimages + || self.destination_script != other.destination_script + || self.to_remote_rescue != other.to_remote_rescue + || self.pending_claim_requests != other.pending_claim_requests + || self.claimable_outpoints != other.claimable_outpoints + || self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf { false } else { @@ -788,63 +762,58 @@ impl PartialEq for ChannelMonitor { } impl ChannelMonitor { - pub(super) fn new( - funding_key: &SecretKey, - revocation_base_key: &SecretKey, - delayed_payment_base_key: &SecretKey, - htlc_base_key: &SecretKey, - payment_base_key: &SecretKey, - shutdown_pubkey: &PublicKey, - our_to_self_delay: u16, - destination_script: Script, - logger: Arc, - ) -> ChannelMonitor { - ChannelMonitor { - commitment_transaction_number_obscure_factor: 0, - - key_storage: Storage::Local { - funding_key: funding_key.clone(), - revocation_base_key: revocation_base_key.clone(), - htlc_base_key: htlc_base_key.clone(), - delayed_payment_base_key: delayed_payment_base_key.clone(), - payment_base_key: payment_base_key.clone(), - shutdown_pubkey: shutdown_pubkey.clone(), - funding_info: None, - current_remote_commitment_txid: None, - prev_remote_commitment_txid: None, - }, - their_htlc_base_key: None, - their_delayed_payment_base_key: None, - funding_redeemscript: None, - channel_value_satoshis: None, - their_cur_revocation_points: None, - - our_to_self_delay, - their_to_self_delay: None, - - old_secrets: [([0; 32], 1 << 48); 49], - remote_claimable_outpoints: HashMap::new(), - remote_commitment_txn_on_chain: HashMap::new(), - remote_hash_commitment_number: HashMap::new(), - - prev_local_signed_commitment_tx: None, - current_local_signed_commitment_tx: None, - current_remote_commitment_number: 1 << 48, - - payment_preimages: HashMap::new(), - destination_script, - to_remote_rescue: None, - - pending_claim_requests: HashMap::new(), - - claimable_outpoints: HashMap::new(), - - onchain_events_waiting_threshold_conf: HashMap::new(), - - last_block_hash: Default::default(), - secp_ctx: Secp256k1::new(), - logger, - } + pub(super) fn new(funding_key: &SecretKey, + revocation_base_key: &SecretKey, + delayed_payment_base_key: &SecretKey, + htlc_base_key: &SecretKey, + payment_base_key: &SecretKey, + shutdown_pubkey: &PublicKey, + our_to_self_delay: u16, + destination_script: Script, + logger: Arc) + -> ChannelMonitor { + ChannelMonitor { commitment_transaction_number_obscure_factor: 0, + + key_storage: Storage::Local { funding_key: funding_key.clone(), + revocation_base_key: revocation_base_key.clone(), + htlc_base_key: htlc_base_key.clone(), + delayed_payment_base_key: delayed_payment_base_key.clone(), + payment_base_key: payment_base_key.clone(), + shutdown_pubkey: shutdown_pubkey.clone(), + funding_info: None, + current_remote_commitment_txid: None, + prev_remote_commitment_txid: None }, + their_htlc_base_key: None, + their_delayed_payment_base_key: None, + funding_redeemscript: None, + channel_value_satoshis: None, + their_cur_revocation_points: None, + + our_to_self_delay, + their_to_self_delay: None, + + old_secrets: [([0; 32], 1 << 48); 49], + remote_claimable_outpoints: HashMap::new(), + remote_commitment_txn_on_chain: HashMap::new(), + remote_hash_commitment_number: HashMap::new(), + + prev_local_signed_commitment_tx: None, + current_local_signed_commitment_tx: None, + current_remote_commitment_number: 1 << 48, + + payment_preimages: HashMap::new(), + destination_script, + to_remote_rescue: None, + + pending_claim_requests: HashMap::new(), + + claimable_outpoints: HashMap::new(), + + onchain_events_waiting_threshold_conf: HashMap::new(), + + last_block_hash: Default::default(), + secp_ctx: Secp256k1::new(), + logger } } fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize { @@ -918,10 +887,8 @@ impl ChannelMonitor { // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill // events for now-revoked/fulfilled HTLCs. // TODO: We should probably consider whether we're really getting the next secret here. - if let Storage::Local { - ref mut prev_remote_commitment_txid, - .. - } = self.key_storage + if let Storage::Local { ref mut prev_remote_commitment_txid, + .. } = self.key_storage { if let Some(txid) = prev_remote_commitment_txid.take() { for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() { @@ -931,40 +898,39 @@ impl ChannelMonitor { } if !self.payment_preimages.is_empty() { - let local_signed_commitment_tx = self - .current_local_signed_commitment_tx - .as_ref() - .expect("Channel needs at least an initial commitment tx !"); + let local_signed_commitment_tx = self.current_local_signed_commitment_tx + .as_ref() + .expect("Channel needs at least an initial commitment tx !"); let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref(); let min_idx = self.get_min_seen_secret(); let remote_hash_commitment_number = &mut self.remote_hash_commitment_number; self.payment_preimages.retain(|&k, _| { - for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs { - if k == htlc.payment_hash { - return true; - } - } - if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx { - for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() { - if k == htlc.payment_hash { - return true; - } - } - } - let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) { - if *cn < min_idx { - return true; - } - true - } else { - false - }; - if contains { - remote_hash_commitment_number.remove(&k); - } - false - }); + for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs { + if k == htlc.payment_hash { + return true; + } + } + if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx { + for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() { + if k == htlc.payment_hash { + return true; + } + } + } + let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) { + if *cn < min_idx { + return true; + } + true + } else { + false + }; + if contains { + remote_hash_commitment_number.remove(&k); + } + false + }); } Ok(()) @@ -974,20 +940,21 @@ impl ChannelMonitor { /// The monitor watches for it to be broadcasted and then uses the HTLC information (and /// possibly future revocation/preimage information) to claim outputs where possible. /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers. - pub(super) fn provide_latest_remote_commitment_tx_info( - &mut self, - unsigned_commitment_tx: &Transaction, - htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, - commitment_number: u64, - their_revocation_point: PublicKey, - ) { + pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, + unsigned_commitment_tx: &Transaction, + htlc_outputs: Vec<( + HTLCOutputInCommitment, + Option>, + )>, + commitment_number: u64, + their_revocation_point: PublicKey) { // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction // so that a remote monitor doesn't learn anything unless there is a malicious close. // (only maybe, sadly we cant do the same for local info, as we need to be aware of // timeouts) for &(ref htlc, _) in &htlc_outputs { self.remote_hash_commitment_number - .insert(htlc.payment_hash, commitment_number); + .insert(htlc.payment_hash, commitment_number); } let new_txid = unsigned_commitment_tx.txid(); @@ -999,15 +966,13 @@ impl ChannelMonitor { htlc_outputs.len() ); log_trace!( - self, - "New potential remote commitment transaction: {}", - encode::serialize_hex(unsigned_commitment_tx) + self, + "New potential remote commitment transaction: {}", + encode::serialize_hex(unsigned_commitment_tx) ); - if let Storage::Local { - ref mut current_remote_commitment_txid, - ref mut prev_remote_commitment_txid, - .. - } = self.key_storage + if let Storage::Local { ref mut current_remote_commitment_txid, + ref mut prev_remote_commitment_txid, + .. } = self.key_storage { *prev_remote_commitment_txid = current_remote_commitment_txid.take(); *current_remote_commitment_txid = Some(new_txid); @@ -1038,18 +1003,16 @@ impl ChannelMonitor { pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) { match self.key_storage { - Storage::Local { - ref payment_base_key, .. - } => { - if let Ok(payment_key) = chan_utils::derive_public_key( - &self.secp_ctx, - &their_revocation_point, - &PublicKey::from_secret_key(&self.secp_ctx, &payment_base_key), - ) { - let to_remote_script = Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&Hash160::hash(&payment_key.serialize())[..]) - .into_script(); + Storage::Local { ref payment_base_key, .. } => { + if let Ok(payment_key) = + chan_utils::derive_public_key( + &self.secp_ctx, + &their_revocation_point, + &PublicKey::from_secret_key(&self.secp_ctx, &payment_base_key), + ) { + let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&Hash160::hash(&payment_key.serialize())[..]) + .into_script(); if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) { @@ -1066,33 +1029,34 @@ impl ChannelMonitor { /// is important that any clones of this channel monitor (including remote clones) by kept /// up-to-date as our local commitment transaction is updated. /// Panics if set_their_to_self_delay has never been called. - pub(super) fn provide_latest_local_commitment_tx_info( - &mut self, - commitment_tx: LocalCommitmentTransaction, - local_keys: chan_utils::TxCreationKeys, - feerate_per_kw: u64, - htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, - ) { + pub(super) fn provide_latest_local_commitment_tx_info(&mut self, + commitment_tx: LocalCommitmentTransaction, + local_keys: chan_utils::TxCreationKeys, + feerate_per_kw: u64, + htlc_outputs: Vec<( + HTLCOutputInCommitment, + Option, + Option, + )>) { assert!(self.their_to_self_delay.is_some()); self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take(); - self.current_local_signed_commitment_tx = Some(LocalSignedTx { - txid: commitment_tx.txid(), - tx: commitment_tx, - revocation_key: local_keys.revocation_key, - a_htlc_key: local_keys.a_htlc_key, - b_htlc_key: local_keys.b_htlc_key, - delayed_payment_key: local_keys.a_delayed_payment_key, - per_commitment_point: local_keys.per_commitment_point, - feerate_per_kw, - htlc_outputs, - }); + self.current_local_signed_commitment_tx = + Some(LocalSignedTx { txid: commitment_tx.txid(), + tx: commitment_tx, + revocation_key: local_keys.revocation_key, + a_htlc_key: local_keys.a_htlc_key, + b_htlc_key: local_keys.b_htlc_key, + delayed_payment_key: local_keys.a_delayed_payment_key, + per_commitment_point: local_keys.per_commitment_point, + feerate_per_kw, + htlc_outputs }); } /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all /// commitment_tx_infos which contain the payment hash have been revoked. pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) { self.payment_preimages - .insert(payment_hash.clone(), payment_preimage.clone()); + .insert(payment_hash.clone(), payment_preimage.clone()); } /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor. @@ -1102,16 +1066,12 @@ impl ChannelMonitor { match self.key_storage { Storage::Local { ref funding_info, .. } => { if funding_info.is_none() { - return Err(MonitorUpdateError( - "Try to combine a Local monitor without funding_info", - )); + return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); } let our_funding_info = funding_info; if let Storage::Local { ref funding_info, .. } = other.key_storage { if funding_info.is_none() { - return Err(MonitorUpdateError( - "Try to combine a Local monitor without funding_info", - )); + return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); } // We should be able to compare the entire funding_txo, but in fuzztarget it's trivially // easy to collide the funding_txo hash and have a different scriptPubKey. @@ -1119,18 +1079,14 @@ impl ChannelMonitor { return Err(MonitorUpdateError("Funding transaction outputs are not identical!")); } } else { - return Err(MonitorUpdateError( - "Try to combine a Local monitor with a Watchtower one !", - )); + return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !")); } }, Storage::Watchtower { .. } => { if let Storage::Watchtower { .. } = other.key_storage { unimplemented!(); } else { - return Err(MonitorUpdateError( - "Try to combine a Watchtower monitor with a Local one !", - )); + return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !")); } }, } @@ -1142,13 +1098,15 @@ impl ChannelMonitor { if let Some(ref local_tx) = self.current_local_signed_commitment_tx { if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx { let our_commitment_number = 0xffffffffffff - - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3 * 8) - | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) - ^ self.commitment_transaction_number_obscure_factor); - let other_commitment_number = 0xffffffffffff + - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 + & 0xffffff) << 3 * 8) + | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) + ^ self.commitment_transaction_number_obscure_factor); + let other_commitment_number = + 0xffffffffffff - ((((other_local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3 * 8) - | (other_local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) - ^ other.commitment_transaction_number_obscure_factor); + | (other_local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) + ^ other.commitment_transaction_number_obscure_factor); if our_commitment_number >= other_commitment_number { self.key_storage = other.key_storage; } @@ -1172,8 +1130,8 @@ impl ChannelMonitor { } self.current_remote_commitment_number = cmp::min( - self.current_remote_commitment_number, - other.current_remote_commitment_number, + self.current_remote_commitment_number, + other.current_remote_commitment_number, ); Ok(()) } @@ -1186,9 +1144,7 @@ impl ChannelMonitor { /// value as key to add_update_monitor. pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) { match self.key_storage { - Storage::Local { - ref mut funding_info, .. - } => { + Storage::Local { ref mut funding_info, .. } => { *funding_info = Some(new_funding_info); }, Storage::Watchtower { .. } => { @@ -1199,15 +1155,13 @@ impl ChannelMonitor { /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits - pub(super) fn set_basic_channel_info( - &mut self, - their_htlc_base_key: &PublicKey, - their_delayed_payment_base_key: &PublicKey, - their_to_self_delay: u16, - funding_redeemscript: Script, - channel_value_satoshis: u64, - commitment_transaction_number_obscure_factor: u64, - ) { + pub(super) fn set_basic_channel_info(&mut self, + their_htlc_base_key: &PublicKey, + their_delayed_payment_base_key: &PublicKey, + their_to_self_delay: u16, + funding_redeemscript: Script, + channel_value_satoshis: u64, + commitment_transaction_number_obscure_factor: u64) { self.their_htlc_base_key = Some(their_htlc_base_key.clone()); self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone()); self.their_to_self_delay = Some(their_to_self_delay); @@ -1219,9 +1173,7 @@ impl ChannelMonitor { pub(super) fn unset_funding_info(&mut self) { match self.key_storage { - Storage::Local { - ref mut funding_info, .. - } => { + Storage::Local { ref mut funding_info, .. } => { *funding_info = None; }, Storage::Watchtower { .. } => { @@ -1280,17 +1232,15 @@ impl ChannelMonitor { } match self.key_storage { - Storage::Local { - ref funding_key, - ref revocation_base_key, - ref htlc_base_key, - ref delayed_payment_base_key, - ref payment_base_key, - ref shutdown_pubkey, - ref funding_info, - ref current_remote_commitment_txid, - ref prev_remote_commitment_txid, - } => { + Storage::Local { ref funding_key, + ref revocation_base_key, + ref htlc_base_key, + ref delayed_payment_base_key, + ref payment_base_key, + ref shutdown_pubkey, + ref funding_info, + ref current_remote_commitment_txid, + ref prev_remote_commitment_txid, } => { writer.write_all(&[0; 1])?; writer.write_all(&funding_key[..])?; writer.write_all(&revocation_base_key[..])?; @@ -1365,9 +1315,7 @@ impl ChannelMonitor { } } - writer.write_all(&byte_utils::be64_to_array( - self.remote_commitment_txn_on_chain.len() as u64 - ))?; + writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?; for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() { writer.write_all(&txid[..])?; writer.write_all(&byte_utils::be48_to_array(commitment_number))?; @@ -1378,9 +1326,7 @@ impl ChannelMonitor { } if for_local_storage { - writer.write_all(&byte_utils::be64_to_array( - self.remote_hash_commitment_number.len() as u64 - ))?; + writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?; for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() { writer.write_all(&payment_hash.0[..])?; writer.write_all(&byte_utils::be48_to_array(*commitment_number))?; @@ -1461,9 +1407,7 @@ impl ChannelMonitor { claim_and_height.1.write(writer)?; } - writer.write_all(&byte_utils::be64_to_array( - self.onchain_events_waiting_threshold_conf.len() as u64, - ))?; + writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?; for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() { writer.write_all(&byte_utils::be32_to_array(**target))?; writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?; @@ -1478,10 +1422,8 @@ impl ChannelMonitor { htlc_update.0.write(writer)?; htlc_update.1.write(writer)?; }, - OnchainEvent::ContentiousOutpoint { - ref outpoint, - ref input_material, - } => { + OnchainEvent::ContentiousOutpoint { ref outpoint, + ref input_material, } => { writer.write_all(&[2; 1])?; outpoint.write(writer)?; input_material.write(writer)?; @@ -1540,9 +1482,9 @@ impl ChannelMonitor { pub(super) fn get_cur_local_commitment_number(&self) -> u64 { if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx { 0xffff_ffff_ffff - - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3 * 8) - | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) - ^ self.commitment_transaction_number_obscure_factor) + - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3 * 8) + | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) + ^ self.commitment_transaction_number_obscure_factor) } else { 0xffff_ffff_ffff } @@ -1558,12 +1500,8 @@ impl ChannelMonitor { &mut self, tx: &Transaction, height: u32, - fee_estimator: &FeeEstimator, - ) -> ( - Vec, - (Sha256dHash, Vec), - Vec, - ) { + fee_estimator: &FeeEstimator) + -> (Vec, (Sha256dHash, Vec), Vec) { // Most secp and related errors trying to create keys means we have no hope of constructing // a spend transaction...so we return no transactions to broadcast let mut txn_to_broadcast = Vec::new(); @@ -1583,56 +1521,49 @@ impl ChannelMonitor { } let commitment_number = 0xffffffffffff - - ((((tx.input[0].sequence as u64 & 0xffffff) << 3 * 8) | (tx.lock_time as u64 & 0xffffff)) - ^ self.commitment_transaction_number_obscure_factor); + - ((((tx.input[0].sequence as u64 & 0xffffff) << 3 * 8) + | (tx.lock_time as u64 & 0xffffff)) + ^ self.commitment_transaction_number_obscure_factor); if commitment_number >= self.get_min_seen_secret() { let secret = self.get_secret(commitment_number).unwrap(); let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret)); let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage { - Storage::Local { - ref revocation_base_key, - ref htlc_base_key, - ref payment_base_key, - .. - } => { + Storage::Local { ref revocation_base_key, + ref htlc_base_key, + ref payment_base_key, + .. } => { let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key); - ( - ignore_error!(chan_utils::derive_public_revocation_key( + (ignore_error!(chan_utils::derive_public_revocation_key( &self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key) )), - ignore_error!(chan_utils::derive_public_key( - &self.secp_ctx, - &per_commitment_point, - &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key) - )), - Some(ignore_error!(chan_utils::derive_private_key( - &self.secp_ctx, - &per_commitment_point, - &payment_base_key - ))), - ) + ignore_error!(chan_utils::derive_public_key( + &self.secp_ctx, + &per_commitment_point, + &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key) + )), + Some(ignore_error!(chan_utils::derive_private_key( + &self.secp_ctx, + &per_commitment_point, + &payment_base_key + )))) }, - Storage::Watchtower { - ref revocation_base_key, - ref htlc_base_key, - .. - } => { + Storage::Watchtower { ref revocation_base_key, + ref htlc_base_key, + .. } => { let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key); - ( - ignore_error!(chan_utils::derive_public_revocation_key( - &self.secp_ctx, - &per_commitment_point, - &revocation_base_key - )), - ignore_error!(chan_utils::derive_public_key( - &self.secp_ctx, - &per_commitment_point, - &htlc_base_key - )), - None, - ) + (ignore_error!(chan_utils::derive_public_revocation_key( + &self.secp_ctx, + &per_commitment_point, + &revocation_base_key + )), + ignore_error!(chan_utils::derive_public_key( + &self.secp_ctx, + &per_commitment_point, + &htlc_base_key + )), + None) }, }; let delayed_key = ignore_error!(chan_utils::derive_public_key( @@ -1658,12 +1589,9 @@ impl ChannelMonitor { // script_pubkey version. let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize()); - Some( - Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&payment_hash160[..]) - .into_script(), - ) + Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&payment_hash160[..]) + .into_script()) } else { None }; @@ -1675,15 +1603,11 @@ impl ChannelMonitor { for (idx, outp) in tx.output.iter().enumerate() { if outp.script_pubkey == revokeable_p2wsh { - inputs.push(TxIn { - previous_output: BitcoinOutPoint { - txid: commitment_txid, - vout: idx as u32, - }, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }); + inputs.push(TxIn { previous_output: BitcoinOutPoint { txid: commitment_txid, + vout: idx as u32, }, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new(), }); inputs_desc.push(InputDescriptors::RevokedOutput); inputs_info.push((None, outp.value, self.our_to_self_delay as u32)); total_value += outp.value; @@ -1735,34 +1659,30 @@ impl ChannelMonitor { for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() { if let Some(transaction_output_index) = htlc.transaction_output_index { let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys( - &htlc, - &a_htlc_key, - &b_htlc_key, - &revocation_pubkey, + &htlc, + &a_htlc_key, + &b_htlc_key, + &revocation_pubkey, ); if transaction_output_index as usize >= tx.output.len() - || tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 - || tx.output[transaction_output_index as usize].script_pubkey - != expected_script.to_v0_p2wsh() + || tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 + || tx.output[transaction_output_index as usize].script_pubkey + != expected_script.to_v0_p2wsh() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user } - let input = TxIn { - previous_output: BitcoinOutPoint { - txid: commitment_txid, - vout: transaction_output_index, - }, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }; + let input = TxIn { previous_output: BitcoinOutPoint { txid: commitment_txid, + vout: transaction_output_index }, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new() }; if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER { inputs.push(input); inputs_desc.push(if htlc.offered { - InputDescriptors::RevokedOfferedHTLC - } else { - InputDescriptors::RevokedReceivedHTLC - }); + InputDescriptors::RevokedOfferedHTLC + } else { + InputDescriptors::RevokedReceivedHTLC + }); inputs_info.push(( Some(idx), tx.output[transaction_output_index as usize].value, @@ -1770,49 +1690,45 @@ impl ChannelMonitor { )); total_value += tx.output[transaction_output_index as usize].value; } else { - let mut single_htlc_tx = Transaction { - version: 2, - lock_time: 0, - input: vec![input], - output: vec![TxOut { - script_pubkey: self.destination_script.clone(), - value: htlc.amount_msat / 1000, - }], - }; + let mut single_htlc_tx = + Transaction { version: 2, + lock_time: 0, + input: vec![input], + output: vec![TxOut { script_pubkey: self.destination_script + .clone(), + value: htlc.amount_msat / 1000, }] }; let predicted_weight = single_htlc_tx.get_weight() - + Self::get_witnesses_weight(&[if htlc.offered { - InputDescriptors::RevokedOfferedHTLC - } else { - InputDescriptors::RevokedReceivedHTLC - }]); + + Self::get_witnesses_weight(&[if htlc.offered { + InputDescriptors::RevokedOfferedHTLC + } else { + InputDescriptors::RevokedReceivedHTLC + }]); let height_timer = Self::get_height_timer(height, htlc.cltv_expiry); let mut used_feerate; if subtract_high_prio_fee!( - self, - fee_estimator, - single_htlc_tx.output[0].value, - predicted_weight, - used_feerate + self, + fee_estimator, + single_htlc_tx.output[0].value, + predicted_weight, + used_feerate ) { let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx); let (redeemscript, revocation_key) = sign_input!( - sighash_parts, - single_htlc_tx.input[0], - Some(idx), - htlc.amount_msat / 1000 + sighash_parts, + single_htlc_tx.input[0], + Some(idx), + htlc.amount_msat / 1000 ); assert!(predicted_weight >= single_htlc_tx.get_weight()); log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", single_htlc_tx.input[0].previous_output.txid, single_htlc_tx.input[0].previous_output.vout, height_timer); let mut per_input_material = HashMap::with_capacity(1); per_input_material.insert( - single_htlc_tx.input[0].previous_output, - InputMaterial::Revoked { - script: redeemscript, - pubkey: Some(revocation_pubkey), - key: revocation_key, - is_htlc: true, - amount: htlc.amount_msat / 1000, - }, + single_htlc_tx.input[0].previous_output, + InputMaterial::Revoked { script: redeemscript, + pubkey: Some(revocation_pubkey), + key: revocation_key, + is_htlc: true, + amount: htlc.amount_msat / 1000, }, ); match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) { hash_map::Entry::Occupied(_) => {}, @@ -1823,12 +1739,10 @@ impl ChannelMonitor { match self.pending_claim_requests.entry(single_htlc_tx.txid()) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { - entry.insert(ClaimTxBumpMaterial { - height_timer, - feerate_previous: used_feerate, - soonest_timelock: htlc.cltv_expiry, - per_input_material, - }); + entry.insert(ClaimTxBumpMaterial { height_timer, + feerate_previous: used_feerate, + soonest_timelock: htlc.cltv_expiry, + per_input_material, }); }, } txn_to_broadcast.push(single_htlc_tx); @@ -1844,11 +1758,11 @@ impl ChannelMonitor { log_trace!(self, "Got broadcast of revoked remote commitment transaction, generating general spend tx with {} inputs and {} other txn to broadcast", inputs.len(), txn_to_broadcast.len()); watch_outputs.append(&mut tx.output.clone()); self.remote_commitment_txn_on_chain.insert( - commitment_txid, - ( - commitment_number, - tx.output.iter().map(|output| output.script_pubkey.clone()).collect(), - ), + commitment_txid, + ( + commitment_number, + tx.output.iter().map(|output| output.script_pubkey.clone()).collect(), + ), ); macro_rules! check_htlc_fails { @@ -1875,11 +1789,9 @@ impl ChannelMonitor { } }; } - if let Storage::Local { - ref current_remote_commitment_txid, - ref prev_remote_commitment_txid, - .. - } = self.key_storage + if let Storage::Local { ref current_remote_commitment_txid, + ref prev_remote_commitment_txid, + .. } = self.key_storage { if let &Some(ref txid) = current_remote_commitment_txid { check_htlc_fails!(txid, "current"); @@ -1894,26 +1806,22 @@ impl ChannelMonitor { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx - let outputs = vec![TxOut { - script_pubkey: self.destination_script.clone(), - value: total_value, - }]; - let mut spend_tx = Transaction { - version: 2, - lock_time: 0, - input: inputs, - output: outputs, - }; + let outputs = vec![TxOut { script_pubkey: self.destination_script.clone(), + value: total_value }]; + let mut spend_tx = Transaction { version: 2, + lock_time: 0, + input: inputs, + output: outputs }; let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]); let mut used_feerate; if !subtract_high_prio_fee!( - self, - fee_estimator, - spend_tx.output[0].value, - predicted_weight, - used_feerate + self, + fee_estimator, + spend_tx.output[0].value, + predicted_weight, + used_feerate ) { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } @@ -1933,18 +1841,20 @@ impl ChannelMonitor { let (redeemscript, revocation_key) = sign_input!(sighash_parts, input, info.0, info.1); log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer); per_input_material.insert( - input.previous_output, - InputMaterial::Revoked { - script: redeemscript, - pubkey: if info.0.is_some() { - Some(revocation_pubkey) - } else { - None - }, - key: revocation_key, - is_htlc: if info.0.is_some() { true } else { false }, - amount: info.1, - }, + input.previous_output, + InputMaterial::Revoked { script: redeemscript, + pubkey: if info.0.is_some() { + Some(revocation_pubkey) + } else { + None + }, + key: revocation_key, + is_htlc: if info.0.is_some() { + true + } else { + false + }, + amount: info.1, }, ); match self.claimable_outpoints.entry(input.previous_output) { hash_map::Entry::Occupied(_) => {}, @@ -1956,24 +1866,20 @@ impl ChannelMonitor { match self.pending_claim_requests.entry(spend_txid) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { - entry.insert(ClaimTxBumpMaterial { - height_timer, - feerate_previous: used_feerate, - soonest_timelock, - per_input_material, - }); + entry.insert(ClaimTxBumpMaterial { height_timer, + feerate_previous: used_feerate, + soonest_timelock, + per_input_material }); }, } assert!(predicted_weight >= spend_tx.get_weight()); - spendable_outputs.push(SpendableOutputDescriptor::StaticOutput { - outpoint: BitcoinOutPoint { - txid: spend_tx.txid(), - vout: 0, - }, - output: spend_tx.output[0].clone(), - }); + spendable_outputs.push(SpendableOutputDescriptor::StaticOutput { outpoint: + BitcoinOutPoint { txid: + spend_tx.txid(), + vout: 0 }, + output: spend_tx.output[0].clone() }); txn_to_broadcast.push(spend_tx); } else if let Some(per_commitment_data) = per_commitment_option { // While this isn't useful yet, there is a potential race where if a counterparty @@ -1985,17 +1891,17 @@ impl ChannelMonitor { // insert it here. watch_outputs.append(&mut tx.output.clone()); self.remote_commitment_txn_on_chain.insert( - commitment_txid, - ( - commitment_number, - tx.output.iter().map(|output| output.script_pubkey.clone()).collect(), - ), + commitment_txid, + ( + commitment_number, + tx.output.iter().map(|output| output.script_pubkey.clone()).collect(), + ), ); log_trace!( - self, - "Got broadcast of non-revoked remote commitment transaction {}", - commitment_txid + self, + "Got broadcast of non-revoked remote commitment transaction {}", + commitment_txid ); macro_rules! check_htlc_fails { @@ -2040,11 +1946,9 @@ impl ChannelMonitor { } }; } - if let Storage::Local { - ref current_remote_commitment_txid, - ref prev_remote_commitment_txid, - .. - } = self.key_storage + if let Storage::Local { ref current_remote_commitment_txid, + ref prev_remote_commitment_txid, + .. } = self.key_storage { if let &Some(ref txid) = current_remote_commitment_txid { check_htlc_fails!(txid, "current", 'current_loop); @@ -2068,38 +1972,30 @@ impl ChannelMonitor { }; if let Some(revocation_point) = revocation_point_option { let (revocation_pubkey, b_htlc_key) = match self.key_storage { - Storage::Local { - ref revocation_base_key, - ref htlc_base_key, - .. - } => ( - ignore_error!(chan_utils::derive_public_revocation_key( + Storage::Local { ref revocation_base_key, + ref htlc_base_key, + .. } => (ignore_error!(chan_utils::derive_public_revocation_key( &self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key) )), - ignore_error!(chan_utils::derive_public_key( + ignore_error!(chan_utils::derive_public_key( &self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key) - )), - ), - Storage::Watchtower { - ref revocation_base_key, - ref htlc_base_key, - .. - } => ( - ignore_error!(chan_utils::derive_public_revocation_key( - &self.secp_ctx, - revocation_point, - &revocation_base_key - )), - ignore_error!(chan_utils::derive_public_key( - &self.secp_ctx, - revocation_point, - &htlc_base_key - )), - ), + ))), + Storage::Watchtower { ref revocation_base_key, + ref htlc_base_key, + .. } => (ignore_error!(chan_utils::derive_public_revocation_key( + &self.secp_ctx, + revocation_point, + &revocation_base_key + )), + ignore_error!(chan_utils::derive_public_key( + &self.secp_ctx, + revocation_point, + &htlc_base_key + ))), }; let a_htlc_key = match self.their_htlc_base_key { None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs), @@ -2113,13 +2009,11 @@ impl ChannelMonitor { for (idx, outp) in tx.output.iter().enumerate() { if outp.script_pubkey.is_v0_p2wpkh() { match self.key_storage { - Storage::Local { - ref payment_base_key, .. - } => { + Storage::Local { ref payment_base_key, .. } => { if let Ok(local_key) = chan_utils::derive_private_key( - &self.secp_ctx, - &revocation_point, - &payment_base_key, + &self.secp_ctx, + &revocation_point, + &payment_base_key, ) { spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH { outpoint: BitcoinOutPoint { @@ -2166,37 +2060,35 @@ impl ChannelMonitor { for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() { if let Some(transaction_output_index) = htlc.transaction_output_index { - let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys( - &htlc, - &a_htlc_key, - &b_htlc_key, - &revocation_pubkey, - ); + let expected_script = + chan_utils::get_htlc_redeemscript_with_explicit_keys( + &htlc, + &a_htlc_key, + &b_htlc_key, + &revocation_pubkey, + ); if transaction_output_index as usize >= tx.output.len() - || tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 - || tx.output[transaction_output_index as usize].script_pubkey - != expected_script.to_v0_p2wsh() + || tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 + || tx.output[transaction_output_index as usize].script_pubkey + != expected_script.to_v0_p2wsh() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user } if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) { if htlc.offered { - let input = TxIn { - previous_output: BitcoinOutPoint { - txid: commitment_txid, - vout: transaction_output_index, - }, - script_sig: Script::new(), - sequence: idx as u32, // reset to 0xfffffffd in sign_input - witness: Vec::new(), - }; + let input = TxIn { previous_output: BitcoinOutPoint { txid: commitment_txid, + vout: + transaction_output_index }, + script_sig: Script::new(), + sequence: idx as u32, // reset to 0xfffffffd in sign_input + witness: Vec::new() }; if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER { inputs.push(input); inputs_desc.push(if htlc.offered { - InputDescriptors::OfferedHTLC - } else { - InputDescriptors::ReceivedHTLC - }); + InputDescriptors::OfferedHTLC + } else { + InputDescriptors::ReceivedHTLC + }); inputs_info.push(( payment_preimage, tx.output[transaction_output_index as usize].value, @@ -2204,36 +2096,34 @@ impl ChannelMonitor { )); total_value += tx.output[transaction_output_index as usize].value; } else { - let mut single_htlc_tx = Transaction { - version: 2, - lock_time: 0, - input: vec![input], - output: vec![TxOut { + let mut single_htlc_tx = Transaction { version: 2, + lock_time: 0, + input: vec![input], + output: vec![TxOut { script_pubkey: self.destination_script.clone(), value: htlc.amount_msat / 1000, - }], - }; + }] }; let predicted_weight = single_htlc_tx.get_weight() - + Self::get_witnesses_weight(&[if htlc.offered { - InputDescriptors::OfferedHTLC - } else { - InputDescriptors::ReceivedHTLC - }]); + + Self::get_witnesses_weight(&[if htlc.offered { + InputDescriptors::OfferedHTLC + } else { + InputDescriptors::ReceivedHTLC + }]); let height_timer = Self::get_height_timer(height, htlc.cltv_expiry); let mut used_feerate; if subtract_high_prio_fee!( - self, - fee_estimator, - single_htlc_tx.output[0].value, - predicted_weight, - used_feerate + self, + fee_estimator, + single_htlc_tx.output[0].value, + predicted_weight, + used_feerate ) { let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx); let (redeemscript, htlc_key) = sign_input!( - sighash_parts, - single_htlc_tx.input[0], - htlc.amount_msat / 1000, - payment_preimage.0.to_vec() + sighash_parts, + single_htlc_tx.input[0], + htlc.amount_msat / 1000, + payment_preimage.0.to_vec() ); assert!(predicted_weight >= single_htlc_tx.get_weight()); spendable_outputs.push(SpendableOutputDescriptor::StaticOutput { @@ -2255,9 +2145,8 @@ impl ChannelMonitor { locktime: 0, }, ); - match self - .claimable_outpoints - .entry(single_htlc_tx.input[0].previous_output) + match self.claimable_outpoints + .entry(single_htlc_tx.input[0].previous_output) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { @@ -2267,12 +2156,12 @@ impl ChannelMonitor { match self.pending_claim_requests.entry(single_htlc_tx.txid()) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { - entry.insert(ClaimTxBumpMaterial { - height_timer, - feerate_previous: used_feerate, - soonest_timelock: htlc.cltv_expiry, - per_input_material, - }); + entry.insert(ClaimTxBumpMaterial { height_timer, + feerate_previous: + used_feerate, + soonest_timelock: + htlc.cltv_expiry, + per_input_material, }); }, } txn_to_broadcast.push(single_htlc_tx); @@ -2283,55 +2172,50 @@ impl ChannelMonitor { if !htlc.offered { // TODO: If the HTLC has already expired, potentially merge it with the // rest of the claim transaction, as above. - let input = TxIn { - previous_output: BitcoinOutPoint { - txid: commitment_txid, - vout: transaction_output_index, - }, - script_sig: Script::new(), - sequence: idx as u32, - witness: Vec::new(), - }; - let mut timeout_tx = Transaction { - version: 2, - lock_time: htlc.cltv_expiry, - input: vec![input], - output: vec![TxOut { - script_pubkey: self.destination_script.clone(), - value: htlc.amount_msat / 1000, - }], - }; + let input = TxIn { previous_output: BitcoinOutPoint { txid: commitment_txid, + vout: + transaction_output_index }, + script_sig: Script::new(), + sequence: idx as u32, + witness: Vec::new() }; + let mut timeout_tx = + Transaction { version: 2, + lock_time: htlc.cltv_expiry, + input: vec![input], + output: vec![TxOut { script_pubkey: self.destination_script + .clone(), + value: htlc.amount_msat / 1000, }] }; let predicted_weight = timeout_tx.get_weight() - + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]); + + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]); let height_timer = Self::get_height_timer(height, htlc.cltv_expiry); let mut used_feerate; if subtract_high_prio_fee!( - self, - fee_estimator, - timeout_tx.output[0].value, - predicted_weight, - used_feerate + self, + fee_estimator, + timeout_tx.output[0].value, + predicted_weight, + used_feerate ) { let sighash_parts = bip143::SighashComponents::new(&timeout_tx); let (redeemscript, htlc_key) = sign_input!( - sighash_parts, - timeout_tx.input[0], - htlc.amount_msat / 1000, - vec![0] + sighash_parts, + timeout_tx.input[0], + htlc.amount_msat / 1000, + vec![0] ); assert!(predicted_weight >= timeout_tx.get_weight()); //TODO: track SpendableOutputDescriptor log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", timeout_tx.input[0].previous_output.txid, timeout_tx.input[0].previous_output.vout, height_timer); let mut per_input_material = HashMap::with_capacity(1); per_input_material.insert( - timeout_tx.input[0].previous_output, - InputMaterial::RemoteHTLC { - script: redeemscript, - key: htlc_key, - preimage: None, - amount: htlc.amount_msat / 1000, - locktime: htlc.cltv_expiry, - }, + timeout_tx.input[0].previous_output, + InputMaterial::RemoteHTLC { script: redeemscript, + key: htlc_key, + preimage: None, + amount: htlc.amount_msat + / 1000, + locktime: + htlc.cltv_expiry, }, ); match self.claimable_outpoints.entry(timeout_tx.input[0].previous_output) { hash_map::Entry::Occupied(_) => {}, @@ -2342,12 +2226,10 @@ impl ChannelMonitor { match self.pending_claim_requests.entry(timeout_tx.txid()) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { - entry.insert(ClaimTxBumpMaterial { - height_timer, - feerate_previous: used_feerate, - soonest_timelock: htlc.cltv_expiry, - per_input_material, - }); + entry.insert(ClaimTxBumpMaterial { height_timer, + feerate_previous: used_feerate, + soonest_timelock: htlc.cltv_expiry, + per_input_material, }); }, } } @@ -2360,26 +2242,22 @@ impl ChannelMonitor { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx - let outputs = vec![TxOut { - script_pubkey: self.destination_script.clone(), - value: total_value, - }]; - let mut spend_tx = Transaction { - version: 2, - lock_time: 0, - input: inputs, - output: outputs, - }; + let outputs = vec![TxOut { script_pubkey: self.destination_script.clone(), + value: total_value, }]; + let mut spend_tx = Transaction { version: 2, + lock_time: 0, + input: inputs, + output: outputs }; let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]); let mut used_feerate; if !subtract_high_prio_fee!( - self, - fee_estimator, - spend_tx.output[0].value, - predicted_weight, - used_feerate + self, + fee_estimator, + spend_tx.output[0].value, + predicted_weight, + used_feerate ) { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } @@ -2399,14 +2277,12 @@ impl ChannelMonitor { let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec()); log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer); per_input_material.insert( - input.previous_output, - InputMaterial::RemoteHTLC { - script: redeemscript, - key: htlc_key, - preimage: Some(*(info.0)), - amount: info.1, - locktime: 0, - }, + input.previous_output, + InputMaterial::RemoteHTLC { script: redeemscript, + key: htlc_key, + preimage: Some(*(info.0)), + amount: info.1, + locktime: 0, }, ); match self.claimable_outpoints.entry(input.previous_output) { hash_map::Entry::Occupied(_) => {}, @@ -2418,12 +2294,10 @@ impl ChannelMonitor { match self.pending_claim_requests.entry(spend_txid) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { - entry.insert(ClaimTxBumpMaterial { - height_timer, - feerate_previous: used_feerate, - soonest_timelock, - per_input_material, - }); + entry.insert(ClaimTxBumpMaterial { height_timer, + feerate_previous: used_feerate, + soonest_timelock, + per_input_material }); }, } assert!(predicted_weight >= spend_tx.get_weight()); @@ -2456,13 +2330,12 @@ impl ChannelMonitor { } /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key - fn check_spend_remote_htlc( - &mut self, - tx: &Transaction, - commitment_number: u64, - height: u32, - fee_estimator: &FeeEstimator, - ) -> (Option, Option) { + fn check_spend_remote_htlc(&mut self, + tx: &Transaction, + commitment_number: u64, + height: u32, + fee_estimator: &FeeEstimator) + -> (Option, Option) { //TODO: send back new outputs to guarantee pending_claim_request consistency if tx.input.len() != 1 || tx.output.len() != 1 { return (None, None); @@ -2485,18 +2358,14 @@ impl ChannelMonitor { let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret)); let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key); let revocation_pubkey = match self.key_storage { - Storage::Local { - ref revocation_base_key, - .. - } => ignore_error!(chan_utils::derive_public_revocation_key( + Storage::Local { ref revocation_base_key, + .. } => ignore_error!(chan_utils::derive_public_revocation_key( &self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key) )), - Storage::Watchtower { - ref revocation_base_key, - .. - } => ignore_error!(chan_utils::derive_public_revocation_key( + Storage::Watchtower { ref revocation_base_key, + .. } => ignore_error!(chan_utils::derive_public_revocation_key( &self.secp_ctx, &per_commitment_point, &revocation_base_key @@ -2520,39 +2389,31 @@ impl ChannelMonitor { if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout - inputs.push(TxIn { - previous_output: BitcoinOutPoint { - txid: htlc_txid, - vout: 0, - }, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }); + inputs.push(TxIn { previous_output: BitcoinOutPoint { txid: htlc_txid, + vout: 0, }, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new(), }); amount = tx.output[0].value; } if !inputs.is_empty() { - let outputs = vec![TxOut { - script_pubkey: self.destination_script.clone(), - value: amount, - }]; - - let mut spend_tx = Transaction { - version: 2, - lock_time: 0, - input: inputs, - output: outputs, - }; + let outputs = vec![TxOut { script_pubkey: self.destination_script.clone(), + value: amount }]; + + let mut spend_tx = Transaction { version: 2, + lock_time: 0, + input: inputs, + output: outputs }; let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]); let mut used_feerate; if !subtract_high_prio_fee!( - self, - fee_estimator, - spend_tx.output[0].value, - predicted_weight, - used_feerate + self, + fee_estimator, + spend_tx.output[0].value, + predicted_weight, + used_feerate ) { return (None, None); } @@ -2560,10 +2421,8 @@ impl ChannelMonitor { let sighash_parts = bip143::SighashComponents::new(&spend_tx); let (sig, revocation_key) = match self.key_storage { - Storage::Local { - ref revocation_base_key, - .. - } => { + Storage::Local { ref revocation_base_key, + .. } => { let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]); let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key( @@ -2583,23 +2442,19 @@ impl ChannelMonitor { spend_tx.input[0].witness.push(redeemscript.clone().into_bytes()); assert!(predicted_weight >= spend_tx.get_weight()); - let outpoint = BitcoinOutPoint { - txid: spend_tx.txid(), - vout: 0, - }; + let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), + vout: 0 }; let output = spend_tx.output[0].clone(); let height_timer = Self::get_height_timer(height, self.their_to_self_delay.unwrap() as u32); // We can safely unwrap given we are past channel opening log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", spend_tx.input[0].previous_output.txid, spend_tx.input[0].previous_output.vout, height_timer); let mut per_input_material = HashMap::with_capacity(1); per_input_material.insert( - spend_tx.input[0].previous_output, - InputMaterial::Revoked { - script: redeemscript, - pubkey: None, - key: revocation_key, - is_htlc: false, - amount: tx.output[0].value, - }, + spend_tx.input[0].previous_output, + InputMaterial::Revoked { script: redeemscript, + pubkey: None, + key: revocation_key, + is_htlc: false, + amount: tx.output[0].value, }, ); match self.claimable_outpoints.entry(spend_tx.input[0].previous_output) { hash_map::Entry::Occupied(_) => {}, @@ -2610,18 +2465,13 @@ impl ChannelMonitor { match self.pending_claim_requests.entry(spend_tx.txid()) { hash_map::Entry::Occupied(_) => {}, hash_map::Entry::Vacant(entry) => { - entry.insert(ClaimTxBumpMaterial { - height_timer, - feerate_previous: used_feerate, - soonest_timelock: height + self.our_to_self_delay as u32, - per_input_material, - }); + entry.insert(ClaimTxBumpMaterial { height_timer, + feerate_previous: used_feerate, + soonest_timelock: height + self.our_to_self_delay as u32, + per_input_material }); }, } - ( - Some(spend_tx), - Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }), - ) + (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output })) } else { (None, None) } @@ -2631,13 +2481,8 @@ impl ChannelMonitor { &self, local_tx: &LocalSignedTx, delayed_payment_base_key: &SecretKey, - height: u32, - ) -> ( - Vec, - Vec, - Vec, - Vec<(Sha256dHash, ClaimTxBumpMaterial)>, - ) { + height: u32) + -> (Vec, Vec, Vec, Vec<(Sha256dHash, ClaimTxBumpMaterial)>) { let mut res = Vec::with_capacity(local_tx.htlc_outputs.len()); let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len()); let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len()); @@ -2652,9 +2497,9 @@ impl ChannelMonitor { } let redeemscript = chan_utils::get_revokeable_redeemscript( - &local_tx.revocation_key, - self.their_to_self_delay.unwrap(), - &local_tx.delayed_payment_key, + &local_tx.revocation_key, + self.their_to_self_delay.unwrap(), + &local_tx.delayed_payment_key, ); let revokeable_p2wsh = redeemscript.to_v0_p2wsh(); for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() { @@ -2670,55 +2515,53 @@ impl ChannelMonitor { if let &Some(ref their_sig) = sigs { if htlc.offered { log_trace!( - self, - "Broadcasting HTLC-Timeout transaction against local commitment transactions" + self, + "Broadcasting HTLC-Timeout transaction against local commitment transactions" ); let mut htlc_timeout_tx = chan_utils::build_htlc_transaction( - &local_tx.txid, - local_tx.feerate_per_kw, - self.their_to_self_delay.unwrap(), - htlc, - &local_tx.delayed_payment_key, - &local_tx.revocation_key, + &local_tx.txid, + local_tx.feerate_per_kw, + self.their_to_self_delay + .unwrap(), + htlc, + &local_tx.delayed_payment_key, + &local_tx.revocation_key, ); - let (our_sig, htlc_script) = match chan_utils::sign_htlc_transaction( - &mut htlc_timeout_tx, - their_sig, - &None, - htlc, - &local_tx.a_htlc_key, - &local_tx.b_htlc_key, - &local_tx.revocation_key, - &local_tx.per_commitment_point, - htlc_base_key, - &self.secp_ctx, - ) { - Ok(res) => res, - Err(_) => continue, - }; + let (our_sig, htlc_script) = + match chan_utils::sign_htlc_transaction( + &mut htlc_timeout_tx, + their_sig, + &None, + htlc, + &local_tx.a_htlc_key, + &local_tx.b_htlc_key, + &local_tx.revocation_key, + &local_tx.per_commitment_point, + htlc_base_key, + &self.secp_ctx, + ) { + Ok(res) => res, + Err(_) => continue, + }; add_dynamic_output!(htlc_timeout_tx, 0); let height_timer = Self::get_height_timer(height, htlc.cltv_expiry); let mut per_input_material = HashMap::with_capacity(1); per_input_material.insert( - htlc_timeout_tx.input[0].previous_output, - InputMaterial::LocalHTLC { - script: htlc_script, - sigs: (*their_sig, our_sig), - preimage: None, - amount: htlc.amount_msat / 1000, - }, + htlc_timeout_tx.input[0].previous_output, + InputMaterial::LocalHTLC { script: htlc_script, + sigs: (*their_sig, our_sig), + preimage: None, + amount: htlc.amount_msat / 1000, }, ); //TODO: with option_simplified_commitment track outpoint too log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid, height_timer); pending_claims.push(( htlc_timeout_tx.txid(), - ClaimTxBumpMaterial { - height_timer, - feerate_previous: 0, - soonest_timelock: htlc.cltv_expiry, - per_input_material, - }, + ClaimTxBumpMaterial { height_timer, + feerate_previous: 0, + soonest_timelock: htlc.cltv_expiry, + per_input_material, }, )); res.push(htlc_timeout_tx); } else { @@ -2727,58 +2570,61 @@ impl ChannelMonitor { self, "Broadcasting HTLC-Success transaction against local commitment transactions" ); - let mut htlc_success_tx = chan_utils::build_htlc_transaction( - &local_tx.txid, - local_tx.feerate_per_kw, - self.their_to_self_delay.unwrap(), - htlc, - &local_tx.delayed_payment_key, - &local_tx.revocation_key, - ); - let (our_sig, htlc_script) = match chan_utils::sign_htlc_transaction( - &mut htlc_success_tx, - their_sig, - &Some(*payment_preimage), - htlc, - &local_tx.a_htlc_key, - &local_tx.b_htlc_key, - &local_tx.revocation_key, - &local_tx.per_commitment_point, - htlc_base_key, - &self.secp_ctx, - ) { - Ok(res) => res, - Err(_) => continue, - }; + let mut htlc_success_tx = + chan_utils::build_htlc_transaction( + &local_tx.txid, + local_tx.feerate_per_kw, + self.their_to_self_delay.unwrap(), + htlc, + &local_tx.delayed_payment_key, + &local_tx.revocation_key, + ); + let (our_sig, htlc_script) = + match chan_utils::sign_htlc_transaction( + &mut htlc_success_tx, + their_sig, + &Some(*payment_preimage), + htlc, + &local_tx.a_htlc_key, + &local_tx.b_htlc_key, + &local_tx.revocation_key, + &local_tx.per_commitment_point, + htlc_base_key, + &self.secp_ctx, + ) { + Ok(res) => res, + Err(_) => continue, + }; add_dynamic_output!(htlc_success_tx, 0); let height_timer = Self::get_height_timer(height, htlc.cltv_expiry); let mut per_input_material = HashMap::with_capacity(1); per_input_material.insert( - htlc_success_tx.input[0].previous_output, - InputMaterial::LocalHTLC { - script: htlc_script, - sigs: (*their_sig, our_sig), - preimage: Some(*payment_preimage), - amount: htlc.amount_msat / 1000, - }, + htlc_success_tx.input[0].previous_output, + InputMaterial::LocalHTLC { script: htlc_script, + sigs: (*their_sig, our_sig), + preimage: Some( + *payment_preimage, + ), + amount: htlc.amount_msat + / 1000, }, ); //TODO: with option_simplified_commitment track outpoint too log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid, height_timer); pending_claims.push(( htlc_success_tx.txid(), - ClaimTxBumpMaterial { - height_timer, - feerate_previous: 0, - soonest_timelock: htlc.cltv_expiry, - per_input_material, - }, + ClaimTxBumpMaterial { height_timer, + feerate_previous: 0, + soonest_timelock: htlc.cltv_expiry, + per_input_material, }, )); res.push(htlc_success_tx); } } watch_outputs.push( - local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone(), + local_tx.tx.without_valid_witness().output + [transaction_output_index as usize] + .clone(), ); } else { panic!("Should have sigs for non-dust local tx outputs!") @@ -2796,12 +2642,8 @@ impl ChannelMonitor { fn check_spend_local_transaction( &mut self, tx: &Transaction, - height: u32, - ) -> ( - Vec, - Vec, - (Sha256dHash, Vec), - ) { + height: u32) + -> (Vec, Vec, (Sha256dHash, Vec)) { let commitment_txid = tx.txid(); let mut local_txn = Vec::new(); let mut spendable_outputs = Vec::new(); @@ -2850,10 +2692,10 @@ impl ChannelMonitor { match self.key_storage { Storage::Local { ref funding_key, .. } => { local_tx.tx.add_local_sig( - funding_key, - self.funding_redeemscript.as_ref().unwrap(), - self.channel_value_satoshis.unwrap(), - &self.secp_ctx, + funding_key, + self.funding_redeemscript.as_ref().unwrap(), + self.channel_value_satoshis.unwrap(), + &self.secp_ctx, ); }, _ => {}, @@ -2864,15 +2706,13 @@ impl ChannelMonitor { if local_tx.txid == commitment_txid { is_local_tx = true; log_trace!( - self, - "Got latest local commitment tx broadcast, searching for available HTLCs to claim" + self, + "Got latest local commitment tx broadcast, searching for available HTLCs to claim" ); assert!(local_tx.tx.has_local_sig()); match self.key_storage { - Storage::Local { - ref delayed_payment_base_key, - .. - } => { + Storage::Local { ref delayed_payment_base_key, + .. } => { append_onchain_update!(self.broadcast_by_local_state( local_tx, delayed_payment_base_key, @@ -2888,10 +2728,10 @@ impl ChannelMonitor { match self.key_storage { Storage::Local { ref funding_key, .. } => { local_tx.tx.add_local_sig( - funding_key, - self.funding_redeemscript.as_ref().unwrap(), - self.channel_value_satoshis.unwrap(), - &self.secp_ctx, + funding_key, + self.funding_redeemscript.as_ref().unwrap(), + self.channel_value_satoshis.unwrap(), + &self.secp_ctx, ); }, _ => {}, @@ -2902,15 +2742,13 @@ impl ChannelMonitor { if local_tx.txid == commitment_txid { is_local_tx = true; log_trace!( - self, - "Got previous local commitment tx broadcast, searching for available HTLCs to claim" + self, + "Got previous local commitment tx broadcast, searching for available HTLCs to claim" ); assert!(local_tx.tx.has_local_sig()); match self.key_storage { - Storage::Local { - ref delayed_payment_base_key, - .. - } => { + Storage::Local { ref delayed_payment_base_key, + .. } => { append_onchain_update!(self.broadcast_by_local_state( local_tx, delayed_payment_base_key, @@ -2949,27 +2787,23 @@ impl ChannelMonitor { /// Generate a spendable output event when closing_transaction get registered onchain. fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option { if tx.input[0].sequence == 0xFFFFFFFF - && !tx.input[0].witness.is_empty() - && tx.input[0].witness.last().unwrap().len() == 71 + && !tx.input[0].witness.is_empty() + && tx.input[0].witness.last().unwrap().len() == 71 { match self.key_storage { - Storage::Local { - ref shutdown_pubkey, .. - } => { + Storage::Local { ref shutdown_pubkey, .. } => { let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize()); - let shutdown_script = Builder::new() - .push_opcode(opcodes::all::OP_PUSHBYTES_0) - .push_slice(&our_channel_close_key_hash[..]) - .into_script(); + let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(&our_channel_close_key_hash[..]) + .into_script(); for (idx, output) in tx.output.iter().enumerate() { if shutdown_script == output.script_pubkey { - return Some(SpendableOutputDescriptor::StaticOutput { - outpoint: BitcoinOutPoint { - txid: tx.txid(), - vout: idx as u32, - }, - output: output.clone(), - }); + return Some(SpendableOutputDescriptor::StaticOutput { outpoint: + BitcoinOutPoint { txid: + tx.txid(), + vout: idx + as u32 }, + output: output.clone() }); } } }, @@ -2997,10 +2831,10 @@ impl ChannelMonitor { match self.key_storage { Storage::Local { ref funding_key, .. } => { local_tx.tx.add_local_sig( - funding_key, - self.funding_redeemscript.as_ref().unwrap(), - self.channel_value_satoshis.unwrap(), - &self.secp_ctx, + funding_key, + self.funding_redeemscript.as_ref().unwrap(), + self.channel_value_satoshis.unwrap(), + &self.secp_ctx, ); }, _ => {}, @@ -3009,10 +2843,8 @@ impl ChannelMonitor { if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx { let mut res = vec![local_tx.tx.with_valid_witness().clone()]; match self.key_storage { - Storage::Local { - ref delayed_payment_base_key, - .. - } => { + Storage::Local { ref delayed_payment_base_key, + .. } => { res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0); // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do. // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation. @@ -3031,18 +2863,16 @@ impl ChannelMonitor { height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, - fee_estimator: &FeeEstimator, - ) -> ( - Vec<(Sha256dHash, Vec)>, - Vec, - Vec<(HTLCSource, Option, PaymentHash)>, - ) { + fee_estimator: &FeeEstimator) + -> (Vec<(Sha256dHash, Vec)>, + Vec, + Vec<(HTLCSource, Option, PaymentHash)>) { log_trace!( - self, - "Block {} at height {} connected with {} txn matched", - block_hash, - height, - txn_matched.len() + self, + "Block {} at height {} connected with {} txn matched", + block_hash, + height, + txn_matched.len() ); let mut watch_outputs = Vec::new(); let mut spendable_outputs = Vec::new(); @@ -3063,8 +2893,8 @@ impl ChannelMonitor { }, }; if funding_txo.is_none() - || (prevout.txid == funding_txo.as_ref().unwrap().0.txid - && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) + || (prevout.txid == funding_txo.as_ref().unwrap().0.txid + && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) { if (tx.input[0].sequence >> 8 * 3) as u8 == 0x80 && (tx.lock_time >> 8 * 3) as u8 == 0x20 { let (remote_txn, new_outputs, mut spendable_output) = @@ -3178,13 +3008,10 @@ impl ChannelMonitor { } } for (outpoint, input_material) in claimed_outputs_material.drain(..) { - let new_event = OnchainEvent::ContentiousOutpoint { - outpoint, - input_material, - }; - match self - .onchain_events_waiting_threshold_conf - .entry(height + ANTI_REORG_DELAY - 1) + let new_event = OnchainEvent::ContentiousOutpoint { outpoint, + input_material }; + match self.onchain_events_waiting_threshold_conf + .entry(height + ANTI_REORG_DELAY - 1) { hash_map::Entry::Occupied(mut entry) => { if !entry.get().contains(&new_event) { @@ -3207,10 +3034,10 @@ impl ChannelMonitor { match self.key_storage { Storage::Local { ref funding_key, .. } => { cur_local_tx.tx.add_local_sig( - funding_key, - self.funding_redeemscript.as_ref().unwrap(), - self.channel_value_satoshis.unwrap(), - &self.secp_ctx, + funding_key, + self.funding_redeemscript.as_ref().unwrap(), + self.channel_value_satoshis.unwrap(), + &self.secp_ctx, ); }, _ => {}, @@ -3220,16 +3047,14 @@ impl ChannelMonitor { if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx { if should_broadcast { log_trace!( - self, - "Broadcast onchain {}", - log_tx!(cur_local_tx.tx.with_valid_witness()) + self, + "Broadcast onchain {}", + log_tx!(cur_local_tx.tx.with_valid_witness()) ); broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness()); match self.key_storage { - Storage::Local { - ref delayed_payment_base_key, - .. - } => { + Storage::Local { ref delayed_payment_base_key, + .. } => { let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height); spendable_outputs.append(&mut spendable_output); @@ -3259,9 +3084,9 @@ impl ChannelMonitor { }, OnchainEvent::HTLCUpdate { htlc_update } => { log_trace!( - self, - "HTLC {} failure update has got enough confirmations to be passed upstream", - log_bytes!((htlc_update.1).0) + self, + "HTLC {} failure update has got enough confirmations to be passed upstream", + log_bytes!((htlc_update.1).0) ); htlc_updated.push((htlc_update.0, None, htlc_update.1)); }, @@ -3303,17 +3128,14 @@ impl ChannelMonitor { (watch_outputs, spendable_outputs, htlc_updated) } - fn block_disconnected( - &mut self, - height: u32, - block_hash: &Sha256dHash, - broadcaster: &BroadcasterInterface, - fee_estimator: &FeeEstimator, - ) { + fn block_disconnected(&mut self, + height: u32, + block_hash: &Sha256dHash, + broadcaster: &BroadcasterInterface, + fee_estimator: &FeeEstimator) { let mut bump_candidates = HashMap::new(); - if let Some(events) = self - .onchain_events_waiting_threshold_conf - .remove(&(height + ANTI_REORG_DELAY - 1)) + if let Some(events) = self.onchain_events_waiting_threshold_conf + .remove(&(height + ANTI_REORG_DELAY - 1)) { //We may discard: //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected @@ -3321,10 +3143,8 @@ impl ChannelMonitor { //- resurect outpoint back in its claimable set and regenerate tx for ev in events { match ev { - OnchainEvent::ContentiousOutpoint { - outpoint, - input_material, - } => { + OnchainEvent::ContentiousOutpoint { outpoint, + input_material, } => { if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) { if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) @@ -3350,19 +3170,19 @@ impl ChannelMonitor { } for (ancestor_claim_txid, claim_material) in bump_candidates.drain() { self.pending_claim_requests - .insert(ancestor_claim_txid.0, claim_material); + .insert(ancestor_claim_txid.0, claim_material); } //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but // right now if one of the outpoint get disconnected, just erase whole pending claim request. let mut remove_request = Vec::new(); self.claimable_outpoints.retain(|_, ref v| { - if v.1 == height { - remove_request.push(v.0.clone()); - false - } else { - true - } - }); + if v.1 == height { + remove_request.push(v.0.clone()); + false + } else { + true + } + }); for req in remove_request { self.pending_claim_requests.remove(&req); } @@ -3419,11 +3239,9 @@ impl ChannelMonitor { scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true); } - if let Storage::Local { - ref current_remote_commitment_txid, - ref prev_remote_commitment_txid, - .. - } = self.key_storage + if let Storage::Local { ref current_remote_commitment_txid, + ref prev_remote_commitment_txid, + .. } = self.key_storage { if let &Some(ref txid) = current_remote_commitment_txid { if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) { @@ -3442,21 +3260,20 @@ impl ChannelMonitor { /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC - fn is_resolving_htlc_output( - &mut self, - tx: &Transaction, - height: u32, - ) -> Vec<(HTLCSource, Option, PaymentHash)> { + fn is_resolving_htlc_output(&mut self, + tx: &Transaction, + height: u32) + -> Vec<(HTLCSource, Option, PaymentHash)> { let mut htlc_updated = Vec::new(); 'outer_loop: for input in &tx.input { let mut payment_data = None; let revocation_sig_claim = (input.witness.len() == 3 - && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT - && input.witness[1].len() == 33) - || (input.witness.len() == 3 - && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT - && input.witness[1].len() == 33); + && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT + && input.witness[1].len() == 33) + || (input.witness.len() == 3 + && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT + && input.witness[1].len() == 33); let accepted_preimage_claim = input.witness.len() == 5 && input.witness[4].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT; let offered_preimage_claim = @@ -3543,34 +3360,31 @@ impl ChannelMonitor { if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx { if input.previous_output.txid == current_local_signed_commitment_tx.txid { scan_commitment!( - current_local_signed_commitment_tx - .htlc_outputs - .iter() - .map(|&(ref a, _, ref b)| (a, b.as_ref())), - "our latest local commitment tx", - true + current_local_signed_commitment_tx.htlc_outputs + .iter() + .map(|&(ref a, _, ref b)| (a, b.as_ref())), + "our latest local commitment tx", + true ); } } if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx { if input.previous_output.txid == prev_local_signed_commitment_tx.txid { scan_commitment!( - prev_local_signed_commitment_tx - .htlc_outputs - .iter() - .map(|&(ref a, _, ref b)| (a, b.as_ref())), - "our previous local commitment tx", - true + prev_local_signed_commitment_tx.htlc_outputs + .iter() + .map(|&(ref a, _, ref b)| (a, b.as_ref())), + "our previous local commitment tx", + true ); } } if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) { scan_commitment!( - htlc_outputs - .iter() - .map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))), - "remote commitment tx", - false + htlc_outputs.iter() + .map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))), + "remote commitment tx", + false ); } @@ -3586,24 +3400,19 @@ impl ChannelMonitor { htlc_updated.push((source, Some(payment_preimage), payment_hash)); } else { log_info!(self, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height{})", log_bytes!(payment_hash.0), height + ANTI_REORG_DELAY - 1); - match self - .onchain_events_waiting_threshold_conf - .entry(height + ANTI_REORG_DELAY - 1) + match self.onchain_events_waiting_threshold_conf + .entry(height + ANTI_REORG_DELAY - 1) { hash_map::Entry::Occupied(mut entry) => { let e = entry.get_mut(); e.retain(|ref event| match **event { - OnchainEvent::HTLCUpdate { ref htlc_update } => return htlc_update.0 != source, - _ => return true, - }); - e.push(OnchainEvent::HTLCUpdate { - htlc_update: (source, payment_hash), - }); + OnchainEvent::HTLCUpdate { ref htlc_update } => return htlc_update.0 != source, + _ => return true, + }); + e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash) }); }, hash_map::Entry::Vacant(entry) => { - entry.insert(vec![OnchainEvent::HTLCUpdate { - htlc_update: (source, payment_hash), - }]); + entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash) }]); }, } } @@ -3614,33 +3423,26 @@ impl ChannelMonitor { /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent. - fn bump_claim_tx( - &self, - height: u32, - cached_claim_datas: &ClaimTxBumpMaterial, - fee_estimator: &FeeEstimator, - ) -> Option<(u32, u64, Transaction)> { + fn bump_claim_tx(&self, + height: u32, + cached_claim_datas: &ClaimTxBumpMaterial, + fee_estimator: &FeeEstimator) + -> Option<(u32, u64, Transaction)> { if cached_claim_datas.per_input_material.len() == 0 { return None; } // But don't prune pending claiming request yet, we may have to resurrect HTLCs let mut inputs = Vec::new(); for outp in cached_claim_datas.per_input_material.keys() { - inputs.push(TxIn { - previous_output: *outp, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }); + inputs.push(TxIn { previous_output: *outp, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new(), }); } - let mut bumped_tx = Transaction { - version: 2, - lock_time: 0, - input: inputs, - output: vec![TxOut { - script_pubkey: self.destination_script.clone(), - value: 0, - }], - }; + let mut bumped_tx = Transaction { version: 2, + lock_time: 0, + input: inputs, + output: vec![TxOut { script_pubkey: self.destination_script.clone(), + value: 0 }] }; macro_rules! RBF_bump { ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {{ @@ -3680,12 +3482,10 @@ impl ChannelMonitor { let mut amt = 0; for per_outp_material in cached_claim_datas.per_input_material.values() { match per_outp_material { - &InputMaterial::Revoked { - ref script, - ref is_htlc, - ref amount, - .. - } => { + &InputMaterial::Revoked { ref script, + ref is_htlc, + ref amount, + .. } => { inputs_witnesses_weight += Self::get_witnesses_weight(if !is_htlc { &[InputDescriptors::RevokedOutput] } else if script.len() == OFFERED_HTLC_SCRIPT_WEIGHT { @@ -3697,11 +3497,9 @@ impl ChannelMonitor { }); amt += *amount; }, - &InputMaterial::RemoteHTLC { - ref preimage, - ref amount, - .. - } => { + &InputMaterial::RemoteHTLC { ref preimage, + ref amount, + .. } => { inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { @@ -3718,10 +3516,10 @@ impl ChannelMonitor { let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight; let new_feerate; if let Some((new_fee, feerate)) = RBF_bump!( - amt, - cached_claim_datas.feerate_previous, - fee_estimator, - predicted_weight as u64 + amt, + cached_claim_datas.feerate_previous, + fee_estimator, + predicted_weight as u64 ) { // If new computed fee is superior at the whole claimable amount burn all in fees if new_fee > amt { @@ -3737,13 +3535,11 @@ impl ChannelMonitor { for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() { match per_outp_material { - &InputMaterial::Revoked { - ref script, - ref pubkey, - ref key, - ref is_htlc, - ref amount, - } => { + &InputMaterial::Revoked { ref script, + ref pubkey, + ref key, + ref is_htlc, + ref amount, } => { let sighash_parts = bip143::SighashComponents::new(&bumped_tx); let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]); @@ -3751,9 +3547,8 @@ impl ChannelMonitor { bumped_tx.input[i].witness.push(sig.serialize_der().to_vec()); bumped_tx.input[i].witness[0].push(SigHashType::All as u8); if *is_htlc { - bumped_tx.input[i] - .witness - .push(pubkey.unwrap().clone().serialize().to_vec()); + bumped_tx.input[i].witness + .push(pubkey.unwrap().clone().serialize().to_vec()); } else { bumped_tx.input[i].witness.push(vec![1]); } @@ -3776,13 +3571,11 @@ impl ChannelMonitor { new_feerate ); }, - &InputMaterial::RemoteHTLC { - ref script, - ref key, - ref preimage, - ref amount, - ref locktime, - } => { + &InputMaterial::RemoteHTLC { ref script, + ref key, + ref preimage, + ref amount, + ref locktime, } => { if !preimage.is_some() { bumped_tx.lock_time = *locktime }; @@ -3845,24 +3638,20 @@ impl ReadableArgs> for (Sha256dHash, ChannelM let shutdown_pubkey = Readable::read(reader)?; // Technically this can fail and serialize fail a round-trip, but only for serialization of // barely-init'd ChannelMonitors that we can't do anything with. - let outpoint = OutPoint { - txid: Readable::read(reader)?, - index: Readable::read(reader)?, - }; + let outpoint = OutPoint { txid: Readable::read(reader)?, + index: Readable::read(reader)? }; let funding_info = Some((outpoint, Readable::read(reader)?)); let current_remote_commitment_txid = Readable::read(reader)?; let prev_remote_commitment_txid = Readable::read(reader)?; - Storage::Local { - funding_key, - revocation_base_key, - htlc_base_key, - delayed_payment_base_key, - payment_base_key, - shutdown_pubkey, - funding_info, - current_remote_commitment_txid, - prev_remote_commitment_txid, - } + Storage::Local { funding_key, + revocation_base_key, + htlc_base_key, + delayed_payment_base_key, + payment_base_key, + shutdown_pubkey, + funding_info, + current_remote_commitment_txid, + prev_remote_commitment_txid } }, _ => return Err(DecodeError::InvalidValue), }; @@ -3882,11 +3671,7 @@ impl ReadableArgs> for (Sha256dHash, ChannelM if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 { Some((first_idx, first_point, None)) } else { - Some(( - first_idx, - first_point, - Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice))), - )) + Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice))))) } } }; @@ -3931,10 +3716,8 @@ impl ReadableArgs> for (Sha256dHash, ChannelM } let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?; - let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min( - remote_commitment_txn_on_chain_len as usize, - MAX_ALLOC_SIZE / 32, - )); + let mut remote_commitment_txn_on_chain = + HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32)); for _ in 0..remote_commitment_txn_on_chain_len { let txid: Sha256dHash = Readable::read(reader)?; let commitment_number = >::read(reader)?.0; @@ -3949,10 +3732,8 @@ impl ReadableArgs> for (Sha256dHash, ChannelM } let remote_hash_commitment_number_len: u64 = Readable::read(reader)?; - let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min( - remote_hash_commitment_number_len as usize, - MAX_ALLOC_SIZE / 32, - )); + let mut remote_hash_commitment_number = + HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32)); for _ in 0..remote_hash_commitment_number_len { let payment_hash: PaymentHash = Readable::read(reader)?; let commitment_number = >::read(reader)?.0; @@ -4057,17 +3838,13 @@ impl ReadableArgs> for (Sha256dHash, ChannelM 1 => { let htlc_source = Readable::read(reader)?; let hash = Readable::read(reader)?; - OnchainEvent::HTLCUpdate { - htlc_update: (htlc_source, hash), - } + OnchainEvent::HTLCUpdate { htlc_update: (htlc_source, hash) } }, 2 => { let outpoint = Readable::read(reader)?; let input_material = Readable::read(reader)?; - OnchainEvent::ContentiousOutpoint { - outpoint, - input_material, - } + OnchainEvent::ContentiousOutpoint { outpoint, + input_material } }, _ => return Err(DecodeError::InvalidValue), }; @@ -4076,36 +3853,32 @@ impl ReadableArgs> for (Sha256dHash, ChannelM onchain_events_waiting_threshold_conf.insert(height_target, events); } - Ok(( - last_block_hash.clone(), - ChannelMonitor { - commitment_transaction_number_obscure_factor, - key_storage, - their_htlc_base_key, - their_delayed_payment_base_key, - funding_redeemscript, - channel_value_satoshis, - their_cur_revocation_points, - our_to_self_delay, - their_to_self_delay, - old_secrets, - remote_claimable_outpoints, - remote_commitment_txn_on_chain, - remote_hash_commitment_number, - prev_local_signed_commitment_tx, - current_local_signed_commitment_tx, - current_remote_commitment_number, - payment_preimages, - destination_script, - to_remote_rescue, - pending_claim_requests, - claimable_outpoints, - onchain_events_waiting_threshold_conf, - last_block_hash, - secp_ctx, - logger, - }, - )) + Ok((last_block_hash.clone(), + ChannelMonitor { commitment_transaction_number_obscure_factor, + key_storage, + their_htlc_base_key, + their_delayed_payment_base_key, + funding_redeemscript, + channel_value_satoshis, + their_cur_revocation_points, + our_to_self_delay, + their_to_self_delay, + old_secrets, + remote_claimable_outpoints, + remote_commitment_txn_on_chain, + remote_hash_commitment_number, + prev_local_signed_commitment_tx, + current_local_signed_commitment_tx, + current_remote_commitment_number, + payment_preimages, + destination_script, + to_remote_rescue, + pending_claim_requests, + claimable_outpoints, + onchain_events_waiting_threshold_conf, + last_block_hash, + secp_ctx, + logger })) } } @@ -4153,114 +3926,107 @@ mod tests { { // insert_secret correct sequence - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap(), ); - monitor - .provide_secret(281474976710651, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap(), ); - monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap(), ); - monitor - .provide_secret(281474976710649, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap(), ); - monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); } { // insert_secret #1 incorrect - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4268,54 +4034,51 @@ mod tests { &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #2 incorrect (#1 derived from incorrect) - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4323,54 +4086,51 @@ mod tests { &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #3 incorrect - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4378,90 +4138,83 @@ mod tests { &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #4 incorrect (1,2,3 derived from incorrect) - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap(), ); - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap(), ); - monitor - .provide_secret(281474976710651, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap(), ); - monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap(), ); - monitor - .provide_secret(281474976710649, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4469,72 +4222,67 @@ mod tests { &hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #5 incorrect - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap(), ); - monitor - .provide_secret(281474976710651, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4542,90 +4290,83 @@ mod tests { &hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #6 incorrect (5 derived from incorrect) - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap(), ); - monitor - .provide_secret(281474976710651, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap(), ); - monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap(), ); - monitor - .provide_secret(281474976710649, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4633,90 +4374,83 @@ mod tests { &hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #7 incorrect - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap(), ); - monitor - .provide_secret(281474976710651, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap(), ); - monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap(), ); - monitor - .provide_secret(281474976710649, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4724,90 +4458,83 @@ mod tests { &hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } { // insert_secret #8 incorrect - monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); secrets.clear(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap(), ); - monitor - .provide_secret(281474976710655, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap(), ); - monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), ); - monitor - .provide_secret(281474976710653, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), ); - monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap(), ); - monitor - .provide_secret(281474976710651, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap(), ); - monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice( &hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap(), ); - monitor - .provide_secret(281474976710649, secrets.last().unwrap().clone()) - .unwrap(); + monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()) + .unwrap(); test_secrets!(); secrets.push([0; 32]); @@ -4815,11 +4542,10 @@ mod tests { &hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap(), ); assert_eq!( - monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .unwrap_err() - .0, - "Previous secret did not match new one" + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()) + .unwrap_err() + .0, + "Previous secret did not match new one" ); } } @@ -4835,12 +4561,10 @@ mod tests { TxCreationKeys { per_commitment_point: dummy_key.clone(), revocation_key: dummy_key.clone(), a_htlc_key: dummy_key.clone(), b_htlc_key: dummy_key.clone(), a_delayed_payment_key: dummy_key.clone(), b_payment_key: dummy_key.clone() } }}; } - let dummy_tx = Transaction { - version: 0, - lock_time: 0, - input: Vec::new(), - output: Vec::new(), - }; + let dummy_tx = Transaction { version: 0, + lock_time: 0, + input: Vec::new(), + output: Vec::new() }; let mut preimages = Vec::new(); { @@ -4880,48 +4604,49 @@ mod tests { // Prune with one old state and a local commitment tx holding a few overlaps with the // old state. - let mut monitor = ChannelMonitor::new( - &SecretKey::from_slice(&[41; 32]).unwrap(), - &SecretKey::from_slice(&[42; 32]).unwrap(), - &SecretKey::from_slice(&[43; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &SecretKey::from_slice(&[44; 32]).unwrap(), - &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), - 0, - Script::new(), - logger.clone(), - ); + let mut monitor = + ChannelMonitor::new( + &SecretKey::from_slice(&[41; 32]).unwrap(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + &SecretKey::from_slice(&[43; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &SecretKey::from_slice(&[44; 32]).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + 0, + Script::new(), + logger.clone(), + ); monitor.their_to_self_delay = Some(10); monitor.provide_latest_local_commitment_tx_info( - LocalCommitmentTransaction::dummy(), - dummy_keys!(), - 0, - preimages_to_local_htlcs!(preimages[0..10]), + LocalCommitmentTransaction::dummy(), + dummy_keys!(), + 0, + preimages_to_local_htlcs!(preimages[0..10]), ); monitor.provide_latest_remote_commitment_tx_info( - &dummy_tx, - preimages_slice_to_htlc_outputs!(preimages[5..15]), - 281474976710655, - dummy_key, + &dummy_tx, + preimages_slice_to_htlc_outputs!(preimages[5..15]), + 281474976710655, + dummy_key, ); monitor.provide_latest_remote_commitment_tx_info( - &dummy_tx, - preimages_slice_to_htlc_outputs!(preimages[15..20]), - 281474976710654, - dummy_key, + &dummy_tx, + preimages_slice_to_htlc_outputs!(preimages[15..20]), + 281474976710654, + dummy_key, ); monitor.provide_latest_remote_commitment_tx_info( - &dummy_tx, - preimages_slice_to_htlc_outputs!(preimages[17..20]), - 281474976710653, - dummy_key, + &dummy_tx, + preimages_slice_to_htlc_outputs!(preimages[17..20]), + 281474976710653, + dummy_key, ); monitor.provide_latest_remote_commitment_tx_info( - &dummy_tx, - preimages_slice_to_htlc_outputs!(preimages[18..20]), - 281474976710652, - dummy_key, + &dummy_tx, + preimages_slice_to_htlc_outputs!(preimages[18..20]), + 281474976710652, + dummy_key, ); for &(ref preimage, ref hash) in preimages.iter() { monitor.provide_payment_preimage(hash, preimage); @@ -4949,10 +4674,10 @@ mod tests { // Now update local commitment tx info, pruning only element 18 as we still care about the // previous commitment tx's preimages too monitor.provide_latest_local_commitment_tx_info( - LocalCommitmentTransaction::dummy(), - dummy_keys!(), - 0, - preimages_to_local_htlcs!(preimages[0..5]), + LocalCommitmentTransaction::dummy(), + dummy_keys!(), + 0, + preimages_to_local_htlcs!(preimages[0..5]), ); secret[0..32].clone_from_slice( &hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap(), @@ -4964,10 +4689,10 @@ mod tests { // But if we do it again, we'll prune 5-10 monitor.provide_latest_local_commitment_tx_info( - LocalCommitmentTransaction::dummy(), - dummy_keys!(), - 0, - preimages_to_local_htlcs!(preimages[0..3]), + LocalCommitmentTransaction::dummy(), + dummy_keys!(), + 0, + preimages_to_local_htlcs!(preimages[0..3]), ); secret[0..32].clone_from_slice( &hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap(), @@ -5019,76 +4744,69 @@ mod tests { let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap(); // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs - let mut claim_tx = Transaction { - version: 0, - lock_time: 0, - input: Vec::new(), - output: Vec::new(), - }; + let mut claim_tx = Transaction { version: 0, + lock_time: 0, + input: Vec::new(), + output: Vec::new() }; for i in 0..4 { - claim_tx.input.push(TxIn { - previous_output: BitcoinOutPoint { txid, vout: i }, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }); + claim_tx.input + .push(TxIn { previous_output: BitcoinOutPoint { txid, vout: i }, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new(), }); } - claim_tx.output.push(TxOut { - script_pubkey: script_pubkey.clone(), - value: 0, - }); + claim_tx.output.push(TxOut { script_pubkey: script_pubkey.clone(), + value: 0 }); let base_weight = claim_tx.get_weight(); let sighash_parts = bip143::SighashComponents::new(&claim_tx); let inputs_des = vec![ - InputDescriptors::RevokedOutput, - InputDescriptors::RevokedOfferedHTLC, - InputDescriptors::RevokedOfferedHTLC, - InputDescriptors::RevokedReceivedHTLC, + InputDescriptors::RevokedOutput, + InputDescriptors::RevokedOfferedHTLC, + InputDescriptors::RevokedOfferedHTLC, + InputDescriptors::RevokedReceivedHTLC, ]; for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() { sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs); } assert_eq!( - base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), - claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs) + base_weight + ChannelMonitor::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(); sum_actual_sigs = 0; for i in 0..4 { - claim_tx.input.push(TxIn { - previous_output: BitcoinOutPoint { txid, vout: i }, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }); + claim_tx.input + .push(TxIn { previous_output: BitcoinOutPoint { txid, vout: i }, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new(), }); } let base_weight = claim_tx.get_weight(); let sighash_parts = bip143::SighashComponents::new(&claim_tx); let inputs_des = vec![ - InputDescriptors::OfferedHTLC, - InputDescriptors::ReceivedHTLC, - InputDescriptors::ReceivedHTLC, - InputDescriptors::ReceivedHTLC, + InputDescriptors::OfferedHTLC, + InputDescriptors::ReceivedHTLC, + InputDescriptors::ReceivedHTLC, + InputDescriptors::ReceivedHTLC, ]; for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() { sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs); } assert_eq!( - base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), - claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs) + base_weight + ChannelMonitor::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(); sum_actual_sigs = 0; - claim_tx.input.push(TxIn { - previous_output: BitcoinOutPoint { txid, vout: 0 }, - script_sig: Script::new(), - sequence: 0xfffffffd, - witness: Vec::new(), - }); + claim_tx.input + .push(TxIn { previous_output: BitcoinOutPoint { txid, vout: 0 }, + script_sig: Script::new(), + sequence: 0xfffffffd, + witness: Vec::new() }); let base_weight = claim_tx.get_weight(); let sighash_parts = bip143::SighashComponents::new(&claim_tx); let inputs_des = vec![InputDescriptors::RevokedOutput]; @@ -5096,8 +4814,8 @@ mod tests { sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs); } assert_eq!( - base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), - claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs) + base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), + claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs) ); } diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index d3910542c6f..1f0d30e05ff 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -35,60 +35,49 @@ use std::rc::Rc; use std::sync::{Arc, Mutex}; pub const CHAN_CONFIRM_DEPTH: u32 = 100; -pub fn confirm_transaction( - notifier: &chaininterface::BlockNotifier, - chain: &chaininterface::ChainWatchInterfaceUtil, - tx: &Transaction, - chan_id: u32, -) { +pub fn confirm_transaction(notifier: &chaininterface::BlockNotifier, + chain: &chaininterface::ChainWatchInterfaceUtil, + tx: &Transaction, + chan_id: u32) { assert!(chain.does_match_tx(tx)); - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; notifier.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]); for i in 2..CHAN_CONFIRM_DEPTH { - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; notifier.block_connected_checked(&header, i, &vec![], &[0; 0]); } } -pub fn connect_blocks( - notifier: &chaininterface::BlockNotifier, - depth: u32, - height: u32, - parent: bool, - prev_blockhash: Sha256d, -) -> Sha256d { - let mut header = BlockHeader { - version: 0x2000000, - prev_blockhash: if parent { prev_blockhash } else { Default::default() }, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; +pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, + depth: u32, + height: u32, + parent: bool, + prev_blockhash: Sha256d) + -> Sha256d { + let mut header = BlockHeader { version: 0x2000000, + prev_blockhash: if parent { prev_blockhash } else { Default::default() }, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; notifier.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new()); for i in 2..depth + 1 { - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; notifier.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new()); } header.bitcoin_hash() @@ -122,14 +111,8 @@ pub fn create_chan_between_nodes( node_a: &Node, node_b: &Node, a_flags: LocalFeatures, - b_flags: LocalFeatures, -) -> ( - msgs::ChannelAnnouncement, - msgs::ChannelUpdate, - msgs::ChannelUpdate, - [u8; 32], - Transaction, -) { + b_flags: LocalFeatures) + -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) { create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags) } @@ -139,14 +122,8 @@ pub fn create_chan_between_nodes_with_value( channel_value: u64, push_msat: u64, a_flags: LocalFeatures, - b_flags: LocalFeatures, -) -> ( - msgs::ChannelAnnouncement, - msgs::ChannelUpdate, - msgs::ChannelUpdate, - [u8; 32], - Transaction, -) { + b_flags: LocalFeatures) + -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) { let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat, a_flags, b_flags); let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked); @@ -217,34 +194,27 @@ macro_rules! get_feerate { }}; } -pub fn create_funding_transaction( - node: &Node, - expected_chan_value: u64, - expected_user_chan_id: u64, -) -> ([u8; 32], Transaction, OutPoint) { +pub fn create_funding_transaction(node: &Node, + expected_chan_value: u64, + expected_user_chan_id: u64) + -> ([u8; 32], Transaction, OutPoint) { let chan_id = *node.network_chan_count.borrow(); let events = node.node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { - Event::FundingGenerationReady { - ref temporary_channel_id, - ref channel_value_satoshis, - ref output_script, - user_channel_id, - } => { + Event::FundingGenerationReady { ref temporary_channel_id, + ref channel_value_satoshis, + ref output_script, + user_channel_id, } => { assert_eq!(*channel_value_satoshis, expected_chan_value); assert_eq!(user_channel_id, expected_user_chan_id); - let tx = Transaction { - version: chan_id as u32, - lock_time: 0, - input: Vec::new(), - output: vec![TxOut { - value: *channel_value_satoshis, - script_pubkey: output_script.clone(), - }], - }; + let tx = Transaction { version: chan_id as u32, + lock_time: 0, + input: Vec::new(), + output: vec![TxOut { value: *channel_value_satoshis, + script_pubkey: output_script.clone() }] }; let funding_outpoint = OutPoint::new(tx.txid(), 0); (*temporary_channel_id, tx, funding_outpoint) }, @@ -252,39 +222,40 @@ pub fn create_funding_transaction( } } -pub fn create_chan_between_nodes_with_value_init( - node_a: &Node, - node_b: &Node, - channel_value: u64, - push_msat: u64, - a_flags: LocalFeatures, - b_flags: LocalFeatures, -) -> Transaction { - node_a - .node - .create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42) - .unwrap(); +pub fn create_chan_between_nodes_with_value_init(node_a: &Node, + node_b: &Node, + channel_value: u64, + push_msat: u64, + a_flags: LocalFeatures, + b_flags: LocalFeatures) + -> Transaction { + node_a.node + .create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42) + .unwrap(); node_b.node.handle_open_channel( - &node_a.node.get_our_node_id(), - a_flags, - &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()), + &node_a.node.get_our_node_id(), + a_flags, + &get_event_msg!( + node_a, + MessageSendEvent::SendOpenChannel, + node_b.node.get_our_node_id() + ), ); node_a.node.handle_accept_channel( - &node_b.node.get_our_node_id(), - b_flags, - &get_event_msg!( - node_b, - MessageSendEvent::SendAcceptChannel, - node_a.node.get_our_node_id() - ), + &node_b.node.get_our_node_id(), + b_flags, + &get_event_msg!( + node_b, + MessageSendEvent::SendAcceptChannel, + node_a.node.get_our_node_id() + ), ); let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42); { - node_a - .node - .funding_transaction_generated(&temporary_channel_id, funding_output); + node_a.node + .funding_transaction_generated(&temporary_channel_id, funding_output); let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap(); assert_eq!(added_monitors.len(), 1); assert_eq!(added_monitors[0].0, funding_output); @@ -292,12 +263,12 @@ pub fn create_chan_between_nodes_with_value_init( } node_b.node.handle_funding_created( - &node_a.node.get_our_node_id(), - &get_event_msg!( - node_a, - MessageSendEvent::SendFundingCreated, - node_b.node.get_our_node_id() - ), + &node_a.node.get_our_node_id(), + &get_event_msg!( + node_a, + MessageSendEvent::SendFundingCreated, + node_b.node.get_our_node_id() + ), ); { let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap(); @@ -307,12 +278,12 @@ pub fn create_chan_between_nodes_with_value_init( } node_a.node.handle_funding_signed( - &node_b.node.get_our_node_id(), - &get_event_msg!( - node_b, - MessageSendEvent::SendFundingSigned, - node_a.node.get_our_node_id() - ), + &node_b.node.get_our_node_id(), + &get_event_msg!( + node_b, + MessageSendEvent::SendFundingSigned, + node_a.node.get_our_node_id() + ), ); { let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap(); @@ -324,10 +295,8 @@ pub fn create_chan_between_nodes_with_value_init( let events_4 = node_a.node.get_and_clear_pending_events(); assert_eq!(events_4.len(), 1); match events_4[0] { - Event::FundingBroadcastSafe { - ref funding_txo, - user_channel_id, - } => { + Event::FundingBroadcastSafe { ref funding_txo, + user_channel_id, } => { assert_eq!(user_channel_id, 42); assert_eq!(*funding_txo, funding_output); }, @@ -340,49 +309,45 @@ pub fn create_chan_between_nodes_with_value_init( pub fn create_chan_between_nodes_with_value_confirm_first(node_recv: &Node, node_conf: &Node, tx: &Transaction) { confirm_transaction(&node_conf.block_notifier, &node_conf.chain_monitor, &tx, tx.version); node_recv.node.handle_funding_locked( - &node_conf.node.get_our_node_id(), - &get_event_msg!( - node_conf, - MessageSendEvent::SendFundingLocked, - node_recv.node.get_our_node_id() - ), + &node_conf.node.get_our_node_id(), + &get_event_msg!( + node_conf, + MessageSendEvent::SendFundingLocked, + node_recv.node.get_our_node_id() + ), ); } pub fn create_chan_between_nodes_with_value_confirm_second( node_recv: &Node, - node_conf: &Node, -) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) { + node_conf: &Node) + -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) { let channel_id; let events_6 = node_conf.node.get_and_clear_pending_msg_events(); assert_eq!(events_6.len(), 2); - ( - ( - match events_6[0] { - MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => { - channel_id = msg.channel_id.clone(); - assert_eq!(*node_id, node_recv.node.get_our_node_id()); - msg.clone() - }, - _ => panic!("Unexpected event"), - }, - match events_6[1] { - MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => { - assert_eq!(*node_id, node_recv.node.get_our_node_id()); - msg.clone() - }, - _ => panic!("Unexpected event"), - }, - ), - channel_id, - ) + ((match events_6[0] { + MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => { + channel_id = msg.channel_id.clone(); + assert_eq!(*node_id, node_recv.node.get_our_node_id()); + msg.clone() + }, + _ => panic!("Unexpected event"), + }, + match events_6[1] { + MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => { + assert_eq!(*node_id, node_recv.node.get_our_node_id()); + msg.clone() + }, + _ => panic!("Unexpected event"), + }), + channel_id) } pub fn create_chan_between_nodes_with_value_confirm( node_a: &Node, node_b: &Node, - tx: &Transaction, -) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) { + tx: &Transaction) + -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) { create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx); confirm_transaction(&node_a.block_notifier, &node_a.chain_monitor, &tx, tx.version); create_chan_between_nodes_with_value_confirm_second(node_b, node_a) @@ -394,12 +359,8 @@ pub fn create_chan_between_nodes_with_value_a( channel_value: u64, push_msat: u64, a_flags: LocalFeatures, - b_flags: LocalFeatures, -) -> ( - (msgs::FundingLocked, msgs::AnnouncementSignatures), - [u8; 32], - Transaction, -) { + b_flags: LocalFeatures) + -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) { let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags); let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx); (msgs, chan_id, tx) @@ -408,48 +369,41 @@ pub fn create_chan_between_nodes_with_value_a( pub fn create_chan_between_nodes_with_value_b( node_a: &Node, node_b: &Node, - as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures), -) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) { - node_b - .node - .handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0); + as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) + -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) { + node_b.node + .handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0); let bs_announcement_sigs = get_event_msg!( - node_b, - MessageSendEvent::SendAnnouncementSignatures, - node_a.node.get_our_node_id() + node_b, + MessageSendEvent::SendAnnouncementSignatures, + node_a.node.get_our_node_id() ); - node_b - .node - .handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1); + node_b.node + .handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1); let events_7 = node_b.node.get_and_clear_pending_msg_events(); assert_eq!(events_7.len(), 1); let (announcement, bs_update) = match events_7[0] { - MessageSendEvent::BroadcastChannelAnnouncement { - ref msg, - ref update_msg, - } => (msg, update_msg), + MessageSendEvent::BroadcastChannelAnnouncement { ref msg, + ref update_msg, } => (msg, update_msg), _ => panic!("Unexpected event"), }; - node_a - .node - .handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs); + node_a.node + .handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs); let events_8 = node_a.node.get_and_clear_pending_msg_events(); assert_eq!(events_8.len(), 1); let as_update = match events_8[0] { - MessageSendEvent::BroadcastChannelAnnouncement { - ref msg, - ref update_msg, - } => { + MessageSendEvent::BroadcastChannelAnnouncement { ref msg, + ref update_msg, } => { assert!(*announcement == *msg); assert_eq!( - update_msg.contents.short_channel_id, - announcement.contents.short_channel_id + update_msg.contents.short_channel_id, + announcement.contents.short_channel_id ); assert_eq!( - update_msg.contents.short_channel_id, - bs_update.contents.short_channel_id + update_msg.contents.short_channel_id, + bs_update.contents.short_channel_id ); update_msg }, @@ -461,13 +415,12 @@ pub fn create_chan_between_nodes_with_value_b( ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone()) } -pub fn create_announced_chan_between_nodes( - nodes: &Vec, - a: usize, - b: usize, - a_flags: LocalFeatures, - b_flags: LocalFeatures, -) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) { +pub fn create_announced_chan_between_nodes(nodes: &Vec, + a: usize, + b: usize, + a_flags: LocalFeatures, + b_flags: LocalFeatures) + -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) { create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags) } @@ -478,8 +431,8 @@ pub fn create_announced_chan_between_nodes_with_value( channel_value: u64, push_msat: u64, a_flags: LocalFeatures, - b_flags: LocalFeatures, -) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) { + b_flags: LocalFeatures) + -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) { let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags); for node in nodes { @@ -487,12 +440,7 @@ pub fn create_announced_chan_between_nodes_with_value( node.router.handle_channel_update(&chan_announcement.1).unwrap(); node.router.handle_channel_update(&chan_announcement.2).unwrap(); } - ( - chan_announcement.1, - chan_announcement.2, - chan_announcement.3, - chan_announcement.4, - ) + (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4) } macro_rules! check_spends { @@ -552,13 +500,12 @@ macro_rules! check_closed_broadcast { }}; } -pub fn close_channel( - outbound_node: &Node, - inbound_node: &Node, - channel_id: &[u8; 32], - funding_tx: Transaction, - close_inbound_first: bool, -) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) { +pub fn close_channel(outbound_node: &Node, + inbound_node: &Node, + channel_id: &[u8; 32], + funding_tx: Transaction, + close_inbound_first: bool) + -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) { let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { @@ -573,8 +520,8 @@ pub fn close_channel( node_a.close_channel(channel_id).unwrap(); node_b.handle_shutdown( - &node_a.get_our_node_id(), - &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()), + &node_a.get_our_node_id(), + &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()), ); let events_1 = node_b.get_and_clear_pending_msg_events(); @@ -646,11 +593,9 @@ impl SendEvent { assert!(updates.update_fail_htlcs.is_empty()); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - SendEvent { - node_id, - msgs: updates.update_add_htlcs, - commitment_msg: updates.commitment_signed, - } + SendEvent { node_id, + msgs: updates.update_add_htlcs, + commitment_msg: updates.commitment_signed } } pub fn from_event(event: MessageSendEvent) -> SendEvent { @@ -797,13 +742,11 @@ macro_rules! expect_payment_sent { }; } -pub fn send_along_route_with_hash( - origin_node: &Node, - route: Route, - expected_route: &[&Node], - recv_value: u64, - our_payment_hash: PaymentHash, -) { +pub fn send_along_route_with_hash(origin_node: &Node, + route: Route, + expected_route: &[&Node], + recv_value: u64, + our_payment_hash: PaymentHash) { let mut payment_event = { origin_node.node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(origin_node, 1); @@ -818,7 +761,7 @@ pub fn send_along_route_with_hash( assert_eq!(node.node.get_our_node_id(), payment_event.node_id); node.node - .handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]); + .handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]); check_added_monitors!(node, 0); commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false); @@ -846,29 +789,25 @@ pub fn send_along_route_with_hash( } } -pub fn send_along_route( - origin_node: &Node, - route: Route, - expected_route: &[&Node], - recv_value: u64, -) -> (PaymentPreimage, PaymentHash) { +pub fn send_along_route(origin_node: &Node, + route: Route, + expected_route: &[&Node], + recv_value: u64) + -> (PaymentPreimage, PaymentHash) { let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node); send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash); (our_payment_preimage, our_payment_hash) } -pub fn claim_payment_along_route( - origin_node: &Node, - expected_route: &[&Node], - skip_last: bool, - our_payment_preimage: PaymentPreimage, - expected_amount: u64, -) { - assert!(expected_route - .last() - .unwrap() - .node - .claim_funds(our_payment_preimage, expected_amount)); +pub fn claim_payment_along_route(origin_node: &Node, + expected_route: &[&Node], + skip_last: bool, + our_payment_preimage: PaymentPreimage, + expected_amount: u64) { + assert!(expected_route.last() + .unwrap() + .node + .claim_funds(our_payment_preimage, expected_amount)); check_added_monitors!(expected_route.last().unwrap(), 1); let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None; @@ -939,34 +878,31 @@ pub fn claim_payment_along_route( } } -pub fn claim_payment( - origin_node: &Node, - expected_route: &[&Node], - our_payment_preimage: PaymentPreimage, - expected_amount: u64, -) { +pub fn claim_payment(origin_node: &Node, + expected_route: &[&Node], + our_payment_preimage: PaymentPreimage, + expected_amount: u64) { claim_payment_along_route( - origin_node, - expected_route, - false, - our_payment_preimage, - expected_amount, + origin_node, + expected_route, + false, + our_payment_preimage, + expected_amount, ); } pub const TEST_FINAL_CLTV: u32 = 32; pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) { - let route = origin_node - .router - .get_route( - &expected_route.last().unwrap().node.get_our_node_id(), - None, - &Vec::new(), - recv_value, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = origin_node.router + .get_route( + &expected_route.last().unwrap().node.get_our_node_id(), + None, + &Vec::new(), + recv_value, + TEST_FINAL_CLTV, + ) + .unwrap(); assert_eq!(route.hops.len(), expected_route.len()); for (node, hop) in expected_route.iter().zip(route.hops.iter()) { assert_eq!(hop.pubkey, node.node.get_our_node_id()); @@ -976,16 +912,15 @@ pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u } pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) { - let route = origin_node - .router - .get_route( - &expected_route.last().unwrap().node.get_our_node_id(), - None, - &Vec::new(), - recv_value, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = origin_node.router + .get_route( + &expected_route.last().unwrap().node.get_our_node_id(), + None, + &Vec::new(), + recv_value, + TEST_FINAL_CLTV, + ) + .unwrap(); assert_eq!(route.hops.len(), expected_route.len()); for (node, hop) in expected_route.iter().zip(route.hops.iter()) { assert_eq!(hop.pubkey, node.node.get_our_node_id()); @@ -1008,17 +943,14 @@ pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64, ex claim_payment(&origin, expected_route, our_payment_preimage, expected_value); } -pub fn fail_payment_along_route( - origin_node: &Node, - expected_route: &[&Node], - skip_last: bool, - our_payment_hash: PaymentHash, -) { - assert!(expected_route - .last() - .unwrap() - .node - .fail_htlc_backwards(&our_payment_hash)); +pub fn fail_payment_along_route(origin_node: &Node, + expected_route: &[&Node], + skip_last: bool, + our_payment_hash: PaymentHash) { + assert!(expected_route.last() + .unwrap() + .node + .fail_htlc_backwards(&our_payment_hash)); expect_pending_htlcs_forwardable!(expected_route.last().unwrap()); check_added_monitors!(expected_route.last().unwrap(), 1); @@ -1048,18 +980,14 @@ pub fn fail_payment_along_route( if !skip_last || idx != expected_route.len() - 1 { assert_eq!(events.len(), 1); match events[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - ref commitment_signed, - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + ref commitment_signed, }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); assert_eq!(update_fail_htlcs.len(), 1); @@ -1086,11 +1014,9 @@ pub fn fail_payment_along_route( let events = origin_node.node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { - Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } => { + Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } => { assert_eq!(payment_hash, our_payment_hash); assert!(rejected_by_dest); }, @@ -1115,21 +1041,13 @@ pub fn create_network(node_count: usize, node_config: &[Option]) -> let test_logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i))); let logger = &(Arc::clone(&test_logger) as Arc); let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }); - let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new( - Network::Testnet, - Arc::clone(&logger), - )); + let chain_monitor = + Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger))); let block_notifier = Arc::new(chaininterface::BlockNotifier::new(chain_monitor.clone())); - let tx_broadcaster = Arc::new(test_utils::TestBroadcaster { - txn_broadcasted: Mutex::new(Vec::new()), - }); + let tx_broadcaster = Arc::new(test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()) }); let mut seed = [0; 32]; rng.fill_bytes(&mut seed); - let keys_manager = Arc::new(test_utils::TestKeysInterface::new( - &seed, - Network::Testnet, - Arc::clone(&logger), - )); + let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger))); let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new( chain_monitor.clone(), tx_broadcaster.clone(), @@ -1140,44 +1058,40 @@ pub fn create_network(node_count: usize, node_config: &[Option]) -> block_notifier.register_listener(weak_res); let mut default_config = UserConfig::default(); default_config.channel_options.announced_channel = true; - default_config - .peer_channel_config_limits - .force_announced_channel_preference = false; + default_config.peer_channel_config_limits + .force_announced_channel_preference = false; let node = ChannelManager::new( - Network::Testnet, - feeest.clone(), - chan_monitor.clone(), - tx_broadcaster.clone(), - Arc::clone(&logger), - keys_manager.clone(), - if node_config[i].is_some() { - node_config[i].clone().unwrap() - } else { - default_config - }, - 0, - ) - .unwrap(); + Network::Testnet, + feeest.clone(), + chan_monitor.clone(), + tx_broadcaster.clone(), + Arc::clone(&logger), + keys_manager.clone(), + if node_config[i].is_some() { + node_config[i].clone().unwrap() + } else { + default_config + }, + 0, + ).unwrap(); let weak_res = Arc::downgrade(&node); block_notifier.register_listener(weak_res); let router = Router::new( - PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), - chain_monitor.clone(), - Arc::clone(&logger), + PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), + chain_monitor.clone(), + Arc::clone(&logger), ); - nodes.push(Node { - chain_monitor, - tx_broadcaster, - chan_monitor, - node, - router, - keys_manager, - node_seed: seed, - network_payment_count: payment_count.clone(), - network_chan_count: chan_count.clone(), - block_notifier, - logger: test_logger, - }); + nodes.push(Node { chain_monitor, + tx_broadcaster, + chan_monitor, + node, + router, + keys_manager, + node_seed: seed, + network_payment_count: payment_count.clone(), + network_chan_count: chan_count.clone(), + block_notifier, + logger: test_logger }); } nodes @@ -1200,30 +1114,29 @@ pub enum HTLCType { /// /// All broadcast transactions must be accounted for in one of the above three types of we'll /// also fail. -pub fn test_txn_broadcast( - node: &Node, - chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), - commitment_tx: Option, - has_htlc_tx: HTLCType, -) -> Vec { +pub fn test_txn_broadcast(node: &Node, + chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), + commitment_tx: Option, + has_htlc_tx: HTLCType) + -> Vec { let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap(); assert!( - node_txn.len() - >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 } + node_txn.len() + >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 } ); let mut res = Vec::with_capacity(2); node_txn.retain(|tx| { - if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() { - check_spends!(tx, chan.3.clone()); - if commitment_tx.is_none() { - res.push(tx.clone()); - } - false - } else { - true - } - }); + if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() { + check_spends!(tx, chan.3.clone()); + if commitment_tx.is_none() { + res.push(tx.clone()); + } + false + } else { + true + } + }); if let Some(explicit_tx) = commitment_tx { res.push(explicit_tx.clone()); } @@ -1232,19 +1145,19 @@ pub fn test_txn_broadcast( if has_htlc_tx != HTLCType::NONE { node_txn.retain(|tx| { - if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() { - check_spends!(tx, res[0].clone()); - if has_htlc_tx == HTLCType::TIMEOUT { - assert!(tx.lock_time != 0); - } else { - assert!(tx.lock_time == 0); - } - res.push(tx.clone()); - false - } else { - true - } - }); + if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() { + check_spends!(tx, res[0].clone()); + if has_htlc_tx == HTLCType::TIMEOUT { + assert!(tx.lock_time != 0); + } else { + assert!(tx.lock_time == 0); + } + res.push(tx.clone()); + false + } else { + true + } + }); assert!(res.len() == 2 || res.len() == 3); if res.len() == 3 { assert_eq!(res[1], res[2]); @@ -1265,17 +1178,17 @@ pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transactio assert!(false); } node_txn.retain(|tx| { - if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() { - check_spends!(tx, revoked_tx); - false - } else { - true - } - }); + if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() { + check_spends!(tx, revoked_tx); + false + } else { + true + } + }); node_txn.retain(|tx| { - check_spends!(tx, commitment_revoked_tx); - false - }); + check_spends!(tx, commitment_revoked_tx); + false + }); assert!(node_txn.is_empty()); } @@ -1402,16 +1315,14 @@ macro_rules! handle_chan_reestablish_msgs { /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas /// for claims/fails they are separated out. -pub fn reconnect_nodes( - node_a: &Node, - node_b: &Node, - send_funding_locked: (bool, bool), - pending_htlc_adds: (i64, i64), - pending_htlc_claims: (usize, usize), - pending_cell_htlc_claims: (usize, usize), - pending_cell_htlc_fails: (usize, usize), - pending_raa: (bool, bool), -) { +pub fn reconnect_nodes(node_a: &Node, + node_b: &Node, + send_funding_locked: (bool, bool), + pending_htlc_adds: (i64, i64), + pending_htlc_claims: (usize, usize), + pending_cell_htlc_claims: (usize, usize), + pending_cell_htlc_fails: (usize, usize), + pending_raa: (bool, bool)) { node_a.node.peer_connected(&node_b.node.get_our_node_id()); let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b); node_b.node.peer_connected(&node_a.node.get_our_node_id()); @@ -1444,9 +1355,8 @@ pub fn reconnect_nodes( let mut resp_1 = Vec::new(); for msg in reestablish_1 { - node_b - .node - .handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg); + node_b.node + .handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg); resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a)); } if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 { @@ -1457,9 +1367,8 @@ pub fn reconnect_nodes( let mut resp_2 = Vec::new(); for msg in reestablish_2 { - node_a - .node - .handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg); + node_a.node + .handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg); resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b)); } if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 { @@ -1470,21 +1379,20 @@ pub fn reconnect_nodes( // We don't yet support both needing updates, as that would require a different commitment dance: assert!( - (pending_htlc_adds.0 == 0 - && pending_htlc_claims.0 == 0 - && pending_cell_htlc_claims.0 == 0 - && pending_cell_htlc_fails.0 == 0) - || (pending_htlc_adds.1 == 0 - && pending_htlc_claims.1 == 0 - && pending_cell_htlc_claims.1 == 0 - && pending_cell_htlc_fails.1 == 0) + (pending_htlc_adds.0 == 0 + && pending_htlc_claims.0 == 0 + && pending_cell_htlc_claims.0 == 0 + && pending_cell_htlc_fails.0 == 0) + || (pending_htlc_adds.1 == 0 + && pending_htlc_claims.1 == 0 + && pending_cell_htlc_claims.1 == 0 + && pending_cell_htlc_fails.1 == 0) ); for chan_msgs in resp_1.drain(..) { if send_funding_locked.0 { - node_a - .node - .handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()); + node_a.node + .handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()); let announcement_event = node_a.node.get_and_clear_pending_msg_events(); if !announcement_event.is_empty() { assert_eq!(announcement_event.len(), 1); @@ -1499,18 +1407,17 @@ pub fn reconnect_nodes( } if pending_raa.0 { assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst); - node_a - .node - .handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()); + node_a.node + .handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()); assert!(node_a.node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(node_a, 1); } else { assert!(chan_msgs.1.is_none()); } if pending_htlc_adds.0 != 0 - || pending_htlc_claims.0 != 0 - || pending_cell_htlc_claims.0 != 0 - || pending_cell_htlc_fails.0 != 0 + || pending_htlc_claims.0 != 0 + || pending_cell_htlc_claims.0 != 0 + || pending_cell_htlc_fails.0 != 0 { let commitment_update = chan_msgs.2.unwrap(); if pending_htlc_adds.0 != -1 { @@ -1520,44 +1427,39 @@ pub fn reconnect_nodes( assert!(commitment_update.update_add_htlcs.is_empty()); } assert_eq!( - commitment_update.update_fulfill_htlcs.len(), - pending_htlc_claims.0 + pending_cell_htlc_claims.0 + commitment_update.update_fulfill_htlcs.len(), + pending_htlc_claims.0 + pending_cell_htlc_claims.0 ); assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0); assert!(commitment_update.update_fail_malformed_htlcs.is_empty()); for update_add in commitment_update.update_add_htlcs { - node_a - .node - .handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add); + node_a.node + .handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add); } for update_fulfill in commitment_update.update_fulfill_htlcs { - node_a - .node - .handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill); + node_a.node + .handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill); } for update_fail in commitment_update.update_fail_htlcs { - node_a - .node - .handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail); + node_a.node + .handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail); } if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false); } else { - node_a - .node - .handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed); + node_a.node + .handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed); check_added_monitors!(node_a, 1); let as_revoke_and_ack = get_event_msg!( - node_a, - MessageSendEvent::SendRevokeAndACK, - node_b.node.get_our_node_id() + node_a, + MessageSendEvent::SendRevokeAndACK, + node_b.node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes - node_b - .node - .handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack); + node_b.node + .handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack); assert!(node_b.node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(node_b, 1); } @@ -1568,9 +1470,8 @@ pub fn reconnect_nodes( for chan_msgs in resp_2.drain(..) { if send_funding_locked.1 { - node_b - .node - .handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()); + node_b.node + .handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()); let announcement_event = node_b.node.get_and_clear_pending_msg_events(); if !announcement_event.is_empty() { assert_eq!(announcement_event.len(), 1); @@ -1585,18 +1486,17 @@ pub fn reconnect_nodes( } if pending_raa.1 { assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst); - node_b - .node - .handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()); + node_b.node + .handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()); assert!(node_b.node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(node_b, 1); } else { assert!(chan_msgs.1.is_none()); } if pending_htlc_adds.1 != 0 - || pending_htlc_claims.1 != 0 - || pending_cell_htlc_claims.1 != 0 - || pending_cell_htlc_fails.1 != 0 + || pending_htlc_claims.1 != 0 + || pending_cell_htlc_claims.1 != 0 + || pending_cell_htlc_fails.1 != 0 { let commitment_update = chan_msgs.2.unwrap(); if pending_htlc_adds.1 != -1 { @@ -1604,44 +1504,39 @@ pub fn reconnect_nodes( assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize); } assert_eq!( - commitment_update.update_fulfill_htlcs.len(), - pending_htlc_claims.0 + pending_cell_htlc_claims.0 + commitment_update.update_fulfill_htlcs.len(), + pending_htlc_claims.0 + pending_cell_htlc_claims.0 ); assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0); assert!(commitment_update.update_fail_malformed_htlcs.is_empty()); for update_add in commitment_update.update_add_htlcs { - node_b - .node - .handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add); + node_b.node + .handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add); } for update_fulfill in commitment_update.update_fulfill_htlcs { - node_b - .node - .handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill); + node_b.node + .handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill); } for update_fail in commitment_update.update_fail_htlcs { - node_b - .node - .handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail); + node_b.node + .handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail); } if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false); } else { - node_b - .node - .handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed); + node_b.node + .handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed); check_added_monitors!(node_b, 1); let bs_revoke_and_ack = get_event_msg!( - node_b, - MessageSendEvent::SendRevokeAndACK, - node_a.node.get_our_node_id() + node_b, + MessageSendEvent::SendRevokeAndACK, + node_a.node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes - node_a - .node - .handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack); + node_a.node + .handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack); assert!(node_a.node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(node_a, 1); } diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index 545cc018d7e..c1b177da1a1 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -66,25 +66,24 @@ fn test_insane_channel_opens() { let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000; // Have node0 initiate a channel to node1 with aforementioned parameters - nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42) - .unwrap(); + nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42) + .unwrap(); // Extract the channel open message from node0 to node1 let open_channel_message = get_event_msg!( - nodes[0], - MessageSendEvent::SendOpenChannel, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() ); // Test helper that asserts we get the correct error string given a mutator // that supposedly makes the channel open message insane let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| { nodes[1].node.handle_open_channel( - &nodes[0].node.get_our_node_id(), - LocalFeatures::new(), - &message_mutator(open_channel_message.clone()), + &nodes[0].node.get_our_node_id(), + LocalFeatures::new(), + &message_mutator(open_channel_message.clone()), ); let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1); @@ -92,9 +91,9 @@ fn test_insane_channel_opens() { match action { &ErrorAction::SendErrorMessage { .. } => { nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - expected_error_str.to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + expected_error_str.to_string(), + 1, ); }, _ => panic!("unexpected event!"), @@ -139,11 +138,11 @@ fn test_insane_channel_opens() { }); insane_open_helper( - "They wanted our payments to be delayed by a needlessly long period", - |mut msg| { - msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; - msg - }, + "They wanted our payments to be delayed by a needlessly long period", + |mut msg| { + msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; + msg + }, ); insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { @@ -184,49 +183,42 @@ fn test_async_inbound_update_fee() { // (6) RAA is delivered -> // First nodes[0] generates an update_fee - nodes[0] - .node - .update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20) - .unwrap(); + nodes[0].node + .update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20) + .unwrap(); check_added_monitors!(nodes[0], 1); let events_0 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_0.len(), 1); let (update_msg, commitment_signed) = match events_0[0] { // (1) - MessageSendEvent::UpdateHTLCs { - updates: msgs::CommitmentUpdate { - ref update_fee, - ref commitment_signed, - .. - }, - .. - } => (update_fee.as_ref(), commitment_signed), + MessageSendEvent::UpdateHTLCs { updates: + msgs::CommitmentUpdate { ref update_fee, + ref commitment_signed, + .. }, + .. } => (update_fee.as_ref(), commitment_signed), _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]... let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); - nodes[1] - .node - .send_payment( - nodes[1] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 40000, - TEST_FINAL_CLTV, - ) - .unwrap(), - our_payment_hash, - ) - .unwrap(); + nodes[1].node + .send_payment( + nodes[1].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 40000, + TEST_FINAL_CLTV, + ) + .unwrap(), + our_payment_hash, + ) + .unwrap(); check_added_monitors!(nodes[1], 1); let payment_event = { @@ -238,35 +230,31 @@ fn test_async_inbound_update_fee() { assert_eq!(payment_event.msgs.len(), 1); // ...now when the messages get delivered everyone should be happy - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2) + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2) let as_revoke_and_ack = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); // deliver(1), generate (3): - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); let bs_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2) + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2) let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(bs_update.update_add_htlcs.is_empty()); // (4) assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4) @@ -275,9 +263,8 @@ fn test_async_inbound_update_fee() { assert!(bs_update.update_fee.is_none()); // (4) check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3) + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3) let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); assert!(as_update.update_add_htlcs.is_empty()); // (5) assert!(as_update.update_fulfill_htlcs.is_empty()); // (5) @@ -286,30 +273,27 @@ fn test_async_inbound_update_fee() { assert!(as_update.update_fee.is_none()); // (5) check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4) + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4) let as_second_revoke = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // only (6) so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5) + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5) let bs_second_revoke = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke); check_added_monitors!(nodes[0], 1); let events_2 = nodes[0].node.get_and_clear_pending_events(); @@ -319,9 +303,8 @@ fn test_async_inbound_update_fee() { _ => panic!("Unexpected event"), } - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6) + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6) check_added_monitors!(nodes[1], 1); } @@ -337,45 +320,39 @@ fn test_update_fee_unordered_raa() { send_payment(&nodes[0], &vec![&nodes[1]][..], 8000000, 8_000_000); // First nodes[0] generates an update_fee - nodes[0] - .node - .update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20) - .unwrap(); + nodes[0].node + .update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20) + .unwrap(); check_added_monitors!(nodes[0], 1); let events_0 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_0.len(), 1); let update_msg = match events_0[0] { // (1) - MessageSendEvent::UpdateHTLCs { - updates: msgs::CommitmentUpdate { ref update_fee, .. }, - .. - } => update_fee.as_ref(), + MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, + .. } => update_fee.as_ref(), _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]... let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); - nodes[1] - .node - .send_payment( - nodes[1] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 40000, - TEST_FINAL_CLTV, - ) - .unwrap(), - our_payment_hash, - ) - .unwrap(); + nodes[1].node + .send_payment( + nodes[1].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 40000, + TEST_FINAL_CLTV, + ) + .unwrap(), + our_payment_hash, + ) + .unwrap(); check_added_monitors!(nodes[1], 1); let payment_event = { @@ -387,23 +364,20 @@ fn test_update_fee_unordered_raa() { assert_eq!(payment_event.msgs.len(), 1); // ...now when the messages get delivered everyone should be happy - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2) + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2) let as_revoke_msg = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2) + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2) check_added_monitors!(nodes[1], 1); // We can't continue, sadly, because our (1) now has a bogus signature @@ -443,24 +417,19 @@ fn test_multi_flight_update_fee() { assert_eq!(events_0.len(), 1); let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1) - MessageSendEvent::UpdateHTLCs { - updates: msgs::CommitmentUpdate { - ref update_fee, - ref commitment_signed, - .. - }, - .. - } => (update_fee.as_ref().unwrap(), commitment_signed), + MessageSendEvent::UpdateHTLCs { updates: + msgs::CommitmentUpdate { ref update_fee, + ref commitment_signed, + .. }, + .. } => (update_fee.as_ref().unwrap(), commitment_signed), _ => panic!("Unexpected event"), }; // Deliver first update_fee/commitment_signed pair, generating (1) and (2): - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1); let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); check_added_monitors!(nodes[1], 1); @@ -471,25 +440,20 @@ fn test_multi_flight_update_fee() { assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); // Create the (3) update_fee message that nodes[0] will generate before it does... - let mut update_msg_2 = msgs::UpdateFee { - channel_id: update_msg_1.channel_id.clone(), - feerate_per_kw: (initial_feerate + 30) as u32, - }; + let mut update_msg_2 = msgs::UpdateFee { channel_id: update_msg_1.channel_id.clone(), + feerate_per_kw: (initial_feerate + 30) as u32 }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2); update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32; // Deliver (3) - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2); // Deliver (1), generating (3) and (4) - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg); let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); check_added_monitors!(nodes[0], 1); assert!(as_second_update.update_add_htlcs.is_empty()); @@ -498,59 +462,53 @@ fn test_multi_flight_update_fee() { assert!(as_second_update.update_fail_malformed_htlcs.is_empty()); // Check that the update_fee newly generated matches what we delivered: assert_eq!( - as_second_update.update_fee.as_ref().unwrap().channel_id, - update_msg_2.channel_id + as_second_update.update_fee.as_ref().unwrap().channel_id, + update_msg_2.channel_id ); assert_eq!( - as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, - update_msg_2.feerate_per_kw + as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, + update_msg_2.feerate_per_kw ); // Deliver (2) commitment_signed - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed); let as_revoke_msg = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); check_added_monitors!(nodes[0], 1); // No commitment_signed so get_event_msg's assert(len == 1) passes - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); // Delever (4) - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed); let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment); let as_second_revoke = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); } @@ -568,50 +526,43 @@ fn test_update_fee_vanilla() { let events_0 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_0.len(), 1); let (update_msg, commitment_signed) = match events_0[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - update_add_htlcs: _, - update_fulfill_htlcs: _, - update_fail_htlcs: _, - update_fail_malformed_htlcs: _, - ref update_fee, - ref commitment_signed, - }, - } => (update_fee.as_ref(), commitment_signed), + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { update_add_htlcs: _, + update_fulfill_htlcs: _, + update_fail_htlcs: _, + update_fail_malformed_htlcs: _, + ref update_fee, + ref commitment_signed, }, } => { + (update_fee.as_ref(), commitment_signed) + }, _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed); let revoke_msg = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); } @@ -621,13 +572,13 @@ fn test_update_fee_that_funder_cannot_afford() { let nodes = create_network(2, &[None, None]); let channel_value = 1888; let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - channel_value, - 700000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + channel_value, + 700000, + LocalFeatures::new(), + LocalFeatures::new(), ); let channel_id = chan.2; @@ -636,9 +587,8 @@ fn test_update_fee_that_funder_cannot_afford() { check_added_monitors!(nodes[0], 1); let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()); commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false); @@ -652,10 +602,10 @@ fn test_update_fee_that_funder_cannot_afford() { let num_htlcs = chan.channel_monitor().get_latest_local_commitment_txn()[0].output.len() - 2; let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000; - let mut actual_fee = chan.channel_monitor().get_latest_local_commitment_txn()[0] - .output - .iter() - .fold(0, |acc, output| acc + output.value); + let mut actual_fee = + chan.channel_monitor().get_latest_local_commitment_txn()[0].output + .iter() + .fold(0, |acc, output| acc + output.value); actual_fee = channel_value - actual_fee; assert_eq!(total_fee, actual_fee); } //drop the mutex @@ -667,20 +617,18 @@ fn test_update_fee_that_funder_cannot_afford() { let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()); //While producing the commitment_signed response after handling a received update_fee request the //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve) //Should produce and error. - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Funding remote cannot afford proposed new fee".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Funding remote cannot afford proposed new fee".to_string(), + 1, ); //clear the message we could not handle @@ -703,39 +651,34 @@ fn test_update_fee_with_fundee_update_add_htlc() { let events_0 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_0.len(), 1); let (update_msg, commitment_signed) = match events_0[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - update_add_htlcs: _, - update_fulfill_htlcs: _, - update_fail_htlcs: _, - update_fail_malformed_htlcs: _, - ref update_fee, - ref commitment_signed, - }, - } => (update_fee.as_ref(), commitment_signed), + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { update_add_htlcs: _, + update_fulfill_htlcs: _, + update_fail_htlcs: _, + update_fail_malformed_htlcs: _, + ref update_fee, + ref commitment_signed, }, } => { + (update_fee.as_ref(), commitment_signed) + }, _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); check_added_monitors!(nodes[1], 1); - let route = nodes[1] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 800000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 800000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]); @@ -750,25 +693,22 @@ fn test_update_fee_with_fundee_update_add_htlc() { assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); // node[1] has nothing to do - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed); let revoke_msg = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg); check_added_monitors!(nodes[1], 1); // AwaitingRemoteRevoke ends here @@ -779,35 +719,30 @@ fn test_update_fee_with_fundee_update_add_htlc() { assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0); assert_eq!(commitment_update.update_fee.is_none(), true); - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed); + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed); check_added_monitors!(nodes[0], 1); let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed); check_added_monitors!(nodes[1], 1); let revoke = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke); check_added_monitors!(nodes[0], 1); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); @@ -855,35 +790,30 @@ fn test_update_fee() { let events_0 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_0.len(), 1); let (update_msg, commitment_signed) = match events_0[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - update_add_htlcs: _, - update_fulfill_htlcs: _, - update_fail_htlcs: _, - update_fail_malformed_htlcs: _, - ref update_fee, - ref commitment_signed, - }, - } => (update_fee.as_ref(), commitment_signed), + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { update_add_htlcs: _, + update_fulfill_htlcs: _, + update_fail_htlcs: _, + update_fail_malformed_htlcs: _, + ref update_fee, + ref commitment_signed, }, } => { + (update_fee.as_ref(), commitment_signed) + }, _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); // Generate (2) and (3): - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); check_added_monitors!(nodes[1], 1); // Deliver (2): - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); @@ -893,59 +823,52 @@ fn test_update_fee() { let events_0 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_0.len(), 1); let (update_msg, commitment_signed) = match events_0[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - update_add_htlcs: _, - update_fulfill_htlcs: _, - update_fail_htlcs: _, - update_fail_malformed_htlcs: _, - ref update_fee, - ref commitment_signed, - }, - } => (update_fee.as_ref(), commitment_signed), + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { update_add_htlcs: _, + update_fulfill_htlcs: _, + update_fail_htlcs: _, + update_fail_malformed_htlcs: _, + ref update_fee, + ref commitment_signed, }, } => { + (update_fee.as_ref(), commitment_signed) + }, _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); + nodes[1].node + .handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed); check_added_monitors!(nodes[1], 1); // ... creating (5) let revoke_msg = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes // Handle (3), creating (6): - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0); check_added_monitors!(nodes[0], 1); let revoke_msg_0 = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes // Deliver (5): - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); // Deliver (6), creating (7): - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0); let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(commitment_update.update_add_htlcs.is_empty()); assert!(commitment_update.update_fulfill_htlcs.is_empty()); @@ -955,20 +878,18 @@ fn test_update_fee() { check_added_monitors!(nodes[1], 1); // Deliver (7) - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed); check_added_monitors!(nodes[0], 1); let revoke_msg = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -982,69 +903,58 @@ fn pre_funding_lock_shutdown_test() { // Test sending a shutdown prior to funding_locked after funding generation let nodes = create_network(2, &[None, None]); let tx = create_chan_between_nodes_with_value_init( - &nodes[0], - &nodes[1], - 8000000, - 0, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + &nodes[0], + &nodes[1], + 8000000, + 0, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![tx.clone()], - }, - 1, + &Block { header, + txdata: vec![tx.clone()], }, + 1, ); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![tx.clone()], - }, - 1, + &Block { header, + txdata: vec![tx.clone()], }, + 1, ); - nodes[0] - .node - .close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()) - .unwrap(); + nodes[0].node + .close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()) + .unwrap(); let node_0_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); let node_1_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); let node_0_closing_signed = get_event_msg!( - nodes[0], - MessageSendEvent::SendClosingSigned, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendClosingSigned, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); + nodes[1].node + .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); + nodes[0].node + .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id()); assert!(node_0_none.is_none()); @@ -1058,34 +968,30 @@ fn updates_shutdown_wait() { let mut nodes = create_network(3, &[None, None, None]); let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new()); - let route_1 = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); - let route_2 = nodes[1] - .router - .get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); + let route_1 = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); + let route_2 = nodes[1].router + .get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000); nodes[0].node.close_channel(&chan_1.2).unwrap(); let node_0_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); let node_1_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -1108,9 +1014,8 @@ fn updates_shutdown_wait() { assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); assert_eq!(updates.update_fulfill_htlcs.len(), 1); - nodes[1] - .node - .handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); + nodes[1].node + .handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); check_added_monitors!(nodes[1], 1); let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false); @@ -1120,9 +1025,8 @@ fn updates_shutdown_wait() { assert!(updates_2.update_fail_malformed_htlcs.is_empty()); assert!(updates_2.update_fee.is_none()); assert_eq!(updates_2.update_fulfill_htlcs.len(), 1); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_events(); @@ -1135,17 +1039,15 @@ fn updates_shutdown_wait() { } let node_0_closing_signed = get_event_msg!( - nodes[0], - MessageSendEvent::SendClosingSigned, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendClosingSigned, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); + nodes[1].node + .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); + nodes[0].node + .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id()); assert!(node_0_none.is_none()); @@ -1165,10 +1067,9 @@ fn htlc_fail_async_shutdown() { let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); @@ -1181,29 +1082,25 @@ fn htlc_fail_async_shutdown() { nodes[1].node.close_channel(&chan_1.2).unwrap(); let node_1_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); let node_0_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed); check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false); let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); @@ -1213,19 +1110,16 @@ fn htlc_fail_async_shutdown() { assert!(updates_2.update_fail_malformed_htlcs.is_empty()); assert!(updates_2.update_fee.is_none()); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { - Event::PaymentFailed { - ref payment_hash, - ref rejected_by_dest, - .. - } => { + Event::PaymentFailed { ref payment_hash, + ref rejected_by_dest, + .. } => { assert_eq!(our_payment_hash, *payment_hash); assert!(!rejected_by_dest); }, @@ -1242,22 +1136,20 @@ fn htlc_fail_async_shutdown() { _ => panic!("Unexpected event"), }; match msg_events[1] { - MessageSendEvent::PaymentFailureNetworkUpdate { - update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }, - } => { + MessageSendEvent::PaymentFailureNetworkUpdate { update: + msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref + msg, }, } => { assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id); }, _ => panic!("Unexpected event"), } assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[1] - .node - .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); + nodes[1].node + .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); + nodes[0].node + .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id()); assert!(node_0_none.is_none()); @@ -1281,23 +1173,21 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { nodes[1].node.close_channel(&chan_1.2).unwrap(); let node_1_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() ); if recv_count > 0 { - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown); let node_0_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ); if recv_count > 1 { - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); } } @@ -1306,54 +1196,49 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id()); let node_0_reestablish = get_event_msg!( - nodes[0], - MessageSendEvent::SendChannelReestablish, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendChannelReestablish, + nodes[1].node.get_our_node_id() ); nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); let node_1_reestablish = get_event_msg!( - nodes[1], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish); let node_1_2nd_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() ); assert!(node_1_shutdown == node_1_2nd_shutdown); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish); let node_0_2nd_shutdown = if recv_count > 0 { let node_0_2nd_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown); node_0_2nd_shutdown } else { assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown); get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ) }; - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -1366,9 +1251,8 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); assert_eq!(updates.update_fulfill_htlcs.len(), 1); - nodes[1] - .node - .handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); + nodes[1].node + .handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); check_added_monitors!(nodes[1], 1); let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false); @@ -1378,9 +1262,8 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { assert!(updates_2.update_fail_malformed_htlcs.is_empty()); assert!(updates_2.update_fee.is_none()); assert_eq!(updates_2.update_fulfill_htlcs.len(), 1); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_events(); @@ -1393,14 +1276,13 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { } let node_0_closing_signed = get_event_msg!( - nodes[0], - MessageSendEvent::SendClosingSigned, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendClosingSigned, + nodes[1].node.get_our_node_id() ); if recv_count > 0 { - nodes[1] - .node - .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); + nodes[1].node + .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed); let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); assert!(node_1_closing_signed.is_some()); } @@ -1410,61 +1292,55 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id()); let node_0_2nd_reestablish = get_event_msg!( - nodes[0], - MessageSendEvent::SendChannelReestablish, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendChannelReestablish, + nodes[1].node.get_our_node_id() ); nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); if recv_count == 0 { // If all closing_signeds weren't delivered we can just resume where we left off... let node_1_2nd_reestablish = get_event_msg!( - nodes[1], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish); let node_0_3rd_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() ); assert!(node_0_2nd_shutdown == node_0_3rd_shutdown); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish); let node_1_3rd_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() ); assert!(node_1_3rd_shutdown == node_1_2nd_shutdown); - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown); let node_0_2nd_closing_signed = get_event_msg!( - nodes[0], - MessageSendEvent::SendClosingSigned, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendClosingSigned, + nodes[1].node.get_our_node_id() ); assert!(node_0_closing_signed == node_0_2nd_closing_signed); - nodes[1] - .node - .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed); + nodes[1].node + .handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed); let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); + nodes[0].node + .handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()); let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id()); assert!(node_0_none.is_none()); } else { @@ -1477,9 +1353,8 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) { // transaction. assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish); let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1); if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] { @@ -1529,37 +1404,37 @@ fn fake_network_test() { // Rebalance the network a bit by relaying one payment through all the channels... send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3]][..], + 8000000, + 8_000_000, ); send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3]][..], + 8000000, + 8_000_000, ); send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3]][..], + 8000000, + 8_000_000, ); send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3]][..], + 8000000, + 8_000_000, ); // Send some more payments send_payment(&nodes[1], &vec![&nodes[2], &nodes[3]][..], 1000000, 1_000_000); send_payment( - &nodes[3], - &vec![&nodes[2], &nodes[1], &nodes[0]][..], - 1000000, - 1_000_000, + &nodes[3], + &vec![&nodes[2], &nodes[1], &nodes[0]][..], + 1000000, + 1_000_000, ); send_payment(&nodes[3], &vec![&nodes[2], &nodes[1]][..], 1000000, 1_000_000); @@ -1580,74 +1455,60 @@ fn fake_network_test() { // Do some rebalance loop payments, simultaneously let mut hops = Vec::with_capacity(3); - hops.push(RouteHop { - pubkey: nodes[2].node.get_our_node_id(), - short_channel_id: chan_2.0.contents.short_channel_id, - fee_msat: 0, - cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32, - }); - hops.push(RouteHop { - pubkey: nodes[3].node.get_our_node_id(), - short_channel_id: chan_3.0.contents.short_channel_id, - fee_msat: 0, - cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32, - }); - hops.push(RouteHop { - pubkey: nodes[1].node.get_our_node_id(), - short_channel_id: chan_4.0.contents.short_channel_id, - fee_msat: 1000000, - cltv_expiry_delta: TEST_FINAL_CLTV, - }); + hops.push(RouteHop { pubkey: nodes[2].node.get_our_node_id(), + short_channel_id: chan_2.0.contents.short_channel_id, + fee_msat: 0, + cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32 }); + hops.push(RouteHop { pubkey: nodes[3].node.get_our_node_id(), + short_channel_id: chan_3.0.contents.short_channel_id, + fee_msat: 0, + cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32 }); + hops.push(RouteHop { pubkey: nodes[1].node.get_our_node_id(), + short_channel_id: chan_4.0.contents.short_channel_id, + fee_msat: 1000000, + cltv_expiry_delta: TEST_FINAL_CLTV }); hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 - + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000; + + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000; hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 - + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000; + + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000; let payment_preimage_1 = send_along_route( - &nodes[1], - Route { hops }, - &vec![&nodes[2], &nodes[3], &nodes[1]][..], - 1000000, - ) - .0; + &nodes[1], + Route { hops }, + &vec![&nodes[2], &nodes[3], &nodes[1]][..], + 1000000, + ).0; let mut hops = Vec::with_capacity(3); - hops.push(RouteHop { - pubkey: nodes[3].node.get_our_node_id(), - short_channel_id: chan_4.0.contents.short_channel_id, - fee_msat: 0, - cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32, - }); - hops.push(RouteHop { - pubkey: nodes[2].node.get_our_node_id(), - short_channel_id: chan_3.0.contents.short_channel_id, - fee_msat: 0, - cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32, - }); - hops.push(RouteHop { - pubkey: nodes[1].node.get_our_node_id(), - short_channel_id: chan_2.0.contents.short_channel_id, - fee_msat: 1000000, - cltv_expiry_delta: TEST_FINAL_CLTV, - }); + hops.push(RouteHop { pubkey: nodes[3].node.get_our_node_id(), + short_channel_id: chan_4.0.contents.short_channel_id, + fee_msat: 0, + cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32 }); + hops.push(RouteHop { pubkey: nodes[2].node.get_our_node_id(), + short_channel_id: chan_3.0.contents.short_channel_id, + fee_msat: 0, + cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32 }); + hops.push(RouteHop { pubkey: nodes[1].node.get_our_node_id(), + short_channel_id: chan_2.0.contents.short_channel_id, + fee_msat: 1000000, + cltv_expiry_delta: TEST_FINAL_CLTV }); hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 - + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000; + + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000; hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 - + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000; + + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000; let payment_hash_2 = send_along_route( - &nodes[1], - Route { hops }, - &vec![&nodes[3], &nodes[2], &nodes[1]][..], - 1000000, - ) - .1; + &nodes[1], + Route { hops }, + &vec![&nodes[3], &nodes[2], &nodes[1]][..], + 1000000, + ).1; // Claim the rebalances... fail_payment(&nodes[1], &vec![&nodes[3], &nodes[2], &nodes[1]][..], payment_hash_2); claim_payment( - &nodes[1], - &vec![&nodes[2], &nodes[3], &nodes[1]][..], - payment_preimage_1, - 1_000_000, + &nodes[1], + &vec![&nodes[2], &nodes[3], &nodes[1]][..], + payment_preimage_1, + 1_000_000, ); // Add a duplicate new channel from 2 to 4 @@ -1670,22 +1531,22 @@ fn fake_network_test() { //TODO: Test that routes work again here as we've been notified that the channel is full claim_payment( - &nodes[0], - &vec![&nodes[1], &nodes[3]][..], - payment_preimage_3, - 3_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[3]][..], + payment_preimage_3, + 3_000_000, ); claim_payment( - &nodes[0], - &vec![&nodes[1], &nodes[3]][..], - payment_preimage_4, - 3_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[3]][..], + payment_preimage_4, + 3_000_000, ); claim_payment( - &nodes[0], - &vec![&nodes[1], &nodes[3]][..], - payment_preimage_5, - 3_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[3]][..], + payment_preimage_5, + 3_000_000, ); // Close down the channels... @@ -1707,16 +1568,15 @@ fn holding_cell_htlc_counting() { let mut payments = Vec::new(); for _ in 0..::ln::channel::OUR_MAX_HTLCS { - let route = nodes[1] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 100000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 100000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[1].node.send_payment(route, payment_hash).unwrap(); payments.push((payment_preimage, payment_hash)); @@ -1731,16 +1591,15 @@ fn holding_cell_htlc_counting() { // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in // the holding cell waiting on B's RAA to send. At this point we should not be able to add // another HTLC. - let route = nodes[1] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 100000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 100000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() { assert_eq!(err, "Cannot push more than their max accepted HTLCs"); @@ -1749,22 +1608,21 @@ fn holding_cell_htlc_counting() { } assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); nodes[1].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Cannot push more than their max accepted HTLCs".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Cannot push more than their max accepted HTLCs".to_string(), + 1, ); // This should also be true if we try to forward a payment. - let route = nodes[0] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 100000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 100000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash_2).unwrap(); check_added_monitors!(nodes[0], 1); @@ -1774,9 +1632,8 @@ fn holding_cell_htlc_counting() { let payment_event = SendEvent::from_event(events.pop().unwrap()); assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); // We have to forward pending HTLCs twice - once tries to forward the payment forward (and // fails), the second will process the resulting failure and fail the HTLC backward. @@ -1785,17 +1642,16 @@ fn holding_cell_htlc_counting() { check_added_monitors!(nodes[1], 1); let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { - MessageSendEvent::PaymentFailureNetworkUpdate { - update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }, - } => { + MessageSendEvent::PaymentFailureNetworkUpdate { update: + msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref + msg, }, } => { assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id); }, _ => panic!("Unexpected event"), @@ -1804,11 +1660,9 @@ fn holding_cell_htlc_counting() { let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { - Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } => { + Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } => { assert_eq!(payment_hash, payment_hash_2); assert!(!rejected_by_dest); }, @@ -1816,63 +1670,53 @@ fn holding_cell_htlc_counting() { } // Now forward all the pending HTLCs and claim them back - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]); - nodes[2] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]); + nodes[2].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg); check_added_monitors!(nodes[2], 1); let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); check_added_monitors!(nodes[1], 1); let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id()); - nodes[1] - .node - .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed); check_added_monitors!(nodes[1], 1); let as_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[2].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[2].node.get_our_node_id() ); for ref update in as_updates.update_add_htlcs.iter() { - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update); } - nodes[2] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed); + nodes[2].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed); check_added_monitors!(nodes[2], 1); - nodes[2] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); + nodes[2].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[2], 1); let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack); check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed); check_added_monitors!(nodes[1], 1); let as_final_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[2].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[2].node.get_our_node_id() ); - nodes[2] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa); + nodes[2].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa); check_added_monitors!(nodes[2], 1); expect_pending_htlcs_forwardable!(nodes[2]); @@ -1912,14 +1756,14 @@ fn duplicate_htlc_test() { *nodes[0].network_payment_count.borrow_mut() -= 1; assert_eq!( - route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, - payment_preimage + route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, + payment_preimage ); *nodes[0].network_payment_count.borrow_mut() -= 1; assert_eq!( - route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, - payment_preimage + route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, + payment_preimage ); claim_payment(&nodes[0], &vec![&nodes[3], &nodes[4]][..], payment_preimage, 1_000_000); @@ -1941,16 +1785,15 @@ fn test_duplicate_htlc_different_direction_onchain() { let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec![&nodes[1]][..], 900_000); - let route = nodes[1] - .router - .get_route( - &nodes[0].node.get_our_node_id(), - None, - &Vec::new(), - 800_000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[0].node.get_our_node_id(), + None, + &Vec::new(), + 800_000, + TEST_FINAL_CLTV, + ) + .unwrap(); send_along_route_with_hash(&nodes[1], route, &vec![&nodes[0]][..], 800_000, payment_hash); // Provide preimage to node 0 by claiming payment @@ -1958,16 +1801,15 @@ fn test_duplicate_htlc_different_direction_onchain() { check_added_monitors!(nodes[0], 1); // Broadcast node 1 commitment txn - let remote_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let remote_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound let mut has_both_htlcs = 0; // check htlcs match ones committed @@ -1980,20 +1822,16 @@ fn test_duplicate_htlc_different_direction_onchain() { } assert_eq!(has_both_htlcs, 2); - let header = BlockHeader { - version: 0x2000_0000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x2000_0000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![remote_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![remote_txn[0].clone()], }, + 1, ); // Check we only broadcast 1 timeout tx @@ -2010,14 +1848,14 @@ fn test_duplicate_htlc_different_direction_onchain() { assert_eq!(claim_txn[1], claim_txn[6]); assert_eq!(htlc_pair.0.input.len(), 1); assert_eq!( - htlc_pair.0.input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + htlc_pair.0.input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); // HTLC 1 <--> 0, preimage tx check_spends!(htlc_pair.0, remote_txn[0].clone()); assert_eq!(htlc_pair.1.input.len(), 1); assert_eq!( - htlc_pair.1.input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + htlc_pair.1.input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); // HTLC 0 <--> 1, timeout tx check_spends!(htlc_pair.1, remote_txn[0].clone()); @@ -2026,17 +1864,13 @@ fn test_duplicate_htlc_different_direction_onchain() { for e in events { match e { MessageSendEvent::BroadcastChannelUpdate { .. } => {}, - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fail_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); @@ -2051,22 +1885,22 @@ fn test_duplicate_htlc_different_direction_onchain() { fn do_channel_reserve_test(test_recv: bool) { let mut nodes = create_network(3, &[None, None, None]); let chan_1 = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1900, - 1001, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1900, + 1001, + LocalFeatures::new(), + LocalFeatures::new(), ); let chan_2 = create_announced_chan_between_nodes_with_value( - &nodes, - 1, - 2, - 1900, - 1001, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 1, + 2, + 1900, + 1001, + LocalFeatures::new(), + LocalFeatures::new(), ); let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2); @@ -2129,22 +1963,20 @@ fn do_channel_reserve_test(test_recv: bool) { send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0); htlc_id += 1; - let (stat01_, stat11_, stat12_, stat22_) = ( - get_channel_value_stat!(nodes[0], chan_1.2), - get_channel_value_stat!(nodes[1], chan_1.2), - get_channel_value_stat!(nodes[1], chan_2.2), - get_channel_value_stat!(nodes[2], chan_2.2), - ); + let (stat01_, stat11_, stat12_, stat22_) = (get_channel_value_stat!(nodes[0], chan_1.2), + get_channel_value_stat!(nodes[1], chan_1.2), + get_channel_value_stat!(nodes[1], chan_2.2), + get_channel_value_stat!(nodes[2], chan_2.2)); assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat); assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat); assert_eq!( - stat12_.value_to_self_msat, - stat12.value_to_self_msat - (amt_msat - feemsat) + stat12_.value_to_self_msat, + stat12.value_to_self_msat - (amt_msat - feemsat) ); assert_eq!( - stat22_.value_to_self_msat, - stat22.value_to_self_msat + (amt_msat - feemsat) + stat22_.value_to_self_msat, + stat22.value_to_self_msat + (amt_msat - feemsat) ); stat01 = stat01_; stat11 = stat11_; @@ -2156,11 +1988,10 @@ fn do_channel_reserve_test(test_recv: bool) { let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat; // attempt to get channel_reserve violation let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1); - let err = nodes[0] - .node - .send_payment(route.clone(), our_payment_hash) - .err() - .unwrap(); + let err = nodes[0].node + .send_payment(route.clone(), our_payment_hash) + .err() + .unwrap(); match err { APIError::ChannelUnavailable { err } => { assert_eq!(err, "Cannot send value that would put us over their reserve value") @@ -2169,9 +2000,9 @@ fn do_channel_reserve_test(test_recv: bool) { } assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Cannot send value that would put us over their reserve value".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Cannot send value that would put us over their reserve value".to_string(), + 1, ); } @@ -2188,9 +2019,8 @@ fn do_channel_reserve_test(test_recv: bool) { assert_eq!(events.len(), 1); SendEvent::from_event(events.remove(0)) }; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]); // channel reserve test with htlc pending output > 0 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat; @@ -2204,9 +2034,9 @@ fn do_channel_reserve_test(test_recv: bool) { } assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Cannot send value that would put us over their reserve value".to_string(), - 2, + "lightning::ln::channelmanager".to_string(), + "Cannot send value that would put us over their reserve value".to_string(), + 2, ); } @@ -2217,30 +2047,26 @@ fn do_channel_reserve_test(test_recv: bool) { // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc() let secp_ctx = Secp256k1::new(); let session_priv = SecretKey::from_slice(&{ - let mut session_key = [0; 32]; - let mut rng = thread_rng(); - rng.fill_bytes(&mut session_key); - session_key - }) - .expect("RNG is bad!"); + let mut session_key = [0; 32]; + let mut rng = thread_rng(); + rng.fill_bytes(&mut session_key); + session_key + }).expect("RNG is bad!"); let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1; let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap(); let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap(); let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash); - let msg = msgs::UpdateAddHTLC { - channel_id: chan_1.2, - htlc_id, - amount_msat: htlc_msat, - payment_hash: our_payment_hash, - cltv_expiry: htlc_cltv, - onion_routing_packet: onion_packet, - }; + let msg = msgs::UpdateAddHTLC { channel_id: chan_1.2, + htlc_id, + amount_msat: htlc_msat, + payment_hash: our_payment_hash, + cltv_expiry: htlc_cltv, + onion_routing_packet: onion_packet }; if test_recv { - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg); // If we send a garbage message, the channel should get closed, making the rest of this test case fail. assert_eq!(nodes[1].node.list_channels().len(), 1); assert_eq!(nodes[1].node.list_channels().len(), 1); @@ -2256,11 +2082,13 @@ fn do_channel_reserve_test(test_recv: bool) { { let stat = get_channel_value_stat!(nodes[0], chan_1.2); assert_eq!( - stat.value_to_self_msat - - (stat.pending_outbound_htlcs_amount_msat - + recv_value_21 + recv_value_22 - + total_fee_msat + total_fee_msat), - stat.channel_reserve_msat + stat.value_to_self_msat + - (stat.pending_outbound_htlcs_amount_msat + + recv_value_21 + + recv_value_22 + + total_fee_msat + + total_fee_msat), + stat.channel_reserve_msat ); } @@ -2283,9 +2111,9 @@ fn do_channel_reserve_test(test_recv: bool) { } assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Cannot send value that would put us over their reserve value".to_string(), - 3, + "lightning::ln::channelmanager".to_string(), + "Cannot send value that would put us over their reserve value".to_string(), + 3, ); } @@ -2297,41 +2125,36 @@ fn do_channel_reserve_test(test_recv: bool) { assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); // flush the pending htlc - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg); let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack); check_added_monitors!(nodes[0], 1); let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed); let bs_revoke_and_ack = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); expect_pending_htlcs_forwardable!(nodes[1]); let ref payment_event_11 = expect_forward!(nodes[1]); - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]); commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[2]); @@ -2340,24 +2163,22 @@ fn do_channel_reserve_test(test_recv: bool) { // flush the htlcs in the holding cell assert_eq!(commitment_update_2.update_add_htlcs.len(), 2); nodes[1].node.handle_update_add_htlc( - &nodes[0].node.get_our_node_id(), - &commitment_update_2.update_add_htlcs[0], + &nodes[0].node.get_our_node_id(), + &commitment_update_2.update_add_htlcs[0], ); nodes[1].node.handle_update_add_htlc( - &nodes[0].node.get_our_node_id(), - &commitment_update_2.update_add_htlcs[1], + &nodes[0].node.get_our_node_id(), + &commitment_update_2.update_add_htlcs[1], ); commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false); expect_pending_htlcs_forwardable!(nodes[1]); let ref payment_event_3 = expect_forward!(nodes[1]); assert_eq!(payment_event_3.msgs.len(), 2); - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]); - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]); commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[2]); @@ -2380,36 +2201,36 @@ fn do_channel_reserve_test(test_recv: bool) { } claim_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2]], - our_payment_preimage_1, - recv_value_1, + &nodes[0], + &vec![&nodes[1], &nodes[2]], + our_payment_preimage_1, + recv_value_1, ); claim_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2]], - our_payment_preimage_21, - recv_value_21, + &nodes[0], + &vec![&nodes[1], &nodes[2]], + our_payment_preimage_21, + recv_value_21, ); claim_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2]], - our_payment_preimage_22, - recv_value_22, + &nodes[0], + &vec![&nodes[1], &nodes[2]], + our_payment_preimage_22, + recv_value_22, ); let expected_value_to_self = stat01.value_to_self_msat - - (recv_value_1 + total_fee_msat) - - (recv_value_21 + total_fee_msat) - - (recv_value_22 + total_fee_msat); + - (recv_value_1 + total_fee_msat) + - (recv_value_21 + total_fee_msat) + - (recv_value_22 + total_fee_msat); let stat0 = get_channel_value_stat!(nodes[0], chan_1.2); assert_eq!(stat0.value_to_self_msat, expected_value_to_self); assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat); let stat2 = get_channel_value_stat!(nodes[2], chan_2.2); assert_eq!( - stat2.value_to_self_msat, - stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + stat2.value_to_self_msat, + stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 ); } @@ -2448,20 +2269,20 @@ fn channel_reserve_in_flight_removes() { let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2); // Route the first two HTLCs. - let (payment_preimage_1, _) = route_payment( - &nodes[0], - &[&nodes[1]], - b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000, - ); + let (payment_preimage_1, _) = + route_payment( + &nodes[0], + &[&nodes[1]], + b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000, + ); let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000); // Start routing the third HTLC (this is just used to get everyone in the right state). let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]); let send_1 = { - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); nodes[0].node.send_payment(route, payment_hash_3).unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); @@ -2484,54 +2305,47 @@ fn channel_reserve_in_flight_removes() { check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); expect_payment_sent!(nodes[0], payment_preimage_1); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg); check_added_monitors!(nodes[1], 1); // B is already AwaitingRAA, so cant generate a CS here let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); check_added_monitors!(nodes[0], 1); let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed); check_added_monitors!(nodes[1], 1); let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the @@ -2539,23 +2353,20 @@ fn channel_reserve_in_flight_removes() { // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A // can no longer broadcast a commitment transaction with it and B has the preimage so can go // on-chain as necessary). - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); expect_payment_sent!(nodes[0], payment_preimage_2); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -2564,9 +2375,8 @@ fn channel_reserve_in_flight_removes() { // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't // resolve the second HTLC from A's point of view. - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); check_added_monitors!(nodes[0], 1); let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); @@ -2574,10 +2384,9 @@ fn channel_reserve_in_flight_removes() { // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing. let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]); let send_2 = { - let route = nodes[1] - .router - .get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[1].router + .get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV) + .unwrap(); nodes[1].node.send_payment(route, payment_hash_4).unwrap(); check_added_monitors!(nodes[1], 1); let mut events = nodes[1].node.get_and_clear_pending_msg_events(); @@ -2585,55 +2394,48 @@ fn channel_reserve_in_flight_removes() { SendEvent::from_event(events.remove(0)) }; - nodes[0] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg); + nodes[0].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg); check_added_monitors!(nodes[0], 1); let as_raa = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // Now just resolve all the outstanding messages/HTLCs for completeness... - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed); check_added_monitors!(nodes[1], 1); let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); check_added_monitors!(nodes[0], 1); let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed); check_added_monitors!(nodes[1], 1); let bs_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa); check_added_monitors!(nodes[0], 1); expect_pending_htlcs_forwardable!(nodes[0]); @@ -2657,48 +2459,44 @@ fn channel_monitor_network_test() { // Rebalance the network a bit by relaying one payment through all the channels... send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], + 8000000, + 8_000_000, ); send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], + 8000000, + 8_000_000, ); send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], + 8000000, + 8_000_000, ); send_payment( - &nodes[0], - &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], - 8000000, - 8_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2], &nodes[3], &nodes[4]][..], + 8000000, + 8_000_000, ); // Simple case with no pending HTLCs: nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true); { let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn.drain(..).next().unwrap()], - }, - 1, + &Block { header, + txdata: vec![node_txn.drain(..).next().unwrap()], }, + 1, ); test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE); } @@ -2713,20 +2511,16 @@ fn channel_monitor_network_test() { nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true); { let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn.drain(..).next().unwrap()], - }, - 1, + &Block { header, + txdata: vec![node_txn.drain(..).next().unwrap()], }, + 1, ); test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE); } @@ -2763,20 +2557,16 @@ fn channel_monitor_network_test() { // Claim the payment on nodes[3], giving it knowledge of the preimage claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[3].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![node_txn[0].clone()], }, + 1, ); check_preimage_claim(&nodes[3], &node_txn); @@ -2787,17 +2577,14 @@ fn channel_monitor_network_test() { { // Cheat and reset nodes[4]'s height to 1 - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - nodes[4] - .block_notifier - .block_connected(&Block { header, txdata: vec![] }, 1); + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + nodes[4].block_notifier + .block_connected(&Block { header, txdata: vec![] }, 1); } assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1); @@ -2808,41 +2595,35 @@ fn channel_monitor_network_test() { // buffer space). { - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - nodes[3] - .block_notifier - .block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]); + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + nodes[3].block_notifier + .block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]); for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 { - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - nodes[3] - .block_notifier - .block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]); + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + nodes[3].block_notifier + .block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]); } // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer. { let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap(); node_txn.retain(|tx| { - if tx.input[0].previous_output.txid == node2_commitment_txid { - false - } else { - true - } - }); + if tx.input[0].previous_output.txid == node2_commitment_txid { + false + } else { + true + } + }); } let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT); @@ -2850,48 +2631,38 @@ fn channel_monitor_network_test() { // Claim the payment on nodes[4], giving it knowledge of the preimage claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000); - header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; - nodes[4] - .block_notifier - .block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]); + nodes[4].block_notifier + .block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]); for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 { - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - nodes[4] - .block_notifier - .block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]); + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + nodes[4].block_notifier + .block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]); } test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS); - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[4].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone()], - }, - TEST_FINAL_CLTV - 5, + &Block { header, + txdata: vec![node_txn[0].clone()], }, + TEST_FINAL_CLTV - 5, ); check_preimage_claim(&nodes[4], &node_txn); @@ -2906,9 +2677,8 @@ fn test_justice_tx() { // Test justice txn built on revoked HTLC-Success tx, against both sides let mut alice_config = UserConfig::default(); alice_config.channel_options.announced_channel = true; - alice_config - .peer_channel_config_limits - .force_announced_channel_preference = false; + alice_config.peer_channel_config_limits + .force_announced_channel_preference = false; alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5; let mut bob_config = UserConfig::default(); bob_config.channel_options.announced_channel = true; @@ -2922,49 +2692,44 @@ fn test_justice_tx() { // A pending HTLC which will be revoked: let payment_preimage_3 = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; // Get the will-be-revoked local txn from nodes[0] - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .iter_mut() - .next() - .unwrap() - .1 - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .iter_mut() + .next() + .unwrap() + .1 + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid()); assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present assert_eq!(revoked_local_txn[1].input.len(), 1); assert_eq!( - revoked_local_txn[1].input[0].previous_output.txid, - revoked_local_txn[0].txid() + revoked_local_txn[1].input[0].previous_output.txid, + revoked_local_txn[0].txid() ); assert_eq!( - revoked_local_txn[1].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + revoked_local_txn[1].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); // HTLC-Timeout // Revoke the old state claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage_3, 3_000_000); { - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); { let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); @@ -2979,32 +2744,26 @@ fn test_justice_tx() { test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE); nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); let node_txn = test_txn_broadcast( - &nodes[0], - &chan_5, - Some(revoked_local_txn[0].clone()), - HTLCType::TIMEOUT, + &nodes[0], + &chan_5, + Some(revoked_local_txn[0].clone()), + HTLCType::TIMEOUT, ); - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[1].clone()], - }, - 1, + &Block { header, + txdata: vec![node_txn[1].clone()], }, + 1, ); test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone()); } @@ -3024,18 +2783,17 @@ fn test_justice_tx() { // A pending HTLC which will be revoked: let payment_preimage_4 = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; // Get the will-be-revoked local txn from B - let revoked_local_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .iter_mut() - .next() - .unwrap() - .1 - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .iter_mut() + .next() + .unwrap() + .1 + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid()); @@ -3043,20 +2801,16 @@ fn test_justice_tx() { // Revoke the old state claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage_4, 3_000_000); { - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); { let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap(); @@ -3070,32 +2824,26 @@ fn test_justice_tx() { test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); let node_txn = test_txn_broadcast( - &nodes[1], - &chan_6, - Some(revoked_local_txn[0].clone()), - HTLCType::SUCCESS, + &nodes[1], + &chan_6, + Some(revoked_local_txn[0].clone()), + HTLCType::SUCCESS, ); - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[1].clone()], - }, - 1, + &Block { header, + txdata: vec![node_txn[1].clone()], }, + 1, ); test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone()); } @@ -3111,16 +2859,15 @@ fn revoked_output_claim() { let nodes = create_network(2, &[None, None]); let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn.len(), 1); // Only output is the full channel value back to nodes[0]: assert_eq!(revoked_local_txn[0].output.len(), 1); @@ -3128,20 +2875,16 @@ fn revoked_output_claim() { send_payment(&nodes[0], &vec![&nodes[1]][..], 5000000, 5_000_000); // Inform nodes[1] that nodes[0] broadcast a stale tx - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once @@ -3153,11 +2896,9 @@ fn revoked_output_claim() { // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); get_announce_close_broadcast_events(&nodes, 0, 1); } @@ -3177,27 +2918,26 @@ fn claim_htlc_outputs_shared_tx() { let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec![&nodes[0]][..], 3000000); // Get the will-be-revoked local txn from node[0] - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid()); assert_eq!(revoked_local_txn[1].input.len(), 1); assert_eq!( - revoked_local_txn[1].input[0].previous_output.txid, - revoked_local_txn[0].txid() + revoked_local_txn[1].input[0].previous_output.txid, + revoked_local_txn[0].txid() ); assert_eq!( - revoked_local_txn[1].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + revoked_local_txn[1].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); // HTLC-Timeout check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone()); @@ -3205,34 +2945,28 @@ fn claim_htlc_outputs_shared_tx() { claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage_1, 3_000_000); { - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); connect_blocks( - &nodes[1].block_notifier, - ANTI_REORG_DELAY - 1, - 1, - true, - header.bitcoin_hash(), + &nodes[1].block_notifier, + ANTI_REORG_DELAY - 1, + 1, + true, + header.bitcoin_hash(), ); let events = nodes[1].node.get_and_clear_pending_events(); @@ -3260,8 +2994,8 @@ fn claim_htlc_outputs_shared_tx() { assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC assert_eq!( - *witness_lens.iter().skip(2).next().unwrap(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + *witness_lens.iter().skip(2).next().unwrap(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); // revoked received HTLC // Next nodes[1] broadcasts its current local tx state: @@ -3273,12 +3007,12 @@ fn claim_htlc_outputs_shared_tx() { assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid()); assert_ne!( - node_txn[2].input[0].previous_output.txid, - node_txn[0].input[0].previous_output.txid + node_txn[2].input[0].previous_output.txid, + node_txn[0].input[0].previous_output.txid ); assert_ne!( - node_txn[2].input[0].previous_output.txid, - node_txn[0].input[1].previous_output.txid + node_txn[2].input[0].previous_output.txid, + node_txn[0].input[1].previous_output.txid ); } get_announce_close_broadcast_events(&nodes, 0, 1); @@ -3301,49 +3035,42 @@ fn claim_htlc_outputs_single_tx() { let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec![&nodes[0]][..], 3000000); // Get the will-be-revoked local txn from node[0] - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); //Revoke the old state claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage_1, 3_000_000); { - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 200, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 200, ); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 200, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 200, ); connect_blocks( - &nodes[1].block_notifier, - ANTI_REORG_DELAY - 1, - 200, - true, - header.bitcoin_hash(), + &nodes[1].block_notifier, + ANTI_REORG_DELAY - 1, + 200, + true, + header.bitcoin_hash(), ); let events = nodes[1].node.get_and_clear_pending_events(); @@ -3389,8 +3116,8 @@ fn claim_htlc_outputs_single_tx() { assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC assert_eq!( - *witness_lens.iter().skip(2).next().unwrap(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + *witness_lens.iter().skip(2).next().unwrap(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); // revoked received HTLC assert_eq!(node_txn[3].input.len(), 1); @@ -3401,12 +3128,12 @@ fn claim_htlc_outputs_single_tx() { assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid()); assert_ne!( - node_txn[4].input[0].previous_output.txid, - node_txn[0].input[0].previous_output.txid + node_txn[4].input[0].previous_output.txid, + node_txn[0].input[0].previous_output.txid ); assert_ne!( - node_txn[4].input[0].previous_output.txid, - node_txn[1].input[0].previous_output.txid + node_txn[4].input[0].previous_output.txid, + node_txn[1].input[0].previous_output.txid ); } get_announce_close_broadcast_events(&nodes, 0, 1); @@ -3442,27 +3169,24 @@ fn test_htlc_on_chain_success() { let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]], 3000000); let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]], 3000000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; // Broadcast legit commitment tx from C on B's chain // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain - let commitment_tx = nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_2.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let commitment_tx = nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_2.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(commitment_tx.len(), 1); check_spends!(commitment_tx[0], chan_2.3.clone()); nodes[2].node.claim_funds(our_payment_preimage, 3_000_000); @@ -3475,11 +3199,9 @@ fn test_htlc_on_chain_success() { assert_eq!(updates.update_fulfill_htlcs.len(), 1); nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[2], false); let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx) @@ -3492,12 +3214,12 @@ fn test_htlc_on_chain_success() { check_spends!(node_txn[0], commitment_tx[0].clone()); check_spends!(node_txn[1], commitment_tx[0].clone()); assert_eq!( - node_txn[0].input[0].witness.clone().last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + node_txn[0].input[0].witness.clone().last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); assert_eq!( - node_txn[1].input[0].witness.clone().last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + node_txn[1].input[0].witness.clone().last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output @@ -3506,11 +3228,9 @@ fn test_htlc_on_chain_success() { // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: node_txn, - }, - 1, + &Block { header, + txdata: node_txn, }, + 1, ); let events = nodes[1].node.get_and_clear_pending_msg_events(); { @@ -3526,17 +3246,13 @@ fn test_htlc_on_chain_success() { _ => panic!("Unexpected event"), } match events[1] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fail_htlcs, - ref update_fulfill_htlcs, - ref update_fail_malformed_htlcs, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fail_htlcs, + ref update_fulfill_htlcs, + ref update_fail_malformed_htlcs, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fail_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); @@ -3587,23 +3303,20 @@ fn test_htlc_on_chain_success() { // Broadcast legit commitment tx from A on B's chain // Broadcast preimage tx by B on offered output from A commitment tx on A's chain - let commitment_tx = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let commitment_tx = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); check_spends!(commitment_tx[0], chan_1.3.clone()); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + 2*HTLC-Success), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan) @@ -3612,12 +3325,12 @@ fn test_htlc_on_chain_success() { check_spends!(node_txn[0], commitment_tx[0].clone()); assert_eq!(node_txn[0].input.len(), 2); assert_eq!( - node_txn[0].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[0].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); assert_eq!( - node_txn[0].input[1].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[0].input[1].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); assert_eq!(node_txn[0].lock_time, 0); assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment @@ -3630,11 +3343,9 @@ fn test_htlc_on_chain_success() { // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[0], false); let events = nodes[0].node.get_and_clear_pending_events(); @@ -3677,26 +3388,23 @@ fn test_htlc_on_chain_timeout() { send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], 8000000, 8_000_000); let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]], 3000000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; // Broadcast legit commitment tx from C on B's chain - let commitment_tx = nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_2.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let commitment_tx = nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_2.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); check_spends!(commitment_tx[0], chan_2.3.clone()); nodes[2].node.fail_htlc_backwards(&payment_hash); check_added_monitors!(nodes[2], 0); @@ -3706,17 +3414,13 @@ fn test_htlc_on_chain_timeout() { let events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(!update_fail_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); @@ -3726,11 +3430,9 @@ fn test_htlc_on_chain_timeout() { _ => panic!("Unexpected event"), }; nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[2], false); let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx) @@ -3741,11 +3443,9 @@ fn test_htlc_on_chain_timeout() { // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 200, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 200, ); let timeout_tx; { @@ -3756,40 +3456,38 @@ fn test_htlc_on_chain_timeout() { assert_eq!(node_txn[2], node_txn[7]); check_spends!(node_txn[0], commitment_tx[0].clone()); assert_eq!( - node_txn[0].clone().input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + node_txn[0].clone().input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); check_spends!(node_txn[1], chan_2.3.clone()); check_spends!(node_txn[2], node_txn[1].clone()); assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71); assert_eq!( - node_txn[2].clone().input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[2].clone().input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); check_spends!(node_txn[3], chan_2.3.clone()); check_spends!(node_txn[4], node_txn[3].clone()); assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71); assert_eq!( - node_txn[4].input[0].witness.clone().last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[4].input[0].witness.clone().last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); timeout_tx = node_txn[0].clone(); node_txn.clear(); } nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![timeout_tx], - }, - 1, + &Block { header, + txdata: vec![timeout_tx], }, + 1, ); connect_blocks( - &nodes[1].block_notifier, - ANTI_REORG_DELAY - 1, - 1, - true, - header.bitcoin_hash(), + &nodes[1].block_notifier, + ANTI_REORG_DELAY - 1, + 1, + true, + header.bitcoin_hash(), ); check_added_monitors!(nodes[1], 0); check_closed_broadcast!(nodes[1], false); @@ -3799,17 +3497,13 @@ fn test_htlc_on_chain_timeout() { let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fail_htlcs, - ref update_fulfill_htlcs, - ref update_fail_malformed_htlcs, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fail_htlcs, + ref update_fulfill_htlcs, + ref update_fail_malformed_htlcs, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(!update_fail_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); @@ -3822,24 +3516,21 @@ fn test_htlc_on_chain_timeout() { assert_eq!(node_txn.len(), 0); // Broadcast legit commitment tx from B on A's chain - let commitment_tx = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let commitment_tx = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); check_spends!(commitment_tx[0], chan_1.3.clone()); nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 200, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 200, ); check_closed_broadcast!(nodes[0], false); let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan @@ -3847,15 +3538,15 @@ fn test_htlc_on_chain_timeout() { assert_eq!(node_txn[0], node_txn[3]); check_spends!(node_txn[0], commitment_tx[0].clone()); assert_eq!( - node_txn[0].clone().input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + node_txn[0].clone().input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); check_spends!(node_txn[1], chan_1.3.clone()); check_spends!(node_txn[2], node_txn[1].clone()); assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71); assert_eq!( - node_txn[2].clone().input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[2].clone().input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); } @@ -3872,42 +3563,37 @@ fn test_simple_commitment_revoked_fail_backward() { let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000); // Get the will-be-revoked local txn from nodes[2] - let revoked_local_txn = nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_2.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_2.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); // Revoke the old state claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000); route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); connect_blocks( - &nodes[1].block_notifier, - ANTI_REORG_DELAY - 1, - 1, - true, - header.bitcoin_hash(), + &nodes[1].block_notifier, + ANTI_REORG_DELAY - 1, + 1, + true, + header.bitcoin_hash(), ); check_added_monitors!(nodes[1], 0); check_closed_broadcast!(nodes[1], false); @@ -3917,27 +3603,22 @@ fn test_simple_commitment_revoked_fail_backward() { let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fail_htlcs, - ref update_fulfill_htlcs, - ref update_fail_malformed_htlcs, - ref commitment_signed, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fail_htlcs, + ref update_fulfill_htlcs, + ref update_fail_malformed_htlcs, + ref commitment_signed, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert_eq!(update_fail_htlcs.len(), 1); assert!(update_fulfill_htlcs.is_empty()); assert!(update_fail_malformed_htlcs.is_empty()); assert_eq!(nodes[0].node.get_our_node_id(), *node_id); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_msg_events(); @@ -3980,43 +3661,41 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new()); let (payment_preimage, _payment_hash) = route_payment( - &nodes[0], - &[&nodes[1], &nodes[2]], - if no_to_remote { 10_000 } else { 3_000_000 }, + &nodes[0], + &[&nodes[1], &nodes[2]], + if no_to_remote { 10_000 } else { 3_000_000 }, ); // Get the will-be-revoked local txn from nodes[2] - let revoked_local_txn = nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_2.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_2.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 }); // Revoke the old state claim_payment( - &nodes[0], - &[&nodes[1], &nodes[2]], - payment_preimage, - if no_to_remote { 10_000 } else { 3_000_000 }, + &nodes[0], + &[&nodes[1], &nodes[2]], + payment_preimage, + if no_to_remote { 10_000 } else { 3_000_000 }, ); let value = if use_dust { // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as // well, so HTLCs at exactly the dust limit will not be included in commitment txn. - nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan_2.2) - .unwrap() - .our_dust_limit_satoshis - * 1000 + nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan_2.2) + .unwrap() + .our_dust_limit_satoshis + * 1000 } else { 3000000 }; @@ -4034,9 +3713,8 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use assert!(updates.update_fail_malformed_htlcs.is_empty()); assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fee.is_none()); - nodes[1] - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[1].node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true); // Drop the last RAA from 3 -> 2 @@ -4049,22 +3727,19 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use assert!(updates.update_fail_malformed_htlcs.is_empty()); assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fee.is_none()); - nodes[1] - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); - nodes[1] - .node - .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed); + nodes[1].node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[1].node + .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed); check_added_monitors!(nodes[1], 1); // Note that nodes[1] is in AwaitingRAA, so won't send a CS let as_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[2].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[2].node.get_our_node_id() ); - nodes[2] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); + nodes[2].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[2], 1); assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash)); @@ -4076,38 +3751,34 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use assert!(updates.update_fail_malformed_htlcs.is_empty()); assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fee.is_none()); - nodes[1] - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[1].node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); // At this point first_payment_hash has dropped out of the latest two commitment // transactions that nodes[1] is tracking... - nodes[1] - .node - .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed); check_added_monitors!(nodes[1], 1); // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS let as_raa = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[2].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[2].node.get_our_node_id() ); - nodes[2] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); + nodes[2].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa); check_added_monitors!(nodes[2], 1); // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting // on nodes[2]'s RAA. - let route = nodes[1] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[1].node.send_payment(route, fourth_payment_hash).unwrap(); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); @@ -4115,9 +3786,8 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use check_added_monitors!(nodes[1], 0); if deliver_bs_raa { - nodes[1] - .node - .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa); + nodes[1].node + .handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa); // One monitor for the new revocation preimage, no second on as we won't generate a new // commitment transaction for nodes[0] until process_pending_htlc_forwards(). check_added_monitors!(nodes[1], 1); @@ -4134,27 +3804,23 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use let mut failed_htlcs = HashSet::new(); assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); connect_blocks( - &nodes[1].block_notifier, - ANTI_REORG_DELAY - 1, - 1, - true, - header.bitcoin_hash(), + &nodes[1].block_notifier, + ANTI_REORG_DELAY - 1, + 1, + true, + header.bitcoin_hash(), ); let events = nodes[1].node.get_and_clear_pending_events(); @@ -4177,24 +3843,18 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 }); match events[if deliver_bs_raa { 1 } else { 0 }] { - MessageSendEvent::BroadcastChannelUpdate { - msg: msgs::ChannelUpdate { .. }, - } => {}, + MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. }, } => {}, _ => panic!("Unexpected event"), } if deliver_bs_raa { match events[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fail_htlcs, - ref update_fulfill_htlcs, - ref update_fail_malformed_htlcs, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fail_htlcs, + ref update_fulfill_htlcs, + ref update_fail_malformed_htlcs, + .. }, } => { assert_eq!(nodes[2].node.get_our_node_id(), *node_id); assert_eq!(update_add_htlcs.len(), 1); assert!(update_fulfill_htlcs.is_empty()); @@ -4205,33 +3865,26 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use } } match events[if deliver_bs_raa { 2 } else { 1 }] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fail_htlcs, - ref update_fulfill_htlcs, - ref update_fail_malformed_htlcs, - ref commitment_signed, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fail_htlcs, + ref update_fulfill_htlcs, + ref update_fail_malformed_htlcs, + ref commitment_signed, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert_eq!(update_fail_htlcs.len(), 3); assert!(update_fulfill_htlcs.is_empty()); assert!(update_fail_malformed_htlcs.is_empty()); assert_eq!(nodes[0].node.get_our_node_id(), *node_id); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]); commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true); @@ -4298,39 +3951,32 @@ fn test_htlc_ignore_latest_remote_commitment() { create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); route_payment(&nodes[0], &[&nodes[1]], 10000000); - nodes[0] - .node - .force_close_channel(&nodes[0].node.list_channels()[0].channel_id); + nodes[0].node + .force_close_channel(&nodes[0].node.list_channels()[0].channel_id); check_closed_broadcast!(nodes[0], false); let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap(); assert_eq!(node_txn.len(), 2); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone(), node_txn[1].clone()], - }, - 1, + &Block { header, + txdata: vec![node_txn[0].clone(), node_txn[1].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); // Duplicate the block_connected call since this may happen due to other listeners // registering new transactions nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone(), node_txn[1].clone()], - }, - 1, + &Block { header, + txdata: vec![node_txn[0].clone(), node_txn[1].clone()], }, + 1, ); } @@ -4341,10 +3987,9 @@ fn test_force_close_fail_back() { create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42) + .unwrap(); let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); @@ -4357,9 +4002,8 @@ fn test_force_close_fail_back() { SendEvent::from_event(events.remove(0)) }; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); @@ -4370,12 +4014,10 @@ fn test_force_close_fail_back() { assert_eq!(payment_event.msgs.len(), 1); check_added_monitors!(nodes[1], 1); - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); - nodes[2] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[2].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); check_added_monitors!(nodes[2], 1); let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id()); @@ -4383,9 +4025,8 @@ fn test_force_close_fail_back() { // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!). - nodes[2] - .node - .force_close_channel(&payment_event.commitment_msg.channel_id); + nodes[2].node + .force_close_channel(&payment_event.commitment_msg.channel_id); check_closed_broadcast!(nodes[2], false); let tx = { let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap(); @@ -4396,17 +4037,14 @@ fn test_force_close_fail_back() { node_txn.remove(0) }; - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - nodes[1] - .block_notifier - .block_connected_checked(&header, 1, &[&tx], &[1]); + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + nodes[1].block_notifier + .block_connected_checked(&header, 1, &[&tx], &[1]); // Note no UpdateHTLCs event here from nodes[1] to nodes[0]! check_closed_broadcast!(nodes[1], false); @@ -4422,9 +4060,8 @@ fn test_force_close_fail_back() { .unwrap() .provide_payment_preimage(&our_payment_hash, &our_payment_preimage); } - nodes[2] - .block_notifier - .block_connected_checked(&header, 1, &[&tx], &[1]); + nodes[2].block_notifier + .block_connected_checked(&header, 1, &[&tx], &[1]); let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap(); assert_eq!(node_txn.len(), 1); assert_eq!(node_txn[0].input.len(), 1); @@ -4447,24 +4084,20 @@ fn test_unconf_chan() { mem::drop(channel_state); let mut headers = Vec::new(); - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; headers.push(header.clone()); for _i in 2..100 { - header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; headers.push(header.clone()); } let mut height = 99; @@ -4488,14 +4121,14 @@ fn test_simple_peer_disconnect() { nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (true, true), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (true, true), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); let payment_preimage_1 = route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], 1000000).0; @@ -4506,14 +4139,14 @@ fn test_simple_peer_disconnect() { nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); let payment_preimage_3 = route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], 1000000).0; @@ -4525,23 +4158,23 @@ fn test_simple_peer_disconnect() { nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); claim_payment_along_route( - &nodes[0], - &vec![&nodes[1], &nodes[2]], - true, - payment_preimage_3, - 1_000_000, + &nodes[0], + &vec![&nodes[1], &nodes[2]], + true, + payment_preimage_3, + 1_000_000, ); fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (1, 0), - (1, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (1, 0), + (1, 0), + (false, false), ); { let events = nodes[0].node.get_and_clear_pending_events(); @@ -4553,11 +4186,9 @@ fn test_simple_peer_disconnect() { _ => panic!("Unexpected event"), } match events[1] { - Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } => { + Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } => { assert_eq!(payment_hash, payment_hash_5); assert!(rejected_by_dest); }, @@ -4574,28 +4205,27 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { let mut nodes = create_network(2, &[None, None]); if messages_delivered == 0 { create_chan_between_nodes_with_value_a( - &nodes[0], - &nodes[1], - 100000, - 10001, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes[0], + &nodes[1], + 100000, + 10001, + LocalFeatures::new(), + LocalFeatures::new(), ); // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect) } else { create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); } - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - Some(&nodes[0].node.list_usable_channels()), - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + Some(&nodes[0].node.list_usable_channels()), + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]); let payment_event = { @@ -4611,40 +4241,35 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { if messages_delivered < 2 { // Drop the payment_event messages, and let them get re-generated in reconnect_nodes! } else { - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); if messages_delivered >= 3 { - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg); check_added_monitors!(nodes[1], 1); let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); if messages_delivered >= 4 { - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); if messages_delivered >= 5 { - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed); let as_revoke_and_ack = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); if messages_delivered >= 6 { - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); } @@ -4659,62 +4284,62 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { // Even if the funding_locked messages get exchanged, as long as nothing further was // received on either side, both sides will need to resend them. reconnect_nodes( - &nodes[0], - &nodes[1], - (true, true), - (0, 1), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (true, true), + (0, 1), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } else if messages_delivered == 3 { // nodes[0] still wants its RAA + commitment_signed reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (-1, 0), - (0, 0), - (0, 0), - (0, 0), - (true, false), + &nodes[0], + &nodes[1], + (false, false), + (-1, 0), + (0, 0), + (0, 0), + (0, 0), + (true, false), ); } else if messages_delivered == 4 { // nodes[0] still wants its commitment_signed reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (-1, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (-1, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } else if messages_delivered == 5 { // nodes[1] still wants its final RAA reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, true), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, true), ); } else if messages_delivered == 6 { // Everything was delivered... reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } @@ -4728,14 +4353,14 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); nodes[1].node.process_pending_htlc_forwards(); @@ -4756,28 +4381,22 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { let events_3 = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events_3.len(), 1); let (update_fulfill_htlc, commitment_signed) = match events_3[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - ref updates, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + ref updates, } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); assert!(updates.update_add_htlcs.is_empty()); assert!(updates.update_fail_htlcs.is_empty()); assert_eq!(updates.update_fulfill_htlcs.len(), 1); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - ( - updates.update_fulfill_htlcs[0].clone(), - updates.commitment_signed.clone(), - ) + (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone()) }, _ => panic!("Unexpected event"), }; if messages_delivered >= 1 { - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc); let events_4 = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events_4.len(), 1); @@ -4789,36 +4408,32 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { } if messages_delivered >= 2 { - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed); check_added_monitors!(nodes[0], 1); let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); if messages_delivered >= 3 { - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); if messages_delivered >= 4 { - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed); let bs_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[1], 1); if messages_delivered >= 5 { - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); } @@ -4831,14 +4446,14 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); if messages_delivered < 2 { reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (1, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (1, 0), + (0, 0), + (0, 0), + (false, false), ); //TODO: Deduplicate PaymentSent events, then enable this if: //if messages_delivered < 1 { @@ -4854,64 +4469,64 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) { } else if messages_delivered == 2 { // nodes[0] still wants its RAA + commitment_signed reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, -1), - (0, 0), - (0, 0), - (0, 0), - (false, true), + &nodes[0], + &nodes[1], + (false, false), + (0, -1), + (0, 0), + (0, 0), + (0, 0), + (false, true), ); } else if messages_delivered == 3 { // nodes[0] still wants its commitment_signed reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, -1), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, -1), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } else if messages_delivered == 4 { // nodes[1] still wants its final RAA reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (true, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (true, false), ); } else if messages_delivered == 5 { // Everything was delivered... reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); } nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); // Channel should still work fine... @@ -4939,12 +4554,12 @@ fn test_funding_peer_disconnect() { // Test that we can lock in our funding tx while disconnected let nodes = create_network(2, &[None, None]); let tx = create_chan_between_nodes_with_value_init( - &nodes[0], - &nodes[1], - 100000, - 10001, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes[0], + &nodes[1], + 100000, + 10001, + LocalFeatures::new(), + LocalFeatures::new(), ); nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); @@ -4961,14 +4576,14 @@ fn test_funding_peer_disconnect() { } reconnect_nodes( - &nodes[0], - &nodes[1], - (false, true), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, true), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); @@ -4993,22 +4608,20 @@ fn test_funding_peer_disconnect() { }; reconnect_nodes( - &nodes[0], - &nodes[1], - (true, true), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), - ); - - nodes[0] - .node - .handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked); - nodes[0] - .node - .handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs); + &nodes[0], + &nodes[1], + (true, true), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), + ); + + nodes[0].node + .handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked); + nodes[0].node + .handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs); let events_3 = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events_3.len(), 2); let as_announcement_sigs = match events_3[0] { @@ -5019,23 +4632,18 @@ fn test_funding_peer_disconnect() { _ => panic!("Unexpected event"), }; let (as_announcement, as_update) = match events_3[1] { - MessageSendEvent::BroadcastChannelAnnouncement { - ref msg, - ref update_msg, - } => (msg.clone(), update_msg.clone()), + MessageSendEvent::BroadcastChannelAnnouncement { ref msg, + ref update_msg, } => (msg.clone(), update_msg.clone()), _ => panic!("Unexpected event"), }; - nodes[1] - .node - .handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs); + nodes[1].node + .handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs); let events_4 = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events_4.len(), 1); let (_, bs_update) = match events_4[0] { - MessageSendEvent::BroadcastChannelAnnouncement { - ref msg, - ref update_msg, - } => (msg.clone(), update_msg.clone()), + MessageSendEvent::BroadcastChannelAnnouncement { ref msg, + ref update_msg, } => (msg.clone(), update_msg.clone()), _ => panic!("Unexpected event"), }; @@ -5043,16 +4651,15 @@ fn test_funding_peer_disconnect() { nodes[0].router.handle_channel_update(&bs_update).unwrap(); nodes[0].router.handle_channel_update(&as_update).unwrap(); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000); claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000); } @@ -5067,16 +4674,15 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000); // Now try to send a second payment which will fail to send - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap(); @@ -5095,18 +4701,14 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { let events_2 = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events_2.len(), 1); match events_2[0] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - ref commitment_signed, - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + ref commitment_signed, }, } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); assert!(update_add_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); @@ -5114,9 +4716,8 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { assert!(update_fail_malformed_htlcs.is_empty()); assert!(update_fee.is_none()); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]); let events_3 = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events_3.len(), 1); match events_3[0] { @@ -5126,13 +4727,12 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { _ => panic!("Unexpected event"), } - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed); let _ = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); @@ -5150,13 +4750,11 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]); assert_eq!(reestablish_2.len(), 1); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]); assert!(as_resp.0.is_none()); @@ -5173,24 +4771,23 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); assert!(as_resp.2.as_ref().unwrap().update_fee.is_none()); nodes[1].node.handle_update_add_htlc( - &nodes[0].node.get_our_node_id(), - &as_resp.2.as_ref().unwrap().update_add_htlcs[0], + &nodes[0].node.get_our_node_id(), + &as_resp.2.as_ref().unwrap().update_add_htlcs[0], ); nodes[1].node.handle_commitment_signed( - &nodes[0].node.get_our_node_id(), - &as_resp.2.as_ref().unwrap().commitment_signed, + &nodes[0].node.get_our_node_id(), + &as_resp.2.as_ref().unwrap().commitment_signed, ); let bs_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()); let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(bs_second_commitment_signed.update_add_htlcs.is_empty()); assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty()); @@ -5199,9 +4796,8 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { assert!(bs_second_commitment_signed.update_fee.is_none()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); assert!(as_commitment_signed.update_add_htlcs.is_empty()); assert!(as_commitment_signed.update_fulfill_htlcs.is_empty()); @@ -5211,32 +4807,31 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { check_added_monitors!(nodes[0], 1); nodes[0].node.handle_commitment_signed( - &nodes[1].node.get_our_node_id(), - &bs_second_commitment_signed.commitment_signed, + &nodes[1].node.get_our_node_id(), + &bs_second_commitment_signed.commitment_signed, ); let as_revoke_and_ack = get_event_msg!( - nodes[0], - MessageSendEvent::SendRevokeAndACK, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[0], 1); nodes[1].node.handle_commitment_signed( - &nodes[0].node.get_our_node_id(), - &as_commitment_signed.commitment_signed, + &nodes[0].node.get_our_node_id(), + &as_commitment_signed.commitment_signed, ); let bs_second_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); // No commitment_signed so get_event_msg's assert(len == 1) passes check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[1], 1); @@ -5245,18 +4840,15 @@ fn test_drop_messages_peer_disconnect_dual_htlc() { let events_5 = nodes[1].node.get_and_clear_pending_events(); assert_eq!(events_5.len(), 1); match events_5[0] { - Event::PaymentReceived { - ref payment_hash, - amt: _, - } => { + Event::PaymentReceived { ref payment_hash, + amt: _, } => { assert_eq!(payment_hash_2, *payment_hash); }, _ => panic!("Unexpected event"), } - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors!(nodes[0], 1); @@ -5313,8 +4905,8 @@ fn test_invalid_channel_announcement() { let unsigned_msg = dummy_unsigned_msg!(); sign_msg!(unsigned_msg); assert_eq!( - nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), - true + nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), + true ); let _ = nodes[0] .router @@ -5340,41 +4932,42 @@ fn test_no_txn_manager_serialize_deserialize() { let mut nodes = create_network(2, &[None, None]); let tx = create_chan_between_nodes_with_value_init( - &nodes[0], - &nodes[1], - 100000, - 10001, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes[0], + &nodes[1], + 100000, + 10001, + LocalFeatures::new(), + LocalFeatures::new(), ); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false); let nodes_0_serialized = nodes[0].node.encode(); let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new()); - nodes[0] - .chan_monitor - .simple_monitor - .monitors - .lock() - .unwrap() - .iter() - .next() - .unwrap() - .1 - .write_for_disk(&mut chan_0_monitor_serialized) - .unwrap(); - - nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new( - nodes[0].chain_monitor.clone(), - nodes[0].tx_broadcaster.clone(), - Arc::new(test_utils::TestLogger::new()), - Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }), - )); + nodes[0].chan_monitor + .simple_monitor + .monitors + .lock() + .unwrap() + .iter() + .next() + .unwrap() + .1 + .write_for_disk(&mut chan_0_monitor_serialized) + .unwrap(); + + nodes[0].chan_monitor = + Arc::new(test_utils::TestChannelMonitor::new( + nodes[0].chain_monitor.clone(), + nodes[0].tx_broadcaster.clone(), + Arc::new(test_utils::TestLogger::new()), + Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }), + )); let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..]; - let (_, mut chan_0_monitor) = - <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())) - .unwrap(); + let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read( + &mut chan_0_monitor_read, + Arc::new(test_utils::TestLogger::new()), + ).unwrap(); assert!(chan_0_monitor_read.is_empty()); let mut nodes_0_read = &nodes_0_serialized[..]; @@ -5403,15 +4996,13 @@ fn test_no_txn_manager_serialize_deserialize() { }; assert!(nodes_0_read.is_empty()); - assert!(nodes[0] - .chan_monitor - .add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor) - .is_ok()); + assert!(nodes[0].chan_monitor + .add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor) + .is_ok()); nodes[0].node = Arc::new(nodes_0_deserialized); let nodes_0_as_listener: Arc = nodes[0].node.clone(); - nodes[0] - .block_notifier - .register_listener(Arc::downgrade(&nodes_0_as_listener)); + nodes[0].block_notifier + .register_listener(Arc::downgrade(&nodes_0_as_listener)); assert_eq!(nodes[0].node.list_channels().len(), 1); check_added_monitors!(nodes[0], 1); @@ -5420,13 +5011,11 @@ fn test_no_txn_manager_serialize_deserialize() { nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx); @@ -5453,29 +5042,30 @@ fn test_simple_manager_serialize_deserialize() { let nodes_0_serialized = nodes[0].node.encode(); let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new()); - nodes[0] - .chan_monitor - .simple_monitor - .monitors - .lock() - .unwrap() - .iter() - .next() - .unwrap() - .1 - .write_for_disk(&mut chan_0_monitor_serialized) - .unwrap(); - - nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new( - nodes[0].chain_monitor.clone(), - nodes[0].tx_broadcaster.clone(), - Arc::new(test_utils::TestLogger::new()), - Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }), - )); + nodes[0].chan_monitor + .simple_monitor + .monitors + .lock() + .unwrap() + .iter() + .next() + .unwrap() + .1 + .write_for_disk(&mut chan_0_monitor_serialized) + .unwrap(); + + nodes[0].chan_monitor = + Arc::new(test_utils::TestChannelMonitor::new( + nodes[0].chain_monitor.clone(), + nodes[0].tx_broadcaster.clone(), + Arc::new(test_utils::TestLogger::new()), + Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }), + )); let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..]; - let (_, mut chan_0_monitor) = - <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())) - .unwrap(); + let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read( + &mut chan_0_monitor_read, + Arc::new(test_utils::TestLogger::new()), + ).unwrap(); assert!(chan_0_monitor_read.is_empty()); let mut nodes_0_read = &nodes_0_serialized[..]; @@ -5503,22 +5093,21 @@ fn test_simple_manager_serialize_deserialize() { }; assert!(nodes_0_read.is_empty()); - assert!(nodes[0] - .chan_monitor - .add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor) - .is_ok()); + assert!(nodes[0].chan_monitor + .add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor) + .is_ok()); nodes[0].node = Arc::new(nodes_0_deserialized); check_added_monitors!(nodes[0], 1); reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash); @@ -5553,12 +5142,13 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { node_0_monitors_serialized.push(writer.0); } - nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new( - nodes[0].chain_monitor.clone(), - nodes[0].tx_broadcaster.clone(), - Arc::new(test_utils::TestLogger::new()), - Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }), - )); + nodes[0].chan_monitor = + Arc::new(test_utils::TestChannelMonitor::new( + nodes[0].chain_monitor.clone(), + nodes[0].tx_broadcaster.clone(), + Arc::new(test_utils::TestLogger::new()), + Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }), + )); let mut node_0_monitors = Vec::new(); for serialized in node_0_monitors_serialized.iter() { let mut read = &serialized[..]; @@ -5601,48 +5191,46 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { } for monitor in node_0_monitors.drain(..) { - assert!(nodes[0] - .chan_monitor - .add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) - .is_ok()); + assert!(nodes[0].chan_monitor + .add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) + .is_ok()); check_added_monitors!(nodes[0], 1); } nodes[0].node = Arc::new(nodes_0_deserialized); // nodes[1] and nodes[2] have no lost state with nodes[0]... reconnect_nodes( - &nodes[0], - &nodes[1], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[1], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); reconnect_nodes( - &nodes[0], - &nodes[2], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[0], + &nodes[2], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); //... and we can even still claim the payment! claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000); nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id()); let reestablish = get_event_msg!( - nodes[3], - MessageSendEvent::SendChannelReestablish, - nodes[0].node.get_our_node_id() + nodes[3], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id()); - nodes[0] - .node - .handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish); + nodes[0].node + .handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish); let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1); if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] { @@ -5730,13 +5318,13 @@ fn test_claim_sizeable_push_msat() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 99000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 100000, + 99000000, + LocalFeatures::new(), + LocalFeatures::new(), ); nodes[1].node.force_close_channel(&chan.2); check_closed_broadcast!(nodes[1], false); @@ -5745,20 +5333,16 @@ fn test_claim_sizeable_push_msat() { check_spends!(node_txn[0], chan.3.clone()); assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone()], - }, - 0, + &Block { header, + txdata: vec![node_txn[0].clone()], }, + 0, ); let spend_txn = check_spendable_outputs!(nodes[1], 1); assert_eq!(spend_txn.len(), 1); @@ -5772,13 +5356,13 @@ fn test_claim_on_remote_sizeable_push_msat() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 99000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 100000, + 99000000, + LocalFeatures::new(), + LocalFeatures::new(), ); nodes[0].node.force_close_channel(&chan.2); check_closed_broadcast!(nodes[0], false); @@ -5788,20 +5372,16 @@ fn test_claim_on_remote_sizeable_push_msat() { check_spends!(node_txn[0], chan.3.clone()); assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone()], - }, - 0, + &Block { header, + txdata: vec![node_txn[0].clone()], }, + 0, ); check_closed_broadcast!(nodes[1], false); let spend_txn = check_spendable_outputs!(nodes[1], 1); @@ -5818,43 +5398,38 @@ fn test_claim_on_remote_revoked_sizeable_push_msat() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 59000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 100000, + 59000000, + LocalFeatures::new(), + LocalFeatures::new(), ); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid()); claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); @@ -5876,36 +5451,31 @@ fn test_static_spendable_outputs_preimage_tx() { let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; - let commitment_tx = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let commitment_tx = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(commitment_tx[0].input.len(), 1); assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid()); // Settle A's commitment tx on B's chain - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000)); check_added_monitors!(nodes[1], 1); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 1, ); let events = nodes[1].node.get_and_clear_pending_msg_events(); match events[0] { @@ -5923,8 +5493,8 @@ fn test_static_spendable_outputs_preimage_tx() { check_spends!(node_txn[0], commitment_tx[0].clone()); assert_eq!(node_txn[0], node_txn[3]); assert_eq!( - node_txn[0].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[0].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); eprintln!("{:?}", node_txn[1]); check_spends!(node_txn[1], chan_1.3.clone()); @@ -5944,37 +5514,32 @@ fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() { let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .iter_mut() - .next() - .unwrap() - .1 - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .iter_mut() + .next() + .unwrap() + .1 + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid()); claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); @@ -5998,36 +5563,31 @@ fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() { let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; - let revoked_local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid()); claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; // A will generate HTLC-Timeout from revoked commitment tx nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[0], false); @@ -6036,19 +5596,20 @@ fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() { assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]); assert_eq!(revoked_htlc_txn[0].input.len(), 1); assert_eq!( - revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone()); check_spends!(revoked_htlc_txn[1], chan_1.3.clone()); // B will generate justice tx from A's revoked commitment/HTLC tx nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![ + revoked_local_txn[0].clone(), + revoked_htlc_txn[0].clone(), + ], }, + 1, ); check_closed_broadcast!(nodes[1], false); @@ -6073,36 +5634,31 @@ fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() { let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; - let revoked_local_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid()); claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; // B will generate HTLC-Success from revoked commitment tx nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); @@ -6111,18 +5667,19 @@ fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() { assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]); assert_eq!(revoked_htlc_txn[0].input.len(), 1); assert_eq!( - revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone()); // A will generate justice tx from B's revoked commitment/HTLC tx nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![ + revoked_local_txn[0].clone(), + revoked_htlc_txn[0].clone(), + ], }, + 1, ); check_closed_broadcast!(nodes[0], false); @@ -6162,24 +5719,21 @@ fn test_onchain_to_onchain_claim() { send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], 8000000, 8_000_000); let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]], 3000000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - let commitment_tx = nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_2.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + let commitment_tx = nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_2.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); check_spends!(commitment_tx[0], chan_2.3.clone()); nodes[2].node.claim_funds(payment_preimage, 3_000_000); check_added_monitors!(nodes[2], 1); @@ -6190,11 +5744,9 @@ fn test_onchain_to_onchain_claim() { assert!(updates.update_fail_malformed_htlcs.is_empty()); nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[2], false); @@ -6207,19 +5759,17 @@ fn test_onchain_to_onchain_claim() { check_spends!(c_txn[2], c_txn[1].clone()); assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71); assert_eq!( - c_txn[2].input[0].witness.clone().last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + c_txn[2].input[0].witness.clone().last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output assert_eq!(c_txn[0].lock_time, 0); // Success tx // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![c_txn[1].clone(), c_txn[2].clone()], - }, - 1, + &Block { header, + txdata: vec![c_txn[1].clone(), c_txn[2].clone()], }, + 1, ); { let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); @@ -6228,15 +5778,15 @@ fn test_onchain_to_onchain_claim() { check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager assert_eq!( - b_txn[2].input[0].witness.clone().last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + b_txn[2].input[0].witness.clone().last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output assert_ne!(b_txn[2].lock_time, 0); // Timeout tx check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan assert_eq!( - b_txn[0].input[0].witness.clone().last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + b_txn[0].input[0].witness.clone().last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment assert_ne!(b_txn[2].lock_time, 0); // Timeout tx @@ -6249,17 +5799,13 @@ fn test_onchain_to_onchain_claim() { _ => panic!("Unexpected event"), } match msg_events[1] { - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fail_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); @@ -6269,22 +5815,19 @@ fn test_onchain_to_onchain_claim() { _ => panic!("Unexpected event"), }; // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx - let commitment_tx = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let commitment_tx = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_tx[0].clone()], }, + 1, ); let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); assert_eq!(b_txn.len(), 4); @@ -6293,8 +5836,8 @@ fn test_onchain_to_onchain_claim() { assert_eq!(b_txn[0], b_txn[3]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan check_spends!(b_txn[0], commitment_tx[0].clone()); assert_eq!( - b_txn[0].input[0].witness.clone().last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + b_txn[0].input[0].witness.clone().last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment assert_eq!(b_txn[2].lock_time, 0); // Success tx @@ -6315,37 +5858,32 @@ fn test_duplicate_payment_hash_one_failure_one_success() { route_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], 900000); *nodes[0].network_payment_count.borrow_mut() -= 1; assert_eq!( - route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, - duplicate_payment_hash - ); - - let commitment_txn = nodes[2] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_2.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, + duplicate_payment_hash + ); + + let commitment_txn = nodes[2].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_2.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(commitment_txn[0].input.len(), 1); check_spends!(commitment_txn[0], chan_2.3.clone()); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); @@ -6369,11 +5907,9 @@ fn test_duplicate_payment_hash_one_failure_one_success() { nodes[2].node.claim_funds(our_payment_preimage, 900_000); nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![commitment_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![commitment_txn[0].clone()], }, + 1, ); check_added_monitors!(nodes[2], 2); let events = nodes[2].node.get_and_clear_pending_msg_events(); @@ -6393,32 +5929,30 @@ fn test_duplicate_payment_hash_one_failure_one_success() { assert_eq!(htlc_success_txn[0], htlc_success_txn[5]); assert_eq!(htlc_success_txn[0].input.len(), 1); assert_eq!( - htlc_success_txn[0].input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + htlc_success_txn[0].input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); assert_eq!(htlc_success_txn[1], htlc_success_txn[4]); assert_eq!(htlc_success_txn[1].input.len(), 1); assert_eq!( - htlc_success_txn[1].input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + htlc_success_txn[1].input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]); check_spends!(htlc_success_txn[0], commitment_txn[0].clone()); check_spends!(htlc_success_txn[1], commitment_txn[0].clone()); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![htlc_timeout_tx], - }, - 200, + &Block { header, + txdata: vec![htlc_timeout_tx], }, + 200, ); connect_blocks( - &nodes[1].block_notifier, - ANTI_REORG_DELAY - 1, - 200, - true, - header.bitcoin_hash(), + &nodes[1].block_notifier, + ANTI_REORG_DELAY - 1, + 200, + true, + header.bitcoin_hash(), ); expect_pending_htlcs_forwardable!(nodes[1]); let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); @@ -6429,18 +5963,16 @@ fn test_duplicate_payment_hash_one_failure_one_success() { assert!(htlc_updates.update_fail_malformed_htlcs.is_empty()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); { commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { - MessageSendEvent::PaymentFailureNetworkUpdate { - update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }, - } => {}, + MessageSendEvent::PaymentFailureNetworkUpdate { update: + msgs::HTLCFailChannelUpdate::ChannelClosed { .. }, } => {}, _ => { panic!("Unexpected event"); }, @@ -6456,11 +5988,9 @@ fn test_duplicate_payment_hash_one_failure_one_success() { // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![htlc_success_txn[0].clone()], - }, - 200, + &Block { header, + txdata: vec![htlc_success_txn[0].clone()], }, + 200, ); let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(updates.update_add_htlcs.is_empty()); @@ -6470,9 +6000,8 @@ fn test_duplicate_payment_hash_one_failure_one_success() { assert!(updates.update_fail_malformed_htlcs.is_empty()); check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false); let events = nodes[0].node.get_and_clear_pending_events(); @@ -6492,36 +6021,31 @@ fn test_dynamic_spendable_outputs_local_htlc_success_tx() { let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 9000000).0; - let local_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let local_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(local_txn[0].input.len(), 1); check_spends!(local_txn[0], chan_1.3.clone()); // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx nodes[1].node.claim_funds(payment_preimage, 9_000_000); check_added_monitors!(nodes[1], 1); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![local_txn[0].clone()], }, + 1, ); let events = nodes[1].node.get_and_clear_pending_msg_events(); match events[0] { @@ -6535,8 +6059,8 @@ fn test_dynamic_spendable_outputs_local_htlc_success_tx() { let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); assert_eq!(node_txn[0].input.len(), 1); assert_eq!( - node_txn[0].input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + node_txn[0].input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); check_spends!(node_txn[0], local_txn[0].clone()); @@ -6572,164 +6096,156 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000); send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000); assert_eq!( - nodes[3] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn()[0] - .output - .len(), - 2 - ); - - let ds_dust_limit = nodes[3] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan.2) - .unwrap() - .our_dust_limit_satoshis; + nodes[3].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn()[0] + .output + .len(), + 2 + ); + + let ds_dust_limit = nodes[3].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan.2) + .unwrap() + .our_dust_limit_satoshis; // 0th HTLC: let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit * 1000); // not added < dust limit + HTLC tx fee // 1st HTLC: let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit * 1000); // not added < dust limit + HTLC tx fee - let route = nodes[1] - .router - .get_route( - &nodes[5].node.get_our_node_id(), - None, - &Vec::new(), - ds_dust_limit * 1000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[5].node.get_our_node_id(), + None, + &Vec::new(), + ds_dust_limit * 1000, + TEST_FINAL_CLTV, + ) + .unwrap(); // 2nd HTLC: send_along_route_with_hash( - &nodes[1], - route.clone(), - &[&nodes[2], &nodes[3], &nodes[5]], - ds_dust_limit * 1000, - payment_hash_1, + &nodes[1], + route.clone(), + &[&nodes[2], &nodes[3], &nodes[5]], + ds_dust_limit * 1000, + payment_hash_1, ); // not added < dust limit + HTLC tx fee // 3rd HTLC: send_along_route_with_hash( - &nodes[1], - route, - &[&nodes[2], &nodes[3], &nodes[5]], - ds_dust_limit * 1000, - payment_hash_2, + &nodes[1], + route, + &[&nodes[2], &nodes[3], &nodes[5]], + ds_dust_limit * 1000, + payment_hash_2, ); // not added < dust limit + HTLC tx fee // 4th HTLC: let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000); // 5th HTLC: let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000); - let route = nodes[1] - .router - .get_route( - &nodes[5].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[5].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); // 6th HTLC: send_along_route_with_hash( - &nodes[1], - route.clone(), - &[&nodes[2], &nodes[3], &nodes[5]], - 1000000, - payment_hash_3, + &nodes[1], + route.clone(), + &[&nodes[2], &nodes[3], &nodes[5]], + 1000000, + payment_hash_3, ); // 7th HTLC: send_along_route_with_hash( - &nodes[1], - route, - &[&nodes[2], &nodes[3], &nodes[5]], - 1000000, - payment_hash_4, + &nodes[1], + route, + &[&nodes[2], &nodes[3], &nodes[5]], + 1000000, + payment_hash_4, ); // 8th HTLC: let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000); // 9th HTLC: - let route = nodes[1] - .router - .get_route( - &nodes[5].node.get_our_node_id(), - None, - &Vec::new(), - ds_dust_limit * 1000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[5].node.get_our_node_id(), + None, + &Vec::new(), + ds_dust_limit * 1000, + TEST_FINAL_CLTV, + ) + .unwrap(); send_along_route_with_hash( - &nodes[1], - route, - &[&nodes[2], &nodes[3], &nodes[5]], - ds_dust_limit * 1000, - payment_hash_5, + &nodes[1], + route, + &[&nodes[2], &nodes[3], &nodes[5]], + ds_dust_limit * 1000, + payment_hash_5, ); // not added < dust limit + HTLC tx fee // 10th HTLC: let (_, payment_hash_6) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit * 1000); // not added < dust limit + HTLC tx fee // 11th HTLC: - let route = nodes[1] - .router - .get_route( - &nodes[5].node.get_our_node_id(), - None, - &Vec::new(), - 1000000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[1].router + .get_route( + &nodes[5].node.get_our_node_id(), + None, + &Vec::new(), + 1000000, + TEST_FINAL_CLTV, + ) + .unwrap(); send_along_route_with_hash( - &nodes[1], - route, - &[&nodes[2], &nodes[3], &nodes[5]], - 1000000, - payment_hash_6, + &nodes[1], + route, + &[&nodes[2], &nodes[3], &nodes[5]], + 1000000, + payment_hash_6, ); // Double-check that six of the new HTLC were added // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie, // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included). assert_eq!( - nodes[3] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn() - .len(), - 1 + nodes[3].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn() + .len(), + 1 ); assert_eq!( - nodes[3] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn()[0] - .output - .len(), - 8 + nodes[3].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn()[0] + .output + .len(), + 8 ); // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go. @@ -6743,18 +6259,14 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno check_added_monitors!(nodes[4], 1); let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id()); - nodes[3] - .node - .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]); - nodes[3] - .node - .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]); - nodes[3] - .node - .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]); - nodes[3] - .node - .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]); + nodes[3].node + .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]); + nodes[3].node + .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]); + nodes[3].node + .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]); + nodes[3].node + .handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]); commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false); // Fail 3rd below-dust and 7th above-dust HTLCs @@ -6765,57 +6277,48 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno check_added_monitors!(nodes[5], 1); let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id()); - nodes[3] - .node - .handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]); - nodes[3] - .node - .handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]); + nodes[3].node + .handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]); + nodes[3].node + .handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]); commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false); - let ds_prev_commitment_tx = nodes[3] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let ds_prev_commitment_tx = nodes[3].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); expect_pending_htlcs_forwardable!(nodes[3]); check_added_monitors!(nodes[3], 1); let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id()); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]); - nodes[2] - .node - .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]); + nodes[2].node + .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]); + nodes[2].node + .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]); + nodes[2].node + .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]); + nodes[2].node + .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]); + nodes[2].node + .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]); + nodes[2].node + .handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]); if deliver_last_raa { commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false); } else { let _cs_last_raa = commitment_signed_dance!( - nodes[2], - nodes[3], - six_removes.commitment_signed, - false, - true, - false, - true + nodes[2], + nodes[3], + six_removes.commitment_signed, + false, + true, + false, + true ); } @@ -6830,48 +6333,41 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno // // Alternatively, we may broadcast the previous commitment transaction, which should only // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs. - let ds_last_commitment_tx = nodes[3] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); - - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let ds_last_commitment_tx = nodes[3].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); + + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; if announce_latest { nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![ds_last_commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![ds_last_commitment_tx[0].clone()], }, + 1, ); } else { nodes[2].block_notifier.block_connected( - &Block { - header, - txdata: vec![ds_prev_commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![ds_prev_commitment_tx[0].clone()], }, + 1, ); } connect_blocks( - &nodes[2].block_notifier, - ANTI_REORG_DELAY - 1, - 1, - true, - header.bitcoin_hash(), + &nodes[2].block_notifier, + ANTI_REORG_DELAY - 1, + 1, + true, + header.bitcoin_hash(), ); check_closed_broadcast!(nodes[2], false); expect_pending_htlcs_forwardable!(nodes[2]); @@ -6882,23 +6378,21 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno let mut a_done = false; for msg in cs_msgs { match msg { - MessageSendEvent::UpdateHTLCs { - ref node_id, - ref updates, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + ref updates, } => { // Both under-dust HTLCs and the one above-dust HTLC that we had already failed // should be failed-backwards here. let target = if *node_id == nodes[0].node.get_our_node_id() { // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs for htlc in &updates.update_fail_htlcs { assert!( - htlc.htlc_id == 1 - || htlc.htlc_id == 2 || htlc.htlc_id == 6 - || if announce_latest { - htlc.htlc_id == 3 || htlc.htlc_id == 5 - } else { - false - } + htlc.htlc_id == 1 + || htlc.htlc_id == 2 || htlc.htlc_id == 6 + || if announce_latest { + htlc.htlc_id == 3 || htlc.htlc_id == 5 + } else { + false + } ); } assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 }); @@ -6909,32 +6403,27 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs for htlc in &updates.update_fail_htlcs { assert!( - htlc.htlc_id == 1 - || htlc.htlc_id == 2 || htlc.htlc_id == 5 - || if announce_latest { htlc.htlc_id == 4 } else { false } + htlc.htlc_id == 1 + || htlc.htlc_id == 2 || htlc.htlc_id == 5 + || if announce_latest { htlc.htlc_id == 4 } else { false } ); } assert_eq!(*node_id, nodes[1].node.get_our_node_id()); assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 }); &nodes[1] }; - target - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); - target - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]); - target - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]); + target.node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + target.node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]); + target.node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]); if announce_latest { - target - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]); + target.node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]); if *node_id == nodes[0].node.get_our_node_id() { - target - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]); + target.node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]); } } commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true); @@ -6947,11 +6436,9 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 }); let mut as_failds = HashSet::new(); for event in as_events.iter() { - if let &Event::PaymentFailed { - ref payment_hash, - ref rejected_by_dest, - .. - } = event + if let &Event::PaymentFailed { ref payment_hash, + ref rejected_by_dest, + .. } = event { assert!(as_failds.insert(*payment_hash)); if *payment_hash != payment_hash_2 { @@ -6975,11 +6462,9 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 }); let mut bs_failds = HashSet::new(); for event in bs_events.iter() { - if let &Event::PaymentFailed { - ref payment_hash, - ref rejected_by_dest, - .. - } = event + if let &Event::PaymentFailed { ref payment_hash, + ref rejected_by_dest, + .. } = event { assert!(bs_failds.insert(*payment_hash)); if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 { @@ -7005,25 +6490,25 @@ fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, anno // PaymentFailureNetworkUpdates. let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!( - as_msg_events.len(), - if deliver_last_raa { - 1 - } else if !announce_latest { - 3 - } else { - 5 - } + as_msg_events.len(), + if deliver_last_raa { + 1 + } else if !announce_latest { + 3 + } else { + 5 + } ); let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!( - bs_msg_events.len(), - if deliver_last_raa { - 2 - } else if !announce_latest { - 3 - } else { - 4 - } + bs_msg_events.len(), + if deliver_last_raa { + 2 + } else if !announce_latest { + 3 + } else { + 4 + } ); for event in as_msg_events.iter().chain(bs_msg_events.iter()) { match event { @@ -7054,42 +6539,37 @@ fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() { let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); route_payment(&nodes[0], &vec![&nodes[1]][..], 9000000).0; - let local_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan_1.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let local_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan_1.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(local_txn[0].input.len(), 1); check_spends!(local_txn[0], chan_1.3.clone()); // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![local_txn[0].clone()], - }, - 200, + &Block { header, + txdata: vec![local_txn[0].clone()], }, + 200, ); check_closed_broadcast!(nodes[0], false); let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap(); assert_eq!(node_txn[0].input.len(), 1); assert_eq!( - node_txn[0].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + node_txn[0].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); check_spends!(node_txn[0], local_txn[0].clone()); @@ -7115,31 +6595,25 @@ fn test_static_output_closing_tx() { send_payment(&nodes[0], &vec![&nodes[1]][..], 8000000, 8_000_000); let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2; - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![closing_tx.clone()], - }, - 1, + &Block { header, + txdata: vec![closing_tx.clone()], }, + 1, ); let spend_txn = check_spendable_outputs!(nodes[0], 2); assert_eq!(spend_txn.len(), 1); check_spends!(spend_txn[0], closing_tx.clone()); nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![closing_tx.clone()], - }, - 1, + &Block { header, + txdata: vec![closing_tx.clone()], }, + 1, ); let spend_txn = check_spendable_outputs!(nodes[1], 2); assert_eq!(spend_txn.len(), 1); @@ -7154,15 +6628,13 @@ fn do_htlc_claim_local_commitment_only(use_dust: bool) { // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being // present in B's local commitment transaction, but none of A's commitment transactions. - assert!(nodes[1] - .node - .claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 })); + assert!(nodes[1].node + .claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 })); check_added_monitors!(nodes[1], 1); let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { @@ -7172,35 +6644,30 @@ fn do_htlc_claim_local_commitment_only(use_dust: bool) { _ => panic!("Unexpected event"), } - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed); check_added_monitors!(nodes[0], 1); let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0); check_added_monitors!(nodes[1], 1); - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 { - nodes[1] - .block_notifier - .block_connected_checked(&header, i, &Vec::new(), &Vec::new()); + nodes[1].block_notifier + .block_connected_checked(&header, i, &Vec::new(), &Vec::new()); header.prev_blockhash = header.bitcoin_hash(); } test_txn_broadcast( - &nodes[1], - &chan, - None, - if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS }, + &nodes[1], + &chan, + None, + if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS }, ); check_closed_broadcast!(nodes[1], false); } @@ -7209,16 +6676,15 @@ fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) { let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &Vec::new(), - if use_dust { 50000 } else { 3000000 }, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &Vec::new(), + if use_dust { 50000 } else { 3000000 }, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); @@ -7229,22 +6695,18 @@ fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) { // transaction, however it is not in A's latest local commitment, so we can just broadcast that // to "time out" the HTLC. - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 { nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: Vec::new(), - }, - i, + &Block { header, + txdata: Vec::new(), }, + i, ); header.prev_blockhash = header.bitcoin_hash(); } @@ -7267,47 +6729,39 @@ fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no check_added_monitors!(nodes[1], 1); let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed); check_added_monitors!(nodes[0], 1); let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0); + nodes[1].node + .handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0); check_added_monitors!(nodes[1], 1); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1); check_added_monitors!(nodes[1], 1); let bs_revoke_and_ack = get_event_msg!( - nodes[1], - MessageSendEvent::SendRevokeAndACK, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() ); if check_revoke_no_close { - nodes[0] - .node - .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); + nodes[0].node + .handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); check_added_monitors!(nodes[0], 1); } - let mut header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let mut header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 { - nodes[0] - .block_notifier - .block_connected_checked(&header, i, &Vec::new(), &Vec::new()); + nodes[0].block_notifier + .block_connected_checked(&header, i, &Vec::new(), &Vec::new()); header.prev_blockhash = header.bitcoin_hash(); } if !check_revoke_no_close { @@ -7317,11 +6771,9 @@ fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { - Event::PaymentFailed { - payment_hash, - rejected_by_dest, - .. - } => { + Event::PaymentFailed { payment_hash, + rejected_by_dest, + .. } => { assert_eq!(payment_hash, our_payment_hash); assert!(rejected_by_dest); }, @@ -7358,33 +6810,31 @@ fn htlc_claim_single_commitment_only_b() { do_htlc_claim_previous_remote_commitment_only(false, true); } -fn run_onion_failure_test( - _name: &str, - test_case: u8, - nodes: &Vec, - route: &Route, - payment_hash: &PaymentHash, - callback_msg: F1, - callback_node: F2, - expected_retryable: bool, - expected_error_code: Option, - expected_channel_update: Option, -) where - F1: for<'a> FnMut(&'a mut msgs::UpdateAddHTLC), - F2: FnMut(), +fn run_onion_failure_test(_name: &str, + test_case: u8, + nodes: &Vec, + route: &Route, + payment_hash: &PaymentHash, + callback_msg: F1, + callback_node: F2, + expected_retryable: bool, + expected_error_code: Option, + expected_channel_update: Option) + where F1: for<'a> FnMut(&'a mut msgs::UpdateAddHTLC), + F2: FnMut() { run_onion_failure_test_with_fail_intercept( - _name, - test_case, - nodes, - route, - payment_hash, - callback_msg, - |_| {}, - callback_node, - expected_retryable, - expected_error_code, - expected_channel_update, + _name, + test_case, + nodes, + route, + payment_hash, + callback_msg, + |_| {}, + callback_node, + expected_retryable, + expected_error_code, + expected_channel_update, ); } @@ -7395,32 +6845,28 @@ fn run_onion_failure_test( // 3: final node fails backward (but tamper onion payloads from node0) // 100: trigger error in the intermediate node and tamper returning fail_htlc // 200: trigger error in the final node and tamper returning fail_htlc -fn run_onion_failure_test_with_fail_intercept( - _name: &str, - test_case: u8, - nodes: &Vec, - route: &Route, - payment_hash: &PaymentHash, - mut callback_msg: F1, - mut callback_fail: F2, - mut callback_node: F3, - expected_retryable: bool, - expected_error_code: Option, - expected_channel_update: Option, -) where - F1: for<'a> FnMut(&'a mut msgs::UpdateAddHTLC), - F2: for<'a> FnMut(&'a mut msgs::UpdateFailHTLC), - F3: FnMut(), +fn run_onion_failure_test_with_fail_intercept(_name: &str, + test_case: u8, + nodes: &Vec, + route: &Route, + payment_hash: &PaymentHash, + mut callback_msg: F1, + mut callback_fail: F2, + mut callback_node: F3, + expected_retryable: bool, + expected_error_code: Option, + expected_channel_update: Option) + where F1: for<'a> FnMut(&'a mut msgs::UpdateAddHTLC), + F2: for<'a> FnMut(&'a mut msgs::UpdateFailHTLC), + F3: FnMut() { // reset block height - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; for ix in 0..nodes.len() { nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]); } @@ -7454,9 +6900,8 @@ fn run_onion_failure_test_with_fail_intercept( callback_node(); } // 0 => 1 update_add & CS - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0); commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true); let update_1_0 = match test_case { @@ -7464,8 +6909,8 @@ fn run_onion_failure_test_with_fail_intercept( // intermediate node failure; fail backward to 0 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!( - update_1_0.update_fail_htlcs.len() + update_1_0.update_fail_malformed_htlcs.len() == 1 - && (update_1_0.update_fail_htlcs.len() == 1 || update_1_0.update_fail_malformed_htlcs.len() == 1) + update_1_0.update_fail_htlcs.len() + update_1_0.update_fail_malformed_htlcs.len() == 1 + && (update_1_0.update_fail_htlcs.len() == 1 || update_1_0.update_fail_malformed_htlcs.len() == 1) ); update_1_0 }, @@ -7488,9 +6933,8 @@ fn run_onion_failure_test_with_fail_intercept( } // 1 => 2 - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1); commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true); if test_case == 2 || test_case == 200 { @@ -7512,9 +6956,8 @@ fn run_onion_failure_test_with_fail_intercept( } // 2 => 1 - nodes[1] - .node - .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg); + nodes[1].node + .handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg); commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true); // backward fail on 1 @@ -7531,13 +6974,12 @@ fn run_onion_failure_test_with_fail_intercept( if test_case == 100 { callback_fail(&mut fail_msg); } - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg); } else { nodes[0].node.handle_update_fail_malformed_htlc( - &nodes[1].node.get_our_node_id(), - &update_1_0.update_fail_malformed_htlcs[0], + &nodes[1].node.get_our_node_id(), + &update_1_0.update_fail_malformed_htlcs[0], ); }; @@ -7545,11 +6987,9 @@ fn run_onion_failure_test_with_fail_intercept( let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let &Event::PaymentFailed { - payment_hash: _, - ref rejected_by_dest, - ref error_code, - } = &events[0] + if let &Event::PaymentFailed { payment_hash: _, + ref rejected_by_dest, + ref error_code, } = &events[0] { assert_eq!(*rejected_by_dest, !expected_retryable); assert_eq!(*error_code, expected_error_code); @@ -7568,14 +7008,11 @@ fn run_onion_failure_test_with_fail_intercept( panic!("channel_update not found!"); } }, - &HTLCFailChannelUpdate::ChannelClosed { - ref short_channel_id, - ref is_permanent, - } => { - if let HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: ref expected_short_channel_id, - is_permanent: ref expected_is_permanent, - } = expected_channel_update.unwrap() + &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, + ref is_permanent, } => { + if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, + is_permanent: ref expected_is_permanent, } = + expected_channel_update.unwrap() { assert!(*short_channel_id == *expected_short_channel_id); assert!(*is_permanent == *expected_is_permanent); @@ -7583,14 +7020,11 @@ fn run_onion_failure_test_with_fail_intercept( panic!("Unexpected message event"); } }, - &HTLCFailChannelUpdate::NodeFailure { - ref node_id, - ref is_permanent, - } => { - if let HTLCFailChannelUpdate::NodeFailure { - node_id: ref expected_node_id, - is_permanent: ref expected_is_permanent, - } = expected_channel_update.unwrap() + &HTLCFailChannelUpdate::NodeFailure { ref node_id, + ref is_permanent, } => { + if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, + is_permanent: ref expected_is_permanent, } = + expected_channel_update.unwrap() { assert!(*node_id == *expected_node_id); assert!(*is_permanent == *expected_is_permanent); @@ -7610,20 +7044,16 @@ impl msgs::ChannelUpdate { fn dummy() -> msgs::ChannelUpdate { use secp256k1::ffi::Signature as FFISignature; use secp256k1::Signature; - msgs::ChannelUpdate { - signature: Signature::from(FFISignature::new()), - contents: msgs::UnsignedChannelUpdate { - chain_hash: Sha256dHash::hash(&vec![0u8][..]), - short_channel_id: 0, - timestamp: 0, - flags: 0, - cltv_expiry_delta: 0, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - excess_data: vec![], - }, - } + msgs::ChannelUpdate { signature: Signature::from(FFISignature::new()), + contents: msgs::UnsignedChannelUpdate { chain_hash: Sha256dHash::hash(&vec![0u8][..]), + short_channel_id: 0, + timestamp: 0, + flags: 0, + cltv_expiry_delta: 0, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + excess_data: vec![] } } } } @@ -7643,275 +7073,306 @@ fn test_onion_failure() { *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap()); } let channels = [ - create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()), - create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new()), + create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()), + create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new()), ]; let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]); - let route = nodes[0] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 40000, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 40000, + TEST_FINAL_CLTV, + ) + .unwrap(); // positve case send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], 40000, 40_000); // intermediate node failure run_onion_failure_test( - "invalid_realm", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1; - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - let (mut onion_payloads, _htlc_msat, _htlc_cltv) = - onion_utils::build_onion_payloads(&route, cur_height).unwrap(); - onion_payloads[0].realm = 3; - msg.onion_routing_packet = - onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash); - }, - || {}, - true, - Some(PERM | 1), - Some(msgs::HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: channels[1].0.contents.short_channel_id, - is_permanent: true, - }), + "invalid_realm", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1; + let onion_keys = + onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); + let (mut onion_payloads, _htlc_msat, _htlc_cltv) = + onion_utils::build_onion_payloads(&route, cur_height).unwrap(); + onion_payloads[0].realm = 3; + msg.onion_routing_packet = onion_utils::construct_onion_packet( + onion_payloads, + onion_keys, + [0; 32], + &payment_hash, + ); + }, + || {}, + true, + Some(PERM | 1), + Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: + channels[1].0.contents.short_channel_id, + is_permanent: true, }), ); //XXX incremented channels idx here // final node failure run_onion_failure_test( - "invalid_realm", - 3, - &nodes, - &route, - &payment_hash, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1; - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - let (mut onion_payloads, _htlc_msat, _htlc_cltv) = - onion_utils::build_onion_payloads(&route, cur_height).unwrap(); - onion_payloads[1].realm = 3; - msg.onion_routing_packet = - onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash); - }, - || {}, - false, - Some(PERM | 1), - Some(msgs::HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: channels[1].0.contents.short_channel_id, - is_permanent: true, - }), + "invalid_realm", + 3, + &nodes, + &route, + &payment_hash, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1; + let onion_keys = + onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); + let (mut onion_payloads, _htlc_msat, _htlc_cltv) = + onion_utils::build_onion_payloads(&route, cur_height).unwrap(); + onion_payloads[1].realm = 3; + msg.onion_routing_packet = onion_utils::construct_onion_packet( + onion_payloads, + onion_keys, + [0; 32], + &payment_hash, + ); + }, + || {}, + false, + Some(PERM | 1), + Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: + channels[1].0.contents.short_channel_id, + is_permanent: true, }), ); // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node // receiving simulated fail messages // intermediate node failure run_onion_failure_test_with_fail_intercept( - "temporary_node_failure", - 100, - &nodes, - &route, - &payment_hash, - |msg| { - // trigger error - msg.amount_msat -= 1; - }, - |msg| { - // and tamper returning error message - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - msg.reason = + "temporary_node_failure", + 100, + &nodes, + &route, + &payment_hash, + |msg| { + // trigger error + msg.amount_msat -= 1; + }, + |msg| { + // and tamper returning error message + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let onion_keys = onion_utils::construct_onion_keys( + &Secp256k1::new( + ), + &route, + &session_priv, + ).unwrap(); + msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE | 2, &[0; 0]); - }, - || {}, - true, - Some(NODE | 2), - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route.hops[0].pubkey, - is_permanent: false, - }), + }, + || {}, + true, + Some(NODE | 2), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route.hops + [0].pubkey, + is_permanent: false, }), ); // final node failure run_onion_failure_test_with_fail_intercept( - "temporary_node_failure", - 200, - &nodes, - &route, - &payment_hash, - |_msg| {}, - |msg| { - // and tamper returning error message - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - msg.reason = + "temporary_node_failure", + 200, + &nodes, + &route, + &payment_hash, + |_msg| {}, + |msg| { + // and tamper returning error message + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let onion_keys = onion_utils::construct_onion_keys( + &Secp256k1::new( + ), + &route, + &session_priv, + ).unwrap(); + msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE | 2, &[0; 0]); - }, - || { - nodes[2].node.fail_htlc_backwards(&payment_hash); - }, - true, - Some(NODE | 2), - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route.hops[1].pubkey, - is_permanent: false, - }), + }, + || { + nodes[2].node.fail_htlc_backwards(&payment_hash); + }, + true, + Some(NODE | 2), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route.hops + [1].pubkey, + is_permanent: false, }), ); // intermediate node failure run_onion_failure_test_with_fail_intercept( - "permanent_node_failure", - 100, - &nodes, - &route, - &payment_hash, - |msg| { - msg.amount_msat -= 1; - }, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - msg.reason = + "permanent_node_failure", + 100, + &nodes, + &route, + &payment_hash, + |msg| { + msg.amount_msat -= 1; + }, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let onion_keys = onion_utils::construct_onion_keys( + &Secp256k1::new( + ), + &route, + &session_priv, + ).unwrap(); + msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM | NODE | 2, &[0; 0]); - }, - || {}, - true, - Some(PERM | NODE | 2), - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route.hops[0].pubkey, - is_permanent: true, - }), + }, + || {}, + true, + Some(PERM | NODE | 2), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route.hops + [0].pubkey, + is_permanent: true, }), ); // final node failure run_onion_failure_test_with_fail_intercept( - "permanent_node_failure", - 200, - &nodes, - &route, - &payment_hash, - |_msg| {}, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - msg.reason = + "permanent_node_failure", + 200, + &nodes, + &route, + &payment_hash, + |_msg| {}, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let onion_keys = onion_utils::construct_onion_keys( + &Secp256k1::new( + ), + &route, + &session_priv, + ).unwrap(); + msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM | NODE | 2, &[0; 0]); - }, - || { - nodes[2].node.fail_htlc_backwards(&payment_hash); - }, - false, - Some(PERM | NODE | 2), - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route.hops[1].pubkey, - is_permanent: true, - }), + }, + || { + nodes[2].node.fail_htlc_backwards(&payment_hash); + }, + false, + Some(PERM | NODE | 2), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route.hops + [1].pubkey, + is_permanent: true, }), ); // intermediate node failure run_onion_failure_test_with_fail_intercept( - "required_node_feature_missing", - 100, - &nodes, - &route, - &payment_hash, - |msg| { - msg.amount_msat -= 1; - }, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - msg.reason = + "required_node_feature_missing", + 100, + &nodes, + &route, + &payment_hash, + |msg| { + msg.amount_msat -= 1; + }, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let onion_keys = onion_utils::construct_onion_keys( + &Secp256k1::new( + ), + &route, + &session_priv, + ).unwrap(); + msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM | NODE | 3, &[0; 0]); - }, - || { - nodes[2].node.fail_htlc_backwards(&payment_hash); - }, - true, - Some(PERM | NODE | 3), - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route.hops[0].pubkey, - is_permanent: true, - }), + }, + || { + nodes[2].node.fail_htlc_backwards(&payment_hash); + }, + true, + Some(PERM | NODE | 3), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route.hops + [0].pubkey, + is_permanent: true, }), ); // final node failure run_onion_failure_test_with_fail_intercept( - "required_node_feature_missing", - 200, - &nodes, - &route, - &payment_hash, - |_msg| {}, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - msg.reason = + "required_node_feature_missing", + 200, + &nodes, + &route, + &payment_hash, + |_msg| {}, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let onion_keys = onion_utils::construct_onion_keys( + &Secp256k1::new( + ), + &route, + &session_priv, + ).unwrap(); + msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM | NODE | 3, &[0; 0]); - }, - || { - nodes[2].node.fail_htlc_backwards(&payment_hash); - }, - false, - Some(PERM | NODE | 3), - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route.hops[1].pubkey, - is_permanent: true, - }), + }, + || { + nodes[2].node.fail_htlc_backwards(&payment_hash); + }, + false, + Some(PERM | NODE | 3), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route.hops + [1].pubkey, + is_permanent: true, }), ); run_onion_failure_test( - "invalid_onion_version", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - msg.onion_routing_packet.version = 1; - }, - || {}, - true, - Some(BADONION | PERM | 4), - None, + "invalid_onion_version", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + msg.onion_routing_packet.version = 1; + }, + || {}, + true, + Some(BADONION | PERM | 4), + None, ); run_onion_failure_test( - "invalid_onion_hmac", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - msg.onion_routing_packet.hmac = [3; 32]; - }, - || {}, - true, - Some(BADONION | PERM | 5), - None, + "invalid_onion_hmac", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + msg.onion_routing_packet.hmac = [3; 32]; + }, + || {}, + true, + Some(BADONION | PERM | 5), + None, ); run_onion_failure_test( - "invalid_onion_key", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey); - }, - || {}, - true, - Some(BADONION | PERM | 6), - None, + "invalid_onion_key", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey); + }, + || {}, + true, + Some(BADONION | PERM | 6), + None, ); run_onion_failure_test_with_fail_intercept( @@ -7993,274 +7454,264 @@ fn test_onion_failure() { let mut bogus_route = route.clone(); bogus_route.hops[1].short_channel_id -= 1; run_onion_failure_test( - "unknown_next_peer", - 0, - &nodes, - &bogus_route, - &payment_hash, - |_| {}, - || {}, - true, - Some(PERM | 10), - Some(msgs::HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: bogus_route.hops[1].short_channel_id, - is_permanent: true, - }), - ); - - let amt_to_forward = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&channels[1].2) - .unwrap() - .get_their_htlc_minimum_msat() - - 1; + "unknown_next_peer", + 0, + &nodes, + &bogus_route, + &payment_hash, + |_| {}, + || {}, + true, + Some(PERM | 10), + Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: + bogus_route.hops[1].short_channel_id, + is_permanent: true, }), + ); + + let amt_to_forward = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&channels[1].2) + .unwrap() + .get_their_htlc_minimum_msat() + - 1; let mut bogus_route = route.clone(); let route_len = bogus_route.hops.len(); bogus_route.hops[route_len - 1].fee_msat = amt_to_forward; run_onion_failure_test( - "amount_below_minimum", - 0, - &nodes, - &bogus_route, - &payment_hash, - |_| {}, - || {}, - true, - Some(UPDATE | 11), - Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { - msg: ChannelUpdate::dummy(), - }), + "amount_below_minimum", + 0, + &nodes, + &bogus_route, + &payment_hash, + |_| {}, + || {}, + true, + Some(UPDATE | 11), + Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { msg: ChannelUpdate::dummy(), }), ); //TODO: with new config API, we will be able to generate both valid and //invalid channel_update cases. run_onion_failure_test( - "fee_insufficient", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - msg.amount_msat -= 1; - }, - || {}, - true, - Some(UPDATE | 12), - Some(msgs::HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: channels[0].0.contents.short_channel_id, - is_permanent: true, - }), + "fee_insufficient", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + msg.amount_msat -= 1; + }, + || {}, + true, + Some(UPDATE | 12), + Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: + channels[0].0.contents.short_channel_id, + is_permanent: true, }), ); run_onion_failure_test( - "incorrect_cltv_expiry", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value - msg.cltv_expiry -= 1; - }, - || {}, - true, - Some(UPDATE | 13), - Some(msgs::HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: channels[0].0.contents.short_channel_id, - is_permanent: true, - }), + "incorrect_cltv_expiry", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value + msg.cltv_expiry -= 1; + }, + || {}, + true, + Some(UPDATE | 13), + Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: + channels[0].0.contents.short_channel_id, + is_permanent: true, }), ); run_onion_failure_test( - "expiry_too_soon", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1; - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - - nodes[1] - .block_notifier - .block_connected_checked(&header, height, &[], &[]); - }, - || {}, - true, - Some(UPDATE | 14), - Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { - msg: ChannelUpdate::dummy(), - }), + "expiry_too_soon", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + + nodes[1].block_notifier + .block_connected_checked(&header, height, &[], &[]); + }, + || {}, + true, + Some(UPDATE | 14), + Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { msg: ChannelUpdate::dummy(), }), ); run_onion_failure_test( - "unknown_payment_hash", - 2, - &nodes, - &route, - &payment_hash, - |_| {}, - || { - nodes[2].node.fail_htlc_backwards(&payment_hash); - }, - false, - Some(PERM | 15), - None, + "unknown_payment_hash", + 2, + &nodes, + &route, + &payment_hash, + |_| {}, + || { + nodes[2].node.fail_htlc_backwards(&payment_hash); + }, + false, + Some(PERM | 15), + None, ); run_onion_failure_test( - "final_expiry_too_soon", - 1, - &nodes, - &route, - &payment_hash, - |msg| { - let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1; - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - - nodes[2] - .block_notifier - .block_connected_checked(&header, height, &[], &[]); - }, - || {}, - true, - Some(17), - None, + "final_expiry_too_soon", + 1, + &nodes, + &route, + &payment_hash, + |msg| { + let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + + nodes[2].block_notifier + .block_connected_checked(&header, height, &[], &[]); + }, + || {}, + true, + Some(17), + None, ); run_onion_failure_test( - "final_incorrect_cltv_expiry", - 1, - &nodes, - &route, - &payment_hash, - |_| {}, - || { - for (_, pending_forwards) in nodes[1] - .node - .channel_state - .lock() - .unwrap() - .borrow_parts() - .forward_htlcs - .iter_mut() - { - for f in pending_forwards.iter_mut() { - match f { - &mut HTLCForwardInfo::AddHTLC { - ref mut forward_info, .. - } => forward_info.outgoing_cltv_value += 1, - _ => {}, - } - } - } - }, - true, - Some(18), - None, + "final_incorrect_cltv_expiry", + 1, + &nodes, + &route, + &payment_hash, + |_| {}, + || { + for (_, pending_forwards) in nodes[1].node + .channel_state + .lock() + .unwrap() + .borrow_parts() + .forward_htlcs + .iter_mut() + { + for f in pending_forwards.iter_mut() { + match f { + &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } => { + forward_info.outgoing_cltv_value += 1 + }, + _ => {}, + } + } + } + }, + true, + Some(18), + None, ); run_onion_failure_test( - "final_incorrect_htlc_amount", - 1, - &nodes, - &route, - &payment_hash, - |_| {}, - || { - // violate amt_to_forward > msg.amount_msat - for (_, pending_forwards) in nodes[1] - .node - .channel_state - .lock() - .unwrap() - .borrow_parts() - .forward_htlcs - .iter_mut() - { - for f in pending_forwards.iter_mut() { - match f { - &mut HTLCForwardInfo::AddHTLC { - ref mut forward_info, .. - } => forward_info.amt_to_forward -= 1, - _ => {}, - } - } - } - }, - true, - Some(19), - None, + "final_incorrect_htlc_amount", + 1, + &nodes, + &route, + &payment_hash, + |_| {}, + || { + // violate amt_to_forward > msg.amount_msat + for (_, pending_forwards) in nodes[1].node + .channel_state + .lock() + .unwrap() + .borrow_parts() + .forward_htlcs + .iter_mut() + { + for f in pending_forwards.iter_mut() { + match f { + &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } => { + forward_info.amt_to_forward -= 1 + }, + _ => {}, + } + } + } + }, + true, + Some(19), + None, ); run_onion_failure_test( - "channel_disabled", - 0, - &nodes, - &route, - &payment_hash, - |_| {}, - || { - // disconnect event to the channel between nodes[1] ~ nodes[2] - nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false); - nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); - }, - true, - Some(UPDATE | 20), - Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { - msg: ChannelUpdate::dummy(), - }), + "channel_disabled", + 0, + &nodes, + &route, + &payment_hash, + |_| {}, + || { + // disconnect event to the channel between nodes[1] ~ nodes[2] + nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false); + nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); + }, + true, + Some(UPDATE | 20), + Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { msg: ChannelUpdate::dummy(), }), ); reconnect_nodes( - &nodes[1], - &nodes[2], - (false, false), - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (false, false), + &nodes[1], + &nodes[2], + (false, false), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (false, false), ); run_onion_failure_test( - "expiry_too_far", - 0, - &nodes, - &route, - &payment_hash, - |msg| { - let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); - let mut route = route.clone(); - let height = 1; - route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1; - let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); - let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap(); - let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash); - msg.cltv_expiry = htlc_cltv; - msg.onion_routing_packet = onion_packet; - }, - || {}, - true, - Some(21), - None, + "expiry_too_far", + 0, + &nodes, + &route, + &payment_hash, + |msg| { + let session_priv = SecretKey::from_slice(&[3; 32]).unwrap(); + let mut route = route.clone(); + let height = 1; + route.hops[1].cltv_expiry_delta += + CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1; + let onion_keys = + onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap(); + let (onion_payloads, _, htlc_cltv) = + onion_utils::build_onion_payloads(&route, height).unwrap(); + let onion_packet = onion_utils::construct_onion_packet( + onion_payloads, + onion_keys, + [0; 32], + &payment_hash, + ); + msg.cltv_expiry = htlc_cltv; + msg.onion_routing_packet = onion_packet; + }, + || {}, + true, + Some(21), + None, ); } @@ -8277,26 +7728,24 @@ fn bolt2_open_channel_sending_node_checks_part1() { // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer. let channel_value_satoshis = 10000; let push_msat = 10001; - nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) - .unwrap(); + nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) + .unwrap(); let node0_to_1_send_open_channel = get_event_msg!( - nodes[0], - MessageSendEvent::SendOpenChannel, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() ); nodes[1].node.handle_open_channel( - &nodes[0].node.get_our_node_id(), - LocalFeatures::new(), - &node0_to_1_send_open_channel, + &nodes[0].node.get_our_node_id(), + LocalFeatures::new(), + &node0_to_1_send_open_channel, ); //Create a second channel with a channel_id collision - assert!(nodes[0] - .node - .create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) - .is_err()); + assert!(nodes[0].node + .create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) + .is_err()); } #[test] @@ -8306,31 +7755,28 @@ fn bolt2_open_channel_sending_node_checks_part2() { // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis let channel_value_satoshis = 2 ^ 24; let push_msat = 10001; - assert!(nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) - .is_err()); + assert!(nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) + .is_err()); // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis let channel_value_satoshis = 10000; // Test when push_msat is equal to 1000 * funding_satoshis. let push_msat = 1000 * channel_value_satoshis + 1; - assert!(nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) - .is_err()); + assert!(nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) + .is_err()); // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis let channel_value_satoshis = 10000; let push_msat = 10001; - assert!(nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) - .is_ok()); //Create a valid channel + assert!(nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42) + .is_ok()); //Create a valid channel let node0_to_1_send_open_channel = get_event_msg!( - nodes[0], - MessageSendEvent::SendOpenChannel, - nodes[1].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() ); assert!(node0_to_1_send_open_channel.channel_reserve_satoshis >= node0_to_1_send_open_channel.dust_limit_satoshis); @@ -8364,18 +7810,17 @@ fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() { //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these) let mut nodes = create_network(2, &[None, None]); let _chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 95000000, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let mut route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); + &nodes, + 0, + 1, + 100000, + 95000000, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let mut route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); route.hops[0].fee_msat = 0; @@ -8389,9 +7834,9 @@ fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() { } assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Cannot send less than their minimum HTLC value".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Cannot send less than their minimum HTLC value".to_string(), + 1, ); } @@ -8401,18 +7846,17 @@ fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() { //It is enforced when constructing a route. let mut nodes = create_network(2, &[None, None]); let _chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 0, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001) - .unwrap(); + &nodes, + 0, + 1, + 100000, + 0, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); let err = nodes[0].node.send_payment(route, our_payment_hash); @@ -8431,29 +7875,27 @@ fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer. let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 0, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let max_accepted_htlcs = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan.2) - .unwrap() - .their_max_accepted_htlcs as u64; + &nodes, + 0, + 1, + 1000000, + 0, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let max_accepted_htlcs = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan.2) + .unwrap() + .their_max_accepted_htlcs as u64; for i in 0..max_accepted_htlcs { - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); let payment_event = { nodes[0].node.send_payment(route, our_payment_hash).unwrap(); @@ -8461,13 +7903,10 @@ fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - if let MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: msgs::CommitmentUpdate { - update_add_htlcs: ref htlcs, - .. - }, - } = events[0] + if let MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { update_add_htlcs: ref htlcs, + .. }, } = events[0] { assert_eq!(htlcs[0].htlc_id, i); } else { @@ -8475,19 +7914,17 @@ fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() } SendEvent::from_event(events.remove(0)) }; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); expect_payment_received!(nodes[1], our_payment_hash, 100000); } - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); let err = nodes[0].node.send_payment(route, our_payment_hash); @@ -8498,9 +7935,9 @@ fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() } assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log( - "lightning::ln::channelmanager".to_string(), - "Cannot push more than their max accepted HTLCs".to_string(), - 1, + "lightning::ln::channelmanager".to_string(), + "Cannot push more than their max accepted HTLCs".to_string(), + 1, ); } @@ -8510,35 +7947,34 @@ fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() { let mut nodes = create_network(2, &[None, None]); let channel_value = 100000; let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - channel_value, - 0, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + channel_value, + 0, + LocalFeatures::new(), + LocalFeatures::new(), ); let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat; send_payment(&nodes[0], &vec![&nodes[1]][..], max_in_flight, max_in_flight); - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &[], - max_in_flight + 1, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &[], + max_in_flight + 1, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); let err = nodes[0].node.send_payment(route, our_payment_hash); if let Err(APIError::ChannelUnavailable { err }) = err { assert_eq!( - err, - "Cannot send value that would put us over the max HTLC value in flight our peer will accept" + err, + "Cannot send value that would put us over the max HTLC value in flight our peer will accept" ); } else { assert!(false); @@ -8559,13 +7995,13 @@ fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() { //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel. let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 95000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 100000, + 95000000, + LocalFeatures::new(), + LocalFeatures::new(), ); let htlc_minimum_msat: u64; { @@ -8573,29 +8009,27 @@ fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() { let channel = chan_lock.by_id.get(&chan.2).unwrap(); htlc_minimum_msat = channel.get_our_htlc_minimum_msat(); } - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &[], - htlc_minimum_msat, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &[], + htlc_minimum_msat, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat - 1; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[1], true).unwrap(); assert_eq!( - err_msg.data, - "Remote side tried to send less than our minimum HTLC value" + err_msg.data, + "Remote side tried to send less than our minimum HTLC value" ); } @@ -8604,36 +8038,34 @@ fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() { //BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 95000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 100000, + 95000000, + LocalFeatures::new(), + LocalFeatures::new(), ); let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat; - let route = nodes[0] - .router - .get_route( - &nodes[1].node.get_our_node_id(), - None, - &[], - 5000000 - their_channel_reserve, - TEST_FINAL_CLTV, - ) - .unwrap(); + let route = nodes[0].router + .get_route( + &nodes[1].node.get_our_node_id(), + None, + &[], + 5000000 - their_channel_reserve, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); updates.update_add_htlcs[0].amount_msat = 5000000 - their_channel_reserve + 1; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[1], true).unwrap(); @@ -8646,52 +8078,46 @@ fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() { //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash. let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 95000000, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV) - .unwrap(); + &nodes, + 0, + 1, + 100000, + 95000000, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); let session_priv = SecretKey::from_slice(&{ - let mut session_key = [0; 32]; - let mut rng = thread_rng(); - rng.fill_bytes(&mut session_key); - session_key - }) - .expect("RNG is bad!"); + let mut session_key = [0; 32]; + let mut rng = thread_rng(); + rng.fill_bytes(&mut session_key); + session_key + }).expect("RNG is bad!"); let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1; let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap(); let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap(); let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash); - let mut msg = msgs::UpdateAddHTLC { - channel_id: chan.2, - htlc_id: 0, - amount_msat: 1000, - payment_hash: our_payment_hash, - cltv_expiry: htlc_cltv, - onion_routing_packet: onion_packet.clone(), - }; + let mut msg = msgs::UpdateAddHTLC { channel_id: chan.2, + htlc_id: 0, + amount_msat: 1000, + payment_hash: our_payment_hash, + cltv_expiry: htlc_cltv, + onion_routing_packet: onion_packet.clone() }; for i in 0..super::channel::OUR_MAX_HTLCS { msg.htlc_id = i as u64; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg); } msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg); assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[1], true).unwrap(); @@ -8703,27 +8129,25 @@ fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() { //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 1000000, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) - .unwrap(); + &nodes, + 0, + 1, + 1000000, + 1000000, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[1], true).unwrap(); @@ -8735,32 +8159,30 @@ fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() { //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel. let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 100000, - 95000000, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV) - .unwrap(); + &nodes, + 0, + 1, + 100000, + 95000000, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); updates.update_add_htlcs[0].cltv_expiry = 500000000; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[1], true).unwrap(); assert_eq!( - err_msg.data, - "Remote provided CLTV expiry in seconds instead of block height" + err_msg.data, + "Remote provided CLTV expiry in seconds instead of block height" ); } @@ -8771,17 +8193,15 @@ fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() { // after disconnect and that non-sequential htlc_ids result in a channel failure. let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); //Disconnect and Reconnect nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); @@ -8792,29 +8212,24 @@ fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() { nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id()); let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]); assert_eq!(reestablish_2.len(), 1); - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); handle_chan_reestablish_msgs!(nodes[0], nodes[1]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); handle_chan_reestablish_msgs!(nodes[1], nodes[0]); //Resend HTLC - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1); - nodes[1] - .node - .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed); + nodes[1].node + .handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed); check_added_monitors!(nodes[1], 1); let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[1], true).unwrap(); @@ -8828,33 +8243,28 @@ fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() { let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) + .unwrap(); let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - - let update_msg = msgs::UpdateFulfillHTLC { - channel_id: chan.2, - htlc_id: 0, - payment_preimage: our_payment_preimage, - }; + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg); + let update_msg = msgs::UpdateFulfillHTLC { channel_id: chan.2, + htlc_id: 0, + payment_preimage: our_payment_preimage }; + + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg); assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[0], true).unwrap(); assert_eq!( - err_msg.data, - "Remote tried to fulfill/fail HTLC before it had been committed" + err_msg.data, + "Remote tried to fulfill/fail HTLC before it had been committed" ); } @@ -8865,33 +8275,28 @@ fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() { let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - - let update_msg = msgs::UpdateFailHTLC { - channel_id: chan.2, - htlc_id: 0, - reason: msgs::OnionErrorPacket { data: Vec::new() }, - }; + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg); + let update_msg = msgs::UpdateFailHTLC { channel_id: chan.2, + htlc_id: 0, + reason: msgs::OnionErrorPacket { data: Vec::new() } }; + + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg); assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[0], true).unwrap(); assert_eq!( - err_msg.data, - "Remote tried to fulfill/fail HTLC before it had been committed" + err_msg.data, + "Remote tried to fulfill/fail HTLC before it had been committed" ); } @@ -8902,34 +8307,29 @@ fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) - .unwrap(); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - - let update_msg = msgs::UpdateFailMalformedHTLC { - channel_id: chan.2, - htlc_id: 0, - sha256_of_onion: [1; 32], - failure_code: 0x8000, - }; + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - nodes[0] - .node - .handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg); + let update_msg = msgs::UpdateFailMalformedHTLC { channel_id: chan.2, + htlc_id: 0, + sha256_of_onion: [1; 32], + failure_code: 0x8000 }; + + nodes[0].node + .handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg); assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[0], true).unwrap(); assert_eq!( - err_msg.data, - "Remote tried to fulfill/fail HTLC before it had been committed" + err_msg.data, + "Remote tried to fulfill/fail HTLC before it had been committed" ); } @@ -8949,18 +8349,14 @@ fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() { assert_eq!(events.len(), 1); let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = { match events[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); assert!(update_fail_htlcs.is_empty()); @@ -8974,9 +8370,8 @@ fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() { update_fulfill_msg.htlc_id = 1; - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg); assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[0], true).unwrap(); @@ -8999,18 +8394,14 @@ fn test_update_fulfill_htlc_bolt2_wrong_preimage() { assert_eq!(events.len(), 1); let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = { match events[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert_eq!(update_fulfill_htlcs.len(), 1); assert!(update_fail_htlcs.is_empty()); @@ -9024,9 +8415,8 @@ fn test_update_fulfill_htlc_bolt2_wrong_preimage() { update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]); - nodes[0] - .node - .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg); + nodes[0].node + .handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg); assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[0], true).unwrap(); @@ -9039,18 +8429,17 @@ fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_messag let mut nodes = create_network(2, &[None, None]); create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 1000000, - LocalFeatures::new(), - LocalFeatures::new(), - ); - let route = nodes[0] - .router - .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) - .unwrap(); + &nodes, + 0, + 1, + 1000000, + 1000000, + LocalFeatures::new(), + LocalFeatures::new(), + ); + let route = nodes[0].router + .get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); nodes[0].node.send_payment(route, our_payment_hash).unwrap(); check_added_monitors!(nodes[0], 1); @@ -9058,9 +8447,8 @@ fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_messag let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true); @@ -9068,18 +8456,14 @@ fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_messag let mut update_msg: msgs::UpdateFailMalformedHTLC = { match events[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); assert!(update_fail_htlcs.is_empty()); @@ -9091,9 +8475,8 @@ fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_messag } }; update_msg.failure_code &= !0x8000; - nodes[0] - .node - .handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg); + nodes[0].node + .handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg); assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast!(nodes[0], true).unwrap(); @@ -9107,34 +8490,33 @@ fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_upda let mut nodes = create_network(3, &[None, None, None]); create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 1000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 1000000, + LocalFeatures::new(), + LocalFeatures::new(), ); create_announced_chan_between_nodes_with_value( - &nodes, - 1, - 2, - 1000000, - 1000000, - LocalFeatures::new(), - LocalFeatures::new(), - ); - - let route = nodes[0] - .router - .get_route( - &nodes[2].node.get_our_node_id(), - None, - &Vec::new(), - 100000, - TEST_FINAL_CLTV, - ) - .unwrap(); + &nodes, + 1, + 2, + 1000000, + 1000000, + LocalFeatures::new(), + LocalFeatures::new(), + ); + + let route = nodes[0].router + .get_route( + &nodes[2].node.get_our_node_id(), + None, + &Vec::new(), + 100000, + TEST_FINAL_CLTV, + ) + .unwrap(); let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]); //First hop @@ -9145,9 +8527,8 @@ fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_upda assert_eq!(events.len(), 1); SendEvent::from_event(events.remove(0)) }; - nodes[1] - .node - .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[1].node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); @@ -9159,9 +8540,8 @@ fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_upda //Second Hop payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message - nodes[2] - .node - .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); + nodes[2].node + .handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]); check_added_monitors!(nodes[2], 0); commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true); @@ -9169,18 +8549,14 @@ fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_upda assert_eq!(events_3.len(), 1); let update_msg: (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = { match events_3[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - ref commitment_signed, - }, - } => { + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + ref commitment_signed, }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); assert!(update_fail_htlcs.is_empty()); @@ -9192,9 +8568,8 @@ fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_upda } }; - nodes[1] - .node - .handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0); + nodes[1].node + .handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0); check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true); @@ -9204,18 +8579,14 @@ fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_upda //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route match events_4[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - .. - }, - } => { + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + .. }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); assert_eq!(update_fail_htlcs.len(), 1); @@ -9236,15 +8607,14 @@ fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let bs_dust_limit = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan.2) - .unwrap() - .our_dust_limit_satoshis; + let bs_dust_limit = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan.2) + .unwrap() + .our_dust_limit_satoshis; // We route 2 dust-HTLCs between A and B let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit * 1000); @@ -9252,16 +8622,15 @@ fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) { route_payment(&nodes[0], &[&nodes[1]], 1000000); // Cache one local commitment tx as previous - let as_prev_commitment_tx = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let as_prev_commitment_tx = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); // Fail one HTLC to prune it in the will-be-latest-local commitment tx assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2)); @@ -9270,25 +8639,22 @@ fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) { check_added_monitors!(nodes[1], 1); let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]); - nodes[0] - .node - .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]); + nodes[0].node + .handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed); check_added_monitors!(nodes[0], 1); // Cache one local commitment tx as lastest - let as_last_commitment_tx = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let as_last_commitment_tx = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); let events = nodes[0].node.get_and_clear_pending_msg_events(); match events[0] { @@ -9306,30 +8672,24 @@ fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) { assert_ne!(as_prev_commitment_tx, as_last_commitment_tx); // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf) - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; if announce_latest { nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![as_last_commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![as_last_commitment_tx[0].clone()], }, + 1, ); } else { nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![as_prev_commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![as_prev_commitment_tx[0].clone()], }, + 1, ); } @@ -9342,11 +8702,11 @@ fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) { assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0); connect_blocks( - &nodes[0].block_notifier, - ANTI_REORG_DELAY - 1, - 1, - true, - header.bitcoin_hash(), + &nodes[0].block_notifier, + ANTI_REORG_DELAY - 1, + 1, + true, + header.bitcoin_hash(), ); let events = nodes[0].node.get_and_clear_pending_events(); // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx @@ -9384,64 +8744,51 @@ fn test_no_failure_dust_htlc_local_commitment() { // Rebalance a bit send_payment(&nodes[0], &vec![&nodes[1]][..], 8000000, 8_000_000); - let as_dust_limit = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan.2) - .unwrap() - .our_dust_limit_satoshis; - let bs_dust_limit = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan.2) - .unwrap() - .our_dust_limit_satoshis; + let as_dust_limit = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan.2) + .unwrap() + .our_dust_limit_satoshis; + let bs_dust_limit = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan.2) + .unwrap() + .our_dust_limit_satoshis; // We route 2 dust-HTLCs between A and B let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit * 1000); let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit * 1000); // Build a dummy invalid transaction trying to spend a commitment tx - let input = TxIn { - previous_output: BitcoinOutPoint { - txid: chan.3.txid(), - vout: 0, - }, - script_sig: Script::new(), - sequence: 0, - witness: Vec::new(), - }; - - let outp = TxOut { - script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), - value: 10000, - }; - - let dummy_tx = Transaction { - version: 2, - lock_time: 0, - input: vec![input], - output: vec![outp], - }; - - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; - nodes[0] - .chan_monitor - .simple_monitor - .block_connected(&header, 1, &[&dummy_tx], &[1; 1]); + let input = TxIn { previous_output: BitcoinOutPoint { txid: chan.3.txid(), + vout: 0 }, + script_sig: Script::new(), + sequence: 0, + witness: Vec::new() }; + + let outp = TxOut { script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), + value: 10000 }; + + let dummy_tx = Transaction { version: 2, + lock_time: 0, + input: vec![input], + output: vec![outp] }; + + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; + nodes[0].chan_monitor + .simple_monitor + .block_connected(&header, 1, &[&dummy_tx], &[1; 1]); assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0); assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0); // We broadcast a few more block to check everything is all right @@ -9464,39 +8811,36 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { let nodes = create_network(3, &[None, None, None]); let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()); - let bs_dust_limit = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get(&chan.2) - .unwrap() - .our_dust_limit_satoshis; + let bs_dust_limit = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get(&chan.2) + .unwrap() + .our_dust_limit_satoshis; let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit * 1000); let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000); - let as_commitment_tx = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); - let bs_commitment_tx = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let as_commitment_tx = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); + let bs_commitment_tx = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); // We revoked bs_commitment_tx if revoked { @@ -9504,23 +8848,19 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage_3, 1_000_000); } - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; let mut timeout_tx = Vec::new(); if local { // We fail dust-HTLC 1 by broadcast of local commitment tx nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![as_commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![as_commitment_tx[0].clone()], }, + 1, ); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); @@ -9531,11 +8871,11 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0); timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone()); let parent_hash = connect_blocks( - &nodes[0].block_notifier, - ANTI_REORG_DELAY - 1, - 2, - true, - header.bitcoin_hash(), + &nodes[0].block_notifier, + ANTI_REORG_DELAY - 1, + 2, + true, + header.bitcoin_hash(), ); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); @@ -9546,40 +8886,34 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { _ => panic!("Unexpected event"), } assert_eq!( - timeout_tx[0].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + timeout_tx[0].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx - let header_2 = BlockHeader { - version: 0x20000000, - prev_blockhash: parent_hash, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_2 = BlockHeader { version: 0x20000000, + prev_blockhash: parent_hash, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0); nodes[0].block_notifier.block_connected( - &Block { - header: header_2, - txdata: vec![timeout_tx[0].clone()], - }, - 7, + &Block { header: header_2, + txdata: vec![timeout_tx[0].clone()], }, + 7, ); - let header_3 = BlockHeader { - version: 0x20000000, - prev_blockhash: header_2.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_3 = BlockHeader { version: 0x20000000, + prev_blockhash: header_2.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; connect_blocks( - &nodes[0].block_notifier, - ANTI_REORG_DELAY - 1, - 8, - true, - header_3.bitcoin_hash(), + &nodes[0].block_notifier, + ANTI_REORG_DELAY - 1, + 8, + true, + header_3.bitcoin_hash(), ); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); @@ -9592,11 +8926,9 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { } else { // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![bs_commitment_tx[0].clone()], - }, - 1, + &Block { header, + txdata: vec![bs_commitment_tx[0].clone()], }, + 1, ); assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0); let events = nodes[0].node.get_and_clear_pending_msg_events(); @@ -9607,20 +8939,18 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { } timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone()); let parent_hash = connect_blocks( - &nodes[0].block_notifier, - ANTI_REORG_DELAY - 1, - 2, - true, - header.bitcoin_hash(), + &nodes[0].block_notifier, + ANTI_REORG_DELAY - 1, + 2, + true, + header.bitcoin_hash(), ); - let header_2 = BlockHeader { - version: 0x20000000, - prev_blockhash: parent_hash, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_2 = BlockHeader { version: 0x20000000, + prev_blockhash: parent_hash, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; if !revoked { let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); @@ -9631,32 +8961,28 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) { _ => panic!("Unexpected event"), } assert_eq!( - timeout_tx[0].input[0].witness.last().unwrap().len(), - ACCEPTED_HTLC_SCRIPT_WEIGHT + timeout_tx[0].input[0].witness.last().unwrap().len(), + ACCEPTED_HTLC_SCRIPT_WEIGHT ); // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx nodes[0].block_notifier.block_connected( - &Block { - header: header_2, - txdata: vec![timeout_tx[0].clone()], - }, - 7, + &Block { header: header_2, + txdata: vec![timeout_tx[0].clone()], }, + 7, ); assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0); - let header_3 = BlockHeader { - version: 0x20000000, - prev_blockhash: header_2.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_3 = BlockHeader { version: 0x20000000, + prev_blockhash: header_2.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; connect_blocks( - &nodes[0].block_notifier, - ANTI_REORG_DELAY - 1, - 8, - true, - header_3.bitcoin_hash(), + &nodes[0].block_notifier, + ANTI_REORG_DELAY - 1, + 8, + true, + header_3.bitcoin_hash(), ); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); @@ -9719,23 +9045,20 @@ fn test_upfront_shutdown_script() { let flags = LocalFeatures::new(); let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone()); - nodes[0] - .node - .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) - .unwrap(); + nodes[0].node + .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) + .unwrap(); let mut node_0_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[2].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[2].node.get_our_node_id() ); - node_0_shutdown.scriptpubkey = Builder::new() - .push_opcode(opcodes::all::OP_RETURN) - .into_script() - .to_p2sh(); + node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN) + .into_script() + .to_p2sh(); // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer - nodes[2] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); + nodes[2].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); let events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 2); match events[0] { @@ -9746,8 +9069,8 @@ fn test_upfront_shutdown_script() { match action { &ErrorAction::SendErrorMessage { ref msg } => { assert_eq!( - msg.data, - "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey" + msg.data, + "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey" ); }, _ => { @@ -9761,19 +9084,17 @@ fn test_upfront_shutdown_script() { // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone()); - nodes[0] - .node - .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) - .unwrap(); + nodes[0].node + .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) + .unwrap(); let node_0_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[2].node.get_our_node_id() + nodes[0], + MessageSendEvent::SendShutdown, + nodes[2].node.get_our_node_id() ); // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign - nodes[2] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); + nodes[2].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown); let events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { @@ -9785,22 +9106,19 @@ fn test_upfront_shutdown_script() { let mut flags_no = LocalFeatures::new(); flags_no.unset_upfront_shutdown_script(); let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone()); - nodes[0] - .node - .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) - .unwrap(); + nodes[0].node + .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) + .unwrap(); let mut node_1_shutdown = get_event_msg!( - nodes[0], - MessageSendEvent::SendShutdown, - nodes[1].node.get_our_node_id() - ); - node_1_shutdown.scriptpubkey = Builder::new() - .push_opcode(opcodes::all::OP_RETURN) - .into_script() - .to_p2sh(); - nodes[1] - .node - .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown); + nodes[0], + MessageSendEvent::SendShutdown, + nodes[1].node.get_our_node_id() + ); + node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN) + .into_script() + .to_p2sh(); + nodes[1].node + .handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown); let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { @@ -9812,22 +9130,19 @@ fn test_upfront_shutdown_script() { // channel smoothly, opt-out is from channel initiator here let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone()); - nodes[1] - .node - .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) - .unwrap(); + nodes[1].node + .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) + .unwrap(); let mut node_0_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() - ); - node_0_shutdown.scriptpubkey = Builder::new() - .push_opcode(opcodes::all::OP_RETURN) - .into_script() - .to_p2sh(); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown); + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() + ); + node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN) + .into_script() + .to_p2sh(); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match events[0] { @@ -9839,22 +9154,19 @@ fn test_upfront_shutdown_script() { //// channel smoothly let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone()); - nodes[1] - .node - .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) - .unwrap(); + nodes[1].node + .close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()) + .unwrap(); let mut node_0_shutdown = get_event_msg!( - nodes[1], - MessageSendEvent::SendShutdown, - nodes[0].node.get_our_node_id() - ); - node_0_shutdown.scriptpubkey = Builder::new() - .push_opcode(opcodes::all::OP_RETURN) - .into_script() - .to_p2sh(); - nodes[0] - .node - .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown); + nodes[1], + MessageSendEvent::SendShutdown, + nodes[0].node.get_our_node_id() + ); + node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN) + .into_script() + .to_p2sh(); + nodes[0].node + .handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 2); match events[0] { @@ -9886,20 +9198,20 @@ fn test_user_configurable_csv_delay() { Arc::new(test_utils::TestLogger::new()), )); if let Err(error) = Channel::new_outbound( - &test_utils::TestFeeEstimator { sat_per_kw: 253 }, - &keys_manager, - nodes[1].node.get_our_node_id(), - 1000000, - 1000000, - 0, - Arc::new(test_utils::TestLogger::new()), - &low_our_to_self_config, + &test_utils::TestFeeEstimator { sat_per_kw: 253 }, + &keys_manager, + nodes[1].node.get_our_node_id(), + 1000000, + 1000000, + 0, + Arc::new(test_utils::TestLogger::new()), + &low_our_to_self_config, ) { match error { APIError::APIMisuseError { err } => { assert_eq!( - err, - "Configured with an unreasonable our_to_self_delay putting user funds at risks" + err, + "Configured with an unreasonable our_to_self_delay putting user funds at risks" ); }, _ => panic!("Unexpected event"), @@ -9909,31 +9221,30 @@ fn test_user_configurable_csv_delay() { } // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req() - nodes[1] - .node - .create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42) - .unwrap(); + nodes[1].node + .create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42) + .unwrap(); let mut open_channel = get_event_msg!( - nodes[1], - MessageSendEvent::SendOpenChannel, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendOpenChannel, + nodes[0].node.get_our_node_id() ); open_channel.to_self_delay = 200; if let Err(error) = Channel::new_from_req( - &test_utils::TestFeeEstimator { sat_per_kw: 253 }, - &keys_manager, - nodes[1].node.get_our_node_id(), - LocalFeatures::new(), - &open_channel, - 0, - Arc::new(test_utils::TestLogger::new()), - &low_our_to_self_config, + &test_utils::TestFeeEstimator { sat_per_kw: 253 }, + &keys_manager, + nodes[1].node.get_our_node_id(), + LocalFeatures::new(), + &open_channel, + 0, + Arc::new(test_utils::TestLogger::new()), + &low_our_to_self_config, ) { match error { ChannelError::Close(err) => { assert_eq!( - err, - "Configured with an unreasonable our_to_self_delay putting user funds at risks" + err, + "Configured with an unreasonable our_to_self_delay putting user funds at risks" ); }, _ => panic!("Unexpected event"), @@ -9943,34 +9254,32 @@ fn test_user_configurable_csv_delay() { } // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel() - nodes[0] - .node - .create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42) - .unwrap(); + nodes[0].node + .create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42) + .unwrap(); nodes[1].node.handle_open_channel( - &nodes[0].node.get_our_node_id(), - LocalFeatures::new(), - &get_event_msg!( - nodes[0], - MessageSendEvent::SendOpenChannel, - nodes[1].node.get_our_node_id() - ), + &nodes[0].node.get_our_node_id(), + LocalFeatures::new(), + &get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ), ); let mut accept_channel = get_event_msg!( - nodes[1], - MessageSendEvent::SendAcceptChannel, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendAcceptChannel, + nodes[0].node.get_our_node_id() ); accept_channel.to_self_delay = 200; - nodes[0] - .node - .handle_accept_channel(&nodes[1].node.get_our_node_id(), LocalFeatures::new(), &accept_channel); + nodes[0].node + .handle_accept_channel(&nodes[1].node.get_our_node_id(), LocalFeatures::new(), &accept_channel); if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] { match action { &ErrorAction::SendErrorMessage { ref msg } => { assert_eq!( - msg.data, - "They wanted our payments to be delayed by a needlessly long period" + msg.data, + "They wanted our payments to be delayed by a needlessly long period" ); }, _ => { @@ -9982,31 +9291,30 @@ fn test_user_configurable_csv_delay() { } // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req() - nodes[1] - .node - .create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42) - .unwrap(); + nodes[1].node + .create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42) + .unwrap(); let mut open_channel = get_event_msg!( - nodes[1], - MessageSendEvent::SendOpenChannel, - nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendOpenChannel, + nodes[0].node.get_our_node_id() ); open_channel.to_self_delay = 200; if let Err(error) = Channel::new_from_req( - &test_utils::TestFeeEstimator { sat_per_kw: 253 }, - &keys_manager, - nodes[1].node.get_our_node_id(), - LocalFeatures::new(), - &open_channel, - 0, - Arc::new(test_utils::TestLogger::new()), - &high_their_to_self_config, + &test_utils::TestFeeEstimator { sat_per_kw: 253 }, + &keys_manager, + nodes[1].node.get_our_node_id(), + LocalFeatures::new(), + &open_channel, + 0, + Arc::new(test_utils::TestLogger::new()), + &high_their_to_self_config, ) { match error { ChannelError::Close(err) => { assert_eq!( - err, - "They wanted our payments to be delayed by a needlessly long period" + err, + "They wanted our payments to be delayed by a needlessly long period" ); }, _ => panic!("Unexpected event"), @@ -10025,30 +9333,29 @@ fn test_data_loss_protect() { let mut nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 1000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 1000000, + LocalFeatures::new(), + LocalFeatures::new(), ); // Cache node A state before any channel update let previous_node_state = nodes[0].node.encode(); let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new()); - nodes[0] - .chan_monitor - .simple_monitor - .monitors - .lock() - .unwrap() - .iter() - .next() - .unwrap() - .1 - .write_for_disk(&mut previous_chan_monitor_state) - .unwrap(); + nodes[0].chan_monitor + .simple_monitor + .monitors + .lock() + .unwrap() + .iter() + .next() + .unwrap() + .1 + .write_for_disk(&mut previous_chan_monitor_state) + .unwrap(); send_payment(&nodes[0], &vec![&nodes[1]][..], 8000000, 8_000_000); send_payment(&nodes[0], &vec![&nodes[1]][..], 8000000, 8_000_000); @@ -10058,16 +9365,14 @@ fn test_data_loss_protect() { // Restore node A from previous state let logger: Arc = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0))); - let mut chan_monitor = <(Sha256dHash, ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(previous_chan_monitor_state.0), - Arc::clone(&logger), - ) - .unwrap() - .1; + let mut chan_monitor = + <(Sha256dHash, ChannelMonitor)>::read( + &mut ::std::io::Cursor::new(previous_chan_monitor_state.0), + Arc::clone(&logger), + ).unwrap() + .1; let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger))); - let tx_broadcaster = Arc::new(test_utils::TestBroadcaster { - txn_broadcasted: Mutex::new(Vec::new()), - }); + let tx_broadcaster = Arc::new(test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()) }); let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }); let monitor = Arc::new(test_utils::TestChannelMonitor::new( chain_monitor.clone(), @@ -10078,11 +9383,9 @@ fn test_data_loss_protect() { let node_state_0 = { let mut channel_monitors = HashMap::new(); channel_monitors.insert( - OutPoint { - txid: chan.3.txid(), - index: 0, - }, - &mut chan_monitor, + OutPoint { txid: chan.3.txid(), + index: 0, }, + &mut chan_monitor, ); <(Sha256dHash, ChannelManager)>::read( &mut ::std::io::Cursor::new(previous_node_state), @@ -10104,15 +9407,12 @@ fn test_data_loss_protect() { .1 }; nodes[0].node = Arc::new(node_state_0); - assert!(monitor - .add_update_monitor( - OutPoint { - txid: chan.3.txid(), - index: 0 - }, - chan_monitor.clone() - ) - .is_ok()); + assert!(monitor.add_update_monitor( + OutPoint { txid: chan.3.txid(), + index: 0 }, + chan_monitor.clone() + ) + .is_ok()); nodes[0].chan_monitor = monitor; nodes[0].chain_monitor = chain_monitor; @@ -10129,9 +9429,8 @@ fn test_data_loss_protect() { let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]); // Check we update monitor following learning of per_commitment_point from B - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]); check_added_monitors!(nodes[0], 1); { @@ -10158,9 +9457,8 @@ fn test_data_loss_protect() { } // Check we close channel detecting A is fallen-behind - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 2); match events[0] { @@ -10171,8 +9469,8 @@ fn test_data_loss_protect() { MessageSendEvent::HandleError { ref action, .. } => match action { &ErrorAction::SendErrorMessage { ref msg } => { assert_eq!( - msg.data, - "Peer attempted to reestablish channel with a very old local commitment transaction" + msg.data, + "Peer attempted to reestablish channel with a very old local commitment transaction" ); }, _ => panic!("Unexpected event!"), @@ -10185,20 +9483,16 @@ fn test_data_loss_protect() { assert_eq!(node_txn.len(), 1); check_spends!(node_txn[0], chan.3.clone()); assert_eq!(node_txn[0].output.len(), 2); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![node_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![node_txn[0].clone()], }, + 1, ); let spend_txn = check_spendable_outputs!(nodes[0], 1); assert_eq!(spend_txn.len(), 1); @@ -10226,18 +9520,14 @@ fn test_check_htlc_underpaying() { let events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let (update_fail_htlc, commitment_signed) = match events[0] { - MessageSendEvent::UpdateHTLCs { - node_id: _, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - ref commitment_signed, - }, - } => { + MessageSendEvent::UpdateHTLCs { node_id: _, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + ref commitment_signed, }, } => { assert!(update_add_htlcs.is_empty()); assert!(update_fulfill_htlcs.is_empty()); assert_eq!(update_fail_htlcs.len(), 1); @@ -10249,18 +9539,15 @@ fn test_check_htlc_underpaying() { }; check_added_monitors!(nodes[1], 1); - nodes[0] - .node - .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc); + nodes[0].node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc); commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let &Event::PaymentFailed { - payment_hash: _, - ref rejected_by_dest, - ref error_code, - } = &events[0] + if let &Event::PaymentFailed { payment_hash: _, + ref rejected_by_dest, + ref error_code, } = &events[0] { assert_eq!(*rejected_by_dest, true); assert_eq!(error_code.unwrap(), 0x4000 | 15); @@ -10277,18 +9564,18 @@ fn test_announce_disable_channels() { let nodes = create_network(2, &[None, None]); - let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()) - .0 - .contents - .short_channel_id; - let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, LocalFeatures::new(), LocalFeatures::new()) - .0 - .contents - .short_channel_id; - let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()) - .0 - .contents - .short_channel_id; + let short_id_1 = + create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()).0 + .contents + .short_channel_id; + let short_id_2 = + create_announced_chan_between_nodes(&nodes, 1, 0, LocalFeatures::new(), LocalFeatures::new()).0 + .contents + .short_channel_id; + let short_id_3 = + create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()).0 + .contents + .short_channel_id; // Disconnect peers nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); @@ -10319,31 +9606,25 @@ fn test_announce_disable_channels() { assert_eq!(reestablish_2.len(), 3); // Reestablish chan_1 - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]); handle_chan_reestablish_msgs!(nodes[0], nodes[1]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]); handle_chan_reestablish_msgs!(nodes[1], nodes[0]); // Reestablish chan_2 - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]); handle_chan_reestablish_msgs!(nodes[0], nodes[1]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]); handle_chan_reestablish_msgs!(nodes[1], nodes[0]); // Reestablish chan_3 - nodes[0] - .node - .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]); + nodes[0].node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]); handle_chan_reestablish_msgs!(nodes[0], nodes[1]); - nodes[1] - .node - .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]); + nodes[1].node + .handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]); handle_chan_reestablish_msgs!(nodes[1], nodes[0]); nodes[0].node.timer_chan_freshness_every_min(); @@ -10358,31 +9639,29 @@ fn test_bump_penalty_txn_on_revoked_commitment() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 59000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 59000000, + LocalFeatures::new(), + LocalFeatures::new(), ); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; - let route = nodes[1] - .router - .get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30) - .unwrap(); + let route = nodes[1].router + .get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30) + .unwrap(); send_along_route(&nodes[1], route, &vec![&nodes[0]][..], 3000000); - let revoked_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC assert_eq!(revoked_txn[0].output.len(), 4); assert_eq!(revoked_txn[0].input.len(), 1); @@ -10401,20 +9680,16 @@ fn test_bump_penalty_txn_on_revoked_commitment() { // Actually revoke tx by claiming a HTLC claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: header_114, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: header_114, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_txn[0].clone()], - }, - 115, + &Block { header, + txdata: vec![revoked_txn[0].clone()], }, + 115, ); // One or more justice tx should have been broadcast, check it @@ -10491,49 +9766,44 @@ fn test_bump_penalty_txn_on_revoked_htlcs() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 59000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 59000000, + LocalFeatures::new(), + LocalFeatures::new(), ); // Lock HTLC in both directions let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3_000_000).0; route_payment(&nodes[1], &vec![&nodes[0]][..], 3_000_000).0; - let revoked_local_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid()); // Revoke local commitment tx claim_payment(&nodes[0], &vec![&nodes[1]][..], payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![revoked_local_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![revoked_local_txn[0].clone()], }, + 1, ); check_closed_broadcast!(nodes[1], false); @@ -10546,8 +9816,8 @@ fn test_bump_penalty_txn_on_revoked_htlcs() { check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone()); assert_eq!(revoked_htlc_txn[1].input.len(), 1); assert_eq!( - revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); check_spends!(revoked_htlc_txn[1], revoked_local_txn[0].clone()); received = 0; @@ -10557,8 +9827,8 @@ fn test_bump_penalty_txn_on_revoked_htlcs() { check_spends!(revoked_htlc_txn[1], revoked_local_txn[0].clone()); assert_eq!(revoked_htlc_txn[0].input.len(), 1); assert_eq!( - revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), - OFFERED_HTLC_SCRIPT_WEIGHT + revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), + OFFERED_HTLC_SCRIPT_WEIGHT ); check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone()); received = 1; @@ -10567,24 +9837,20 @@ fn test_bump_penalty_txn_on_revoked_htlcs() { // Broadcast set of revoked txn on A let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash()); - let header_129 = BlockHeader { - version: 0x20000000, - prev_blockhash: header_128, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_129 = BlockHeader { version: 0x20000000, + prev_blockhash: header_128, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header: header_129, - txdata: vec![ - revoked_local_txn[0].clone(), - revoked_htlc_txn[0].clone(), - revoked_htlc_txn[1].clone(), - ], - }, - 129, + &Block { header: header_129, + txdata: vec![ + revoked_local_txn[0].clone(), + revoked_htlc_txn[0].clone(), + revoked_htlc_txn[1].clone(), + ], }, + 129, ); let first; let second; @@ -10658,20 +9924,16 @@ fn test_bump_penalty_txn_on_revoked_htlcs() { txn }; // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs - let header_133 = BlockHeader { - version: 0x20000000, - prev_blockhash: header_132, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_133 = BlockHeader { version: 0x20000000, + prev_blockhash: header_132, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header: header_133, - txdata: node_txn, - }, - 133, + &Block { header: header_133, + txdata: node_txn, }, + 133, ); let header_140 = connect_blocks(&nodes[0].block_notifier, 6, 134, true, header_133.bitcoin_hash()); { @@ -10701,48 +9963,43 @@ fn test_bump_penalty_txn_on_remote_commitment() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 59000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 59000000, + LocalFeatures::new(), + LocalFeatures::new(), ); let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 3000000).0; route_payment(&nodes[1], &vec![&nodes[0]][..], 3000000).0; // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC - let remote_txn = nodes[0] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let remote_txn = nodes[0].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(remote_txn[0].output.len(), 4); assert_eq!(remote_txn[0].input.len(), 1); assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid()); // Claim a HTLC without revocation (provide B monitor with preimage) nodes[1].node.claim_funds(payment_preimage, 3_000_000); - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: Default::default(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: Default::default(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[1].block_notifier.block_connected( - &Block { - header, - txdata: vec![remote_txn[0].clone()], - }, - 1, + &Block { header, + txdata: vec![remote_txn[0].clone()], }, + 1, ); check_added_monitors!(nodes[1], 1); @@ -10838,28 +10095,27 @@ fn test_set_outpoints_partial_claiming() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 59000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 59000000, + LocalFeatures::new(), + LocalFeatures::new(), ); let payment_preimage_1 = route_payment(&nodes[1], &vec![&nodes[0]][..], 3_000_000).0; let payment_preimage_2 = route_payment(&nodes[1], &vec![&nodes[0]][..], 3_000_000).0; // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC - let remote_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let remote_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(remote_txn.len(), 3); assert_eq!(remote_txn[0].output.len(), 4); assert_eq!(remote_txn[0].input.len(), 1); @@ -10877,20 +10133,16 @@ fn test_set_outpoints_partial_claiming() { nodes[0].node.get_and_clear_pending_msg_events(); // Connect blocks on node A commitment transaction - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: prev_header_100, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: prev_header_100, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![remote_txn[0].clone()], - }, - 101, + &Block { header, + txdata: vec![remote_txn[0].clone()], }, + 101, ); // Verify node A broadcast tx claiming both HTLCs { @@ -10921,20 +10173,16 @@ fn test_set_outpoints_partial_claiming() { nodes[1].node.get_and_clear_pending_msg_events(); // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped - let header = BlockHeader { - version: 0x20000000, - prev_blockhash: header.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header = BlockHeader { version: 0x20000000, + prev_blockhash: header.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header, - txdata: vec![partial_claim_tx.clone()], - }, - 102, + &Block { header, + txdata: vec![partial_claim_tx.clone()], }, + 102, ); { let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap(); @@ -10973,28 +10221,27 @@ fn test_bump_txn_sanitize_tracking_maps() { let nodes = create_network(2, &[None, None]); let chan = create_announced_chan_between_nodes_with_value( - &nodes, - 0, - 1, - 1000000, - 59000000, - LocalFeatures::new(), - LocalFeatures::new(), + &nodes, + 0, + 1, + 1000000, + 59000000, + LocalFeatures::new(), + LocalFeatures::new(), ); // Lock HTLC in both directions let payment_preimage = route_payment(&nodes[0], &vec![&nodes[1]][..], 9_000_000).0; route_payment(&nodes[1], &vec![&nodes[0]][..], 9_000_000).0; - let revoked_local_txn = nodes[1] - .node - .channel_state - .lock() - .unwrap() - .by_id - .get_mut(&chan.2) - .unwrap() - .channel_monitor() - .get_latest_local_commitment_txn(); + let revoked_local_txn = nodes[1].node + .channel_state + .lock() + .unwrap() + .by_id + .get_mut(&chan.2) + .unwrap() + .channel_monitor() + .get_latest_local_commitment_txn(); assert_eq!(revoked_local_txn[0].input.len(), 1); assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid()); @@ -11003,20 +10250,16 @@ fn test_bump_txn_sanitize_tracking_maps() { // Broadcast set of revoked txn on A let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default()); - let header_129 = BlockHeader { - version: 0x20000000, - prev_blockhash: header_128, - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_129 = BlockHeader { version: 0x20000000, + prev_blockhash: header_128, + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header: header_129, - txdata: vec![revoked_local_txn[0].clone()], - }, - 129, + &Block { header: header_129, + txdata: vec![revoked_local_txn[0].clone()], }, + 129, ); check_closed_broadcast!(nodes[0], false); let penalty_txn = { @@ -11029,20 +10272,16 @@ fn test_bump_txn_sanitize_tracking_maps() { node_txn.clear(); penalty_txn }; - let header_130 = BlockHeader { - version: 0x20000000, - prev_blockhash: header_129.bitcoin_hash(), - merkle_root: Default::default(), - time: 42, - bits: 42, - nonce: 42, - }; + let header_130 = BlockHeader { version: 0x20000000, + prev_blockhash: header_129.bitcoin_hash(), + merkle_root: Default::default(), + time: 42, + bits: 42, + nonce: 42 }; nodes[0].block_notifier.block_connected( - &Block { - header: header_130, - txdata: penalty_txn, - }, - 130, + &Block { header: header_130, + txdata: penalty_txn, }, + 130, ); connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash()); { diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index 93deec1ac8b..0bc2e4ba4bb 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -61,17 +61,9 @@ pub struct LocalFeatures { impl LocalFeatures { /// Create a blank LocalFeatures flags (visibility extended for fuzz tests) #[cfg(not(feature = "fuzztarget"))] - pub(crate) fn new() -> LocalFeatures { - LocalFeatures { - flags: vec![2 | 1 << 5], - } - } + pub(crate) fn new() -> LocalFeatures { LocalFeatures { flags: vec![2 | 1 << 5] } } #[cfg(feature = "fuzztarget")] - pub fn new() -> LocalFeatures { - LocalFeatures { - flags: vec![2 | 1 << 5], - } - } + pub fn new() -> LocalFeatures { LocalFeatures { flags: vec![2 | 1 << 5] } } pub(crate) fn supports_data_loss_protect(&self) -> bool { self.flags.len() > 0 && (self.flags[0] & 3) != 0 } pub(crate) fn initial_routing_sync(&self) -> bool { self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0 } @@ -91,16 +83,16 @@ impl LocalFeatures { pub(crate) fn requires_unknown_bits(&self) -> bool { self.flags - .iter() - .enumerate() - .any(|(idx, &byte)| (idx != 0 && (byte & 0x55) != 0) || (idx == 0 && (byte & 0x14) != 0)) + .iter() + .enumerate() + .any(|(idx, &byte)| (idx != 0 && (byte & 0x55) != 0) || (idx == 0 && (byte & 0x14) != 0)) } pub(crate) fn supports_unknown_bits(&self) -> bool { self.flags - .iter() - .enumerate() - .any(|(idx, &byte)| (idx != 0 && byte != 0) || (idx == 0 && (byte & 0xc4) != 0)) + .iter() + .enumerate() + .any(|(idx, &byte)| (idx != 0 && byte != 0) || (idx == 0 && (byte & 0xc4) != 0)) } } @@ -402,12 +394,10 @@ impl Writeable for NetAddress { addr.write(writer)?; port.write(writer)?; }, - &NetAddress::OnionV3 { - ref ed25519_pubkey, - ref checksum, - ref version, - ref port, - } => { + &NetAddress::OnionV3 { ref ed25519_pubkey, + ref checksum, + ref version, + ref port, } => { 4u8.write(writer)?; ed25519_pubkey.write(writer)?; checksum.write(writer)?; @@ -423,24 +413,16 @@ impl Readable for Result { fn read(reader: &mut R) -> Result, DecodeError> { let byte = >::read(reader)?; match byte { - 1 => Ok(Ok(NetAddress::IPv4 { - addr: Readable::read(reader)?, - port: Readable::read(reader)?, - })), - 2 => Ok(Ok(NetAddress::IPv6 { - addr: Readable::read(reader)?, - port: Readable::read(reader)?, - })), - 3 => Ok(Ok(NetAddress::OnionV2 { - addr: Readable::read(reader)?, - port: Readable::read(reader)?, - })), - 4 => Ok(Ok(NetAddress::OnionV3 { - ed25519_pubkey: Readable::read(reader)?, - checksum: Readable::read(reader)?, - version: Readable::read(reader)?, - port: Readable::read(reader)?, - })), + 1 => Ok(Ok(NetAddress::IPv4 { addr: Readable::read(reader)?, + port: Readable::read(reader)? })), + 2 => Ok(Ok(NetAddress::IPv6 { addr: Readable::read(reader)?, + port: Readable::read(reader)? })), + 3 => Ok(Ok(NetAddress::OnionV2 { addr: Readable::read(reader)?, + port: Readable::read(reader)? })), + 4 => Ok(Ok(NetAddress::OnionV3 { ed25519_pubkey: Readable::read(reader)?, + checksum: Readable::read(reader)?, + version: Readable::read(reader)?, + port: Readable::read(reader)? })), _ => return Ok(Err(byte)), } } @@ -607,12 +589,10 @@ pub trait ChannelMessageHandler: events::MessageSendEventsProvider + Send + Sync /// Handle an incoming open_channel message from the given peer. fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &OpenChannel); /// Handle an incoming accept_channel message from the given peer. - fn handle_accept_channel( - &self, - their_node_id: &PublicKey, - their_local_features: LocalFeatures, - msg: &AcceptChannel, - ); + fn handle_accept_channel(&self, + their_node_id: &PublicKey, + their_local_features: LocalFeatures, + msg: &AcceptChannel); /// Handle an incoming funding_created message from the given peer. fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated); /// Handle an incoming funding_signed message from the given peer. @@ -680,19 +660,17 @@ pub trait RoutingMessageHandler: Send + Sync { /// Gets a subset of the channel announcements and updates required to dump our routing table /// to a remote node, starting at the short_channel_id indicated by starting_point and /// including batch_amount entries. - fn get_next_channel_announcements( - &self, - starting_point: u64, - batch_amount: u8, - ) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>; + fn get_next_channel_announcements(&self, + starting_point: u64, + batch_amount: u8) + -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>; /// Gets a subset of the node announcements required to dump our routing table to a remote node, /// starting at the node *after* the provided publickey and including batch_amount entries. /// If None is provided for starting_point, we start at the first node. - fn get_next_node_announcements( - &self, - starting_point: Option<&PublicKey>, - batch_amount: u8, - ) -> Vec; + fn get_next_node_announcements(&self, + starting_point: Option<&PublicKey>, + batch_amount: u8) + -> Vec; } pub(crate) struct OnionRealm0HopData { @@ -844,10 +822,10 @@ impl_writeable!(AnnouncementSignatures, 32+8+64*2, { impl Writeable for ChannelReestablish { fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { - 32 + 2 * 8 + 33 + 32 - } else { - 32 + 2 * 8 - }); + 32 + 2 * 8 + 33 + 32 + } else { + 32 + 2 * 8 + }); self.channel_id.write(w)?; self.next_local_commitment_number.write(w)?; self.next_remote_commitment_number.write(w)?; @@ -864,21 +842,20 @@ impl Writeable for ChannelReestablish { impl Readable for ChannelReestablish { fn read(r: &mut R) -> Result { - Ok(Self { - channel_id: Readable::read(r)?, - next_local_commitment_number: Readable::read(r)?, - next_remote_commitment_number: Readable::read(r)?, - data_loss_protect: { - match <[u8; 32] as Readable>::read(r) { - Ok(your_last_per_commitment_secret) => OptionalField::Present(DataLossProtect { - your_last_per_commitment_secret, - my_current_per_commitment_point: Readable::read(r)?, - }), - Err(DecodeError::ShortRead) => OptionalField::Absent, - Err(e) => return Err(e), - } - }, - }) + Ok(Self { channel_id: Readable::read(r)?, + next_local_commitment_number: Readable::read(r)?, + next_remote_commitment_number: Readable::read(r)?, + data_loss_protect: { + match <[u8; 32] as Readable>::read(r) { + Ok(your_last_per_commitment_secret) => { + OptionalField::Present(DataLossProtect { your_last_per_commitment_secret, + my_current_per_commitment_point: + Readable::read(r)? }) + }, + Err(DecodeError::ShortRead) => OptionalField::Absent, + Err(e) => return Err(e), + } + } }) } } @@ -1026,16 +1003,14 @@ impl Writeable for OnionPacket { impl Readable for OnionPacket { fn read(r: &mut R) -> Result { - Ok(OnionPacket { - version: Readable::read(r)?, - public_key: { - let mut buf = [0u8; 33]; - r.read_exact(&mut buf)?; - PublicKey::from_slice(&buf) - }, - hop_data: Readable::read(r)?, - hmac: Readable::read(r)?, - }) + Ok(OnionPacket { version: Readable::read(r)?, + public_key: { + let mut buf = [0u8; 33]; + r.read_exact(&mut buf)?; + PublicKey::from_slice(&buf) + }, + hop_data: Readable::read(r)?, + hmac: Readable::read(r)? }) } } @@ -1061,15 +1036,13 @@ impl Writeable for OnionRealm0HopData { impl Readable for OnionRealm0HopData { fn read(r: &mut R) -> Result { - Ok(OnionRealm0HopData { - short_channel_id: Readable::read(r)?, - amt_to_forward: Readable::read(r)?, - outgoing_cltv_value: { - let v: u32 = Readable::read(r)?; - r.read_exact(&mut [0; 12])?; - v - }, - }) + Ok(OnionRealm0HopData { short_channel_id: Readable::read(r)?, + amt_to_forward: Readable::read(r)?, + outgoing_cltv_value: { + let v: u32 = Readable::read(r)?; + r.read_exact(&mut [0; 12])?; + v + } }) } } @@ -1085,17 +1058,15 @@ impl Writeable for OnionHopData { impl Readable for OnionHopData { fn read(r: &mut R) -> Result { - Ok(OnionHopData { - realm: { - let r: u8 = Readable::read(r)?; - if r != 0 { - return Err(DecodeError::UnknownVersion); - } - r - }, - data: Readable::read(r)?, - hmac: Readable::read(r)?, - }) + Ok(OnionHopData { realm: { + let r: u8 = Readable::read(r)?; + if r != 0 { + return Err(DecodeError::UnknownVersion); + } + r + }, + data: Readable::read(r)?, + hmac: Readable::read(r)? }) } } @@ -1110,14 +1081,12 @@ impl Writeable for Ping { impl Readable for Ping { fn read(r: &mut R) -> Result { - Ok(Ping { - ponglen: Readable::read(r)?, - byteslen: { - let byteslen = Readable::read(r)?; - r.read_exact(&mut vec![0u8; byteslen as usize][..])?; - byteslen - }, - }) + Ok(Ping { ponglen: Readable::read(r)?, + byteslen: { + let byteslen = Readable::read(r)?; + r.read_exact(&mut vec![0u8; byteslen as usize][..])?; + byteslen + } }) } } @@ -1131,13 +1100,11 @@ impl Writeable for Pong { impl Readable for Pong { fn read(r: &mut R) -> Result { - Ok(Pong { - byteslen: { - let byteslen = Readable::read(r)?; - r.read_exact(&mut vec![0u8; byteslen as usize][..])?; - byteslen - }, - }) + Ok(Pong { byteslen: { + let byteslen = Readable::read(r)?; + r.read_exact(&mut vec![0u8; byteslen as usize][..])?; + byteslen + } }) } } @@ -1158,26 +1125,24 @@ impl Writeable for UnsignedChannelAnnouncement { impl Readable for UnsignedChannelAnnouncement { fn read(r: &mut R) -> Result { - Ok(Self { - features: { - let f: GlobalFeatures = Readable::read(r)?; - if f.requires_unknown_bits() { - return Err(DecodeError::UnknownRequiredFeature); - } - f - }, - chain_hash: Readable::read(r)?, - short_channel_id: Readable::read(r)?, - node_id_1: Readable::read(r)?, - node_id_2: Readable::read(r)?, - bitcoin_key_1: Readable::read(r)?, - bitcoin_key_2: Readable::read(r)?, - excess_data: { - let mut excess_data = vec![]; - r.read_to_end(&mut excess_data)?; - excess_data - }, - }) + Ok(Self { features: { + let f: GlobalFeatures = Readable::read(r)?; + if f.requires_unknown_bits() { + return Err(DecodeError::UnknownRequiredFeature); + } + f + }, + chain_hash: Readable::read(r)?, + short_channel_id: Readable::read(r)?, + node_id_1: Readable::read(r)?, + node_id_2: Readable::read(r)?, + bitcoin_key_1: Readable::read(r)?, + bitcoin_key_2: Readable::read(r)?, + excess_data: { + let mut excess_data = vec![]; + r.read_to_end(&mut excess_data)?; + excess_data + } }) } } @@ -1210,21 +1175,19 @@ impl Writeable for UnsignedChannelUpdate { impl Readable for UnsignedChannelUpdate { fn read(r: &mut R) -> Result { - Ok(Self { - chain_hash: Readable::read(r)?, - short_channel_id: Readable::read(r)?, - timestamp: Readable::read(r)?, - flags: Readable::read(r)?, - cltv_expiry_delta: Readable::read(r)?, - htlc_minimum_msat: Readable::read(r)?, - fee_base_msat: Readable::read(r)?, - fee_proportional_millionths: Readable::read(r)?, - excess_data: { - let mut excess_data = vec![]; - r.read_to_end(&mut excess_data)?; - excess_data - }, - }) + Ok(Self { chain_hash: Readable::read(r)?, + short_channel_id: Readable::read(r)?, + timestamp: Readable::read(r)?, + flags: Readable::read(r)?, + cltv_expiry_delta: Readable::read(r)?, + htlc_minimum_msat: Readable::read(r)?, + fee_base_msat: Readable::read(r)?, + fee_proportional_millionths: Readable::read(r)?, + excess_data: { + let mut excess_data = vec![]; + r.read_to_end(&mut excess_data)?; + excess_data + } }) } } @@ -1248,30 +1211,28 @@ impl Writeable for ErrorMessage { impl Readable for ErrorMessage { fn read(r: &mut R) -> Result { - Ok(Self { - channel_id: Readable::read(r)?, - data: { - let mut sz: usize = >::read(r)? as usize; - let mut data = vec![]; - let data_len = r.read_to_end(&mut data)?; - sz = cmp::min(data_len, sz); - match String::from_utf8(data[..sz as usize].to_vec()) { - Ok(s) => s, - Err(_) => return Err(DecodeError::InvalidValue), - } - }, - }) + Ok(Self { channel_id: Readable::read(r)?, + data: { + let mut sz: usize = >::read(r)? as usize; + let mut data = vec![]; + let data_len = r.read_to_end(&mut data)?; + sz = cmp::min(data_len, sz); + match String::from_utf8(data[..sz as usize].to_vec()) { + Ok(s) => s, + Err(_) => return Err(DecodeError::InvalidValue), + } + } }) } } impl Writeable for UnsignedNodeAnnouncement { fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { w.size_hint( - 64 + 76 - + self.features.flags.len() - + self.addresses.len() * 38 - + self.excess_address_data.len() - + self.excess_data.len(), + 64 + + 76 + self.features.flags.len() + + self.addresses.len() * 38 + + self.excess_address_data.len() + + self.excess_data.len(), ); self.features.write(w)?; self.timestamp.write(w)?; @@ -1372,16 +1333,14 @@ impl Readable for UnsignedNodeAnnouncement { Vec::new() }; r.read_to_end(&mut excess_data)?; - Ok(UnsignedNodeAnnouncement { - features, - timestamp, - node_id, - rgb, - alias, - addresses, - excess_address_data, - excess_data, - }) + Ok(UnsignedNodeAnnouncement { features, + timestamp, + node_id, + rgb, + alias, + addresses, + excess_address_data, + excess_data }) } } @@ -1413,22 +1372,21 @@ mod tests { #[test] fn encoding_channel_reestablish_no_secret() { - let cr = msgs::ChannelReestablish { - channel_id: [ - 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, - ], - next_local_commitment_number: 3, - next_remote_commitment_number: 4, - data_loss_protect: OptionalField::Absent, - }; + let cr = msgs::ChannelReestablish { channel_id: [ + 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, + 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, + ], + next_local_commitment_number: 3, + next_remote_commitment_number: 4, + data_loss_protect: OptionalField::Absent }; let encoded_value = cr.encode(); assert_eq!( - encoded_value, - vec![ - 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4 - ] + encoded_value, + vec![ + 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4 + ] ); } @@ -1459,13 +1417,13 @@ mod tests { let encoded_value = cr.encode(); assert_eq!( - encoded_value, - vec![ - 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, - 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143 - ] + encoded_value, + vec![ + 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, + 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143 + ] ); } @@ -1488,19 +1446,19 @@ mod tests { fn encoding_announcement_signatures() { let secp_ctx = Secp256k1::new(); let (privkey, _) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101")); let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202")); - let announcement_signatures = msgs::AnnouncementSignatures { - channel_id: [ - 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, - ], - short_channel_id: 2316138423780173, - node_signature: sig_1, - bitcoin_signature: sig_2, - }; + let announcement_signatures = msgs::AnnouncementSignatures { channel_id: [ + 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, + 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, + 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, + ], + short_channel_id: 2316138423780173, + node_signature: sig_1, + bitcoin_signature: sig_2 }; let encoded_value = announcement_signatures.encode(); assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap()); @@ -1509,20 +1467,20 @@ mod tests { fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) { let secp_ctx = Secp256k1::new(); let (privkey_1, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let (privkey_2, pubkey_2) = get_keys_from!( - "0202020202020202020202020202020202020202020202020202020202020202", - secp_ctx + "0202020202020202020202020202020202020202020202020202020202020202", + secp_ctx ); let (privkey_3, pubkey_3) = get_keys_from!( - "0303030303030303030303030303030303030303030303030303030303030303", - secp_ctx + "0303030303030303030303030303030303030303030303030303030303030303", + secp_ctx ); let (privkey_4, pubkey_4) = get_keys_from!( - "0404040404040404040404040404040404040404040404040404040404040404", - secp_ctx + "0404040404040404040404040404040404040404040404040404040404040404", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101")); @@ -1532,31 +1490,30 @@ mod tests { if unknown_features_bits { features.flags = vec![0xFF, 0xFF]; } - let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement { - features, - chain_hash: if !non_bitcoin_chain_hash { - Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() - } else { - Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() - }, - short_channel_id: 2316138423780173, - node_id_1: pubkey_1, - node_id_2: pubkey_2, - bitcoin_key_1: pubkey_3, - bitcoin_key_2: pubkey_4, - excess_data: if excess_data { - vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] - } else { - Vec::new() - }, - }; - let channel_announcement = msgs::ChannelAnnouncement { - node_signature_1: sig_1, - node_signature_2: sig_2, - bitcoin_signature_1: sig_3, - bitcoin_signature_2: sig_4, - contents: unsigned_channel_announcement, - }; + let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement { features, + chain_hash: if !non_bitcoin_chain_hash { + Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() + } else { + Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() + }, + short_channel_id: 2316138423780173, + node_id_1: pubkey_1, + node_id_2: pubkey_2, + bitcoin_key_1: pubkey_3, + bitcoin_key_2: pubkey_4, + excess_data: if excess_data { + vec![ + 10, 0, 0, 20, 0, 0, 30, 0, 0, + 40 + ] + } else { + Vec::new() + } }; + let channel_announcement = msgs::ChannelAnnouncement { node_signature_1: sig_1, + node_signature_2: sig_2, + bitcoin_signature_1: sig_3, + bitcoin_signature_2: sig_4, + contents: unsigned_channel_announcement }; let encoded_value = channel_announcement.encode(); let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap(); if unknown_features_bits { @@ -1590,19 +1547,17 @@ mod tests { do_encoding_channel_announcement(true, false, true); } - fn do_encoding_node_announcement( - unknown_features_bits: bool, - ipv4: bool, - ipv6: bool, - onionv2: bool, - onionv3: bool, - excess_address_data: bool, - excess_data: bool, - ) { + fn do_encoding_node_announcement(unknown_features_bits: bool, + ipv4: bool, + ipv6: bool, + onionv2: bool, + onionv3: bool, + excess_address_data: bool, + excess_data: bool) { let secp_ctx = Secp256k1::new(); let (privkey_1, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); let mut features = GlobalFeatures::new(); @@ -1611,71 +1566,64 @@ mod tests { } let mut addresses = Vec::new(); if ipv4 { - addresses.push(msgs::NetAddress::IPv4 { - addr: [255, 254, 253, 252], - port: 9735, - }); + addresses.push(msgs::NetAddress::IPv4 { addr: [255, 254, 253, 252], + port: 9735 }); } if ipv6 { - addresses.push(msgs::NetAddress::IPv6 { - addr: [ - 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, - ], - port: 9735, - }); + addresses.push(msgs::NetAddress::IPv6 { addr: [ + 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, + ], + port: 9735, }); } if onionv2 { - addresses.push(msgs::NetAddress::OnionV2 { - addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246], - port: 9735, - }); + addresses.push(msgs::NetAddress::OnionV2 { addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246], + port: 9735 }); } if onionv3 { - addresses.push(msgs::NetAddress::OnionV3 { - ed25519_pubkey: [ - 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, - 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, - ], - checksum: 32, - version: 16, - port: 9735, - }); + addresses.push(msgs::NetAddress::OnionV3 { ed25519_pubkey: [ + 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, + 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, + ], + checksum: 32, + version: 16, + port: 9735, }); } let mut addr_len = 0; for addr in &addresses { addr_len += addr.len() + 1; } - let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement { - features, - timestamp: 20190119, - node_id: pubkey_1, - rgb: [32; 3], - alias: [16; 32], - addresses, - excess_address_data: if excess_address_data { - vec![ - 33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34, 241, 90, 79, 146, - 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84, 174, 99, 7, 42, 30, 193, 238, 125, 192, - 192, 75, 222, 92, 132, 120, 6, 23, 42, 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105, + let unsigned_node_announcement = + msgs::UnsignedNodeAnnouncement { features, + timestamp: 20190119, + node_id: pubkey_1, + rgb: [32; 3], + alias: [16; 32], + addresses, + excess_address_data: if excess_address_data { + vec![ + 33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, + 129, 22, 34, 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, + 115, 193, 57, 20, 44, 84, 174, 99, 7, 42, 30, 193, 238, 125, 192, + 192, 75, 222, 92, 132, 120, 6, 23, 42, 160, 92, 146, 194, 42, + 232, 227, 8, 209, 210, 105, ] - } else { - Vec::new() - }, - excess_data: if excess_data { - vec![ - 59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160, 127, 81, 202, 167, 92, - 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8, 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, - 30, 152, 41, 169, 212, 134, 17, 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253, + } else { + Vec::new() + }, + excess_data: if excess_data { + vec![ + 59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, + 159, 160, 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, + 11, 138, 172, 171, 8, 85, 255, 176, 231, 65, 236, 95, 124, 65, + 66, 30, 152, 41, 169, 212, 134, 17, 200, 200, 49, 247, 27, 229, + 234, 115, 230, 101, 148, 151, 127, 253, ] - } else { - Vec::new() - }, - }; + } else { + Vec::new() + } }; addr_len += unsigned_node_announcement.excess_address_data.len() as u16; - let node_announcement = msgs::NodeAnnouncement { - signature: sig_1, - contents: unsigned_node_announcement, - }; + let node_announcement = msgs::NodeAnnouncement { signature: sig_1, + contents: unsigned_node_announcement }; let encoded_value = node_announcement.encode(); let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap(); if unknown_features_bits { @@ -1722,43 +1670,41 @@ mod tests { do_encoding_node_announcement(false, false, true, false, true, false, false); } - fn do_encoding_channel_update( - non_bitcoin_chain_hash: bool, - direction: bool, - disable: bool, - htlc_maximum_msat: bool, - ) { + fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, + direction: bool, + disable: bool, + htlc_maximum_msat: bool) { let secp_ctx = Secp256k1::new(); let (privkey_1, _) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); - let unsigned_channel_update = msgs::UnsignedChannelUpdate { - chain_hash: if !non_bitcoin_chain_hash { - Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() - } else { - Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() - }, - short_channel_id: 2316138423780173, - timestamp: 20190119, - flags: if direction { 1 } else { 0 } - | if disable { 1 << 1 } else { 0 } - | if htlc_maximum_msat { 1 << 8 } else { 0 }, - cltv_expiry_delta: 144, - htlc_minimum_msat: 1000000, - fee_base_msat: 10000, - fee_proportional_millionths: 20, - excess_data: if htlc_maximum_msat { - vec![0, 0, 0, 0, 59, 154, 202, 0] - } else { - Vec::new() - }, - }; - let channel_update = msgs::ChannelUpdate { - signature: sig_1, - contents: unsigned_channel_update, - }; + let unsigned_channel_update = msgs::UnsignedChannelUpdate { chain_hash: if !non_bitcoin_chain_hash { + Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() + } else { + Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() + }, + short_channel_id: 2316138423780173, + timestamp: 20190119, + flags: if direction { 1 } else { 0 } + | if disable { 1 << 1 } else { 0 } + | if htlc_maximum_msat { + 1 << 8 + } else { + 0 + }, + cltv_expiry_delta: 144, + htlc_minimum_msat: 1000000, + fee_base_msat: 10000, + fee_proportional_millionths: 20, + excess_data: if htlc_maximum_msat { + vec![0, 0, 0, 0, 59, 154, 202, 0] + } else { + Vec::new() + } }; + let channel_update = msgs::ChannelUpdate { signature: sig_1, + contents: unsigned_channel_update }; let encoded_value = channel_update.encode(); let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap(); if non_bitcoin_chain_hash { @@ -1803,67 +1749,61 @@ mod tests { fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) { let secp_ctx = Secp256k1::new(); let (_, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let (_, pubkey_2) = get_keys_from!( - "0202020202020202020202020202020202020202020202020202020202020202", - secp_ctx + "0202020202020202020202020202020202020202020202020202020202020202", + secp_ctx ); let (_, pubkey_3) = get_keys_from!( - "0303030303030303030303030303030303030303030303030303030303030303", - secp_ctx + "0303030303030303030303030303030303030303030303030303030303030303", + secp_ctx ); let (_, pubkey_4) = get_keys_from!( - "0404040404040404040404040404040404040404040404040404040404040404", - secp_ctx + "0404040404040404040404040404040404040404040404040404040404040404", + secp_ctx ); let (_, pubkey_5) = get_keys_from!( - "0505050505050505050505050505050505050505050505050505050505050505", - secp_ctx + "0505050505050505050505050505050505050505050505050505050505050505", + secp_ctx ); let (_, pubkey_6) = get_keys_from!( - "0606060606060606060606060606060606060606060606060606060606060606", - secp_ctx + "0606060606060606060606060606060606060606060606060606060606060606", + secp_ctx ); - let open_channel = msgs::OpenChannel { - chain_hash: if !non_bitcoin_chain_hash { - Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() - } else { - Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() - }, - temporary_channel_id: [2; 32], - funding_satoshis: 1311768467284833366, - push_msat: 2536655962884945560, - dust_limit_satoshis: 3608586615801332854, - max_htlc_value_in_flight_msat: 8517154655701053848, - channel_reserve_satoshis: 8665828695742877976, - htlc_minimum_msat: 2316138423780173, - feerate_per_kw: 821716, - to_self_delay: 49340, - max_accepted_htlcs: 49340, - funding_pubkey: pubkey_1, - revocation_basepoint: pubkey_2, - payment_basepoint: pubkey_3, - delayed_payment_basepoint: pubkey_4, - htlc_basepoint: pubkey_5, - first_per_commitment_point: pubkey_6, - channel_flags: if random_bit { 1 << 5 } else { 0 }, - shutdown_scriptpubkey: if shutdown { - OptionalField::Present( - Address::p2pkh( - &::bitcoin::PublicKey { - compressed: true, - key: pubkey_1, - }, - Network::Testnet, - ) - .script_pubkey(), - ) - } else { - OptionalField::Absent - }, - }; + let open_channel = + msgs::OpenChannel { chain_hash: if !non_bitcoin_chain_hash { + Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() + } else { + Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() + }, + temporary_channel_id: [2; 32], + funding_satoshis: 1311768467284833366, + push_msat: 2536655962884945560, + dust_limit_satoshis: 3608586615801332854, + max_htlc_value_in_flight_msat: 8517154655701053848, + channel_reserve_satoshis: 8665828695742877976, + htlc_minimum_msat: 2316138423780173, + feerate_per_kw: 821716, + to_self_delay: 49340, + max_accepted_htlcs: 49340, + funding_pubkey: pubkey_1, + revocation_basepoint: pubkey_2, + payment_basepoint: pubkey_3, + delayed_payment_basepoint: pubkey_4, + htlc_basepoint: pubkey_5, + first_per_commitment_point: pubkey_6, + channel_flags: if random_bit { 1 << 5 } else { 0 }, + shutdown_scriptpubkey: if shutdown { + OptionalField::Present(Address::p2pkh( + &::bitcoin::PublicKey { compressed: true, + key: pubkey_1, }, + Network::Testnet, + ).script_pubkey()) + } else { + OptionalField::Absent + } }; let encoded_value = open_channel.encode(); let mut target_value = Vec::new(); if non_bitcoin_chain_hash { @@ -1897,59 +1837,53 @@ mod tests { fn do_encoding_accept_channel(shutdown: bool) { let secp_ctx = Secp256k1::new(); let (_, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let (_, pubkey_2) = get_keys_from!( - "0202020202020202020202020202020202020202020202020202020202020202", - secp_ctx + "0202020202020202020202020202020202020202020202020202020202020202", + secp_ctx ); let (_, pubkey_3) = get_keys_from!( - "0303030303030303030303030303030303030303030303030303030303030303", - secp_ctx + "0303030303030303030303030303030303030303030303030303030303030303", + secp_ctx ); let (_, pubkey_4) = get_keys_from!( - "0404040404040404040404040404040404040404040404040404040404040404", - secp_ctx + "0404040404040404040404040404040404040404040404040404040404040404", + secp_ctx ); let (_, pubkey_5) = get_keys_from!( - "0505050505050505050505050505050505050505050505050505050505050505", - secp_ctx + "0505050505050505050505050505050505050505050505050505050505050505", + secp_ctx ); let (_, pubkey_6) = get_keys_from!( - "0606060606060606060606060606060606060606060606060606060606060606", - secp_ctx + "0606060606060606060606060606060606060606060606060606060606060606", + secp_ctx ); - let accept_channel = msgs::AcceptChannel { - temporary_channel_id: [2; 32], - dust_limit_satoshis: 1311768467284833366, - max_htlc_value_in_flight_msat: 2536655962884945560, - channel_reserve_satoshis: 3608586615801332854, - htlc_minimum_msat: 2316138423780173, - minimum_depth: 821716, - to_self_delay: 49340, - max_accepted_htlcs: 49340, - funding_pubkey: pubkey_1, - revocation_basepoint: pubkey_2, - payment_basepoint: pubkey_3, - delayed_payment_basepoint: pubkey_4, - htlc_basepoint: pubkey_5, - first_per_commitment_point: pubkey_6, - shutdown_scriptpubkey: if shutdown { - OptionalField::Present( - Address::p2pkh( - &::bitcoin::PublicKey { - compressed: true, - key: pubkey_1, - }, - Network::Testnet, - ) - .script_pubkey(), - ) - } else { - OptionalField::Absent - }, - }; + let accept_channel = + msgs::AcceptChannel { temporary_channel_id: [2; 32], + dust_limit_satoshis: 1311768467284833366, + max_htlc_value_in_flight_msat: 2536655962884945560, + channel_reserve_satoshis: 3608586615801332854, + htlc_minimum_msat: 2316138423780173, + minimum_depth: 821716, + to_self_delay: 49340, + max_accepted_htlcs: 49340, + funding_pubkey: pubkey_1, + revocation_basepoint: pubkey_2, + payment_basepoint: pubkey_3, + delayed_payment_basepoint: pubkey_4, + htlc_basepoint: pubkey_5, + first_per_commitment_point: pubkey_6, + shutdown_scriptpubkey: if shutdown { + OptionalField::Present(Address::p2pkh( + &::bitcoin::PublicKey { compressed: true, + key: pubkey_1, }, + Network::Testnet, + ).script_pubkey()) + } else { + OptionalField::Absent + } }; let encoded_value = accept_channel.encode(); let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap(); if shutdown { @@ -1968,8 +1902,8 @@ mod tests { fn encoding_funding_created() { let secp_ctx = Secp256k1::new(); let (privkey_1, _) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); let funding_created = msgs::FundingCreated { @@ -1988,14 +1922,12 @@ mod tests { fn encoding_funding_signed() { let secp_ctx = Secp256k1::new(); let (privkey_1, _) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); - let funding_signed = msgs::FundingSigned { - channel_id: [2; 32], - signature: sig_1, - }; + let funding_signed = msgs::FundingSigned { channel_id: [2; 32], + signature: sig_1 }; let encoded_value = funding_signed.encode(); let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap(); assert_eq!(encoded_value, target_value); @@ -2005,13 +1937,11 @@ mod tests { fn encoding_funding_locked() { let secp_ctx = Secp256k1::new(); let (_, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); - let funding_locked = msgs::FundingLocked { - channel_id: [2; 32], - next_per_commitment_point: pubkey_1, - }; + let funding_locked = msgs::FundingLocked { channel_id: [2; 32], + next_per_commitment_point: pubkey_1 }; let encoded_value = funding_locked.encode(); let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap(); assert_eq!(encoded_value, target_value); @@ -2020,36 +1950,28 @@ mod tests { fn do_encoding_shutdown(script_type: u8) { let secp_ctx = Secp256k1::new(); let (_, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script(); - let shutdown = msgs::Shutdown { - channel_id: [2; 32], - scriptpubkey: if script_type == 1 { - Address::p2pkh( - &::bitcoin::PublicKey { - compressed: true, - key: pubkey_1, - }, - Network::Testnet, - ) - .script_pubkey() - } else if script_type == 2 { - Address::p2sh(&script, Network::Testnet).script_pubkey() - } else if script_type == 3 { - Address::p2wpkh( - &::bitcoin::PublicKey { - compressed: true, - key: pubkey_1, - }, - Network::Testnet, - ) - .script_pubkey() - } else { - Address::p2wsh(&script, Network::Testnet).script_pubkey() - }, - }; + let shutdown = msgs::Shutdown { channel_id: [2; 32], + scriptpubkey: if script_type == 1 { + Address::p2pkh( + &::bitcoin::PublicKey { compressed: true, + key: pubkey_1, }, + Network::Testnet, + ).script_pubkey() + } else if script_type == 2 { + Address::p2sh(&script, Network::Testnet).script_pubkey() + } else if script_type == 3 { + Address::p2wpkh( + &::bitcoin::PublicKey { compressed: true, + key: pubkey_1, }, + Network::Testnet, + ).script_pubkey() + } else { + Address::p2wsh(&script, Network::Testnet).script_pubkey() + } }; let encoded_value = shutdown.encode(); let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); if script_type == 1 { @@ -2078,15 +2000,13 @@ mod tests { fn encoding_closing_signed() { let secp_ctx = Secp256k1::new(); let (privkey_1, _) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); - let closing_signed = msgs::ClosingSigned { - channel_id: [2; 32], - fee_satoshis: 2316138423780173, - signature: sig_1, - }; + let closing_signed = msgs::ClosingSigned { channel_id: [2; 32], + fee_satoshis: 2316138423780173, + signature: sig_1 }; let encoded_value = closing_signed.encode(); let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap(); assert_eq!(encoded_value, target_value); @@ -2096,23 +2016,19 @@ mod tests { fn encoding_update_add_htlc() { let secp_ctx = Secp256k1::new(); let (_, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); - let onion_routing_packet = msgs::OnionPacket { - version: 255, - public_key: Ok(pubkey_1), - hop_data: [1; 20 * 65], - hmac: [2; 32], - }; - let update_add_htlc = msgs::UpdateAddHTLC { - channel_id: [2; 32], - htlc_id: 2316138423780173, - amount_msat: 3608586615801332854, - payment_hash: PaymentHash([1; 32]), - cltv_expiry: 821716, - onion_routing_packet, - }; + let onion_routing_packet = msgs::OnionPacket { version: 255, + public_key: Ok(pubkey_1), + hop_data: [1; 20 * 65], + hmac: [2; 32] }; + let update_add_htlc = msgs::UpdateAddHTLC { channel_id: [2; 32], + htlc_id: 2316138423780173, + amount_msat: 3608586615801332854, + payment_hash: PaymentHash([1; 32]), + cltv_expiry: 821716, + onion_routing_packet }; let encoded_value = update_add_htlc.encode(); let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap(); assert_eq!(encoded_value, target_value); @@ -2120,11 +2036,9 @@ mod tests { #[test] fn encoding_update_fulfill_htlc() { - let update_fulfill_htlc = msgs::UpdateFulfillHTLC { - channel_id: [2; 32], - htlc_id: 2316138423780173, - payment_preimage: PaymentPreimage([1; 32]), - }; + let update_fulfill_htlc = msgs::UpdateFulfillHTLC { channel_id: [2; 32], + htlc_id: 2316138423780173, + payment_preimage: PaymentPreimage([1; 32]) }; let encoded_value = update_fulfill_htlc.encode(); let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap(); assert_eq!(encoded_value, target_value); @@ -2133,11 +2047,9 @@ mod tests { #[test] fn encoding_update_fail_htlc() { let reason = OnionErrorPacket { data: [1; 32].to_vec() }; - let update_fail_htlc = msgs::UpdateFailHTLC { - channel_id: [2; 32], - htlc_id: 2316138423780173, - reason, - }; + let update_fail_htlc = msgs::UpdateFailHTLC { channel_id: [2; 32], + htlc_id: 2316138423780173, + reason }; let encoded_value = update_fail_htlc.encode(); let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap(); assert_eq!(encoded_value, target_value); @@ -2145,12 +2057,10 @@ mod tests { #[test] fn encoding_update_fail_malformed_htlc() { - let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC { - channel_id: [2; 32], - htlc_id: 2316138423780173, - sha256_of_onion: [1; 32], - failure_code: 255, - }; + let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC { channel_id: [2; 32], + htlc_id: 2316138423780173, + sha256_of_onion: [1; 32], + failure_code: 255 }; let encoded_value = update_fail_malformed_htlc.encode(); let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap(); assert_eq!(encoded_value, target_value); @@ -2159,30 +2069,29 @@ mod tests { fn do_encoding_commitment_signed(htlcs: bool) { let secp_ctx = Secp256k1::new(); let (privkey_1, _) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); let (privkey_2, _) = get_keys_from!( - "0202020202020202020202020202020202020202020202020202020202020202", - secp_ctx + "0202020202020202020202020202020202020202020202020202020202020202", + secp_ctx ); let (privkey_3, _) = get_keys_from!( - "0303030303030303030303030303030303030303030303030303030303030303", - secp_ctx + "0303030303030303030303030303030303030303030303030303030303030303", + secp_ctx ); let (privkey_4, _) = get_keys_from!( - "0404040404040404040404040404040404040404040404040404040404040404", - secp_ctx + "0404040404040404040404040404040404040404040404040404040404040404", + secp_ctx ); let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101")); let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101")); let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101")); let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101")); - let commitment_signed = msgs::CommitmentSigned { - channel_id: [2; 32], - signature: sig_1, - htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() }, - }; + let commitment_signed = + msgs::CommitmentSigned { channel_id: [2; 32], + signature: sig_1, + htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() } }; let encoded_value = commitment_signed.encode(); let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap(); if htlcs { @@ -2203,16 +2112,15 @@ mod tests { fn encoding_revoke_and_ack() { let secp_ctx = Secp256k1::new(); let (_, pubkey_1) = get_keys_from!( - "0101010101010101010101010101010101010101010101010101010101010101", - secp_ctx + "0101010101010101010101010101010101010101010101010101010101010101", + secp_ctx ); - let raa = msgs::RevokeAndACK { - channel_id: [2; 32], - per_commitment_secret: [ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - ], - next_per_commitment_point: pubkey_1, - }; + let raa = msgs::RevokeAndACK { channel_id: [2; 32], + per_commitment_secret: [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + next_per_commitment_point: pubkey_1 }; let encoded_value = raa.encode(); let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap(); assert_eq!(encoded_value, target_value); @@ -2220,10 +2128,8 @@ mod tests { #[test] fn encoding_update_fee() { - let update_fee = msgs::UpdateFee { - channel_id: [2; 32], - feerate_per_kw: 20190119, - }; + let update_fee = msgs::UpdateFee { channel_id: [2; 32], + feerate_per_kw: 20190119 }; let encoded_value = update_fee.encode(); let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap(); @@ -2239,10 +2145,8 @@ mod tests { if initial_routing_sync { local.set_initial_routing_sync(); } - let init = msgs::Init { - global_features: global, - local_features: local, - }; + let init = msgs::Init { global_features: global, + local_features: local }; let encoded_value = init.encode(); let mut target_value = Vec::new(); if unknown_global_bits { @@ -2268,10 +2172,8 @@ mod tests { #[test] fn encoding_error() { - let error = msgs::ErrorMessage { - channel_id: [2; 32], - data: String::from("rust-lightning"), - }; + let error = msgs::ErrorMessage { channel_id: [2; 32], + data: String::from("rust-lightning") }; let encoded_value = error.encode(); let target_value = hex::decode( "0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67", @@ -2282,10 +2184,8 @@ mod tests { #[test] fn encoding_ping() { - let ping = msgs::Ping { - ponglen: 64, - byteslen: 64, - }; + let ping = msgs::Ping { ponglen: 64, + byteslen: 64 }; let encoded_value = ping.encode(); let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); assert_eq!(encoded_value, target_value); diff --git a/lightning/src/ln/onion_utils.rs b/lightning/src/ln/onion_utils.rs index 23451d0415f..704d02977ab 100644 --- a/lightning/src/ln/onion_utils.rs +++ b/lightning/src/ln/onion_utils.rs @@ -33,18 +33,16 @@ pub(super) struct OnionKeys { #[inline] pub(super) fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) { assert_eq!(shared_secret.len(), 32); - ( - { - let mut hmac = HmacEngine::::new(&[0x72, 0x68, 0x6f]); // rho - hmac.input(&shared_secret[..]); - Hmac::from_engine(hmac).into_inner() - }, - { - let mut hmac = HmacEngine::::new(&[0x6d, 0x75]); // mu - hmac.input(&shared_secret[..]); - Hmac::from_engine(hmac).into_inner() - }, - ) + ({ + let mut hmac = HmacEngine::::new(&[0x72, 0x68, 0x6f]); // rho + hmac.input(&shared_secret[..]); + Hmac::from_engine(hmac).into_inner() + }, + { + let mut hmac = HmacEngine::::new(&[0x6d, 0x75]); // mu + hmac.input(&shared_secret[..]); + Hmac::from_engine(hmac).into_inner() + }) } #[inline] @@ -65,15 +63,13 @@ pub(super) fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] { // can only fail if an intermediary hop has an invalid public key or session_priv is invalid #[inline] -pub(super) fn construct_onion_keys_callback< - T: secp256k1::Signing, - FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop), ->( +pub(super) fn construct_onion_keys_callback( secp_ctx: &Secp256k1, route: &Route, session_priv: &SecretKey, - mut callback: FType, -) -> Result<(), secp256k1::Error> { + mut callback: FType) + -> Result<(), secp256k1::Error> { let mut blinded_priv = session_priv.clone(); let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv); @@ -97,40 +93,36 @@ pub(super) fn construct_onion_keys_callback< } // can only fail if an intermediary hop has an invalid public key or session_priv is invalid -pub(super) fn construct_onion_keys( - secp_ctx: &Secp256k1, - route: &Route, - session_priv: &SecretKey, -) -> Result, secp256k1::Error> { +pub(super) fn construct_onion_keys(secp_ctx: &Secp256k1, + route: &Route, + session_priv: &SecretKey) + -> Result, secp256k1::Error> { let mut res = Vec::with_capacity(route.hops.len()); construct_onion_keys_callback( - secp_ctx, - route, - session_priv, - |shared_secret, _blinding_factor, ephemeral_pubkey, _| { - let (rho, mu) = gen_rho_mu_from_shared_secret(&shared_secret[..]); - - res.push(OnionKeys { - #[cfg(test)] - shared_secret, - #[cfg(test)] - blinding_factor: _blinding_factor, - ephemeral_pubkey, - rho, - mu, - }); - }, + secp_ctx, + route, + session_priv, + |shared_secret, _blinding_factor, ephemeral_pubkey, _| { + let (rho, mu) = gen_rho_mu_from_shared_secret(&shared_secret[..]); + + res.push(OnionKeys { #[cfg(test)] + shared_secret, + #[cfg(test)] + blinding_factor: _blinding_factor, + ephemeral_pubkey, + rho, + mu }); + }, )?; Ok(res) } /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send. -pub(super) fn build_onion_payloads( - route: &Route, - starting_htlc_offset: u32, -) -> Result<(Vec, u64, u32), APIError> { +pub(super) fn build_onion_payloads(route: &Route, + starting_htlc_offset: u32) + -> Result<(Vec, u64, u32), APIError> { let mut cur_value_msat = 0u64; let mut cur_cltv = starting_htlc_offset; let mut last_short_channel_id = 0; @@ -151,28 +143,20 @@ pub(super) fn build_onion_payloads( cur_cltv }; res.insert( - 0, - msgs::OnionHopData { - realm: 0, - data: msgs::OnionRealm0HopData { - short_channel_id: last_short_channel_id, - amt_to_forward: value_msat, - outgoing_cltv_value: cltv, - }, - hmac: [0; 32], - }, + 0, + msgs::OnionHopData { realm: 0, + data: msgs::OnionRealm0HopData { short_channel_id: last_short_channel_id, + amt_to_forward: value_msat, + outgoing_cltv_value: cltv, }, + hmac: [0; 32], }, ); cur_value_msat += hop.fee_msat; if cur_value_msat >= 21000000 * 100000000 * 1000 { - return Err(APIError::RouteError { - err: "Channel fees overflowed?!", - }); + return Err(APIError::RouteError { err: "Channel fees overflowed?!" }); } cur_cltv += hop.cltv_expiry_delta as u32; if cur_cltv >= 500000000 { - return Err(APIError::RouteError { - err: "Channel CLTV overflowed?!", - }); + return Err(APIError::RouteError { err: "Channel CLTV overflowed?!" }); } last_short_channel_id = hop.short_channel_id; } @@ -199,12 +183,11 @@ fn xor_bufs(dst: &mut [u8], src: &[u8]) { } const ZERO: [u8; 21 * 65] = [0; 21 * 65]; -pub(super) fn construct_onion_packet( - payloads: Vec, - onion_keys: Vec, - prng_seed: [u8; 32], - associated_data: &PaymentHash, -) -> msgs::OnionPacket { +pub(super) fn construct_onion_packet(payloads: Vec, + onion_keys: Vec, + prng_seed: [u8; 32], + associated_data: &PaymentHash) + -> msgs::OnionPacket { let mut packet_data = [0; 20 * 65]; let mut chacha = ChaCha20::new(&prng_seed, &[0; 8]); @@ -213,12 +196,11 @@ pub(super) fn construct_onion_packet( construct_onion_packet_with_init_noise(payloads, onion_keys, packet_data, associated_data) } -fn construct_onion_packet_with_init_noise( - mut payloads: Vec, - onion_keys: Vec, - mut packet_data: [u8; 20 * 65], - associated_data: &PaymentHash, -) -> msgs::OnionPacket { +fn construct_onion_packet_with_init_noise(mut payloads: Vec, + onion_keys: Vec, + mut packet_data: [u8; 20 * 65], + associated_data: &PaymentHash) + -> msgs::OnionPacket { let mut buf = Vec::with_capacity(21 * 65); buf.resize(21 * 65, 0); @@ -260,12 +242,10 @@ fn construct_onion_packet_with_init_noise( hmac_res = Hmac::from_engine(hmac).into_inner(); } - msgs::OnionPacket { - version: 0, - public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey), - hop_data: packet_data, - hmac: hmac_res, - } + msgs::OnionPacket { version: 0, + public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey), + hop_data: packet_data, + hmac: hmac_res } } /// Encrypts a failure packet. raw_packet can either be a @@ -280,11 +260,10 @@ pub(super) fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket { data: packet_crypted } } -pub(super) fn build_failure_packet( - shared_secret: &[u8], - failure_type: u16, - failure_data: &[u8], -) -> msgs::DecodedOnionErrorPacket { +pub(super) fn build_failure_packet(shared_secret: &[u8], + failure_type: u16, + failure_data: &[u8]) + -> msgs::DecodedOnionErrorPacket { assert_eq!(shared_secret.len(), 32); assert!(failure_data.len() <= 256 - 2); @@ -302,11 +281,9 @@ pub(super) fn build_failure_packet( res.resize(256 - 2 - failure_data.len(), 0); res }; - let mut packet = msgs::DecodedOnionErrorPacket { - hmac: [0; 32], - failuremsg, - pad, - }; + let mut packet = msgs::DecodedOnionErrorPacket { hmac: [0; 32], + failuremsg, + pad }; let mut hmac = HmacEngine::::new(&um); hmac.input(&packet.encode()[32..]); @@ -316,11 +293,10 @@ pub(super) fn build_failure_packet( } #[inline] -pub(super) fn build_first_hop_failure_packet( - shared_secret: &[u8], - failure_type: u16, - failure_data: &[u8], -) -> msgs::OnionErrorPacket { +pub(super) fn build_first_hop_failure_packet(shared_secret: &[u8], + failure_type: u16, + failure_data: &[u8]) + -> msgs::OnionErrorPacket { let failure_packet = build_failure_packet(shared_secret, failure_type, failure_data); encrypt_failure_packet(shared_secret, &failure_packet.encode()[..]) } @@ -332,13 +308,11 @@ pub(super) fn process_onion_failure( secp_ctx: &Secp256k1, logger: &Arc, htlc_source: &HTLCSource, - mut packet_decrypted: Vec, -) -> (Option, bool, Option) { - if let &HTLCSource::OutboundRoute { - ref route, - ref session_priv, - ref first_hop_htlc_msat, - } = htlc_source + mut packet_decrypted: Vec) + -> (Option, bool, Option) { + if let &HTLCSource::OutboundRoute { ref route, + ref session_priv, + ref first_hop_htlc_msat, } = htlc_source { let mut res = None; let mut htlc_msat = *first_hop_htlc_msat; @@ -393,29 +367,34 @@ pub(super) fn process_onion_failure( let mut fail_channel_update = None; if error_code & NODE == NODE { - fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route_hop.pubkey, - is_permanent: error_code & PERM == PERM, - }); + fail_channel_update = + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, + is_permanent: error_code & PERM + == PERM }); } else if error_code & PERM == PERM { fail_channel_update = if payment_failed { None } else { - Some(msgs::HTLCFailChannelUpdate::ChannelClosed { - short_channel_id: route.hops - [next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }] - .short_channel_id, - is_permanent: true, - }) + Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: + route.hops[next_route_hop_ix + - if next_route_hop_ix + == route.hops + .len() + { + 1 + } else { + 0 + }].short_channel_id, + is_permanent: true }) }; } else if error_code & UPDATE == UPDATE { if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size + 2..debug_field_size + 4) { let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize; - if let Some(update_slice) = err_packet - .failuremsg - .get(debug_field_size + 4..debug_field_size + 4 + update_len) + if let Some(update_slice) = + err_packet.failuremsg + .get(debug_field_size + 4..debug_field_size + 4 + update_len) { if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) { @@ -425,19 +404,20 @@ pub(super) fn process_onion_failure( 7 => false, 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat, 12 => { - let new_fee = amt_to_forward - .checked_mul( - chan_update.contents.fee_proportional_millionths as u64, - ) - .and_then(|prop_fee| { - (prop_fee / 1000000) + let new_fee = amt_to_forward.checked_mul( + chan_update.contents + .fee_proportional_millionths + as u64, + ) + .and_then(|prop_fee| { + (prop_fee / 1000000) .checked_add(chan_update.contents.fee_base_msat as u64) - }); + }); new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap() }, 13 => { route_hop.cltv_expiry_delta as u16 - >= chan_update.contents.cltv_expiry_delta + >= chan_update.contents.cltv_expiry_delta }, 14 => false, // expiry_too_soon; always valid? 20 => chan_update.contents.flags & 2 == 0, @@ -451,7 +431,8 @@ pub(super) fn process_onion_failure( is_permanent: true, }) } else { - Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { msg: chan_update }) + Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { msg: + chan_update }) }; } } @@ -459,19 +440,17 @@ pub(super) fn process_onion_failure( if fail_channel_update.is_none() { // They provided an UPDATE which was obviously bogus, not worth // trying to relay through them anymore. - fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route_hop.pubkey, - is_permanent: true, - }); + fail_channel_update = + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, + is_permanent: true }); } } else if !payment_failed { // We can't understand their error messages and they failed to // forward...they probably can't understand our forwards so its // really not worth trying any further. - fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route_hop.pubkey, - is_permanent: true, - }); + fail_channel_update = + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, + is_permanent: true }); } // TODO: Here (and a few other places) we assume that BADONION errors @@ -483,13 +462,13 @@ pub(super) fn process_onion_failure( if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size { let log_holder = LogHolder { logger }; log_warn!( - log_holder, - "Onion Error[{}({:#x}) {}({})] {}", - title, - error_code, - debug_field, - log_bytes!(&err_packet.failuremsg[4..4 + debug_field_size]), - description + log_holder, + "Onion Error[{}({:#x}) {}({})] {}", + title, + error_code, + debug_field, + log_bytes!(&err_packet.failuremsg[4..4 + debug_field_size]), + description ); } else { let log_holder = LogHolder { logger }; @@ -499,17 +478,14 @@ pub(super) fn process_onion_failure( // Useless packet that we can't use but it passed HMAC, so it // definitely came from the peer in question res = Some(( - Some(msgs::HTLCFailChannelUpdate::NodeFailure { - node_id: route_hop.pubkey, - is_permanent: true, - }), + Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, + is_permanent: true, }), !is_from_final_node, )); } } } - }) - .expect("Route that we sent via spontaneously grew invalid keys in the middle of it?"); + }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?"); if let Some((channel_update, payment_retryable)) = res { (channel_update, payment_retryable, error_code_ret) } else { @@ -540,8 +516,7 @@ mod tests { // Keys from BOLT 4, used in both test vector tests let secp_ctx = Secp256k1::new(); - let route = Route { - hops: vec![ + let route = Route { hops: vec![ RouteHop { pubkey: PublicKey::from_slice( &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..], @@ -587,8 +562,7 @@ mod tests { fee_msat: 0, cltv_expiry_delta: 0, // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually }, - ], - }; + ] }; let session_priv = SecretKey::from_slice( &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..], @@ -606,158 +580,139 @@ mod tests { let onion_keys = build_test_onion_keys(); assert_eq!( - onion_keys[0].shared_secret[..], - hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..] + onion_keys[0].shared_secret[..], + hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..] ); assert_eq!( - onion_keys[0].blinding_factor[..], - hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..] + onion_keys[0].blinding_factor[..], + hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..] ); assert_eq!( - onion_keys[0].ephemeral_pubkey.serialize()[..], - hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..] + onion_keys[0].ephemeral_pubkey.serialize()[..], + hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..] ); assert_eq!( - onion_keys[0].rho, - hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..] + onion_keys[0].rho, + hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..] ); assert_eq!( - onion_keys[0].mu, - hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..] + onion_keys[0].mu, + hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..] ); assert_eq!( - onion_keys[1].shared_secret[..], - hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..] + onion_keys[1].shared_secret[..], + hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..] ); assert_eq!( - onion_keys[1].blinding_factor[..], - hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..] + onion_keys[1].blinding_factor[..], + hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..] ); assert_eq!( - onion_keys[1].ephemeral_pubkey.serialize()[..], - hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..] + onion_keys[1].ephemeral_pubkey.serialize()[..], + hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..] ); assert_eq!( - onion_keys[1].rho, - hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..] + onion_keys[1].rho, + hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..] ); assert_eq!( - onion_keys[1].mu, - hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..] + onion_keys[1].mu, + hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..] ); assert_eq!( - onion_keys[2].shared_secret[..], - hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..] + onion_keys[2].shared_secret[..], + hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..] ); assert_eq!( - onion_keys[2].blinding_factor[..], - hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..] + onion_keys[2].blinding_factor[..], + hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..] ); assert_eq!( - onion_keys[2].ephemeral_pubkey.serialize()[..], - hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..] + onion_keys[2].ephemeral_pubkey.serialize()[..], + hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..] ); assert_eq!( - onion_keys[2].rho, - hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..] + onion_keys[2].rho, + hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..] ); assert_eq!( - onion_keys[2].mu, - hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..] + onion_keys[2].mu, + hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..] ); assert_eq!( - onion_keys[3].shared_secret[..], - hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..] + onion_keys[3].shared_secret[..], + hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..] ); assert_eq!( - onion_keys[3].blinding_factor[..], - hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..] + onion_keys[3].blinding_factor[..], + hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..] ); assert_eq!( - onion_keys[3].ephemeral_pubkey.serialize()[..], - hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..] + onion_keys[3].ephemeral_pubkey.serialize()[..], + hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..] ); assert_eq!( - onion_keys[3].rho, - hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..] + onion_keys[3].rho, + hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..] ); assert_eq!( - onion_keys[3].mu, - hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..] + onion_keys[3].mu, + hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..] ); assert_eq!( - onion_keys[4].shared_secret[..], - hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..] + onion_keys[4].shared_secret[..], + hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..] ); assert_eq!( - onion_keys[4].blinding_factor[..], - hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..] + onion_keys[4].blinding_factor[..], + hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..] ); assert_eq!( - onion_keys[4].ephemeral_pubkey.serialize()[..], - hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..] + onion_keys[4].ephemeral_pubkey.serialize()[..], + hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..] ); assert_eq!( - onion_keys[4].rho, - hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..] + onion_keys[4].rho, + hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..] ); assert_eq!( - onion_keys[4].mu, - hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..] + onion_keys[4].mu, + hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..] ); // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/ - let payloads = vec![ - msgs::OnionHopData { - realm: 0, - data: msgs::OnionRealm0HopData { - short_channel_id: 0, - amt_to_forward: 0, - outgoing_cltv_value: 0, - }, - hmac: [0; 32], - }, - msgs::OnionHopData { - realm: 0, - data: msgs::OnionRealm0HopData { - short_channel_id: 0x0101010101010101, - amt_to_forward: 0x0100000001, - outgoing_cltv_value: 0, - }, - hmac: [0; 32], - }, - msgs::OnionHopData { - realm: 0, - data: msgs::OnionRealm0HopData { - short_channel_id: 0x0202020202020202, - amt_to_forward: 0x0200000002, - outgoing_cltv_value: 0, - }, - hmac: [0; 32], - }, - msgs::OnionHopData { - realm: 0, - data: msgs::OnionRealm0HopData { - short_channel_id: 0x0303030303030303, - amt_to_forward: 0x0300000003, - outgoing_cltv_value: 0, - }, - hmac: [0; 32], - }, - msgs::OnionHopData { - realm: 0, - data: msgs::OnionRealm0HopData { - short_channel_id: 0x0404040404040404, - amt_to_forward: 0x0400000004, - outgoing_cltv_value: 0, - }, - hmac: [0; 32], - }, - ]; + let payloads = + vec![ + msgs::OnionHopData { realm: 0, + data: msgs::OnionRealm0HopData { short_channel_id: 0, + amt_to_forward: 0, + outgoing_cltv_value: 0, }, + hmac: [0; 32], }, + msgs::OnionHopData { realm: 0, + data: msgs::OnionRealm0HopData { short_channel_id: 0x0101010101010101, + amt_to_forward: 0x0100000001, + outgoing_cltv_value: 0, }, + hmac: [0; 32], }, + msgs::OnionHopData { realm: 0, + data: msgs::OnionRealm0HopData { short_channel_id: 0x0202020202020202, + amt_to_forward: 0x0200000002, + outgoing_cltv_value: 0, }, + hmac: [0; 32], }, + msgs::OnionHopData { realm: 0, + data: msgs::OnionRealm0HopData { short_channel_id: 0x0303030303030303, + amt_to_forward: 0x0300000003, + outgoing_cltv_value: 0, }, + hmac: [0; 32], }, + msgs::OnionHopData { realm: 0, + data: msgs::OnionRealm0HopData { short_channel_id: 0x0404040404040404, + amt_to_forward: 0x0400000004, + outgoing_cltv_value: 0, }, + hmac: [0; 32], }, + ]; let packet = [0; 20 * 65]; let packet = diff --git a/lightning/src/ln/peer_channel_encryptor.rs b/lightning/src/ln/peer_channel_encryptor.rs index 3b819ee5d7f..4261ea40912 100644 --- a/lightning/src/ln/peer_channel_encryptor.rs +++ b/lightning/src/ln/peer_channel_encryptor.rs @@ -13,15 +13,13 @@ use util::byte_utils; use util::chacha20poly1305rfc::ChaCha20Poly1305RFC; // Sha256("Noise_XK_secp256k1_ChaChaPoly_SHA256") -const NOISE_CK: [u8; 32] = [ - 0x26, 0x40, 0xf5, 0x2e, 0xeb, 0xcd, 0x9e, 0x88, 0x29, 0x58, 0x95, 0x1c, 0x79, 0x42, 0x50, 0xee, 0xdb, 0x28, 0x00, - 0x2c, 0x05, 0xd7, 0xdc, 0x2e, 0xa0, 0xf1, 0x95, 0x40, 0x60, 0x42, 0xca, 0xf1, -]; +const NOISE_CK: [u8; 32] = [0x26, 0x40, 0xf5, 0x2e, 0xeb, 0xcd, 0x9e, 0x88, 0x29, 0x58, 0x95, 0x1c, 0x79, 0x42, 0x50, + 0xee, 0xdb, 0x28, 0x00, 0x2c, 0x05, 0xd7, 0xdc, 0x2e, 0xa0, 0xf1, 0x95, 0x40, 0x60, 0x42, + 0xca, 0xf1]; // Sha256(NOISE_CK || "lightning") -const NOISE_H: [u8; 32] = [ - 0xd1, 0xfb, 0xf6, 0xde, 0xe4, 0xf6, 0x86, 0xf1, 0x32, 0xfd, 0x70, 0x2c, 0x4a, 0xbf, 0x8f, 0xba, 0x4b, 0xb4, 0x20, - 0xd8, 0x9d, 0x2a, 0x04, 0x8a, 0x3c, 0x4f, 0x4c, 0x09, 0x2e, 0x37, 0xb6, 0x76, -]; +const NOISE_H: [u8; 32] = [0xd1, 0xfb, 0xf6, 0xde, 0xe4, 0xf6, 0x86, 0xf1, 0x32, 0xfd, 0x70, 0x2c, 0x4a, 0xbf, 0x8f, + 0xba, 0x4b, 0xb4, 0x20, 0xd8, 0x9d, 0x2a, 0x04, 0x8a, 0x3c, 0x4f, 0x4c, 0x09, 0x2e, 0x37, + 0xb6, 0x76]; pub enum NextNoiseStep { ActOne, @@ -84,15 +82,15 @@ impl PeerChannelEncryptor { sha.input(&their_node_id.serialize()[..]); let h = Sha256::from_engine(sha).into_inner(); - PeerChannelEncryptor { - their_node_id: Some(their_node_id), - secp_ctx, - noise_state: NoiseState::InProgress { - state: NoiseStep::PreActOne, - directional_state: DirectionalNoiseState::Outbound { ie: ephemeral_key }, - bidirectional_state: BidirectionalNoiseState { h, ck: NOISE_CK }, - }, - } + PeerChannelEncryptor { their_node_id: Some(their_node_id), + secp_ctx, + noise_state: + NoiseState::InProgress { state: NoiseStep::PreActOne, + directional_state: + DirectionalNoiseState::Outbound { ie: ephemeral_key }, + bidirectional_state: BidirectionalNoiseState { h, + ck: + NOISE_CK } } } } pub fn new_inbound(our_node_secret: &SecretKey) -> PeerChannelEncryptor { @@ -104,19 +102,16 @@ impl PeerChannelEncryptor { sha.input(&our_node_id.serialize()[..]); let h = Sha256::from_engine(sha).into_inner(); - PeerChannelEncryptor { - their_node_id: None, - secp_ctx, - noise_state: NoiseState::InProgress { - state: NoiseStep::PreActOne, - directional_state: DirectionalNoiseState::Inbound { - ie: None, - re: None, - temp_k2: None, - }, - bidirectional_state: BidirectionalNoiseState { h, ck: NOISE_CK }, - }, - } + PeerChannelEncryptor { their_node_id: None, + secp_ctx, + noise_state: NoiseState::InProgress { state: NoiseStep::PreActOne, + directional_state: + DirectionalNoiseState::Inbound { ie: None, + re: None, + temp_k2: + None }, + bidirectional_state: + BidirectionalNoiseState { h, ck: NOISE_CK } } } } #[inline] @@ -131,26 +126,23 @@ impl PeerChannelEncryptor { } #[inline] - fn decrypt_with_ad( - res: &mut [u8], - n: u64, - key: &[u8; 32], - h: &[u8], - cyphertext: &[u8], - ) -> Result<(), LightningError> { + fn decrypt_with_ad(res: &mut [u8], + n: u64, + key: &[u8; 32], + h: &[u8], + cyphertext: &[u8]) + -> Result<(), LightningError> { let mut nonce = [0; 12]; nonce[4..].copy_from_slice(&byte_utils::le64_to_array(n)); let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h); if !chacha.decrypt( - &cyphertext[0..cyphertext.len() - 16], - res, - &cyphertext[cyphertext.len() - 16..], + &cyphertext[0..cyphertext.len() - 16], + res, + &cyphertext[cyphertext.len() - 16..], ) { - return Err(LightningError { - err: "Bad MAC", - action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }); + return Err(LightningError { err: "Bad MAC", + action: msgs::ErrorAction::DisconnectPeer { msg: None } }); } Ok(()) } @@ -176,12 +168,11 @@ impl PeerChannelEncryptor { } #[inline] - fn outbound_noise_act( - secp_ctx: &Secp256k1, - state: &mut BidirectionalNoiseState, - our_key: &SecretKey, - their_key: &PublicKey, - ) -> ([u8; 50], [u8; 32]) { + fn outbound_noise_act(secp_ctx: &Secp256k1, + state: &mut BidirectionalNoiseState, + our_key: &SecretKey, + their_key: &PublicKey) + -> ([u8; 50], [u8; 32]) { let our_pub = PublicKey::from_secret_key(secp_ctx, &our_key); let mut sha = Sha256::engine(); @@ -205,26 +196,21 @@ impl PeerChannelEncryptor { } #[inline] - fn inbound_noise_act( - state: &mut BidirectionalNoiseState, - act: &[u8], - our_key: &SecretKey, - ) -> Result<(PublicKey, [u8; 32]), LightningError> { + fn inbound_noise_act(state: &mut BidirectionalNoiseState, + act: &[u8], + our_key: &SecretKey) + -> Result<(PublicKey, [u8; 32]), LightningError> { assert_eq!(act.len(), 50); if act[0] != 0 { - return Err(LightningError { - err: "Unknown handshake version number", - action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }); + return Err(LightningError { err: "Unknown handshake version number", + action: msgs::ErrorAction::DisconnectPeer { msg: None } }); } let their_pub = match PublicKey::from_slice(&act[1..34]) { Err(_) => { - return Err(LightningError { - err: "Invalid public key", - action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }) + return Err(LightningError { err: "Invalid public key", + action: msgs::ErrorAction::DisconnectPeer { msg: None } }) }, Ok(key) => key, }; @@ -250,21 +236,19 @@ impl PeerChannelEncryptor { pub fn get_act_one(&mut self) -> [u8; 50] { match self.noise_state { - NoiseState::InProgress { - ref mut state, - ref directional_state, - ref mut bidirectional_state, - } => match directional_state { + NoiseState::InProgress { ref mut state, + ref directional_state, + ref mut bidirectional_state, } => match directional_state { &DirectionalNoiseState::Outbound { ref ie } => { if *state != NoiseStep::PreActOne { panic!("Requested act at wrong step"); } let (res, _) = PeerChannelEncryptor::outbound_noise_act( - &self.secp_ctx, - bidirectional_state, - &ie, - &self.their_node_id.unwrap(), + &self.secp_ctx, + bidirectional_state, + &ie, + &self.their_node_id.unwrap(), ); *state = NoiseStep::PostActOne; res @@ -275,25 +259,20 @@ impl PeerChannelEncryptor { } } - pub fn process_act_one_with_keys( - &mut self, - act_one: &[u8], - our_node_secret: &SecretKey, - our_ephemeral: SecretKey, - ) -> Result<[u8; 50], LightningError> { + pub fn process_act_one_with_keys(&mut self, + act_one: &[u8], + our_node_secret: &SecretKey, + our_ephemeral: SecretKey) + -> Result<[u8; 50], LightningError> { assert_eq!(act_one.len(), 50); match self.noise_state { - NoiseState::InProgress { - ref mut state, - ref mut directional_state, - ref mut bidirectional_state, - } => match directional_state { - &mut DirectionalNoiseState::Inbound { - ref mut ie, - ref mut re, - ref mut temp_k2, - } => { + NoiseState::InProgress { ref mut state, + ref mut directional_state, + ref mut bidirectional_state, } => match directional_state { + &mut DirectionalNoiseState::Inbound { ref mut ie, + ref mut re, + ref mut temp_k2, } => { if *state != NoiseStep::PreActOne { panic!("Requested act at wrong step"); } @@ -305,10 +284,10 @@ impl PeerChannelEncryptor { re.get_or_insert(our_ephemeral); let (res, temp_k) = PeerChannelEncryptor::outbound_noise_act( - &self.secp_ctx, - bidirectional_state, - &re.unwrap(), - &ie.unwrap(), + &self.secp_ctx, + bidirectional_state, + &re.unwrap(), + &ie.unwrap(), ); *temp_k2 = Some(temp_k); *state = NoiseStep::PostActTwo; @@ -320,21 +299,18 @@ impl PeerChannelEncryptor { } } - pub fn process_act_two( - &mut self, - act_two: &[u8], - our_node_secret: &SecretKey, - ) -> Result<([u8; 66], PublicKey), LightningError> { + pub fn process_act_two(&mut self, + act_two: &[u8], + our_node_secret: &SecretKey) + -> Result<([u8; 66], PublicKey), LightningError> { assert_eq!(act_two.len(), 50); let final_hkdf; let ck; let res: [u8; 66] = match self.noise_state { - NoiseState::InProgress { - ref state, - ref directional_state, - ref mut bidirectional_state, - } => match directional_state { + NoiseState::InProgress { ref state, + ref directional_state, + ref mut bidirectional_state, } => match directional_state { &DirectionalNoiseState::Outbound { ref ie } => { if *state != NoiseStep::PostActOne { panic!("Requested act at wrong step"); @@ -346,11 +322,11 @@ impl PeerChannelEncryptor { let our_node_id = PublicKey::from_secret_key(&self.secp_ctx, &our_node_secret); PeerChannelEncryptor::encrypt_with_ad( - &mut res[1..50], - 1, - &temp_k2, - &bidirectional_state.h, - &our_node_id.serialize()[..], + &mut res[1..50], + 1, + &temp_k2, + &bidirectional_state.h, + &our_node_id.serialize()[..], ); let mut sha = Sha256::engine(); @@ -372,14 +348,12 @@ impl PeerChannelEncryptor { }; let (sk, rk) = final_hkdf; - self.noise_state = NoiseState::Finished { - sk, - sn: 0, - sck: ck.clone(), - rk, - rn: 0, - rck: ck, - }; + self.noise_state = NoiseState::Finished { sk, + sn: 0, + sck: ck.clone(), + rk, + rn: 0, + rck: ck }; Ok((res, self.their_node_id.unwrap().clone())) } @@ -390,43 +364,37 @@ impl PeerChannelEncryptor { let final_hkdf; let ck; match self.noise_state { - NoiseState::InProgress { - ref state, - ref directional_state, - ref mut bidirectional_state, - } => match directional_state { - &DirectionalNoiseState::Inbound { - ie: _, - ref re, - ref temp_k2, - } => { + NoiseState::InProgress { ref state, + ref directional_state, + ref mut bidirectional_state, } => match directional_state { + &DirectionalNoiseState::Inbound { ie: _, + ref re, + ref temp_k2, } => { if *state != NoiseStep::PostActTwo { panic!("Requested act at wrong step"); } if act_three[0] != 0 { - return Err(LightningError { - err: "Unknown handshake version number", - action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }); + return Err(LightningError { err: "Unknown handshake version number", + action: msgs::ErrorAction::DisconnectPeer { msg: None } }); } let mut their_node_id = [0; 33]; PeerChannelEncryptor::decrypt_with_ad( - &mut their_node_id, - 1, - &temp_k2.unwrap(), - &bidirectional_state.h, - &act_three[1..50], + &mut their_node_id, + 1, + &temp_k2.unwrap(), + &bidirectional_state.h, + &act_three[1..50], )?; - self.their_node_id = Some(match PublicKey::from_slice(&their_node_id) { - Ok(key) => key, - Err(_) => { - return Err(LightningError { - err: "Bad node_id from peer", - action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }) - }, - }); + self.their_node_id = + Some(match PublicKey::from_slice(&their_node_id) { + Ok(key) => key, + Err(_) => { + return Err(LightningError { err: "Bad node_id from peer", + action: msgs::ErrorAction::DisconnectPeer { msg: + None, }, }) + }, + }); let mut sha = Sha256::engine(); sha.input(&bidirectional_state.h); @@ -437,11 +405,11 @@ impl PeerChannelEncryptor { let temp_k = PeerChannelEncryptor::hkdf(bidirectional_state, ss); PeerChannelEncryptor::decrypt_with_ad( - &mut [0; 0], - 0, - &temp_k, - &bidirectional_state.h, - &act_three[50..], + &mut [0; 0], + 0, + &temp_k, + &bidirectional_state.h, + &act_three[50..], )?; final_hkdf = Self::hkdf_extract_expand(&bidirectional_state.ck, &[0; 0]); ck = bidirectional_state.ck.clone(); @@ -452,14 +420,12 @@ impl PeerChannelEncryptor { } let (rk, sk) = final_hkdf; - self.noise_state = NoiseState::Finished { - sk, - sn: 0, - sck: ck.clone(), - rk, - rn: 0, - rck: ck, - }; + self.noise_state = NoiseState::Finished { sk, + sn: 0, + sck: ck.clone(), + rk, + rn: 0, + rck: ck }; Ok(self.their_node_id.unwrap().clone()) } @@ -475,14 +441,12 @@ impl PeerChannelEncryptor { res.resize(msg.len() + 16 * 2 + 2, 0); match self.noise_state { - NoiseState::Finished { - ref mut sk, - ref mut sn, - ref mut sck, - rk: _, - rn: _, - rck: _, - } => { + NoiseState::Finished { ref mut sk, + ref mut sn, + ref mut sck, + rk: _, + rn: _, + rck: _, } => { if *sn >= 1000 { let (new_sck, new_sk) = Self::hkdf_extract_expand(sck, sk); *sck = new_sck; @@ -491,11 +455,11 @@ impl PeerChannelEncryptor { } Self::encrypt_with_ad( - &mut res[0..16 + 2], - *sn, - sk, - &[0; 0], - &byte_utils::be16_to_array(msg.len() as u16), + &mut res[0..16 + 2], + *sn, + sk, + &[0; 0], + &byte_utils::be16_to_array(msg.len() as u16), ); *sn += 1; @@ -514,14 +478,12 @@ impl PeerChannelEncryptor { assert_eq!(msg.len(), 16 + 2); match self.noise_state { - NoiseState::Finished { - sk: _, - sn: _, - sck: _, - ref mut rk, - ref mut rn, - ref mut rck, - } => { + NoiseState::Finished { sk: _, + sn: _, + sck: _, + ref mut rk, + ref mut rn, + ref mut rck, } => { if *rn >= 1000 { let (new_rck, new_rk) = Self::hkdf_extract_expand(rck, rk); *rck = new_rck; @@ -546,14 +508,12 @@ impl PeerChannelEncryptor { } match self.noise_state { - NoiseState::Finished { - sk: _, - sn: _, - sck: _, - ref rk, - ref mut rn, - rck: _, - } => { + NoiseState::Finished { sk: _, + sn: _, + sck: _, + ref rk, + ref mut rn, + rck: _, } => { let mut res = Vec::with_capacity(msg.len() - 16); res.resize(msg.len() - 16, 0); Self::decrypt_with_ad(&mut res[..], *rn, rk, &[0; 0], msg)?; @@ -634,14 +594,12 @@ mod tests { assert_eq!(outbound_peer.process_act_two(&act_two[..], &our_node_id).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]); match outbound_peer.noise_state { - NoiseState::Finished { - sk, - sn, - sck, - rk, - rn, - rck, - } => { + NoiseState::Finished { sk, + sn, + sck, + rk, + rn, + rck, } => { assert_eq!( sk, hex::decode("969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9").unwrap()[..] @@ -731,19 +689,17 @@ mod tests { // test vector doesn't specify the initiator static key, but it's the same as the one // from transport-initiator successful handshake assert_eq!( - inbound_peer.process_act_three(&act_three[..]).unwrap().serialize()[..], - hex::decode("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa").unwrap()[..] + inbound_peer.process_act_three(&act_three[..]).unwrap().serialize()[..], + hex::decode("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa").unwrap()[..] ); match inbound_peer.noise_state { - NoiseState::Finished { - sk, - sn, - sck, - rk, - rn, - rck, - } => { + NoiseState::Finished { sk, + sn, + sck, + rk, + rn, + rck, } => { assert_eq!( sk, hex::decode("bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442").unwrap()[..] @@ -779,9 +735,8 @@ mod tests { ) .unwrap() .to_vec(); - assert!(inbound_peer - .process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()) - .is_err()); + assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()) + .is_err()); } { // transport-responder act1 bad key serialization test @@ -792,9 +747,8 @@ mod tests { ) .unwrap() .to_vec(); - assert!(inbound_peer - .process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()) - .is_err()); + assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()) + .is_err()); } { // transport-responder act1 bad MAC test @@ -805,9 +759,8 @@ mod tests { ) .unwrap() .to_vec(); - assert!(inbound_peer - .process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()) - .is_err()); + assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &our_node_id, our_ephemeral.clone()) + .is_err()); } { // transport-responder act3 bad version test @@ -891,14 +844,12 @@ mod tests { assert_eq!(outbound_peer.process_act_two(&act_two[..], &our_node_id).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]); match outbound_peer.noise_state { - NoiseState::Finished { - sk, - sn, - sck, - rk, - rn, - rck, - } => { + NoiseState::Finished { sk, + sn, + sck, + rk, + rn, + rck, } => { assert_eq!( sk, hex::decode("969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9").unwrap()[..] @@ -948,19 +899,17 @@ mod tests { // test vector doesn't specify the initiator static key, but it's the same as the one // from transport-initiator successful handshake assert_eq!( - inbound_peer.process_act_three(&act_three[..]).unwrap().serialize()[..], - hex::decode("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa").unwrap()[..] + inbound_peer.process_act_three(&act_three[..]).unwrap().serialize()[..], + hex::decode("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa").unwrap()[..] ); match inbound_peer.noise_state { - NoiseState::Finished { - sk, - sn, - sck, - rk, - rn, - rck, - } => { + NoiseState::Finished { sk, + sn, + sck, + rk, + rn, + rck, } => { assert_eq!( sk, hex::decode("bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442").unwrap()[..] @@ -991,8 +940,8 @@ mod tests { let len_header = res[0..2 + 16].to_vec(); assert_eq!( - inbound_peer.decrypt_length_header(&len_header[..]).unwrap() as usize, - msg.len() + inbound_peer.decrypt_length_header(&len_header[..]).unwrap() as usize, + msg.len() ); assert_eq!(inbound_peer.decrypt_message(&res[2 + 16..]).unwrap()[..], msg[..]); diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index 3b228069dc1..7b94e4c7763 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -148,11 +148,9 @@ struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> { } impl PeerHolder { fn borrow_parts(&mut self) -> MutPeerHolder { - MutPeerHolder { - peers: &mut self.peers, - peers_needing_send: &mut self.peers_needing_send, - node_id_to_descriptor: &mut self.node_id_to_descriptor, - } + MutPeerHolder { peers: &mut self.peers, + peers_needing_send: &mut self.peers_needing_send, + node_id_to_descriptor: &mut self.node_id_to_descriptor } } } @@ -208,29 +206,24 @@ impl PeerManager { /// Constructs a new PeerManager with the given message handlers and node_id secret key /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be /// cryptographically secure random bytes. - pub fn new( - message_handler: MessageHandler, - our_node_secret: SecretKey, - ephemeral_random_data: &[u8; 32], - logger: Arc, - ) -> PeerManager { + pub fn new(message_handler: MessageHandler, + our_node_secret: SecretKey, + ephemeral_random_data: &[u8; 32], + logger: Arc) + -> PeerManager { let mut ephemeral_key_midstate = Sha256::engine(); ephemeral_key_midstate.input(ephemeral_random_data); - PeerManager { - message_handler, - peers: Mutex::new(PeerHolder { - peers: HashMap::new(), - peers_needing_send: HashSet::new(), - node_id_to_descriptor: HashMap::new(), - }), - our_node_secret, - ephemeral_key_midstate, - peer_counter_low: AtomicUsize::new(0), - peer_counter_high: AtomicUsize::new(0), - initial_syncs_sent: AtomicUsize::new(0), - logger, - } + PeerManager { message_handler, + peers: Mutex::new(PeerHolder { peers: HashMap::new(), + peers_needing_send: HashSet::new(), + node_id_to_descriptor: HashMap::new() }), + our_node_secret, + ephemeral_key_midstate, + peer_counter_low: AtomicUsize::new(0), + peer_counter_high: AtomicUsize::new(0), + initial_syncs_sent: AtomicUsize::new(0), + logger } } /// Get the list of node ids for peers which have completed the initial handshake. @@ -240,16 +233,15 @@ impl PeerManager { /// completed and we are sure the remote peer has the private key for the given node_id. pub fn get_peer_node_ids(&self) -> Vec { let peers = self.peers.lock().unwrap(); - peers - .peers - .values() - .filter_map(|p| { - if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() { - return None; - } - p.their_node_id - }) - .collect() + peers.peers + .values() + .filter_map(|p| { + if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() { + return None; + } + p.their_node_id + }) + .collect() } fn get_ephemeral_key(&self) -> SecretKey { @@ -273,37 +265,33 @@ impl PeerManager { /// /// Panics if descriptor is duplicative with some other descriptor which has not yet has a /// disconnect_event. - pub fn new_outbound_connection( - &self, - their_node_id: PublicKey, - descriptor: Descriptor, - ) -> Result, PeerHandleError> { + pub fn new_outbound_connection(&self, + their_node_id: PublicKey, + descriptor: Descriptor) + -> Result, PeerHandleError> { let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key()); let res = peer_encryptor.get_act_one().to_vec(); let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes let mut peers = self.peers.lock().unwrap(); - if peers - .peers - .insert( - descriptor, - Peer { - channel_encryptor: peer_encryptor, - outbound: true, - their_node_id: None, - their_global_features: None, - their_local_features: None, - pending_outbound_buffer: LinkedList::new(), - pending_outbound_buffer_first_msg_offset: 0, - awaiting_write_event: false, - pending_read_buffer, - pending_read_buffer_pos: 0, - pending_read_is_header: false, - sync_status: InitSyncTracker::NoSyncRequested, - awaiting_pong: false, - }, - ) - .is_some() + if peers.peers + .insert( + descriptor, + Peer { channel_encryptor: peer_encryptor, + outbound: true, + their_node_id: None, + their_global_features: None, + their_local_features: None, + pending_outbound_buffer: LinkedList::new(), + pending_outbound_buffer_first_msg_offset: 0, + awaiting_write_event: false, + pending_read_buffer, + pending_read_buffer_pos: 0, + pending_read_is_header: false, + sync_status: InitSyncTracker::NoSyncRequested, + awaiting_pong: false, }, + ) + .is_some() { panic!("PeerManager driver duplicated descriptors!"); }; @@ -324,27 +312,24 @@ impl PeerManager { let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes let mut peers = self.peers.lock().unwrap(); - if peers - .peers - .insert( - descriptor, - Peer { - channel_encryptor: peer_encryptor, - outbound: false, - their_node_id: None, - their_global_features: None, - their_local_features: None, - pending_outbound_buffer: LinkedList::new(), - pending_outbound_buffer_first_msg_offset: 0, - awaiting_write_event: false, - pending_read_buffer, - pending_read_buffer_pos: 0, - pending_read_is_header: false, - sync_status: InitSyncTracker::NoSyncRequested, - awaiting_pong: false, - }, - ) - .is_some() + if peers.peers + .insert( + descriptor, + Peer { channel_encryptor: peer_encryptor, + outbound: false, + their_node_id: None, + their_global_features: None, + their_local_features: None, + pending_outbound_buffer: LinkedList::new(), + pending_outbound_buffer_first_msg_offset: 0, + awaiting_write_event: false, + pending_read_buffer, + pending_read_buffer_pos: 0, + pending_read_is_header: false, + sync_status: InitSyncTracker::NoSyncRequested, + awaiting_pong: false, }, + ) + .is_some() { panic!("PeerManager driver duplicated descriptors!"); }; @@ -365,10 +350,9 @@ impl PeerManager { InitSyncTracker::NoSyncRequested => {}, InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => { let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8; - let all_messages = self - .message_handler - .route_handler - .get_next_channel_announcements(0, steps); + let all_messages = self.message_handler + .route_handler + .get_next_channel_announcements(0, steps); for &(ref announce, ref update_a, ref update_b) in all_messages.iter() { encode_and_send_msg!(announce, 256); encode_and_send_msg!(update_a, 258); @@ -381,10 +365,9 @@ impl PeerManager { }, InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => { let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8; - let all_messages = self - .message_handler - .route_handler - .get_next_node_announcements(None, steps); + let all_messages = self.message_handler + .route_handler + .get_next_node_announcements(None, steps); for msg in all_messages.iter() { encode_and_send_msg!(msg, 256); peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id); @@ -396,10 +379,9 @@ impl PeerManager { InitSyncTracker::ChannelsSyncing(_) => unreachable!(), InitSyncTracker::NodesSyncing(key) => { let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8; - let all_messages = self - .message_handler - .route_handler - .get_next_node_announcements(Some(&key), steps); + let all_messages = self.message_handler + .route_handler + .get_next_node_announcements(Some(&key), steps); for msg in all_messages.iter() { encode_and_send_msg!(msg, 256); peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id); @@ -492,12 +474,16 @@ impl PeerManager { while read_pos < data.len() { { let data_to_copy = cmp::min( - peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, - data.len() - read_pos, + peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, + data.len() - read_pos, ); peer.pending_read_buffer [peer.pending_read_buffer_pos..peer.pending_read_buffer_pos + data_to_copy] - .copy_from_slice(&data[read_pos..read_pos + data_to_copy]); + .copy_from_slice( + &data[read_pos + ..read_pos + + data_to_copy], + ); read_pos += data_to_copy; peer.pending_read_buffer_pos += data_to_copy; } @@ -592,8 +578,7 @@ impl PeerManager { &peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key() - )) - .to_vec(); + )).to_vec(); peer.pending_outbound_buffer.push_back(act_two); peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long }, @@ -613,11 +598,9 @@ impl PeerManager { local_features.set_initial_routing_sync(); } encode_and_send_msg!( - msgs::Init { - global_features: msgs::GlobalFeatures::new(), - local_features - }, - 16 + msgs::Init { global_features: msgs::GlobalFeatures::new(), + local_features }, + 16 ); }, NextNoiseStep::ActThree => { @@ -638,9 +621,7 @@ impl PeerManager { peer.pending_read_buffer.resize(msg_len as usize + 16, 0); if msg_len < 2 { // Need at least the message type tag - return Err(PeerHandleError { - no_connection_possible: false, - }); + return Err(PeerHandleError { no_connection_possible: false }); } peer.pending_read_is_header = false; } else { @@ -655,21 +636,19 @@ impl PeerManager { let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]); log_trace!( - self, - "Received message of type {} from {}", - msg_type, - log_pubkey!(peer.their_node_id.unwrap()) + self, + "Received message of type {} from {}", + msg_type, + log_pubkey!(peer.their_node_id.unwrap()) ); if msg_type != 16 && peer.their_global_features.is_none() { // Need an init message as first message log_trace!( - self, - "Peer {} sent non-Init first message", - log_pubkey!(peer.their_node_id.unwrap()) + self, + "Peer {} sent non-Init first message", + log_pubkey!(peer.their_node_id.unwrap()) ); - return Err(PeerHandleError { - no_connection_possible: false, - }); + return Err(PeerHandleError { no_connection_possible: false }); } let mut reader = ::std::io::Cursor::new(&msg_data[2..]); match msg_type { @@ -678,26 +657,20 @@ impl PeerManager { let msg = try_potential_decodeerror!(msgs::Init::read(&mut reader)); if msg.global_features.requires_unknown_bits() { log_info!( - self, - "Peer global features required unknown version bits" + self, + "Peer global features required unknown version bits" ); - return Err(PeerHandleError { - no_connection_possible: true, - }); + return Err(PeerHandleError { no_connection_possible: true }); } if msg.local_features.requires_unknown_bits() { log_info!( - self, - "Peer local features required unknown version bits" + self, + "Peer local features required unknown version bits" ); - return Err(PeerHandleError { - no_connection_possible: true, - }); + return Err(PeerHandleError { no_connection_possible: true }); } if peer.their_global_features.is_some() { - return Err(PeerHandleError { - no_connection_possible: false, - }); + return Err(PeerHandleError { no_connection_possible: false }); } log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}", if msg.local_features.supports_data_loss_protect() { "supported" } else { "not supported" }, if msg.local_features.initial_routing_sync() { "requested" } else { "not requested" }, if msg.local_features.supports_upfront_shutdown_script() { "supported" } else { "not supported" }, if msg.local_features.supports_unknown_bits() { "present" } else { "none" }, if msg.global_features.supports_unknown_bits() { "present" } else { "none" }); @@ -712,24 +685,23 @@ impl PeerManager { if !peer.outbound { let mut local_features = msgs::LocalFeatures::new(); if self.initial_syncs_sent.load(Ordering::Acquire) - < INITIAL_SYNCS_TO_SEND + < INITIAL_SYNCS_TO_SEND { self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel); local_features.set_initial_routing_sync(); } encode_and_send_msg!( - msgs::Init { - global_features: msgs::GlobalFeatures::new(), - local_features - }, - 16 + msgs::Init { global_features: + msgs::GlobalFeatures::new(), + local_features }, + 16 ); } self.message_handler - .chan_handler - .peer_connected(&peer.their_node_id.unwrap()); + .chan_handler + .peer_connected(&peer.their_node_id.unwrap()); }, 17 => { let msg = @@ -744,25 +716,25 @@ impl PeerManager { if data_is_printable { log_debug!( - self, - "Got Err message from {}: {}", - log_pubkey!(peer.their_node_id.unwrap()), - msg.data + self, + "Got Err message from {}: {}", + log_pubkey!(peer.their_node_id.unwrap()), + msg.data ); } else { log_debug!( - self, - "Got Err message from {} with non-ASCII error message", - log_pubkey!(peer.their_node_id.unwrap()) + self, + "Got Err message from {} with non-ASCII error message", + log_pubkey!(peer.their_node_id.unwrap()) ); } - self.message_handler - .chan_handler - .handle_error(&peer.their_node_id.unwrap(), &msg); + self.message_handler.chan_handler.handle_error( + &peer.their_node_id + .unwrap(), + &msg, + ); if msg.channel_id == [0; 32] { - return Err(PeerHandleError { - no_connection_possible: true, - }); + return Err(PeerHandleError { no_connection_possible: true }); } }, @@ -781,19 +753,23 @@ impl PeerManager { 32 => { let msg = try_potential_decodeerror!(msgs::OpenChannel::read(&mut reader)); - self.message_handler.chan_handler.handle_open_channel( - &peer.their_node_id.unwrap(), - peer.their_local_features.clone().unwrap(), - &msg, + self.message_handler + .chan_handler + .handle_open_channel( + &peer.their_node_id.unwrap(), + peer.their_local_features.clone().unwrap(), + &msg, ); }, 33 => { let msg = try_potential_decodeerror!(msgs::AcceptChannel::read(&mut reader)); - self.message_handler.chan_handler.handle_accept_channel( - &peer.their_node_id.unwrap(), - peer.their_local_features.clone().unwrap(), - &msg, + self.message_handler + .chan_handler + .handle_accept_channel( + &peer.their_node_id.unwrap(), + peer.their_local_features.clone().unwrap(), + &msg, ); }, @@ -801,67 +777,71 @@ impl PeerManager { let msg = try_potential_decodeerror!(msgs::FundingCreated::read(&mut reader)); self.message_handler - .chan_handler - .handle_funding_created(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_funding_created(&peer.their_node_id.unwrap(), &msg); }, 35 => { let msg = try_potential_decodeerror!(msgs::FundingSigned::read(&mut reader)); self.message_handler - .chan_handler - .handle_funding_signed(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_funding_signed(&peer.their_node_id.unwrap(), &msg); }, 36 => { let msg = try_potential_decodeerror!(msgs::FundingLocked::read(&mut reader)); self.message_handler - .chan_handler - .handle_funding_locked(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_funding_locked(&peer.their_node_id.unwrap(), &msg); }, 38 => { let msg = try_potential_decodeerror!(msgs::Shutdown::read(&mut reader)); - self.message_handler - .chan_handler - .handle_shutdown(&peer.their_node_id.unwrap(), &msg); + self.message_handler.chan_handler.handle_shutdown( + &peer.their_node_id + .unwrap(), + &msg, + ); }, 39 => { let msg = try_potential_decodeerror!(msgs::ClosingSigned::read(&mut reader)); self.message_handler - .chan_handler - .handle_closing_signed(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_closing_signed(&peer.their_node_id.unwrap(), &msg); }, 128 => { let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::read(&mut reader)); self.message_handler - .chan_handler - .handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg); }, 130 => { let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::read( &mut reader )); self.message_handler - .chan_handler - .handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg); }, 131 => { let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::read(&mut reader)); self.message_handler - .chan_handler - .handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg); }, 135 => { let msg = try_potential_decodeerror!( msgs::UpdateFailMalformedHTLC::read(&mut reader) ); - self.message_handler.chan_handler.handle_update_fail_malformed_htlc( - &peer.their_node_id.unwrap(), - &msg, + self.message_handler + .chan_handler + .handle_update_fail_malformed_htlc( + &peer.their_node_id.unwrap(), + &msg, ); }, @@ -870,30 +850,30 @@ impl PeerManager { &mut reader )); self.message_handler - .chan_handler - .handle_commitment_signed(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_commitment_signed(&peer.their_node_id.unwrap(), &msg); }, 133 => { let msg = try_potential_decodeerror!(msgs::RevokeAndACK::read(&mut reader)); self.message_handler - .chan_handler - .handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg); }, 134 => { let msg = try_potential_decodeerror!(msgs::UpdateFee::read(&mut reader)); self.message_handler - .chan_handler - .handle_update_fee(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_update_fee(&peer.their_node_id.unwrap(), &msg); }, 136 => { let msg = try_potential_decodeerror!(msgs::ChannelReestablish::read( &mut reader )); self.message_handler - .chan_handler - .handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg); }, // Routing control: @@ -902,8 +882,8 @@ impl PeerManager { msgs::AnnouncementSignatures::read(&mut reader) ); self.message_handler - .chan_handler - .handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg); + .chan_handler + .handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg); }, 256 => { let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::read( @@ -945,9 +925,7 @@ impl PeerManager { }, _ => { if (msg_type & 1) == 0 { - return Err(PeerHandleError { - no_connection_possible: true, - }); + return Err(PeerHandleError { no_connection_possible: true }); } }, } @@ -1006,30 +984,30 @@ impl PeerManager { match event { MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendAcceptChannel event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.temporary_channel_id) + self, + "Handling SendAcceptChannel event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.temporary_channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Drop the pending channel? (or just let it timeout, but that sucks) }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 33))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 33))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendOpenChannel event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.temporary_channel_id) + self, + "Handling SendOpenChannel event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.temporary_channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Drop the pending channel? (or just let it timeout, but that sucks) }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => { @@ -1039,36 +1017,36 @@ impl PeerManager { //they should just throw away this funding transaction }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendFundingSigned event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.channel_id) + self, + "Handling SendFundingSigned event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: generate a DiscardFunding event indicating to the wallet that //they should just throw away this funding transaction }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 35))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 35))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendFundingLocked event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.channel_id) + self, + "Handling SendFundingLocked event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => { @@ -1083,133 +1061,127 @@ impl PeerManager { //they should just throw away this funding transaction }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 259))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 259))); self.do_attempt_write_data(&mut descriptor, peer); }, - MessageSendEvent::UpdateHTLCs { - ref node_id, - updates: - msgs::CommitmentUpdate { - ref update_add_htlcs, - ref update_fulfill_htlcs, - ref update_fail_htlcs, - ref update_fail_malformed_htlcs, - ref update_fee, - ref commitment_signed, - }, - } => { + MessageSendEvent::UpdateHTLCs { ref node_id, + updates: + msgs::CommitmentUpdate { ref update_add_htlcs, + ref update_fulfill_htlcs, + ref update_fail_htlcs, + ref update_fail_malformed_htlcs, + ref update_fee, + ref commitment_signed, }, } => { log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}", log_pubkey!(node_id), update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len(), log_bytes!(commitment_signed.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); for msg in update_add_htlcs { peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128))); } for msg in update_fulfill_htlcs { peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130))); } for msg in update_fail_htlcs { peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131))); } for msg in update_fail_malformed_htlcs { peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135))); } if let &Some(ref msg) = update_fee { peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 134))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 134))); } peer.pending_outbound_buffer.push_back( - peer.channel_encryptor - .encrypt_message(&encode_msg!(commitment_signed, 132)), + peer.channel_encryptor.encrypt_message(&encode_msg!( + commitment_signed, + 132 + )), ); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.channel_id) + self, + "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 133))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 133))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendClosingSigned event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.channel_id) + self, + "Handling SendClosingSigned event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 39))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 39))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendShutdown { ref node_id, ref msg } => { log_trace!( - self, - "Handling Shutdown event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.channel_id) + self, + "Handling Shutdown event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => { log_trace!( - self, - "Handling SendChannelReestablish event in peer_handler for node {} for channel {}", - log_pubkey!(node_id), - log_bytes!(msg.channel_id) + self, + "Handling SendChannelReestablish event in peer_handler for node {} for channel {}", + log_pubkey!(node_id), + log_bytes!(msg.channel_id) ); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 136))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 136))); self.do_attempt_write_data(&mut descriptor, peer); }, - MessageSendEvent::BroadcastChannelAnnouncement { - ref msg, - ref update_msg, - } => { + MessageSendEvent::BroadcastChannelAnnouncement { ref msg, + ref update_msg, } => { log_trace!( self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id ); - if self - .message_handler - .route_handler - .handle_channel_announcement(msg) - .is_ok() && self - .message_handler - .route_handler - .handle_channel_update(update_msg) - .is_ok() + if self.message_handler + .route_handler + .handle_channel_announcement(msg) + .is_ok() && self.message_handler + .route_handler + .handle_channel_update(update_msg) + .is_ok() { let encoded_msg = encode_msg!(msg, 256); let encoded_update_msg = encode_msg!(update_msg, 258); for (ref descriptor, ref mut peer) in peers.peers.iter_mut() { if !peer.channel_encryptor.is_ready_for_encryption() - || peer.their_global_features.is_none() - || !peer.should_forward_channel(msg.contents.short_channel_id) + || peer.their_global_features.is_none() + || !peer.should_forward_channel(msg.contents.short_channel_id) { continue; } @@ -1217,51 +1189,49 @@ impl PeerManager { None => continue, Some(their_node_id) => { if their_node_id == msg.contents.node_id_1 - || their_node_id == msg.contents.node_id_2 + || their_node_id == msg.contents.node_id_2 { continue; } }, } peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); + .push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..])); + .push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..])); self.do_attempt_write_data(&mut (*descriptor).clone(), peer); } } }, MessageSendEvent::BroadcastChannelUpdate { ref msg } => { log_trace!( - self, - "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", - msg.contents.short_channel_id + self, + "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", + msg.contents.short_channel_id ); if self.message_handler.route_handler.handle_channel_update(msg).is_ok() { let encoded_msg = encode_msg!(msg, 258); for (ref descriptor, ref mut peer) in peers.peers.iter_mut() { if !peer.channel_encryptor.is_ready_for_encryption() - || peer.their_global_features.is_none() - || !peer.should_forward_channel(msg.contents.short_channel_id) + || peer.their_global_features.is_none() + || !peer.should_forward_channel(msg.contents.short_channel_id) { continue; } peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); + .push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); self.do_attempt_write_data(&mut (*descriptor).clone(), peer); } } }, MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => { self.message_handler - .route_handler - .handle_htlc_fail_channel_update(update); + .route_handler + .handle_htlc_fail_channel_update(update); }, - MessageSendEvent::HandleError { - ref node_id, - ref action, - } => { + MessageSendEvent::HandleError { ref node_id, + ref action, } => { match *action { msgs::ErrorAction::DisconnectPeer { ref msg } => { if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) { @@ -1269,8 +1239,10 @@ impl PeerManager { if let Some(mut peer) = peers.peers.remove(&descriptor) { if let Some(ref msg) = *msg { log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}", log_pubkey!(node_id), msg.data); - peer.pending_outbound_buffer.push_back( - peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)), + peer.pending_outbound_buffer + .push_back( + peer.channel_encryptor + .encrypt_message(&encode_msg!(msg, 17)), ); // This isn't guaranteed to work, but if there is enough free // room in the send buffer, put the error message there... @@ -1290,7 +1262,7 @@ impl PeerManager { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer - .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17))); + .push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17))); self.do_attempt_write_data(&mut descriptor, peer); }, } @@ -1325,8 +1297,8 @@ impl PeerManager { Some(node_id) => { peers.node_id_to_descriptor.remove(&node_id); self.message_handler - .chan_handler - .peer_disconnected(&node_id, no_connection_possible); + .chan_handler + .peer_disconnected(&node_id, no_connection_possible); }, None => {}, }, @@ -1346,32 +1318,30 @@ impl PeerManager { let peers = peers.peers; peers.retain(|descriptor, peer| { - if peer.awaiting_pong == true { - peers_needing_send.remove(descriptor); - match peer.their_node_id { - Some(node_id) => { - node_id_to_descriptor.remove(&node_id); - self.message_handler.chan_handler.peer_disconnected(&node_id, true); - }, - None => {}, - } - } - - let ping = msgs::Ping { - ponglen: 0, - byteslen: 64, - }; - peer.pending_outbound_buffer.push_back(encode_msg!(ping, 18)); - let mut descriptor_clone = descriptor.clone(); - self.do_attempt_write_data(&mut descriptor_clone, peer); - - if peer.awaiting_pong { - false // Drop the peer - } else { - peer.awaiting_pong = true; - true - } - }); + if peer.awaiting_pong == true { + peers_needing_send.remove(descriptor); + match peer.their_node_id { + Some(node_id) => { + node_id_to_descriptor.remove(&node_id); + self.message_handler.chan_handler.peer_disconnected(&node_id, true); + }, + None => {}, + } + } + + let ping = msgs::Ping { ponglen: 0, + byteslen: 64 }; + peer.pending_outbound_buffer.push_back(encode_msg!(ping, 18)); + let mut descriptor_clone = descriptor.clone(); + self.do_attempt_write_data(&mut descriptor_clone, peer); + + if peer.awaiting_pong { + false // Drop the peer + } else { + peer.awaiting_pong = true; + true + } + }); } } } @@ -1417,10 +1387,8 @@ mod tests { rng.fill_bytes(&mut key_slice); SecretKey::from_slice(&key_slice).unwrap() }; - let msg_handler = MessageHandler { - chan_handler: Arc::new(chan_handler), - route_handler: Arc::new(router), - }; + let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), + route_handler: Arc::new(router) }; let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger)); peers.push(peer); } @@ -1433,12 +1401,11 @@ mod tests { let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret); let fd = FileDescriptor { fd: 1 }; peer_a.new_inbound_connection(fd.clone()).unwrap(); - peer_a - .peers - .lock() - .unwrap() - .node_id_to_descriptor - .insert(their_id, fd.clone()); + peer_a.peers + .lock() + .unwrap() + .node_id_to_descriptor + .insert(their_id, fd.clone()); } #[test] @@ -1453,14 +1420,12 @@ mod tests { let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret); let chan_handler = test_utils::TestChannelMessageHandler::new(); - chan_handler - .pending_events - .lock() - .unwrap() - .push(events::MessageSendEvent::HandleError { - node_id: their_id, - action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }); + chan_handler.pending_events + .lock() + .unwrap() + .push(events::MessageSendEvent::HandleError { node_id: their_id, + action: + msgs::ErrorAction::DisconnectPeer { msg: None } }); assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1); peers[0].message_handler.chan_handler = Arc::new(chan_handler); diff --git a/lightning/src/ln/router.rs b/lightning/src/ln/router.rs index 7b77796121f..86c422b2b77 100644 --- a/lightning/src/ln/router.rs +++ b/lightning/src/ln/router.rs @@ -66,12 +66,10 @@ impl Readable for Route { let hops_count: u8 = Readable::read(reader)?; let mut hops = Vec::with_capacity(hops_count as usize); for _ in 0..hops_count { - hops.push(RouteHop { - pubkey: Readable::read(reader)?, - short_channel_id: Readable::read(reader)?, - fee_msat: Readable::read(reader)?, - cltv_expiry_delta: Readable::read(reader)?, - }); + hops.push(RouteHop { pubkey: Readable::read(reader)?, + short_channel_id: Readable::read(reader)?, + fee_msat: Readable::read(reader)?, + cltv_expiry_delta: Readable::read(reader)? }); } Ok(Route { hops }) } @@ -120,11 +118,11 @@ struct ChannelInfo { impl std::fmt::Display for ChannelInfo { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { write!( - f, - "features: {}, one_to_two: {}, two_to_one: {}", - log_bytes!(self.features.encode()), - self.one_to_two, - self.two_to_one + f, + "features: {}, one_to_two: {}, two_to_one: {}", + log_bytes!(self.features.encode()), + self.one_to_two, + self.two_to_one )?; Ok(()) } @@ -213,17 +211,15 @@ impl Readable for NodeInfo { } } let announcement_message = Readable::read(reader)?; - Ok(NodeInfo { - channels, - lowest_inbound_channel_fee_base_msat, - lowest_inbound_channel_fee_proportional_millionths, - features, - last_update, - rgb, - alias, - addresses, - announcement_message, - }) + Ok(NodeInfo { channels, + lowest_inbound_channel_fee_base_msat, + lowest_inbound_channel_fee_proportional_millionths, + features, + last_update, + rgb, + alias, + addresses, + announcement_message }) } } @@ -272,11 +268,9 @@ impl Readable for NetworkMap { let node_info = Readable::read(reader)?; nodes.insert(node_id, node_info); } - Ok(NetworkMap { - channels, - our_node_id, - nodes, - }) + Ok(NetworkMap { channels, + our_node_id, + nodes }) } } @@ -289,10 +283,8 @@ struct MutNetworkMap<'a> { } impl NetworkMap { fn borrow_parts(&mut self) -> MutNetworkMap { - MutNetworkMap { - channels: &mut self.channels, - nodes: &mut self.nodes, - } + MutNetworkMap { channels: &mut self.channels, + nodes: &mut self.nodes } } } impl std::fmt::Display for NetworkMap { @@ -389,12 +381,10 @@ impl ReadableArgs for Router { return Err(DecodeError::UnknownVersion); } let network_map = Readable::read(reader)?; - Ok(Router { - secp_ctx: Secp256k1::verification_only(), - network_map: RwLock::new(network_map), - chain_monitor: args.chain_monitor, - logger: args.logger, - }) + Ok(Router { secp_ctx: Secp256k1::verification_only(), + network_map: RwLock::new(network_map), + chain_monitor: args.chain_monitor, + logger: args.logger }) } } @@ -418,16 +408,12 @@ impl RoutingMessageHandler for Router { let mut network = self.network_map.write().unwrap(); match network.nodes.get_mut(&msg.contents.node_id) { - None => Err(LightningError { - err: "No existing channels for node_announcement", - action: ErrorAction::IgnoreError, - }), + None => Err(LightningError { err: "No existing channels for node_announcement", + action: ErrorAction::IgnoreError }), Some(node) => { if node.last_update >= msg.contents.timestamp { - return Err(LightningError { - err: "Update older than last processed update", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Update older than last processed update", + action: ErrorAction::IgnoreError }); } node.features = msg.contents.features.clone(); @@ -437,8 +423,8 @@ impl RoutingMessageHandler for Router { node.addresses = msg.contents.addresses.clone(); let should_relay = msg.contents.excess_data.is_empty() - && msg.contents.excess_address_data.is_empty() - && !msg.contents.features.supports_unknown_bits(); + && msg.contents.excess_address_data.is_empty() + && !msg.contents.features.supports_unknown_bits(); node.announcement_message = if should_relay { Some(msg.clone()) } else { None }; Ok(should_relay) }, @@ -448,50 +434,44 @@ impl RoutingMessageHandler for Router { fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result { if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 { - return Err(LightningError { - err: "Channel announcement node had a channel with itself", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Channel announcement node had a channel with itself", + action: ErrorAction::IgnoreError }); } let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]); secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1); secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2); secp_verify_sig!( - self.secp_ctx, - &msg_hash, - &msg.bitcoin_signature_1, - &msg.contents.bitcoin_key_1 + self.secp_ctx, + &msg_hash, + &msg.bitcoin_signature_1, + &msg.contents.bitcoin_key_1 ); secp_verify_sig!( - self.secp_ctx, - &msg_hash, - &msg.bitcoin_signature_2, - &msg.contents.bitcoin_key_2 + self.secp_ctx, + &msg_hash, + &msg.bitcoin_signature_2, + &msg.contents.bitcoin_key_2 ); if msg.contents.features.requires_unknown_bits() { panic!("Unknown-required-features ChannelAnnouncements should never deserialize!"); } - let checked_utxo = match self - .chain_monitor - .get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) + let checked_utxo = match self.chain_monitor + .get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) { Ok((script_pubkey, _value)) => { - let expected_script = Builder::new() - .push_opcode(opcodes::all::OP_PUSHNUM_2) - .push_slice(&msg.contents.bitcoin_key_1.serialize()) - .push_slice(&msg.contents.bitcoin_key_2.serialize()) - .push_opcode(opcodes::all::OP_PUSHNUM_2) - .push_opcode(opcodes::all::OP_CHECKMULTISIG) - .into_script() - .to_v0_p2wsh(); + let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2) + .push_slice(&msg.contents.bitcoin_key_1.serialize()) + .push_slice(&msg.contents.bitcoin_key_2.serialize()) + .push_opcode(opcodes::all::OP_PUSHNUM_2) + .push_opcode(opcodes::all::OP_CHECKMULTISIG) + .into_script() + .to_v0_p2wsh(); if script_pubkey != expected_script { - return Err(LightningError { - err: "Channel announcement keys didn't match on-chain script", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Channel announcement keys didn't match on-chain script", + action: ErrorAction::IgnoreError }); } //TODO: Check if value is worth storing, use it to inform routing, and compare it //to the new HTLC max field in channel_update @@ -502,16 +482,12 @@ impl RoutingMessageHandler for Router { false }, Err(ChainError::NotWatched) => { - return Err(LightningError { - err: "Channel announced on an unknown chain", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Channel announced on an unknown chain", + action: ErrorAction::IgnoreError }); }, Err(ChainError::UnknownTx) => { - return Err(LightningError { - err: "Channel announced without corresponding UTXO entry", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Channel announced without corresponding UTXO entry", + action: ErrorAction::IgnoreError }); }, }; @@ -520,35 +496,29 @@ impl RoutingMessageHandler for Router { let should_relay = msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits(); - let chan_info = ChannelInfo { - features: msg.contents.features.clone(), - one_to_two: DirectionalChannelInfo { - src_node_id: msg.contents.node_id_1.clone(), - last_update: 0, - enabled: false, - cltv_expiry_delta: u16::max_value(), - htlc_minimum_msat: u64::max_value(), - fee_base_msat: u32::max_value(), - fee_proportional_millionths: u32::max_value(), - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: msg.contents.node_id_2.clone(), - last_update: 0, - enabled: false, - cltv_expiry_delta: u16::max_value(), - htlc_minimum_msat: u64::max_value(), - fee_base_msat: u32::max_value(), - fee_proportional_millionths: u32::max_value(), - last_update_message: None, - }, - announcement_message: if should_relay { Some(msg.clone()) } else { None }, - }; - - match network.channels.entry(NetworkMap::get_key( - msg.contents.short_channel_id, - msg.contents.chain_hash, - )) { + let chan_info = + ChannelInfo { features: msg.contents.features.clone(), + one_to_two: DirectionalChannelInfo { src_node_id: msg.contents.node_id_1.clone(), + last_update: 0, + enabled: false, + cltv_expiry_delta: u16::max_value(), + htlc_minimum_msat: u64::max_value(), + fee_base_msat: u32::max_value(), + fee_proportional_millionths: u32::max_value(), + last_update_message: None }, + two_to_one: DirectionalChannelInfo { src_node_id: msg.contents.node_id_2.clone(), + last_update: 0, + enabled: false, + cltv_expiry_delta: u16::max_value(), + htlc_minimum_msat: u64::max_value(), + fee_base_msat: u32::max_value(), + fee_proportional_millionths: u32::max_value(), + last_update_message: None }, + announcement_message: if should_relay { Some(msg.clone()) } else { None } }; + + match network.channels + .entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) + { BtreeEntry::Occupied(mut entry) => { //TODO: because asking the blockchain if short_channel_id is valid is only optional //in the blockchain API, we need to handle it smartly here, though it's unclear @@ -565,10 +535,8 @@ impl RoutingMessageHandler for Router { Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id); *entry.get_mut() = chan_info; } else { - return Err(LightningError { - err: "Already have knowledge of channel", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Already have knowledge of channel", + action: ErrorAction::IgnoreError }); } }, BtreeEntry::Vacant(entry) => { @@ -600,10 +568,8 @@ impl RoutingMessageHandler for Router { &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => { let _ = self.handle_channel_update(msg); }, - &msgs::HTLCFailChannelUpdate::ChannelClosed { - ref short_channel_id, - ref is_permanent, - } => { + &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, + ref is_permanent, } => { let mut network = self.network_map.write().unwrap(); if *is_permanent { if let Some(chan) = network.channels.remove(short_channel_id) { @@ -616,10 +582,8 @@ impl RoutingMessageHandler for Router { } } }, - &msgs::HTLCFailChannelUpdate::NodeFailure { - ref node_id, - ref is_permanent, - } => { + &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, + ref is_permanent, } => { if *is_permanent { //TODO: Wholly remove the node } else { @@ -635,15 +599,12 @@ impl RoutingMessageHandler for Router { let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1); let chan_was_enabled; - match network.channels.get_mut(&NetworkMap::get_key( - msg.contents.short_channel_id, - msg.contents.chain_hash, - )) { + match network.channels + .get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) + { None => { - return Err(LightningError { - err: "Couldn't find channel for update", - action: ErrorAction::IgnoreError, - }) + return Err(LightningError { err: "Couldn't find channel for update", + action: ErrorAction::IgnoreError }) }, Some(channel) => { macro_rules! maybe_update_channel_info { @@ -665,19 +626,19 @@ impl RoutingMessageHandler for Router { if msg.contents.flags & 1 == 1 { dest_node_id = channel.one_to_two.src_node_id.clone(); secp_verify_sig!( - self.secp_ctx, - &msg_hash, - &msg.signature, - &channel.two_to_one.src_node_id + self.secp_ctx, + &msg_hash, + &msg.signature, + &channel.two_to_one.src_node_id ); maybe_update_channel_info!(channel.two_to_one); } else { dest_node_id = channel.two_to_one.src_node_id.clone(); secp_verify_sig!( - self.secp_ctx, - &msg_hash, - &msg.signature, - &channel.one_to_two.src_node_id + self.secp_ctx, + &msg_hash, + &msg.signature, + &channel.one_to_two.src_node_id ); maybe_update_channel_info!(channel.one_to_two); } @@ -688,10 +649,11 @@ impl RoutingMessageHandler for Router { let node = network.nodes.get_mut(&dest_node_id).unwrap(); node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat); - node.lowest_inbound_channel_fee_proportional_millionths = cmp::min( - node.lowest_inbound_channel_fee_proportional_millionths, - msg.contents.fee_proportional_millionths, - ); + node.lowest_inbound_channel_fee_proportional_millionths = + cmp::min( + node.lowest_inbound_channel_fee_proportional_millionths, + msg.contents.fee_proportional_millionths, + ); } else if chan_was_enabled { let mut lowest_inbound_channel_fee_base_msat = u32::max_value(); let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value(); @@ -704,17 +666,19 @@ impl RoutingMessageHandler for Router { if chan.one_to_two.src_node_id == dest_node_id { lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat); - lowest_inbound_channel_fee_proportional_millionths = cmp::min( - lowest_inbound_channel_fee_proportional_millionths, - chan.two_to_one.fee_proportional_millionths, - ); + lowest_inbound_channel_fee_proportional_millionths = + cmp::min( + lowest_inbound_channel_fee_proportional_millionths, + chan.two_to_one.fee_proportional_millionths, + ); } else { lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat); - lowest_inbound_channel_fee_proportional_millionths = cmp::min( - lowest_inbound_channel_fee_proportional_millionths, - chan.one_to_two.fee_proportional_millionths, - ); + lowest_inbound_channel_fee_proportional_millionths = + cmp::min( + lowest_inbound_channel_fee_proportional_millionths, + chan.one_to_two.fee_proportional_millionths, + ); } } } @@ -729,19 +693,18 @@ impl RoutingMessageHandler for Router { Ok(msg.contents.excess_data.is_empty()) } - fn get_next_channel_announcements( - &self, - starting_point: u64, - batch_amount: u8, - ) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate)> { + fn get_next_channel_announcements(&self, + starting_point: u64, + batch_amount: u8) + -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate)> { let mut result = Vec::with_capacity(batch_amount as usize); let network = self.network_map.read().unwrap(); let mut iter = network.channels.range(starting_point..); while result.len() < batch_amount as usize { if let Some((_, ref chan)) = iter.next() { if chan.announcement_message.is_some() - && chan.one_to_two.last_update_message.is_some() - && chan.two_to_one.last_update_message.is_some() + && chan.one_to_two.last_update_message.is_some() + && chan.two_to_one.last_update_message.is_some() { result.push(( chan.announcement_message.clone().unwrap(), @@ -759,11 +722,10 @@ impl RoutingMessageHandler for Router { result } - fn get_next_node_announcements( - &self, - starting_point: Option<&PublicKey>, - batch_amount: u8, - ) -> Vec { + fn get_next_node_announcements(&self, + starting_point: Option<&PublicKey>, + batch_amount: u8) + -> Vec { let mut result = Vec::with_capacity(batch_amount as usize); let network = self.network_map.read().unwrap(); let mut iter = if let Some(pubkey) = starting_point { @@ -795,10 +757,9 @@ struct RouteGraphNode { impl cmp::Ord for RouteGraphNode { fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering { - other - .lowest_fee_to_peer_through_node - .cmp(&self.lowest_fee_to_peer_through_node) - .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize())) + other.lowest_fee_to_peer_through_node + .cmp(&self.lowest_fee_to_peer_through_node) + .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize())) } } @@ -819,29 +780,23 @@ impl Router { pub fn new(our_pubkey: PublicKey, chain_monitor: Arc, logger: Arc) -> Router { let mut nodes = BTreeMap::new(); nodes.insert( - our_pubkey.clone(), - NodeInfo { - channels: Vec::new(), - lowest_inbound_channel_fee_base_msat: u32::max_value(), - lowest_inbound_channel_fee_proportional_millionths: u32::max_value(), - features: GlobalFeatures::new(), - last_update: 0, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + our_pubkey.clone(), + NodeInfo { channels: Vec::new(), + lowest_inbound_channel_fee_base_msat: u32::max_value(), + lowest_inbound_channel_fee_proportional_millionths: u32::max_value(), + features: GlobalFeatures::new(), + last_update: 0, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); - Router { - secp_ctx: Secp256k1::verification_only(), - network_map: RwLock::new(NetworkMap { - channels: BTreeMap::new(), - our_node_id: our_pubkey, - nodes, - }), - chain_monitor, - logger, - } + Router { secp_ctx: Secp256k1::verification_only(), + network_map: RwLock::new(NetworkMap { channels: BTreeMap::new(), + our_node_id: our_pubkey, + nodes }), + chain_monitor, + logger } } /// Dumps the entire network view of this Router to the logger provided in the constructor at @@ -899,30 +854,25 @@ impl Router { /// The fees on channels from us to next-hops are ignored (as they are assumed to all be /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat /// *is* checked as they may change based on the receiving node. - pub fn get_route( - &self, - target: &PublicKey, - first_hops: Option<&[channelmanager::ChannelDetails]>, - last_hops: &[RouteHint], - final_value_msat: u64, - final_cltv: u32, - ) -> Result { + pub fn get_route(&self, + target: &PublicKey, + first_hops: Option<&[channelmanager::ChannelDetails]>, + last_hops: &[RouteHint], + final_value_msat: u64, + final_cltv: u32) + -> Result { // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by // uptime/success in using a node in the past. let network = self.network_map.read().unwrap(); if *target == network.our_node_id { - return Err(LightningError { - err: "Cannot generate a route to ourselves", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Cannot generate a route to ourselves", + action: ErrorAction::IgnoreError }); } if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 { - return Err(LightningError { - err: "Cannot generate a route of more value than all existing satoshis", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Cannot generate a route of more value than all existing satoshis", + action: ErrorAction::IgnoreError }); } // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination @@ -931,14 +881,12 @@ impl Router { // to use as the A* heuristic beyond just the cost to get one node further than the current // one. - let dummy_directional_info = DummyDirectionalChannelInfo { - // used for first_hops routes - src_node_id: network.our_node_id.clone(), - cltv_expiry_delta: 0, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - }; + let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes + src_node_id: network.our_node_id.clone(), + cltv_expiry_delta: 0, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0 }; let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap? let mut dist = HashMap::with_capacity(network.nodes.len()); @@ -950,26 +898,19 @@ impl Router { }); if let Some(hops) = first_hops { for chan in hops { - let short_channel_id = chan - .short_channel_id - .expect("first_hops should be filled in with usable channels, not pending ones"); + let short_channel_id = chan.short_channel_id + .expect("first_hops should be filled in with usable channels, not pending ones"); if chan.remote_network_id == *target { - return Ok(Route { - hops: vec![RouteHop { - pubkey: chan.remote_network_id, - short_channel_id, - fee_msat: final_value_msat, - cltv_expiry_delta: final_cltv, - }], - }); + return Ok(Route { hops: vec![RouteHop { pubkey: chan.remote_network_id, + short_channel_id, + fee_msat: final_value_msat, + cltv_expiry_delta: final_cltv, }] }); } first_hop_targets.insert(chan.remote_network_id, short_channel_id); } if first_hop_targets.is_empty() { - return Err(LightningError { - err: "Cannot route when there are no outbound routes away from us", - action: ErrorAction::IgnoreError, - }); + return Err(LightningError { err: "Cannot route when there are no outbound routes away from us", + action: ErrorAction::IgnoreError }); } } @@ -1064,11 +1005,9 @@ impl Router { } } - while let Some(RouteGraphNode { - pubkey, - lowest_fee_to_node, - .. - }) = targets.pop() + while let Some(RouteGraphNode { pubkey, + lowest_fee_to_node, + .. }) = targets.pop() { if pubkey == network.our_node_id { let mut res = vec![dist.remove(&network.our_node_id).unwrap().3]; @@ -1101,10 +1040,8 @@ impl Router { } } - Err(LightningError { - err: "Failed to find a path to the given destination", - action: ErrorAction::IgnoreError, - }) + Err(LightningError { err: "Failed to find a path to the given destination", + action: ErrorAction::IgnoreError }) } } @@ -1141,10 +1078,8 @@ mod tests { .unwrap(), ); let logger: Arc = Arc::new(test_utils::TestLogger::new()); - let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new( - Network::Testnet, - Arc::clone(&logger), - )); + let chain_monitor = + Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger))); let router = Router::new(our_id, chain_monitor, Arc::clone(&logger)); // Build network from our_id to node8: @@ -1267,394 +1202,343 @@ mod tests { let mut network = router.network_map.write().unwrap(); network.nodes.insert( - node1.clone(), - NodeInfo { - channels: vec![ - NetworkMap::get_key(1, zero_hash.clone()), - NetworkMap::get_key(3, zero_hash.clone()), - ], - lowest_inbound_channel_fee_base_msat: 100, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node1.clone(), + NodeInfo { channels: vec![ + NetworkMap::get_key(1, zero_hash.clone()), + NetworkMap::get_key(3, zero_hash.clone()), + ], + lowest_inbound_channel_fee_base_msat: 100, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(1, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: our_id.clone(), - last_update: 0, - enabled: false, - cltv_expiry_delta: u16::max_value(), // This value should be ignored - htlc_minimum_msat: 0, - fee_base_msat: u32::max_value(), // This value should be ignored - fee_proportional_millionths: u32::max_value(), // This value should be ignored - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node1.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: 0, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(1, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: our_id.clone(), + last_update: 0, + enabled: false, + cltv_expiry_delta: u16::max_value(), // This value should be ignored + htlc_minimum_msat: 0, + fee_base_msat: u32::max_value(), // This value should be ignored + fee_proportional_millionths: + u32::max_value(), // This value should be ignored + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node1.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: 0, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.nodes.insert( - node2.clone(), - NodeInfo { - channels: vec![ - NetworkMap::get_key(2, zero_hash.clone()), - NetworkMap::get_key(4, zero_hash.clone()), - ], - lowest_inbound_channel_fee_base_msat: 0, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node2.clone(), + NodeInfo { channels: vec![ + NetworkMap::get_key(2, zero_hash.clone()), + NetworkMap::get_key(4, zero_hash.clone()), + ], + lowest_inbound_channel_fee_base_msat: 0, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(2, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: our_id.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: u16::max_value(), // This value should be ignored - htlc_minimum_msat: 0, - fee_base_msat: u32::max_value(), // This value should be ignored - fee_proportional_millionths: u32::max_value(), // This value should be ignored - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node2.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: 0, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(2, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: our_id.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: u16::max_value(), // This value should be ignored + htlc_minimum_msat: 0, + fee_base_msat: u32::max_value(), // This value should be ignored + fee_proportional_millionths: + u32::max_value(), // This value should be ignored + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node2.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: 0, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.nodes.insert( - node8.clone(), - NodeInfo { - channels: vec![ - NetworkMap::get_key(12, zero_hash.clone()), - NetworkMap::get_key(13, zero_hash.clone()), - ], - lowest_inbound_channel_fee_base_msat: 0, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node8.clone(), + NodeInfo { channels: vec![ + NetworkMap::get_key(12, zero_hash.clone()), + NetworkMap::get_key(13, zero_hash.clone()), + ], + lowest_inbound_channel_fee_base_msat: 0, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(12, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: our_id.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: u16::max_value(), // This value should be ignored - htlc_minimum_msat: 0, - fee_base_msat: u32::max_value(), // This value should be ignored - fee_proportional_millionths: u32::max_value(), // This value should be ignored - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node8.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: 0, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(12, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: our_id.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: u16::max_value(), // This value should be ignored + htlc_minimum_msat: 0, + fee_base_msat: u32::max_value(), // This value should be ignored + fee_proportional_millionths: + u32::max_value(), // This value should be ignored + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node8.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: 0, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.nodes.insert( - node3.clone(), - NodeInfo { - channels: vec![ - NetworkMap::get_key(3, zero_hash.clone()), - NetworkMap::get_key(4, zero_hash.clone()), - NetworkMap::get_key(13, zero_hash.clone()), - NetworkMap::get_key(5, zero_hash.clone()), - NetworkMap::get_key(6, zero_hash.clone()), - NetworkMap::get_key(7, zero_hash.clone()), - ], - lowest_inbound_channel_fee_base_msat: 0, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node3.clone(), + NodeInfo { channels: vec![ + NetworkMap::get_key(3, zero_hash.clone()), + NetworkMap::get_key(4, zero_hash.clone()), + NetworkMap::get_key(13, zero_hash.clone()), + NetworkMap::get_key(5, zero_hash.clone()), + NetworkMap::get_key(6, zero_hash.clone()), + NetworkMap::get_key(7, zero_hash.clone()), + ], + lowest_inbound_channel_fee_base_msat: 0, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(3, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node1.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (3 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node3.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (3 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 100, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(3, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node1.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (3 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node3.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (3 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 100, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(4, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node2.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (4 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 1000000, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node3.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (4 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(4, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node2.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (4 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 1000000, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node3.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (4 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(13, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node8.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (13 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 2000000, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node3.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (13 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(13, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node8.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (13 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 2000000, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node3.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (13 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.nodes.insert( - node4.clone(), - NodeInfo { - channels: vec![ - NetworkMap::get_key(5, zero_hash.clone()), - NetworkMap::get_key(11, zero_hash.clone()), - ], - lowest_inbound_channel_fee_base_msat: 0, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node4.clone(), + NodeInfo { channels: vec![ + NetworkMap::get_key(5, zero_hash.clone()), + NetworkMap::get_key(11, zero_hash.clone()), + ], + lowest_inbound_channel_fee_base_msat: 0, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(5, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node3.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (5 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 100, - fee_proportional_millionths: 0, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node4.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (5 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(5, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node3.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (5 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 100, + fee_proportional_millionths: 0, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node4.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (5 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.nodes.insert( - node5.clone(), - NodeInfo { - channels: vec![ - NetworkMap::get_key(6, zero_hash.clone()), - NetworkMap::get_key(11, zero_hash.clone()), - ], - lowest_inbound_channel_fee_base_msat: 0, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node5.clone(), + NodeInfo { channels: vec![ + NetworkMap::get_key(6, zero_hash.clone()), + NetworkMap::get_key(11, zero_hash.clone()), + ], + lowest_inbound_channel_fee_base_msat: 0, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(6, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node3.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (6 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node5.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (6 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(6, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node3.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (6 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node5.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (6 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(11, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node5.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (11 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node4.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (11 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(11, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node5.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (11 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node4.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (11 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); network.nodes.insert( - node6.clone(), - NodeInfo { - channels: vec![NetworkMap::get_key(7, zero_hash.clone())], - lowest_inbound_channel_fee_base_msat: 0, - lowest_inbound_channel_fee_proportional_millionths: 0, - features: GlobalFeatures::new(), - last_update: 1, - rgb: [0; 3], - alias: [0; 32], - addresses: Vec::new(), - announcement_message: None, - }, + node6.clone(), + NodeInfo { channels: vec![NetworkMap::get_key(7, zero_hash.clone())], + lowest_inbound_channel_fee_base_msat: 0, + lowest_inbound_channel_fee_proportional_millionths: 0, + features: GlobalFeatures::new(), + last_update: 1, + rgb: [0; 3], + alias: [0; 32], + addresses: Vec::new(), + announcement_message: None, }, ); network.channels.insert( - NetworkMap::get_key(7, zero_hash.clone()), - ChannelInfo { - features: GlobalFeatures::new(), - one_to_two: DirectionalChannelInfo { - src_node_id: node3.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (7 << 8) | 1, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 1000000, - last_update_message: None, - }, - two_to_one: DirectionalChannelInfo { - src_node_id: node6.clone(), - last_update: 0, - enabled: true, - cltv_expiry_delta: (7 << 8) | 2, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - last_update_message: None, - }, - announcement_message: None, - }, + NetworkMap::get_key(7, zero_hash.clone()), + ChannelInfo { features: GlobalFeatures::new(), + one_to_two: + DirectionalChannelInfo { src_node_id: node3.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (7 << 8) | 1, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 1000000, + last_update_message: None, }, + two_to_one: + DirectionalChannelInfo { src_node_id: node6.clone(), + last_update: 0, + enabled: true, + cltv_expiry_delta: (7 << 8) | 2, + htlc_minimum_msat: 0, + fee_base_msat: 0, + fee_proportional_millionths: 0, + last_update_message: None, }, + announcement_message: None, }, ); } @@ -1697,19 +1581,16 @@ mod tests { { // If we specify a channel to node8, that overrides our local channel view and that gets used - let our_chans = vec![channelmanager::ChannelDetails { - channel_id: [0; 32], - short_channel_id: Some(42), - remote_network_id: node8.clone(), - channel_value_satoshis: 0, - user_id: 0, - outbound_capacity_msat: 0, - inbound_capacity_msat: 0, - is_live: true, - }]; - let route = router - .get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42) - .unwrap(); + let our_chans = vec![channelmanager::ChannelDetails { channel_id: [0; 32], + short_channel_id: Some(42), + remote_network_id: node8.clone(), + channel_value_satoshis: 0, + user_id: 0, + outbound_capacity_msat: 0, + inbound_capacity_msat: 0, + is_live: true }]; + let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42) + .unwrap(); assert_eq!(route.hops.len(), 2); assert_eq!(route.hops[0].pubkey, node8); @@ -1724,30 +1605,24 @@ mod tests { } let mut last_hops = vec![ - RouteHint { - src_node_id: node4.clone(), - short_channel_id: 8, - fee_base_msat: 0, - fee_proportional_millionths: 0, - cltv_expiry_delta: (8 << 8) | 1, - htlc_minimum_msat: 0, - }, - RouteHint { - src_node_id: node5.clone(), - short_channel_id: 9, - fee_base_msat: 1001, - fee_proportional_millionths: 0, - cltv_expiry_delta: (9 << 8) | 1, - htlc_minimum_msat: 0, - }, - RouteHint { - src_node_id: node6.clone(), - short_channel_id: 10, - fee_base_msat: 0, - fee_proportional_millionths: 0, - cltv_expiry_delta: (10 << 8) | 1, - htlc_minimum_msat: 0, - }, + RouteHint { src_node_id: node4.clone(), + short_channel_id: 8, + fee_base_msat: 0, + fee_proportional_millionths: 0, + cltv_expiry_delta: (8 << 8) | 1, + htlc_minimum_msat: 0, }, + RouteHint { src_node_id: node5.clone(), + short_channel_id: 9, + fee_base_msat: 1001, + fee_proportional_millionths: 0, + cltv_expiry_delta: (9 << 8) | 1, + htlc_minimum_msat: 0, }, + RouteHint { src_node_id: node6.clone(), + short_channel_id: 10, + fee_base_msat: 0, + fee_proportional_millionths: 0, + cltv_expiry_delta: (10 << 8) | 1, + htlc_minimum_msat: 0, }, ]; { @@ -1783,16 +1658,14 @@ mod tests { { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect - let our_chans = vec![channelmanager::ChannelDetails { - channel_id: [0; 32], - short_channel_id: Some(42), - remote_network_id: node4.clone(), - channel_value_satoshis: 0, - user_id: 0, - outbound_capacity_msat: 0, - inbound_capacity_msat: 0, - is_live: true, - }]; + let our_chans = vec![channelmanager::ChannelDetails { channel_id: [0; 32], + short_channel_id: Some(42), + remote_network_id: node4.clone(), + channel_value_satoshis: 0, + user_id: 0, + outbound_capacity_msat: 0, + inbound_capacity_msat: 0, + is_live: true }]; let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap(); assert_eq!(route.hops.len(), 2); diff --git a/lightning/src/util/chacha20.rs b/lightning/src/util/chacha20.rs index 5c0a47e9cf3..fc0812ac69e 100644 --- a/lightning/src/util/chacha20.rs +++ b/lightning/src/util/chacha20.rs @@ -21,10 +21,10 @@ mod real_chacha { type Output = u32x4; fn add(self, rhs: u32x4) -> u32x4 { u32x4( - self.0.wrapping_add(rhs.0), - self.1.wrapping_add(rhs.1), - self.2.wrapping_add(rhs.2), - self.3.wrapping_add(rhs.3), + self.0.wrapping_add(rhs.0), + self.1.wrapping_add(rhs.1), + self.2.wrapping_add(rhs.2), + self.3.wrapping_add(rhs.3), ) } } @@ -32,10 +32,10 @@ mod real_chacha { type Output = u32x4; fn sub(self, rhs: u32x4) -> u32x4 { u32x4( - self.0.wrapping_sub(rhs.0), - self.1.wrapping_sub(rhs.1), - self.2.wrapping_sub(rhs.2), - self.3.wrapping_sub(rhs.3), + self.0.wrapping_sub(rhs.0), + self.1.wrapping_sub(rhs.1), + self.2.wrapping_sub(rhs.2), + self.3.wrapping_sub(rhs.3), ) } } @@ -128,11 +128,9 @@ mod real_chacha { assert!(key.len() == 16 || key.len() == 32); assert!(nonce.len() == 8 || nonce.len() == 12); - ChaCha20 { - state: ChaCha20::expand(key, nonce), - output: [0u8; 64], - offset: 64, - } + ChaCha20 { state: ChaCha20::expand(key, nonce), + output: [0u8; 64], + offset: 64 } } fn expand(key: &[u8], nonce: &[u8]) -> ChaChaState { @@ -141,52 +139,50 @@ mod real_chacha { 32 => b"expand 32-byte k", _ => unreachable!(), }; - ChaChaState { - a: u32x4( - slice_to_le32(&constant[0..4]), - slice_to_le32(&constant[4..8]), - slice_to_le32(&constant[8..12]), - slice_to_le32(&constant[12..16]), - ), - b: u32x4( - slice_to_le32(&key[0..4]), - slice_to_le32(&key[4..8]), - slice_to_le32(&key[8..12]), - slice_to_le32(&key[12..16]), - ), - c: if key.len() == 16 { - u32x4( - slice_to_le32(&key[0..4]), - slice_to_le32(&key[4..8]), - slice_to_le32(&key[8..12]), - slice_to_le32(&key[12..16]), - ) - } else { - u32x4( - slice_to_le32(&key[16..20]), - slice_to_le32(&key[20..24]), - slice_to_le32(&key[24..28]), - slice_to_le32(&key[28..32]), - ) - }, - d: if nonce.len() == 16 { - u32x4( - slice_to_le32(&nonce[0..4]), - slice_to_le32(&nonce[4..8]), - slice_to_le32(&nonce[8..12]), - slice_to_le32(&nonce[12..16]), - ) - } else if nonce.len() == 12 { - u32x4( - 0, - slice_to_le32(&nonce[0..4]), - slice_to_le32(&nonce[4..8]), - slice_to_le32(&nonce[8..12]), - ) - } else { - u32x4(0, 0, slice_to_le32(&nonce[0..4]), slice_to_le32(&nonce[4..8])) - }, - } + ChaChaState { a: u32x4( + slice_to_le32(&constant[0..4]), + slice_to_le32(&constant[4..8]), + slice_to_le32(&constant[8..12]), + slice_to_le32(&constant[12..16]), + ), + b: u32x4( + slice_to_le32(&key[0..4]), + slice_to_le32(&key[4..8]), + slice_to_le32(&key[8..12]), + slice_to_le32(&key[12..16]), + ), + c: if key.len() == 16 { + u32x4( + slice_to_le32(&key[0..4]), + slice_to_le32(&key[4..8]), + slice_to_le32(&key[8..12]), + slice_to_le32(&key[12..16]), + ) + } else { + u32x4( + slice_to_le32(&key[16..20]), + slice_to_le32(&key[20..24]), + slice_to_le32(&key[24..28]), + slice_to_le32(&key[28..32]), + ) + }, + d: if nonce.len() == 16 { + u32x4( + slice_to_le32(&nonce[0..4]), + slice_to_le32(&nonce[4..8]), + slice_to_le32(&nonce[8..12]), + slice_to_le32(&nonce[12..16]), + ) + } else if nonce.len() == 12 { + u32x4( + 0, + slice_to_le32(&nonce[0..4]), + slice_to_le32(&nonce[4..8]), + slice_to_le32(&nonce[8..12]), + ) + } else { + u32x4(0, 0, slice_to_le32(&nonce[0..4]), slice_to_le32(&nonce[4..8])) + } } } // put the the next 64 keystream bytes into self.output @@ -280,83 +276,72 @@ mod test { }; // taken from http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04 let test_vectors = vec![ - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - keystream: vec![ - 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, - 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, - 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, - 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86, - ], - }, - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - keystream: vec![ - 0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96, 0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96, - 0xeb, 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60, 0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41, - 0xbb, 0xe2, 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2, 0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c, - 0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, 0xea, 0x81, 0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63, - ], - }, - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], - keystream: vec![ - 0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5, 0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a, - 0x0b, 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13, 0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31, - 0xe8, 0x5a, 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45, 0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b, - 0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, 0x43, 0x3e, 0x44, 0x5f, 0x41, 0xe3, - ], - }, - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ], - nonce: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - keystream: vec![ - 0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb, 0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80, - 0x09, 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac, 0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32, - 0x11, 0x1e, 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c, 0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54, - 0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, 0x6e, 0x7d, 0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b, - ], - }, - TestVector { - key: [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - ], - nonce: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07], - keystream: vec![ - 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, - 0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, - 0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, - 0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1, 0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a, - 0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94, 0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66, - 0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58, 0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd, - 0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56, 0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e, - 0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e, 0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7, - 0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15, 0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3, - 0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a, 0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25, - 0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5, 0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69, - 0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4, 0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7, - 0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79, 0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a, - 0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a, 0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2, - 0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a, 0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09, - 0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a, 0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9, - ], - }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + keystream: vec![ + 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, + 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, + 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, + 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86, + ], }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + keystream: vec![ + 0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96, 0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96, 0xeb, 0x4f, + 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60, 0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41, 0xbb, 0xe2, 0xa0, 0xb6, + 0xea, 0x75, 0x66, 0xd2, 0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c, 0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, + 0xea, 0x81, 0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63, + ], }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], + keystream: vec![ + 0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5, 0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a, 0x0b, 0x49, + 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13, 0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31, 0xe8, 0x5a, 0x05, 0x02, + 0x78, 0xa7, 0x08, 0x45, 0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b, 0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, + 0x43, 0x3e, 0x44, 0x5f, 0x41, 0xe3, + ], }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + nonce: [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + keystream: vec![ + 0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb, 0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80, 0x09, 0x63, + 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac, 0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32, 0x11, 0x1e, 0x4c, 0xaf, + 0x23, 0x7e, 0xe5, 0x3c, 0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54, 0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, + 0x6e, 0x7d, 0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b, + ], }, + TestVector { key: [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, + 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + ], + nonce: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07], + keystream: vec![ + 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, 0x7f, 0x57, + 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, 0x34, 0xa4, 0x54, 0x7b, + 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, 0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, + 0x53, 0xf1, 0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a, 0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94, + 0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66, 0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58, 0x89, 0xfb, + 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd, 0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56, 0x3e, 0xb9, 0xb3, 0xa4, + 0xa4, 0x72, 0xf8, 0x2e, 0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e, 0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, + 0x31, 0xc7, 0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15, 0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3, + 0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a, 0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25, 0xd3, 0xce, + 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5, 0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69, 0x59, 0x66, 0x09, 0x96, + 0x54, 0x6c, 0xc9, 0xc4, 0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7, 0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, + 0x39, 0x79, 0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a, 0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a, + 0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2, 0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a, 0xd0, 0xf9, + 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09, 0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a, 0x6d, 0xeb, 0x3a, 0xb7, + 0x8f, 0xab, 0x78, 0xc9, + ], }, ]; for tv in test_vectors.iter() { @@ -376,85 +361,76 @@ mod test { keystream: Vec, }; // taken from http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04 - let test_vectors = vec![ - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - keystream: vec![ - 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, - 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, - 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, - 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86, - ], - }, - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - keystream: vec![ - 0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96, 0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96, - 0xeb, 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60, 0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41, - 0xbb, 0xe2, 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2, 0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c, - 0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, 0xea, 0x81, 0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63, - ], - }, - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], - keystream: vec![ - 0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5, 0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a, - 0x0b, 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13, 0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31, - 0xe8, 0x5a, 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45, 0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b, - 0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, 0x43, 0x3e, 0x44, 0x5f, 0x41, 0xe3, - ], - }, - TestVector { - key: [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - keystream: vec![ - 0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb, 0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80, - 0x09, 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac, 0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32, - 0x11, 0x1e, 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c, 0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54, - 0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, 0x6e, 0x7d, 0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b, - ], - }, - TestVector { - key: [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - ], - nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07], - keystream: vec![ - 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, - 0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, - 0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, - 0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1, 0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a, - 0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94, 0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66, - 0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58, 0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd, - 0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56, 0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e, - 0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e, 0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7, - 0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15, 0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3, - 0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a, 0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25, - 0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5, 0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69, - 0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4, 0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7, - 0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79, 0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a, - 0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a, 0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2, - 0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a, 0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09, - 0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a, 0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9, - ], - }, - ]; + let test_vectors = + vec![ + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + keystream: vec![ + 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, + 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, + 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, + 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86, + ], }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + keystream: vec![ + 0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96, 0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96, 0xeb, + 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60, 0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41, 0xbb, 0xe2, + 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2, 0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c, 0x53, 0xd7, 0x92, + 0xb1, 0xc4, 0x3f, 0xea, 0x81, 0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63, + ], }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], + keystream: vec![ + 0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5, 0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a, 0x0b, + 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13, 0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31, 0xe8, 0x5a, + 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45, 0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b, 0x52, 0x77, 0x06, + 0x2e, 0xb7, 0xa0, 0x43, 0x3e, 0x44, 0x5f, 0x41, 0xe3, + ], }, + TestVector { key: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + keystream: vec![ + 0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb, 0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80, 0x09, + 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac, 0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32, 0x11, 0x1e, + 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c, 0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54, 0x5d, 0xdc, 0x49, + 0x7a, 0x0b, 0x46, 0x6e, 0x7d, 0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b, + ], }, + TestVector { key: [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + ], + nonce: [0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07], + keystream: vec![ + 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, 0x7f, + 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, 0x34, 0xa4, + 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, 0x05, 0xd3, 0xbe, + 0x59, 0xea, 0x1c, 0x53, 0xf1, 0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a, 0x38, 0x00, 0x8b, 0x9a, + 0x26, 0xbc, 0x35, 0x94, 0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66, 0x89, 0xde, 0x95, 0x26, 0x49, + 0x86, 0xd9, 0x58, 0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd, 0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, + 0xbe, 0x56, 0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e, 0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, + 0x2e, 0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7, 0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15, + 0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3, 0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a, 0x97, + 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25, 0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5, 0x07, 0xb1, + 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69, 0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4, 0xa6, 0xea, 0xfd, + 0xc7, 0x77, 0xc0, 0x40, 0xd7, 0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79, 0xe5, 0xc5, 0x36, 0x0c, + 0x33, 0x17, 0x16, 0x6a, 0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a, 0x94, 0xdf, 0x76, 0x28, 0xfe, + 0x4e, 0xaa, 0xf2, 0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a, 0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, + 0x54, 0x09, 0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a, 0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, + 0xc9, + ], }, + ]; for tv in test_vectors.iter() { let mut c = ChaCha20::new(&tv.key, &tv.nonce); diff --git a/lightning/src/util/chacha20poly1305rfc.rs b/lightning/src/util/chacha20poly1305rfc.rs index 8639f4bdb3a..8af2cdc83e8 100644 --- a/lightning/src/util/chacha20poly1305rfc.rs +++ b/lightning/src/util/chacha20poly1305rfc.rs @@ -50,13 +50,11 @@ mod real_chachapoly { mac.input(aad); ChaCha20Poly1305RFC::pad_mac_16(&mut mac, aad.len()); - ChaCha20Poly1305RFC { - cipher, - mac, - finished: false, - data_len: 0, - aad_len: aad.len() as u64, - } + ChaCha20Poly1305RFC { cipher, + mac, + finished: false, + data_len: 0, + aad_len: aad.len() as u64 } } pub fn encrypt(&mut self, input: &[u8], output: &mut [u8], out_tag: &mut [u8]) { diff --git a/lightning/src/util/config.rs b/lightning/src/util/config.rs index 13fd8bf059e..8f66fc30b81 100644 --- a/lightning/src/util/config.rs +++ b/lightning/src/util/config.rs @@ -19,11 +19,9 @@ pub struct UserConfig { impl Default for UserConfig { fn default() -> Self { - UserConfig { - own_channel_config: ChannelHandshakeConfig::default(), - peer_channel_config_limits: ChannelHandshakeLimits::default(), - channel_options: ChannelConfig::default(), - } + UserConfig { own_channel_config: ChannelHandshakeConfig::default(), + peer_channel_config_limits: ChannelHandshakeLimits::default(), + channel_options: ChannelConfig::default() } } } @@ -55,10 +53,8 @@ pub struct ChannelHandshakeConfig { impl Default for ChannelHandshakeConfig { fn default() -> ChannelHandshakeConfig { - ChannelHandshakeConfig { - minimum_depth: 6, - our_to_self_delay: BREAKDOWN_TIMEOUT, - } + ChannelHandshakeConfig { minimum_depth: 6, + our_to_self_delay: BREAKDOWN_TIMEOUT } } } @@ -142,18 +138,16 @@ pub struct ChannelHandshakeLimits { impl Default for ChannelHandshakeLimits { fn default() -> Self { - ChannelHandshakeLimits { - min_funding_satoshis: 0, - max_htlc_minimum_msat: ::max_value(), - min_max_htlc_value_in_flight_msat: 0, - max_channel_reserve_satoshis: ::max_value(), - min_max_accepted_htlcs: 0, - min_dust_limit_satoshis: 546, - max_dust_limit_satoshis: ::max_value(), - max_minimum_depth: 144, - force_announced_channel_preference: true, - their_to_self_delay: MAX_LOCAL_BREAKDOWN_TIMEOUT, - } + ChannelHandshakeLimits { min_funding_satoshis: 0, + max_htlc_minimum_msat: ::max_value(), + min_max_htlc_value_in_flight_msat: 0, + max_channel_reserve_satoshis: ::max_value(), + min_max_accepted_htlcs: 0, + min_dust_limit_satoshis: 546, + max_dust_limit_satoshis: ::max_value(), + max_minimum_depth: 144, + force_announced_channel_preference: true, + their_to_self_delay: MAX_LOCAL_BREAKDOWN_TIMEOUT } } } @@ -196,11 +190,9 @@ pub struct ChannelConfig { impl Default for ChannelConfig { /// Provides sane defaults for most configurations (but with zero relay fees!). fn default() -> Self { - ChannelConfig { - fee_proportional_millionths: 0, - announced_channel: false, - commit_upfront_shutdown_pubkey: true, - } + ChannelConfig { fee_proportional_millionths: 0, + announced_channel: false, + commit_upfront_shutdown_pubkey: true } } } diff --git a/lightning/src/util/enforcing_trait_impls.rs b/lightning/src/util/enforcing_trait_impls.rs index 0746c041a73..80590830f16 100644 --- a/lightning/src/util/enforcing_trait_impls.rs +++ b/lightning/src/util/enforcing_trait_impls.rs @@ -21,10 +21,8 @@ pub struct EnforcingChannelKeys { impl EnforcingChannelKeys { pub fn new(inner: InMemoryChannelKeys) -> Self { - Self { - inner, - commitment_number_obscure_and_last: Mutex::new((None, 0)), - } + Self { inner, + commitment_number_obscure_and_last: Mutex::new((None, 0)) } } } impl ChannelKeys for EnforcingChannelKeys { @@ -35,22 +33,21 @@ impl ChannelKeys for EnforcingChannelKeys { fn htlc_base_key(&self) -> &SecretKey { self.inner.htlc_base_key() } fn commitment_seed(&self) -> &[u8; 32] { self.inner.commitment_seed() } - fn sign_remote_commitment( - &self, - channel_value_satoshis: u64, - channel_funding_script: &Script, - feerate_per_kw: u64, - commitment_tx: &Transaction, - keys: &TxCreationKeys, - htlcs: &[&HTLCOutputInCommitment], - to_self_delay: u16, - secp_ctx: &Secp256k1, - ) -> Result<(Signature, Vec), ()> { + fn sign_remote_commitment(&self, + channel_value_satoshis: u64, + channel_funding_script: &Script, + feerate_per_kw: u64, + commitment_tx: &Transaction, + keys: &TxCreationKeys, + htlcs: &[&HTLCOutputInCommitment], + to_self_delay: u16, + secp_ctx: &Secp256k1) + -> Result<(Signature, Vec), ()> { if commitment_tx.input.len() != 1 { panic!(); } let obscured_commitment_transaction_number = (commitment_tx.lock_time & 0xffffff) as u64 - | ((commitment_tx.input[0].sequence as u64 & 0xffffff) << 3 * 8); + | ((commitment_tx.input[0].sequence as u64 & 0xffffff) << 3 * 8); { let mut commitment_data = self.commitment_number_obscure_and_last.lock().unwrap(); @@ -62,44 +59,40 @@ impl ChannelKeys for EnforcingChannelKeys { commitment_data.1 = cmp::max(commitment_number, commitment_data.1) } - Ok(self - .inner - .sign_remote_commitment( - channel_value_satoshis, - channel_funding_script, - feerate_per_kw, - commitment_tx, - keys, - htlcs, - to_self_delay, - secp_ctx, - ) - .unwrap()) + Ok(self.inner + .sign_remote_commitment( + channel_value_satoshis, + channel_funding_script, + feerate_per_kw, + commitment_tx, + keys, + htlcs, + to_self_delay, + secp_ctx, + ) + .unwrap()) } - fn sign_closing_transaction( - &self, - channel_value_satoshis: u64, - channel_funding_redeemscript: &Script, - closing_tx: &Transaction, - secp_ctx: &Secp256k1, - ) -> Result { - Ok(self - .inner - .sign_closing_transaction( - channel_value_satoshis, - channel_funding_redeemscript, - closing_tx, - secp_ctx, - ) - .unwrap()) + fn sign_closing_transaction(&self, + channel_value_satoshis: u64, + channel_funding_redeemscript: &Script, + closing_tx: &Transaction, + secp_ctx: &Secp256k1) + -> Result { + Ok(self.inner + .sign_closing_transaction( + channel_value_satoshis, + channel_funding_redeemscript, + closing_tx, + secp_ctx, + ) + .unwrap()) } - fn sign_channel_announcement( - &self, - msg: &msgs::UnsignedChannelAnnouncement, - secp_ctx: &Secp256k1, - ) -> Result { + fn sign_channel_announcement(&self, + msg: &msgs::UnsignedChannelAnnouncement, + secp_ctx: &Secp256k1) + -> Result { self.inner.sign_channel_announcement(msg, secp_ctx) } } diff --git a/lightning/src/util/logger.rs b/lightning/src/util/logger.rs index b3cb18cab03..a0b81e3f330 100644 --- a/lightning/src/util/logger.rs +++ b/lightning/src/util/logger.rs @@ -89,13 +89,11 @@ impl<'a> Record<'a> { /// Returns a new Record. #[inline] pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'a str, file: &'a str, line: u32) -> Record<'a> { - Record { - level, - args, - module_path, - file, - line, - } + Record { level, + args, + module_path, + file, + line } } } diff --git a/lightning/src/util/macro_logger.rs b/lightning/src/util/macro_logger.rs index 92ddc5b82bc..c36459e451c 100644 --- a/lightning/src/util/macro_logger.rs +++ b/lightning/src/util/macro_logger.rs @@ -76,12 +76,12 @@ impl<'a> std::fmt::Display for DebugRoute<'a> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { for h in self.0.hops.iter() { write!( - f, - "node_id: {}, short_channel_id: {}, fee_msat: {}, cltv_expiry_delta: {}\n", - log_pubkey!(h.pubkey), - h.short_channel_id, - h.fee_msat, - h.cltv_expiry_delta + f, + "node_id: {}, short_channel_id: {}, fee_msat: {}, cltv_expiry_delta: {}\n", + log_pubkey!(h.pubkey), + h.short_channel_id, + h.fee_msat, + h.cltv_expiry_delta )?; } Ok(()) @@ -97,21 +97,21 @@ pub(crate) struct DebugTx<'a>(pub &'a Transaction); impl<'a> std::fmt::Display for DebugTx<'a> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { if self.0.input.len() == 1 - && self.0.input[0].witness.last().unwrap().len() == 71 - && (self.0.input[0].sequence >> 8 * 3) as u8 == 0x80 + && self.0.input[0].witness.last().unwrap().len() == 71 + && (self.0.input[0].sequence >> 8 * 3) as u8 == 0x80 { write!(f, "commitment tx")?; } else if self.0.input.len() == 1 && self.0.input[0].witness.last().unwrap().len() == 71 { write!(f, "closing tx")?; } else if self.0.input.len() == 1 - && self.0.input[0].witness.last().unwrap().len() == 133 - && self.0.input[0].witness.len() == 5 + && self.0.input[0].witness.last().unwrap().len() == 133 + && self.0.input[0].witness.len() == 5 { write!(f, "HTLC-timeout tx")?; } else if self.0.input.len() == 1 - && (self.0.input[0].witness.last().unwrap().len() == 138 - || self.0.input[0].witness.last().unwrap().len() == 139) - && self.0.input[0].witness.len() == 5 + && (self.0.input[0].witness.last().unwrap().len() == 138 + || self.0.input[0].witness.last().unwrap().len() == 139) + && self.0.input[0].witness.len() == 5 { write!(f, "HTLC-success tx")?; } else { diff --git a/lightning/src/util/poly1305.rs b/lightning/src/util/poly1305.rs index e9f0d886007..88978c8ac30 100644 --- a/lightning/src/util/poly1305.rs +++ b/lightning/src/util/poly1305.rs @@ -23,14 +23,12 @@ pub struct Poly1305 { impl Poly1305 { pub fn new(key: &[u8]) -> Poly1305 { assert!(key.len() == 32); - let mut poly = Poly1305 { - r: [0u32; 5], - h: [0u32; 5], - pad: [0u32; 4], - leftover: 0, - buffer: [0u8; 16], - finalized: false, - }; + let mut poly = Poly1305 { r: [0u32; 5], + h: [0u32; 5], + pad: [0u32; 4], + leftover: 0, + buffer: [0u8; 16], + finalized: false }; // r &= 0xffffffc0ffffffc0ffffffc0fffffff poly.r[0] = (slice_to_le32(&key[0..4])) & 0x3ffffff; @@ -227,24 +225,23 @@ mod test { #[test] fn test_nacl_vector() { let key = [ - 0xee, 0xa6, 0xa7, 0x25, 0x1c, 0x1e, 0x72, 0x91, 0x6d, 0x11, 0xc2, 0xcb, 0x21, 0x4d, 0x3c, 0x25, 0x25, 0x39, - 0x12, 0x1d, 0x8e, 0x23, 0x4e, 0x65, 0x2d, 0x65, 0x1f, 0xa4, 0xc8, 0xcf, 0xf8, 0x80, + 0xee, 0xa6, 0xa7, 0x25, 0x1c, 0x1e, 0x72, 0x91, 0x6d, 0x11, 0xc2, 0xcb, 0x21, 0x4d, 0x3c, 0x25, + 0x25, 0x39, 0x12, 0x1d, 0x8e, 0x23, 0x4e, 0x65, 0x2d, 0x65, 0x1f, 0xa4, 0xc8, 0xcf, 0xf8, 0x80, ]; let msg = [ - 0x8e, 0x99, 0x3b, 0x9f, 0x48, 0x68, 0x12, 0x73, 0xc2, 0x96, 0x50, 0xba, 0x32, 0xfc, 0x76, 0xce, 0x48, 0x33, - 0x2e, 0xa7, 0x16, 0x4d, 0x96, 0xa4, 0x47, 0x6f, 0xb8, 0xc5, 0x31, 0xa1, 0x18, 0x6a, 0xc0, 0xdf, 0xc1, 0x7c, - 0x98, 0xdc, 0xe8, 0x7b, 0x4d, 0xa7, 0xf0, 0x11, 0xec, 0x48, 0xc9, 0x72, 0x71, 0xd2, 0xc2, 0x0f, 0x9b, 0x92, - 0x8f, 0xe2, 0x27, 0x0d, 0x6f, 0xb8, 0x63, 0xd5, 0x17, 0x38, 0xb4, 0x8e, 0xee, 0xe3, 0x14, 0xa7, 0xcc, 0x8a, - 0xb9, 0x32, 0x16, 0x45, 0x48, 0xe5, 0x26, 0xae, 0x90, 0x22, 0x43, 0x68, 0x51, 0x7a, 0xcf, 0xea, 0xbd, 0x6b, - 0xb3, 0x73, 0x2b, 0xc0, 0xe9, 0xda, 0x99, 0x83, 0x2b, 0x61, 0xca, 0x01, 0xb6, 0xde, 0x56, 0x24, 0x4a, 0x9e, - 0x88, 0xd5, 0xf9, 0xb3, 0x79, 0x73, 0xf6, 0x22, 0xa4, 0x3d, 0x14, 0xa6, 0x59, 0x9b, 0x1f, 0x65, 0x4c, 0xb4, - 0x5a, 0x74, 0xe3, 0x55, 0xa5, + 0x8e, 0x99, 0x3b, 0x9f, 0x48, 0x68, 0x12, 0x73, 0xc2, 0x96, 0x50, 0xba, 0x32, 0xfc, 0x76, 0xce, + 0x48, 0x33, 0x2e, 0xa7, 0x16, 0x4d, 0x96, 0xa4, 0x47, 0x6f, 0xb8, 0xc5, 0x31, 0xa1, 0x18, 0x6a, + 0xc0, 0xdf, 0xc1, 0x7c, 0x98, 0xdc, 0xe8, 0x7b, 0x4d, 0xa7, 0xf0, 0x11, 0xec, 0x48, 0xc9, 0x72, + 0x71, 0xd2, 0xc2, 0x0f, 0x9b, 0x92, 0x8f, 0xe2, 0x27, 0x0d, 0x6f, 0xb8, 0x63, 0xd5, 0x17, 0x38, + 0xb4, 0x8e, 0xee, 0xe3, 0x14, 0xa7, 0xcc, 0x8a, 0xb9, 0x32, 0x16, 0x45, 0x48, 0xe5, 0x26, 0xae, + 0x90, 0x22, 0x43, 0x68, 0x51, 0x7a, 0xcf, 0xea, 0xbd, 0x6b, 0xb3, 0x73, 0x2b, 0xc0, 0xe9, 0xda, + 0x99, 0x83, 0x2b, 0x61, 0xca, 0x01, 0xb6, 0xde, 0x56, 0x24, 0x4a, 0x9e, 0x88, 0xd5, 0xf9, 0xb3, + 0x79, 0x73, 0xf6, 0x22, 0xa4, 0x3d, 0x14, 0xa6, 0x59, 0x9b, 0x1f, 0x65, 0x4c, 0xb4, 0x5a, 0x74, + 0xe3, 0x55, 0xa5, ]; - let expected = [ - 0xf3, 0xff, 0xc7, 0x70, 0x3f, 0x94, 0x00, 0xe5, 0x2a, 0x7d, 0xfb, 0x4b, 0x3d, 0x33, 0x05, 0xd9, - ]; + let expected = [0xf3, 0xff, 0xc7, 0x70, 0x3f, 0x94, 0x00, 0xe5, 0x2a, 0x7d, 0xfb, 0x4b, 0x3d, 0x33, 0x05, 0xd9]; let mut mac = [0u8; 16]; poly1305(&key, &msg, &mut mac); @@ -269,30 +266,27 @@ mod test { #[test] fn donna_self_test() { let wrap_key = [ - 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, ]; - let wrap_msg = [ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - ]; + let wrap_msg = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; - let wrap_mac = [ - 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ]; + let wrap_mac = [0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; let mut mac = [0u8; 16]; poly1305(&wrap_key, &wrap_msg, &mut mac); assert_eq!(&mac[..], &wrap_mac[..]); let total_key = [ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, + 0x00, 0x00, ]; - let total_mac = [ - 0x64, 0xaf, 0xe2, 0xe8, 0xd6, 0xad, 0x7b, 0xbd, 0xd2, 0x87, 0xf9, 0x7c, 0x44, 0x62, 0x3d, 0x39, - ]; + let total_mac = + [0x64, 0xaf, 0xe2, 0xe8, 0xd6, 0xad, 0x7b, 0xbd, 0xd2, 0x87, 0xf9, 0x7c, 0x44, 0x62, 0x3d, 0x39]; let mut tpoly = Poly1305::new(&total_key); for i in 0..256 { @@ -311,17 +305,13 @@ mod test { // from http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04 let key = b"this is 32-byte key for Poly1305"; let msg = [0u8; 32]; - let expected = [ - 0x49, 0xec, 0x78, 0x09, 0x0e, 0x48, 0x1e, 0xc6, 0xc2, 0x6b, 0x33, 0xb9, 0x1c, 0xcc, 0x03, 0x07, - ]; + let expected = [0x49, 0xec, 0x78, 0x09, 0x0e, 0x48, 0x1e, 0xc6, 0xc2, 0x6b, 0x33, 0xb9, 0x1c, 0xcc, 0x03, 0x07]; let mut mac = [0u8; 16]; poly1305(key, &msg, &mut mac); assert_eq!(&mac[..], &expected[..]); let msg = b"Hello world!"; - let expected = [ - 0xa6, 0xf7, 0x45, 0x00, 0x8f, 0x81, 0xc9, 0x16, 0xa2, 0x0d, 0xcc, 0x74, 0xee, 0xf2, 0xb2, 0xf0, - ]; + let expected = [0xa6, 0xf7, 0x45, 0x00, 0x8f, 0x81, 0xc9, 0x16, 0xa2, 0x0d, 0xcc, 0x74, 0xee, 0xf2, 0xb2, 0xf0]; poly1305(key, msg, &mut mac); assert_eq!(&mac[..], &expected[..]); } diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index 05349738d97..5ff89f62a74 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -89,9 +89,8 @@ pub trait Writeable { /// A trait that various rust-lightning types implement allowing them to be read in from a Read pub trait Readable -where - Self: Sized, - R: Read, + where Self: Sized, + R: Read { /// Reads a Self in from the given Read fn read(reader: &mut R) -> Result; @@ -100,9 +99,8 @@ where /// A trait that various higher-level rust-lightning types implement allowing them to be read in /// from a Read given some additional set of arguments which is required to deserialize. pub trait ReadableArgs -where - Self: Sized, - R: Read, + where Self: Sized, + R: Read { /// Reads a Self in from the given Read fn read(reader: &mut R, params: P) -> Result; @@ -211,9 +209,8 @@ impl_array!(1300); // for OnionPacket.hop_data // HashMap impl Writeable for HashMap -where - K: Writeable + Eq + Hash, - V: Writeable, + where K: Writeable + Eq + Hash, + V: Writeable { #[inline] fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { @@ -227,10 +224,9 @@ where } impl Readable for HashMap -where - R: Read, - K: Readable + Eq + Hash, - V: Readable, + where R: Read, + K: Readable + Eq + Hash, + V: Readable { #[inline] fn read(r: &mut R) -> Result { @@ -400,9 +396,8 @@ impl Writeable for Option { } impl Readable for Option -where - R: Read, - T: Readable, + where R: Read, + T: Readable { fn read(r: &mut R) -> Result { match >::read(r)? { diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index b0ab769426c..08c053bda2f 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -46,41 +46,36 @@ pub struct TestChannelMonitor { pub update_ret: Mutex>, } impl TestChannelMonitor { - pub fn new( - chain_monitor: Arc, - broadcaster: Arc, - logger: Arc, - fee_estimator: Arc, - ) -> Self { - Self { - added_monitors: Mutex::new(Vec::new()), - simple_monitor: channelmonitor::SimpleManyChannelMonitor::new( - chain_monitor, - broadcaster, - logger, - fee_estimator, - ), - update_ret: Mutex::new(Ok(())), - } + pub fn new(chain_monitor: Arc, + broadcaster: Arc, + logger: Arc, + fee_estimator: Arc) + -> Self { + Self { added_monitors: Mutex::new(Vec::new()), + simple_monitor: channelmonitor::SimpleManyChannelMonitor::new( + chain_monitor, + broadcaster, + logger, + fee_estimator, + ), + update_ret: Mutex::new(Ok(())) } } } impl channelmonitor::ManyChannelMonitor for TestChannelMonitor { - fn add_update_monitor( - &self, - funding_txo: OutPoint, - monitor: channelmonitor::ChannelMonitor, - ) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> { + fn add_update_monitor(&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_for_disk(&mut w).unwrap(); assert!( - <(Sha256dHash, channelmonitor::ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(&w.0), - Arc::new(TestLogger::new()) - ) - .unwrap() - .1 == monitor + <(Sha256dHash, channelmonitor::ChannelMonitor)>::read( + &mut ::std::io::Cursor::new(&w.0), + Arc::new(TestLogger::new()) + ).unwrap() + .1 == monitor ); w.0.clear(); monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash... @@ -104,27 +99,19 @@ pub struct TestChannelMessageHandler { } impl TestChannelMessageHandler { - pub fn new() -> Self { - TestChannelMessageHandler { - pending_events: Mutex::new(Vec::new()), - } - } + pub fn new() -> Self { TestChannelMessageHandler { pending_events: Mutex::new(Vec::new()) } } } impl msgs::ChannelMessageHandler for TestChannelMessageHandler { - fn handle_open_channel( - &self, - _their_node_id: &PublicKey, - _their_local_features: LocalFeatures, - _msg: &msgs::OpenChannel, - ) { + fn handle_open_channel(&self, + _their_node_id: &PublicKey, + _their_local_features: LocalFeatures, + _msg: &msgs::OpenChannel) { } - fn handle_accept_channel( - &self, - _their_node_id: &PublicKey, - _their_local_features: LocalFeatures, - _msg: &msgs::AcceptChannel, - ) { + fn handle_accept_channel(&self, + _their_node_id: &PublicKey, + _their_local_features: LocalFeatures, + _msg: &msgs::AcceptChannel) { } fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {} fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {} @@ -161,36 +148,28 @@ impl TestRoutingMessageHandler { } impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result { - Err(LightningError { - err: "", - action: msgs::ErrorAction::IgnoreError, - }) + Err(LightningError { err: "", + action: msgs::ErrorAction::IgnoreError }) } fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result { - Err(LightningError { - err: "", - action: msgs::ErrorAction::IgnoreError, - }) + Err(LightningError { err: "", + action: msgs::ErrorAction::IgnoreError }) } fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result { - Err(LightningError { - err: "", - action: msgs::ErrorAction::IgnoreError, - }) + Err(LightningError { err: "", + action: msgs::ErrorAction::IgnoreError }) } fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {} - fn get_next_channel_announcements( - &self, - _starting_point: u64, - _batch_amount: u8, - ) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate)> { + fn get_next_channel_announcements(&self, + _starting_point: u64, + _batch_amount: u8) + -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate)> { Vec::new() } - fn get_next_node_announcements( - &self, - _starting_point: Option<&PublicKey>, - _batch_amount: u8, - ) -> Vec { + fn get_next_node_announcements(&self, + _starting_point: Option<&PublicKey>, + _batch_amount: u8) + -> Vec { Vec::new() } } @@ -204,11 +183,9 @@ pub struct TestLogger { impl TestLogger { pub fn new() -> TestLogger { Self::with_id("".to_owned()) } pub fn with_id(id: String) -> TestLogger { - TestLogger { - level: Level::Trace, - id, - lines: Mutex::new(HashMap::new()), - } + TestLogger { level: Level::Trace, + id, + lines: Mutex::new(HashMap::new()) } } pub fn enable(&mut self, level: Level) { self.level = level; } pub fn assert_log(&self, module: String, line: String, count: usize) { @@ -219,21 +196,20 @@ impl TestLogger { impl Logger for TestLogger { fn log(&self, record: &Record) { - *self - .lines - .lock() - .unwrap() - .entry((record.module_path.to_string(), format!("{}", record.args))) - .or_insert(0) += 1; + *self.lines + .lock() + .unwrap() + .entry((record.module_path.to_string(), format!("{}", record.args))) + .or_insert(0) += 1; if self.level >= record.level { println!( - "{:<5} {} [{} : {}, {}] {}", - record.level.to_string(), - self.id, - record.module_path, - record.file, - record.line, - record.args + "{:<5} {} [{} : {}, {}] {}", + record.level.to_string(), + self.id, + record.module_path, + record.file, + record.line, + record.args ); } } @@ -272,13 +248,10 @@ impl keysinterface::KeysInterface for TestKeysInterface { impl TestKeysInterface { pub fn new(seed: &[u8; 32], network: Network, logger: Arc) -> Self { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("Time went backwards"); - Self { - backing: keysinterface::KeysManager::new(seed, network, logger, now.as_secs(), now.subsec_nanos()), - override_session_priv: Mutex::new(None), - override_channel_id_priv: Mutex::new(None), - } + let now = SystemTime::now().duration_since(UNIX_EPOCH) + .expect("Time went backwards"); + Self { backing: keysinterface::KeysManager::new(seed, network, logger, now.as_secs(), now.subsec_nanos()), + override_session_priv: Mutex::new(None), + override_channel_id_priv: Mutex::new(None) } } } diff --git a/lightning/src/util/transaction_utils.rs b/lightning/src/util/transaction_utils.rs index 6532d2da8a3..58b8b4f79c2 100644 --- a/lightning/src/util/transaction_utils.rs +++ b/lightning/src/util/transaction_utils.rs @@ -4,12 +4,11 @@ use std::cmp::Ordering; pub fn sort_outputs Ordering>(outputs: &mut Vec<(TxOut, T)>, tie_breaker: C) { outputs.sort_unstable_by(|a, b| { - a.0.value.cmp(&b.0.value).then_with(|| { - a.0.script_pubkey[..] - .cmp(&b.0.script_pubkey[..]) - .then_with(|| tie_breaker(&a.1, &b.1)) - }) - }); + a.0.value.cmp(&b.0.value).then_with(|| { + a.0.script_pubkey[..].cmp(&b.0.script_pubkey[..]) + .then_with(|| tie_breaker(&a.1, &b.1)) + }) + }); } #[cfg(test)] @@ -23,16 +22,12 @@ mod tests { #[test] fn sort_output_by_value() { - let txout1 = TxOut { - value: 100, - script_pubkey: Builder::new().push_int(0).into_script(), - }; + let txout1 = TxOut { value: 100, + script_pubkey: Builder::new().push_int(0).into_script() }; let txout1_ = txout1.clone(); - let txout2 = TxOut { - value: 99, - script_pubkey: Builder::new().push_int(0).into_script(), - }; + let txout2 = TxOut { value: 99, + script_pubkey: Builder::new().push_int(0).into_script() }; let txout2_ = txout2.clone(); let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")]; @@ -45,16 +40,12 @@ mod tests { #[test] fn sort_output_by_script_pubkey() { - let txout1 = TxOut { - value: 100, - script_pubkey: Builder::new().push_int(3).into_script(), - }; + let txout1 = TxOut { value: 100, + script_pubkey: Builder::new().push_int(3).into_script() }; let txout1_ = txout1.clone(); - let txout2 = TxOut { - value: 100, - script_pubkey: Builder::new().push_int(1).push_int(2).into_script(), - }; + let txout2 = TxOut { value: 100, + script_pubkey: Builder::new().push_int(1).push_int(2).into_script() }; let txout2_ = txout2.clone(); let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")]; @@ -84,10 +75,8 @@ mod tests { #[test] fn sort_output_tie_breaker_test() { - let txout1 = TxOut { - value: 100, - script_pubkey: Builder::new().push_int(1).push_int(2).into_script(), - }; + let txout1 = TxOut { value: 100, + script_pubkey: Builder::new().push_int(1).push_int(2).into_script() }; let txout1_ = txout1.clone(); let txout2 = txout1.clone(); @@ -127,8 +116,8 @@ mod tests { } const TXOUT1: [(u64, &str); 2] = [ - (400057456, "76a9144a5fba237213a062f6f57978f796390bdcf8d01588ac"), - (40000000000, "76a9145be32612930b8323add2212a4ec03c1562084f8488ac"), + (400057456, "76a9144a5fba237213a062f6f57978f796390bdcf8d01588ac"), + (40000000000, "76a9145be32612930b8323add2212a4ec03c1562084f8488ac"), ]; const TXOUT2: [(u64, &str); 2] = [(100000000, "41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac"), (2400000000, "41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac")]; bip_txout_tests! {