Skip to content

Commit

Permalink
Refactor protocol into internal, external modules.
Browse files Browse the repository at this point in the history
This commit just moves things around and patches import paths.
  • Loading branch information
hdevalence authored and dconnolly committed Nov 27, 2019
1 parent 8a9a5ba commit 6db852f
Show file tree
Hide file tree
Showing 16 changed files with 137 additions and 126 deletions.
2 changes: 1 addition & 1 deletion zebra-network/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::time::Duration;

// XXX should these constants be split into protocol also?
use crate::protocol::types::*;
use crate::protocol::external::types::*;

/// The timeout for requests made to a remote peer.
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
Expand Down
2 changes: 1 addition & 1 deletion zebra-network/src/network.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{constants::magics, protocol::types::Magic};
use crate::{constants::magics, protocol::external::types::Magic};

/// An enum describing the possible network choices.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
Expand Down
2 changes: 1 addition & 1 deletion zebra-network/src/peer/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ where
let client = hs.call((stream, addr)).await?;
Ok(Change::Insert(addr, client))
}
.boxed()
.boxed()
}
}
2 changes: 1 addition & 1 deletion zebra-network/src/peer/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl ErrorSlot {
pub enum HandshakeError {
/// The remote peer sent an unexpected message during the handshake.
#[error("The remote peer sent an unexpected message: {0:?}")]
UnexpectedMessage(crate::protocol::message::Message),
UnexpectedMessage(crate::protocol::external::Message),
/// The peer connector detected handshake nonce reuse, possibly indicating self-connection.
#[error("Detected nonce reuse, possible self-connection")]
NonceReuse,
Expand Down
5 changes: 4 additions & 1 deletion zebra-network/src/peer/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ use zebra_chain::types::BlockHeight;

use crate::{
constants,
protocol::{codec::*, internal::*, message::*, types::*},
protocol::{
external::{types::*, Codec, Message},
internal::{Request, Response},
},
types::MetaAddr,
BoxedStdError, Config,
};
Expand Down
3 changes: 1 addition & 2 deletions zebra-network/src/peer/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ use zebra_chain::{serialization::SerializationError, transaction::TransactionHas
use crate::{
constants,
protocol::{
external::{InventoryHash, Message},
internal::{Request, Response},
inv::InventoryHash,
message::Message,
},
BoxedStdError,
};
Expand Down
16 changes: 5 additions & 11 deletions zebra-network/src/protocol.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
//! Zcash network protocol handling.
pub mod codec;
pub mod message;
pub mod types;

pub mod inv;

// XXX at some later point the above should move to an `external` submodule, so
// that we have
// - protocol::external::{all_bitcoin_zcash_types};
// - protocol::internal::{all_internal_req_rsp_types};

/// The external Bitcoin-based protocol.
pub mod external;
/// The internal request/response protocol.
pub mod internal;
/// Newtype wrappers giving semantic meaning to primitive datatypes.
pub mod types;
12 changes: 12 additions & 0 deletions zebra-network/src/protocol/external.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// A Tokio codec that transforms an `AsyncRead` into a `Stream` of `Message`s.
mod codec;
/// Inventory items.
mod inv;
/// An enum of all supported Bitcoin message types.
mod message;
/// Newtype wrappers for primitive types.
pub mod types;

pub use codec::Codec;
pub use inv::InventoryHash;
pub use message::Message;
File renamed without changes.
File renamed without changes.
File renamed without changes.
55 changes: 55 additions & 0 deletions zebra-network/src/protocol/external/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use hex;
use std::fmt;

/// A magic number identifying the network.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Magic(pub [u8; 4]);

impl fmt::Debug for Magic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Magic").field(&hex::encode(&self.0)).finish()
}
}

/// A protocol version number.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Version(pub u32);

bitflags! {
/// A bitflag describing services advertised by a node in the network.
///
/// Note that bits 24-31 are reserved for temporary experiments; other
/// service bits should be allocated via the ZIP process.
#[derive(Default)]
pub struct PeerServices: u64 {
/// NODE_NETWORK means that the node is a full node capable of serving
/// blocks, as opposed to a light client that makes network requests but
/// does not provide network services.
const NODE_NETWORK = (1 << 0);
/// NODE_BLOOM means that the node supports bloom-filtered connections.
const NODE_BLOOM = (1 << 2);
}
}

/// A nonce used in the networking layer to identify messages.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Nonce(pub u64);

impl Default for Nonce {
fn default() -> Self {
use rand::{thread_rng, Rng};
Self(thread_rng().gen())
}
}

#[cfg(test)]
mod tests {

use crate::constants::magics;

#[test]
fn magic_debug() {
assert_eq!(format!("{:?}", magics::MAINNET), "Magic(\"24e92764\")");
assert_eq!(format!("{:?}", magics::TESTNET), "Magic(\"fa1af9bf\")");
}
}
55 changes: 4 additions & 51 deletions zebra-network/src/protocol/internal.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,5 @@
//! Message types for the internal request/response protocol.
//!
//! These are currently defined just as enums with all possible requests and
//! responses, so that we have unified types to pass around. No serialization
//! is performed as these are only internal types.
mod request;
mod response;

use std::error::Error;

use zebra_chain::transaction::Transaction;

use crate::meta_addr::MetaAddr;

use super::types::Nonce;

/// A network request, represented in internal format.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Request {
/// Requests additional peers from the server.
GetPeers,
/// Advertises peers to the remote server.
PushPeers(Vec<MetaAddr>),
/// Heartbeats triggered on peer connection start.
// This is included as a bit of a hack, it should only be used
// internally for connection management. You should not expect to
// be firing or handling `Ping` requests or `Pong` responses.
Ping(Nonce),
/// Requests the transactions the remote server has verified but
/// not yet confirmed.
GetMempool,
}

