keypair.rs (3242B)
1 use nostr::nips::nip49::EncryptedSecretKey; 2 use serde::Deserialize; 3 use serde::Serialize; 4 5 use crate::Pubkey; 6 use crate::SecretKey; 7 8 #[derive(Debug, Eq, PartialEq)] 9 pub struct Keypair { 10 pub pubkey: Pubkey, 11 pub secret_key: Option<SecretKey>, 12 } 13 14 impl Keypair { 15 pub fn from_secret(secret_key: SecretKey) -> Self { 16 let cloned_secret_key = secret_key.clone(); 17 let nostr_keys = nostr::Keys::new(secret_key); 18 Keypair { 19 pubkey: Pubkey::new(nostr_keys.public_key().to_bytes()), 20 secret_key: Some(cloned_secret_key), 21 } 22 } 23 24 pub fn new(pubkey: Pubkey, secret_key: Option<SecretKey>) -> Self { 25 Keypair { pubkey, secret_key } 26 } 27 28 pub fn only_pubkey(pubkey: Pubkey) -> Self { 29 Keypair { 30 pubkey, 31 secret_key: None, 32 } 33 } 34 35 pub fn to_full(self) -> Option<FullKeypair> { 36 if let Some(secret_key) = self.secret_key { 37 Some(FullKeypair { 38 pubkey: self.pubkey, 39 secret_key, 40 }) 41 } else { 42 None 43 } 44 } 45 } 46 47 #[derive(Debug, Eq, PartialEq)] 48 pub struct FullKeypair { 49 pub pubkey: Pubkey, 50 pub secret_key: SecretKey, 51 } 52 53 impl FullKeypair { 54 pub fn new(pubkey: Pubkey, secret_key: SecretKey) -> Self { 55 FullKeypair { pubkey, secret_key } 56 } 57 58 pub fn generate() -> Self { 59 let mut rng = nostr::secp256k1::rand::rngs::OsRng; 60 let (secret_key, _) = &nostr::SECP256K1.generate_keypair(&mut rng); 61 let (xopk, _) = secret_key.x_only_public_key(&nostr::SECP256K1); 62 let secret_key = nostr::SecretKey::from(*secret_key); 63 FullKeypair { 64 pubkey: Pubkey::new(xopk.serialize()), 65 secret_key, 66 } 67 } 68 69 pub fn to_keypair(self) -> Keypair { 70 Keypair { 71 pubkey: self.pubkey, 72 secret_key: Some(self.secret_key), 73 } 74 } 75 } 76 77 impl std::fmt::Display for Keypair { 78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 79 write!( 80 f, 81 "Keypair:\n\tpublic: {}\n\tsecret: {}", 82 self.pubkey, 83 match self.secret_key { 84 Some(_) => "Some(<hidden>)", 85 None => "None", 86 } 87 ) 88 } 89 } 90 91 impl std::fmt::Display for FullKeypair { 92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 93 write!(f, "Keypair:\n\tpublic: {}\n\tsecret: <hidden>", self.pubkey) 94 } 95 } 96 97 #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] 98 pub struct SerializableKeypair { 99 pub pubkey: Pubkey, 100 pub encrypted_secret_key: Option<EncryptedSecretKey>, 101 } 102 103 impl SerializableKeypair { 104 pub fn from_keypair(kp: &Keypair, pass: &str, log_n: u8) -> Self { 105 Self { 106 pubkey: kp.pubkey.clone(), 107 encrypted_secret_key: kp.secret_key.clone().and_then(|s| { 108 EncryptedSecretKey::new(&s, pass, log_n, nostr::nips::nip49::KeySecurity::Weak).ok() 109 }), 110 } 111 } 112 113 pub fn to_keypair(&self, pass: &str) -> Keypair { 114 Keypair::new( 115 self.pubkey.clone(), 116 self.encrypted_secret_key 117 .and_then(|e| e.to_secret_key(pass).ok()), 118 ) 119 } 120 }