cashu/util/
mod.rs

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