hbbft/examples/simulation.rs

457 lines
16 KiB
Rust
Raw Normal View History

2018-07-17 06:54:12 -07:00
use std::collections::{BTreeMap, VecDeque};
use std::time::{Duration, Instant};
2018-05-17 02:51:14 -07:00
use std::{cmp, u64};
use colored::*;
use docopt::Docopt;
use itertools::Itertools;
use number_prefix::{NumberPrefix, Prefixed, Standalone};
use rand::{distributions::Standard, rngs::OsRng, seq::SliceRandom, Rng};
2018-10-29 07:36:56 -07:00
use rand_derive::Rand;
2019-04-01 05:37:14 -07:00
use serde::{de::DeserializeOwned, Deserialize, Serialize};
2018-05-17 02:51:14 -07:00
use hbbft::crypto::SecretKey;
2018-07-17 06:54:12 -07:00
use hbbft::dynamic_honey_badger::DynamicHoneyBadger;
use hbbft::queueing_honey_badger::{Batch, QueueingHoneyBadger};
2018-10-25 08:07:52 -07:00
use hbbft::sender_queue::{Message, SenderQueue};
use hbbft::{to_pub_keys, ConsensusProtocol, CpStep, NetworkInfo, PubKeyMap, Step, Target};
2018-05-17 02:51:14 -07:00
const VERSION: &str = env!("CARGO_PKG_VERSION");
const USAGE: &str = "
Benchmark example
Usage:
benchmark [options]
benchmark (--help | -h )
benchmark --version
Options:
-h, --help Show this message.
--version Show the version of hbbft.
-n <n>, --nodes <n> The total number of nodes [default: 10]
-f <f>, --faulty <f> The number of faulty nodes [default: 0]
-t <txs>, --txs <txs> The number of transactions to process [default: 1000]
-b <b>, --batch <b> The batch size, i.e. txs per epoch [default: 100]
-l <lag>, --lag <lag> The network lag between sending and receiving [default: 100]
--bw <bw> The bandwidth, in kbit/s [default: 2000]
--cpu <cpu> The CPU speed, in percent of this machine's [default: 100]
--tx-size <size> The size of a transaction, in bytes [default: 10]
2018-05-17 02:51:14 -07:00
";
#[derive(Deserialize)]
struct Args {
flag_n: usize,
flag_f: usize,
flag_txs: usize,
flag_b: usize,
flag_lag: u64,
flag_bw: u32,
flag_cpu: f32,
flag_tx_size: usize,
2018-05-17 02:51:14 -07:00
}
/// A node identifier. In the simulation, nodes are simply numbered.
#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, Rand)]
2018-08-29 09:08:35 -07:00
pub struct NodeId(pub usize);
2018-05-17 02:51:14 -07:00
/// A transaction.
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
type Transaction = Vec<u8>;
/// A serialized message with a sender and the timestamp of arrival.
#[derive(Eq, PartialEq, Debug)]
struct TimestampedMessage<D: ConsensusProtocol> {
time: Duration,
2018-08-29 09:08:35 -07:00
sender_id: D::NodeId,
target: Target<D::NodeId>,
message: Vec<u8>,
2018-05-17 02:51:14 -07:00
}
impl<D: ConsensusProtocol> Clone for TimestampedMessage<D>
2018-05-17 02:51:14 -07:00
where
D::Message: Clone,
{
fn clone(&self) -> Self {
TimestampedMessage {
time: self.time,
sender_id: self.sender_id.clone(),
target: self.target.clone(),
2018-05-17 02:51:14 -07:00
message: self.message.clone(),
}
}
}
/// Performance parameters of a node's hardware and Internet connection. For simplicity, only the
/// sender's lag and bandwidth are taken into account. (I.e. infinite downstream, limited
/// upstream.)
#[derive(Clone, Copy)]
pub struct HwQuality {
/// The network latency. This is added once for every message.
latency: Duration,
/// The inverse bandwidth, in time per byte.
inv_bw: Duration,
/// The CPU time multiplier: how much slower, in percent, is this node than your computer?
cpu_factor: u32,
}
2018-05-17 02:51:14 -07:00
/// A "node" running an instance of the algorithm `D`.
pub struct TestNode<D: ConsensusProtocol> {
2018-05-17 02:51:14 -07:00
/// This node's own ID.
2018-08-29 09:08:35 -07:00
id: D::NodeId,
2018-05-17 02:51:14 -07:00
/// The instance of the broadcast algorithm.
algo: D,
/// The duration for which this node's CPU has already been simulated.
time: Duration,
/// The time when this node last sent data over the network.
sent_time: Duration,
2018-05-17 02:51:14 -07:00
/// Incoming messages from other nodes that this node has not yet handled, with timestamps.
in_queue: VecDeque<TimestampedMessage<D>>,
/// Outgoing messages to other nodes, with timestamps.
out_queue: VecDeque<TimestampedMessage<D>>,
2018-05-17 02:51:14 -07:00
/// The values this node has output so far, with timestamps.
outputs: Vec<(Duration, D::Output)>,
/// The number of messages this node has handled so far.
message_count: usize,
/// The total size of messages this node has handled so far, in bytes.
message_size: u64,
/// The hardware and network quality of this node.
hw_quality: HwQuality,
2018-05-17 02:51:14 -07:00
}
type TestNodeStepResult<D> = CpStep<D>;
impl<D: ConsensusProtocol> TestNode<D>
where
D::Message: Serialize + DeserializeOwned,
{
2018-05-17 02:51:14 -07:00
/// Creates a new test node with the given broadcast instance.
fn new((algo, step): (D, CpStep<D>), hw_quality: HwQuality) -> TestNode<D> {
2018-07-21 01:18:08 -07:00
let out_queue = step
.messages
.into_iter()
.map(|msg| {
let ser_msg = bincode::serialize(&msg.message).expect("serialize");
TimestampedMessage {
time: Duration::default(),
sender_id: algo.our_id().clone(),
target: msg.target,
message: ser_msg,
}
})
.collect();
2018-07-21 01:18:08 -07:00
let outputs = step
.output
.into_iter()
.map(|out| (Duration::default(), out))
.collect();
let mut node = TestNode {
2018-05-17 02:51:14 -07:00
id: algo.our_id().clone(),
algo,
time: Duration::default(),
sent_time: Duration::default(),
in_queue: VecDeque::new(),
2018-07-21 01:18:08 -07:00
out_queue,
outputs,
message_count: 0,
message_size: 0,
hw_quality,
};
node.send_output_and_msgs(Step::default());
node
2018-05-17 02:51:14 -07:00
}
/// Handles the first message in the node's queue.
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
fn handle_message<R: Rng>(&mut self, rng: &mut R) {
let ts_msg = self.in_queue.pop_front().expect("message not found");
2018-05-17 02:51:14 -07:00
self.time = cmp::max(self.time, ts_msg.time);
self.message_count += 1;
self.message_size += ts_msg.message.len() as u64;
let start = Instant::now();
let msg = bincode::deserialize::<D::Message>(&ts_msg.message).expect("deserialize");
let step = self
.algo
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
.handle_message(&ts_msg.sender_id, msg, rng)
2018-05-17 02:51:14 -07:00
.expect("handling message");
self.time += start.elapsed() * self.hw_quality.cpu_factor / 100;
self.send_output_and_msgs(step)
}
/// Handles the algorithm's output and messages.
fn send_output_and_msgs(&mut self, step: TestNodeStepResult<D>) {
let start = Instant::now();
2018-07-18 05:15:47 -07:00
let out_msgs: Vec<_> = step
.messages
.into_iter()
.map(|msg| {
2018-07-21 01:18:08 -07:00
let ser_msg = bincode::serialize(&msg.message).expect("serialize");
(msg.target, ser_msg)
})
.collect();
self.time += start.elapsed() * self.hw_quality.cpu_factor / 100;
2018-05-17 02:51:14 -07:00
let time = self.time;
self.outputs
.extend(step.output.into_iter().map(|out| (time, out)));
self.sent_time = cmp::max(self.time, self.sent_time);
for (target, message) in out_msgs {
self.sent_time += self.hw_quality.inv_bw * message.len() as u32;
self.out_queue.push_back(TimestampedMessage {
time: self.sent_time + self.hw_quality.latency,
sender_id: self.id.clone(),
target,
message,
});
}
2018-05-17 02:51:14 -07:00
}
/// Returns the time when the next message can be handled.
fn next_event_time(&self) -> Option<Duration> {
match self.in_queue.front() {
2018-05-17 02:51:14 -07:00
None => None,
Some(ts_msg) => Some(cmp::max(ts_msg.time, self.time)),
}
}
/// Returns the number of messages this node has handled so far.
fn message_count(&self) -> usize {
self.message_count
}
/// Returns the size of messages this node has handled so far.
fn message_size(&self) -> u64 {
self.message_size
}
/// Adds a message into the incoming queue.
fn add_message(&mut self, msg: TimestampedMessage<D>) {
match self.in_queue.iter().position(|other| other.time > msg.time) {
None => self.in_queue.push_back(msg),
Some(i) => self.in_queue.insert(i, msg),
}
}
2018-05-17 02:51:14 -07:00
}
/// A collection of `TestNode`s representing a network.
pub struct TestNetwork<D: ConsensusProtocol> {
2018-08-29 09:08:35 -07:00
nodes: BTreeMap<D::NodeId, TestNode<D>>,
2018-05-17 02:51:14 -07:00
}
impl<D: ConsensusProtocol<NodeId = NodeId>> TestNetwork<D>
2018-05-17 02:51:14 -07:00
where
D::Message: Serialize + DeserializeOwned + Clone,
2018-05-17 02:51:14 -07:00
{
/// Creates a new network with `good_num` good nodes, and `dead_num` dead nodes.
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
pub fn new<F, R: Rng>(
good_num: usize,
2018-07-17 06:54:12 -07:00
adv_num: usize,
new_algo: F,
hw_quality: HwQuality,
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
rng: &mut R,
) -> TestNetwork<D>
2018-05-17 02:51:14 -07:00
where
F: Fn(NetworkInfo<NodeId>, SecretKey, PubKeyMap<NodeId>, &mut R) -> (D, CpStep<D>),
2018-05-17 02:51:14 -07:00
{
2018-08-29 09:08:35 -07:00
let node_ids = (0..(good_num + adv_num)).map(NodeId);
// Generate keys for signing and encrypting messages, and for threshold cryptography.
let sec_keys: BTreeMap<_, SecretKey> = node_ids.map(|id| (id, rng.gen())).collect();
let pub_keys = to_pub_keys(&sec_keys);
let netinfos = NetworkInfo::generate_map(pub_keys.keys().cloned(), rng)
.expect("Failed to create `NetworkInfo` map");
2018-08-29 09:08:35 -07:00
let new_node = |(id, netinfo): (NodeId, NetworkInfo<_>)| {
let algo = new_algo(netinfo, sec_keys[&id].clone(), pub_keys.clone(), rng);
(id, TestNode::new(algo, hw_quality))
};
2018-05-17 02:51:14 -07:00
let mut network = TestNetwork {
2018-07-17 06:54:12 -07:00
nodes: netinfos.into_iter().map(new_node).collect(),
2018-05-17 02:51:14 -07:00
};
let initial_msgs: Vec<_> = network
.nodes
.values_mut()
.flat_map(|node| node.out_queue.drain(..))
.collect();
network.dispatch_messages(initial_msgs);
2018-05-17 02:51:14 -07:00
network
}
/// Pushes the messages into the queues of the corresponding recipients.
fn dispatch_messages<Q>(&mut self, msgs: Q)
2018-05-17 02:51:14 -07:00
where
Q: IntoIterator<Item = TimestampedMessage<D>>,
2018-05-17 02:51:14 -07:00
{
for ts_msg in msgs {
for node in self.nodes.values_mut() {
if ts_msg.target.contains(&node.id) && node.id != ts_msg.sender_id {
node.add_message(ts_msg.clone())
2018-05-17 02:51:14 -07:00
}
}
}
}
/// Handles a queued message in one of the nodes with the earliest timestamp, if any. Returns
/// the recipient's ID.
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
pub fn step<R: Rng>(&mut self, rng: &mut R) -> Option<NodeId> {
2018-05-21 02:01:49 -07:00
let min_time = self
.nodes
2018-05-17 02:51:14 -07:00
.values()
.filter_map(TestNode::next_event_time)
.min()?;
2018-08-29 09:08:35 -07:00
let min_ids: Vec<NodeId> = self
2018-05-21 02:01:49 -07:00
.nodes
2018-05-17 02:51:14 -07:00
.iter()
.filter(|(_, node)| node.next_event_time() == Some(min_time))
.map(|(id, _)| *id)
.collect();
let next_id = *min_ids.choose(rng).unwrap();
2018-05-17 02:51:14 -07:00
let msgs: Vec<_> = {
let node = self.nodes.get_mut(&next_id).unwrap();
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
node.handle_message(rng);
node.out_queue.drain(..).collect()
2018-05-17 02:51:14 -07:00
};
self.dispatch_messages(msgs);
Some(next_id)
2018-05-17 02:51:14 -07:00
}
/// Returns the number of messages that have been handled so far.
pub fn message_count(&self) -> usize {
self.nodes.values().map(TestNode::message_count).sum()
}
/// Returns the total size of messages that have been handled so far.
pub fn message_size(&self) -> u64 {
self.nodes.values().map(TestNode::message_size).sum()
}
2018-05-17 02:51:14 -07:00
}
/// The timestamped batches for a particular epoch that have already been output.
#[derive(Clone, Default)]
struct EpochInfo {
2018-08-29 09:08:35 -07:00
nodes: BTreeMap<NodeId, (Duration, Batch<Transaction, NodeId>)>,
2018-05-17 02:51:14 -07:00
}
2018-10-25 08:07:52 -07:00
type QHB = SenderQueue<QueueingHoneyBadger<Transaction, NodeId, Vec<Transaction>>>;
2018-05-17 02:51:14 -07:00
impl EpochInfo {
/// Adds a batch to this epoch. Prints information if the epoch is complete.
fn add(
&mut self,
2018-08-29 09:08:35 -07:00
id: NodeId,
time: Duration,
2018-08-29 09:08:35 -07:00
batch: &Batch<Transaction, NodeId>,
2018-10-25 08:07:52 -07:00
network: &TestNetwork<QHB>,
) {
2018-05-17 02:51:14 -07:00
if self.nodes.contains_key(&id) {
return;
}
self.nodes.insert(id, (time, batch.clone()));
if self.nodes.len() < network.nodes.len() {
2018-05-17 02:51:14 -07:00
return;
}
let (min_t, max_t) = self
2018-05-21 02:01:49 -07:00
.nodes
2018-05-17 02:51:14 -07:00
.values()
.map(|&(time, _)| time)
.minmax()
.into_option()
.unwrap();
let txs = batch.iter().unique().count();
2018-05-17 02:51:14 -07:00
println!(
"{:>5} {:6} {:6} {:5} {:9} {:>9}B",
2018-11-01 11:18:08 -07:00
batch.epoch().to_string().cyan(),
2018-07-17 06:54:12 -07:00
min_t.as_secs() * 1000 + u64::from(max_t.subsec_nanos()) / 1_000_000,
max_t.as_secs() * 1000 + u64::from(max_t.subsec_nanos()) / 1_000_000,
txs,
network.message_count() / network.nodes.len(),
match NumberPrefix::decimal(network.message_size() as f64 / network.nodes.len() as f64)
{
Standalone(bytes) => format!("{:3.0} ", bytes),
Prefixed(prefix, n) => format!("{:3.0} {}", n, prefix),
}
2018-05-17 02:51:14 -07:00
);
}
}
/// Proposes `num_txs` values and expects nodes to output and order them.
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
fn simulate_honey_badger<R: Rng>(mut network: TestNetwork<QHB>, rng: &mut R) {
2018-05-17 02:51:14 -07:00
// Handle messages until all nodes have output all transactions.
println!(
"{}",
"Epoch Min/Max Time Txs Msgs/Node Size/Node".bold()
);
2018-05-17 02:51:14 -07:00
let mut epochs = Vec::new();
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
while let Some(id) = network.step(rng) {
2018-05-17 02:51:14 -07:00
for &(time, ref batch) in &network.nodes[&id].outputs {
2018-11-01 11:18:08 -07:00
let epoch = batch.epoch() as usize;
if epochs.len() <= epoch {
epochs.resize(epoch + 1, EpochInfo::default());
2018-05-17 02:51:14 -07:00
}
epochs[epoch].add(id, time, batch, &network);
2018-05-17 02:51:14 -07:00
}
}
}
/// Parses the command line arguments.
fn parse_args() -> Result<Args, docopt::Error> {
Docopt::new(USAGE)?
.version(Some(VERSION.to_string()))
.parse()?
.deserialize()
}
fn main() {
2018-05-31 05:27:55 -07:00
env_logger::init();
let mut rng = OsRng::new().expect("Could not initialize OS random number generator.");
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
2018-05-17 02:51:14 -07:00
let args = parse_args().unwrap_or_else(|e| e.exit());
if args.flag_n <= 3 * args.flag_f {
let msg = "Honey Badger only works if less than one third of the nodes are faulty.";
println!("{}", msg.red().bold());
}
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
2018-05-17 02:51:14 -07:00
println!("Simulating Honey Badger with:");
println!("{} nodes, {} faulty", args.flag_n, args.flag_f);
println!(
"{} transactions, {} bytes each, ≤{} per epoch",
args.flag_txs, args.flag_tx_size, args.flag_b
);
println!(
"Network lag: {} ms, bandwidth: {} kbit/s, {:5.2}% CPU speed",
args.flag_lag, args.flag_bw, args.flag_cpu
2018-05-17 02:51:14 -07:00
);
println!();
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
2018-05-17 02:51:14 -07:00
let num_good_nodes = args.flag_n - args.flag_f;
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
let txs: Vec<_> = (0..args.flag_txs)
.map(|_| rng.sample_iter(&Standard).take(args.flag_tx_size).collect())
.collect();
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
let new_honey_badger = |netinfo: NetworkInfo<NodeId>, secret_key, pub_keys, rng: &mut OsRng| {
2018-11-01 11:18:08 -07:00
let our_id = *netinfo.our_id();
2019-07-23 02:23:42 -07:00
let peer_ids: Vec<_> = netinfo.other_ids().cloned().collect();
let dhb = DynamicHoneyBadger::builder().build(netinfo, secret_key, pub_keys);
2018-10-25 08:07:52 -07:00
let (qhb, qhb_step) = QueueingHoneyBadger::builder(dhb)
2018-06-28 12:31:27 -07:00
.batch_size(args.flag_b)
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
.build_with_transactions(txs.clone(), rng)
2018-10-25 08:07:52 -07:00
.expect("instantiate QueueingHoneyBadger");
2018-11-01 11:18:08 -07:00
let (sq, mut step) = SenderQueue::builder(qhb, peer_ids.into_iter()).build(our_id);
2018-12-18 07:17:46 -08:00
let output = step.extend_with(qhb_step, |fault| fault, Message::from);
assert!(output.is_empty());
2018-10-25 08:07:52 -07:00
(sq, step)
};
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
let hw_quality = HwQuality {
latency: Duration::from_millis(args.flag_lag),
inv_bw: Duration::new(0, 8_000_000 / args.flag_bw),
cpu_factor: (10_000f32 / args.flag_cpu) as u32,
2018-05-17 02:51:14 -07:00
};
OsRng / external RNG Refactoring (#357) * Use `OsRng` in place of `thread_rng`. This changes the defaults of any builder by instantiating an `OsRng` instead of a `thread_rng`, the former being much more secure than the latter. Additionally, all the unit tests that still instantiate RNGs manually used `OsRng`s as well; while there is no actual need for this level of security in tests, the performance overhead is very small and random number generation complexity has such a small impact on these tests that the convenience of being able to ban `thread_rng` from the codebase altogether, setting a good example and avoid issues when refactoring later greatly outweigh the negatives. * Instead of storing random number generators in the various consensus algorithm instances, pass them in from the outside whenever they are needed. This changes a large amount of interfaces (and in this commit is only partially done, since `DistAlgorithm` needs to be fundamentally altered as well. It also obsoletes parts of the `util` module. * Added an `R: Rng` type parameter to both methods of `DistAlgorithm`, forcing callers to pass in their own Rngs. * Fixed documentation grammar and spelling in some of the altered interfaces due to RNG refactoring. * Move `rng` argument to the end of the argument for most functions. Also includes a reformatting due to Rust 1.30. * Updated tests, accomodate `rng`-API changes. * Fixed remaining compilation issues with new RNG code. * Fix illegal `self` import outside curly braces. * Cleaned up comments and fixed broken definition of `broadcast_input`. * Updated existing test cases to properly work with static dispatch randomness. * Do not use boxed `Rng`s for key generation in test networks. * Use the passed-in `Rng` in `ReorderingAdversary`, instead of storing a boxed one. * Fixed clippy lints after refactoring. * Removed some no-longer necessary manual `fmt::Debug` implementations in test framework. * Use `OsRng` even in tests in `binary_agreement_mitm`. * Use a proper deterministic RNG in tests `binary_agreement_mitm`. * Refactor `examples/simulation.rs` by not using `ThreadRng`, passing generic `Rng` parameters throughout and using a type alias instead of a newtype as the `Transaction`. * Remove `thread_rng` use from `examples/node.rs`. * Explicitly construct `InternalContrib` in `DynamicHoneyBadger::propose`. * Fixed typo in description of `DistAlgorithm` trait.
2018-12-14 04:51:09 -08:00
let network = TestNetwork::new(
num_good_nodes,
args.flag_f,
new_honey_badger,
hw_quality,
&mut rng,
);
simulate_honey_badger(network, &mut rng);
2018-05-17 02:51:14 -07:00
}