Skip to content

Commit

Permalink
Parallel proof of work + Update Rayon (#645)
Browse files Browse the repository at this point in the history
* Parallel proof of work

* Fmt

* Fix clippy
  • Loading branch information
MauroToscano authored Oct 30, 2023
1 parent 8b95b81 commit dff5f2d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion provers/cairo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ serde_cbor = { version = "0.11.1" }
# For cli
clap = { version = "4.4.6", features = ["derive"], optional = true }
# Parallelization crates
rayon = { version = "1.7.0", optional = true }
rayon = { version = "1.8.0", optional = true }

# wasm
wasm-bindgen = { version = "0.2", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion provers/stark/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ num-integer = "0.1.45"
itertools = "0.11.0"

# Parallelization crates
rayon = { version = "1.7.0", optional = true }
rayon = { version = "1.8.0", optional = true }

# wasm
wasm-bindgen = { version = "0.2", optional = true }
Expand Down
14 changes: 12 additions & 2 deletions provers/stark/src/grinding.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#[cfg(feature = "parallel")]
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use sha3::{Digest, Keccak256};

const PREFIX: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xed];
Expand Down Expand Up @@ -38,8 +40,16 @@ pub fn is_valid_nonce(seed: &[u8; 32], nonce: u64, grinding_factor: u8) -> bool
pub fn generate_nonce(seed: &[u8; 32], grinding_factor: u8) -> Option<u64> {
let inner_hash = get_inner_hash(seed, grinding_factor);
let limit = 1 << (64 - grinding_factor);
(0..u64::MAX)
.find(|&candidate_nonce| is_valid_nonce_for_inner_hash(&inner_hash, candidate_nonce, limit))

#[cfg(not(feature = "parallel"))]
return (0..u64::MAX).find(|&candidate_nonce| {
is_valid_nonce_for_inner_hash(&inner_hash, candidate_nonce, limit)
});

#[cfg(feature = "parallel")]
return (0..u64::MAX).into_par_iter().find_any(|&candidate_nonce| {
is_valid_nonce_for_inner_hash(&inner_hash, candidate_nonce, limit)
});
}

/// Checks if the leftmost 8 bytes of `Hash(inner_hash || candidate_nonce)` are less than `limit`
Expand Down

0 comments on commit dff5f2d

Please sign in to comment.