time.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::time::UNIX_EPOCH;
  19. use chrono::{NaiveDateTime, Utc};
  20. use darkfi_serial::{SerialDecodable, SerialEncodable};
  21. use serde::{Deserialize, Serialize};
  22. use crate::Result;
  23. /// Helper structure providing time related calculations.
  24. #[derive(Clone)]
  25. pub struct TimeKeeper {
  26. /// Genesis block creation timestamp
  27. pub genesis_ts: Timestamp,
  28. /// Currently configured epoch duration.
  29. pub epoch_length: u64,
  30. /// Currently configured slot duration.
  31. pub slot_time: u64,
  32. }
  33. impl TimeKeeper {
  34. pub fn new(genesis_ts: Timestamp, epoch_length: u64, slot_time: u64) -> Self {
  35. Self { genesis_ts, epoch_length, slot_time }
  36. }
  37. /// Calculates current epoch.
  38. pub fn current_epoch(&self) -> u64 {
  39. self.slot_epoch(self.current_slot())
  40. }
  41. /// Calculates the epoch of the provided slot.
  42. pub fn slot_epoch(&self, slot: u64) -> u64 {
  43. slot / self.epoch_length
  44. }
  45. /// Calculates current slot, based on elapsed time from the genesis block.
  46. pub fn current_slot(&self) -> u64 {
  47. self.genesis_ts.elapsed() / self.slot_time
  48. }
  49. /// Calculates the relative number of the provided slot.
  50. pub fn relative_slot(&self, slot: u64) -> u64 {
  51. slot % self.epoch_length
  52. }
  53. /// Calculates seconds until next Nth slot starting time.
  54. pub fn next_n_slot_start(&self, n: u64) -> u64 {
  55. assert!(n > 0);
  56. let next_slot_start = self.genesis_ts.0 + (self.current_slot() + n) * self.slot_time;
  57. next_slot_start - Timestamp::current_time().0
  58. }
  59. /// Calculate slots until next Nth epoch.
  60. /// Epoch duration is configured using the EPOCH_LENGTH value.
  61. pub fn slots_to_next_n_epoch(&self, n: u64) -> u64 {
  62. assert!(n > 0);
  63. let slots_till_next_epoch = self.epoch_length - self.relative_slot(self.current_slot());
  64. ((n - 1) * self.epoch_length) + slots_till_next_epoch
  65. }
  66. /// Calculates seconds until next Nth epoch starting time.
  67. pub fn next_n_epoch_start(&self, n: u64) -> u64 {
  68. self.next_n_slot_start(self.slots_to_next_n_epoch(n))
  69. }
  70. /// Calculates current blockchain timestamp.
  71. /// Blockchain timestamp is the time elapsed since
  72. /// Genesis timestamp, based on slot time ticking,
  73. /// therefore representing the starting timestamp of
  74. /// current slot.
  75. pub fn blockchain_timestamp(&self) -> u64 {
  76. self.genesis_ts.0 + self.current_slot() * self.slot_time
  77. }
  78. /// Calculates current system timestamp.
  79. pub fn system_timestamp(&self) -> Result<u64> {
  80. Ok(UNIX_EPOCH.elapsed()?.as_secs())
  81. }
  82. }
  83. /// Wrapper struct to represent system timestamps.
  84. #[derive(
  85. Clone,
  86. Copy,
  87. Debug,
  88. Serialize,
  89. Deserialize,
  90. SerialEncodable,
  91. SerialDecodable,
  92. PartialEq,
  93. PartialOrd,
  94. Eq,
  95. )]
  96. pub struct Timestamp(pub u64);
  97. impl Timestamp {
  98. /// Generate a `Timestamp` of the current time.
  99. pub fn current_time() -> Self {
  100. Self(UNIX_EPOCH.elapsed().unwrap().as_secs())
  101. }
  102. /// Calculates elapsed time of a `Timestamp`.
  103. pub fn elapsed(&self) -> u64 {
  104. UNIX_EPOCH.elapsed().unwrap().as_secs() - self.0
  105. }
  106. /// Increment a 'Timestamp'.
  107. pub fn add(&mut self, inc: u64) {
  108. self.0 += inc;
  109. }
  110. }
  111. // TODO: NanoTimestamp to not use chrono
  112. #[derive(
  113. Clone,
  114. Copy,
  115. Debug,
  116. Serialize,
  117. Deserialize,
  118. SerialEncodable,
  119. SerialDecodable,
  120. PartialEq,
  121. PartialOrd,
  122. Eq,
  123. )]
  124. pub struct NanoTimestamp(pub i64);
  125. impl NanoTimestamp {
  126. pub fn current_time() -> Self {
  127. Self(Utc::now().timestamp_nanos())
  128. }
  129. }
  130. impl std::fmt::Display for NanoTimestamp {
  131. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  132. let date = timestamp_to_date(self.0, DateFormat::Nanos);
  133. write!(f, "{}", date)
  134. }
  135. }
  136. pub enum DateFormat {
  137. Default,
  138. Date,
  139. DateTime,
  140. Nanos,
  141. }
  142. pub fn timestamp_to_date(timestamp: i64, format: DateFormat) -> String {
  143. if timestamp <= 0 {
  144. return "".to_string()
  145. }
  146. match format {
  147. DateFormat::Date => NaiveDateTime::from_timestamp_opt(timestamp, 0)
  148. .unwrap()
  149. .date()
  150. .format("%-d %b")
  151. .to_string(),
  152. DateFormat::DateTime => NaiveDateTime::from_timestamp_opt(timestamp, 0)
  153. .unwrap()
  154. .format("%H:%M:%S %A %-d %B")
  155. .to_string(),
  156. DateFormat::Nanos => {
  157. const A_BILLION: i64 = 1_000_000_000;
  158. NaiveDateTime::from_timestamp_opt(timestamp / A_BILLION, (timestamp % A_BILLION) as u32)
  159. .unwrap()
  160. .format("%H:%M:%S.%f")
  161. .to_string()
  162. }
  163. DateFormat::Default => "".to_string(),
  164. }
  165. }