Skip to content

Commit 0df41f4

Browse files
author
Antoine Riard
committed
Implement SendErrorMessage event with disconnection flag + test disconnection
1 parent 48b0d99 commit 0df41f4

File tree

4 files changed

+175
-10
lines changed

4 files changed

+175
-10
lines changed

src/ln/channelmanager.rs

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,15 @@ impl ChannelManager {
677677
/// Call this upon creation of a funding transaction for the given channel.
678678
/// Panics if a funding transaction has already been provided for this channel.
679679
pub fn funding_transaction_generated(&self, temporary_channel_id: &Uint256, funding_txo: OutPoint) {
680+
681+
macro_rules! add_pending_event {
682+
($event: expr) => {
683+
let mut pending_events = self.pending_events.lock().unwrap();
684+
pending_events.push($event);
685+
}
686+
}
687+
688+
let mut temporary_pending_events = Vec::new();
680689
let (chan, msg, chan_monitor) = {
681690
let mut channel_state = self.channel_state.lock().unwrap();
682691
match channel_state.by_id.remove(&temporary_channel_id) {
@@ -685,25 +694,40 @@ impl ChannelManager {
685694
Ok(funding_msg) => {
686695
(chan, funding_msg.0, funding_msg.1)
687696
},
688-
Err(_e) => {
689-
//TODO: Push e to pendingevents
697+
Err(e) => {
698+
println!("Got error handling message: {}!", e.err);
699+
if let Some(action) = e.msg {
700+
match action {
701+
msgs::ErrorAction::DisconnectPeer {} => {
702+
temporary_pending_events.push(events::Event::SendErrorMessage {
703+
node_id: chan.get_their_node_id(),
704+
msg: msgs::ErrorMessage { err: "" },
705+
disconnect: true,
706+
hard: true,
707+
});
708+
},
709+
_ => panic!("Kind of error not implemented yet for funding_transaction_generated"),
710+
}
711+
} else {
712+
panic!("ErrorAction needed for this HandleError into funding_transaction_generated");
713+
}
690714
return;
691-
}
715+
},
692716
}
693717
},
694718
None => return
695719
}
696720
}; // Release channel lock for install_watch_outpoint call,
721+
if let Some(event) = temporary_pending_events.pop() {
722+
add_pending_event!(event);
723+
}
697724
if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
698725
unimplemented!(); // maybe remove from claimable_htlcs?
699726
}
700-
{
701-
let mut pending_events = self.pending_events.lock().unwrap();
702-
pending_events.push(events::Event::SendFundingCreated {
703-
node_id: chan.get_their_node_id(),
704-
msg: msg,
705-
});
706-
}
727+
add_pending_event!(events::Event::SendFundingCreated {
728+
node_id: chan.get_their_node_id(),
729+
msg: msg,
730+
});
707731

708732
let mut channel_state = self.channel_state.lock().unwrap();
709733
channel_state.by_id.insert(chan.channel_id(), chan);
@@ -1811,6 +1835,13 @@ impl ChannelMessageHandler for ChannelManager {
18111835
}
18121836
}
18131837
}
1838+
1839+
//For testing purpose in peer_handler, to manually push target event
1840+
#[cfg(test)]
1841+
fn push_event(&self, event: events::Event) {
1842+
let mut pending_events = self.pending_events.lock().unwrap();
1843+
pending_events.push(event);
1844+
}
18141845
}
18151846

18161847
#[cfg(test)]

src/ln/msgs.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,10 @@ pub struct Init {
139139
pub local_features: LocalFeatures,
140140
}
141141

142+
pub struct ErrorMessage {
143+
pub err: &'static str,
144+
}
145+
142146
pub struct Ping {
143147
pub ponglen: u16,
144148
pub byteslen: u16,
@@ -435,6 +439,10 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
435439
/// understand or indicate they require unknown feature bits), no_connection_possible is set
436440
/// and any outstanding channels should be failed.
437441
fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
442+
443+
//Testing
444+
#[cfg(test)]
445+
fn push_event(&self, event: events::Event);
438446
}
439447

440448
pub trait RoutingMessageHandler : Send + Sync {
@@ -1534,3 +1542,11 @@ impl MsgEncodable for OnionErrorPacket {
15341542
res
15351543
}
15361544
}
1545+
1546+
impl MsgEncodable for ErrorMessage {
1547+
fn encode(&self) -> Vec<u8> {
1548+
let mut res = Vec::with_capacity(self.err.len());
1549+
res.extend_from_slice(&self.err.as_bytes());
1550+
res
1551+
}
1552+
}

src/ln/peer_handler.rs

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
3737
/// indicating that read events on this descriptor should resume. A resume_read of false does
3838
/// *not* imply that further read events should be paused.
3939
fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
40+
///Indicate to the network provider that we want to disconnect this peer, no more allowing any call
41+
///to disconnect_event or read_event
42+
fn notify_disconnection(&mut self);
4043
}
4144

