1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
|
use bincode::Encode;
use sha2::{Digest, Sha256, digest::DynDigest};
use std::ops::Deref;
use serde::{Deserialize, Serialize};
use crate::{ZERO_PREFIX_AMOUNT, hash_chain::HashChain, transaction::Transaction};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use tokio::sync::mpsc;
use tokio::task;
pub trait CryptoDigest {
fn digest(&self, state: &mut impl DynDigest);
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Encode)]
pub struct Block {
pub prev_hash: Vec<u8>,
pub trans: Transaction,
pub pow: Option<u64>,
}
impl Block {
fn new(prev_hash: Option<&[u8]>, trans: Transaction) -> Self {
Self {
prev_hash: prev_hash
.unwrap_or(&[])
.to_vec(),
trans,
pow: None,
}
}
fn pref_zeros(hashed: &[u8]) -> Result<usize, usize> {
hashed
.iter()
.try_fold(0, |nonce, x| {
if nonce >= ZERO_PREFIX_AMOUNT {
Ok(nonce)
} else if *x == 0 {
Ok(nonce + 1)
} else {
Err(nonce)
}
})
}
pub async fn calc_pow(&self) -> u64 {
let threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4); // TODO: config
let found = Arc::new(AtomicBool::new(false));
let (tx, mut rx) = mpsc::unbounded_channel::<u64>();
let prev_hash = Arc::new(
self.prev_hash
.clone(),
);
let trans = self.trans;
for t in 0..threads {
let tx = tx.clone();
let prev_hash = Arc::clone(&prev_hash);
let step = threads as u64;
let found = found.clone();
task::spawn_blocking(move || {
let mut i = t as u64;
while !found.load(Ordering::Relaxed) {
let mut hasher = Sha256::new();
Digest::update(&mut hasher, bincode::encode_to_vec((&*prev_hash, &trans, i), bincode::config::standard()).unwrap());
let hashed = hasher.finalize();
if Self::pref_zeros(&hashed).is_ok() {
if !found.swap(true, Ordering::Relaxed) {
_ = tx.send(i);
}
break;
}
i = i.wrapping_add(step);
}
});
}
// for h in handles {
// h.abort(); // h.join();
// }
rx.recv() // blocking
.await
.expect("miner dropped without sending")
}
pub async fn calc_set_pow(&mut self) {
self.pow = Some(
self.calc_pow()
.await,
);
}
pub fn verify_pow(&self) -> bool {
if let Some(nonce) = self.pow {
let mut hasher = Sha256::new();
Digest::update(&mut hasher, bincode::encode_to_vec((&self.prev_hash, &self.trans, nonce), bincode::config::standard()).unwrap());
Self::pref_zeros(&hasher.finalize()).is_ok()
} else {
false
}
}
}
impl CryptoDigest for Block {
fn digest(&self, state: &mut impl DynDigest) {
state.update(&bincode::encode_to_vec((&self.prev_hash, &self.trans, &self.pow), bincode::config::standard()).unwrap());
}
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct BlockChain {
pub blocks: HashChain<Block>,
}
impl BlockChain {
pub fn new(blocks: Vec<Block>) -> Self {
Self {
blocks: HashChain::new(blocks),
}
}
pub fn new_block(&self, trans: Transaction) -> Block {
let prev = self
.blocks
.last();
let prev_hash = if let Some(b) = prev {
Some(HashChain::hash_o_item(b))
} else {
None
};
Block::new(prev_hash.as_deref(), trans)
}
pub fn store(&mut self, block: Block) {
// TODO: check config
if block.verify_pow() {
self.blocks
.push(block)
} else {
eprint!("Err: Failed to store unverified block")
}
}
}
impl Deref for BlockChain {
type Target = HashChain<Block>;
fn deref(&self) -> &Self::Target {
&self.blocks
}
}
|