1use heika_block::scoring::{BlockStatistic, target};
21use heika_core::network::NetworkParameters;
22
23const HIT_SCALE: f64 = (1u64 << 54) as f64;
25
26pub fn hazard_per_importance(
28 elapsed_seconds: u64,
29 difficulty: u64,
30 parameters: &NetworkParameters,
31) -> f64 {
32 let scale = parameters.total_chain_importance.max(1);
34 target(elapsed_seconds, difficulty, scale, parameters).to_f64() / scale as f64 / HIT_SCALE
35}
36
37pub fn active_importance(recent: &[BlockStatistic], parameters: &NetworkParameters) -> Option<f64> {
40 let intervals: Vec<(f64, f64)> = recent
42 .windows(2)
43 .filter_map(|pair| {
44 let elapsed = pair[1].timestamp.saturating_sub(pair[0].timestamp) / 1000;
45 let before =
47 hazard_per_importance(elapsed.checked_sub(1)?, pair[1].difficulty, parameters);
48 let at = hazard_per_importance(elapsed, pair[1].difficulty, parameters);
49 (at > before).then_some((before, at - before))
50 })
51 .collect();
52 if intervals.is_empty() {
53 return None;
54 }
55 let score = |active: f64| -> f64 {
57 intervals
58 .iter()
59 .map(|&(before, width)| -before + width / (active * width).exp_m1())
60 .sum()
61 };
62 let start = intervals.len() as f64
64 / intervals
65 .iter()
66 .map(|(before, width)| before + width)
67 .sum::<f64>();
68 let (mut low, mut high) = (start, start);
69 for _ in 0..64 {
70 if score(low) > 0.0 {
71 break;
72 }
73 low /= 2.0;
74 }
75 for _ in 0..64 {
76 if score(high) < 0.0 {
77 break;
78 }
79 high *= 2.0;
80 }
81 if !(score(low) > 0.0 && score(high) < 0.0) {
82 return None;
83 }
84 for _ in 0..100 {
86 let middle = (low * high).sqrt();
87 if score(middle) > 0.0 {
88 low = middle;
89 } else {
90 high = middle;
91 }
92 }
93 Some((low * high).sqrt())
94}
95
96pub fn average_block_seconds(recent: &[BlockStatistic]) -> Option<f64> {
98 let (first, last) = (recent.first()?, recent.last()?);
99 (recent.len() >= 2).then(|| {
100 last.timestamp.saturating_sub(first.timestamp) as f64 / 1000.0 / (recent.len() - 1) as f64
101 })
102}
103
104pub fn win_chance(
107 elapsed_seconds: u64,
108 difficulty: u64,
109 others: f64,
110 parameters: &NetworkParameters,
111) -> f64 {
112 let none_by =
113 |seconds| (-others * hazard_per_importance(seconds, difficulty, parameters)).exp();
114 let before = elapsed_seconds.checked_sub(1).map_or(1.0, none_by);
115 (before + none_by(elapsed_seconds)) / 2.0
116}
117
118#[cfg(test)]
119mod tests {
120 use heika_block::scoring::{DEFAULT_DIFFICULTY, earliest_hit_seconds};
121
122 use super::*;
123
124 const MAINNET: &NetworkParameters = &NetworkParameters::MAINNET;
125
126 #[test]
127 fn the_hazard_agrees_with_the_earliest_hit() {
128 let importance = 1_000_000_000_000u64;
130 let hazard = |seconds| hazard_per_importance(seconds, DEFAULT_DIFFICULTY, MAINNET);
131 for hit in [1u64 << 50, 1 << 53, 1 << 54, 3 << 54] {
132 let seconds =
133 earliest_hit_seconds(hit, DEFAULT_DIFFICULTY, importance, 3600, MAINNET).unwrap();
134 let at = |seconds| hazard(seconds) * importance as f64 * HIT_SCALE;
135 assert!(at(seconds) >= hit as f64 * 0.999, "{hit}: {seconds}");
136 assert!(at(seconds - 1) <= hit as f64 * 1.001, "{hit}: {seconds}");
137 }
138 }
139
140 struct Uniform(u64);
142
143 impl Uniform {
144 fn next(&mut self) -> f64 {
145 self.0 ^= self.0 << 13;
146 self.0 ^= self.0 >> 7;
147 self.0 ^= self.0 << 17;
148 ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64
149 }
150 }
151
152 fn simulate(active: f64, count: usize, parameters: &NetworkParameters) -> Vec<BlockStatistic> {
155 let mut uniform = Uniform(0x9E37_79B9_7F4A_7C15);
156 let mut timestamp = 0;
157 let mut recent = vec![BlockStatistic {
158 timestamp,
159 difficulty: DEFAULT_DIFFICULTY,
160 }];
161 for _ in 0..count {
162 let needed = -uniform.next().ln();
164 let seconds = (1..)
165 .find(|&seconds| {
166 active * hazard_per_importance(seconds, DEFAULT_DIFFICULTY, parameters)
167 >= needed
168 })
169 .unwrap();
170 timestamp += seconds * 1000;
171 recent.push(BlockStatistic {
172 timestamp,
173 difficulty: DEFAULT_DIFFICULTY,
174 });
175 }
176 recent
177 }
178
179 #[test]
180 fn estimates_back_the_importance_that_made_the_blocks() {
181 let mut fast = NetworkParameters::MAINNET;
182 fast.block_generation_target_time = std::time::Duration::from_secs(5);
183 for parameters in [MAINNET, &fast] {
184 let target_time = parameters.block_generation_target_time.as_secs();
186 let active = 1.0 / hazard_per_importance(target_time, DEFAULT_DIFFICULTY, parameters);
187 let recent = simulate(active, 3000, parameters);
188 let estimated = active_importance(&recent, parameters).unwrap();
189 assert!(
190 (estimated / active - 1.0).abs() < 0.05,
191 "{target_time}: {estimated} / {active}"
192 );
193 let naive = (recent.len() - 1) as f64
195 / recent
196 .windows(2)
197 .map(|pair| {
198 let seconds = (pair[1].timestamp - pair[0].timestamp) / 1000;
199 hazard_per_importance(seconds, DEFAULT_DIFFICULTY, parameters)
200 })
201 .sum::<f64>();
202 let bias = if target_time == 5 { 0.7 } else { 0.99 };
203 assert!(naive < active * bias, "{target_time}: {naive} / {active}");
204 }
205 let recent = simulate(1e12, 1, MAINNET);
206 assert_eq!(active_importance(&recent[..1], MAINNET), None);
207 }
208
209 #[test]
210 fn counts_a_tie_as_half_and_is_surer_the_earlier() {
211 let others = 1.0 / hazard_per_importance(30, DEFAULT_DIFFICULTY, MAINNET);
212 assert_eq!(win_chance(30, DEFAULT_DIFFICULTY, 0.0, MAINNET), 1.0);
214 let first = win_chance(1, DEFAULT_DIFFICULTY, others, MAINNET);
216 assert!(first > 0.5 && first <= 1.0, "{first}");
217 let chances: Vec<f64> = [1, 10, 30, 40]
218 .into_iter()
219 .map(|seconds| win_chance(seconds, DEFAULT_DIFFICULTY, others, MAINNET))
220 .collect();
221 assert!(
222 chances.windows(2).all(|pair| pair[0] > pair[1]),
223 "{chances:?}"
224 );
225 assert_eq!(average_block_seconds(&simulate(others, 0, MAINNET)), None);
226 }
227}