/// A response to a network request, represented in internal format.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Response {
/// Generic success.
Ok,
/// Generic error.
Error,
/// A list of peers, used to respond to `GetPeers`.
Peers(Vec<MetaAddr>),
/// A list of transactions, such as in response to `GetMempool`.
Transactions(Vec<Transaction>),
}

impl<E> From<E> for Response
where
E: Error,
{
fn from(_e: E) -> Self {
Self::Error
}
}
pub use request::Request;
pub use response::Response;
20 changes: 20 additions & 0 deletions zebra-network/src/protocol/internal/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use crate::meta_addr::MetaAddr;

use super::super::types::Nonce;

/// A network request, represented in internal format.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Request {
/// Requests additional peers from the server.
GetPeers,
/// Advertises peers to the remote server.
PushPeers(Vec<MetaAddr>),
/// Heartbeats triggered on peer connection start.
// This is included as a bit of a hack, it should only be used
// internally for connection management. You should not expect to
// be firing or handling `Ping` requests or `Pong` responses.
Ping(Nonce),
/// Requests the transactions the remote server has verified but
/// not yet confirmed.
GetMempool,
}
28 changes: 28 additions & 0 deletions zebra-network/src/protocol/internal/response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::error::Error;

// XXX clean module layout of zebra_chain
use zebra_chain::transaction::Transaction;

use crate::meta_addr::MetaAddr;

/// A response to a network request, represented in internal format.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Response {
/// Generic success.
Ok,
/// Generic error.
Error,
/// A list of peers, used to respond to `GetPeers`.
Peers(Vec<MetaAddr>),
/// A list of transactions, such as in response to `GetMempool`.
Transactions(Vec<Transaction>),
}

impl<E> From<E> for Response
where
E: Error,
{
fn from(_e: E) -> Self {
Self::Error
}
}
61 changes: 4 additions & 57 deletions zebra-network/src/protocol/types.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,4 @@
//! Newtype wrappers assigning semantic meaning to primitive types.
use hex;
use std::fmt;

/// A magic number identifying the network.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Magic(pub [u8; 4]);

impl fmt::Debug for Magic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Magic").field(&hex::encode(&self.0)).finish()
}
}

/// A protocol version number.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Version(pub u32);

bitflags! {
/// A bitflag describing services advertised by a node in the network.
///
/// Note that bits 24-31 are reserved for temporary experiments; other
/// service bits should be allocated via the ZIP process.
#[derive(Default)]
pub struct PeerServices: u64 {
/// NODE_NETWORK means that the node is a full node capable of serving
/// blocks, as opposed to a light client that makes network requests but
/// does not provide network services.
const NODE_NETWORK = (1 << 0);
/// NODE_BLOOM means that the node supports bloom-filtered connections.
const NODE_BLOOM = (1 << 2);
}
}

/// A nonce used in the networking layer to identify messages.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Nonce(pub u64);

impl Default for Nonce {
fn default() -> Self {
use rand::{thread_rng, Rng};
Self(thread_rng().gen())
}
}

#[cfg(test)]
mod tests {

use crate::constants::magics;

#[test]
fn magic_debug() {
assert_eq!(format!("{:?}", magics::MAINNET), "Magic(\"24e92764\")");
assert_eq!(format!("{:?}", magics::TESTNET), "Magic(\"fa1af9bf\")");
}
}
// Because of the `ping` hack, `Nonce` is included in `Request`s.
pub use super::external::types::Nonce;
// The services flag is used in `MetaAddr`s.
pub use super::external::types::PeerServices;

0 comments on commit 6db852f

Please sign in to comment.