util.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. collections::HashMap,
  20. fs::{self, File, OpenOptions},
  21. io::Write,
  22. path::Path,
  23. time::UNIX_EPOCH,
  24. };
  25. use darkfi_serial::{deserialize, deserialize_async, serialize};
  26. use log::error;
  27. use sled_overlay::sled;
  28. use tinyjson::JsonValue;
  29. use crate::{
  30. event_graph::{Event, GENESIS_CONTENTS, INITIAL_GENESIS, NULL_ID, N_EVENT_PARENTS},
  31. rpc::{
  32. jsonrpc::{ErrorCode, JsonError, JsonResponse, JsonResult},
  33. util::json_map,
  34. },
  35. util::{encoding::base64, file::load_file},
  36. Result,
  37. };
  38. /// MilliSeconds in a day
  39. pub(super) const DAY: i64 = 86_400_000;
  40. /// Calculate the midnight timestamp given a number of days.
  41. /// If `days` is 0, calculate the midnight timestamp of today.
  42. pub(super) fn midnight_timestamp(days: i64) -> u64 {
  43. // Get current time
  44. let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as i64;
  45. // Find the timestamp for the midnight of the current day
  46. let cur_midnight = (now / DAY) * DAY;
  47. // Adjust for days_from_now
  48. (cur_midnight + (DAY * days)) as u64
  49. }
  50. /// Calculate the number of days since a given midnight timestamp.
  51. pub(super) fn days_since(midnight_ts: u64) -> u64 {
  52. // Get current time
  53. let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  54. // Calculate the difference between the current timestamp
  55. // and the given midnight timestamp
  56. let elapsed_seconds = now - midnight_ts;
  57. // Convert the elapsed seconds into days
  58. elapsed_seconds / DAY as u64
  59. }
  60. /// Calculate the timestamp of the next DAG rotation.
  61. pub fn next_rotation_timestamp(starting_timestamp: u64, rotation_period: u64) -> u64 {
  62. // Prevent division by 0
  63. if rotation_period == 0 {
  64. panic!("Rotation period cannot be 0");
  65. }
  66. // Calculate the number of days since the given starting point
  67. let days_passed = days_since(starting_timestamp);
  68. // Find out how many rotation periods have occurred since
  69. // the starting point.
  70. // Note: when rotation_period = 1, rotations_since_start = days_passed
  71. let rotations_since_start = days_passed.div_ceil(rotation_period);
  72. // Find out the number of days until the next rotation. Panic if result is beyond the range
  73. // of i64.
  74. let days_until_next_rotation: i64 =
  75. (rotations_since_start * rotation_period - days_passed).try_into().unwrap();
  76. // Get the timestamp for the next rotation
  77. if days_until_next_rotation == 0 {
  78. // If there are 0 days until the next rotation, we want
  79. // to rotate tomorrow, at midnight. This is a special case.
  80. return midnight_timestamp(1)
  81. }
  82. midnight_timestamp(days_until_next_rotation)
  83. }
  84. /// Calculate the time in milliseconds until the next_rotation, given
  85. /// as a timestamp.
  86. /// `next_rotation` here represents a timestamp in UNIX epoch format.
  87. pub fn millis_until_next_rotation(next_rotation: u64) -> u64 {
  88. // Store `now` in a variable in order to avoid a TOCTOU error.
  89. // There may be a drift of one second between this panic check and
  90. // the return value if we get unlucky.
  91. let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  92. if next_rotation < now {
  93. panic!("Next rotation timestamp is in the past");
  94. }
  95. next_rotation - now
  96. }
  97. /// Generate a deterministic genesis event corresponding to the DAG's configuration.
  98. pub fn generate_genesis(days_rotation: u64) -> Event {
  99. // Days rotation is u64 except zero
  100. let timestamp = if days_rotation == 0 {
  101. INITIAL_GENESIS
  102. } else {
  103. // First check how many days passed since initial genesis.
  104. let days_passed = days_since(INITIAL_GENESIS);
  105. // Calculate the number of days_rotation intervals since INITIAL_GENESIS
  106. let rotations_since_genesis = days_passed / days_rotation;
  107. // Calculate the timestamp of the most recent event
  108. INITIAL_GENESIS + (rotations_since_genesis * days_rotation * DAY as u64)
  109. };
  110. Event {
  111. timestamp,
  112. content: GENESIS_CONTENTS.to_vec(),
  113. parents: [NULL_ID; N_EVENT_PARENTS],
  114. layer: 0,
  115. }
  116. }
  117. pub(super) fn replayer_log(datastore: &Path, cmd: String, value: Vec<u8>) -> Result<()> {
  118. fs::create_dir_all(datastore)?;
  119. let datastore = datastore.join("replayer.log");
  120. if !datastore.exists() {
  121. File::create(&datastore)?;
  122. };
  123. let mut file = OpenOptions::new().append(true).open(&datastore)?;
  124. let v = base64::encode(&value);
  125. let f = format!("{cmd} {v}");
  126. writeln!(file, "{}", f)?;
  127. Ok(())
  128. }
  129. pub async fn recreate_from_replayer_log(datastore: &Path) -> JsonResult {
  130. let log_path = datastore.join("replayer.log");
  131. if !log_path.exists() {
  132. error!("Error loading replayed log");
  133. return JsonResult::Error(JsonError::new(
  134. ErrorCode::ParseError,
  135. Some("Error loading replayed log".to_string()),
  136. 1,
  137. ))
  138. };
  139. let reader = load_file(&log_path).unwrap();
  140. let db_datastore = datastore.join("replayed_db");
  141. let sled_db = sled::open(db_datastore).unwrap();
  142. let dag = sled_db.open_tree("replayer").unwrap();
  143. for line in reader.lines() {
  144. let line = line.split(' ').collect::<Vec<&str>>();
  145. if line[0] == "insert" {
  146. let v = base64::decode(line[1]).unwrap();
  147. let v: Event = deserialize(&v).unwrap();
  148. let v_se = serialize(&v);
  149. dag.insert(v.id().as_bytes(), v_se).unwrap();
  150. }
  151. }
  152. let mut graph = HashMap::new();
  153. for iter_elem in dag.iter() {
  154. let (id, val) = iter_elem.unwrap();
  155. let id = blake3::Hash::from_bytes((&id as &[u8]).try_into().unwrap());
  156. let val: Event = deserialize_async(&val).await.unwrap();
  157. graph.insert(id, val);
  158. }
  159. let json_graph = graph
  160. .into_iter()
  161. .map(|(k, v)| {
  162. let key = k.to_string();
  163. let value = JsonValue::from(v);
  164. (key, value)
  165. })
  166. .collect();
  167. let values = json_map([("dag", JsonValue::Object(json_graph))]);
  168. let result = JsonValue::Object(HashMap::from([("eventgraph_info".to_string(), values)]));
  169. JsonResponse::new(result, 1).into()
  170. }
  171. #[cfg(test)]
  172. mod tests {
  173. use super::*;
  174. #[test]
  175. fn test_days_since() {
  176. let five_days_ago = midnight_timestamp(-5);
  177. assert_eq!(days_since(five_days_ago), 5);
  178. let today = midnight_timestamp(0);
  179. assert_eq!(days_since(today), 0);
  180. }
  181. #[test]
  182. fn test_next_rotation_timestamp() {
  183. let starting_point = midnight_timestamp(-10);
  184. let rotation_period = 7;
  185. // The first rotation since the starting point would be 3 days ago.
  186. // So the next rotation should be 4 days from now.
  187. let expected = midnight_timestamp(4);
  188. assert_eq!(next_rotation_timestamp(starting_point, rotation_period), expected);
  189. // When starting from today with a rotation period of 1 (day),
  190. // we should get tomorrow's timestamp.
  191. // This is a special case.
  192. let midnight_today: u64 = midnight_timestamp(0);
  193. let midnight_tomorrow = midnight_today + 86_400_000u64; // add a day
  194. assert_eq!(midnight_tomorrow, next_rotation_timestamp(midnight_today, 1));
  195. }
  196. #[test]
  197. #[should_panic]
  198. fn test_next_rotation_timestamp_panics_on_overflow() {
  199. next_rotation_timestamp(0, u64::MAX);
  200. }
  201. #[test]
  202. #[should_panic]
  203. fn test_next_rotation_timestamp_panics_on_division_by_zero() {
  204. next_rotation_timestamp(0, 0);
  205. }
  206. #[test]
  207. fn test_millis_until_next_rotation_is_within_rotation_interval() {
  208. let days_rotation = 1u64;
  209. // The amount of time in seconds between rotations.
  210. let rotation_interval = days_rotation * 86_400_000u64;
  211. let next_rotation_timestamp = next_rotation_timestamp(INITIAL_GENESIS, days_rotation);
  212. let s = millis_until_next_rotation(next_rotation_timestamp);
  213. assert!(s < rotation_interval);
  214. }
  215. }