gossip/src/signer.rs

284 lines
9.5 KiB
Rust
Raw Normal View History

2023-04-24 06:27:56 +00:00
use std::sync::mpsc::Sender;
use crate::error::{Error, ErrorKind};
use crate::globals::GLOBALS;
2023-07-06 02:21:13 +00:00
use nostr_types::{
2023-08-21 20:17:27 +00:00
EncryptedPrivateKey, Event, EventKind, Id, KeySecurity, PreEvent, PrivateKey, PublicKey, Rumor,
2023-07-06 02:21:13 +00:00
};
use parking_lot::RwLock;
use tokio::task;
2022-12-27 06:45:57 +00:00
#[derive(Default)]
2023-01-05 08:43:16 +00:00
pub struct Signer {
public: RwLock<Option<PublicKey>>,
encrypted: RwLock<Option<EncryptedPrivateKey>>,
private: RwLock<Option<PrivateKey>>,
2022-12-27 06:45:57 +00:00
}
impl Signer {
pub fn load_from_settings(&self) -> Result<(), Error> {
2023-08-22 22:13:59 +00:00
if self.public.read().is_none() {
*self.public.write() = GLOBALS.storage.read_setting_public_key();
}
if self.encrypted.read().is_none() {
let epk = GLOBALS.storage.read_encrypted_private_key()?;
*self.encrypted.write() = epk;
}
Ok(())
2023-01-05 08:43:16 +00:00
}
2023-08-18 22:32:56 +00:00
pub async fn save(&self) -> Result<(), Error> {
GLOBALS
.storage
.write_setting_public_key(&self.public.read(), None)?;
let epk = self.encrypted.read().clone();
GLOBALS.storage.write_encrypted_private_key(&epk, None)?;
Ok(())
2023-01-05 08:43:16 +00:00
}
pub fn set_public_key(&self, pk: PublicKey) {
if self.private.read().is_some() {
2023-06-24 23:01:55 +00:00
GLOBALS
.status_queue
.write()
.write("Ignored setting of public key (private key supercedes)".to_string());
2023-01-05 08:43:16 +00:00
} else {
*self.public.write() = Some(pk);
2023-01-05 08:43:16 +00:00
}
}
pub fn clear_public_key(&self) {
if self.private.read().is_some() {
2023-06-24 23:01:55 +00:00
GLOBALS
.status_queue
.write()
.write("Ignored clearing of public key (private key supercedes)".to_string());
} else {
*self.public.write() = None;
}
}
pub fn set_encrypted_private_key(&self, epk: EncryptedPrivateKey) {
if self.private.read().is_some() && self.encrypted.read().is_some() {
2023-01-05 08:43:16 +00:00
// ignore, epk supercedes
} else {
*self.encrypted.write() = Some(epk);
2023-01-05 08:43:16 +00:00
}
}
pub fn set_private_key(&self, pk: PrivateKey, pass: &str) -> Result<(), Error> {
*self.encrypted.write() =
Some(pk.export_encrypted(pass, GLOBALS.storage.read_setting_log_n())?);
*self.public.write() = Some(pk.public_key());
*self.private.write() = Some(pk);
2023-01-05 08:43:16 +00:00
Ok(())
2022-12-27 06:45:57 +00:00
}
pub fn unlock_encrypted_private_key(&self, pass: &str) -> Result<(), Error> {
if self.private.read().is_some() {
2023-01-05 08:43:16 +00:00
// ignore, already unlocked
Ok(())
} else if let Some(epk) = &*self.encrypted.read() {
*self.private.write() = Some(epk.decrypt(pass)?);
if let Some(private) = &*self.private.read() {
2023-01-20 05:16:04 +00:00
// it will be
// If older version, re-encrypt with new version at default 2^18 rounds
if epk.version()? < 2 {
2023-08-11 06:14:25 +00:00
*self.encrypted.write() =
Some(private.export_encrypted(pass, GLOBALS.storage.read_setting_log_n())?);
// and eventually save
task::spawn(async move {
2023-08-18 22:32:56 +00:00
if let Err(e) = GLOBALS.signer.save().await {
tracing::error!("{}", e);
}
});
}
2023-01-20 05:16:04 +00:00
if self.public.read().is_none() {
*self.public.write() = Some(private.public_key());
2023-01-20 05:16:04 +00:00
}
// Invalidate DMs so they rerender decrypted
2023-07-06 02:21:13 +00:00
let dms: Vec<Id> = GLOBALS
.storage
.find_events(
2023-08-21 20:17:27 +00:00
&[EventKind::EncryptedDirectMessage, EventKind::GiftWrap],
2023-07-26 07:43:31 +00:00
&[],
None,
|_| true,
false,
)?
2023-07-06 02:21:13 +00:00
.iter()
.map(|e| e.id)
.collect();
GLOBALS.ui_notes_to_invalidate.write().extend(dms);
}
2022-12-27 06:45:57 +00:00
Ok(())
} else {
Err((ErrorKind::NoPrivateKey, file!(), line!()).into())
2022-12-27 06:45:57 +00:00
}
}
pub fn change_passphrase(&self, old: &str, new: &str) -> Result<(), Error> {
let maybe_encrypted = self.encrypted.read().to_owned();
match maybe_encrypted {
Some(epk) => {
// Test password
let pk = epk.decrypt(old)?;
let epk = pk.export_encrypted(new, GLOBALS.storage.read_setting_log_n())?;
*self.encrypted.write() = Some(epk);
task::spawn(async move {
2023-08-18 22:32:56 +00:00
if let Err(e) = GLOBALS.signer.save().await {
tracing::error!("{}", e);
}
2023-06-24 23:01:55 +00:00
GLOBALS
.status_queue
.write()
.write("Passphrase changed.".to_owned())
});
Ok(())
}
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
}
}
pub fn generate_private_key(&self, pass: &str) -> Result<(), Error> {
let pk = PrivateKey::generate();
*self.encrypted.write() =
Some(pk.export_encrypted(pass, GLOBALS.storage.read_setting_log_n())?);
*self.public.write() = Some(pk.public_key());
*self.private.write() = Some(pk);
2023-01-05 08:43:16 +00:00
Ok(())
}
2022-12-27 06:45:57 +00:00
pub fn is_loaded(&self) -> bool {
self.encrypted.read().is_some() || self.private.read().is_some()
2022-12-27 06:45:57 +00:00
}
pub fn is_ready(&self) -> bool {
self.private.read().is_some()
2022-12-27 06:45:57 +00:00
}
pub fn public_key(&self) -> Option<PublicKey> {
*self.public.read()
2022-12-27 06:45:57 +00:00
}
pub fn encrypted_private_key(&self) -> Option<EncryptedPrivateKey> {
self.encrypted.read().clone()
}
2022-12-27 06:45:57 +00:00
pub fn key_security(&self) -> Option<KeySecurity> {
self.private.read().as_ref().map(|pk| pk.key_security())
2022-12-27 06:45:57 +00:00
}
2023-04-24 06:27:56 +00:00
pub fn sign_preevent(
&self,
preevent: PreEvent,
pow: Option<u8>,
work_sender: Option<Sender<u8>>,
) -> Result<Event, Error> {
match &*self.private.read() {
2023-01-05 08:43:16 +00:00
Some(pk) => match pow {
2023-04-24 06:27:56 +00:00
Some(pow) => Ok(Event::new_with_pow(preevent, pk, pow, work_sender)?),
None => Ok(Event::new(preevent, pk)?),
},
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
2022-12-27 06:45:57 +00:00
}
}
pub fn export_private_key_bech32(&self, pass: &str) -> Result<String, Error> {
let maybe_encrypted = self.encrypted.read().to_owned();
match maybe_encrypted {
2023-01-05 08:43:16 +00:00
Some(epk) => {
// Test password
let mut pk = epk.decrypt(pass)?;
2023-01-05 08:43:16 +00:00
let output = pk.as_bech32_string();
// We have to regenerate encrypted private key because it may have fallen from
2023-01-05 08:43:16 +00:00
// medium to weak security. And then we need to save that
let epk = pk.export_encrypted(pass, GLOBALS.storage.read_setting_log_n())?;
*self.encrypted.write() = Some(epk);
*self.private.write() = Some(pk);
task::spawn(async move {
2023-08-18 22:32:56 +00:00
if let Err(e) = GLOBALS.signer.save().await {
tracing::error!("{}", e);
}
});
Ok(output)
}
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
}
}
pub fn export_private_key_hex(&self, pass: &str) -> Result<String, Error> {
let maybe_encrypted = self.encrypted.read().to_owned();
match maybe_encrypted {
2023-01-05 08:43:16 +00:00
Some(epk) => {
// Test password
let mut pk = epk.decrypt(pass)?;
2023-01-05 08:43:16 +00:00
let output = pk.as_hex_string();
// We have to regenerate encrypted private key because it may have fallen from
2023-01-05 08:43:16 +00:00
// medium to weak security. And then we need to save that
let epk = pk.export_encrypted(pass, GLOBALS.storage.read_setting_log_n())?;
*self.encrypted.write() = Some(epk);
*self.private.write() = Some(pk);
task::spawn(async move {
2023-08-18 22:32:56 +00:00
if let Err(e) = GLOBALS.signer.save().await {
tracing::error!("{}", e);
}
});
Ok(output)
}
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
}
}
2023-01-04 03:35:54 +00:00
pub fn delete_identity(&self) {
2023-02-03 22:38:02 +00:00
*self.private.write() = None;
*self.encrypted.write() = None;
*self.public.write() = None;
task::spawn(async move {
2023-08-18 22:32:56 +00:00
if let Err(e) = GLOBALS.signer.save().await {
2023-02-03 22:38:02 +00:00
tracing::error!("{}", e);
2023-01-04 03:35:54 +00:00
}
2023-02-03 22:38:02 +00:00
});
2023-01-04 03:35:54 +00:00
}
pub fn decrypt_message(&self, event: &Event) -> Result<String, Error> {
match &*self.private.read() {
Some(private) => Ok(event.decrypted_contents(private)?),
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
}
}
2023-08-21 20:17:27 +00:00
pub fn unwrap_giftwrap(&self, event: &Event) -> Result<Rumor, Error> {
match &*self.private.read() {
Some(private) => Ok(event.giftwrap_unwrap(private, false)?),
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
}
}
2023-08-22 21:41:54 +00:00
pub fn nip44_decrypt(
&self,
other: &PublicKey,
ciphertext: &str,
padded: bool,
) -> Result<Vec<u8>, Error> {
match &*self.private.read() {
Some(private) => Ok(private.nip44_decrypt(other, ciphertext, padded)?),
_ => Err((ErrorKind::NoPrivateKey, file!(), line!()).into()),
}
}
2022-12-27 06:45:57 +00:00
}