From 31bf3225742206dd81fb630fdb6afa59112199f5 Mon Sep 17 00:00:00 2001 From: Shing Him Ng Date: Fri, 6 Dec 2024 23:54:25 -0600 Subject: [PATCH] Add deserializer for ohttp keys --- payjoin-cli/src/app/config.rs | 38 ++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/payjoin-cli/src/app/config.rs b/payjoin-cli/src/app/config.rs index faf22536..c4c14dd8 100644 --- a/payjoin-cli/src/app/config.rs +++ b/payjoin-cli/src/app/config.rs @@ -20,6 +20,7 @@ pub struct AppConfig { // v2 only #[cfg(feature = "v2")] + #[serde(deserialize_with = "deserialize_ohttp_keys_from_path")] pub ohttp_keys: Option, #[cfg(feature = "v2")] pub ohttp_relay: Url, @@ -72,7 +73,8 @@ impl AppConfig { "ohttp_relay", matches.get_one::("ohttp_relay").map(|s| s.as_str()), )? - .set_default("pj_directory", "https://payjo.in")?; + .set_default("pj_directory", "https://payjo.in")? + .set_default("ohttp_keys", None::)?; let builder = match matches.subcommand() { Some(("send", _)) => builder, @@ -101,17 +103,7 @@ impl AppConfig { )? .set_override_option( "ohttp_keys", - matches.get_one::("ohttp_keys").and_then(|s| { - std::fs::read(s) - .map_err(|e| { - log::error!("Failed to read ohttp_keys file: {}", e); - ConfigError::Message(format!( - "Failed to read ohttp_keys file: {}", - e - )) - }) - .ok() - }), + matches.get_one::("ohttp_keys").map(|s| s.as_str()), )? }; @@ -135,3 +127,25 @@ impl AppConfig { Ok(app_config) } } + +#[cfg(feature = "v2")] +fn deserialize_ohttp_keys_from_path<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let path_str: Option = Option::deserialize(deserializer)?; + + match path_str { + None => Ok(None), + Some(path) => std::fs::read(path) + .map_err(|e| serde::de::Error::custom(format!("Failed to read ohttp_keys file: {}", e))) + .and_then(|bytes| { + payjoin::OhttpKeys::decode(&bytes).map_err(|e| { + serde::de::Error::custom(format!("Failed to decode ohttp keys: {}", e)) + }) + }) + .map(Some), + } +}