Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
No Multiaddress requirement for substrate network
  • Loading branch information
timorl committed Nov 11, 2022
commit 4018aee5edb18bf9f2669707d2c0c8499a85760f
4 changes: 2 additions & 2 deletions finality-aleph/src/network/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ impl<T> Default for Channel<T> {
}
}

pub type MockEvent = Event<MockMultiaddress>;
pub type MockEvent = Event<MockMultiaddress, MockPeerId>;

pub type MockData = Vec<u8>;
type MessageForUser<D, M> = (NetworkData<D, M>, DataCommand<<M as Multiaddress>::PeerId>);
Expand Down Expand Up @@ -183,7 +183,7 @@ impl<M: Multiaddress + 'static> MockIO<M> {
pub struct MockEventStream(mpsc::UnboundedReceiver<MockEvent>);

#[async_trait]
impl EventStream<MockMultiaddress> for MockEventStream {
impl EventStream<MockMultiaddress, MockPeerId> for MockEventStream {
async fn next_event(&mut self) -> Option<MockEvent> {
self.0.next().await
}
Expand Down
18 changes: 9 additions & 9 deletions finality-aleph/src/network/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,26 +89,26 @@ pub trait NetworkSender: Send + Sync + 'static {
}

#[derive(Clone)]
pub enum Event<M: Multiaddress> {
pub enum Event<M, P> {
Connected(M),
Disconnected(M::PeerId),
StreamOpened(M::PeerId, Protocol),
StreamClosed(M::PeerId, Protocol),
Disconnected(P),
StreamOpened(P, Protocol),
StreamClosed(P, Protocol),
Messages(Vec<(Protocol, Bytes)>),
}

#[async_trait]
pub trait EventStream<M: Multiaddress> {
async fn next_event(&mut self) -> Option<Event<M>>;
pub trait EventStream<M, P> {
async fn next_event(&mut self) -> Option<Event<M, P>>;
}

/// Abstraction over a network.
pub trait Network: Clone + Send + Sync + 'static {
type SenderError: std::error::Error;
type NetworkSender: NetworkSender;
type PeerId: PeerId;
type Multiaddress: Multiaddress<PeerId = Self::PeerId>;
type EventStream: EventStream<Self::Multiaddress>;
type PeerId: Clone + Debug + Eq + Hash + Send;
type Multiaddress: Debug + Eq + Hash;
type EventStream: EventStream<Self::Multiaddress, Self::PeerId>;

/// Returns a stream of events representing what happens on the network.
fn event_stream(&self) -> Self::EventStream;
Expand Down
2 changes: 1 addition & 1 deletion finality-aleph/src/network/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ impl<

fn handle_network_event(
&mut self,
event: Event<N::Multiaddress>,
event: Event<N::Multiaddress, N::PeerId>,
) -> Result<(), mpsc::TrySendError<NetworkData<D, A>>> {
use Event::*;
match event {
Expand Down
135 changes: 3 additions & 132 deletions finality-aleph/src/substrate_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ use sp_consensus::SyncOracle;
use sp_runtime::traits::Block;

use crate::network::{
Event, EventStream, Multiaddress as MultiaddressT, Network, NetworkSender,
PeerId as PeerIdT, Protocol, RequestBlocks,
Event, EventStream, Network, NetworkSender, Protocol, RequestBlocks,
};

impl<B: Block, H: ExHashT> RequestBlocks<B> for Arc<NetworkService<B, H>> {
Expand Down Expand Up @@ -80,19 +79,6 @@ impl fmt::Display for PeerId {
}
}

impl PeerIdT for PeerId {}

fn peer_id(protocol: &MultiaddressProtocol<'_>) -> Option<PeerId> {
match protocol {
MultiaddressProtocol::P2p(hashed_peer_id) => {
SubstratePeerId::from_multihash(*hashed_peer_id)
.ok()
.map(PeerId)
}
_ => None,
}
}

/// A wrapper for the Substrate multiaddress to allow encoding & decoding.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Multiaddress(Multiaddr);
Expand Down Expand Up @@ -124,66 +110,6 @@ impl Decode for Multiaddress {
}
}

enum CommonPeerId {
Unknown,
Unique(PeerId),
NotUnique,
}

impl From<CommonPeerId> for Option<PeerId> {
fn from(cpi: CommonPeerId) -> Self {
use CommonPeerId::*;
match cpi {
Unique(peer_id) => Some(peer_id),
Unknown | NotUnique => None,
}
}
}

impl CommonPeerId {
fn aggregate(self, peer_id: PeerId) -> Self {
use CommonPeerId::*;
match self {
Unknown => Unique(peer_id),
Unique(current_peer_id) => match peer_id == current_peer_id {
true => Unique(current_peer_id),
false => NotUnique,
},
NotUnique => NotUnique,
}
}
}

impl MultiaddressT for Multiaddress {
type PeerId = PeerId;

fn get_peer_id(&self) -> Option<Self::PeerId> {
self.0
.iter()
.fold(
CommonPeerId::Unknown,
|common_peer_id, protocol| match peer_id(&protocol) {
Some(peer_id) => common_peer_id.aggregate(peer_id),
None => common_peer_id,
},
)
.into()
}

fn add_matching_peer_id(mut self, peer_id: Self::PeerId) -> Option<Self> {
match self.get_peer_id() {
Some(peer) => match peer == peer_id {
true => Some(self),
false => None,
},
None => {
self.0.push(MultiaddressProtocol::P2p(peer_id.0.into()));
Some(self)
}
}
}
}

/// Name of the network protocol used by Aleph Zero. This is how messages
/// are subscribed to ensure that we are gossiping and communicating with our
/// own network.
Expand Down Expand Up @@ -267,8 +193,8 @@ impl NetworkSender for SubstrateNetworkSender {
type NetworkEventStream = Pin<Box<dyn Stream<Item = SubstrateEvent> + Send>>;

#[async_trait]
impl EventStream<Multiaddress> for NetworkEventStream {
async fn next_event(&mut self) -> Option<Event<Multiaddress>> {
impl EventStream<Multiaddress, PeerId> for NetworkEventStream {
async fn next_event(&mut self) -> Option<Event<Multiaddress, PeerId>> {
use Event::*;
use SubstrateEvent::*;
loop {
Expand Down Expand Up @@ -364,66 +290,11 @@ mod tests {
use codec::{Decode, Encode};

use super::Multiaddress;
use crate::network::Multiaddress as _;

fn address(text: &str) -> Multiaddress {
Multiaddress(text.parse().unwrap())
}

#[test]
fn non_p2p_addresses_are_not_p2p() {
assert!(address("/dns4/example.com/udt/sctp/5678")
.get_peer_id()
.is_none());
}

#[test]
fn p2p_addresses_are_p2p() {
assert!(address(
"/dns4/example.com/tcp/30333/p2p/12D3KooWRkGLz4YbVmrsWK75VjFTs8NvaBu42xhAmQaP4KeJpw1L"
)
.get_peer_id()
.is_some());
}

#[test]
fn non_p2p_address_matches_peer_id() {
let address = address(
"/dns4/example.com/tcp/30333/p2p/12D3KooWRkGLz4YbVmrsWK75VjFTs8NvaBu42xhAmQaP4KeJpw1L",
);
let peer_id = address.get_peer_id().unwrap();
let mut peerless_address = address.clone().0;
peerless_address.pop();
let peerless_address = Multiaddress(peerless_address);
assert!(peerless_address.get_peer_id().is_none());
assert_eq!(
peerless_address.add_matching_peer_id(peer_id),
Some(address),
);
}

#[test]
fn p2p_address_matches_own_peer_id() {
let address = address(
"/dns4/example.com/tcp/30333/p2p/12D3KooWRkGLz4YbVmrsWK75VjFTs8NvaBu42xhAmQaP4KeJpw1L",
);
let peer_id = address.get_peer_id().unwrap();
let expected_address = address.clone();
assert_eq!(
address.add_matching_peer_id(peer_id),
Some(expected_address),
);
}

#[test]
fn p2p_address_does_not_match_other_peer_id() {
let nonmatching_address = address(
"/dns4/example.com/tcp/30333/p2p/12D3KooWRkGLz4YbVmrsWK75VjFTs8NvaBu42xhAmQaP4KeJpw1L",
);
let peer_id = address("/dns4/peer.example.com/tcp/30333/p2p/12D3KooWFVXnvJdPuGnGYMPn5qLQAQYwmRBgo6SmEQsKZSrDoo2k").get_peer_id().unwrap();
assert!(nonmatching_address.add_matching_peer_id(peer_id).is_none());
}

#[test]
fn multiaddr_encode_decode() {
let multiaddr: Multiaddress = address(
Expand Down