hydrabadger/src/lib.rs

481 lines
14 KiB
Rust
Raw Normal View History

2018-08-04 18:54:30 -07:00
#![cfg_attr(feature = "nightly", feature(alloc_system))]
2018-09-10 12:07:53 -07:00
#![cfg_attr(feature = "nightly", feature(proc_macro))]
#![cfg_attr(feature = "cargo-clippy",
allow(large_enum_variant, new_without_default_derive, expect_fun_call, or_fun_call,
useless_format, cyclomatic_complexity, needless_pass_by_value, module_inception,
match_bool))]
2018-06-30 12:00:23 -07:00
2018-08-04 18:54:30 -07:00
#[cfg(feature = "nightly")]
extern crate alloc_system;
2018-06-30 12:00:23 -07:00
extern crate clap;
2018-07-02 19:36:12 -07:00
extern crate env_logger;
2018-08-04 18:54:30 -07:00
#[macro_use]
extern crate log;
#[macro_use]
extern crate failure;
2018-06-30 12:00:23 -07:00
extern crate crossbeam;
// #[macro_use] extern crate crossbeam_channel;
2018-07-02 19:36:12 -07:00
extern crate chrono;
2018-09-28 06:13:31 -07:00
extern crate crypto;
2018-07-02 19:36:12 -07:00
extern crate num_bigint;
2018-09-28 06:13:31 -07:00
extern crate num_traits;
2018-08-04 18:54:30 -07:00
#[macro_use]
extern crate futures;
2018-09-28 06:13:31 -07:00
extern crate byteorder;
extern crate bytes;
extern crate rand;
2018-07-02 19:36:12 -07:00
extern crate tokio;
extern crate tokio_codec;
extern crate tokio_io;
extern crate uuid;
2018-08-04 18:54:30 -07:00
#[macro_use]
extern crate serde_derive;
extern crate bincode;
2018-07-12 15:32:39 -07:00
extern crate clear_on_drop;
extern crate hbbft;
2018-09-28 06:13:31 -07:00
extern crate parking_lot;
extern crate serde;
extern crate serde_bytes;
extern crate tokio_serde_bincode;
2018-06-30 12:00:23 -07:00
2018-08-04 18:54:30 -07:00
#[cfg(feature = "nightly")]
use alloc_system::System;
2018-07-28 15:43:13 -07:00
2018-08-04 18:54:30 -07:00
#[cfg(feature = "nightly")]
#[global_allocator]
static A: System = System;
2018-07-28 15:43:13 -07:00
// pub mod network;
2018-07-02 19:36:12 -07:00
pub mod blockchain;
2018-09-28 06:13:31 -07:00
pub mod hydrabadger;
2018-07-17 14:06:23 -07:00
pub mod peer;
2018-07-02 19:36:12 -07:00
2018-09-28 06:13:31 -07:00
use bytes::{Bytes, BytesMut};
use futures::{sync::mpsc, AsyncSink, StartSend};
use rand::{Rand, Rng};
use serde::{de::DeserializeOwned, Serialize};
2018-07-20 19:07:49 -07:00
use std::{
collections::BTreeMap,
fmt::{self, Debug},
marker::PhantomData,
2018-09-28 06:13:31 -07:00
net::SocketAddr,
ops::Deref,
2018-07-20 19:07:49 -07:00
};
use tokio::{io, net::TcpStream, prelude::*, codec::{Framed, LengthDelimitedCodec}};
2018-07-20 19:07:49 -07:00
use uuid::Uuid;
use hbbft::{
crypto::{PublicKey, PublicKeySet},
2018-10-03 20:14:04 -07:00
dynamic_honey_badger::{JoinPlan, Message as DhbMessage, DynamicHoneyBadger, Input as DhbInput},
2018-09-28 06:13:31 -07:00
sync_key_gen::{Ack, Part},
DaStep as MessagingStep,
2018-10-12 12:51:35 -07:00
Contribution as HbbftContribution,
2018-07-20 19:07:49 -07:00
};
pub use blockchain::{Blockchain, MiningError};
2018-10-23 11:28:29 -07:00
pub use hydrabadger::{Config, Hydrabadger, HydrabadgerWeak};
// TODO: Create a separate, library-wide error type.
2018-09-28 06:13:31 -07:00
pub use hydrabadger::Error;
pub use hbbft::dynamic_honey_badger::Batch;
2018-10-15 15:10:36 -07:00
pub use hydrabadger::StateDsct;
2018-07-20 19:07:49 -07:00
/// Transmit half of the wire message channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
type WireTx<T> = mpsc::UnboundedSender<WireMessage<T>>;
2018-07-20 19:07:49 -07:00
/// Receive half of the wire message channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
type WireRx<T> = mpsc::UnboundedReceiver<WireMessage<T>>;
2018-07-20 19:07:49 -07:00
/// Transmit half of the internal message channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
type InternalTx<T> = mpsc::UnboundedSender<InternalMessage<T>>;
2018-07-20 19:07:49 -07:00
/// Receive half of the internal message channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
type InternalRx<T> = mpsc::UnboundedReceiver<InternalMessage<T>>;
2018-07-20 19:07:49 -07:00
2018-10-02 09:47:11 -07:00
/// Transmit half of the batch output channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
2018-10-03 20:14:04 -07:00
type BatchTx<T> = mpsc::UnboundedSender<Batch<T, Uid>>;
2018-10-02 09:47:11 -07:00
/// Receive half of the batch output channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
2018-10-03 20:14:04 -07:00
pub type BatchRx<T> = mpsc::UnboundedReceiver<Batch<T, Uid>>;
2018-10-02 09:47:11 -07:00
/// Transmit half of the epoch number output channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
type EpochTx = mpsc::UnboundedSender<u64>;
/// Receive half of the epoch number output channel.
// TODO: Use a bounded tx/rx (find a sensible upper bound):
pub type EpochRx = mpsc::UnboundedReceiver<u64>;
2018-09-28 06:13:31 -07:00
pub trait Contribution:
HbbftContribution + Clone + Debug + Serialize + DeserializeOwned + 'static
{
}
impl<C> Contribution for C where
C: HbbftContribution + Clone + Debug + Serialize + DeserializeOwned + 'static
{}
2018-07-20 19:07:49 -07:00
/// A unique identifier.
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Uid(pub(crate) Uuid);
impl Uid {
/// Returns a new, random `Uid`.
pub fn new() -> Uid {
Uid(Uuid::new_v4())
}
}
impl Rand for Uid {
fn rand<R: Rng>(_rng: &mut R) -> Uid {
Uid::new()
}
}
impl fmt::Display for Uid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&self.0, f)
}
}
impl fmt::Debug for Uid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&self.0, f)
}
}
type Message = DhbMessage<Uid>;
2018-10-03 20:14:04 -07:00
type Step<T> = MessagingStep<DynamicHoneyBadger<T, Uid>>;
type Input<T> = DhbInput<T, Uid>;
2018-07-20 19:07:49 -07:00
/// A peer's incoming (listening) address.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct InAddr(pub SocketAddr);
impl Deref for InAddr {
type Target = SocketAddr;
fn deref(&self) -> &SocketAddr {
&self.0
}
}
impl fmt::Display for InAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "InAddr({})", self.0)
}
}
/// An internal address used to respond to a connected peer.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct OutAddr(pub SocketAddr);
impl Deref for OutAddr {
type Target = SocketAddr;
fn deref(&self) -> &SocketAddr {
&self.0
}
}
impl fmt::Display for OutAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "OutAddr({})", self.0)
}
}
/// Nodes of the network.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NetworkNodeInfo {
pub(crate) uid: Uid,
pub(crate) in_addr: InAddr,
pub(crate) pk: PublicKey,
}
/// The current state of the network.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum NetworkState {
None,
Unknown(Vec<NetworkNodeInfo>),
2018-07-23 16:01:27 -07:00
AwaitingMorePeersForKeyGeneration(Vec<NetworkNodeInfo>),
GeneratingKeys(Vec<NetworkNodeInfo>, BTreeMap<Uid, PublicKey>),
Active((Vec<NetworkNodeInfo>, PublicKeySet, BTreeMap<Uid, PublicKey>)),
2018-07-20 19:07:49 -07:00
}
/// Messages sent over the network between nodes.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum WireMessageKind<T> {
2018-07-20 19:07:49 -07:00
HelloFromValidator(Uid, InAddr, PublicKey, NetworkState),
HelloRequestChangeAdd(Uid, InAddr, PublicKey),
WelcomeReceivedChangeAdd(Uid, PublicKey, NetworkState),
RequestNetworkState,
NetworkState(NetworkState),
Goodbye,
#[serde(with = "serde_bytes")]
Bytes(Bytes),
2018-07-23 12:01:13 -07:00
Message(Uid, Message),
2018-10-03 20:14:04 -07:00
Transaction(Uid, T),
2018-07-20 19:07:49 -07:00
KeyGenPart(Part),
KeyGenAck(Ack),
2018-09-28 06:13:31 -07:00
JoinPlan(JoinPlan<Uid>), // TargetedMessage(TargetedMessage<Uid>)
2018-07-20 19:07:49 -07:00
}
/// Messages sent over the network between nodes.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WireMessage<T> {
kind: WireMessageKind<T>,
2018-07-20 19:07:49 -07:00
}
impl<T: Contribution> WireMessage<T> {
2018-09-28 06:13:31 -07:00
pub fn hello_from_validator(
src_uid: Uid,
in_addr: InAddr,
pk: PublicKey,
net_state: NetworkState,
) -> WireMessage<T> {
2018-07-23 12:01:13 -07:00
WireMessageKind::HelloFromValidator(src_uid, in_addr, pk, net_state).into()
2018-07-20 19:07:49 -07:00
}
/// Returns a `HelloRequestChangeAdd` variant.
2018-09-28 06:13:31 -07:00
pub fn hello_request_change_add(
src_uid: Uid,
in_addr: InAddr,
pk: PublicKey,
) -> WireMessage<T> {
WireMessage {
kind: WireMessageKind::HelloRequestChangeAdd(src_uid, in_addr, pk),
}
2018-07-20 19:07:49 -07:00
}
/// Returns a `WelcomeReceivedChangeAdd` variant.
2018-09-28 06:13:31 -07:00
pub fn welcome_received_change_add(
src_uid: Uid,
pk: PublicKey,
net_state: NetworkState,
) -> WireMessage<T> {
WireMessage {
kind: WireMessageKind::WelcomeReceivedChangeAdd(src_uid, pk, net_state),
}
2018-07-20 19:07:49 -07:00
}
2018-07-23 12:34:08 -07:00
/// Returns an `Input` variant.
2018-10-03 20:14:04 -07:00
pub fn transaction(src_uid: Uid, txn: T) -> WireMessage<T> {
2018-09-28 06:13:31 -07:00
WireMessage {
2018-10-03 20:14:04 -07:00
kind: WireMessageKind::Transaction(src_uid, txn),
2018-09-28 06:13:31 -07:00
}
2018-07-23 12:34:08 -07:00
}
/// Returns a `Message` variant.
pub fn message(src_uid: Uid, msg: Message) -> WireMessage<T> {
2018-09-28 06:13:31 -07:00
WireMessage {
kind: WireMessageKind::Message(src_uid, msg),
}
}
pub fn key_gen_part(part: Part) -> WireMessage<T> {
2018-09-28 06:13:31 -07:00
WireMessage {
kind: WireMessageKind::KeyGenPart(part),
}
2018-07-20 19:07:49 -07:00
}
pub fn key_gen_part_ack(outcome: Ack) -> WireMessage<T> {
WireMessageKind::KeyGenAck(outcome).into()
2018-07-20 19:07:49 -07:00
}
pub fn join_plan(jp: JoinPlan<Uid>) -> WireMessage<T> {
WireMessageKind::JoinPlan(jp).into()
2018-07-20 19:07:49 -07:00
}
/// Returns the wire message kind.
pub fn kind(&self) -> &WireMessageKind<T> {
2018-07-20 19:07:49 -07:00
&self.kind
}
/// Consumes this `WireMessage` into its kind.
pub fn into_kind(self) -> WireMessageKind<T> {
2018-07-20 19:07:49 -07:00
self.kind
}
}
impl<T: Contribution> From<WireMessageKind<T>> for WireMessage<T> {
fn from(kind: WireMessageKind<T>) -> WireMessage<T> {
2018-07-20 19:07:49 -07:00
WireMessage { kind }
}
}
/// A stream/sink of `WireMessage`s connected to a socket.
#[derive(Debug)]
pub struct WireMessages<T> {
framed: Framed<TcpStream, LengthDelimitedCodec>,
_t: PhantomData<T>,
2018-07-20 19:07:49 -07:00
}
impl<T: Contribution> WireMessages<T> {
pub fn new(socket: TcpStream) -> WireMessages<T> {
2018-07-20 19:07:49 -07:00
WireMessages {
framed: Framed::new(socket, LengthDelimitedCodec::new()),
_t: PhantomData,
2018-07-20 19:07:49 -07:00
}
}
pub fn socket(&self) -> &TcpStream {
self.framed.get_ref()
}
pub fn send_msg(&mut self, msg: WireMessage<T>) -> Result<(), Error> {
2018-07-20 19:07:49 -07:00
self.start_send(msg)?;
let _ = self.poll_complete()?;
Ok(())
}
}
impl<T: Contribution> Stream for WireMessages<T> {
type Item = WireMessage<T>;
2018-07-20 19:07:49 -07:00
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match try_ready!(self.framed.poll()) {
Some(frame) => {
Ok(Async::Ready(Some(
// deserialize_from(frame.reader()).map_err(Error::Serde)?
2018-09-28 06:13:31 -07:00
bincode::deserialize(&frame.freeze()).map_err(Error::Serde)?,
2018-07-20 19:07:49 -07:00
)))
}
2018-09-28 06:13:31 -07:00
None => Ok(Async::Ready(None)),
2018-07-20 19:07:49 -07:00
}
}
}
impl<T: Contribution> Sink for WireMessages<T> {
type SinkItem = WireMessage<T>;
2018-07-20 19:07:49 -07:00
type SinkError = Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
// TODO: Reuse buffer:
let mut serialized = BytesMut::new();
2018-08-03 06:35:15 -07:00
// Downgraded from bincode 1.0:
//
// Original: `bincode::serialize(&item)`
//
2018-10-04 07:08:29 -07:00
match bincode::serialize(&item) {
2018-07-20 19:07:49 -07:00
Ok(s) => serialized.extend_from_slice(&s),
Err(err) => return Err(Error::Io(io::Error::new(io::ErrorKind::Other, err))),
}
match self.framed.start_send(serialized.freeze()) {
2018-07-20 19:07:49 -07:00
Ok(async_sink) => match async_sink {
AsyncSink::Ready => Ok(AsyncSink::Ready),
AsyncSink::NotReady(_) => Ok(AsyncSink::NotReady(item)),
},
2018-09-28 06:13:31 -07:00
Err(err) => Err(Error::Io(err)),
2018-07-20 19:07:49 -07:00
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
self.framed.poll_complete().map_err(Error::from)
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
self.framed.close().map_err(Error::from)
}
}
/// A message between internal threads/tasks.
#[derive(Clone, Debug)]
pub enum InternalMessageKind<T: Contribution> {
Wire(WireMessage<T>),
2018-07-20 19:07:49 -07:00
HbMessage(Message),
HbInput(Input<T>),
2018-07-20 19:07:49 -07:00
PeerDisconnect,
NewIncomingConnection(InAddr, PublicKey, bool),
2018-07-20 19:07:49 -07:00
NewOutgoingConnection,
}
/// A message between internal threads/tasks.
#[derive(Clone, Debug)]
pub struct InternalMessage<T: Contribution> {
2018-07-20 19:07:49 -07:00
src_uid: Option<Uid>,
src_addr: OutAddr,
kind: InternalMessageKind<T>,
2018-07-20 19:07:49 -07:00
}
impl<T: Contribution> InternalMessage<T> {
2018-09-28 06:13:31 -07:00
pub fn new(
src_uid: Option<Uid>,
src_addr: OutAddr,
kind: InternalMessageKind<T>,
) -> InternalMessage<T> {
InternalMessage {
src_uid,
src_addr,
kind,
}
2018-07-20 19:07:49 -07:00
}
/// Returns a new `InternalMessage` without a uid.
pub fn new_without_uid(src_addr: OutAddr, kind: InternalMessageKind<T>) -> InternalMessage<T> {
2018-07-20 19:07:49 -07:00
InternalMessage::new(None, src_addr, kind)
}
2018-09-28 06:13:31 -07:00
pub fn wire(
src_uid: Option<Uid>,
src_addr: OutAddr,
wire_message: WireMessage<T>,
) -> InternalMessage<T> {
2018-07-20 19:07:49 -07:00
InternalMessage::new(src_uid, src_addr, InternalMessageKind::Wire(wire_message))
}
pub fn hb_message(src_uid: Uid, src_addr: OutAddr, msg: Message) -> InternalMessage<T> {
2018-07-20 19:07:49 -07:00
InternalMessage::new(Some(src_uid), src_addr, InternalMessageKind::HbMessage(msg))
}
pub fn hb_input(src_uid: Uid, src_addr: OutAddr, input: Input<T>) -> InternalMessage<T> {
2018-07-20 19:07:49 -07:00
InternalMessage::new(Some(src_uid), src_addr, InternalMessageKind::HbInput(input))
}
pub fn peer_disconnect(src_uid: Uid, src_addr: OutAddr) -> InternalMessage<T> {
2018-07-20 19:07:49 -07:00
InternalMessage::new(Some(src_uid), src_addr, InternalMessageKind::PeerDisconnect)
}
2018-09-28 06:13:31 -07:00
pub fn new_incoming_connection(
src_uid: Uid,
src_addr: OutAddr,
src_in_addr: InAddr,
src_pk: PublicKey,
request_change_add: bool,
) -> InternalMessage<T> {
InternalMessage::new(
Some(src_uid),
src_addr,
InternalMessageKind::NewIncomingConnection(src_in_addr, src_pk, request_change_add),
)
2018-07-20 19:07:49 -07:00
}
pub fn new_outgoing_connection(src_addr: OutAddr) -> InternalMessage<T> {
2018-07-20 19:07:49 -07:00
InternalMessage::new_without_uid(src_addr, InternalMessageKind::NewOutgoingConnection)
}
/// Returns the source unique identifier this message was received in.
pub fn src_uid(&self) -> Option<&Uid> {
self.src_uid.as_ref()
}
/// Returns the source socket this message was received on.
pub fn src_addr(&self) -> &OutAddr {
&self.src_addr
}
/// Returns the internal message kind.
pub fn kind(&self) -> &InternalMessageKind<T> {
2018-07-20 19:07:49 -07:00
&self.kind
}
/// Consumes this `InternalMessage` into its parts.
pub fn into_parts(self) -> (Option<Uid>, OutAddr, InternalMessageKind<T>) {
2018-07-20 19:07:49 -07:00
(self.src_uid, self.src_addr, self.kind)
}
}