nostr.rs (2304B)
1 use std::collections::HashMap; 2 3 use radroots_nostr::prelude::{radroots_nostr_parse_pubkey, RadrootsNostrToBech32}; 4 use thiserror::Error; 5 6 #[derive(Debug, Error)] 7 pub enum NostrUtilsError { 8 #[error("Invalid public key: {0}")] 9 InvalidPublicKey(#[from] radroots_nostr::parse::ParseError), 10 #[error("Tag parsing error: {0}")] 11 TagParseError(String), 12 } 13 14 pub fn public_key_to_npub(public_key_hex: &str) -> Result<String, NostrUtilsError> { 15 let pubkey = radroots_nostr_parse_pubkey(public_key_hex)?; 16 let bech32 = match pubkey.to_bech32() { 17 Ok(value) => value, 18 Err(err) => match err {}, 19 }; 20 Ok(bech32) 21 } 22 23 pub(crate) fn normalize_nip05(nip05: &str) -> (String, String, String) { 24 let lower = nip05.to_lowercase(); 25 let local = lower 26 .split_once('@') 27 .map(|(name, _)| name.to_string()) 28 .unwrap_or_else(|| lower.clone()); 29 let index_key = lower 30 .strip_suffix("@radroots.market") 31 .map(|s| s.to_string()) 32 .unwrap_or_else(|| lower.clone()); 33 (lower, local, index_key) 34 } 35 36 pub fn get_tag_value<'a>( 37 tags_map: &'a HashMap<String, Vec<String>>, 38 key: &str, 39 idx: usize, 40 ) -> Result<Option<String>, NostrUtilsError> { 41 match tags_map.get(key) { 42 Some(values) => Ok(values.get(idx).cloned()), 43 None => Err(NostrUtilsError::TagParseError(format!( 44 "Tag '{}' not found", 45 key 46 ))), 47 } 48 } 49 50 #[cfg(test)] 51 mod tests { 52 use super::normalize_nip05; 53 54 #[test] 55 fn normalize_nip05_lowercases_and_extracts_parts() { 56 let (full, local, index_key) = normalize_nip05("Alice@Radroots.Market"); 57 assert_eq!(full, "alice@radroots.market"); 58 assert_eq!(local, "alice"); 59 assert_eq!(index_key, "alice"); 60 } 61 62 #[test] 63 fn normalize_nip05_without_domain_keeps_value() { 64 let (full, local, index_key) = normalize_nip05("User"); 65 assert_eq!(full, "user"); 66 assert_eq!(local, "user"); 67 assert_eq!(index_key, "user"); 68 } 69 70 #[test] 71 fn normalize_nip05_non_radroots_domain_keeps_index_key() { 72 let (full, local, index_key) = normalize_nip05("bob@example.com"); 73 assert_eq!(full, "bob@example.com"); 74 assert_eq!(local, "bob"); 75 assert_eq!(index_key, "bob@example.com"); 76 } 77 }