Created
February 6, 2020 05:52
-
-
Save davich/8912b985897afafcfa1c512ff48893f0 to your computer and use it in GitHub Desktop.
mine.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use sha2::{Digest, Sha256}; | |
fn main() { | |
println!("Answer is {:?}", rust_mine("hello")); | |
} | |
pub fn rust_mine(text: &str) -> String { | |
let mut hasher = Sha256::new(); | |
(0..std::usize::MAX) | |
.find_map(|nonce| { | |
hasher.input(&format!("{}{}", text, nonce)); | |
let result = hasher.clone().result(); | |
// Ensure the first two hex digets match, then we only want to check the part of the | |
// 3rd hex digit. | |
// | |
// 11 >> 4 # => 0 | |
// 12 >> 4 # => 0 | |
// 22 >> 4 # => 1 | |
if &result[0..2] == &[0, 0] && result[2] >> 4 == 0 { | |
Some(format!("{:x}", result)) | |
} else { | |
None | |
} | |
}) | |
.expect("unable to find answer") | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn it_works() { | |
assert_eq!( | |
rust_mine("hello"), | |
"00000ae1e9539146cffff9f6e177926993877055191da80dba6171711f33b363".to_string() | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah wow that hex matching is way faster then the string and splice