Created
July 29, 2019 20:26
-
-
Save Silur/0a69ffc4234b3d9eafde5741eb7048c2 to your computer and use it in GitHub Desktop.
hashcash rust
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
extern crate sha3; | |
extern crate num_bigint; | |
extern crate num_traits; | |
use num_bigint::{BigUint, ToBigUint}; | |
use sha3::{Digest, Sha3_256}; | |
fn sha3(data: &Vec) -> [u8; 32] { | |
let mut hasher = Sha3_256::new(); | |
hasher.input(data); | |
let r = hasher.result(); | |
let mut ret = [0u8; 32]; | |
for i in 0..32 { | |
ret[i] = r[i]; | |
} | |
ret | |
} | |
pub fn genpow(data: Vec, difficulty: &BigUint) -> ([u8; 32], u32) { | |
let mut nonce = 0u32; | |
let mut input = data.clone(); | |
while BigUint::from_bytes_be(&sha3(&input)) >= *difficulty { | |
nonce += 1; | |
input = data.clone(); | |
input.append(&mut nonce.to_be_bytes().to_vec()); | |
} | |
return (sha3(&input), nonce) | |
} | |
pub fn verify(data: Vec, pow: [u8; 32], nonce: u32, difficulty: &BigUint) -> bool { | |
let mut input = data.clone(); | |
input.append(&mut nonce.to_be_bytes().to_vec()); | |
return BigUint::from_bytes_be(&sha3(&input)) < *difficulty; | |
} | |
fn main() { | |
// 2^240 | |
let mut difficulty: BigUint = BigUint::parse_bytes(b"1766847064778384329583297500742918515827483896875618958121606201292619776", 10).unwrap(); | |
println!("difficulty set to {}", difficulty); | |
println!("generating pow..."); | |
let (pow, nonce) = genpow(vec![1, 2, 3, 4, 5], &difficulty); | |
println!("got it! {:x?}", pow); | |
println!("verification: {}", verify(vec![1,2,3,4,5], pow, nonce, &difficulty)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment