tests.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. cmp::min,
  20. io::{BufRead, Cursor},
  21. process::Command,
  22. };
  23. use darkfi_sdk::num_traits::{Num, Zero};
  24. use num_bigint::BigUint;
  25. use crate::{next_difficulty, DIFFICULTY_LAG, DIFFICULTY_WINDOW};
  26. const DEFAULT_TEST_DIFFICULTY_TARGET: usize = 120;
  27. #[test]
  28. fn test_wide_difficulty() {
  29. let mut timestamps: Vec<u64> = vec![];
  30. let mut cummulative_difficulties: Vec<BigUint> = vec![];
  31. let mut cummulative_difficulty = BigUint::zero();
  32. let output = Command::new("./gen_wide_data.py").output().unwrap();
  33. let reader = Cursor::new(output.stdout);
  34. for (n, line) in reader.lines().enumerate() {
  35. let line = line.unwrap();
  36. let parts: Vec<String> = line.split(' ').map(|x| x.to_string()).collect();
  37. assert!(parts.len() == 2);
  38. let timestamp = parts[0].parse::<u64>().unwrap();
  39. let difficulty = BigUint::from_str_radix(&parts[1], 10).unwrap();
  40. let begin: usize;
  41. let end: usize;
  42. if n < DIFFICULTY_WINDOW + DIFFICULTY_LAG {
  43. begin = 0;
  44. end = min(n, DIFFICULTY_WINDOW);
  45. } else {
  46. end = n - DIFFICULTY_LAG;
  47. begin = end - DIFFICULTY_WINDOW;
  48. }
  49. let mut timestamps_cut = timestamps[begin..end].to_vec();
  50. let difficulty_cut = &cummulative_difficulties[begin..end];
  51. let res =
  52. next_difficulty(&mut timestamps_cut, difficulty_cut, DEFAULT_TEST_DIFFICULTY_TARGET);
  53. if res != difficulty {
  54. eprintln!("Wrong wide difficulty for block {}", n);
  55. eprintln!("Expected: {}", difficulty);
  56. eprintln!("Found: {}", res);
  57. assert!(res == difficulty);
  58. }
  59. timestamps.push(timestamp);
  60. cummulative_difficulty += difficulty;
  61. cummulative_difficulties.push(cummulative_difficulty.clone());
  62. }
  63. }