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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use crate::error::ConsensusError;
use mina_rs_base::consensus_state::ConsensusState;
use mina_rs_base::global_slot::GlobalSlot;
use mina_rs_base::protocol_state::ProtocolStateHeader;
use mina_rs_base::types::{BlockTime, Length};
use proof_systems::mina_hasher::Fp;
pub struct ConsensusConstants {
pub k: Length,
pub slots_per_epoch: Length,
pub slots_per_sub_window: Length,
pub delta: Length,
pub genesis_state_timestamp: BlockTime,
pub sub_windows_per_window: Length,
pub grace_period_end: Length,
}
impl ConsensusConstants {
pub fn mainnet() -> Self {
Self {
k: Length(290),
slots_per_epoch: Length(7140),
slots_per_sub_window: Length(7),
delta: Length(0),
genesis_state_timestamp: BlockTime(1615939200000),
sub_windows_per_window: Length(11),
grace_period_end: Length(1440),
}
}
pub fn devnet() -> Self {
todo!()
}
}
#[derive(Debug, Default, Eq, PartialEq, Clone)]
pub struct ProtocolStateChain<T>(pub Vec<T>)
where
T: ProtocolStateHeader;
impl<T> ProtocolStateChain<T>
where
T: ProtocolStateHeader,
{
pub fn push(&mut self, new: T) -> Result<(), ConsensusError> {
match self.0.len() {
0 => (),
n => {
if new.get_height().0 != self.0[n - 1].get_height().0 + 1 {
return Err(ConsensusError::InvalidHeight);
}
}
}
self.0.push(new);
Ok(())
}
pub fn top(&self) -> Option<&T> {
self.0.last()
}
pub fn consensus_state(&self) -> Option<&ConsensusState> {
self.top().map(|s| s.consensus_state())
}
pub fn genesis_block(&self) -> Option<&T> {
self.0.first()
}
pub fn global_slot(&self) -> Option<&GlobalSlot> {
self.top().map(|s| &s.consensus_state().curr_global_slot)
}
pub fn epoch_slot(&self) -> Option<u32> {
self.global_slot()
.map(|s| (s.slot_number.0 % s.slots_per_epoch.0))
}
pub fn length(&self) -> usize {
self.consensus_state()
.map(|s| s.blockchain_length.0 as usize)
.unwrap_or(0)
}
pub fn last_vrf_hash_digest(&self) -> Result<String, ConsensusError> {
let hash = self
.consensus_state()
.ok_or(ConsensusError::TopBlockNotFound)?
.last_vrf_output
.digest();
Ok(hex::encode(hash))
}
pub fn state_hash(&self) -> Option<Fp> {
self.top().map(|s| s.state_hash_fp())
}
}
pub trait ChainSelection {
fn select_secure_chain(&mut self, candidates: Vec<Self>) -> Result<(), ConsensusError>
where
Self: Sized;
fn select_longer_chain(&mut self, candidate: Self) -> Result<(), ConsensusError>
where
Self: Sized;
fn is_short_range(&self, candidate: &Self) -> Result<bool, ConsensusError>;
fn relative_min_window_density(&self, candidate: &Self) -> Result<u32, ConsensusError>;
fn config(&self) -> ConsensusConstants;
}
impl<T> ChainSelection for ProtocolStateChain<T>
where
T: ProtocolStateHeader,
{
fn select_secure_chain(&mut self, candidates: Vec<Self>) -> Result<(), ConsensusError> {
for candidate in candidates {
if self.is_short_range(&candidate)? {
self.select_longer_chain(candidate)?;
} else {
let candidate_state = candidate
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
if candidate_state
.sub_window_densities()
.iter()
.any(|s| *s > self.config().slots_per_sub_window.0)
{
continue;
};
let sub_windows_per_window = self.config().sub_windows_per_window.0 as usize;
if candidate_state.sub_window_densities.len() != sub_windows_per_window {
continue;
}
let tip_density = self.relative_min_window_density(&candidate)?;
let candidate_density = candidate.relative_min_window_density(self)?;
match candidate_density.cmp(&tip_density) {
std::cmp::Ordering::Greater => *self = candidate,
std::cmp::Ordering::Equal => self.select_longer_chain(candidate)?,
_ => (), }
}
}
Ok(())
}
fn select_longer_chain(&mut self, candidate: Self) -> Result<(), ConsensusError> {
let top_state = self
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
let candidate_state = candidate
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
if top_state.blockchain_length < candidate_state.blockchain_length {
*self = candidate;
} else if top_state.blockchain_length == candidate_state.blockchain_length {
match candidate
.last_vrf_hash_digest()?
.cmp(&self.last_vrf_hash_digest()?)
{
std::cmp::Ordering::Greater => {
*self = candidate;
}
std::cmp::Ordering::Equal => {
if candidate.state_hash() > self.state_hash() {
*self = candidate;
}
}
_ => {}
}
}
Ok(())
}
fn is_short_range(&self, candidate: &Self) -> Result<bool, ConsensusError> {
let a = self
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
let b = candidate
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
let a_prev_lock_checkpoint = &a.staking_epoch_data.lock_checkpoint;
let b_prev_lock_checkpoint = &b.staking_epoch_data.lock_checkpoint;
let check = |s1: &ConsensusState, s2: &ConsensusState, s2_epoch_slot: Option<u32>| {
if s1.epoch_count.0 == s2.epoch_count.0 + 1
&& s2_epoch_slot >= Some(self.config().slots_per_epoch.0 * 2 / 3)
{
s1.staking_epoch_data.lock_checkpoint == s2.next_epoch_data.lock_checkpoint
} else {
false
}
};
if a.epoch_count == b.epoch_count {
Ok(a_prev_lock_checkpoint == b_prev_lock_checkpoint)
} else {
Ok(check(a, b, candidate.epoch_slot()) || check(b, a, self.epoch_slot()))
}
}
fn config(&self) -> ConsensusConstants {
ConsensusConstants::mainnet()
}
fn relative_min_window_density(&self, chain_b: &Self) -> Result<u32, ConsensusError> {
let tip_state = self
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
let chain_b = chain_b
.consensus_state()
.ok_or(ConsensusError::ConsensusStateNotFound)?;
let min = |a: u32, b: u32| a.min(b);
let max = |a: u32, b: u32| a.max(b);
let max_slot = max(
tip_state.curr_global_slot.slot_number.0,
chain_b.curr_global_slot.slot_number.0,
);
if max_slot < self.config().grace_period_end.0 {
return Ok(tip_state.min_window_density.0);
}
let projected_window = {
let mut shift_count = min(
max(
max_slot - tip_state.curr_global_slot.slot_number.0.saturating_sub(1),
0,
),
self.config().sub_windows_per_window.0,
);
let mut projected_window = tip_state.sub_window_densities.clone();
let mut rel_sub_window = tip_state.curr_global_slot.slot_number.0
/ self.config().sub_windows_per_window.0
% self.config().sub_windows_per_window.0;
while shift_count > 0 {
rel_sub_window = (rel_sub_window + 1) % self.config().sub_windows_per_window.0;
match projected_window.get_mut(rel_sub_window as usize) {
Some(density) => *density = Length(0),
None => return Err(ConsensusError::CandidatesMissingSubWindowDensities),
};
shift_count -= 1;
}
projected_window
};
let projected_window_density = projected_window.iter().map(|s| s.0).sum();
Ok(min(
tip_state.min_window_density.0,
projected_window_density,
))
}
}