1extern crate sha2;
8
9use crate::wsactor::{MiningComplete, NonceUpdate};
10use actix::prelude::*;
11use sha2::{Digest, Sha256};
12
13fn calculate_hash(input: &str) -> String {
17 let mut hasher = Sha256::new();
18 hasher.update(input);
19 let result = hasher.finalize();
20 hex::encode(result)
21}
22
23pub fn mine_block(
27 data: &str,
28 previous_hash: &str,
29 difficulty: usize,
30 addr: Option<Addr<crate::wsactor::MiningProgressWebSocket>>,
31) -> (u64, String) {
32 let mut nonce = 0;
33 let target = "0".repeat(difficulty);
34 loop {
35 let input = format!("{}{}{}", data, previous_hash, nonce);
36 let hash = calculate_hash(&input);
37
38 if let Some(addr) = &addr {
39 addr.do_send(NonceUpdate {
40 nonce,
41 hash: hash.clone(),
42 });
43 } else {
44 println!("Nonce: {}, Hash: {}", nonce, hash);
45 }
46
47 if &hash[..difficulty] == target {
48 if let Some(addr) = &addr {
49 addr.do_send(MiningComplete {
50 nonce,
51 hash: hash.clone(),
52 });
53 }
54 return (nonce, hash);
55 }
56 nonce += 1;
57 }
58}