forked from GeekLaunch/blockchain-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.rs
73 lines (65 loc) · 1.85 KB
/
block.rs
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
use std::fmt::{ self, Debug, Formatter };
use super::*;
pub struct Block {
pub index: u32,
pub timestamp: u128,
pub hash: Hash,
pub prev_block_hash: Hash,
pub nonce: u64,
pub transactions: Vec<Transaction>,
pub difficulty: u128,
}
impl Debug for Block {
fn fmt (&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Block[{}]: {} at: {} with: {} nonce: {}",
&self.index,
&hex::encode(&self.hash),
&self.timestamp,
&self.transactions.len(),
&self.nonce,
)
}
}
impl Block {
pub fn new (index: u32, timestamp: u128, prev_block_hash: Hash, transactions: Vec<Transaction>, difficulty: u128) -> Self {
Block {
index,
timestamp,
hash: vec![0; 32],
prev_block_hash,
nonce: 0,
transactions,
difficulty,
}
}
pub fn mine (&mut self) {
for nonce_attempt in 0..(u64::max_value()) {
self.nonce = nonce_attempt;
let hash = self.hash();
if check_difficulty(&hash, self.difficulty) {
self.hash = hash;
return;
}
}
}
}
impl Hashable for Block {
fn bytes (&self) -> Vec<u8> {
let mut bytes = vec![];
bytes.extend(&u32_bytes(&self.index));
bytes.extend(&u128_bytes(&self.timestamp));
bytes.extend(&self.prev_block_hash);
bytes.extend(&u64_bytes(&self.nonce));
bytes.extend(
self.transactions
.iter()
.flat_map(|transaction| transaction.bytes())
.collect::<Vec<u8>>()
);
bytes.extend(&u128_bytes(&self.difficulty));
bytes
}
}
pub fn check_difficulty (hash: &Hash, difficulty: u128) -> bool {
difficulty > difficulty_bytes_as_u128(&hash)
}