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
162
163
164
165
166
|
use bincode::Encode;
use sha2::{Digest, Sha256, digest::DynDigest};
use std::ops::Deref;
use serde::{Deserialize, Serialize};
use crate::{ZERO_PREFIX_AMOUNT, 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 tx: Transaction,
pub pow: Option<u64>,
}
impl Block {
fn new(prev_hash: Option<&[u8]>, tx: Transaction) -> Self {
Self {
prev_hash: prev_hash
.unwrap_or(&[])
.to_vec(), // special blocks
tx,
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);
let found = Arc::new(AtomicBool::new(false));
let (ptx, mut rx) = mpsc::unbounded_channel::<u64>();
let prev_hash = Arc::new(
self.prev_hash
.clone(),
);
let tx = self.tx;
let mut handles = Vec::with_capacity(threads);
for t in 0..threads {
let found = Arc::clone(&found);
let ptx = ptx.clone();
let prev_hash = Arc::clone(&prev_hash);
let start = t as u64;
handles.push(task::spawn_blocking(move || {
let mut i = start;
while !found.load(Ordering::Relaxed) {
let mut hasher = Sha256::new();
Digest::update(&mut hasher, bincode::encode_to_vec((&*prev_hash, &tx, i), bincode::config::standard()).unwrap());
let hashed = hasher.finalize();
if Block::pref_zeros(&hashed).is_ok() {
if !found.swap(true, Ordering::Relaxed) {
let _ = ptx.send(i);
}
break;
}
println!("{i}");
i = i.wrapping_add(threads as u64);
}
}));
}
drop(ptx);
let pow_nonce = rx
.recv()
.await
.expect("miner dropped without sending");
for h in handles {
_ = h.await;
}
pow_nonce
}
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.tx, 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.tx, &self.pow), bincode::config::standard()).unwrap());
}
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct BlockChain {
pub blocks: Vec<Block>,
}
impl BlockChain {
pub fn new(blocks: Vec<Block>) -> Self {
Self {
blocks,
}
}
pub fn new_block(&self, tx: Transaction) -> Block {
let mut hasher = Sha256::new();
let prev = self
.blocks
.last();
let prev_hash = if let Some(b) = prev {
b.digest(&mut hasher);
Some(&*hasher.finalize())
} else {
None
};
Block::new(prev_hash, tx)
}
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 = Vec<Block>;
fn deref(&self) -> &Self::Target {
&self.blocks
}
}
|