4245
/// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
@@ -576,6 +579,7 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
576579
/// calls to ChannelManager::process_pending_htlc_forward.
577580
pub fn process_events(&self) {
578581
let mut upstream_events = Vec::new();
582+
let mut disconnect_peers = Vec::new();
579583
{
580584
// TODO: There are some DoS attacks here where you can flood someone's outbound send
581585
// buffer by doing things like announcing channels on another node. We should be willing to
@@ -710,12 +714,30 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
710714
}
711715
continue;
712716
},
717+
Event::SendErrorMessage { ref node_id, ref msg, ref disconnect, ref hard } => {
718+
let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
719+
//TODO: Do whatever we're gonna do for handling dropped messages
720+
});
721+
if *disconnect == true {
722+
disconnect_peers.push(descriptor.clone());
723+
}
724+
if *hard == false {
725+
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
726+
Self::do_attempt_write_data(&mut descriptor, peer);
727+
}
728+
continue;
729+
},
713730
}
714731

715732
upstream_events.push(event);
716733
}
717734
}
718735

736+
for mut descriptor in disconnect_peers {
737+
descriptor.notify_disconnection();
738+
self.disconnect_event(&descriptor);
739+
}
740+
719741
let mut pending_events = self.pending_events.lock().unwrap();
720742
for event in upstream_events.drain(..) {
721743
pending_events.push(event);
@@ -756,3 +778,92 @@ impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
756778
ret
757779
}
758780
}
781+
782+
#[cfg(test)]
783+
mod tests {
784+
use chain::chaininterface;
785+
use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
786+
use ln::channelmanager::{ChannelManager};
787+
use ln::router::{Router};
788+
use ln::msgs;
789+
use ln::msgs::{HandleError};
790+
use util::test_utils;
791+
use util::events;
792+
793+
use bitcoin::network::constants::Network;
794+
use bitcoin::util::misc::hex_bytes;
795+
796+
use secp256k1::Secp256k1;
797+
use secp256k1::key::{SecretKey, PublicKey};
798+
799+
use rand::{thread_rng,Rng};
800+
801+
use std::sync::{Arc, Mutex};
802+
803+
#[derive(PartialEq, Eq, Clone, Hash)]
804+
struct FileDescriptor {
805+
fd: u16,
806+
}
807+
808+
impl SocketDescriptor for FileDescriptor {
809+
fn send_data(&mut self, data: &Vec<u8>, _write_offset: usize, _resume_read: bool) -> usize {
810+
data.len()
811+
}
812+
813+
fn notify_disconnection(&mut self) {}
814+
}
815+
816+
fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
817+
let secp_ctx = Secp256k1::new();
818+
let mut peers = Vec::new();
819+
let mut rng = thread_rng();
820+
821+
for _ in 0..peer_count {
822+
let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_vbyte: 1 });
823+
let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new());
824+
let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
825+
let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
826+
let node_id = {
827+
let mut key_slice = [0;32];
828+
rng.fill_bytes(&mut key_slice);
829+
SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
830+
};
831+
let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone()).unwrap();
832+
let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id).unwrap());
833+
let msg_handler = MessageHandler { chan_handler: node, route_handler: Arc::new(router) };
834+
let peer = PeerManager::new(msg_handler, node_id);
835+
peers.push(peer);
836+
}
837+
838+
peers
839+
}
840+
841+
fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
842+
let secp_ctx = Secp256k1::new();
843+
let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret).unwrap();
844+
let fd = FileDescriptor { fd: 1};
845+
peer_a.new_inbound_connection(fd.clone());
846+
peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
847+
}
848+
849+
#[test]
850+
fn test_disconnect_peer() {
851+
// Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
852+
// push an DisconnectPeer event to remove the node flagged by id
853+
let peers = create_network(2);
854+
establish_connection(&peers[0], &peers[1]);
855+
assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
856+
857+
let secp_ctx = Secp256k1::new();
858+
let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret).unwrap();
859+
peers[0].message_handler.chan_handler.push_event(events::Event::SendErrorMessage {
860+
node_id: their_id,
861+
msg: msgs::ErrorMessage { err: "" },
862+
disconnect: true,
863+
hard: true,
864+
});
865+
866+
peers[0].process_events();
867+
assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
868+
}
869+
}

src/util/events.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ pub enum Event {
100100
BroadcastChannelUpdate {
101101
msg: msgs::ChannelUpdate,
102102
},
103+
/// Used to tell a peer that something is incorrect
104+
SendErrorMessage {
105+
node_id: PublicKey,
106+
msg: msgs::ErrorMessage,
107+
disconnect: bool,
108+
hard: bool, //disconnect without message
109+
},
103110
}
104111

105112
pub trait EventsProvider {

0 commit comments

Comments
 (0)