Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils): add random module #267

Merged
merged 3 commits into from
Oct 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/utils-random.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"stronghold-utils": minor
---

[[PR 267](https://github.com/iotaledger/stronghold.rs/pull/267)]
Extract `random` functions from `test_utils` into own module.
1 change: 0 additions & 1 deletion client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ p2p = ["stronghold-p2p", "futures"]
hex = "0.4.2"
criterion = { version = "0.3.3", features = ["async_tokio"] }
clap = { version = "3.0.0-beta.1", features = [ "yaml" ] }
rand = "0.8.3"
tokio = {version = "1.9", features = ["rt-multi-thread"] }

[[example]]
Expand Down
8 changes: 4 additions & 4 deletions client/src/tests/fresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use crypto::{keys::slip10::Chain, utils::rand::fill};
pub use stronghold_utils::test_utils::{self, fresh::*};
pub use stronghold_utils::{random::*, test_utils};

use crate::{Location, RecordHint};

Expand All @@ -15,13 +15,13 @@ pub fn record_hint() -> RecordHint {

/// Generates a random [`Location`].
pub fn location() -> Location {
Location::generic(bytestring(), bytestring())
Location::generic(bytestring(4096), bytestring(4096))
}

/// generates a random string based on a coinflip.
pub fn passphrase() -> Option<String> {
if coinflip() {
Some(string())
Some(string(4096))
} else {
None
}
Expand All @@ -32,7 +32,7 @@ pub fn hd_path() -> (String, Chain) {
let mut s = "m".to_string();
let mut is = vec![];
while coinflip() {
let i = rand::random::<u32>() & 0x7fffff;
let i = random::<u32>() & 0x7fffff;
s.push_str(&format!("/{}'", i.to_string()));
is.push(i);
}
Expand Down
4 changes: 2 additions & 2 deletions client/src/tests/procedures_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::fresh;
use crate::{ProcResult, Procedure, ResultMessage, SLIP10DeriveInput, Stronghold};

async fn setup_stronghold() -> (Vec<u8>, Stronghold) {
let cp = fresh::bytestring();
let cp = fresh::bytestring(u8::MAX.into());

let s = Stronghold::init_stronghold_system(cp.clone(), vec![]).await.unwrap();
(cp, s)
Expand Down Expand Up @@ -77,7 +77,7 @@ async fn usecase_ed25519() {
r => panic!("unexpected result: {:?}", r),
};

let msg = fresh::bytestring();
let msg = fresh::bytestring(4096);

let sig = match sh
.runtime_exec(Procedure::Ed25519Sign {
Expand Down
1 change: 0 additions & 1 deletion engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ features = [ "random", "chacha", "hmac", "sha", "x25519", "blake2b" ]

[dev-dependencies]
tempfile = "3.1.0"
rand = "0.8.3"
proptest = "1.0.0"
criterion = "0.3.3"
json = "0.12"
Expand Down
31 changes: 19 additions & 12 deletions engine/src/snapshot/logic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,14 @@ fn check_header<I: Read>(input: &mut I) -> crate::Result<()> {
#[cfg(test)]
mod test {
use super::*;
use stronghold_utils::test_utils::{corrupt, corrupt_file_at, fresh};
use stronghold_utils::{
random,
test_utils::{corrupt, corrupt_file_at},
};

fn random_bytestring() -> Vec<u8> {
random::bytestring(4096)
}

fn random_key() -> Key {
let mut key: Key = [0u8; KEY_SIZE];
Expand All @@ -221,8 +228,8 @@ mod test {
#[test]
fn test_write_read() -> crate::Result<()> {
let key: Key = random_key();
let bs0 = fresh::bytestring();
let ad = fresh::bytestring();
let bs0 = random_bytestring();
let ad = random_bytestring();

let mut buf = Vec::new();
write(&bs0, &mut buf, &key, &ad)?;
Expand All @@ -234,8 +241,8 @@ mod test {
#[should_panic]
fn test_corrupted_read_write() {
let key: Key = random_key();
let bs0 = fresh::bytestring();
let ad = fresh::bytestring();
let bs0 = random_bytestring();
let ad = random_bytestring();

let mut buf = Vec::new();
write(&bs0, &mut buf, &key, &ad).unwrap();
Expand All @@ -250,8 +257,8 @@ mod test {
pb.push("snapshot");

let key: Key = random_key();
let bs0 = fresh::bytestring();
let ad = fresh::bytestring();
let bs0 = random_bytestring();
let ad = random_bytestring();

write_to(&bs0, &pb, &key, &ad)?;
let bs1 = read_from(&pb, &key, &ad)?;
Expand All @@ -268,8 +275,8 @@ mod test {
pb.push("snapshot");

let key: Key = random_key();
let bs0 = fresh::bytestring();
let ad = fresh::bytestring();
let bs0 = random_bytestring();
let ad = random_bytestring();

write_to(&bs0, &pb, &key, &ad).unwrap();
corrupt_file_at(&pb);
Expand All @@ -282,11 +289,11 @@ mod test {
let mut pb = f.into_path();
pb.push("snapshot");

write_to(&fresh::bytestring(), &pb, &random_key(), &fresh::bytestring())?;
write_to(&random_bytestring(), &pb, &random_key(), &random_bytestring())?;

let key: Key = random_key();
let bs0 = fresh::bytestring();
let ad = fresh::bytestring();
let bs0 = random_bytestring();
let ad = random_bytestring();
write_to(&bs0, &pb, &key, &ad).unwrap();
let bs1 = read_from(&pb, &key, &ad)?;
assert_eq!(bs0, bs1);
Expand Down
4 changes: 2 additions & 2 deletions p2p/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ libp2p = { version = "0.39", default-features = false, features = ["noise", "yam
serde = { version = "1.0", default-features = false, features = [ "alloc", "derive" ] }
serde_json = { version = "1.0", default-features = false, features = [ "alloc" ] }
smallvec = "1.6.1"
stronghold-derive = { path = "../derive", version = "0.2.0" }
stronghold-derive = { path = "../derive", version = "0.2" }
tokio = { version = "1.10", default-features = false, features = ["rt", "sync"] }
wasm-timer = "0.2.5"

Expand All @@ -31,6 +31,6 @@ relay = ["libp2p/relay"]
tcp-transport = ["libp2p/tcp-tokio", "libp2p/dns-tokio", "libp2p/websocket"]

[dev-dependencies]
rand = "0.8.3"
stronghold-utils = { path = "../utils", version = "0.3" }
tokio = {version = "1.10", features = ["time", "macros"]}
libp2p = { version = "0.39", default-features = false, features = ["tcp-tokio"] }
5 changes: 3 additions & 2 deletions p2p/tests/test_dialing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use p2p::{
};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use stronghold_utils::random::random;
use tokio::runtime::Builder;

type TestPeer = StrongholdP2p<Request, Response>;
Expand Down Expand Up @@ -46,7 +47,7 @@ async fn init_peer() -> (mpsc::Receiver<NetworkEvent>, TestPeer) {
}

fn rand_bool(n: u8) -> bool {
rand::random::<u8>() % n > 0
random::<u8>() % n > 0
}

#[derive(Debug)]
Expand Down Expand Up @@ -82,7 +83,7 @@ struct TestSourceConfig {

impl TestSourceConfig {
fn random() -> Self {
let set_relay = match rand::random::<u8>() % 10 {
let set_relay = match random::<u8>() % 10 {
0 | 1 | 2 | 3 => UseRelay::Default,
4 | 5 | 6 => UseRelay::UseSpecificRelay,
7 | 8 | 9 => UseRelay::NoRelay,
Expand Down
13 changes: 7 additions & 6 deletions p2p/tests/test_firewall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use p2p::{
};
use serde::{Deserialize, Serialize};
use std::{borrow::Borrow, fmt, future, marker::PhantomData, task::Poll, time::Duration};
use stronghold_utils::random::random;
use tokio::time::sleep;

type TestPeer = StrongholdP2p<Request, Response, RequestPermission>;
Expand Down Expand Up @@ -79,7 +80,7 @@ enum TestPermission {

impl TestPermission {
fn random() -> Self {
match rand::random::<u8>() % 4 {
match random::<u8>() % 4 {
0 => TestPermission::AllowAll,
1 => TestPermission::RejectAll,
2 => TestPermission::PingOnly,
Expand Down Expand Up @@ -145,9 +146,9 @@ impl<'a> RulesTestConfig<'a> {
b_events_rx: &'a mut mpsc::Receiver<NetworkEvent>,
b_request_rx: &'a mut mpsc::Receiver<ReceiveRequest<Request, Response>>,
) -> Self {
let a_rule = (rand::random::<u8>() % 2 > 0).then(TestPermission::random);
let b_rule = (rand::random::<u8>() % 2 > 0).then(TestPermission::random);
let req = (rand::random::<u8>() % 2 > 0)
let a_rule = (random::<u8>() % 2 > 0).then(TestPermission::random);
let b_rule = (random::<u8>() % 2 > 0).then(TestPermission::random);
let req = (random::<u8>() % 2 > 0)
.then(|| Request::Ping)
.unwrap_or(Request::Other);
RulesTestConfig {
Expand Down Expand Up @@ -310,7 +311,7 @@ enum FwRuleRes {

impl FwRuleRes {
fn random() -> Self {
match rand::random::<u8>() % 6 {
match random::<u8>() % 6 {
0 | 1 => FwRuleRes::AllowAll,
2 => FwRuleRes::RejectAll,
3 | 4 => FwRuleRes::Ask,
Expand All @@ -329,7 +330,7 @@ enum FwApprovalRes {

impl FwApprovalRes {
fn random() -> Self {
match rand::random::<u8>() % 4 {
match random::<u8>() % 4 {
0 | 1 => FwApprovalRes::Allow,
2 => FwApprovalRes::Reject,
3 => FwApprovalRes::Drop,
Expand Down
1 change: 1 addition & 0 deletions utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

pub mod random;
pub mod test_utils;
pub use stronghold_derive::{GuardDebug, RequestPermissions};
43 changes: 43 additions & 0 deletions utils/src/random.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use rand::distributions::{Distribution, Standard};

// Random value for `T`.
pub fn random<T>() -> T
where
Standard: Distribution<T>,
{
rand::random()
}

// Random Bytestring with random length in range 1..max_len.
pub fn bytestring(max_len: usize) -> Vec<u8> {
let s = (random::<usize>() % (max_len - 1)) + 1;
let mut bs = Vec::with_capacity(s);
for _ in 1..s {
bs.push(random());
}
bs
}

// Random string with random length in range 1..max_len.
pub fn string(max_len: usize) -> String {
let l = (random::<usize>() % (max_len - 1)) + 1;

let mut s = String::with_capacity(l);
for _ in 0..l {
s.push(random())
}
s
}

// Random bool.
pub fn coinflip() -> bool {
random()
}

// Random usize in range 0..upper_bound (excluding the upper bound).
pub fn usize(upper_bound: usize) -> usize {
random::<usize>() % upper_bound
}
9 changes: 4 additions & 5 deletions utils/src/test_utils/mod.rs → utils/src/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use crate::random;
use std::{
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom, Write},
path::Path,
};

pub mod fresh;

pub fn corrupt(bs: &mut [u8]) {
if bs.is_empty() {
return;
}
loop {
let i = rand::random::<usize>() % bs.len();
let i = random::usize(bs.len());
let b = bs[i];
bs[i] = rand::random();
if b != bs[i] && rand::random() {
bs[i] = random::random();
if b != bs[i] && random::coinflip() {
break;
}
}
Expand Down
51 changes: 0 additions & 51 deletions utils/src/test_utils/fresh.rs

This file was deleted.