use ln::features::InitFeatures;
use ln::msgs;
-use util::ser::{Writeable, Writer, Readable};
+use ln::msgs::ChannelMessageHandler;
+use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
+use util::ser::{Writeable, Readable, VecWriter};
use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
use util::byte_utils;
-use util::events::{MessageSendEvent};
+use util::events::{MessageSendEvent, MessageSendEventsProvider};
use util::logger::Logger;
use std::collections::{HashMap,hash_map,HashSet,LinkedList};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{cmp,error,hash,fmt};
+use std::ops::Deref;
use bitcoin_hashes::sha256::Hash as Sha256;
use bitcoin_hashes::sha256::HashEngine as Sha256Engine;
use bitcoin_hashes::{HashEngine, Hash};
/// Provides references to trait impls which handle different types of messages.
-pub struct MessageHandler {
+pub struct MessageHandler<CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
/// A message handler which handles messages specific to channels. Usually this is just a
/// ChannelManager object.
- pub chan_handler: Arc<msgs::ChannelMessageHandler>,
+ pub chan_handler: CM,
/// A message handler which handles messages updating our knowledge of the network channel
/// graph. Usually this is just a Router object.
pub route_handler: Arc<msgs::RoutingMessageHandler>,
unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
}
+/// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
+/// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
+/// lifetimes). Other times you can afford a reference, which is more efficient, in which case
+/// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
+/// issues such as overly long function definitions.
+pub type SimpleArcPeerManager<SD, M> = Arc<PeerManager<SD, SimpleArcChannelManager<M>>>;
+
+/// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
+/// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
+/// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
+/// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
+/// But if this is not necessary, using a reference is more efficient. Defining these type aliases
+/// helps with issues such as long function definitions.
+pub type SimpleRefPeerManager<'a, SD, M> = PeerManager<SD, SimpleRefChannelManager<'a, M>>;
+
/// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
/// events into messages which it passes on to its MessageHandlers.
-pub struct PeerManager<Descriptor: SocketDescriptor> {
- message_handler: MessageHandler,
+///
+/// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
+/// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
+/// essentially you should default to using a SimpleRefPeerManager, and use a
+/// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
+/// you're using lightning-net-tokio.
+pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
+ message_handler: MessageHandler<CM>,
peers: Mutex<PeerHolder<Descriptor>>,
our_node_secret: SecretKey,
ephemeral_key_midstate: Sha256Engine,
logger: Arc<Logger>,
}
-struct VecWriter(Vec<u8>);
-impl Writer for VecWriter {
- fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
- self.0.extend_from_slice(buf);
- Ok(())
- }
- fn size_hint(&mut self, size: usize) {
- self.0.reserve_exact(size);
- }
-}
-
macro_rules! encode_msg {
($msg: expr, $msg_code: expr) => {{
let mut msg = VecWriter(Vec::new());
/// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
/// PeerIds may repeat, but only after disconnect_event() has been called.
-impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
+impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where CM::Target: msgs::ChannelMessageHandler {
/// 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<Logger>) -> PeerManager<Descriptor> {
+ pub fn new(message_handler: MessageHandler<CM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor, CM> {
let mut ephemeral_key_midstate = Sha256::engine();
ephemeral_key_midstate.input(ephemeral_random_data);
fn disconnect_socket(&mut self) {}
}
- fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
+ fn create_chan_handlers(peer_count: usize) -> Vec<test_utils::TestChannelMessageHandler> {
+ let mut chan_handlers = Vec::new();
+ for _ in 0..peer_count {
+ let chan_handler = test_utils::TestChannelMessageHandler::new();
+ chan_handlers.push(chan_handler);
+ }
+
+ chan_handlers
+ }
+
+ fn create_network<'a>(peer_count: usize, chan_handlers: &'a Vec<test_utils::TestChannelMessageHandler>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>> {
let mut peers = Vec::new();
let mut rng = thread_rng();
let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
let mut ephemeral_bytes = [0; 32];
rng.fill_bytes(&mut ephemeral_bytes);
- for _ in 0..peer_count {
- let chan_handler = test_utils::TestChannelMessageHandler::new();
+ for i in 0..peer_count {
let router = test_utils::TestRoutingMessageHandler::new();
let node_id = {
let mut key_slice = [0;32];
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: &chan_handlers[i], route_handler: Arc::new(router) };
let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
peers.push(peer);
}
peers
}
- fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
+ fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>) {
let secp_ctx = Secp256k1::new();
let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
let fd = FileDescriptor { fd: 1};
fn test_disconnect_peer() {
// Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
// push a DisconnectPeer event to remove the node flagged by id
- let mut peers = create_network(2);
+ let chan_handlers = create_chan_handlers(2);
+ let chan_handler = test_utils::TestChannelMessageHandler::new();
+ let mut peers = create_network(2, &chan_handlers);
establish_connection(&peers[0], &peers[1]);
assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
let secp_ctx = Secp256k1::new();
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 },
});
assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
- peers[0].message_handler.chan_handler = Arc::new(chan_handler);
+ peers[0].message_handler.chan_handler = &chan_handler;
peers[0].process_events();
assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
#[test]
fn test_timer_tick_occured(){
// Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
- let peers = create_network(2);
+ let chan_handlers = create_chan_handlers(2);
+ let peers = create_network(2, &chan_handlers);
establish_connection(&peers[0], &peers[1]);
assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);