cashu/util/
mod.rs

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