Last active
March 11, 2021 07:49
-
-
Save harshvishu/40996b995acd66ff5f6f971f7313978a to your computer and use it in GitHub Desktop.
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
/** | |
Creates a SHA-256 hash of a Block | |
- Parameter block: Block | |
- returns: String | |
*/ | |
pub fn hash(block: &Block) -> String { | |
let json = serde_json::to_string(block).unwrap(); | |
let readable_string = Cursor::new(&json); | |
sha::calc_sha_sum(readable_string).hash_string() | |
} | |
/** | |
Simple Proof of Work Algorithm: | |
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' | |
- p is the previous proof, and p' is the new proof | |
- Parameter: last_proof: u64 | |
- returns: u64 | |
*/ | |
pub fn proof_of_work(last_proof: u64) -> u64 { | |
let mut proof: u64 = 0; | |
while !Chain::is_valid_proof(last_proof, proof) { | |
proof += 1; | |
} | |
proof | |
} | |
/** | |
Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes? | |
- Parameter last_proof: u64 Previous Proof | |
- Parameter proof: u64 Current Proof | |
- returns: True if correct, False if not. | |
*/ | |
pub fn is_valid_proof(last_proof: u64, proof: u64) -> bool { | |
let guess = format!("{}{}", last_proof, proof); | |
let readable_guess = Cursor::new(&guess); | |
let guess_hash = sha::calc_sha_sum(readable_guess); | |
guess_hash.hash_string().ends_with("0000") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment