Remove NetworkSpecialization (#4665)

* remove networkspecialization

* Fix most of the fallout

* get all tests compiling

Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
This commit is contained in:
Robert Habermeier
2020-02-21 05:02:12 -08:00
committed by GitHub
parent e8000e7429
commit 0090fe979b
20 changed files with 136 additions and 503 deletions
@@ -25,7 +25,8 @@ use libp2p::swarm::{PollParameters, NetworkBehaviour, NetworkBehaviourAction};
use libp2p::{PeerId, Multiaddr, Transport};
use rand::seq::SliceRandom;
use std::{error, io, task::Context, task::Poll, time::Duration};
use crate::message::Message;
use std::collections::HashSet;
use crate::message::{generic::BlockResponse, Message};
use crate::protocol::generic_proto::{GenericProto, GenericProtoOut};
use sp_test_primitives::Block;
@@ -227,7 +228,10 @@ fn two_nodes_transfer_lots_of_packets() {
for n in 0 .. NUM_PACKETS {
service1.send_packet(
&peer_id,
Message::<Block>::ChainSpecific(vec![(n % 256) as u8]).encode()
Message::<Block>::BlockResponse(BlockResponse {
id: n as _,
blocks: Vec::new(),
}).encode()
);
}
},
@@ -243,8 +247,8 @@ fn two_nodes_transfer_lots_of_packets() {
Some(GenericProtoOut::CustomProtocolOpen { .. }) => {},
Some(GenericProtoOut::CustomMessage { message, .. }) => {
match Message::<Block>::decode(&mut &message[..]).unwrap() {
Message::<Block>::ChainSpecific(message) => {
assert_eq!(message.len(), 1);
Message::<Block>::BlockResponse(BlockResponse { id: _, blocks }) => {
assert!(blocks.is_empty());
packet_counter += 1;
if packet_counter == NUM_PACKETS {
return Poll::Ready(())
@@ -270,9 +274,21 @@ fn basic_two_nodes_requests_in_parallel() {
// Generate random messages with or without a request id.
let mut to_send = {
let mut to_send = Vec::new();
let mut existing_ids = HashSet::new();
for _ in 0..200 { // Note: don't make that number too high or the CPU usage will explode.
let msg = (0..10).map(|_| rand::random::<u8>()).collect::<Vec<_>>();
to_send.push(Message::<Block>::ChainSpecific(msg));
let req_id = loop {
let req_id = rand::random::<u64>();
// ensure uniqueness - odds of randomly sampling collisions
// is unlikely, but possible to cause spurious test failures.
if existing_ids.insert(req_id) {
break req_id;
}
};
to_send.push(Message::<Block>::BlockResponse(
BlockResponse { id: req_id, blocks: Vec::new() }
));
}
to_send
};
@@ -219,9 +219,6 @@ pub mod generic {
FinalityProofResponse(FinalityProofResponse<Hash>),
/// Batch of consensus protocol messages.
ConsensusBatch(Vec<ConsensusMessage>),
/// Chain-specific message.
#[codec(index = "255")]
ChainSpecific(Vec<u8>),
}
impl<Header, Hash, Number, Extrinsic> Message<Header, Hash, Number, Extrinsic> {
@@ -246,7 +243,6 @@ pub mod generic {
Message::FinalityProofRequest(_) => "FinalityProofRequest",
Message::FinalityProofResponse(_) => "FinalityProofResponse",
Message::ConsensusBatch(_) => "ConsensusBatch",
Message::ChainSpecific(_) => "ChainSpecific",
}
}
}
@@ -1,171 +0,0 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Specializations of the substrate network protocol to allow more complex forms of communication.
pub use crate::protocol::event::{DhtEvent, Event};
use crate::protocol::Context;
use libp2p::PeerId;
use sp_runtime::traits::Block as BlockT;
/// A specialization of the substrate network protocol. Handles events and sends messages.
pub trait NetworkSpecialization<B: BlockT>: Send + Sync + 'static {
/// Get the current specialization-status.
fn status(&self) -> Vec<u8>;
/// Called when a peer successfully handshakes.
fn on_connect(&mut self, ctx: &mut dyn Context<B>, who: PeerId, status: crate::protocol::message::Status<B>);
/// Called when a peer is disconnected. If the peer ID is unknown, it should be ignored.
fn on_disconnect(&mut self, ctx: &mut dyn Context<B>, who: PeerId);
/// Called when a network-specific message arrives.
fn on_message(
&mut self,
ctx: &mut dyn Context<B>,
who: PeerId,
message: Vec<u8>
);
/// Called periodically to maintain peers and handle timeouts.
fn maintain_peers(&mut self, _ctx: &mut dyn Context<B>) { }
/// Called when a block is _imported_ at the head of the chain (not during major sync).
/// Not guaranteed to be called for every block, but will be most of the after major sync.
fn on_block_imported(&mut self, _ctx: &mut dyn Context<B>, _hash: B::Hash, _header: &B::Header) { }
}
/// A specialization that does nothing.
#[derive(Clone)]
pub struct DummySpecialization;
impl<B: BlockT> NetworkSpecialization<B> for DummySpecialization {
fn status(&self) -> Vec<u8> {
vec![]
}
fn on_connect(
&mut self,
_ctx: &mut dyn Context<B>,
_peer_id: PeerId,
_status: crate::protocol::message::Status<B>
) {}
fn on_disconnect(&mut self, _ctx: &mut dyn Context<B>, _peer_id: PeerId) {}
fn on_message(
&mut self,
_ctx: &mut dyn Context<B>,
_peer_id: PeerId,
_message: Vec<u8>,
) {}
}
/// Construct a simple protocol that is composed of several sub protocols.
/// Each "sub protocol" needs to implement `Specialization` and needs to provide a `new()` function.
/// For more fine grained implementations, this macro is not usable.
///
/// # Example
///
/// ```nocompile
/// construct_simple_protocol! {
/// pub struct MyProtocol where Block = MyBlock {
/// consensus_gossip: ConsensusGossip<MyBlock>,
/// other_protocol: MyCoolStuff,
/// }
/// }
/// ```
///
/// You can also provide an optional parameter after `where Block = MyBlock`, so it looks like
/// `where Block = MyBlock, Status = consensus_gossip`. This will instruct the implementation to
/// use the `status()` function from the `ConsensusGossip` protocol. By default, `status()` returns
/// an empty vector.
#[macro_export]
macro_rules! construct_simple_protocol {
(
$( #[ $attr:meta ] )*
pub struct $protocol:ident where
Block = $block:ident
$( , Status = $status_protocol_name:ident )*
{
$( $sub_protocol_name:ident : $sub_protocol:ident $( <$protocol_block:ty> )*, )*
}
) => {
$( #[$attr] )*
pub struct $protocol {
$( $sub_protocol_name: $sub_protocol $( <$protocol_block> )*, )*
}
impl $protocol {
/// Instantiate a node protocol handler.
pub fn new() -> Self {
Self {
$( $sub_protocol_name: $sub_protocol::new(), )*
}
}
}
impl $crate::specialization::NetworkSpecialization<$block> for $protocol {
fn status(&self) -> Vec<u8> {
$(
let status = self.$status_protocol_name.status();
if !status.is_empty() {
return status;
}
)*
Vec::new()
}
fn on_connect(
&mut self,
_ctx: &mut $crate::Context<$block>,
_who: $crate::PeerId,
_status: $crate::StatusMessage<$block>
) {
$( self.$sub_protocol_name.on_connect(_ctx, _who, _status); )*
}
fn on_disconnect(&mut self, _ctx: &mut $crate::Context<$block>, _who: $crate::PeerId) {
$( self.$sub_protocol_name.on_disconnect(_ctx, _who); )*
}
fn on_message(
&mut self,
_ctx: &mut $crate::Context<$block>,
_who: $crate::PeerId,
_message: Vec<u8>,
) {
$( self.$sub_protocol_name.on_message(_ctx, _who, _message); )*
}
fn maintain_peers(&mut self, _ctx: &mut $crate::Context<$block>) {
$( self.$sub_protocol_name.maintain_peers(_ctx); )*
}
fn on_block_imported(
&mut self,
_ctx: &mut $crate::Context<$block>,
_hash: <$block as $crate::BlockT>::Hash,
_header: &<$block as $crate::BlockT>::Header
) {
$( self.$sub_protocol_name.on_block_imported(_ctx, _hash, _header); )*
}
}
}
}