Added hashing result to PoW struct

This commit is contained in:
Robert Kornacki 2019-07-22 12:22:53 -04:00
parent 7654f2722e
commit c1ec5d2a68

View file

@ -2,12 +2,13 @@ use serde::{Deserialize, Serialize};
use sha2::{digest::FixedOutput, Digest, Sha256};
use std::marker::PhantomData;
const SALT: &str = "35af8f4890981391c191e6df45b5f780812ddf0213f29299576ac1c98e18173e";
const SALT: &str = "79ziepia7vhjgviiwjhnend3ofjqocsi2winc4ptqhmkvcajihywxcizewvckg9h6gs4j83v9";
/// Proof of work over concrete type T. T can be any type that implements serde::Serialize.
#[derive(Serialize, Deserialize, PartialEq, Clone, Copy, Debug)]
pub struct Pow<T> {
proof: u128,
nonce: u128,
result: u128,
_spook: PhantomData<T>,
}
@ -36,11 +37,14 @@ impl<T: Serialize> Pow<T> {
pub fn prove_work_serialized(prefix: &[u8], difficulty: u128) -> Pow<T> {
let prefix_sha = Sha256::new().chain(SALT).chain(prefix);
let mut n = 0;
while score(prefix_sha.clone(), n) < difficulty {
let mut result = 0;
while result < difficulty {
n += 1;
result = score(prefix_sha.clone(), n);
}
Pow {
proof: n,
nonce: n,
result: result,
_spook: PhantomData,
}
}
@ -55,14 +59,14 @@ impl<T: Serialize> Pow<T> {
/// Calculate the pow score of an already serialized T and self.
/// The input is assumed to be serialized using network byte order.
pub fn score_serialized(&self, target: &[u8]) -> u128 {
score(Sha256::new().chain(SALT).chain(target), self.proof)
score(Sha256::new().chain(SALT).chain(target), self.nonce)
}
}
fn score(prefix_sha: Sha256, proof: u128) -> u128 {
fn score(prefix_sha: Sha256, nonce: u128) -> u128 {
first_bytes_as_u128(
prefix_sha
.chain(&proof.to_be_bytes()) // to_be_bytes() converts to network endian
.chain(&nonce.to_be_bytes()) // to_be_bytes() converts to network endian
.fixed_result()
.as_slice(),
)