Procházet zdrojové kódy

CLI decode_token: use CBOR diagnostic format instead of pure JSON

This brings decoded TokenV4s in line with the format specified in NUT-00, especially around how byte array fields are handled.
ok300 před 6 měsíci
rodič
revize
65c1aea408

+ 2 - 1
crates/cdk-cli/src/sub_commands/decode_token.rs

@@ -2,6 +2,7 @@ use std::str::FromStr;
 
 use anyhow::Result;
 use cdk::nuts::Token;
+use cdk::util::serialize_to_cbor_diag;
 use clap::Args;
 
 #[derive(Args)]
@@ -13,6 +14,6 @@ pub struct DecodeTokenSubCommand {
 pub fn decode_token(sub_command_args: &DecodeTokenSubCommand) -> Result<()> {
     let token = Token::from_str(&sub_command_args.token)?;
 
-    println!("{:}", serde_json::to_string_pretty(&token)?);
+    println!("{:}", serialize_to_cbor_diag(&token)?);
     Ok(())
 }

+ 1 - 0
crates/cdk/Cargo.toml

@@ -27,6 +27,7 @@ bitcoin = { version= "0.30", features = [
     "rand-std",
 ] } # lightning-invoice uses v0.30
 ciborium = { version = "0.2.2", default-features = false, features = ["std"] }
+cbor-diag = "0.1.12"
 lightning-invoice = { version = "0.31", features = ["serde"] }
 once_cell = "1.19"
 regex = "1"

+ 12 - 0
crates/cdk/src/util/mod.rs

@@ -3,6 +3,7 @@
 #[cfg(not(target_arch = "wasm32"))]
 use std::time::{SystemTime, UNIX_EPOCH};
 
+use anyhow::Result;
 use bitcoin::secp256k1::{rand, All, Secp256k1};
 #[cfg(target_arch = "wasm32")]
 use instant::SystemTime;
@@ -28,3 +29,14 @@ pub fn unix_time() -> u64 {
         .unwrap_or_default()
         .as_secs()
 }
+
+/// Serializes a struct to the CBOR diagnostic notation.
+///
+/// See <https://www.rfc-editor.org/rfc/rfc8949.html#name-diagnostic-notation>
+pub fn serialize_to_cbor_diag<T: serde::Serialize>(data: &T) -> Result<String> {
+    let mut cbor_buffer = Vec::new();
+    ciborium::ser::into_writer(data, &mut cbor_buffer)?;
+
+    let diag = cbor_diag::parse_bytes(&cbor_buffer)?;
+    Ok(diag.to_diag_pretty())
+}