bc_utils/
mining.rs

1//!
2//! This is the Mining module.<br>
3//! The mining function used to put pending
4//! transactions on the blockchain.
5//!
6
7extern crate sha2;
8
9use crate::wsactor::{MiningComplete, NonceUpdate};
10use actix::prelude::*;
11use sha2::{Digest, Sha256};
12
13///
14/// Calculate a hash using SHA256.
15///
16fn 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
23///
24/// Mine a transaction.
25///
26pub 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}