util.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. use chrono::{NaiveDateTime, Utc};
  2. use std::io;
  3. use crate::{
  4. util::serial::{Decodable, Encodable, ReadExt, SerialDecodable, SerialEncodable, WriteExt},
  5. Result,
  6. };
  7. // Serialized blake3 hash bytes for character "⊥"
  8. pub const GENESIS_HASH_BYTES: [u8; 32] = [
  9. 254, 233, 82, 102, 23, 208, 153, 87, 96, 165, 163, 194, 238, 7, 1, 88, 14, 1, 249, 118, 197,
  10. 29, 180, 211, 87, 66, 59, 38, 86, 54, 12, 39,
  11. ];
  12. /// Util structure to represend chrono UTC timestamps.
  13. #[derive(Debug, Clone, SerialDecodable, SerialEncodable)]
  14. pub struct Timestamp(pub i64);
  15. impl Timestamp {
  16. /// Calculates elapsed time of a Timestamp.
  17. pub fn elapsed(self) -> u64 {
  18. let start_time = NaiveDateTime::from_timestamp(self.0, 0);
  19. let end_time = NaiveDateTime::from_timestamp(Utc::now().timestamp(), 0);
  20. let diff = end_time - start_time;
  21. diff.num_seconds().try_into().unwrap()
  22. }
  23. }
  24. /// Util function to generate a Timestamp of current time.
  25. pub fn get_current_time() -> Timestamp {
  26. Timestamp(Utc::now().timestamp())
  27. }
  28. impl Encodable for blake3::Hash {
  29. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  30. s.write_slice(self.as_bytes())?;
  31. Ok(32)
  32. }
  33. }
  34. impl Decodable for blake3::Hash {
  35. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  36. let mut bytes = [0u8; 32];
  37. d.read_slice(&mut bytes)?;
  38. Ok(bytes.into())
  39. }
  40. }