nostr_types/types/
identity.rs

1#[cfg(feature = "nip46")]
2use crate::nip46::BunkerClient;
3use crate::{
4    ContentEncryptionAlgorithm, DelegationConditions, EncryptedPrivateKey, Error, Event, Id,
5    KeySecurity, KeySigner, LockableSigner, Metadata, PreEvent, PrivateKey, PublicKey, Rumor,
6    Signature, Signer, SignerExt,
7};
8use serde::{Deserialize, Serialize};
9use std::sync::mpsc::Sender;
10use std::sync::Arc;
11
12/// All states that your identity can be in
13#[derive(Debug, Default, Serialize, Deserialize)]
14pub enum Identity {
15    /// No identity information
16    #[default]
17    None,
18
19    /// Public key only
20    Public(PublicKey),
21
22    /// Private key
23    Private(Arc<KeySigner>),
24
25    /// Remote Signer (Bunker)
26    #[cfg(feature = "nip46")]
27    Remote(BunkerClient),
28}
29
30// No one besides the Identity has the internal Signer, so we can safely Send
31unsafe impl Send for Identity {}
32
33// Nobody can write while someone else is reading with just a non-mutable &reference
34unsafe impl Sync for Identity {}
35
36impl Identity {
37    /// New `Identity` from a public key
38    pub fn from_public_key(pk: PublicKey) -> Self {
39        Self::Public(pk)
40    }
41
42    /// New `Identity` from a private key
43    pub fn from_private_key(pk: PrivateKey, pass: &str, log_n: u8) -> Result<Self, Error> {
44        let key_signer = KeySigner::from_private_key(pk, pass, log_n)?;
45        Ok(Self::Private(Arc::new(key_signer)))
46    }
47
48    /// New `Identity` from an encrypted private key and a public key
49    pub fn from_locked_parts(pk: PublicKey, epk: EncryptedPrivateKey) -> Self {
50        let key_signer = KeySigner::from_locked_parts(epk, pk);
51        Self::Private(Arc::new(key_signer))
52    }
53
54    /// New `Identity` from an encrypted private key and its password
55    pub fn from_encrypted_private_key(epk: EncryptedPrivateKey, pass: &str) -> Result<Self, Error> {
56        let key_signer = KeySigner::from_encrypted_private_key(epk, pass)?;
57        Ok(Self::Private(Arc::new(key_signer)))
58    }
59
60    /// Generate a new `Identity`
61    pub fn generate(password: &str, log_n: u8) -> Result<Self, Error> {
62        let key_signer = KeySigner::generate(password, log_n)?;
63        Ok(Self::Private(Arc::new(key_signer)))
64    }
65
66    /// Get access to the inner `KeySigner`
67    pub fn inner_key_signer(&self) -> Option<Arc<KeySigner>> {
68        match self {
69            Self::None => None,
70            Self::Public(_) => None,
71            Self::Private(b) => Some(b.clone()),
72            #[cfg(feature = "nip46")]
73            Self::Remote(_) => None,
74        }
75    }
76
77    /// Unlock
78    pub fn unlock(&self, password: &str) -> Result<(), Error> {
79        match self {
80            Self::Private(arcsigner) => arcsigner.unlock(password),
81            #[cfg(feature = "nip46")]
82            Self::Remote(bc) => bc.unlock(password),
83            _ => Ok(()),
84        }
85    }
86
87    /// Lock access to the private key
88    pub fn lock(&self) {
89        match self {
90            Self::Private(arcsigner) => arcsigner.lock(),
91            #[cfg(feature = "nip46")]
92            Self::Remote(bc) => bc.lock(),
93            _ => (),
94        }
95    }
96
97    /// Has a public key
98    pub fn has_public_key(&self) -> bool {
99        !matches!(self, Self::None)
100    }
101
102    /// Has a private key
103    pub fn has_private_key(&self) -> bool {
104        matches!(self, Self::Private(_))
105    }
106
107    /// Is the identity locked?
108    pub fn is_locked(&self) -> bool {
109        match self {
110            Self::Private(box_signer) => box_signer.is_locked(),
111            #[cfg(feature = "nip46")]
112            Self::Remote(bc) => bc.is_locked(),
113            _ => false,
114        }
115    }
116
117    /// Is the identity unlocked?
118    pub fn is_unlocked(&self) -> bool {
119        !self.is_locked()
120    }
121
122    /// Can sign if unlocked
123    pub fn can_sign_if_unlocked(&self) -> bool {
124        match self {
125            Self::Private(_) => true,
126            #[cfg(feature = "nip46")]
127            Self::Remote(_) => true,
128            _ => false,
129        }
130    }
131
132    /// Change the passphrase used for locking access to the private key
133    pub fn change_passphrase(&self, old: &str, new: &str, log_n: u8) -> Result<(), Error> {
134        match self {
135            Self::None => Err(Error::NoPublicKey),
136            Self::Public(_) => Err(Error::NoPrivateKey),
137            Self::Private(arcsigner) => arcsigner.change_passphrase(old, new, log_n),
138            #[cfg(feature = "nip46")]
139            Self::Remote(bunkerclient) => bunkerclient.change_passphrase(old, new, log_n),
140        }
141    }
142
143    /// What is the public key?
144    pub fn public_key(&self) -> Option<PublicKey> {
145        match self {
146            Self::None => None,
147            Self::Public(pk) => Some(*pk),
148            Self::Private(arcsigner) => Some(arcsigner.public_key()),
149            #[cfg(feature = "nip46")]
150            Self::Remote(bunkerclient) => Some(bunkerclient.public_key()),
151        }
152    }
153
154    /// What is the signer's encrypted private key?
155    pub fn encrypted_private_key(&self) -> Option<EncryptedPrivateKey> {
156        if let Self::Private(arcsigner) = self {
157            arcsigner.encrypted_private_key()
158        } else {
159            None
160        }
161    }
162
163    /// Sign a 32-bit hash
164    pub async fn sign_id(&self, id: Id) -> Result<Signature, Error> {
165        match self {
166            Self::None => Err(Error::NoPublicKey),
167            Self::Public(_) => Err(Error::NoPrivateKey),
168            Self::Private(arcsigner) => arcsigner.sign_id(id).await,
169            #[cfg(feature = "nip46")]
170            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
171        }
172    }
173
174    /// Sign a message (this hashes with SHA-256 first internally)
175    pub async fn sign(&self, message: &[u8]) -> Result<Signature, Error> {
176        match self {
177            Self::None => Err(Error::NoPublicKey),
178            Self::Public(_) => Err(Error::NoPrivateKey),
179            Self::Private(arcsigner) => arcsigner.sign(message).await,
180            #[cfg(feature = "nip46")]
181            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
182        }
183    }
184
185    /// Encrypt
186    pub async fn encrypt(
187        &self,
188        other: &PublicKey,
189        plaintext: &str,
190        algo: ContentEncryptionAlgorithm,
191    ) -> Result<String, Error> {
192        match self {
193            Self::None => Err(Error::NoPublicKey),
194            Self::Public(_) => Err(Error::NoPrivateKey),
195            Self::Private(arcsigner) => arcsigner.encrypt(other, plaintext, algo).await,
196            #[cfg(feature = "nip46")]
197            Self::Remote(bunkerclient) => bunkerclient.encrypt(other, plaintext, algo).await,
198        }
199    }
200
201    /// Decrypt
202    pub async fn decrypt(&self, other: &PublicKey, ciphertext: &str) -> Result<String, Error> {
203        match self {
204            Self::None => Err(Error::NoPublicKey),
205            Self::Public(_) => Err(Error::NoPrivateKey),
206            Self::Private(arcsigner) => arcsigner.decrypt(other, ciphertext).await,
207            #[cfg(feature = "nip46")]
208            Self::Remote(bunkerclient) => bunkerclient.decrypt(other, ciphertext).await,
209        }
210    }
211
212    /// Get NIP-44 conversation key
213    pub async fn nip44_conversation_key(&self, other: &PublicKey) -> Result<[u8; 32], Error> {
214        match self {
215            Self::None => Err(Error::NoPublicKey),
216            Self::Public(_) => Err(Error::NoPrivateKey),
217            Self::Private(arcsigner) => arcsigner.nip44_conversation_key(other).await,
218            #[cfg(feature = "nip46")]
219            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
220        }
221    }
222
223    /// Get the security level of the private key
224    pub fn key_security(&self) -> Result<KeySecurity, Error> {
225        match self {
226            Self::None => Err(Error::NoPublicKey),
227            Self::Public(_) => Err(Error::NoPrivateKey),
228            Self::Private(arcsigner) => arcsigner.key_security(),
229            #[cfg(feature = "nip46")]
230            Self::Remote(bunkerclient) => bunkerclient.key_security(),
231        }
232    }
233
234    /// Upgrade the encrypted private key to the latest format
235    pub fn upgrade(&self, pass: &str, log_n: u8) -> Result<(), Error> {
236        match self {
237            Self::None => Err(Error::NoPublicKey),
238            Self::Public(_) => Err(Error::NoPrivateKey),
239            Self::Private(arcsigner) => arcsigner.upgrade(pass, log_n),
240            #[cfg(feature = "nip46")]
241            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
242        }
243    }
244
245    /// Create an event that sets Metadata
246    pub async fn create_metadata_event(
247        &self,
248        input: PreEvent,
249        metadata: Metadata,
250    ) -> Result<Event, Error> {
251        match self {
252            Self::None => Err(Error::NoPublicKey),
253            Self::Public(_) => Err(Error::NoPrivateKey),
254            Self::Private(arcsigner) => arcsigner.create_metadata_event(input, metadata).await,
255            #[cfg(feature = "nip46")]
256            Self::Remote(bunkerclient) => bunkerclient.create_metadata_event(input, metadata).await,
257        }
258    }
259
260    /// Create a ZapRequest event These events are not published to nostr, they are sent to a lnurl.
261    pub async fn create_zap_request_event(
262        &self,
263        recipient_pubkey: PublicKey,
264        zapped_event: Option<Id>,
265        millisatoshis: u64,
266        relays: Vec<String>,
267        content: String,
268    ) -> Result<Event, Error> {
269        match self {
270            Self::None => Err(Error::NoPublicKey),
271            Self::Public(_) => Err(Error::NoPrivateKey),
272            Self::Private(arcsigner) => {
273                arcsigner
274                    .create_zap_request_event(
275                        recipient_pubkey,
276                        zapped_event,
277                        millisatoshis,
278                        relays,
279                        content,
280                    )
281                    .await
282            }
283            #[cfg(feature = "nip46")]
284            Self::Remote(bunkerclient) => {
285                bunkerclient
286                    .create_zap_request_event(
287                        recipient_pubkey,
288                        zapped_event,
289                        millisatoshis,
290                        relays,
291                        content,
292                    )
293                    .await
294            }
295        }
296    }
297
298    /// Decrypt the contents of an event
299    pub async fn decrypt_event_contents(&self, event: &Event) -> Result<String, Error> {
300        match self {
301            Self::None => Err(Error::NoPublicKey),
302            Self::Public(_) => Err(Error::NoPrivateKey),
303            Self::Private(arcsigner) => arcsigner.decrypt_event_contents(event).await,
304            #[cfg(feature = "nip46")]
305            Self::Remote(bunkerclient) => bunkerclient.decrypt_event_contents(event).await,
306        }
307    }
308
309    /// If a gift wrap event, unwrap and return the inner Rumor
310    pub async fn unwrap_giftwrap(&self, event: &Event) -> Result<Rumor, Error> {
311        match self {
312            Self::None => Err(Error::NoPublicKey),
313            Self::Public(_) => Err(Error::NoPrivateKey),
314            Self::Private(arcsigner) => arcsigner.unwrap_giftwrap(event).await,
315            #[cfg(feature = "nip46")]
316            Self::Remote(bunkerclient) => bunkerclient.unwrap_giftwrap(event).await,
317        }
318    }
319
320    /// Generate delegation signature
321    pub async fn generate_delegation_signature(
322        &self,
323        delegated_pubkey: PublicKey,
324        delegation_conditions: &DelegationConditions,
325    ) -> Result<Signature, Error> {
326        match self {
327            Self::None => Err(Error::NoPublicKey),
328            Self::Public(_) => Err(Error::NoPrivateKey),
329            Self::Private(arcsigner) => {
330                arcsigner
331                    .generate_delegation_signature(delegated_pubkey, delegation_conditions)
332                    .await
333            }
334            #[cfg(feature = "nip46")]
335            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
336        }
337    }
338
339    /// Giftwrap an event
340    pub async fn giftwrap(&self, input: PreEvent, pubkey: PublicKey) -> Result<Event, Error> {
341        match self {
342            Self::None => Err(Error::NoPublicKey),
343            Self::Public(_) => Err(Error::NoPrivateKey),
344            Self::Private(arcsigner) => arcsigner.giftwrap(input, pubkey).await,
345            #[cfg(feature = "nip46")]
346            Self::Remote(bunkerclient) => bunkerclient.giftwrap(input, pubkey).await,
347        }
348    }
349
350    /// Sign an event
351    pub async fn sign_event(&self, input: PreEvent) -> Result<Event, Error> {
352        match self {
353            Self::None => Err(Error::NoPublicKey),
354            Self::Public(_) => Err(Error::NoPrivateKey),
355            Self::Private(arcsigner) => arcsigner.sign_event(input).await,
356            #[cfg(feature = "nip46")]
357            Self::Remote(bunkerclient) => bunkerclient.sign_event(input).await,
358        }
359    }
360
361    /// Sign an event with Proof-of-Work
362    pub async fn sign_event_with_pow(
363        &self,
364        input: PreEvent,
365        zero_bits: u8,
366        work_sender: Option<Sender<u8>>,
367    ) -> Result<Event, Error> {
368        match self {
369            Self::None => Err(Error::NoPublicKey),
370            Self::Public(_) => Err(Error::NoPrivateKey),
371            Self::Private(arcsigner) => {
372                arcsigner
373                    .sign_event_with_pow(input, zero_bits, work_sender)
374                    .await
375            }
376            #[cfg(feature = "nip46")]
377            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
378        }
379    }
380
381    /// Verify delegation signature
382    pub fn verify_delegation_signature(
383        &self,
384        delegated_pubkey: PublicKey,
385        delegation_conditions: &DelegationConditions,
386        signature: &Signature,
387    ) -> Result<(), Error> {
388        match self {
389            Self::None => Err(Error::NoPublicKey),
390            Self::Public(_) => Err(Error::NoPrivateKey),
391            Self::Private(arcsigner) => arcsigner.verify_delegation_signature(
392                delegated_pubkey,
393                delegation_conditions,
394                signature,
395            ),
396            #[cfg(feature = "nip46")]
397            Self::Remote(_bunkerclient) => Err(Error::NoPrivateKey),
398        }
399    }
400}