From af1d44e8b0716be1d1e68a4255448e3613567604 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Fri, 15 Feb 2019 12:56:50 +1100 Subject: [PATCH] Add shuffling to fuzzer, fixing a bug We were being to strict on list length, it can be 2**24 as all index's will need to be less than that. --- eth2/utils/swap_or_not_shuffle/Cargo.toml | 1 + eth2/utils/swap_or_not_shuffle/src/lib.rs | 46 +++++++++++++++++++++-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/eth2/utils/swap_or_not_shuffle/Cargo.toml b/eth2/utils/swap_or_not_shuffle/Cargo.toml index 3dc03da82e..272abf6084 100644 --- a/eth2/utils/swap_or_not_shuffle/Cargo.toml +++ b/eth2/utils/swap_or_not_shuffle/Cargo.toml @@ -12,3 +12,4 @@ int_to_bytes = { path = "../int_to_bytes" } [dev-dependencies] yaml-rust = "0.4.2" hex = "0.3" +ethereum-types = "0.5" diff --git a/eth2/utils/swap_or_not_shuffle/src/lib.rs b/eth2/utils/swap_or_not_shuffle/src/lib.rs index 22d657bb44..753265f3e7 100644 --- a/eth2/utils/swap_or_not_shuffle/src/lib.rs +++ b/eth2/utils/swap_or_not_shuffle/src/lib.rs @@ -13,8 +13,8 @@ use std::io::Cursor; /// Returns `None` under any of the following conditions: /// - `list_size == 0` /// - `index >= list_size` -/// - `list_size >= 2**24` -/// - `list_size >= usize::max_value() / 2` +/// - `list_size > 2**24` +/// - `list_size > usize::max_value() / 2` pub fn get_permutated_index( index: usize, list_size: usize, @@ -23,8 +23,8 @@ pub fn get_permutated_index( ) -> Option { if list_size == 0 || index >= list_size - || list_size >= usize::max_value() / 2 - || list_size >= 2_usize.pow(24) + || list_size > usize::max_value() / 2 + || list_size > 2_usize.pow(24) { return None; } @@ -67,10 +67,48 @@ fn bytes_to_int64(bytes: &[u8]) -> u64 { #[cfg(test)] mod tests { use super::*; + use ethereum_types::H256 as Hash256; use hex; use std::{fs::File, io::prelude::*, path::PathBuf}; use yaml_rust::yaml; + #[test] + #[ignore] + fn fuzz_test() { + let max_list_size = 2_usize.pow(24); + let test_runs = 1000; + + // Test at max list_size with the end index. + for _ in 0..test_runs { + let index = max_list_size - 1; + let list_size = max_list_size; + let seed = Hash256::random(); + let shuffle_rounds = 90; + + assert!(get_permutated_index(index, list_size, &seed[..], shuffle_rounds).is_some()); + } + + // Test at max list_size low indices. + for i in 0..test_runs { + let index = i; + let list_size = max_list_size; + let seed = Hash256::random(); + let shuffle_rounds = 90; + + assert!(get_permutated_index(index, list_size, &seed[..], shuffle_rounds).is_some()); + } + + // Test at max list_size high indices. + for i in 0..test_runs { + let index = max_list_size - 1 - i; + let list_size = max_list_size; + let seed = Hash256::random(); + let shuffle_rounds = 90; + + assert!(get_permutated_index(index, list_size, &seed[..], shuffle_rounds).is_some()); + } + } + #[test] fn returns_none_for_zero_length_list() { assert_eq!(None, get_permutated_index(100, 0, &[42, 42], 90));