-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
163 lines (152 loc) · 4.92 KB
/
main.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
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
pub struct App {
pub blocks: Vec,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
pub id: u64,
pub hash: String,
pub previous_hash: String,
pub timestamp: i64,
pub data: String,
pub nonce: u64,
}
impl App {
fn new() -> Self {
Self { blocks: vec![] }
}
fn genesis(&mut self) {
let genesis_block = Block {
id: 0,
timestamp: Utc::now().timestamp(),
previous_hash: String::from("genesis"),
data: String::from("genesis!"),
nonce: 2836,
hash: "0000f816a87f806bb0073dcf026a64fb40c946b5abee2573702828694d5b4c43".to_string(),
};
self.blocks.push(genesis_block);
}
fn try_add_block(&mut self, block: Block) {
let latest_block = self.blocks.last().expect("there is at least one block");
if self.is_block_valid(&block, latest_block) {
self.blocks.push(block);
} else {
error!("could not add block - invalid");
}
}
const DIFFICULTY_PREFIX: &str = "00";
fn hash_to_binary_representation(hash: &[u8]) -> String {
let mut res: String = String::default();
for c in hash {
res.push_str(&format!("{:b}", c));
}
res
}
fn is_block_valid(&self, block: &Block, previous_block: &Block) -> bool {
if block.previous_hash != previous_block.hash {
warn!("block with id: {} has wrong previous hash", block.id);
return false;
} else if !hash_to_binary_representation(
&hex::decode(&block.hash).expect("can decode from hex"),
)
.starts_with(DIFFICULTY_PREFIX)
{
warn!("block with id: {} has invalid difficulty", block.id);
return false;
} else if block.id != previous_block.id + 1 {
warn!(
"block with id: {} is not the next block after the latest: {}",
block.id, previous_block.id
);
return false;
} else if hex::encode(calculate_hash(
block.id,
block.timestamp,
&block.previous_hash,
&block.data,
block.nonce,
)) != block.hash
{
warn!("block with id: {} has invalid hash", block.id);
return false;
}
true
}
fn is_chain_valid(&self, chain: &[Block]) -> bool {
for i in 0..chain.len() {
if i == 0 {
continue;
}
let first = chain.get(i - 1).expect("has to exist");
let second = chain.get(i).expect("has to exist");
if !self.is_block_valid(second, first) {
return false;
}
}
true
}
fn choose_chain(&mut self, local: Vec, remote: Vec) -> Vec {
let is_local_valid = self.is_chain_valid(&local);
let is_remote_valid = self.is_chain_valid(&remote);
if is_local_valid && is_remote_valid {
if local.len() >= remote.len() {
local
} else {
remote
}
} else if is_remote_valid && !is_local_valid {
remote
} else if !is_remote_valid && is_local_valid {
local
} else {
panic!("local and remote chains are both invalid");
}
}
}
//mining
impl Block {
pub fn new(id: u64, previous_hash: String, data: String) -> Self {
let now = Utc::now();
let (nonce, hash) = mine_block(id, now.timestamp(), &previous_hash, &data);
Self {
id,
hash,
timestamp: now.timestamp(),
previous_hash,
data,
nonce,
}
}
fn mine_block(id: u64, timestamp: i64, previous_hash: &str, data: &str) -> (u64, String) {
info!("mining block...");
let mut nonce = 0;
loop {
if nonce % 100000 == 0 {
info!("nonce: {}", nonce);
}
let hash = calculate_hash(id, timestamp, previous_hash, data, nonce);
let binary_hash = hash_to_binary_representation(&hash);
if binary_hash.starts_with(DIFFICULTY_PREFIX) {
info!(
"mined! nonce: {}, hash: {}, binary hash: {}",
nonce,
hex::encode(&hash),
binary_hash
);
return (nonce, hex::encode(hash));
}
nonce += 1;
}
fn calculate_hash(id: u64, timestamp: i64, previous_hash: &str, data: &str, nonce: u64) -> Vec<u8> {
let data = serde_json::json!({
"id": id,
"previous_hash": previous_hash,
"data": data,
"timestamp": timestamp,
"nonce": nonce
});
let mut hasher = Sha256::new();
hasher.update(data.to_string().as_bytes());
hasher.finalize().as_slice().to_owned()
}
}
}