lighthouse-pulse/lighthouse/sync/network.rs

83 lines
2.1 KiB
Rust
Raw Normal View History

2018-09-14 05:52:49 +00:00
use std::sync::Arc;
use super::db::ClientDB;
2018-09-09 14:36:00 +00:00
use slog::Logger;
use super::network_libp2p::message::{
NetworkEvent,
OutgoingMessage,
NetworkEventType,
};
2018-09-14 05:52:49 +00:00
use super::block::process_unverified_blocks;
use super::wire_protocol::{
WireMessage,
WireMessageHeader,
};
2018-09-09 16:28:36 +00:00
2018-09-09 14:36:00 +00:00
use super::futures::sync::mpsc::{
UnboundedSender,
};
2018-09-09 16:28:36 +00:00
/// Accept a network event and perform all required processing.
///
/// This function should be called whenever an underlying network
/// (e.g., libp2p) has an event to push up to the sync process.
2018-09-09 14:36:00 +00:00
pub fn handle_network_event(
event: NetworkEvent,
db: Arc<ClientDB>,
2018-09-09 14:36:00 +00:00
network_tx: UnboundedSender<OutgoingMessage>,
log: Logger)
-> Result<(), ()>
{
2018-09-09 16:28:36 +00:00
debug!(&log, "";
"network_event" => format!("{:?}", &event));
2018-09-09 14:36:00 +00:00
match event.event {
NetworkEventType::PeerConnect => Ok(()),
NetworkEventType::PeerDrop => Ok(()),
2018-09-09 16:28:36 +00:00
NetworkEventType::Message => {
if let Some(data) = event.data {
handle_network_message(
data,
db,
2018-09-09 16:28:36 +00:00
network_tx,
log)
} else {
Ok(())
}
}
2018-09-09 14:36:00 +00:00
}
}
2018-09-09 16:28:36 +00:00
/// Accept a message from the network and perform all required
/// processing.
///
/// This function should be called whenever a peer from a network
/// (e.g., libp2p) has sent a message to us.
2018-09-09 14:36:00 +00:00
fn handle_network_message(
2018-09-09 16:28:36 +00:00
message: Vec<u8>,
db: Arc<ClientDB>,
2018-09-09 14:36:00 +00:00
_network_tx: UnboundedSender<OutgoingMessage>,
2018-09-14 05:52:49 +00:00
log: Logger)
2018-09-09 14:36:00 +00:00
-> Result<(), ()>
{
2018-09-14 05:52:49 +00:00
match WireMessage::decode(&message) {
Ok(msg) => {
match msg.header {
WireMessageHeader::Blocks => {
process_unverified_blocks(
msg.body,
db,
log
);
Ok(())
}
_ => Ok(())
}
}
Err(_) => {
return Ok(()) // No need to pass the error back
2018-09-09 16:28:36 +00:00
}
}
2018-09-09 14:36:00 +00:00
}