mod.rs 1.3 KB

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