1use heika_core::network::NetworkParameters;
12use heika_core::vrf::GenerationHash;
13
14use crate::Block;
15
16pub const DEFAULT_DIFFICULTY: u64 = 100_000_000_000_000;
18pub const MIN_DIFFICULTY: u64 = DEFAULT_DIFFICULTY / 10;
20pub const MAX_DIFFICULTY: u64 = DEFAULT_DIFFICULTY * 10;
22
23#[derive(Clone, Copy, PartialEq, Eq, Debug)]
25pub struct BlockStatistic {
26 pub timestamp: u64,
28 pub difficulty: u64,
29}
30
31impl From<&Block> for BlockStatistic {
32 fn from(block: &Block) -> Self {
33 Self {
34 timestamp: block.timestamp,
35 difficulty: block.difficulty,
36 }
37 }
38}
39
40pub const NEMESIS_CHAIN_SCORE: u128 = 1;
42
43pub fn block_score(parent: &BlockStatistic, block: &BlockStatistic) -> u64 {
47 if block.timestamp <= parent.timestamp {
48 return 0;
49 }
50 block
51 .difficulty
52 .wrapping_sub((block.timestamp - parent.timestamp) / 1000)
53}
54
55pub fn difficulty(previous: &[BlockStatistic], parameters: &NetworkParameters) -> u64 {
60 let previous = &previous[previous
61 .len()
62 .saturating_sub(parameters.max_difficulty_blocks)..];
63 let (Some(first), Some(last)) = (previous.first(), previous.last()) else {
64 return DEFAULT_DIFFICULTY;
65 };
66 if previous.len() < 2 {
67 return DEFAULT_DIFFICULTY;
68 }
69 let count = previous.len() as u64;
70 let average = previous
71 .iter()
72 .map(|statistic| statistic.difficulty)
73 .sum::<u64>()
74 / count;
75 let elapsed = last.timestamp - first.timestamp;
76 let target_time = parameters.block_generation_target_time.as_millis();
77 let scaled = u128::from(average) * target_time * u128::from(count - 1) / u128::from(elapsed);
79 let mut difficulty = u64::try_from(scaled).unwrap_or(u64::MAX);
80 let last = last.difficulty;
81 if 19 * last > 20 * difficulty {
82 difficulty = 19 * last / 20;
83 } else if 21 * last < 20 * difficulty {
84 difficulty = 21 * last / 20;
85 }
86 difficulty.clamp(MIN_DIFFICULTY, MAX_DIFFICULTY)
87}
88
89pub fn hit(generation_hash: &GenerationHash) -> u64 {
93 let hash = &generation_hash.0;
94 let leading_zeros = hash
95 .iter()
96 .position(|&byte| byte != 0)
97 .map_or(256, |index| 8 * index as u32 + hash[index].leading_zeros());
98 let at = |index: usize| u32::from_be_bytes(hash[index..index + 4].try_into().expect("4 bytes"));
99 let (value, leading_zeros) = if leading_zeros >= 224 {
100 (at(28), 224)
101 } else {
102 let quotient = (leading_zeros / 8) as usize;
103 let remainder = leading_zeros % 8;
104 let next = u32::from(hash[quotient + 4]) >> (8 - remainder);
106 (
107 (at(quotient) << remainder).wrapping_add(next),
108 leading_zeros,
109 )
110 };
111 if value == 0 {
112 return u64::MAX;
113 }
114 if value == u32::MAX {
115 return 0;
116 }
117 let log = log2_times_power_of_two(u64::from(value), 54);
118 let result = u128::from(32 + leading_zeros) * (1 << 54) - u128::from(log);
119 (result * 10_000_000_000_000_000 / 14_426_950_408_889_634) as u64
121}
122
123pub fn target(
128 elapsed_seconds: u64,
129 difficulty: u64,
130 importance: u64,
131 parameters: &NetworkParameters,
132) -> U256 {
133 let mut target = U256::from(elapsed_seconds);
134 target = target.mul_u64(importance);
135 target = target.mul_u64(u64::from(smoother(elapsed_seconds, parameters)));
137 target = target.shl(48);
138 target = target.mul_u64(8_999_999_998);
139 target = target.div_u64(parameters.total_chain_importance);
140 target.div_u64(difficulty)
141}
142
143pub fn earliest_hit_seconds(
146 hit: u64,
147 difficulty: u64,
148 importance: u64,
149 max_seconds: u64,
150 parameters: &NetworkParameters,
151) -> Option<u64> {
152 let passes =
153 |seconds| target(seconds, difficulty, importance, parameters).greater_than_u64(hit);
154 if max_seconds == 0 || !passes(max_seconds) {
155 return None;
156 }
157 let (mut low, mut high) = (0, max_seconds);
159 while high - low > 1 {
160 let middle = low + (high - low) / 2;
161 if passes(middle) {
162 high = middle;
163 } else {
164 low = middle;
165 }
166 }
167 Some(high)
168}
169
170pub fn is_hit(
173 parent: &Block,
174 block: &Block,
175 importance: u64,
176 parameters: &NetworkParameters,
177) -> bool {
178 if block.timestamp <= parent.timestamp {
179 return false;
180 }
181 let elapsed_seconds = (block.timestamp - parent.timestamp) / 1000;
182 let target = target(elapsed_seconds, block.difficulty, importance, parameters);
183 target.greater_than_u64(hit(&block.generation_hash()))
184}
185
186fn smoother(elapsed_seconds: u64, parameters: &NetworkParameters) -> u32 {
188 const LOG2_100: i128 = 435_411;
190 if parameters.block_time_smoothing_factor == 0 {
191 return 1 << 16;
192 }
193 let factor = ((i128::from(parameters.block_time_smoothing_factor) << 16) << 16) / (1000 << 16);
194 let target_time = (parameters.block_generation_target_time.as_secs() as i128) << 16;
195 let elapsed = i128::from(elapsed_seconds) << 16;
196 let power = factor * (elapsed - target_time) / target_time;
198 let power = power * 14_426_950_408 / 10_000_000_000;
199 if power < -(5 << 16) {
200 0
201 } else if power > LOG2_100 {
202 100 << 16
203 } else {
204 fixed_point_power_of_two(power as i32)
205 }
206}
207
208fn log2_times_power_of_two(value: u64, n: u32) -> u64 {
210 const PRECISION: u64 = 31;
211 const POWER_OF_TWO: u64 = 1 << PRECISION;
212 let mut y = PRECISION;
213 let mut x = value;
214 while x < POWER_OF_TWO {
216 x <<= 1;
217 y -= 1;
218 }
219 for _ in 0..n {
221 x = (x * x) >> PRECISION;
222 y <<= 1;
223 if x >= 2 * POWER_OF_TWO {
224 x >>= 1;
225 y += 1;
226 }
227 }
228 y
229}
230
231fn fixed_point_power_of_two(value: i32) -> u32 {
233 let i = (value + 0x8000) & !0xFFFF;
235 let f = i64::from(value - i);
236 let shift = ((15 << 16) - i) / 65_536;
237 let mut r: i64 = 0x0000_0E20;
239 r = (r * f + 0x3E1C_C333) / 131_072;
240 r = (r * f + 0x58BD_46A6) / 65_536;
241 r = r * f + 0x7FFD_E4A3;
242 (r as u32) >> shift
243}
244
245#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
248pub struct U256 {
249 limbs: [u64; 4],
251}
252
253impl From<u64> for U256 {
254 fn from(value: u64) -> Self {
255 Self {
256 limbs: [0, 0, 0, value],
257 }
258 }
259}
260
261impl U256 {
262 pub fn to_be_bytes(self) -> [u8; 32] {
264 let mut out = [0; 32];
265 for (chunk, limb) in out.as_chunks_mut::<8>().0.iter_mut().zip(self.limbs) {
266 *chunk = limb.to_be_bytes();
267 }
268 out
269 }
270
271 pub fn to_f64(self) -> f64 {
273 self.limbs.iter().fold(0.0, |value, &limb| {
274 value * 18_446_744_073_709_551_616.0 + limb as f64
275 })
276 }
277
278 pub fn greater_than_u64(self, value: u64) -> bool {
280 self > Self::from(value)
281 }
282
283 fn mul_u64(self, value: u64) -> Self {
285 let mut limbs = [0; 4];
286 let mut carry = 0u128;
287 for index in (0..4).rev() {
288 let product = u128::from(self.limbs[index]) * u128::from(value) + carry;
289 limbs[index] = product as u64;
290 carry = product >> 64;
291 }
292 Self { limbs }
293 }
294
295 fn div_u64(self, value: u64) -> Self {
297 let mut limbs = [0; 4];
298 let mut remainder = 0u128;
299 for (limb, ¤t) in limbs.iter_mut().zip(&self.limbs) {
300 let current = (remainder << 64) | u128::from(current);
301 *limb = (current / u128::from(value)) as u64;
302 remainder = current % u128::from(value);
303 }
304 Self { limbs }
305 }
306
307 fn shl(self, bits: u32) -> Self {
309 debug_assert!(0 < bits && bits < 64);
310 let mut limbs = [0; 4];
311 for (index, limb) in limbs.iter_mut().enumerate() {
312 *limb = self.limbs[index] << bits;
313 if let Some(lower) = self.limbs.get(index + 1) {
314 *limb |= lower >> (64 - bits);
315 }
316 }
317 Self { limbs }
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 const MAINNET: NetworkParameters = NetworkParameters::MAINNET;
326
327 fn steady(count: usize, interval: u64, difficulty: u64) -> Vec<BlockStatistic> {
329 (0..count as u64)
330 .map(|index| BlockStatistic {
331 timestamp: 1_000_000 + index * interval,
332 difficulty,
333 })
334 .collect()
335 }
336
337 #[test]
338 fn earliest_hit_is_where_the_target_first_passes_the_hit() {
339 let (difficulty, importance) = (DEFAULT_DIFFICULTY, MAINNET.total_chain_importance / 1000);
340 let passes =
341 |seconds| target(seconds, difficulty, importance, &MAINNET).greater_than_u64(1 << 50);
342 let seconds = earliest_hit_seconds(1 << 50, difficulty, importance, 3600, &MAINNET)
343 .expect("1時間のうちには当たる");
344 assert!(passes(seconds));
345 assert!(seconds == 1 || !passes(seconds - 1));
346 for shift in [40, 45, 50, 55, 60] {
348 let linear = (1..=3600_u64).find(|&s| {
349 target(s, difficulty, importance, &MAINNET).greater_than_u64(1 << shift)
350 });
351 assert_eq!(
352 earliest_hit_seconds(1 << shift, difficulty, importance, 3600, &MAINNET),
353 linear
354 );
355 }
356 assert_eq!(
358 earliest_hit_seconds(1 << 50, difficulty, importance, seconds - 1, &MAINNET),
359 None
360 );
361 }
362
363 #[test]
364 fn difficulty_defaults_with_fewer_than_two_blocks() {
365 assert_eq!(difficulty(&[], &MAINNET), DEFAULT_DIFFICULTY);
366 assert_eq!(
367 difficulty(&steady(1, 30_000, 5 * MIN_DIFFICULTY), &MAINNET),
368 DEFAULT_DIFFICULTY
369 );
370 }
371
372 #[test]
373 fn difficulty_stays_when_blocks_keep_the_target_time() {
374 let difficulty_value = 3 * DEFAULT_DIFFICULTY;
375 assert_eq!(
376 difficulty(&steady(60, 30_000, difficulty_value), &MAINNET),
377 difficulty_value
378 );
379 }
380
381 #[test]
382 fn difficulty_moves_at_most_five_percent() {
383 let base = 2 * DEFAULT_DIFFICULTY;
384 assert_eq!(
386 difficulty(&steady(60, 1_000, base), &MAINNET),
387 base * 21 / 20
388 );
389 assert_eq!(
390 difficulty(&steady(60, 600_000, base), &MAINNET),
391 base * 19 / 20
392 );
393 let slower = difficulty(&steady(60, 31_000, base), &MAINNET);
395 assert_eq!(slower, (u128::from(base) * 30_000 / 31_000) as u64);
396 }
397
398 #[test]
399 fn difficulty_stays_within_the_range() {
400 assert_eq!(
401 difficulty(&steady(60, 600_000, MIN_DIFFICULTY), &MAINNET),
402 MIN_DIFFICULTY
403 );
404 assert_eq!(
405 difficulty(&steady(60, 1_000, MAX_DIFFICULTY), &MAINNET),
406 MAX_DIFFICULTY
407 );
408 }
409
410 #[test]
411 fn difficulty_looks_only_at_the_last_max_difficulty_blocks() {
412 let mut statistics = steady(100, 30_000, DEFAULT_DIFFICULTY);
413 statistics[0].difficulty = MAX_DIFFICULTY;
415 statistics[39].timestamp = 0;
416 assert_eq!(difficulty(&statistics, &MAINNET), DEFAULT_DIFFICULTY);
417 }
418
419 fn approximate_hit(hash: &[u8; 32]) -> f64 {
421 let leading_zeros = hash
422 .iter()
423 .position(|&byte| byte != 0)
424 .map_or(256, |index| 8 * index as u32 + hash[index].leading_zeros());
425 let start = (leading_zeros / 8) as usize;
426 let mut mantissa = 0f64;
427 for (offset, &byte) in hash[start..].iter().take(8).enumerate() {
428 mantissa += f64::from(byte) * 256f64.powi(-(offset as i32) - 1);
429 }
430 let log2 = mantissa.log2() - 8.0 * start as f64;
431 -log2 * std::f64::consts::LN_2 * 2f64.powi(54)
432 }
433
434 #[test]
435 fn hit_is_close_to_the_logarithm() {
436 let mut hash = [0u8; 32];
437 for seed in 0..200u32 {
438 for (index, byte) in hash.iter_mut().enumerate() {
440 *byte = (seed
441 .wrapping_mul(2_654_435_761)
442 .rotate_left(index as u32 * 7)
443 >> 11) as u8;
444 }
445 let zeros = (seed % 9) as usize;
446 hash[..zeros].fill(0);
447 if hash.iter().all(|&byte| byte == 0) {
448 continue;
449 }
450 let expected = approximate_hit(&hash);
451 let actual = hit(&GenerationHash(hash)) as f64;
452 assert!(
454 ((actual - expected) / expected).abs() < 1e-6,
455 "{seed}: {actual} と {expected}"
456 );
457 }
458 }
459
460 #[test]
461 fn hit_handles_the_edges() {
462 assert_eq!(hit(&GenerationHash([0; 32])), u64::MAX);
463 assert_eq!(hit(&GenerationHash([0xFF; 32])), 0);
464 let mut small = [0; 32];
466 small[..2].copy_from_slice(&[0x01, 0x80]);
467 let mut large = [0; 32];
468 large[0] = 0x80;
469 assert!(hit(&GenerationHash(small)) > hit(&GenerationHash(large)));
470 let mut ones = [0xFF; 32];
472 ones[0] = 0x01;
473 assert_eq!(hit(&GenerationHash(ones)), 0);
474 }
475
476 #[test]
477 fn log2_times_power_of_two_matches_the_logarithm() {
478 for value in [1u64, 2, 3, 1_000, 0x8000_0000, 0xFFFF_FFFE, 123_456_789] {
479 let expected = (value as f64).log2() * 2f64.powi(20);
480 let actual = log2_times_power_of_two(value, 20) as f64;
481 assert!(
482 (actual - expected).abs() <= 1.0,
483 "{value}: {actual} と {expected}"
484 );
485 }
486 }
487
488 #[test]
489 fn fixed_point_power_of_two_matches_the_power() {
490 for value in (-5 * 65_536..=435_411).step_by(4_099) {
491 let expected = 2f64.powf(f64::from(value) / 65_536.0) * 65_536.0;
492 let actual = f64::from(fixed_point_power_of_two(value));
493 assert!(
495 (actual - expected).abs() <= expected * 1e-4 + 1.0,
496 "{value}: {actual} と {expected}"
497 );
498 }
499 }
500
501 #[test]
502 fn converts_to_f64() {
503 assert_eq!(U256::from(12_345).to_f64(), 12_345.0);
504 let big = U256::from(u64::MAX).shl(48);
505 let expected = u64::MAX as f64 * 2f64.powi(48);
506 assert!((big.to_f64() - expected).abs() / expected < 1e-12);
507 }
508
509 #[test]
510 fn smoother_is_one_at_the_target_time_and_capped() {
511 let one = f64::from(smoother(30, &MAINNET)) / 65_536.0;
512 assert!((one - 1.0).abs() < 1e-3, "{one}");
513 assert!(smoother(20, &MAINNET) < smoother(30, &MAINNET));
515 assert!(smoother(40, &MAINNET) > smoother(30, &MAINNET));
516 assert_eq!(smoother(10_000, &MAINNET), 100 << 16);
517 let zero = f64::from(smoother(0, &MAINNET)) / 65_536.0;
519 assert!(
520 (zero - 2f64.powf(-3.0 * std::f64::consts::LOG2_E)).abs() < 1e-3,
521 "{zero}"
522 );
523 }
524
525 #[test]
526 fn target_scales_with_time_and_importance() {
527 let importance = MAINNET.total_chain_importance / 1000;
528 let at = |seconds| {
529 let bytes = target(seconds, DEFAULT_DIFFICULTY, importance, &MAINNET).to_be_bytes();
530 u128::from_be_bytes(bytes[16..].try_into().unwrap())
531 };
532 let expected = 30.0 * importance as f64 * 2f64.powi(64) * 8_999_999_998.0
534 / (MAINNET.total_chain_importance as f64 * DEFAULT_DIFFICULTY as f64);
535 let actual = at(30) as f64;
536 assert!(
537 ((actual - expected) / expected).abs() < 1e-3,
538 "{actual} と {expected}"
539 );
540 assert!(at(31) > at(30));
541 assert_eq!(target(30, DEFAULT_DIFFICULTY, 0, &MAINNET), U256::default());
542 }
543
544 #[test]
545 fn u256_multiplies_divides_and_shifts() {
546 let value = U256::from(u64::MAX).mul_u64(u64::MAX).shl(48).mul_u64(3);
547 assert_eq!(
548 value.div_u64(3).div_u64(u64::MAX),
549 U256::from(u64::MAX).shl(48)
550 );
551 let bytes = U256::from(1).shl(63).mul_u64(4).to_be_bytes();
552 assert_eq!(bytes[23], 2);
553 assert!(U256::from(1).shl(1).greater_than_u64(1));
554 assert!(!U256::from(5).greater_than_u64(5));
555 }
556
557 #[test]
558 fn scores_a_block_by_its_difficulty_minus_the_seconds_since_the_parent() {
559 let at = |timestamp, difficulty| BlockStatistic {
560 timestamp,
561 difficulty,
562 };
563 assert_eq!(block_score(&at(1_000, 7), &at(31_999, 100)), 100 - 30);
564 assert_eq!(block_score(&at(1_000, 7), &at(1_000, 100)), 0);
565 assert_eq!(block_score(&at(2_000, 7), &at(1_000, 100)), 0);
566 }
567}