Skip to content

Instantly share code, notes, and snippets.

@davich
Created February 6, 2020 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davich/8912b985897afafcfa1c512ff48893f0 to your computer and use it in GitHub Desktop.
Save davich/8912b985897afafcfa1c512ff48893f0 to your computer and use it in GitHub Desktop.
mine.rs
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()
);
}
}
@saramic
Copy link

saramic commented Feb 6, 2020

Yeah wow that hex matching is way faster then the string and splice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment