Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[network] Refactor PeerMessage #1726

Merged
merged 3 commits into from
Dec 1, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 5 additions & 34 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -34,7 +34,6 @@ members = [
"txpool",
"txpool/api",
"txpool/mock-service",
"txpool/tx-relay",
"executor",
"executor/benchmark",
"chain",
@@ -49,7 +48,6 @@ members = [
"sync",
"sync/api",
"block-relayer",
"block-relayer/api",
"miner",
"node",
"network-p2p",
1 change: 0 additions & 1 deletion block-relayer/Cargo.toml
Original file line number Diff line number Diff line change
@@ -21,7 +21,6 @@ network-api = { package = "network-api", path = "../network/api" }
starcoin-sync-api = {package="starcoin-sync-api", path="../sync/api"}
starcoin-sync = {package="starcoin-sync", path="../sync"}
starcoin-network ={path = "../network"}
starcoin-block-relayer-api = { path = "./api"}
starcoin-canonical-serialization = { package="starcoin-canonical-serialization", path = "../commons/scs"}
starcoin-types = {path = "../types", package = "starcoin-types" }
starcoin-metrics = {path = "../commons/metrics"}
16 changes: 0 additions & 16 deletions block-relayer/api/Cargo.toml

This file was deleted.

19 changes: 0 additions & 19 deletions block-relayer/api/src/lib.rs

This file was deleted.

53 changes: 39 additions & 14 deletions block-relayer/src/block_relayer.rs
Original file line number Diff line number Diff line change
@@ -6,7 +6,8 @@ use anyhow::Result;
use crypto::HashValue;
use futures::FutureExt;
use logger::prelude::*;
use starcoin_block_relayer_api::{NetCmpctBlockMessage, PeerCmpctBlockEvent};
use network_api::messages::{CompactBlockMessage, NotificationMessage, PeerCompactBlockMessage};
use network_api::NetworkService;
use starcoin_network::NetworkAsyncService;
use starcoin_network_rpc_api::{gen_client::NetworkRpcClient, GetTxns};
use starcoin_service_registry::{ActorService, EventHandler, ServiceContext, ServiceFactory};
@@ -130,17 +131,16 @@ impl BlockRelayer {

fn handle_block_event(
&self,
cmpct_block_msg: PeerCmpctBlockEvent,
compact_block_msg: PeerCompactBlockMessage,
ctx: &mut ServiceContext<BlockRelayer>,
) -> Result<()> {
let network = ctx.get_shared::<NetworkAsyncService>()?;
let block_connector_service = ctx.service_ref::<BlockConnectorService>()?.clone();
//TODO use VerifiedRpcClient and filter peers, avoid fetch from a no synced peer.
let rpc_client = NetworkRpcClient::new(network);
let txpool = self.txpool.clone();
let fut = async move {
let compact_block = cmpct_block_msg.compact_block;
let peer_id = cmpct_block_msg.peer_id;
let compact_block = compact_block_msg.message.compact_block;
let peer_id = compact_block_msg.peer_id;
debug!("Receive peer compact block event from peer id:{}", peer_id);
let block = BlockRelayer::fill_compact_block(
txpool,
@@ -191,30 +191,55 @@ impl EventHandler<Self, NewHeadBlock> for BlockRelayer {
debug!("[block-relay] Ignore NewHeadBlock event because the node has not been synchronized yet.");
return;
}
let network = match ctx.get_shared::<NetworkAsyncService>() {
Ok(network) => network,
Err(e) => {
error!("Get network service error: {:?}", e);
return;
}
};
let compact_block = self.block_into_compact(event.0.get_block().clone());
let total_difficulty = event.0.get_total_difficulty();
let net_cmpct_block_msg = NetCmpctBlockMessage {
let compact_block_msg = CompactBlockMessage {
compact_block,
total_difficulty,
};
//TODO directly send to network.
ctx.broadcast(net_cmpct_block_msg);
ctx.spawn(async move {
network
.broadcast(NotificationMessage::CompactBlock(Box::new(
compact_block_msg,
)))
.await;
});
}
}

impl EventHandler<Self, PeerCmpctBlockEvent> for BlockRelayer {
impl EventHandler<Self, PeerCompactBlockMessage> for BlockRelayer {
fn handle_event(
&mut self,
cmpct_block_msg: PeerCmpctBlockEvent,
compact_block_msg: PeerCompactBlockMessage,
ctx: &mut ServiceContext<BlockRelayer>,
) {
if !self.is_synced() {
debug!("[block-relay] Ignore PeerCmpctBlock event because the node has not been synchronized yet.");
debug!("[block-relay] Ignore PeerCompactBlockMessage because the node has not been synchronized yet.");
return;
}
let sync_status = self
.sync_status
.as_ref()
.expect("Sync status should bean some at here");
let current_total_difficulty = sync_status.chain_status().total_difficulty();
let block_total_difficulty = compact_block_msg.message.total_difficulty;
let block_id = compact_block_msg.message.compact_block.header.id();
if current_total_difficulty > block_total_difficulty {
debug!("[block-relay] Ignore PeerCompactBlockMessage because node current total_difficulty({}) > block({})'s total_difficulty({}).", current_total_difficulty, block_id, block_total_difficulty);
return;
}
//TODO filter by total_difficulty and block number, ignore too old block.
if let Err(e) = self.handle_block_event(cmpct_block_msg, ctx) {
error!("[block-relay] handle PeerCmpctBlock event error: {:?}", e);
if let Err(e) = self.handle_block_event(compact_block_msg, ctx) {
error!(
"[block-relay] handle PeerCompactBlockMessage error: {:?}",
e
);
}
}
}
2 changes: 1 addition & 1 deletion commons/service-registry/src/handler_proxy.rs
Original file line number Diff line number Diff line change
@@ -80,7 +80,7 @@ where

fn stop(&mut self, ctx: &mut ServiceContext<S>) -> Result<()> {
if self.status().is_stopped() {
warn!("Service {} has bean stopped", S::service_name());
info!("Service {} has bean stopped", S::service_name());
return Ok(());
}
let service = self.service.take();
2 changes: 1 addition & 1 deletion commons/service-registry/src/service_actor.rs
Original file line number Diff line number Diff line change
@@ -255,7 +255,7 @@ where
fn handle(&mut self, msg: EventMessage<M>, ctx: &mut Self::Context) -> Self::Result {
debug!("{} handle event: {:?}", S::service_name(), &msg.msg);
if self.proxy.status().is_stopped() {
error!("Service {} is stopped", S::service_name());
info!("Service {} is already stopped", S::service_name());
return;
}
let mut service_ctx = ServiceContext::new(&mut self.cache, ctx);
26 changes: 18 additions & 8 deletions config/src/network_config.rs
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ use crate::{
};
use anyhow::{bail, format_err, Result};
use network_p2p_types::{
is_memory_addr, memory_addr,
multiaddr::{Multiaddr, Protocol},
MultiaddrWithPeerId,
};
@@ -58,11 +59,14 @@ impl NetworkConfig {

fn prepare_peer_id(&mut self) {
let peer_id = PeerId::from_ed25519_public_key(self.network_keypair().public_key.clone());
let host = self
.listen
.clone()
.replace(0, |_p| Some(Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1))))
.expect("Replace multi address fail.");
let host = if is_memory_addr(&self.listen) {
self.listen.clone()
} else {
self.listen
.clone()
.replace(0, |_p| Some(Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1))))
.expect("Replace multi address fail.")
};
self.self_address = Some(MultiaddrWithPeerId::new(host, peer_id.clone().into()));
self.self_peer_id = Some(peer_id);
}
@@ -103,10 +107,16 @@ impl ConfigModule for NetworkConfig {
} else {
DEFAULT_NETWORK_PORT
};
Ok(Self {
listen: format!("/ip4/0.0.0.0/tcp/{}", port)
//test env use in memory transport.
let listen = if base.net.is_test() {
memory_addr(port as u64)
} else {
format!("/ip4/0.0.0.0/tcp/{}", port)
.parse()
.expect("Parse multi address fail."),
.expect("Parse multi address fail.")
};
Ok(Self {
listen,
seeds,
network_keypair: Some(Arc::new(Self::load_or_generate_keypair(opt, base)?)),
self_peer_id: None,
Loading