Skip to content

Commit

Permalink
Add Frontier::random_of_size to facilitate testing.
Browse files Browse the repository at this point in the history
  • Loading branch information
nuttycom committed Mar 16, 2024
1 parent 4ea60ea commit fec53a7
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion incrementalmerkletree/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,13 @@ rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
either = "1.8"
proptest = { version = "1.0.0", optional = true }
rand = { version = "0.8", optional = true }
rand_core = { version = "0.6", optional = true }

[dev-dependencies]
proptest = "1.0.0"
rand = "0.8"
rand_core = "0.6"

[features]
# The legacy-api feature guards types and functions that were previously
Expand All @@ -31,4 +35,4 @@ proptest = "1.0.0"
legacy-api = []
# The test-dependencies feature guards types and functions that are
# useful for testing incremental Merkle trees and Merkle tree frontiers.
test-dependencies = ["proptest"]
test-dependencies = ["dep:proptest", "dep:rand", "dep:rand_core"]
29 changes: 29 additions & 0 deletions incrementalmerkletree/src/frontier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ use crate::{Address, Hashable, Level, MerklePath, Position, Source};
#[cfg(feature = "legacy-api")]
use {std::collections::VecDeque, std::iter::repeat};

#[cfg(any(test, feature = "test-dependencies"))]
use rand::{
distributions::{Distribution, Standard},
Rng, RngCore,
};

/// Validation errors that can occur during reconstruction of a Merkle frontier from
/// its constituent parts.
#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -287,6 +293,29 @@ impl<H: Hashable + Clone, const DEPTH: u8> Frontier<H, DEPTH> {
}
}

#[cfg(any(test, feature = "test-dependencies"))]
impl<H: Hashable + Clone, const DEPTH: u8> Frontier<H, DEPTH>
where
Standard: Distribution<H>,
{
/// Generates a random frontier of a Merkle tree having the specified size.
pub fn random_of_size<R: RngCore>(rng: &mut R, tree_size: u64) -> Self {
if tree_size == 0 {
Frontier::empty()
} else {
let position = tree_size.into();
Frontier::from_parts(
position,
rng.gen(),
std::iter::repeat_with(|| rng.gen())
.take(position.past_ommer_count().into())
.collect(),
)
.unwrap()
}
}
}

#[cfg(feature = "legacy-api")]
#[cfg_attr(docsrs, doc(cfg(feature = "legacy-api")))]
pub struct PathFiller<H> {
Expand Down

0 comments on commit fec53a7

Please sign in to comment.