mod.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //! Cashu utils
  2. #[cfg(not(target_arch = "wasm32"))]
  3. use std::time::{SystemTime, UNIX_EPOCH};
  4. use bitcoin::secp256k1::{rand, All, Secp256k1};
  5. use once_cell::sync::Lazy;
  6. pub mod hex;
  7. #[cfg(target_arch = "wasm32")]
  8. use instant::SystemTime;
  9. #[cfg(target_arch = "wasm32")]
  10. const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH;
  11. /// Secp256k1 global context
  12. pub static SECP256K1: Lazy<Secp256k1<All>> = Lazy::new(|| {
  13. let mut ctx = Secp256k1::new();
  14. let mut rng = rand::thread_rng();
  15. ctx.randomize(&mut rng);
  16. ctx
  17. });
  18. /// Seconds since unix epoch
  19. pub fn unix_time() -> u64 {
  20. SystemTime::now()
  21. .duration_since(UNIX_EPOCH)
  22. .unwrap_or_default()
  23. .as_secs()
  24. }
  25. #[derive(Debug, thiserror::Error)]
  26. /// Error type for serialization
  27. pub enum CborError {
  28. /// CBOR serialization error
  29. #[error("CBOR serialization error")]
  30. Cbor(#[from] ciborium::ser::Error<std::io::Error>),
  31. /// CBOR diagnostic notation error
  32. #[error("CBOR diagnostic notation error: {0}")]
  33. CborDiag(#[from] cbor_diag::Error),
  34. }
  35. /// Serializes a struct to the CBOR diagnostic notation.
  36. ///
  37. /// See <https://www.rfc-editor.org/rfc/rfc8949.html#name-diagnostic-notation>
  38. pub fn serialize_to_cbor_diag<T: serde::Serialize>(data: &T) -> Result<String, CborError> {
  39. let mut cbor_buffer = Vec::new();
  40. ciborium::ser::into_writer(data, &mut cbor_buffer)?;
  41. let diag = cbor_diag::parse_bytes(&cbor_buffer)?;
  42. Ok(diag.to_diag_pretty())
  43. }