Rename uid to id.

This commit is contained in:
Andreas Fackler 2018-08-29 18:08:35 +02:00 committed by Andreas Fackler
parent f27eed4eef
commit 7276621397
30 changed files with 347 additions and 353 deletions

View File

@ -65,7 +65,7 @@ struct Args {
/// A node identifier. In the simulation, nodes are simply numbered.
#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, Rand)]
pub struct NodeUid(pub usize);
pub struct NodeId(pub usize);
/// A transaction.
#[derive(Serialize, Deserialize, Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)]
@ -81,8 +81,8 @@ impl Transaction {
#[derive(Eq, PartialEq, Debug)]
struct TimestampedMessage<D: DistAlgorithm> {
time: Duration,
sender_id: D::NodeUid,
target: Target<D::NodeUid>,
sender_id: D::NodeId,
target: Target<D::NodeId>,
message: Vec<u8>,
}
@ -116,7 +116,7 @@ pub struct HwQuality {
/// A "node" running an instance of the algorithm `D`.
pub struct TestNode<D: DistAlgorithm> {
/// This node's own ID.
id: D::NodeUid,
id: D::NodeId,
/// The instance of the broadcast algorithm.
algo: D,
/// The duration for which this node's CPU has already been simulated.
@ -251,10 +251,10 @@ where
/// A collection of `TestNode`s representing a network.
pub struct TestNetwork<D: DistAlgorithm> {
nodes: BTreeMap<D::NodeUid, TestNode<D>>,
nodes: BTreeMap<D::NodeId, TestNode<D>>,
}
impl<D: DistAlgorithm<NodeUid = NodeUid>> TestNetwork<D>
impl<D: DistAlgorithm<NodeId = NodeId>> TestNetwork<D>
where
D::Message: Serialize + DeserializeOwned + Clone,
{
@ -266,13 +266,13 @@ where
hw_quality: HwQuality,
) -> TestNetwork<D>
where
F: Fn(NetworkInfo<NodeUid>) -> (D, Step<D>),
F: Fn(NetworkInfo<NodeId>) -> (D, Step<D>),
{
let node_ids = (0..(good_num + adv_num)).map(NodeUid);
let node_ids = (0..(good_num + adv_num)).map(NodeId);
let netinfos =
NetworkInfo::generate_map(node_ids).expect("Failed to create `NetworkInfo` map");
let new_node = |(uid, netinfo): (NodeUid, NetworkInfo<_>)| {
(uid, TestNode::new(new_algo(netinfo), hw_quality))
let new_node = |(id, netinfo): (NodeId, NetworkInfo<_>)| {
(id, TestNode::new(new_algo(netinfo), hw_quality))
};
let mut network = TestNetwork {
nodes: netinfos.into_iter().map(new_node).collect(),
@ -311,13 +311,13 @@ where
/// Handles a queued message in one of the nodes with the earliest timestamp, if any. Returns
/// the recipient's ID.
pub fn step(&mut self) -> Option<NodeUid> {
pub fn step(&mut self) -> Option<NodeId> {
let min_time = self
.nodes
.values()
.filter_map(TestNode::next_event_time)
.min()?;
let min_ids: Vec<NodeUid> = self
let min_ids: Vec<NodeId> = self
.nodes
.iter()
.filter(|(_, node)| node.next_event_time() == Some(min_time))
@ -347,17 +347,17 @@ where
/// The timestamped batches for a particular epoch that have already been output.
#[derive(Clone, Default)]
struct EpochInfo {
nodes: BTreeMap<NodeUid, (Duration, Batch<Transaction, NodeUid>)>,
nodes: BTreeMap<NodeId, (Duration, Batch<Transaction, NodeId>)>,
}
impl EpochInfo {
/// Adds a batch to this epoch. Prints information if the epoch is complete.
fn add(
&mut self,
id: NodeUid,
id: NodeId,
time: Duration,
batch: &Batch<Transaction, NodeUid>,
network: &TestNetwork<QueueingHoneyBadger<Transaction, NodeUid>>,
batch: &Batch<Transaction, NodeId>,
network: &TestNetwork<QueueingHoneyBadger<Transaction, NodeId>>,
) {
if self.nodes.contains_key(&id) {
return;
@ -388,7 +388,7 @@ impl EpochInfo {
}
/// Proposes `num_txs` values and expects nodes to output and order them.
fn simulate_honey_badger(mut network: TestNetwork<QueueingHoneyBadger<Transaction, NodeUid>>) {
fn simulate_honey_badger(mut network: TestNetwork<QueueingHoneyBadger<Transaction, NodeId>>) {
// Handle messages until all nodes have output all transactions.
println!(
"{}",
@ -436,7 +436,7 @@ fn main() {
let txs: Vec<_> = (0..args.flag_txs)
.map(|_| Transaction::new(args.flag_tx_size))
.collect();
let new_honey_badger = |netinfo: NetworkInfo<NodeUid>| {
let new_honey_badger = |netinfo: NetworkInfo<NodeId>| {
let dyn_hb = DynamicHoneyBadger::builder().build(netinfo);
QueueingHoneyBadger::builder(dyn_hb)
.batch_size(args.flag_b)

View File

@ -9,7 +9,7 @@ use super::{AgreementContent, Error, Message, Nonce, Result, Step};
use agreement::bool_set::BoolSet;
use coin::{self, Coin, CoinMessage};
use messaging::{DistAlgorithm, NetworkInfo, Target};
use traits::NodeUidT;
use traits::NodeIdT;
/// The state of the current epoch's coin. In some epochs this is fixed, in others it starts
/// with in `InProgress`.
@ -72,8 +72,8 @@ pub struct Agreement<N> {
coin_state: CoinState<N>,
}
impl<N: NodeUidT> DistAlgorithm for Agreement<N> {
type NodeUid = N;
impl<N: NodeIdT> DistAlgorithm for Agreement<N> {
type NodeId = N;
type Input = bool;
type Output = bool;
type Message = Message;
@ -84,7 +84,7 @@ impl<N: NodeUidT> DistAlgorithm for Agreement<N> {
}
/// Receive input from a remote node.
fn handle_message(&mut self, sender_id: &Self::NodeUid, msg: Message) -> Result<Step<N>> {
fn handle_message(&mut self, sender_id: &Self::NodeId, msg: Message) -> Result<Step<N>> {
let Message { epoch, content } = msg;
if self.decision.is_some() || (epoch < self.epoch && content.can_expire()) {
// Message is obsolete: We are already in a later epoch or terminated.
@ -104,12 +104,12 @@ impl<N: NodeUidT> DistAlgorithm for Agreement<N> {
self.decision.is_some()
}
fn our_id(&self) -> &Self::NodeUid {
self.netinfo.our_uid()
fn our_id(&self) -> &Self::NodeId {
self.netinfo.our_id()
}
}
impl<N: NodeUidT> Agreement<N> {
impl<N: NodeIdT> Agreement<N> {
pub fn new(netinfo: Arc<NetworkInfo<N>>, session_id: u64, proposer_id: N) -> Result<Self> {
if !netinfo.is_node_validator(&proposer_id) {
return Err(Error::UnknownProposer);
@ -261,8 +261,8 @@ impl<N: NodeUidT> Agreement<N> {
let mut step: Step<_> = Target::All
.message(content.clone().with_epoch(self.epoch))
.into();
let our_uid = &self.netinfo.our_uid().clone();
step.extend(self.handle_message_content(our_uid, content)?);
let our_id = &self.netinfo.our_id().clone();
step.extend(self.handle_message_content(our_id, content)?);
Ok(step)
}
@ -336,7 +336,7 @@ impl<N: NodeUidT> Agreement<N> {
self.decision = Some(b);
debug!(
"{:?}/{:?} (is_validator: {}) decision: {}",
self.netinfo.our_uid(),
self.netinfo.our_id(),
self.proposer_id,
self.netinfo.is_validator(),
b
@ -384,7 +384,7 @@ impl<N: NodeUidT> Agreement<N> {
self.coin_state = self.coin_state();
debug!(
"{:?} Agreement instance {:?} started epoch {}, {} terminated",
self.netinfo.our_uid(),
self.netinfo.our_id(),
self.proposer_id,
self.epoch,
self.received_conf.len(),

View File

@ -17,7 +17,7 @@ use super::bool_set::{self, BoolSet};
use super::{Error, Result};
use fault_log::{Fault, FaultKind};
use messaging::{self, DistAlgorithm, NetworkInfo, Target};
use traits::NodeUidT;
use traits::NodeIdT;
pub type Step<N> = messaging::Step<SbvBroadcast<N>>;
@ -58,8 +58,8 @@ pub struct SbvBroadcast<N> {
terminated: bool,
}
impl<N: NodeUidT> DistAlgorithm for SbvBroadcast<N> {
type NodeUid = N;
impl<N: NodeIdT> DistAlgorithm for SbvBroadcast<N> {
type NodeId = N;
type Input = bool;
type Output = BoolSet;
type Message = Message;
@ -69,7 +69,7 @@ impl<N: NodeUidT> DistAlgorithm for SbvBroadcast<N> {
self.send_bval(input)
}
fn handle_message(&mut self, sender_id: &Self::NodeUid, msg: Self::Message) -> Result<Step<N>> {
fn handle_message(&mut self, sender_id: &Self::NodeId, msg: Self::Message) -> Result<Step<N>> {
match msg {
Message::BVal(b) => self.handle_bval(sender_id, b),
Message::Aux(b) => self.handle_aux(sender_id, b),
@ -80,12 +80,12 @@ impl<N: NodeUidT> DistAlgorithm for SbvBroadcast<N> {
self.terminated
}
fn our_id(&self) -> &Self::NodeUid {
self.netinfo.our_uid()
fn our_id(&self) -> &Self::NodeId {
self.netinfo.our_id()
}
}
impl<N: NodeUidT> SbvBroadcast<N> {
impl<N: NodeIdT> SbvBroadcast<N> {
pub fn new(netinfo: Arc<NetworkInfo<N>>) -> Self {
SbvBroadcast {
netinfo,
@ -149,8 +149,8 @@ impl<N: NodeUidT> SbvBroadcast<N> {
return Ok(Step::default());
}
let mut step: Step<_> = Target::All.message(msg.clone()).into();
let our_uid = &self.netinfo.our_uid().clone();
step.extend(self.handle_message(our_uid, msg)?);
let our_id = &self.netinfo.our_id().clone();
step.extend(self.handle_message(our_id, msg)?);
Ok(step)
}

View File

@ -13,7 +13,7 @@ use super::{Error, Result};
use fault_log::{Fault, FaultKind};
use fmt::{HexBytes, HexList, HexProof};
use messaging::{self, DistAlgorithm, NetworkInfo, Target};
use traits::NodeUidT;
use traits::NodeIdT;
/// The three kinds of message sent during the reliable broadcast stage of the
/// consensus algorithm.
@ -62,7 +62,7 @@ impl Debug for Message {
pub struct Broadcast<N> {
/// Shared network data.
netinfo: Arc<NetworkInfo<N>>,
/// The UID of the sending node.
/// The ID of the sending node.
proposer_id: N,
data_shard_num: usize,
coding: Coding,
@ -80,8 +80,8 @@ pub struct Broadcast<N> {
pub type Step<N> = messaging::Step<Broadcast<N>>;
impl<N: NodeUidT> DistAlgorithm for Broadcast<N> {
type NodeUid = N;
impl<N: NodeIdT> DistAlgorithm for Broadcast<N> {
type NodeId = N;
// TODO: Allow anything serializable and deserializable, i.e. make this a type parameter
// T: Serialize + DeserializeOwned
type Input = Vec<u8>;
@ -90,15 +90,15 @@ impl<N: NodeUidT> DistAlgorithm for Broadcast<N> {
type Error = Error;
fn handle_input(&mut self, input: Self::Input) -> Result<Step<N>> {
if *self.netinfo.our_uid() != self.proposer_id {
if *self.netinfo.our_id() != self.proposer_id {
return Err(Error::InstanceCannotPropose);
}
// Split the value into chunks/shards, encode them with erasure codes.
// Assemble a Merkle tree from data and parity shards. Take all proofs
// from this tree and send them, each to its own node.
let (proof, mut step) = self.send_shards(input)?;
let our_uid = &self.netinfo.our_uid().clone();
step.extend(self.handle_value(our_uid, proof)?);
let our_id = &self.netinfo.our_id().clone();
step.extend(self.handle_value(our_id, proof)?);
Ok(step)
}
@ -118,11 +118,11 @@ impl<N: NodeUidT> DistAlgorithm for Broadcast<N> {
}
fn our_id(&self) -> &N {
self.netinfo.our_uid()
self.netinfo.our_id()
}
}
impl<N: NodeUidT> Broadcast<N> {
impl<N: NodeIdT> Broadcast<N> {
/// Creates a new broadcast instance to be used by node `our_id` which expects a value proposal
/// from node `proposer_id`.
pub fn new(netinfo: Arc<NetworkInfo<N>>, proposer_id: N) -> Result<Self> {
@ -196,14 +196,14 @@ impl<N: NodeUidT> Broadcast<N> {
let mut step = Step::default();
// Send each proof to a node.
for (index, uid) in self.netinfo.all_uids().enumerate() {
for (index, id) in self.netinfo.all_ids().enumerate() {
let proof = mtree.proof(index).ok_or(Error::ProofConstructionFailed)?;
if *uid == *self.netinfo.our_uid() {
if *id == *self.netinfo.our_id() {
// The proof is addressed to this node.
result = Ok(proof);
} else {
// Rest of the proofs are sent to remote nodes.
let msg = Target::Node(uid.clone()).message(Message::Value(proof));
let msg = Target::Node(id.clone()).message(Message::Value(proof));
step.messages.push_back(msg);
}
}
@ -217,7 +217,7 @@ impl<N: NodeUidT> Broadcast<N> {
if *sender_id != self.proposer_id {
info!(
"Node {:?} received Value from {:?} instead of {:?}.",
self.netinfo.our_uid(),
self.netinfo.our_id(),
sender_id,
self.proposer_id
);
@ -225,17 +225,14 @@ impl<N: NodeUidT> Broadcast<N> {
return Ok(Fault::new(sender_id.clone(), fault_kind).into());
}
if self.echo_sent {
info!(
"Node {:?} received multiple Values.",
self.netinfo.our_uid()
);
info!("Node {:?} received multiple Values.", self.netinfo.our_id());
// TODO: should receiving two Values from a node be considered
// a fault? If so, return a `Fault` here. For now, ignore.
return Ok(Step::default());
}
// If the proof is invalid, log the faulty node behavior and ignore.
if !self.validate_proof(&p, &self.netinfo.our_uid()) {
if !self.validate_proof(&p, &self.netinfo.our_id()) {
return Ok(Fault::new(sender_id.clone(), FaultKind::InvalidProof).into());
}
@ -249,7 +246,7 @@ impl<N: NodeUidT> Broadcast<N> {
if self.echos.contains_key(sender_id) {
info!(
"Node {:?} received multiple Echos from {:?}.",
self.netinfo.our_uid(),
self.netinfo.our_id(),
sender_id,
);
return Ok(Step::default());
@ -279,7 +276,7 @@ impl<N: NodeUidT> Broadcast<N> {
if self.readys.contains_key(sender_id) {
info!(
"Node {:?} received multiple Readys from {:?}.",
self.netinfo.our_uid(),
self.netinfo.our_id(),
sender_id
);
return Ok(Step::default());
@ -306,8 +303,8 @@ impl<N: NodeUidT> Broadcast<N> {
}
let echo_msg = Message::Echo(p.clone());
let mut step: Step<_> = Target::All.message(echo_msg).into();
let our_uid = &self.netinfo.our_uid().clone();
step.extend(self.handle_echo(our_uid, p)?);
let our_id = &self.netinfo.our_id().clone();
step.extend(self.handle_echo(our_id, p)?);
Ok(step)
}
@ -319,8 +316,8 @@ impl<N: NodeUidT> Broadcast<N> {
}
let ready_msg = Message::Ready(*hash);
let mut step: Step<_> = Target::All.message(ready_msg).into();
let our_uid = &self.netinfo.our_uid().clone();
step.extend(self.handle_ready(our_uid, hash)?);
let our_id = &self.netinfo.our_id().clone();
step.extend(self.handle_ready(our_id, hash)?);
Ok(step)
}
@ -337,7 +334,7 @@ impl<N: NodeUidT> Broadcast<N> {
// Upon receiving 2f + 1 matching Ready(h) messages, wait for N 2f Echo messages.
let mut leaf_values: Vec<Option<Box<[u8]>>> = self
.netinfo
.all_uids()
.all_ids()
.map(|id| {
self.echos.get(id).and_then(|p| {
if p.root_hash() == hash {
@ -364,14 +361,14 @@ impl<N: NodeUidT> Broadcast<N> {
if !p.validate(self.netinfo.num_nodes()) {
info!(
"Node {:?} received invalid proof: {:?}",
self.netinfo.our_uid(),
self.netinfo.our_id(),
HexProof(&p)
);
false
} else if self.netinfo.node_index(id) != Some(p.index()) {
info!(
"Node {:?} received proof for wrong position: {:?}.",
self.netinfo.our_uid(),
self.netinfo.our_id(),
HexProof(&p)
);
false

View File

@ -28,7 +28,7 @@ use crypto::error as cerror;
use crypto::{Signature, SignatureShare};
use fault_log::{Fault, FaultKind};
use messaging::{self, DistAlgorithm, NetworkInfo, Target};
use traits::NodeUidT;
use traits::NodeIdT;
/// A coin error.
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
@ -77,10 +77,10 @@ pub type Step<N, T> = messaging::Step<Coin<N, T>>;
impl<N, T> DistAlgorithm for Coin<N, T>
where
N: NodeUidT,
N: NodeIdT,
T: Clone + AsRef<[u8]>,
{
type NodeUid = N;
type NodeId = N;
type Input = ();
type Output = bool;
type Message = CoinMessage;
@ -99,7 +99,7 @@ where
/// Receives input from a remote node.
fn handle_message(
&mut self,
sender_id: &Self::NodeUid,
sender_id: &Self::NodeId,
message: Self::Message,
) -> Result<Step<N, T>> {
if !self.terminated {
@ -115,14 +115,14 @@ where
self.terminated
}
fn our_id(&self) -> &Self::NodeUid {
self.netinfo.our_uid()
fn our_id(&self) -> &Self::NodeId {
self.netinfo.our_id()
}
}
impl<N, T> Coin<N, T>
where
N: NodeUidT,
N: NodeIdT,
T: Clone + AsRef<[u8]>,
{
pub fn new(netinfo: Arc<NetworkInfo<N>>, nonce: T) -> Self {
@ -141,7 +141,7 @@ where
}
let share = self.netinfo.secret_key_share().sign(&self.nonce);
let mut step: Step<_, _> = Target::All.message(CoinMessage(share.clone())).into();
let id = self.netinfo.our_uid().clone();
let id = self.netinfo.our_id().clone();
step.extend(self.handle_share(&id, share)?);
Ok(step)
}
@ -163,7 +163,7 @@ where
fn try_output(&mut self) -> Result<Step<N, T>> {
debug!(
"{:?} received {} shares, had_input = {}",
self.netinfo.our_uid(),
self.netinfo.our_id(),
self.received_shares.len(),
self.had_input
);
@ -171,7 +171,7 @@ where
let sig = self.combine_and_verify_sig()?;
// Output the parity of the verified signature.
let parity = sig.parity();
debug!("{:?} output {}", self.netinfo.our_uid(), parity);
debug!("{:?} output {}", self.netinfo.our_id(), parity);
self.terminated = true;
let step = self.handle_input(())?; // Before terminating, make sure we sent our share.
Ok(step.with_output(parity))
@ -198,7 +198,7 @@ where
// Abort
error!(
"{:?} main public key verification failed",
self.netinfo.our_uid()
self.netinfo.our_id()
);
Err(Error::VerificationFailed)
} else {

View File

@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use super::{ChangeState, JoinPlan};
use crypto::{PublicKey, PublicKeySet};
use messaging::NetworkInfo;
use traits::NodeUidT;
use traits::NodeIdT;
/// A batch of transactions the algorithm has output.
#[derive(Clone, Debug, Eq, PartialEq)]
@ -22,7 +22,7 @@ pub struct Batch<C, N> {
pub_netinfo: Option<(PublicKeySet, BTreeMap<N, PublicKey>)>,
}
impl<C, N: NodeUidT + Rand> Batch<C, N> {
impl<C, N: NodeIdT + Rand> Batch<C, N> {
/// Returns a new, empty batch with the given epoch.
pub fn new(epoch: u64) -> Self {
Batch {

View File

@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use super::{ChangeState, DynamicHoneyBadger, JoinPlan, Result, Step, VoteCounter};
use honey_badger::HoneyBadger;
use messaging::NetworkInfo;
use traits::{Contribution, NodeUidT};
use traits::{Contribution, NodeIdT};
/// A Dynamic Honey Badger builder, to configure the parameters and create new instances of
/// `DynamicHoneyBadger`.
@ -33,7 +33,7 @@ impl<C, N> Default for DynamicHoneyBadgerBuilder<C, N> {
impl<C, N> DynamicHoneyBadgerBuilder<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
/// Returns a new `DynamicHoneyBadgerBuilder` configured to use the node IDs and cryptographic
/// keys specified by `netinfo`.
@ -66,14 +66,14 @@ where
}
/// Creates a new `DynamicHoneyBadger` configured to start a new network as a single validator.
pub fn build_first_node(&self, our_uid: N) -> Result<DynamicHoneyBadger<C, N>> {
pub fn build_first_node(&self, our_id: N) -> Result<DynamicHoneyBadger<C, N>> {
let mut rng = rand::thread_rng();
let sk_set = SecretKeySet::random(0, &mut rng)?;
let pk_set = sk_set.public_keys();
let sks = sk_set.secret_key_share(0)?;
let sk: SecretKey = rng.gen();
let pub_keys = once((our_uid.clone(), sk.public_key())).collect();
let netinfo = NetworkInfo::new(our_uid, sks, pk_set, sk, pub_keys);
let pub_keys = once((our_id.clone(), sk.public_key())).collect();
let netinfo = NetworkInfo::new(our_id, sks, pk_set, sk, pub_keys);
Ok(self.build(netinfo))
}
@ -81,12 +81,12 @@ where
/// the `JoinPlan`.
pub fn build_joining(
&self,
our_uid: N,
our_id: N,
secret_key: SecretKey,
join_plan: JoinPlan<N>,
) -> Result<(DynamicHoneyBadger<C, N>, Step<C, N>)> {
let netinfo = NetworkInfo::new(
our_uid,
our_id,
SecretKeyShare::default(), // TODO: Should be an option?
join_plan.pub_key_set,
secret_key,

View File

@ -15,7 +15,7 @@ use fault_log::{Fault, FaultKind, FaultLog};
use honey_badger::{self, HoneyBadger, Message as HbMessage};
use messaging::{DistAlgorithm, NetworkInfo, Target};
use sync_key_gen::{Ack, Part, PartOutcome, SyncKeyGen};
use traits::{Contribution, NodeUidT};
use traits::{Contribution, NodeIdT};
/// A Honey Badger instance that can handle adding and removing nodes.
#[derive(Debug)]
@ -41,9 +41,9 @@ pub struct DynamicHoneyBadger<C, N: Rand> {
impl<C, N> DistAlgorithm for DynamicHoneyBadger<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
type NodeUid = N;
type NodeId = N;
type Input = Input<C, N>;
type Output = Batch<C, N>;
type Message = Message<N>;
@ -89,14 +89,14 @@ where
}
fn our_id(&self) -> &N {
self.netinfo.our_uid()
self.netinfo.our_id()
}
}
impl<C, N> DynamicHoneyBadger<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
/// Returns a new `DynamicHoneyBadgerBuilder`.
pub fn builder() -> DynamicHoneyBadgerBuilder<C, N> {
@ -315,8 +315,8 @@ where
// `NetworkInfo` if the change goes through. It would be safer to deduplicate.
let threshold = (pub_keys.len() - 1) / 3;
let sk = self.netinfo.secret_key().clone();
let our_uid = self.our_id().clone();
let (key_gen, part) = SyncKeyGen::new(our_uid, sk, pub_keys, threshold)?;
let our_id = self.our_id().clone();
let (key_gen, part) = SyncKeyGen::new(our_id, sk, pub_keys, threshold)?;
self.key_gen_state = Some(KeyGenState::new(key_gen, change.clone()));
if let Some(part) = part {
self.send_transaction(KeyGenMessage::Part(part))
@ -362,9 +362,9 @@ where
bincode::serialize(&kg_msg).map_err(|err| ErrorKind::SendTransactionBincode(*err))?;
let sig = Box::new(self.netinfo.secret_key().sign(ser));
if self.netinfo.is_validator() {
let our_uid = self.netinfo.our_uid().clone();
let our_id = self.netinfo.our_id().clone();
let signed_msg =
SignedKeyGenMsg(self.start_epoch, our_uid, kg_msg.clone(), *sig.clone());
SignedKeyGenMsg(self.start_epoch, our_id, kg_msg.clone(), *sig.clone());
self.key_gen_msg_buffer.push(signed_msg);
}
let msg = Message::KeyGen(self.start_epoch, kg_msg, sig);

View File

@ -70,7 +70,7 @@ use self::votes::{SignedVote, VoteCounter};
use honey_badger::Message as HbMessage;
use messaging;
use sync_key_gen::{Ack, Part, SyncKeyGen};
use traits::NodeUidT;
use traits::NodeIdT;
pub use self::batch::Batch;
pub use self::builder::DynamicHoneyBadgerBuilder;
@ -156,7 +156,7 @@ struct KeyGenState<N> {
candidate_msg_count: usize,
}
impl<N: NodeUidT> KeyGenState<N> {
impl<N: NodeIdT> KeyGenState<N> {
fn new(key_gen: SyncKeyGen<N>, change: Change<N>) -> Self {
KeyGenState {
key_gen,

View File

@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use super::{Change, ErrorKind, Result};
use fault_log::{FaultKind, FaultLog};
use messaging::NetworkInfo;
use traits::NodeUidT;
use traits::NodeIdT;
/// A buffer and counter collecting pending and committed votes for validator set changes.
///
@ -29,7 +29,7 @@ pub struct VoteCounter<N> {
impl<N> VoteCounter<N>
where
N: NodeUidT + Serialize + for<'r> Deserialize<'r>,
N: NodeIdT + Serialize + for<'r> Deserialize<'r>,
{
/// Creates a new `VoteCounter` object with empty buffer and counter.
pub fn new(netinfo: Arc<NetworkInfo<N>>, era: u64) -> Self {
@ -43,7 +43,7 @@ where
/// Creates a signed vote for the given change, and inserts it into the pending votes buffer.
pub fn sign_vote_for(&mut self, change: Change<N>) -> Result<&SignedVote<N>> {
let voter = self.netinfo.our_uid().clone();
let voter = self.netinfo.our_id().clone();
let vote = Vote {
change,
era: self.era,

View File

@ -1,6 +1,6 @@
use std::collections::BTreeMap;
use traits::NodeUidT;
use traits::NodeIdT;
/// A batch of contributions the algorithm has output.
#[derive(Clone, Debug)]
@ -9,7 +9,7 @@ pub struct Batch<C, N> {
pub contributions: BTreeMap<N, C>,
}
impl<C, N: NodeUidT> Batch<C, N> {
impl<C, N: NodeIdT> Batch<C, N> {
/// Returns an iterator over references to all transactions included in the batch.
pub fn iter<'a>(&'a self) -> impl Iterator<Item = <&'a C as IntoIterator>::Item>
where

View File

@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use super::HoneyBadger;
use messaging::NetworkInfo;
use traits::{Contribution, NodeUidT};
use traits::{Contribution, NodeIdT};
/// A Honey Badger builder, to configure the parameters and create new instances of `HoneyBadger`.
pub struct HoneyBadgerBuilder<C, N> {
@ -21,7 +21,7 @@ pub struct HoneyBadgerBuilder<C, N> {
impl<C, N> HoneyBadgerBuilder<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Rand,
N: NodeIdT + Rand,
{
/// Returns a new `HoneyBadgerBuilder` configured to use the node IDs and cryptographic keys
/// specified by `netinfo`.

View File

@ -13,7 +13,7 @@ use fault_log::{Fault, FaultKind, FaultLog};
use messaging::{DistAlgorithm, NetworkInfo};
use subset::{self as cs, Subset};
use threshold_decryption::{self as td, ThresholdDecryption};
use traits::{Contribution, NodeUidT};
use traits::{Contribution, NodeIdT};
/// The status of an encrypted contribution.
#[derive(Debug)]
@ -26,7 +26,7 @@ enum DecryptionState<N> {
impl<N> DecryptionState<N>
where
N: NodeUidT + Rand,
N: NodeIdT + Rand,
{
/// Creates a new `ThresholdDecryption` instance, waiting for shares and a ciphertext.
fn new(netinfo: Arc<NetworkInfo<N>>) -> Self {
@ -69,7 +69,7 @@ enum SubsetState<N: Rand> {
impl<N> SubsetState<N>
where
N: NodeUidT + Rand,
N: NodeIdT + Rand,
{
/// Provides input to the Subset instance, unless it has already completed.
fn handle_input(&mut self, proposal: Vec<u8>) -> Result<cs::Step<N>> {
@ -122,7 +122,7 @@ pub struct EpochState<C, N: Rand> {
impl<C, N> EpochState<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Rand,
N: NodeIdT + Rand,
{
/// Creates a new `Subset` instance.
pub fn new(netinfo: Arc<NetworkInfo<N>>, epoch: u64) -> Result<Self> {
@ -208,7 +208,7 @@ where
}
debug!(
"{:?} Epoch {} output {:?}",
self.netinfo.our_uid(),
self.netinfo.our_id(),
self.epoch,
batch.contributions.keys().collect::<Vec<_>>()
);

View File

@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use super::epoch_state::EpochState;
use super::{Batch, Error, ErrorKind, HoneyBadgerBuilder, Message, MessageContent, Result};
use messaging::{self, DistAlgorithm, NetworkInfo};
use traits::{Contribution, NodeUidT};
use traits::{Contribution, NodeIdT};
/// An instance of the Honey Badger Byzantine fault tolerant consensus algorithm.
#[derive(Debug)]
@ -33,9 +33,9 @@ pub type Step<C, N> = messaging::Step<HoneyBadger<C, N>>;
impl<C, N> DistAlgorithm for HoneyBadger<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Rand,
N: NodeIdT + Rand,
{
type NodeUid = N;
type NodeId = N;
type Input = C;
type Output = Batch<C, N>;
type Message = Message<N>;
@ -54,14 +54,14 @@ where
}
fn our_id(&self) -> &N {
self.netinfo.our_uid()
self.netinfo.our_id()
}
}
impl<C, N> HoneyBadger<C, N>
where
C: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Rand,
N: NodeIdT + Rand,
{
/// Returns a new `HoneyBadgerBuilder` configured to use the node IDs and cryptographic keys
/// specified by `netinfo`.

View File

@ -161,8 +161,8 @@ pub mod traits {
impl<C> Contribution for C where C: Eq + Debug + Hash + Send + Sync {}
/// A peer node's unique identifier.
pub trait NodeUidT: Eq + Ord + Clone + Debug + Hash + Send + Sync {}
impl<N> NodeUidT for N where N: Eq + Ord + Clone + Debug + Hash + Send + Sync {}
pub trait NodeIdT: Eq + Ord + Clone + Debug + Hash + Send + Sync {}
impl<N> NodeIdT for N where N: Eq + Ord + Clone + Debug + Hash + Send + Sync {}
/// Messages.
pub trait Message: Debug + Send + Sync {}

View File

@ -5,7 +5,7 @@ use failure::Fail;
use crypto::{self, PublicKey, PublicKeySet, PublicKeyShare, SecretKey, SecretKeyShare};
use fault_log::{Fault, FaultLog};
use traits::{Message, NodeUidT};
use traits::{Message, NodeIdT};
/// Message sent by a given source.
#[derive(Clone, Debug)]
@ -59,17 +59,17 @@ impl<M, N> TargetedMessage<M, N> {
pub struct Step<D>
where
D: DistAlgorithm,
<D as DistAlgorithm>::NodeUid: NodeUidT,
<D as DistAlgorithm>::NodeId: NodeIdT,
{
pub output: VecDeque<D::Output>,
pub fault_log: FaultLog<D::NodeUid>,
pub messages: VecDeque<TargetedMessage<D::Message, D::NodeUid>>,
pub fault_log: FaultLog<D::NodeId>,
pub messages: VecDeque<TargetedMessage<D::Message, D::NodeId>>,
}
impl<D> Default for Step<D>
where
D: DistAlgorithm,
<D as DistAlgorithm>::NodeUid: NodeUidT,
<D as DistAlgorithm>::NodeId: NodeIdT,
{
fn default() -> Step<D> {
Step {
@ -82,13 +82,13 @@ where
impl<D: DistAlgorithm> Step<D>
where
<D as DistAlgorithm>::NodeUid: NodeUidT,
<D as DistAlgorithm>::NodeId: NodeIdT,
{
/// Creates a new `Step` from the given collections.
pub fn new(
output: VecDeque<D::Output>,
fault_log: FaultLog<D::NodeUid>,
messages: VecDeque<TargetedMessage<D::Message, D::NodeUid>>,
fault_log: FaultLog<D::NodeId>,
messages: VecDeque<TargetedMessage<D::Message, D::NodeId>>,
) -> Self {
Step {
output,
@ -107,7 +107,7 @@ where
/// messages.
pub fn map<D2, FO, FM>(self, f_out: FO, f_msg: FM) -> Step<D2>
where
D2: DistAlgorithm<NodeUid = D::NodeUid>,
D2: DistAlgorithm<NodeId = D::NodeId>,
FO: Fn(D::Output) -> D2::Output,
FM: Fn(D::Message) -> D2::Message,
{
@ -121,7 +121,7 @@ where
/// Extends `self` with `other`s messages and fault logs, and returns `other.output`.
pub fn extend_with<D2, FM>(&mut self, other: Step<D2>, f_msg: FM) -> VecDeque<D2::Output>
where
D2: DistAlgorithm<NodeUid = D::NodeUid>,
D2: DistAlgorithm<NodeId = D::NodeId>,
FM: Fn(D2::Message) -> D::Message,
{
self.fault_log.extend(other.fault_log);
@ -141,7 +141,7 @@ where
// This cannot be a `From` impl, because it would conflict with `impl From<T> for T`.
pub fn convert<D2>(self) -> Step<D2>
where
D2: DistAlgorithm<NodeUid = D::NodeUid, Output = D::Output, Message = D::Message>,
D2: DistAlgorithm<NodeId = D::NodeId, Output = D::Output, Message = D::Message>,
{
Step {
output: self.output,
@ -156,8 +156,8 @@ where
}
}
impl<D: DistAlgorithm> From<FaultLog<D::NodeUid>> for Step<D> {
fn from(fault_log: FaultLog<D::NodeUid>) -> Self {
impl<D: DistAlgorithm> From<FaultLog<D::NodeId>> for Step<D> {
fn from(fault_log: FaultLog<D::NodeId>) -> Self {
Step {
fault_log,
..Step::default()
@ -165,8 +165,8 @@ impl<D: DistAlgorithm> From<FaultLog<D::NodeUid>> for Step<D> {
}
}
impl<D: DistAlgorithm> From<Fault<D::NodeUid>> for Step<D> {
fn from(fault: Fault<D::NodeUid>) -> Self {
impl<D: DistAlgorithm> From<Fault<D::NodeId>> for Step<D> {
fn from(fault: Fault<D::NodeId>) -> Self {
Step {
fault_log: fault.into(),
..Step::default()
@ -174,8 +174,8 @@ impl<D: DistAlgorithm> From<Fault<D::NodeUid>> for Step<D> {
}
}
impl<D: DistAlgorithm> From<TargetedMessage<D::Message, D::NodeUid>> for Step<D> {
fn from(msg: TargetedMessage<D::Message, D::NodeUid>) -> Self {
impl<D: DistAlgorithm> From<TargetedMessage<D::Message, D::NodeId>> for Step<D> {
fn from(msg: TargetedMessage<D::Message, D::NodeId>) -> Self {
Step {
messages: once(msg).collect(),
..Step::default()
@ -186,7 +186,7 @@ impl<D: DistAlgorithm> From<TargetedMessage<D::Message, D::NodeUid>> for Step<D>
/// A distributed algorithm that defines a message flow.
pub trait DistAlgorithm {
/// Unique node identifier.
type NodeUid: NodeUidT;
type NodeId: NodeIdT;
/// The input provided by the user.
type Input;
/// The output type. Some algorithms return an output exactly once, others return multiple
@ -205,7 +205,7 @@ pub trait DistAlgorithm {
/// Handles a message received from node `sender_id`.
fn handle_message(
&mut self,
sender_id: &Self::NodeUid,
sender_id: &Self::NodeId,
message: Self::Message,
) -> Result<Step<Self>, Self::Error>
where
@ -215,13 +215,13 @@ pub trait DistAlgorithm {
fn terminated(&self) -> bool;
/// Returns this node's own ID.
fn our_id(&self) -> &Self::NodeUid;
fn our_id(&self) -> &Self::NodeId;
}
/// Common data shared between algorithms: the nodes' IDs and key shares.
#[derive(Debug, Clone)]
pub struct NetworkInfo<N> {
our_uid: N,
our_id: N,
num_nodes: usize,
num_faulty: usize,
is_validator: bool,
@ -234,16 +234,16 @@ pub struct NetworkInfo<N> {
node_indices: BTreeMap<N, usize>,
}
impl<N: NodeUidT> NetworkInfo<N> {
impl<N: NodeIdT> NetworkInfo<N> {
pub fn new(
our_uid: N,
our_id: N,
secret_key_share: SecretKeyShare,
public_key_set: PublicKeySet,
secret_key: SecretKey,
public_keys: BTreeMap<N, PublicKey>,
) -> Self {
let num_nodes = public_keys.len();
let is_validator = public_keys.contains_key(&our_uid);
let is_validator = public_keys.contains_key(&our_id);
let node_indices: BTreeMap<N, usize> = public_keys
.keys()
.enumerate()
@ -254,7 +254,7 @@ impl<N: NodeUidT> NetworkInfo<N> {
.map(|(id, idx)| (id.clone(), public_key_set.public_key_share(*idx)))
.collect();
NetworkInfo {
our_uid,
our_id,
num_nodes,
num_faulty: (num_nodes - 1) / 3,
is_validator,
@ -268,12 +268,12 @@ impl<N: NodeUidT> NetworkInfo<N> {
}
/// The ID of the node the algorithm runs on.
pub fn our_uid(&self) -> &N {
&self.our_uid
pub fn our_id(&self) -> &N {
&self.our_id
}
/// ID of all nodes in the network.
pub fn all_uids(&self) -> impl Iterator<Item = &N> {
pub fn all_ids(&self) -> impl Iterator<Item = &N> {
self.public_keys.keys()
}
@ -352,12 +352,12 @@ impl<N: NodeUidT> NetworkInfo<N> {
/// Returns `true` if the given node takes part in the consensus itself. If not, it is only an
/// observer.
pub fn is_node_validator(&self, uid: &N) -> bool {
self.public_keys.contains_key(uid)
pub fn is_node_validator(&self, id: &N) -> bool {
self.public_keys.contains_key(id)
}
/// Generates a map of matching `NetworkInfo`s for testing.
pub fn generate_map<I>(uids: I) -> Result<BTreeMap<N, NetworkInfo<N>>, crypto::error::Error>
pub fn generate_map<I>(ids: I) -> Result<BTreeMap<N, NetworkInfo<N>>, crypto::error::Error>
where
I: IntoIterator<Item = N>,
{
@ -367,8 +367,8 @@ impl<N: NodeUidT> NetworkInfo<N> {
let mut rng = rand::thread_rng();
let all_uids: BTreeSet<N> = uids.into_iter().collect();
let num_faulty = (all_uids.len() - 1) / 3;
let all_ids: BTreeSet<N> = ids.into_iter().collect();
let num_faulty = (all_ids.len() - 1) / 3;
// Generate the keys for threshold cryptography.
let sk_set = SecretKeySet::random(num_faulty, &mut rng)?;
@ -376,24 +376,24 @@ impl<N: NodeUidT> NetworkInfo<N> {
// Generate keys for individually signing and encrypting messages.
let sec_keys: BTreeMap<_, SecretKey> =
all_uids.iter().map(|id| (id.clone(), rng.gen())).collect();
all_ids.iter().map(|id| (id.clone(), rng.gen())).collect();
let pub_keys: BTreeMap<_, PublicKey> = sec_keys
.iter()
.map(|(id, sk)| (id.clone(), sk.public_key()))
.collect();
// Create the corresponding `NetworkInfo` for each node.
let create_netinfo = |(i, uid): (usize, N)| {
let create_netinfo = |(i, id): (usize, N)| {
let netinfo = NetworkInfo::new(
uid.clone(),
id.clone(),
sk_set.secret_key_share(i)?,
pk_set.clone(),
sec_keys[&uid].clone(),
sec_keys[&id].clone(),
pub_keys.clone(),
);
Ok((uid, netinfo))
Ok((id, netinfo))
};
all_uids
all_ids
.into_iter()
.enumerate()
.map(create_netinfo)

View File

@ -32,7 +32,7 @@ use serde::{Deserialize, Serialize};
use dynamic_honey_badger::{self, Batch as DhbBatch, DynamicHoneyBadger, Message};
use messaging::{self, DistAlgorithm};
use traits::{Contribution, NodeUidT};
use traits::{Contribution, NodeIdT};
use transaction_queue::TransactionQueue;
pub use dynamic_honey_badger::{Change, ChangeState, Input};
@ -105,7 +105,7 @@ pub struct QueueingHoneyBadgerBuilder<T, N: Rand> {
impl<T, N> QueueingHoneyBadgerBuilder<T, N>
where
T: Contribution + Serialize + for<'r> Deserialize<'r> + Clone,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
/// Returns a new `QueueingHoneyBadgerBuilder` configured to use the node IDs and cryptographic
/// keys specified by `netinfo`.
@ -162,7 +162,7 @@ where
pub struct QueueingHoneyBadger<T, N>
where
T: Contribution + Serialize + for<'r> Deserialize<'r>,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
/// The target number of transactions to be included in each batch.
batch_size: usize,
@ -177,9 +177,9 @@ pub type Step<T, N> = messaging::Step<QueueingHoneyBadger<T, N>>;
impl<T, N> DistAlgorithm for QueueingHoneyBadger<T, N>
where
T: Contribution + Serialize + for<'r> Deserialize<'r> + Clone,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
type NodeUid = N;
type NodeId = N;
type Input = Input<T, N>;
type Output = Batch<T, N>;
type Message = Message<N>;
@ -228,7 +228,7 @@ where
impl<T, N> QueueingHoneyBadger<T, N>
where
T: Contribution + Serialize + for<'r> Deserialize<'r> + Clone,
N: NodeUidT + Serialize + for<'r> Deserialize<'r> + Rand,
N: NodeIdT + Serialize + for<'r> Deserialize<'r> + Rand,
{
/// Returns a new `QueueingHoneyBadgerBuilder` configured to use the node IDs and cryptographic
/// keys specified by `netinfo`.

View File

@ -32,7 +32,7 @@ use broadcast::{self, Broadcast};
use fmt::HexBytes;
use messaging::{self, DistAlgorithm, NetworkInfo};
use rand::Rand;
use traits::NodeUidT;
use traits::NodeIdT;
/// A subset error.
#[derive(Clone, PartialEq, Debug, Fail)]
@ -86,8 +86,8 @@ pub struct Subset<N: Rand> {
pub type Step<N> = messaging::Step<Subset<N>>;
impl<N: NodeUidT + Rand> DistAlgorithm for Subset<N> {
type NodeUid = N;
impl<N: NodeIdT + Rand> DistAlgorithm for Subset<N> {
type NodeId = N;
type Input = ProposedValue;
type Output = BTreeMap<N, ProposedValue>;
type Message = Message<N>;
@ -96,7 +96,7 @@ impl<N: NodeUidT + Rand> DistAlgorithm for Subset<N> {
fn handle_input(&mut self, input: Self::Input) -> Result<Step<N>> {
debug!(
"{:?} Proposing {:?}",
self.netinfo.our_uid(),
self.netinfo.our_id(),
HexBytes(&input)
);
self.send_proposed_value(input)
@ -104,7 +104,7 @@ impl<N: NodeUidT + Rand> DistAlgorithm for Subset<N> {
fn handle_message(
&mut self,
sender_id: &Self::NodeUid,
sender_id: &Self::NodeId,
message: Self::Message,
) -> Result<Step<N>> {
match message {
@ -117,16 +117,16 @@ impl<N: NodeUidT + Rand> DistAlgorithm for Subset<N> {
self.agreement_instances.values().all(Agreement::terminated)
}
fn our_id(&self) -> &Self::NodeUid {
self.netinfo.our_uid()
fn our_id(&self) -> &Self::NodeId {
self.netinfo.our_id()
}
}
impl<N: NodeUidT + Rand> Subset<N> {
impl<N: NodeIdT + Rand> Subset<N> {
pub fn new(netinfo: Arc<NetworkInfo<N>>, session_id: u64) -> Result<Self> {
// Create all broadcast instances.
let mut broadcast_instances: BTreeMap<N, Broadcast<N>> = BTreeMap::new();
for proposer_id in netinfo.all_uids() {
for proposer_id in netinfo.all_ids() {
broadcast_instances.insert(
proposer_id.clone(),
Broadcast::new(netinfo.clone(), proposer_id.clone()).map_err(Error::NewBroadcast)?,
@ -135,7 +135,7 @@ impl<N: NodeUidT + Rand> Subset<N> {
// Create all agreement instances.
let mut agreement_instances: BTreeMap<N, Agreement<N>> = BTreeMap::new();
for proposer_id in netinfo.all_uids() {
for proposer_id in netinfo.all_ids() {
agreement_instances.insert(
proposer_id.clone(),
Agreement::new(netinfo.clone(), session_id, proposer_id.clone())
@ -159,9 +159,9 @@ impl<N: NodeUidT + Rand> Subset<N> {
if !self.netinfo.is_validator() {
return Ok(Step::default());
}
let uid = self.netinfo.our_uid().clone();
let id = self.netinfo.our_id().clone();
// Upon receiving input v_i , input v_i to RBC_i. See Figure 2.
self.process_broadcast(&uid, |bc| bc.handle_input(value))
self.process_broadcast(&id, |bc| bc.handle_input(value))
}
/// Returns the number of validators from which we have already received a proposal.
@ -230,7 +230,7 @@ impl<N: NodeUidT + Rand> Subset<N> {
}
/// Callback to be invoked on receipt of the decision value of the Agreement
/// instance `uid`.
/// instance `id`.
fn process_agreement<F>(&mut self, proposer_id: &N, f: F) -> Result<Step<N>>
where
F: FnOnce(&mut Agreement<N>) -> result::Result<agreement::Step<N>, agreement::Error>,
@ -264,23 +264,23 @@ impl<N: NodeUidT + Rand> Subset<N> {
}
debug!(
"{:?} Updated Agreement results: {:?}",
self.netinfo.our_uid(),
self.netinfo.our_id(),
self.agreement_results
);
if value && self.count_true() == self.netinfo.num_correct() {
// Upon delivery of value 1 from at least N f instances of BA, provide
// input 0 to each instance of BA that has not yet been provided input.
for (uid, agreement) in &mut self.agreement_instances {
for (id, agreement) in &mut self.agreement_instances {
if agreement.accepts_input() {
let to_msg = |a_msg| Message::Agreement(uid.clone(), a_msg);
let to_msg = |a_msg| Message::Agreement(id.clone(), a_msg);
for output in step.extend_with(
agreement
.handle_input(false)
.map_err(Error::ProcessAgreementAgreement1)?,
to_msg,
) {
if self.agreement_results.insert(uid.clone(), output).is_some() {
if self.agreement_results.insert(id.clone(), output).is_some() {
return Err(Error::MultipleAgreementResults);
}
}
@ -308,7 +308,7 @@ impl<N: NodeUidT + Rand> Subset<N> {
}
debug!(
"{:?} All Agreement instances have terminated",
self.netinfo.our_uid()
self.netinfo.our_id()
);
// All instances of Agreement that delivered `true` (or "1" in the paper).
let delivered_1: BTreeSet<&N> = self
@ -328,12 +328,9 @@ impl<N: NodeUidT + Rand> Subset<N> {
.collect();
if delivered_1.len() == broadcast_results.len() {
debug!(
"{:?} Agreement instances completed:",
self.netinfo.our_uid()
);
for (uid, result) in &broadcast_results {
debug!(" {:?} → {:?}", uid, HexBytes(&result));
debug!("{:?} Agreement instances completed:", self.netinfo.our_id());
for (id, result) in &broadcast_results {
debug!(" {:?} → {:?}", id, HexBytes(&result));
}
self.decided = true;
Some(broadcast_results)

View File

@ -173,7 +173,7 @@ use rand::OsRng;
use fault_log::{AckMessageFault as Fault, FaultKind, FaultLog};
use messaging::NetworkInfo;
use traits::NodeUidT;
use traits::NodeIdT;
// TODO: No need to send our own row and value to ourselves.
@ -264,7 +264,7 @@ pub enum PartOutcome<N: Clone> {
#[derive(Debug)]
pub struct SyncKeyGen<N> {
/// Our node ID.
our_uid: N,
our_id: N,
/// Our node index.
our_idx: Option<u64>,
/// Our secret key.
@ -277,24 +277,24 @@ pub struct SyncKeyGen<N> {
threshold: usize,
}
impl<N: NodeUidT> SyncKeyGen<N> {
impl<N: NodeIdT> SyncKeyGen<N> {
/// Creates a new `SyncKeyGen` instance, together with the `Part` message that should be
/// multicast to all nodes.
///
/// If we are not a validator but only an observer, no `Part` message is produced and no
/// messages need to be sent.
pub fn new(
our_uid: N,
our_id: N,
sec_key: SecretKey,
pub_keys: BTreeMap<N, PublicKey>,
threshold: usize,
) -> Result<(SyncKeyGen<N>, Option<Part>), Error> {
let our_idx = pub_keys
.keys()
.position(|uid| *uid == our_uid)
.position(|id| *id == our_id)
.map(|idx| idx as u64);
let key_gen = SyncKeyGen {
our_uid,
our_id,
our_idx,
sec_key,
pub_keys,
@ -445,7 +445,7 @@ impl<N: NodeUidT> SyncKeyGen<N> {
pub fn into_network_info(self) -> Result<NetworkInfo<N>, Error> {
let (pk_set, opt_sk_share) = self.generate()?;
let sk_share = opt_sk_share.unwrap_or_default(); // TODO: Make this an option.
let netinfo = NetworkInfo::new(self.our_uid, sk_share, pk_set, self.sec_key, self.pub_keys);
let netinfo = NetworkInfo::new(self.our_id, sk_share, pk_set, self.sec_key, self.pub_keys);
Ok(netinfo)
}
@ -491,7 +491,7 @@ impl<N: NodeUidT> SyncKeyGen<N> {
/// Returns the index of the node, or `None` if it is unknown.
fn node_index(&self, node_id: &N) -> Option<u64> {
if let Some(node_idx) = self.pub_keys.keys().position(|uid| uid == node_id) {
if let Some(node_idx) = self.pub_keys.keys().position(|id| id == node_id) {
Some(node_idx as u64)
} else {
error!("Unknown node {:?}", node_id);

View File

@ -17,7 +17,7 @@ use crypto::error as cerror;
use crypto::{Ciphertext, DecryptionShare};
use fault_log::{Fault, FaultKind, FaultLog};
use messaging::{self, DistAlgorithm, NetworkInfo, Target};
use traits::NodeUidT;
use traits::NodeIdT;
/// A threshold decryption error.
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
@ -54,8 +54,8 @@ pub struct ThresholdDecryption<N> {
pub type Step<N> = messaging::Step<ThresholdDecryption<N>>;
impl<N: NodeUidT> DistAlgorithm for ThresholdDecryption<N> {
type NodeUid = N;
impl<N: NodeIdT> DistAlgorithm for ThresholdDecryption<N> {
type NodeId = N;
type Input = Ciphertext;
type Output = Vec<u8>;
type Message = Message;
@ -74,11 +74,11 @@ impl<N: NodeUidT> DistAlgorithm for ThresholdDecryption<N> {
}
fn our_id(&self) -> &N {
self.netinfo.our_uid()
self.netinfo.our_id()
}
}
impl<N: NodeUidT> ThresholdDecryption<N> {
impl<N: NodeIdT> ThresholdDecryption<N> {
/// Creates a new Threshold Decryption instance.
pub fn new(netinfo: Arc<NetworkInfo<N>>) -> Self {
ThresholdDecryption {

View File

@ -36,13 +36,13 @@ use rand::Rng;
use hbbft::agreement::Agreement;
use hbbft::messaging::NetworkInfo;
use network::{Adversary, MessageScheduler, NodeUid, SilentAdversary, TestNetwork, TestNode};
use network::{Adversary, MessageScheduler, NodeId, SilentAdversary, TestNetwork, TestNode};
fn test_agreement<A: Adversary<Agreement<NodeUid>>>(
mut network: TestNetwork<A, Agreement<NodeUid>>,
fn test_agreement<A: Adversary<Agreement<NodeId>>>(
mut network: TestNetwork<A, Agreement<NodeId>>,
input: Option<bool>,
) {
let ids: Vec<NodeUid> = network.nodes.keys().cloned().collect();
let ids: Vec<NodeId> = network.nodes.keys().cloned().collect();
for id in ids {
network.input(id, input.unwrap_or_else(rand::random));
}
@ -66,7 +66,7 @@ fn test_agreement<A: Adversary<Agreement<NodeUid>>>(
fn test_agreement_different_sizes<A, F>(new_adversary: F)
where
A: Adversary<Agreement<NodeUid>>,
A: Adversary<Agreement<NodeId>>,
F: Fn(usize, usize) -> A,
{
// This returns an error in all but the first test.
@ -85,8 +85,8 @@ where
num_good_nodes, num_faulty_nodes, input
);
let adversary = |_| new_adversary(num_good_nodes, num_faulty_nodes);
let new_agreement = |netinfo: Arc<NetworkInfo<NodeUid>>| {
Agreement::new(netinfo, 0, NodeUid(0)).expect("agreement instance")
let new_agreement = |netinfo: Arc<NetworkInfo<NodeId>>| {
Agreement::new(netinfo, 0, NodeId(0)).expect("agreement instance")
};
let network =
TestNetwork::new(num_good_nodes, num_faulty_nodes, adversary, new_agreement);

View File

@ -24,15 +24,15 @@ use rand::Rng;
use hbbft::broadcast::{Broadcast, Message};
use hbbft::messaging::{DistAlgorithm, NetworkInfo, Target, TargetedMessage};
use network::{
Adversary, MessageScheduler, MessageWithSender, NodeUid, RandomAdversary, SilentAdversary,
Adversary, MessageScheduler, MessageWithSender, NodeId, RandomAdversary, SilentAdversary,
TestNetwork, TestNode,
};
/// An adversary that inputs an alternate value.
struct ProposeAdversary {
scheduler: MessageScheduler,
good_nodes: BTreeSet<NodeUid>,
adv_nodes: BTreeSet<NodeUid>,
good_nodes: BTreeSet<NodeId>,
adv_nodes: BTreeSet<NodeId>,
has_sent: bool,
}
@ -40,8 +40,8 @@ impl ProposeAdversary {
/// Creates a new replay adversary with the given message scheduler.
fn new(
scheduler: MessageScheduler,
good_nodes: BTreeSet<NodeUid>,
adv_nodes: BTreeSet<NodeUid>,
good_nodes: BTreeSet<NodeId>,
adv_nodes: BTreeSet<NodeId>,
) -> ProposeAdversary {
ProposeAdversary {
scheduler,
@ -52,21 +52,21 @@ impl ProposeAdversary {
}
}
impl Adversary<Broadcast<NodeUid>> for ProposeAdversary {
fn pick_node(&self, nodes: &BTreeMap<NodeUid, TestNode<Broadcast<NodeUid>>>) -> NodeUid {
impl Adversary<Broadcast<NodeId>> for ProposeAdversary {
fn pick_node(&self, nodes: &BTreeMap<NodeId, TestNode<Broadcast<NodeId>>>) -> NodeId {
self.scheduler.pick_node(nodes)
}
fn push_message(&mut self, _: NodeUid, _: TargetedMessage<Message, NodeUid>) {
fn push_message(&mut self, _: NodeId, _: TargetedMessage<Message, NodeId>) {
// All messages are ignored.
}
fn step(&mut self) -> Vec<MessageWithSender<Broadcast<NodeUid>>> {
fn step(&mut self) -> Vec<MessageWithSender<Broadcast<NodeId>>> {
if self.has_sent {
return vec![];
}
self.has_sent = true;
let node_ids: BTreeSet<NodeUid> = self
let node_ids: BTreeSet<NodeId> = self
.adv_nodes
.iter()
.chain(self.good_nodes.iter())
@ -95,15 +95,15 @@ impl Adversary<Broadcast<NodeUid>> for ProposeAdversary {
}
/// Broadcasts a value from node 0 and expects all good nodes to receive it.
fn test_broadcast<A: Adversary<Broadcast<NodeUid>>>(
mut network: TestNetwork<A, Broadcast<NodeUid>>,
fn test_broadcast<A: Adversary<Broadcast<NodeId>>>(
mut network: TestNetwork<A, Broadcast<NodeId>>,
proposed_value: &[u8],
) {
// This returns an error in all but the first test.
let _ = env_logger::try_init();
// Make node 0 propose the value.
network.input(NodeUid(0), proposed_value.to_vec());
network.input(NodeId(0), proposed_value.to_vec());
// Handle messages in random order until all nodes have output the proposed value.
while !network.nodes.values().all(TestNode::terminated) {
@ -116,13 +116,13 @@ fn test_broadcast<A: Adversary<Broadcast<NodeUid>>>(
assert!(once(&proposed_value.to_vec()).eq(network.observer.outputs()));
}
fn new_broadcast(netinfo: Arc<NetworkInfo<NodeUid>>) -> Broadcast<NodeUid> {
Broadcast::new(netinfo, NodeUid(0)).expect("Instantiate broadcast")
fn new_broadcast(netinfo: Arc<NetworkInfo<NodeId>>) -> Broadcast<NodeId> {
Broadcast::new(netinfo, NodeId(0)).expect("Instantiate broadcast")
}
fn test_broadcast_different_sizes<A, F>(new_adversary: F, proposed_value: &[u8])
where
A: Adversary<Broadcast<NodeUid>>,
A: Adversary<Broadcast<NodeId>>,
F: Fn(usize, usize) -> A,
{
let mut rng = rand::thread_rng();
@ -168,9 +168,9 @@ fn test_broadcast_first_delivery_silent() {
#[test]
fn test_broadcast_random_delivery_adv_propose() {
let new_adversary = |num_good_nodes: usize, num_faulty_nodes: usize| {
let good_nodes: BTreeSet<NodeUid> = (0..num_good_nodes).map(NodeUid).collect();
let adv_nodes: BTreeSet<NodeUid> = (num_good_nodes..(num_good_nodes + num_faulty_nodes))
.map(NodeUid)
let good_nodes: BTreeSet<NodeId> = (0..num_good_nodes).map(NodeId).collect();
let adv_nodes: BTreeSet<NodeId> = (num_good_nodes..(num_good_nodes + num_faulty_nodes))
.map(NodeId)
.collect();
ProposeAdversary::new(MessageScheduler::Random, good_nodes, adv_nodes)
};
@ -180,9 +180,9 @@ fn test_broadcast_random_delivery_adv_propose() {
#[test]
fn test_broadcast_first_delivery_adv_propose() {
let new_adversary = |num_good_nodes: usize, num_faulty_nodes: usize| {
let good_nodes: BTreeSet<NodeUid> = (0..num_good_nodes).map(NodeUid).collect();
let adv_nodes: BTreeSet<NodeUid> = (num_good_nodes..(num_good_nodes + num_faulty_nodes))
.map(NodeUid)
let good_nodes: BTreeSet<NodeId> = (0..num_good_nodes).map(NodeId).collect();
let adv_nodes: BTreeSet<NodeId> = (num_good_nodes..(num_good_nodes + num_faulty_nodes))
.map(NodeId)
.collect();
ProposeAdversary::new(MessageScheduler::First, good_nodes, adv_nodes)
};

View File

@ -21,13 +21,13 @@ use rand::Rng;
use hbbft::coin::Coin;
use network::{Adversary, MessageScheduler, NodeUid, SilentAdversary, TestNetwork, TestNode};
use network::{Adversary, MessageScheduler, NodeId, SilentAdversary, TestNetwork, TestNode};
/// Tests a network of Coin instances with an optional expected value. Outputs the computed
/// coin value if the test is successful.
fn test_coin<A>(mut network: TestNetwork<A, Coin<NodeUid, String>>) -> bool
fn test_coin<A>(mut network: TestNetwork<A, Coin<NodeId, String>>) -> bool
where
A: Adversary<Coin<NodeUid, String>>,
A: Adversary<Coin<NodeId, String>>,
{
network.input_all(());
network.observer.handle_input(()); // Observer will only return after `input` was called.
@ -74,7 +74,7 @@ fn check_coin_distribution(num_samples: usize, count_true: usize, count_false: u
fn test_coin_different_sizes<A, F>(new_adversary: F, num_samples: usize)
where
A: Adversary<Coin<NodeUid, String>>,
A: Adversary<Coin<NodeId, String>>,
F: Fn(usize, usize) -> A,
{
assert!(num_samples > 0);

View File

@ -27,32 +27,32 @@ use hbbft::dynamic_honey_badger::{Batch, Change, ChangeState, DynamicHoneyBadger
use hbbft::messaging::NetworkInfo;
use hbbft::transaction_queue::TransactionQueue;
use network::{Adversary, MessageScheduler, NodeUid, SilentAdversary, TestNetwork, TestNode};
use network::{Adversary, MessageScheduler, NodeId, SilentAdversary, TestNetwork, TestNode};
type UsizeDhb = DynamicHoneyBadger<Vec<usize>, NodeUid>;
type UsizeDhb = DynamicHoneyBadger<Vec<usize>, NodeId>;
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_dynamic_honey_badger<A>(mut network: TestNetwork<A, UsizeDhb>, num_txs: usize)
where
A: Adversary<UsizeDhb>,
{
let new_queue = |id: &NodeUid| (*id, TransactionQueue((0..num_txs).collect()));
let new_queue = |id: &NodeId| (*id, TransactionQueue((0..num_txs).collect()));
let mut queues: BTreeMap<_, _> = network.nodes.keys().map(new_queue).collect();
for (id, queue) in &queues {
network.input(*id, Input::User(queue.choose(3, 10)));
}
network.input_all(Input::Change(Change::Remove(NodeUid(0))));
network.input_all(Input::Change(Change::Remove(NodeId(0))));
fn has_remove(node: &TestNode<UsizeDhb>) -> bool {
node.outputs()
.iter()
.any(|batch| *batch.change() == ChangeState::Complete(Change::Remove(NodeUid(0))))
.any(|batch| *batch.change() == ChangeState::Complete(Change::Remove(NodeId(0))))
}
fn has_add(node: &TestNode<UsizeDhb>) -> bool {
node.outputs().iter().any(|batch| match *batch.change() {
ChangeState::Complete(Change::Add(ref id, _)) => *id == NodeUid(0),
ChangeState::Complete(Change::Add(ref id, _)) => *id == NodeId(0),
_ => false,
})
}
@ -94,12 +94,12 @@ where
network.step();
// Once all nodes have processed the removal of node 0, add it again.
if !input_add && network.nodes.values().all(has_remove) {
let pk = network.nodes[&NodeUid(0)]
let pk = network.nodes[&NodeId(0)]
.instance()
.netinfo()
.secret_key()
.public_key();
network.input_all(Input::Change(Change::Add(NodeUid(0), pk)));
network.input_all(Input::Change(Change::Add(NodeId(0), pk)));
input_add = true;
}
}
@ -113,7 +113,7 @@ fn verify_output_sequence<A>(network: &TestNetwork<A, UsizeDhb>)
where
A: Adversary<UsizeDhb>,
{
let expected = network.nodes[&NodeUid(0)].outputs().to_vec();
let expected = network.nodes[&NodeId(0)].outputs().to_vec();
assert!(!expected.is_empty());
for node in network.nodes.values() {
let len = cmp::min(expected.len(), node.outputs().len());
@ -123,14 +123,14 @@ where
// Allow passing `netinfo` by value. `TestNetwork` expects this function signature.
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn new_dynamic_hb(netinfo: Arc<NetworkInfo<NodeUid>>) -> UsizeDhb {
fn new_dynamic_hb(netinfo: Arc<NetworkInfo<NodeId>>) -> UsizeDhb {
DynamicHoneyBadger::builder().build((*netinfo).clone())
}
fn test_dynamic_honey_badger_different_sizes<A, F>(new_adversary: F, num_txs: usize)
where
A: Adversary<UsizeDhb>,
F: Fn(usize, usize, BTreeMap<NodeUid, Arc<NetworkInfo<NodeUid>>>) -> A,
F: Fn(usize, usize, BTreeMap<NodeId, Arc<NetworkInfo<NodeId>>>) -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();

View File

@ -29,17 +29,17 @@ use hbbft::threshold_decryption;
use hbbft::transaction_queue::TransactionQueue;
use network::{
Adversary, MessageScheduler, MessageWithSender, NodeUid, RandomAdversary, SilentAdversary,
Adversary, MessageScheduler, MessageWithSender, NodeId, RandomAdversary, SilentAdversary,
TestNetwork, TestNode,
};
type UsizeHoneyBadger = HoneyBadger<Vec<usize>, NodeUid>;
type UsizeHoneyBadger = HoneyBadger<Vec<usize>, NodeId>;
/// An adversary whose nodes only send messages with incorrect decryption shares.
pub struct FaultyShareAdversary {
num_good: usize,
num_adv: usize,
adv_nodes: BTreeMap<NodeUid, Arc<NetworkInfo<NodeUid>>>,
adv_nodes: BTreeMap<NodeId, Arc<NetworkInfo<NodeId>>>,
scheduler: MessageScheduler,
share_triggers: BTreeMap<u64, bool>,
}
@ -49,7 +49,7 @@ impl FaultyShareAdversary {
pub fn new(
num_good: usize,
num_adv: usize,
adv_nodes: BTreeMap<NodeUid, Arc<NetworkInfo<NodeUid>>>,
adv_nodes: BTreeMap<NodeId, Arc<NetworkInfo<NodeId>>>,
scheduler: MessageScheduler,
) -> FaultyShareAdversary {
FaultyShareAdversary {
@ -63,16 +63,16 @@ impl FaultyShareAdversary {
}
impl Adversary<UsizeHoneyBadger> for FaultyShareAdversary {
fn pick_node(&self, nodes: &BTreeMap<NodeUid, TestNode<UsizeHoneyBadger>>) -> NodeUid {
fn pick_node(&self, nodes: &BTreeMap<NodeId, TestNode<UsizeHoneyBadger>>) -> NodeId {
self.scheduler.pick_node(nodes)
}
fn push_message(
&mut self,
sender_id: NodeUid,
msg: TargetedMessage<honey_badger::Message<NodeUid>, NodeUid>,
sender_id: NodeId,
msg: TargetedMessage<honey_badger::Message<NodeId>, NodeId>,
) {
let NodeUid(sender_id) = sender_id;
let NodeId(sender_id) = sender_id;
if sender_id < self.num_good {
if let TargetedMessage {
target: Target::All,
@ -96,7 +96,7 @@ impl Adversary<UsizeHoneyBadger> for FaultyShareAdversary {
*trigger_set = false;
// Broadcast fake decryption shares from all adversarial nodes.
for sender_id in self.num_good..self.num_adv {
let adv_node = &self.adv_nodes[&NodeUid(sender_id)];
let adv_node = &self.adv_nodes[&NodeId(sender_id)];
let fake_ciphertext = (*adv_node)
.public_key_set()
.public_key()
@ -108,10 +108,10 @@ impl Adversary<UsizeHoneyBadger> for FaultyShareAdversary {
// Send the share to remote nodes.
for proposer_id in 0..self.num_good + self.num_adv {
outgoing.push(MessageWithSender::new(
NodeUid(sender_id),
NodeId(sender_id),
Target::All.message(
MessageContent::DecryptionShare {
proposer_id: NodeUid(proposer_id),
proposer_id: NodeId(proposer_id),
share: threshold_decryption::Message(share.clone()),
}.with_epoch(*epoch),
),
@ -129,7 +129,7 @@ fn test_honey_badger<A>(mut network: TestNetwork<A, UsizeHoneyBadger>, num_txs:
where
A: Adversary<UsizeHoneyBadger>,
{
let new_queue = |id: &NodeUid| (*id, TransactionQueue((0..num_txs).collect()));
let new_queue = |id: &NodeId| (*id, TransactionQueue((0..num_txs).collect()));
let mut queues: BTreeMap<_, _> = network.nodes.keys().map(new_queue).collect();
// Returns `true` if the node has not output all transactions yet.
@ -168,7 +168,7 @@ where
let mut expected: Option<BTreeMap<&_, &_>> = None;
for node in network.nodes.values() {
assert!(!node.outputs().is_empty());
let outputs: BTreeMap<&u64, &BTreeMap<NodeUid, Vec<usize>>> = node
let outputs: BTreeMap<&u64, &BTreeMap<NodeId, Vec<usize>>> = node
.outputs()
.iter()
.map(
@ -186,14 +186,14 @@ where
}
}
fn new_honey_badger(netinfo: Arc<NetworkInfo<NodeUid>>) -> UsizeHoneyBadger {
fn new_honey_badger(netinfo: Arc<NetworkInfo<NodeId>>) -> UsizeHoneyBadger {
HoneyBadger::builder(netinfo).build()
}
fn test_honey_badger_different_sizes<A, F>(new_adversary: F, num_txs: usize)
where
A: Adversary<UsizeHoneyBadger>,
F: Fn(usize, usize, BTreeMap<NodeUid, Arc<NetworkInfo<NodeUid>>>) -> A,
F: Fn(usize, usize, BTreeMap<NodeId, Arc<NetworkInfo<NodeId>>>) -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();

View File

@ -22,7 +22,7 @@ where
},
/// A node unexpectly disappeared from the list of nodes. Note that this is likely a bug in
/// the network framework code.
NodeDisappeared(D::NodeUid),
NodeDisappeared(D::NodeId),
/// The configured maximum number of cranks has been reached or exceeded.
CrankLimitExceeded(usize),
/// The configured maximum number of messages has been reached or exceeded.

View File

@ -102,7 +102,7 @@ impl<D: DistAlgorithm> Node<D> {
///
/// A node's ID is equal to its underlying algorithm instance's ID.
#[inline]
pub fn id(&self) -> &D::NodeUid {
pub fn id(&self) -> &D::NodeId {
self.algorithm.our_id()
}
@ -137,11 +137,11 @@ impl<M, N> NetworkMessage<M, N> {
}
/// Mapping from node IDs to actual node instances.
pub type NodeMap<D> = collections::BTreeMap<<D as DistAlgorithm>::NodeUid, Node<D>>;
pub type NodeMap<D> = collections::BTreeMap<<D as DistAlgorithm>::NodeId, Node<D>>;
/// A virtual network message tied to a distributed algorithm.
pub type NetMessage<D> =
NetworkMessage<<D as DistAlgorithm>::Message, <D as DistAlgorithm>::NodeUid>;
NetworkMessage<<D as DistAlgorithm>::Message, <D as DistAlgorithm>::NodeId>;
/// Process a step.
///
@ -158,8 +158,8 @@ pub type NetMessage<D> =
// borrow-checker restrictions.
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn process_step<'a, D>(
nodes: &'a mut collections::BTreeMap<D::NodeUid, Node<D>>,
sender: D::NodeUid,
nodes: &'a mut collections::BTreeMap<D::NodeId, Node<D>>,
sender: D::NodeId,
step: &Step<D>,
dest: &mut collections::VecDeque<NetMessage<D>>,
) -> usize
@ -224,9 +224,9 @@ where
D: DistAlgorithm,
{
/// The node ID for the new node.
pub id: D::NodeUid,
pub id: D::NodeId,
/// Network info struct, containing keys and other information.
pub netinfo: NetworkInfo<D::NodeUid>,
pub netinfo: NetworkInfo<D::NodeId>,
/// Whether or not the node is marked faulty.
pub faulty: bool,
}
@ -263,7 +263,7 @@ where
D: DistAlgorithm,
D::Message: Clone,
D::Output: Clone,
I: IntoIterator<Item = D::NodeUid>,
I: IntoIterator<Item = D::NodeId>,
{
/// Construct a new network builder.
///
@ -463,7 +463,7 @@ where
/// Returns `None` if the node ID is not part of the network.
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn get<'a>(&'a self, id: D::NodeUid) -> Option<&'a Node<D>> {
pub fn get<'a>(&'a self, id: D::NodeId) -> Option<&'a Node<D>> {
self.nodes.get(&id)
}
@ -472,7 +472,7 @@ where
/// Returns `None` if the node ID is not part of the network.
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn get_mut<'a>(&'a mut self, id: D::NodeUid) -> Option<&'a mut Node<D>> {
pub fn get_mut<'a>(&'a mut self, id: D::NodeId) -> Option<&'a mut Node<D>> {
self.nodes.get_mut(&id)
}
}
@ -500,7 +500,7 @@ where
fn new<F, I>(node_ids: I, faulty: usize, cons: F) -> Result<Self, crypto::error::Error>
where
F: Fn(NewNodeInfo<D>) -> (D, Step<D>),
I: IntoIterator<Item = D::NodeUid>,
I: IntoIterator<Item = D::NodeId>,
{
// Generate a new set of cryptographic keys for threshold cryptography.
let net_infos = messaging::NetworkInfo::generate_map(node_ids)?;
@ -582,7 +582,7 @@ where
///
/// Panics if `id` does not name a valid node.
#[inline]
pub fn send_input(&mut self, id: D::NodeUid, input: D::Input) -> Result<Step<D>, D::Error> {
pub fn send_input(&mut self, id: D::NodeId, input: D::Input) -> Result<Step<D>, D::Error> {
let step = self
.nodes
.get_mut(&id)
@ -608,7 +608,7 @@ where
/// If a successful `Step` was generated, all of its messages are queued on the network and the
/// `Step` is returned.
#[inline]
pub fn crank(&mut self) -> Option<Result<(D::NodeUid, Step<D>), CrankError<D>>> {
pub fn crank(&mut self) -> Option<Result<(D::NodeId, Step<D>), CrankError<D>>> {
// Check limits.
if let Some(limit) = self.crank_limit {
if self.crank_count >= limit {
@ -692,7 +692,7 @@ where
///
/// Shortcut for cranking the network, expecting both progress to be made as well as processing
/// to proceed.
pub fn crank_expect(&mut self) -> (D::NodeUid, Step<D>) {
pub fn crank_expect(&mut self) -> (D::NodeId, Step<D>) {
self.crank()
.expect("crank: network queue empty")
.expect("crank: node failed to process step")
@ -716,7 +716,7 @@ where
pub fn broadcast_input<'a>(
&'a mut self,
input: &'a D::Input,
) -> Result<Vec<(D::NodeUid, Step<D>)>, D::Error> {
) -> Result<Vec<(D::NodeId, Step<D>)>, D::Error> {
// Note: The tricky lifetime annotation basically says that the input value given must
// live as long as the iterator returned lives (because it is cloned on every step,
// with steps only evaluated each time `next()` is called. For the same reason the
@ -749,24 +749,24 @@ where
}
}
impl<D> ops::Index<D::NodeUid> for VirtualNet<D>
impl<D> ops::Index<D::NodeId> for VirtualNet<D>
where
D: DistAlgorithm,
{
type Output = Node<D>;
#[inline]
fn index(&self, index: D::NodeUid) -> &Self::Output {
fn index(&self, index: D::NodeId) -> &Self::Output {
self.get(index).expect("indexed node not found")
}
}
impl<D> ops::IndexMut<D::NodeUid> for VirtualNet<D>
impl<D> ops::IndexMut<D::NodeId> for VirtualNet<D>
where
D: DistAlgorithm,
{
#[inline]
fn index_mut(&mut self, index: D::NodeUid) -> &mut Self::Output {
fn index_mut(&mut self, index: D::NodeId) -> &mut Self::Output {
self.get_mut(index).expect("indexed node not found")
}
}
@ -788,7 +788,7 @@ where
D::Message: Clone,
D::Output: Clone,
{
type Item = Result<(D::NodeUid, Step<D>), CrankError<D>>;
type Item = Result<(D::NodeId, Step<D>), CrankError<D>>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {

View File

@ -10,20 +10,20 @@ use hbbft::messaging::{DistAlgorithm, NetworkInfo, Step, Target, TargetedMessage
/// A node identifier. In the tests, nodes are simply numbered.
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, Serialize, Deserialize, Rand)]
pub struct NodeUid(pub usize);
pub struct NodeId(pub usize);
/// A "node" running an instance of the algorithm `D`.
pub struct TestNode<D: DistAlgorithm> {
/// This node's own ID.
pub id: D::NodeUid,
pub id: D::NodeId,
/// The instance of the broadcast algorithm.
algo: D,
/// Incoming messages from other nodes that this node has not yet handled.
pub queue: VecDeque<(D::NodeUid, D::Message)>,
pub queue: VecDeque<(D::NodeId, D::Message)>,
/// The values this node has output so far.
outputs: Vec<D::Output>,
/// Outgoing messages to be sent to other nodes.
messages: VecDeque<TargetedMessage<D::Message, D::NodeUid>>,
messages: VecDeque<TargetedMessage<D::Message, D::NodeId>>,
}
impl<D: DistAlgorithm> TestNode<D> {
@ -92,8 +92,8 @@ impl MessageScheduler {
/// Chooses a node to be the next one to handle a message.
pub fn pick_node<D: DistAlgorithm>(
&self,
nodes: &BTreeMap<D::NodeUid, TestNode<D>>,
) -> D::NodeUid {
nodes: &BTreeMap<D::NodeId, TestNode<D>>,
) -> D::NodeId {
match *self {
MessageScheduler::First => nodes
.iter()
@ -101,7 +101,7 @@ impl MessageScheduler {
.map(|(id, _)| id.clone())
.expect("no more messages in queue"),
MessageScheduler::Random => {
let ids: Vec<D::NodeUid> = nodes
let ids: Vec<D::NodeId> = nodes
.iter()
.filter(|(_, node)| !node.queue.is_empty())
.map(|(id, _)| id.clone())
@ -118,9 +118,9 @@ impl MessageScheduler {
/// A message combined with a sender.
pub struct MessageWithSender<D: DistAlgorithm> {
/// The sender of the message.
pub sender: <D as DistAlgorithm>::NodeUid,
pub sender: <D as DistAlgorithm>::NodeId,
/// The targeted message (recipient and message body).
pub tm: TargetedMessage<<D as DistAlgorithm>::Message, <D as DistAlgorithm>::NodeUid>,
pub tm: TargetedMessage<<D as DistAlgorithm>::Message, <D as DistAlgorithm>::NodeId>,
}
// The Debug implementation cannot be derived automatically, possibly due to a compiler bug. For
@ -138,8 +138,8 @@ impl<D: DistAlgorithm> fmt::Debug for MessageWithSender<D> {
impl<D: DistAlgorithm> MessageWithSender<D> {
/// Creates a new message with a sender.
pub fn new(
sender: D::NodeUid,
tm: TargetedMessage<D::Message, D::NodeUid>,
sender: D::NodeId,
tm: TargetedMessage<D::Message, D::NodeId>,
) -> MessageWithSender<D> {
MessageWithSender { sender, tm }
}
@ -153,10 +153,10 @@ pub trait Adversary<D: DistAlgorithm> {
///
/// Starvation is illegal, i.e. in every iteration a node that has pending incoming messages
/// must be chosen.
fn pick_node(&self, nodes: &BTreeMap<D::NodeUid, TestNode<D>>) -> D::NodeUid;
fn pick_node(&self, nodes: &BTreeMap<D::NodeId, TestNode<D>>) -> D::NodeId;
/// Called when a node controlled by the adversary receives a message.
fn push_message(&mut self, sender_id: D::NodeUid, msg: TargetedMessage<D::Message, D::NodeUid>);
fn push_message(&mut self, sender_id: D::NodeId, msg: TargetedMessage<D::Message, D::NodeId>);
/// Produces a list of messages to be sent from the adversary's nodes.
fn step(&mut self) -> Vec<MessageWithSender<D>>;
@ -165,8 +165,8 @@ pub trait Adversary<D: DistAlgorithm> {
/// some aspects of the network, such as which nodes they control.
fn init(
&mut self,
_all_nodes: &BTreeMap<D::NodeUid, TestNode<D>>,
_adv_nodes: &BTreeMap<D::NodeUid, Arc<NetworkInfo<D::NodeUid>>>,
_all_nodes: &BTreeMap<D::NodeId, TestNode<D>>,
_adv_nodes: &BTreeMap<D::NodeId, Arc<NetworkInfo<D::NodeId>>>,
) {
// default: does nothing
}
@ -185,11 +185,11 @@ impl SilentAdversary {
}
impl<D: DistAlgorithm> Adversary<D> for SilentAdversary {
fn pick_node(&self, nodes: &BTreeMap<D::NodeUid, TestNode<D>>) -> D::NodeUid {
fn pick_node(&self, nodes: &BTreeMap<D::NodeId, TestNode<D>>) -> D::NodeId {
self.scheduler.pick_node(nodes)
}
fn push_message(&mut self, _: D::NodeUid, _: TargetedMessage<D::Message, D::NodeUid>) {
fn push_message(&mut self, _: D::NodeId, _: TargetedMessage<D::Message, D::NodeId>) {
// All messages are ignored.
}
@ -223,9 +223,9 @@ pub struct RandomAdversary<D: DistAlgorithm, F> {
scheduler: MessageScheduler,
/// Node ids seen by the adversary.
known_node_ids: Vec<D::NodeUid>,
known_node_ids: Vec<D::NodeId>,
/// Node ids under control of adversary
known_adversarial_ids: Vec<D::NodeUid>,
known_adversarial_ids: Vec<D::NodeId>,
/// Internal queue for messages to be returned on the next `Adversary::step()` call
outgoing: Vec<MessageWithSender<D>>,
@ -260,24 +260,24 @@ impl<D: DistAlgorithm, F> RandomAdversary<D, F> {
}
}
impl<D: DistAlgorithm, F: Fn() -> TargetedMessage<D::Message, D::NodeUid>> Adversary<D>
impl<D: DistAlgorithm, F: Fn() -> TargetedMessage<D::Message, D::NodeId>> Adversary<D>
for RandomAdversary<D, F>
{
fn init(
&mut self,
all_nodes: &BTreeMap<D::NodeUid, TestNode<D>>,
nodes: &BTreeMap<D::NodeUid, Arc<NetworkInfo<D::NodeUid>>>,
all_nodes: &BTreeMap<D::NodeId, TestNode<D>>,
nodes: &BTreeMap<D::NodeId, Arc<NetworkInfo<D::NodeId>>>,
) {
self.known_adversarial_ids = nodes.keys().cloned().collect();
self.known_node_ids = all_nodes.keys().cloned().collect();
}
fn pick_node(&self, nodes: &BTreeMap<D::NodeUid, TestNode<D>>) -> D::NodeUid {
fn pick_node(&self, nodes: &BTreeMap<D::NodeId, TestNode<D>>) -> D::NodeId {
// Just let the scheduler pick a node.
self.scheduler.pick_node(nodes)
}
fn push_message(&mut self, _: D::NodeUid, msg: TargetedMessage<D::Message, D::NodeUid>) {
fn push_message(&mut self, _: D::NodeId, msg: TargetedMessage<D::Message, D::NodeId>) {
// If we have not discovered the network topology yet, abort.
if self.known_node_ids.is_empty() {
return;
@ -357,13 +357,13 @@ impl<D: DistAlgorithm, F: Fn() -> TargetedMessage<D::Message, D::NodeUid>> Adver
///
/// See the `step` function for details on actual operation of the network.
pub struct TestNetwork<A: Adversary<D>, D: DistAlgorithm> {
pub nodes: BTreeMap<D::NodeUid, TestNode<D>>,
pub nodes: BTreeMap<D::NodeId, TestNode<D>>,
pub observer: TestNode<D>,
pub adv_nodes: BTreeMap<D::NodeUid, Arc<NetworkInfo<D::NodeUid>>>,
pub adv_nodes: BTreeMap<D::NodeId, Arc<NetworkInfo<D::NodeId>>>,
adversary: A,
}
impl<A: Adversary<D>, D: DistAlgorithm<NodeUid = NodeUid>> TestNetwork<A, D>
impl<A: Adversary<D>, D: DistAlgorithm<NodeId = NodeId>> TestNetwork<A, D>
where
D::Message: Clone,
{
@ -377,8 +377,8 @@ where
new_algo: F,
) -> TestNetwork<A, D>
where
F: Fn(Arc<NetworkInfo<NodeUid>>) -> D,
G: Fn(BTreeMap<D::NodeUid, Arc<NetworkInfo<D::NodeUid>>>) -> A,
F: Fn(Arc<NetworkInfo<NodeId>>) -> D,
G: Fn(BTreeMap<D::NodeId, Arc<NetworkInfo<D::NodeId>>>) -> A,
{
Self::new_with_step(good_num, adv_num, adversary, |netinfo| {
(new_algo(netinfo), Step::default())
@ -394,29 +394,29 @@ where
new_algo: F,
) -> TestNetwork<A, D>
where
F: Fn(Arc<NetworkInfo<NodeUid>>) -> (D, Step<D>),
G: Fn(BTreeMap<D::NodeUid, Arc<NetworkInfo<D::NodeUid>>>) -> A,
F: Fn(Arc<NetworkInfo<NodeId>>) -> (D, Step<D>),
G: Fn(BTreeMap<D::NodeId, Arc<NetworkInfo<D::NodeId>>>) -> A,
{
let mut rng = rand::thread_rng();
let node_ids = (0..(good_num + adv_num)).map(NodeUid);
let node_ids = (0..(good_num + adv_num)).map(NodeId);
let mut netinfos =
NetworkInfo::generate_map(node_ids).expect("Failed to generate `NetworkInfo` map");
let obs_netinfo = {
let node_ni = netinfos.values().next().unwrap();
NetworkInfo::new(
NodeUid(good_num + adv_num),
NodeId(good_num + adv_num),
SecretKeyShare::default(),
node_ni.public_key_set().clone(),
rng.gen(),
node_ni.public_key_map().clone(),
)
};
let adv_netinfos = netinfos.split_off(&NodeUid(good_num));
let adv_netinfos = netinfos.split_off(&NodeId(good_num));
let new_node = |(uid, netinfo): (NodeUid, NetworkInfo<_>)| {
(uid, TestNode::new(new_algo(Arc::new(netinfo))))
let new_node = |(id, netinfo): (NodeId, NetworkInfo<_>)| {
(id, TestNode::new(new_algo(Arc::new(netinfo))))
};
let new_adv_node = |(uid, netinfo): (NodeUid, NetworkInfo<_>)| (uid, Arc::new(netinfo));
let new_adv_node = |(id, netinfo): (NodeId, NetworkInfo<_>)| (id, Arc::new(netinfo));
let adv_nodes: BTreeMap<_, _> = adv_netinfos.into_iter().map(new_adv_node).collect();
let observer = TestNode::new(new_algo(Arc::new(obs_netinfo)));
@ -435,7 +435,7 @@ where
for MessageWithSender { sender, tm } in msgs {
network.dispatch_messages(sender, vec![tm]);
}
let mut initial_msgs: Vec<(D::NodeUid, Vec<_>)> = Vec::new();
let mut initial_msgs: Vec<(D::NodeId, Vec<_>)> = Vec::new();
for (id, node) in &mut network.nodes {
initial_msgs.push((*id, node.messages.drain(..).collect()));
}
@ -446,9 +446,9 @@ where
}
/// Pushes the messages into the queues of the corresponding recipients.
fn dispatch_messages<Q>(&mut self, sender_id: NodeUid, msgs: Q)
fn dispatch_messages<Q>(&mut self, sender_id: NodeId, msgs: Q)
where
Q: IntoIterator<Item = TargetedMessage<D::Message, NodeUid>> + Debug,
Q: IntoIterator<Item = TargetedMessage<D::Message, NodeId>> + Debug,
{
for msg in msgs {
match msg.target {
@ -489,7 +489,7 @@ where
/// `Adversary::pick_node()`.
///
/// Returns the node ID of the node that made progress.
pub fn step(&mut self) -> NodeUid {
pub fn step(&mut self) -> NodeId {
// We let the adversary send out messages to any number of nodes.
let msgs = self.adversary.step();
for MessageWithSender { sender, tm } in msgs {
@ -520,7 +520,7 @@ where
}
/// Inputs a value in node `id`.
pub fn input(&mut self, id: NodeUid, value: D::Input) {
pub fn input(&mut self, id: NodeId, value: D::Input) {
let msgs: Vec<_> = {
let mut node = self.nodes.get_mut(&id).expect("input instance");
node.handle_input(value);
@ -535,7 +535,7 @@ where
where
D::Input: Clone,
{
let ids: Vec<D::NodeUid> = self.nodes.keys().cloned().collect();
let ids: Vec<D::NodeId> = self.nodes.keys().cloned().collect();
for id in ids {
self.input(id, value.clone());
}

View File

@ -26,37 +26,37 @@ use hbbft::queueing_honey_badger::{Batch, Change, ChangeState, Input, QueueingHo
use itertools::Itertools;
use rand::Rng;
use network::{Adversary, MessageScheduler, NodeUid, SilentAdversary, TestNetwork, TestNode};
use network::{Adversary, MessageScheduler, NodeId, SilentAdversary, TestNetwork, TestNode};
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_queueing_honey_badger<A>(
mut network: TestNetwork<A, QueueingHoneyBadger<usize, NodeUid>>,
mut network: TestNetwork<A, QueueingHoneyBadger<usize, NodeId>>,
num_txs: usize,
) where
A: Adversary<QueueingHoneyBadger<usize, NodeUid>>,
A: Adversary<QueueingHoneyBadger<usize, NodeId>>,
{
// The second half of the transactions will be input only after a node has been removed.
network.input_all(Input::Change(Change::Remove(NodeUid(0))));
network.input_all(Input::Change(Change::Remove(NodeId(0))));
for tx in 0..(num_txs / 2) {
network.input_all(Input::User(tx));
}
fn has_remove(node: &TestNode<QueueingHoneyBadger<usize, NodeUid>>) -> bool {
fn has_remove(node: &TestNode<QueueingHoneyBadger<usize, NodeId>>) -> bool {
node.outputs()
.iter()
.any(|batch| *batch.change() == ChangeState::Complete(Change::Remove(NodeUid(0))))
.any(|batch| *batch.change() == ChangeState::Complete(Change::Remove(NodeId(0))))
}
fn has_add(node: &TestNode<QueueingHoneyBadger<usize, NodeUid>>) -> bool {
fn has_add(node: &TestNode<QueueingHoneyBadger<usize, NodeId>>) -> bool {
node.outputs().iter().any(|batch| match *batch.change() {
ChangeState::Complete(Change::Add(ref id, _)) => *id == NodeUid(0),
ChangeState::Complete(Change::Add(ref id, _)) => *id == NodeId(0),
_ => false,
})
}
// Returns `true` if the node has not output all transactions yet.
// If it has, and has advanced another epoch, it clears all messages for later epochs.
let node_busy = |node: &mut TestNode<QueueingHoneyBadger<usize, NodeUid>>| {
let node_busy = |node: &mut TestNode<QueueingHoneyBadger<usize, NodeId>>| {
if !has_remove(node) || !has_add(node) {
return true;
}
@ -74,13 +74,13 @@ fn test_queueing_honey_badger<A>(
for tx in (num_txs / 2)..num_txs {
network.input_all(Input::User(tx));
}
let pk = network.nodes[&NodeUid(0)]
let pk = network.nodes[&NodeId(0)]
.instance()
.dyn_hb()
.netinfo()
.secret_key()
.public_key();
network.input_all(Input::Change(Change::Add(NodeUid(0), pk)));
network.input_all(Input::Change(Change::Add(NodeId(0), pk)));
input_add = true;
}
}
@ -90,11 +90,11 @@ fn test_queueing_honey_badger<A>(
/// Verifies that all instances output the same sequence of batches. We already know that all of
/// them have output all transactions and events, but some may have advanced a few empty batches
/// more than others, so we ignore those.
fn verify_output_sequence<A>(network: &TestNetwork<A, QueueingHoneyBadger<usize, NodeUid>>)
fn verify_output_sequence<A>(network: &TestNetwork<A, QueueingHoneyBadger<usize, NodeId>>)
where
A: Adversary<QueueingHoneyBadger<usize, NodeUid>>,
A: Adversary<QueueingHoneyBadger<usize, NodeId>>,
{
let expected = network.nodes[&NodeUid(0)].outputs().to_vec();
let expected = network.nodes[&NodeId(0)].outputs().to_vec();
assert!(!expected.is_empty());
for node in network.nodes.values() {
let len = cmp::min(expected.len(), node.outputs().len());
@ -105,16 +105,16 @@ where
// Allow passing `netinfo` by value. `TestNetwork` expects this function signature.
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn new_queueing_hb(
netinfo: Arc<NetworkInfo<NodeUid>>,
) -> (QueueingHoneyBadger<usize, NodeUid>, Step<usize, NodeUid>) {
netinfo: Arc<NetworkInfo<NodeId>>,
) -> (QueueingHoneyBadger<usize, NodeId>, Step<usize, NodeId>) {
let dyn_hb = DynamicHoneyBadger::builder().build((*netinfo).clone());
QueueingHoneyBadger::builder(dyn_hb).batch_size(3).build()
}
fn test_queueing_honey_badger_different_sizes<A, F>(new_adversary: F, num_txs: usize)
where
A: Adversary<QueueingHoneyBadger<usize, NodeUid>>,
F: Fn(usize, usize, BTreeMap<NodeUid, Arc<NetworkInfo<NodeUid>>>) -> A,
A: Adversary<QueueingHoneyBadger<usize, NodeId>>,
F: Fn(usize, usize, BTreeMap<NodeId, Arc<NetworkInfo<NodeId>>>) -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();

View File

@ -22,15 +22,15 @@ use std::sync::Arc;
use hbbft::messaging::NetworkInfo;
use hbbft::subset::Subset;
use network::{Adversary, MessageScheduler, NodeUid, SilentAdversary, TestNetwork, TestNode};
use network::{Adversary, MessageScheduler, NodeId, SilentAdversary, TestNetwork, TestNode};
type ProposedValue = Vec<u8>;
fn test_subset<A: Adversary<Subset<NodeUid>>>(
mut network: TestNetwork<A, Subset<NodeUid>>,
inputs: &BTreeMap<NodeUid, ProposedValue>,
fn test_subset<A: Adversary<Subset<NodeId>>>(
mut network: TestNetwork<A, Subset<NodeId>>,
inputs: &BTreeMap<NodeId, ProposedValue>,
) {
let ids: Vec<NodeUid> = network.nodes.keys().cloned().collect();
let ids: Vec<NodeId> = network.nodes.keys().cloned().collect();
for id in ids {
if let Some(value) = inputs.get(&id) {
@ -67,24 +67,24 @@ fn new_network<A, F>(
good_num: usize,
bad_num: usize,
adversary: F,
) -> TestNetwork<A, Subset<NodeUid>>
) -> TestNetwork<A, Subset<NodeId>>
where
A: Adversary<Subset<NodeUid>>,
F: Fn(BTreeMap<NodeUid, Arc<NetworkInfo<NodeUid>>>) -> A,
A: Adversary<Subset<NodeId>>,
F: Fn(BTreeMap<NodeId, Arc<NetworkInfo<NodeId>>>) -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();
let new_subset =
|netinfo: Arc<NetworkInfo<NodeUid>>| Subset::new(netinfo, 0).expect("new Subset instance");
|netinfo: Arc<NetworkInfo<NodeId>>| Subset::new(netinfo, 0).expect("new Subset instance");
TestNetwork::new(good_num, bad_num, adversary, new_subset)
}
#[test]
fn test_subset_3_out_of_4_nodes_propose() {
let proposed_value = Vec::from("Fake news");
let proposing_ids: BTreeSet<NodeUid> = (0..3).map(NodeUid).collect();
let proposals: BTreeMap<NodeUid, ProposedValue> = proposing_ids
let proposing_ids: BTreeSet<NodeId> = (0..3).map(NodeId).collect();
let proposals: BTreeMap<NodeId, ProposedValue> = proposing_ids
.iter()
.map(|id| (*id, proposed_value.clone()))
.collect();
@ -102,9 +102,9 @@ fn test_subset_5_nodes_different_proposed_values() {
Vec::from("Delta"),
Vec::from("Echo"),
];
let proposals: BTreeMap<NodeUid, ProposedValue> = (0..5)
let proposals: BTreeMap<NodeId, ProposedValue> = (0..5)
.into_iter()
.map(NodeUid)
.map(NodeId)
.zip(proposed_values)
.collect();
let adversary = |_| SilentAdversary::new(MessageScheduler::Random);
@ -114,8 +114,8 @@ fn test_subset_5_nodes_different_proposed_values() {
#[test]
fn test_subset_1_node() {
let proposals: BTreeMap<NodeUid, ProposedValue> =
once((NodeUid(0), Vec::from("Node 0 is the greatest!"))).collect();
let proposals: BTreeMap<NodeId, ProposedValue> =
once((NodeId(0), Vec::from("Node 0 is the greatest!"))).collect();
let adversary = |_| SilentAdversary::new(MessageScheduler::Random);
let network = new_network(1, 0, adversary);
test_subset(network, &proposals);