solana-entry 4.0.0-rc.0

Solana Entry
Documentation
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! The `Poh` module provides an object for generating a Proof of History.
use {
    log::*,
    solana_hash::Hash,
    solana_sha256_hasher::{hash, hashv},
    std::time::{Duration, Instant},
};

const LOW_POWER_MODE: u64 = u64::MAX;

pub struct Poh {
    pub hash: Hash,
    num_hashes: u64,
    hashes_per_tick: u64,
    remaining_hashes_until_tick: u64,
    tick_number: u64,
    slot_start_time: Instant,
}

#[derive(Debug)]
pub struct PohEntry {
    pub num_hashes: u64,
    pub hash: Hash,
}

impl Poh {
    pub fn new(hash: Hash, hashes_per_tick: Option<u64>) -> Self {
        Self::new_with_slot_info(hash, hashes_per_tick, 0)
    }

    pub fn new_with_slot_info(hash: Hash, hashes_per_tick: Option<u64>, tick_number: u64) -> Self {
        let hashes_per_tick = hashes_per_tick.unwrap_or(LOW_POWER_MODE);
        assert!(hashes_per_tick > 1);
        let now = Instant::now();
        Poh {
            hash,
            num_hashes: 0,
            hashes_per_tick,
            remaining_hashes_until_tick: hashes_per_tick,
            tick_number,
            slot_start_time: now,
        }
    }

    pub fn reset(&mut self, hash: Hash, hashes_per_tick: Option<u64>) {
        // retains ticks_per_slot: this cannot change without restarting the validator
        let tick_number = 0;
        *self = Poh::new_with_slot_info(hash, hashes_per_tick, tick_number);
    }

    pub fn hashes_per_tick(&self) -> u64 {
        self.hashes_per_tick
    }

    pub fn target_poh_time(&self, target_ns_per_tick: u64) -> Instant {
        assert!(self.hashes_per_tick > 0);
        let offset_tick_ns = target_ns_per_tick * self.tick_number;
        let offset_ns = target_ns_per_tick * self.num_hashes / self.hashes_per_tick;
        self.slot_start_time + Duration::from_nanos(offset_ns + offset_tick_ns)
    }

    /// Return `true` if the caller needs to `tick()` next, i.e. if the
    /// remaining_hashes is 1.
    pub fn hash(&mut self, max_num_hashes: u64) -> bool {
        let num_hashes = std::cmp::min(self.remaining_hashes_until_tick - 1, max_num_hashes);

        for _ in 0..num_hashes {
            self.hash = hash(self.hash.as_ref());
        }
        self.num_hashes += num_hashes;
        self.remaining_hashes_until_tick -= num_hashes;

        assert!(self.remaining_hashes_until_tick > 0);
        self.remaining_hashes_until_tick == 1
    }

    pub fn record(&mut self, mixin: Hash) -> Option<PohEntry> {
        if self.remaining_hashes_until_tick == 1 {
            return None; // Caller needs to `tick()` first
        }

        self.hash = hashv(&[self.hash.as_ref(), mixin.as_ref()]);
        let num_hashes = self.num_hashes + 1;
        self.num_hashes = 0;
        self.remaining_hashes_until_tick -= 1;

        Some(PohEntry {
            num_hashes,
            hash: self.hash,
        })
    }

    /// Returns `true` if the batches were recorded successfully and `false` if the batches
    /// were not recorded because there were not enough hashes remaining to record all `mixins`.
    /// If `true` is returned, the `entries` vector will be populated with the `PohEntry`s for each
    /// batch. If `false` is returned, the `entries` vector will not be modified.
    pub fn record_batches(&mut self, mixins: &[Hash], entries: &mut Vec<PohEntry>) -> bool {
        let num_mixins = mixins.len() as u64;
        debug_assert_ne!(num_mixins, 0, "mixins.len() == 0");

        if self.remaining_hashes_until_tick < num_mixins + 1 {
            return false; // Not enough hashes remaining to record all mixins
        }

        entries.clear();
        entries.reserve(mixins.len());

        // The first entry will have the current number of hashes plus one.
        // All subsequent entries will have 1.
        let mut num_hashes = self.num_hashes + 1;
        entries.extend(mixins.iter().map(|mixin| {
            self.hash = hashv(&[self.hash.as_ref(), mixin.as_ref()]);
            let entry = PohEntry {
                num_hashes,
                hash: self.hash,
            };

            num_hashes = 1;
            entry
        }));

        self.num_hashes = 0;
        self.remaining_hashes_until_tick -= num_mixins;

        true
    }

