gemachain_program/sysvar/
recent_blockhashes.rs

1#![allow(deprecated)]
2#![allow(clippy::integer_arithmetic)]
3use crate::{
4    declare_deprecated_sysvar_id,
5    fee_calculator::FeeCalculator,
6    hash::{hash, Hash},
7    sysvar::Sysvar,
8};
9use std::{cmp::Ordering, collections::BinaryHeap, iter::FromIterator, ops::Deref};
10
11#[deprecated(
12    since = "1.8.0",
13    note = "Please do not use, will no longer be available in the future"
14)]
15pub const MAX_ENTRIES: usize = 150;
16
17declare_deprecated_sysvar_id!(
18    "SysvarRecentB1ockHashes11111111111111111111",
19    RecentBlockhashes
20);
21
22#[deprecated(
23    since = "1.8.0",
24    note = "Please do not use, will no longer be available in the future"
25)]
26#[repr(C)]
27#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
28pub struct Entry {
29    pub blockhash: Hash,
30    pub fee_calculator: FeeCalculator,
31}
32impl Entry {
33    pub fn new(blockhash: &Hash, fee_calculator: &FeeCalculator) -> Self {
34        Self {
35            blockhash: *blockhash,
36            fee_calculator: fee_calculator.clone(),
37        }
38    }
39}
40
41#[deprecated(
42    since = "1.8.0",
43    note = "Please do not use, will no longer be available in the future"
44)]
45#[derive(Clone, Debug)]
46pub struct IterItem<'a>(pub u64, pub &'a Hash, pub &'a FeeCalculator);
47
48impl<'a> Eq for IterItem<'a> {}
49
50impl<'a> PartialEq for IterItem<'a> {
51    fn eq(&self, other: &Self) -> bool {
52        self.0 == other.0
53    }
54}
55
56impl<'a> Ord for IterItem<'a> {
57    fn cmp(&self, other: &Self) -> Ordering {
58        self.0.cmp(&other.0)
59    }
60}
61
62impl<'a> PartialOrd for IterItem<'a> {
63    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
64        Some(self.cmp(other))
65    }
66}
67
68/// Contains recent block hashes and fee calculators.
69///
70/// The entries are ordered by descending block height, so the first entry holds
71/// the most recent block hash, and the last entry holds an old block hash.
72#[deprecated(
73    since = "1.8.0",
74    note = "Please do not use, will no longer be available in the future"
75)]
76#[repr(C)]
77#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
78pub struct RecentBlockhashes(Vec<Entry>);
79
80impl Default for RecentBlockhashes {
81    fn default() -> Self {
82        Self(Vec::with_capacity(MAX_ENTRIES))
83    }
84}
85
86impl<'a> FromIterator<IterItem<'a>> for RecentBlockhashes {
87    fn from_iter<I>(iter: I) -> Self
88    where
89        I: IntoIterator<Item = IterItem<'a>>,
90    {
91        let mut new = Self::default();
92        for i in iter {
93            new.0.push(Entry::new(i.1, i.2))
94        }
95        new
96    }
97}
98
99// This is cherry-picked from HEAD of rust-lang's master (ref1) because it's
100// a nightly-only experimental API.
101// (binary_heap_into_iter_sorted [rustc issue #59278])
102// Remove this and use the standard API once BinaryHeap::into_iter_sorted (ref2)
103// is stabilized.
104// ref1: https://github.com/rust-lang/rust/blob/2f688ac602d50129388bb2a5519942049096cbff/src/liballoc/collections/binary_heap.rs#L1149
105// ref2: https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html#into_iter_sorted.v
106
107#[derive(Clone, Debug)]
108pub struct IntoIterSorted<T> {
109    inner: BinaryHeap<T>,
110}
111impl<T> IntoIterSorted<T> {
112    pub fn new(binary_heap: BinaryHeap<T>) -> Self {
113        Self { inner: binary_heap }
114    }
115}
116
117impl<T: Ord> Iterator for IntoIterSorted<T> {
118    type Item = T;
119
120    #[inline]
121    fn next(&mut self) -> Option<T> {
122        self.inner.pop()
123    }
124
125    #[inline]
126    fn size_hint(&self) -> (usize, Option<usize>) {
127        let exact = self.inner.len();
128        (exact, Some(exact))
129    }
130}
131
132impl Sysvar for RecentBlockhashes {
133    fn size_of() -> usize {
134        // hard-coded so that we don't have to construct an empty
135        6008 // golden, update if MAX_ENTRIES changes
136    }
137}
138
139impl Deref for RecentBlockhashes {
140    type Target = Vec<Entry>;
141    fn deref(&self) -> &Self::Target {
142        &self.0
143    }
144}
145
146pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
147    let blocks: Vec<_> = (start..start + MAX_ENTRIES)
148        .map(|i| {
149            (
150                i as u64,
151                hash(&bincode::serialize(&i).unwrap()),
152                FeeCalculator::new(i as u64 * 100),
153            )
154        })
155        .collect();
156    blocks
157        .iter()
158        .map(|(i, hash, fee_calc)| IterItem(*i, hash, fee_calc))
159        .collect()
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::clock::MAX_PROCESSING_AGE;
166
167    #[test]
168    #[allow(clippy::assertions_on_constants)]
169    fn test_sysvar_can_hold_all_active_blockhashes() {
170        // Ensure we can still hold all of the active entries in `BlockhashQueue`
171        assert!(MAX_PROCESSING_AGE <= MAX_ENTRIES);
172    }
173
174    #[test]
175    fn test_size_of() {
176        let entry = Entry::new(&Hash::default(), &FeeCalculator::default());
177        assert_eq!(
178            bincode::serialized_size(&RecentBlockhashes(vec![entry; MAX_ENTRIES])).unwrap()
179                as usize,
180            RecentBlockhashes::size_of()
181        );
182    }
183}