Skip to main content

cashu/util/
mod.rs

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