    pub fn tick(&mut self) -> Option<PohEntry> {
        self.hash = hash(self.hash.as_ref());
        self.num_hashes += 1;
        self.remaining_hashes_until_tick -= 1;

        // If we are in low power mode then always generate a tick.
        // Otherwise only tick if there are no remaining hashes
        if self.hashes_per_tick != LOW_POWER_MODE && self.remaining_hashes_until_tick != 0 {
            return None;
        }

        let num_hashes = self.num_hashes;
        self.remaining_hashes_until_tick = self.hashes_per_tick;
        self.num_hashes = 0;
        self.tick_number += 1;
        Some(PohEntry {
            num_hashes,
            hash: self.hash,
        })
    }

    pub fn remaining_hashes_in_slot(&self, ticks_per_slot: u64) -> u64 {
        // ticks_per_slot must be a power of two so we can use a bitmask
        debug_assert!(ticks_per_slot.is_power_of_two() && ticks_per_slot > 0);
        ticks_per_slot
            .saturating_sub((self.tick_number & (ticks_per_slot.wrapping_sub(1))).wrapping_add(1))
            .wrapping_mul(self.hashes_per_tick)
            .wrapping_add(self.remaining_hashes_until_tick)
    }
}

pub fn compute_hash_time(hashes_sample_size: u64) -> Duration {
    info!("Running {hashes_sample_size} hashes...");
    let mut v = Hash::default();
    let start = Instant::now();
    for _ in 0..hashes_sample_size {
        v = hash(v.as_ref());
    }
    start.elapsed()
}

pub fn compute_hashes_per_tick(duration: Duration, hashes_sample_size: u64) -> u64 {
    let elapsed_ms = compute_hash_time(hashes_sample_size).as_millis() as u64;
    duration.as_millis() as u64 * hashes_sample_size / elapsed_ms
}

#[cfg(test)]
mod tests {
    use {
        crate::poh::{Poh, PohEntry},
        assert_matches::assert_matches,
        solana_hash::Hash,
        solana_sha256_hasher::{hash, hashv},
        std::time::Duration,
    };

    fn verify(initial_hash: Hash, entries: &[(PohEntry, Option<Hash>)]) -> bool {
        let mut current_hash = initial_hash;

        for (entry, mixin) in entries {
            assert_ne!(entry.num_hashes, 0);

            for _ in 1..entry.num_hashes {
                current_hash = hash(current_hash.as_ref());
            }
            current_hash = match mixin {
                Some(mixin) => hashv(&[current_hash.as_ref(), mixin.as_ref()]),
                None => hash(current_hash.as_ref()),
            };
            if current_hash != entry.hash {
                return false;
            }
        }

        true
    }

    #[test]
    fn test_target_poh_time() {
        let zero = Hash::default();
        for target_ns_per_tick in 10..12 {
            let mut poh = Poh::new(zero, None);
            assert_eq!(poh.target_poh_time(target_ns_per_tick), poh.slot_start_time);
            poh.tick_number = 2;
            assert_eq!(
                poh.target_poh_time(target_ns_per_tick),
                poh.slot_start_time + Duration::from_nanos(target_ns_per_tick * 2)
            );
            let mut poh = Poh::new(zero, Some(5));
            assert_eq!(poh.target_poh_time(target_ns_per_tick), poh.slot_start_time);
            poh.tick_number = 2;
            assert_eq!(
                poh.target_poh_time(target_ns_per_tick),
                poh.slot_start_time + Duration::from_nanos(target_ns_per_tick * 2)
            );
            poh.num_hashes = 3;
            assert_eq!(
                poh.target_poh_time(target_ns_per_tick),
                poh.slot_start_time
                    + Duration::from_nanos(target_ns_per_tick * 2 + target_ns_per_tick * 3 / 5)
            );
        }
    }

    #[test]
    #[should_panic(expected = "hashes_per_tick > 1")]
    fn test_target_poh_time_hashes_per_tick() {
        let zero = Hash::default();
        let poh = Poh::new(zero, Some(0));
        let target_ns_per_tick = 10;
        poh.target_poh_time(target_ns_per_tick);
    }

