Skip to content

Commit f71ff8f

Browse files
authored
Merge pull request #164 from TheBlueMatt/2018-09-channel-connection-cleanups
Minor cleanups
2 parents 6c07555 + e9fed49 commit f71ff8f

File tree

3 files changed

+46
-18
lines changed

3 files changed

+46
-18
lines changed

src/ln/channel.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -893,10 +893,11 @@ impl Channel {
893893

894894
/// Gets the redeemscript for the funding transaction output (ie the funding transaction output
895895
/// pays to get_funding_redeemscript().to_v0_p2wsh()).
896+
/// Panics if called before accept_channel/new_from_req
896897
pub fn get_funding_redeemscript(&self) -> Script {
897898
let builder = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2);
898899
let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).serialize();
899-
let their_funding_key = self.their_funding_pubkey.unwrap().serialize();
900+
let their_funding_key = self.their_funding_pubkey.expect("get_funding_redeemscript only allowed after accept_channel").serialize();
900901
if our_funding_key[..] < their_funding_key[..] {
901902
builder.push_slice(&our_funding_key)
902903
.push_slice(&their_funding_key)

src/ln/channelmonitor.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,11 @@ pub enum ChannelMonitorUpdateErr {
4646
/// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
4747
/// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
4848
/// which we have revoked, allowing our counterparty to claim all funds in the channel!
49-
/// A call to add_update_monitor is needed to register outpoint and its txid with ChainWatchInterface
50-
/// after setting funding_txo in a ChannelMonitor
5149
pub trait ManyChannelMonitor: Send + Sync {
5250
/// Adds or updates a monitor for the given `funding_txo`.
51+
/// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
52+
/// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
53+
/// any spends of it.
5354
fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
5455
}
5556

@@ -471,7 +472,7 @@ impl ChannelMonitor {
471472
/// optional, without it this monitor cannot be used in an SPV client, but you may wish to
472473
/// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
473474
/// provides slightly better privacy.
474-
/// It's the responsability of the caller to register outpoint and script with passing the former
475+
/// It's the responsibility of the caller to register outpoint and script with passing the former
475476
/// value as key to add_update_monitor.
476477
pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
477478
self.funding_txo = Some(funding_info);

src/ln/peer_handler.rs

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use util::byte_utils;
77
use util::events::{EventsProvider,Event};
88
use util::logger::Logger;
99

10-
use std::collections::{HashMap,LinkedList};
10+
use std::collections::{HashMap,hash_map,LinkedList};
1111
use std::sync::{Arc, Mutex};
1212
use std::sync::atomic::{AtomicUsize, Ordering};
1313
use std::{cmp,error,mem,hash,fmt};
@@ -90,6 +90,18 @@ struct PeerHolder<Descriptor: SocketDescriptor> {
9090
/// Only add to this set when noise completes:
9191
node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
9292
}
93+
struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> {
94+
peers: &'a mut HashMap<Descriptor, Peer>,
95+
node_id_to_descriptor: &'a mut HashMap<PublicKey, Descriptor>,
96+
}
97+
impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
98+
fn borrow_parts(&mut self) -> MutPeerHolder<Descriptor> {
99+
MutPeerHolder {
100+
peers: &mut self.peers,
101+
node_id_to_descriptor: &mut self.node_id_to_descriptor,
102+
}
103+
}
104+
}
93105

94106
pub struct PeerManager<Descriptor: SocketDescriptor> {
95107
message_handler: MessageHandler,
@@ -100,7 +112,6 @@ pub struct PeerManager<Descriptor: SocketDescriptor> {
100112
logger: Arc<Logger>,
101113
}
102114

103-
104115
macro_rules! encode_msg {
105116
($msg: expr, $msg_code: expr) => {
106117
{
@@ -136,7 +147,12 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
136147
/// completed and we are sure the remote peer has the private key for the given node_id.
137148
pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
138149
let peers = self.peers.lock().unwrap();
139-
peers.peers.values().filter_map(|p| p.their_node_id).collect()
150+
peers.peers.values().filter_map(|p| {
151+
if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() {
152+
return None;
153+
}
154+
p.their_node_id
155+
}).collect()
140156
}
141157

142158
/// Indicates a new outbound connection has been established to a node with the given node_id.
@@ -267,14 +283,14 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
267283

268284
fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
269285
let pause_read = {
270-
let mut peers = self.peers.lock().unwrap();
271-
let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
286+
let mut peers_lock = self.peers.lock().unwrap();
287+
let peers = peers_lock.borrow_parts();
288+
let pause_read = match peers.peers.get_mut(peer_descriptor) {
272289
None => panic!("Descriptor for read_event is not already known to PeerManager"),
273290
Some(peer) => {
274291
assert!(peer.pending_read_buffer.len() > 0);
275292
assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
276293

277-
let mut insert_node_id = None;
278294
let mut read_pos = 0;
279295
while read_pos < data.len() {
280296
{
@@ -353,6 +369,18 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
353369
}
354370
}
355371

372+
macro_rules! insert_node_id {
373+
() => {
374+
match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
375+
hash_map::Entry::Occupied(_) => {
376+
peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
377+
return Err(PeerHandleError{ no_connection_possible: false })
378+
},
379+
hash_map::Entry::Vacant(entry) => entry.insert(peer_descriptor.clone()),
380+
};
381+
}
382+
}
383+
356384
let next_step = peer.channel_encryptor.get_noise_step();
357385
match next_step {
358386
NextNoiseStep::ActOne => {
@@ -366,7 +394,7 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
366394
peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
367395
peer.pending_read_is_header = true;
368396

369-
insert_node_id = Some(peer.their_node_id.unwrap());
397+
insert_node_id!();
370398
let mut local_features = msgs::LocalFeatures::new();
371399
if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
372400
self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
@@ -382,7 +410,7 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
382410
peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
383411
peer.pending_read_is_header = true;
384412
peer.their_node_id = Some(their_node_id);
385-
insert_node_id = Some(peer.their_node_id.unwrap());
413+
insert_node_id!();
386414
},
387415
NextNoiseStep::NoiseComplete => {
388416
if peer.pending_read_is_header {
@@ -417,6 +445,9 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
417445
if msg.local_features.requires_unknown_bits() {
418446
return Err(PeerHandleError{ no_connection_possible: true });
419447
}
448+
if peer.their_global_features.is_some() {
449+
return Err(PeerHandleError{ no_connection_possible: false });
450+
}
420451
peer.their_global_features = Some(msg.global_features);
421452
peer.their_local_features = Some(msg.local_features);
422453

@@ -607,15 +638,10 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
607638

608639
Self::do_attempt_write_data(peer_descriptor, peer);
609640

610-
(insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
641+
peer.pending_outbound_buffer.len() > 10 // pause_read
611642
}
612643
};
613644

614-
match should_insert_node_id {
615-
Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
616-
None => {}
617-
};
618-
619645
pause_read
620646
};
621647

0 commit comments

Comments
 (0)