    #[test]
    fn test_poh_verify() {
        let zero = Hash::default();
        let one = hash(zero.as_ref());
        let two = hash(one.as_ref());
        let one_with_zero = hashv(&[zero.as_ref(), zero.as_ref()]);

        let mut poh = Poh::new(zero, None);
        assert!(verify(
            zero,
            &[
                (poh.tick().unwrap(), None),
                (poh.record(zero).unwrap(), Some(zero)),
                (poh.record(zero).unwrap(), Some(zero)),
                (poh.tick().unwrap(), None),
            ],
        ));

        assert!(verify(
            zero,
            &[(
                PohEntry {
                    num_hashes: 1,
                    hash: one,
                },
                None
            )],
        ));
        assert!(verify(
            zero,
            &[(
                PohEntry {
                    num_hashes: 2,
                    hash: two,
                },
                None
            )]
        ));

        assert!(verify(
            zero,
            &[(
                PohEntry {
                    num_hashes: 1,
                    hash: one_with_zero,
                },
                Some(zero)
            )]
        ));
        assert!(!verify(
            zero,
            &[(
                PohEntry {
                    num_hashes: 1,
                    hash: zero,
                },
                None
            )]
        ));

        assert!(verify(
            zero,
            &[
                (
                    PohEntry {
                        num_hashes: 1,
                        hash: one_with_zero,
                    },
                    Some(zero)
                ),
                (
                    PohEntry {
                        num_hashes: 1,
                        hash: hash(one_with_zero.as_ref()),
                    },
                    None
                )
            ]
        ));
    }

    #[test]
    #[should_panic]
    fn test_poh_verify_assert() {
        verify(
            Hash::default(),
            &[(
                PohEntry {
                    num_hashes: 0,
                    hash: Hash::default(),
                },
                None,
            )],
        );
    }

    #[test]
    fn test_poh_tick() {
        let mut poh = Poh::new(Hash::default(), Some(2));
        assert_eq!(poh.remaining_hashes_until_tick, 2);
        assert!(poh.tick().is_none());
        assert_eq!(poh.remaining_hashes_until_tick, 1);
        assert_matches!(poh.tick(), Some(PohEntry { num_hashes: 2, .. }));
        assert_eq!(poh.remaining_hashes_until_tick, 2); // Ready for the next tick
    }

    #[test]
    fn test_poh_tick_large_batch() {
        let mut poh = Poh::new(Hash::default(), Some(2));
        assert_eq!(poh.remaining_hashes_until_tick, 2);
        assert!(poh.hash(1_000_000)); // Stop hashing before the next tick
        assert_eq!(poh.remaining_hashes_until_tick, 1);
        assert!(poh.hash(1_000_000)); // Does nothing...
        assert_eq!(poh.remaining_hashes_until_tick, 1);
        assert_eq!(poh.remaining_hashes_in_slot(2), 3);
        poh.tick();
        assert_eq!(poh.remaining_hashes_until_tick, 2); // Ready for the next tick
        assert_eq!(poh.remaining_hashes_in_slot(2), 2);
    }

    #[test]
    fn test_poh_tick_too_soon() {
        let mut poh = Poh::new(Hash::default(), Some(2));
        assert_eq!(poh.remaining_hashes_until_tick, 2);
        assert_eq!(poh.remaining_hashes_in_slot(2), 4);
        assert!(poh.tick().is_none());
    }

    #[test]
    fn test_poh_record_not_permitted_at_final_hash() {
        let mut poh = Poh::new(Hash::default(), Some(10));
        assert!(poh.hash(9));
        assert_eq!(poh.remaining_hashes_until_tick, 1);
        assert_eq!(poh.remaining_hashes_in_slot(2), 11);
        assert!(poh.record(Hash::default()).is_none()); // <-- record() rejected to avoid exceeding hashes_per_tick
        assert_matches!(poh.tick(), Some(PohEntry { num_hashes: 10, .. }));
        assert_matches!(
            poh.record(Hash::default()),
            Some(PohEntry { num_hashes: 1, .. }) // <-- record() ok
        );
        assert_eq!(poh.remaining_hashes_until_tick, 9);
        assert_eq!(poh.remaining_hashes_in_slot(2), 9);
    }

    #[test]
    fn test_poh_record_batches() {
        let mut poh = Poh::new(Hash::default(), Some(10));
        assert!(!poh.hash(4));

        let mut entries = Vec::with_capacity(3);
        let dummy_hashes = [Hash::default(); 4];
        assert!(poh.record_batches(&dummy_hashes[..3], &mut entries,));
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].num_hashes, 5);
        assert_eq!(entries[1].num_hashes, 1);
        assert_eq!(entries[2].num_hashes, 1);
        assert_eq!(poh.remaining_hashes_until_tick, 3);
        assert_eq!(poh.remaining_hashes_in_slot(2), 13);

        // Cannot record more than number of remaining hashes
        assert!(!poh.record_batches(&dummy_hashes[..4], &mut entries,));

        // Cannot record more than number of remaining hashes
        assert!(!poh.record_batches(&dummy_hashes[..3], &mut entries,));

        // Can record less than number of remaining hashes
        assert!(poh.record_batches(&dummy_hashes[..2], &mut entries,));
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].num_hashes, 1);
        assert_eq!(entries[1].num_hashes, 1);
        assert_eq!(poh.remaining_hashes_until_tick, 1);
        assert_eq!(poh.remaining_hashes_in_slot(2), 11);
    }
}