Skip to content

Commit

Permalink
nostr: update Keys struct
Browse files Browse the repository at this point in the history
* Impl custom `Debug`, `PartialEq` and `Eq`
* Impl `PartialOrd`, `Ord` and `Hash`
* Change `Keys::secret_key` and `Keys::sign_schnorr` methods fingerprint
* Deprecate `Keys::generate_without_keypair`
* Remove `Keys::from_public_key`

Signed-off-by: Yuki Kishimoto <[email protected]>
  • Loading branch information
yukibtc committed Aug 23, 2024
1 parent a0a7b1c commit fa6afe5
Show file tree
Hide file tree
Showing 24 changed files with 159 additions and 160 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
* nostr: deprecate `Event::is_*` kind related methods ([Yuki Kishimoto])
* nostr: change `TryIntoUrl::Err` to `Infallible` for `Url` ([Yuki Kishimoto])
* nostr: change `Event::verify_id` and `Event::verify_signature` fingerprint ([Yuki Kishimoto])
* nostr: impl custom `Debug`, `PartialEq` and `Eq` for `Keys` ([Yuki Kishimoto])
* nostr: impl `PartialOrd`, `Ord` and `Hash` for `Keys` ([Yuki Kishimoto])
* nostr: change `Keys::secret_key` and `Keys::sign_schnorr` methods fingerprint ([Yuki Kishimoto])
* nostr: deprecate `Keys::generate_without_keypair` ([Yuki Kishimoto])
* nostr: change NIP-26 functions fingerprint ([Yuki Kishimoto])
* signer: update NIP-04 and NIP-44 methods signature ([Yuki Kishimoto])
* webln: bump `webln` to `v0.3` ([Yuki Kishimoto])
* sdk: bump `lnurl-pay` to `v0.6` ([Yuki Kishimoto])
Expand All @@ -59,6 +64,8 @@
### Removed

* nostr: remove `bech32` from the public API ([Yuki Kishimoto])
* nostr: remove `Keys::from_public_key` ([Yuki Kishimoto])
* js(nostr): remove `Keys::vanity` ([Yuki Kishimoto])

## [v0.34.0]

Expand Down
13 changes: 3 additions & 10 deletions bindings/nostr-ffi/src/key/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,6 @@ impl Keys {
})
}

#[uniffi::constructor]
pub fn from_public_key(public_key: &PublicKey) -> Self {
Self {
inner: key::Keys::from_public_key(**public_key),
}
}

/// Generate random `Keys`
#[uniffi::constructor]
pub fn generate() -> Self {
Expand Down Expand Up @@ -95,12 +88,12 @@ impl Keys {
self.inner.public_key().into()
}

pub fn secret_key(&self) -> Result<SecretKey> {
Ok(self.inner.secret_key()?.clone().into())
pub fn secret_key(&self) -> SecretKey {
self.inner.secret_key().clone().into()
}

pub fn sign_schnorr(&self, message: &[u8]) -> Result<String> {
let message: Message = Message::from_digest_slice(message)?;
Ok(self.inner.sign_schnorr(&message)?.to_string())
Ok(self.inner.sign_schnorr(&message).to_string())
}
}
4 changes: 2 additions & 2 deletions bindings/nostr-ffi/src/nips/nip26.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn create_delegation_tag(
conditions: &str,
) -> Result<String> {
let conditions = Conditions::from_str(conditions)?;
let tag = DelegationTag::new(delegator_keys.deref(), delegatee_pubkey.deref(), conditions)?;
let tag = DelegationTag::new(delegator_keys.deref(), delegatee_pubkey.deref(), conditions);
Ok(tag.to_string())
}

Expand Down Expand Up @@ -57,7 +57,7 @@ pub fn sign_delegation(
) -> Result<String> {
let conditions = Conditions::from_str(conditions)?;
Ok(
nip26::sign_delegation(delegator_keys.deref(), delegatee_pk.deref(), &conditions)?
nip26::sign_delegation(delegator_keys.deref(), delegatee_pk.deref(), &conditions)
.to_string(),
)
}
Expand Down
18 changes: 2 additions & 16 deletions bindings/nostr-js/src/key/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,27 +50,13 @@ impl JsKeys {
})
}

/// Initialize with public key only (no secret key).
#[wasm_bindgen(js_name = fromPublicKey)]
pub fn from_public_key(public_key: &JsPublicKey) -> JsKeys {
Self {
inner: Keys::from_public_key(**public_key),
}
}

/// Generate new random keys
pub fn generate() -> JsKeys {
Self {
inner: Keys::generate(),
}
}

pub fn vanity(prefixes: Vec<String>, bech32: bool, num_cores: u8) -> Result<JsKeys> {
Ok(Self {
inner: Keys::vanity(prefixes, bech32, num_cores as usize).map_err(into_err)?,
})
}

/// Derive keys from BIP-39 mnemonics (ENGLISH wordlist).
///
/// <https://github.com/nostr-protocol/nips/blob/master/06.md>
Expand Down Expand Up @@ -102,7 +88,7 @@ impl JsKeys {

/// Get secret key
#[wasm_bindgen(js_name = secretKey, getter)]
pub fn secret_key(&self) -> Result<JsSecretKey> {
Ok(self.inner.secret_key().cloned().map_err(into_err)?.into())
pub fn secret_key(&self) -> JsSecretKey {
self.inner.secret_key().clone().into()
}
}
6 changes: 2 additions & 4 deletions bindings/nostr-js/src/nips/nip26.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ pub fn create_delegation_tag(
conditions: &str,
) -> Result<String> {
let conditions = Conditions::from_str(conditions).map_err(into_err)?;
let tag = DelegationTag::new(delegator_keys.deref(), delegatee_pubkey.deref(), conditions)
.map_err(into_err)?;
let tag = DelegationTag::new(delegator_keys.deref(), delegatee_pubkey.deref(), conditions);
Ok(tag.to_string())
}

Expand Down Expand Up @@ -61,8 +60,7 @@ pub fn sign_delegation(
) -> Result<String> {
let conditions = Conditions::from_str(conditions).map_err(into_err)?;
let signature: Signature =
nip26::sign_delegation(keys.deref(), delegatee_pk.deref(), &conditions)
.map_err(into_err)?;
nip26::sign_delegation(keys.deref(), delegatee_pk.deref(), &conditions);
Ok(signature.to_string())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/nostr-sdk/examples/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ async fn main() -> Result<()> {
// Check kind
if event.kind == Kind::EncryptedDirectMessage {
if let Ok(msg) =
nip04::decrypt(keys.secret_key()?, &event.pubkey, &event.content)
nip04::decrypt(keys.secret_key(), &event.pubkey, &event.content)
{
println!("DM: {msg}");
} else {
Expand Down
8 changes: 4 additions & 4 deletions crates/nostr-signer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ impl NostrSigner {
{
let content: &[u8] = content.as_ref();
match self {
Self::Keys(keys) => Ok(nip04::encrypt(keys.secret_key()?, public_key, content)?),
Self::Keys(keys) => Ok(nip04::encrypt(keys.secret_key(), public_key, content)?),
#[cfg(all(feature = "nip07", target_arch = "wasm32"))]
Self::NIP07(signer) => Ok(signer.nip04_encrypt(public_key, content).await?),
#[cfg(feature = "nip46")]
Expand All @@ -181,7 +181,7 @@ impl NostrSigner {
let encrypted_content: &str = encrypted_content.as_ref();
match self {
Self::Keys(keys) => Ok(nip04::decrypt(
keys.secret_key()?,
keys.secret_key(),
public_key,
encrypted_content,
)?),
Expand All @@ -205,7 +205,7 @@ impl NostrSigner {
let content: &[u8] = content.as_ref();
match self {
Self::Keys(keys) => Ok(nip44::encrypt(
keys.secret_key()?,
keys.secret_key(),
public_key,
content,
nip44::Version::default(),
Expand All @@ -229,7 +229,7 @@ impl NostrSigner {
{
let payload: &[u8] = payload.as_ref();
match self {
Self::Keys(keys) => Ok(nip44::decrypt(keys.secret_key()?, public_key, payload)?),
Self::Keys(keys) => Ok(nip44::decrypt(keys.secret_key(), public_key, payload)?),
#[cfg(all(feature = "nip07", target_arch = "wasm32"))]
Self::NIP07(signer) => Ok(signer.nip44_decrypt(public_key, payload).await?),
#[cfg(feature = "nip46")]
Expand Down
6 changes: 3 additions & 3 deletions crates/nostr-signer/src/nip46/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl Nip46Signer {
}

async fn send_request(&self, req: Request) -> Result<ResponseResult, Error> {
let secret_key: &SecretKey = self.app_keys.secret_key()?;
let secret_key: &SecretKey = self.app_keys.secret_key();
let signer_public_key: PublicKey = self.signer_public_key();

// Convert request to event
Expand Down Expand Up @@ -275,13 +275,13 @@ async fn get_signer_public_key(
mut notifications: Receiver<RelayPoolNotification>,
timeout: Duration,
) -> Result<PublicKey, Error> {
let secret_key = app_keys.secret_key()?;
time::timeout(Some(timeout), async {
while let Ok(notification) = notifications.recv().await {
if let RelayPoolNotification::Event { event, .. } = notification {
if event.kind == Kind::NostrConnect {
// Decrypt content
let msg: String = nip04::decrypt(secret_key, &event.pubkey, event.content)?;
let msg: String =
nip04::decrypt(app_keys.secret_key(), &event.pubkey, event.content)?;

tracing::debug!("Received Nostr Connect message: '{msg}'");

Expand Down
10 changes: 5 additions & 5 deletions crates/nostr-signer/src/nip46/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ impl NostrConnectRemoteSigner {
if let RelayPoolNotification::Event { event, .. } = notification {
if event.kind == Kind::NostrConnect {
if let Ok(msg) =
nip04::decrypt(self.keys.secret_key()?, &event.pubkey, event.content)
nip04::decrypt(self.keys.secret_key(), &event.pubkey, event.content)
{
tracing::debug!("New Nostr Connect message received: {msg}");

Expand Down Expand Up @@ -160,7 +160,7 @@ impl NostrConnectRemoteSigner {
}
Request::Nip04Encrypt { public_key, text } => {
match nip04::encrypt(
self.keys.secret_key()?,
self.keys.secret_key(),
&public_key,
text,
) {
Expand All @@ -178,7 +178,7 @@ impl NostrConnectRemoteSigner {
ciphertext,
} => {
match nip04::decrypt(
self.keys.secret_key()?,
self.keys.secret_key(),
&public_key,
ciphertext,
) {
Expand All @@ -193,7 +193,7 @@ impl NostrConnectRemoteSigner {
}
Request::Nip44Encrypt { public_key, text } => {
match nip44::encrypt(
self.keys.secret_key()?,
self.keys.secret_key(),
&public_key,
text,
nip44::Version::default(),
Expand All @@ -212,7 +212,7 @@ impl NostrConnectRemoteSigner {
ciphertext,
} => {
match nip44::decrypt(
self.keys.secret_key()?,
self.keys.secret_key(),
&public_key,
ciphertext,
) {
Expand Down
4 changes: 2 additions & 2 deletions crates/nostr/examples/embedded/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@ fn main() -> ! {
fn print_keys(keys: &Keys) {
hprintln!(
"- Secret Key (hex): {}",
keys.secret_key().unwrap().to_secret_hex()
keys.secret_key().to_secret_hex()
)
.unwrap();
hprintln!("- Public Key (hex): {}", keys.public_key()).unwrap();
hprintln!(
"- Secret Key (bech32): {}",
keys.secret_key().unwrap().to_bech32().unwrap()
keys.secret_key().to_bech32().unwrap()
)
.unwrap();
hprintln!(
Expand Down
9 changes: 2 additions & 7 deletions crates/nostr/examples/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ fn main() -> Result<()> {
// Random keys
let keys = Keys::generate();
let public_key = keys.public_key();
let secret_key = keys.secret_key()?;
let secret_key = keys.secret_key();

println!("Public key: {}", public_key);
println!("Public key bech32: {}", public_key.to_bech32()?);
println!("Secret key: {}", keys.secret_key()?.to_secret_hex());
println!("Secret key: {}", secret_key.to_secret_hex());
println!("Secret key bech32: {}", secret_key.to_bech32()?);

// Bech32 keys
Expand All @@ -21,10 +21,5 @@ fn main() -> Result<()> {
let keys = Keys::new(secret_key);
println!("Public key: {}", keys.public_key());

let public_key =
PublicKey::from_bech32("npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy")?;
let keys = Keys::from_public_key(public_key);
println!("Public key: {}", keys.public_key());

Ok(())
}
2 changes: 1 addition & 1 deletion crates/nostr/examples/nip06.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const MNEMONIC_PHRASE: &str = "equal dragon fabric refuse stable cherry smoke al

fn main() -> Result<()> {
let keys = Keys::from_mnemonic(MNEMONIC_PHRASE, Some("mypassphrase"))?;
println!("{}", keys.secret_key()?.to_bech32()?);
println!("{}", keys.secret_key().to_bech32()?);

Ok(())
}
2 changes: 1 addition & 1 deletion crates/nostr/examples/vanity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use nostr::prelude::*;
fn main() -> Result<()> {
let num_cores = num_cpus::get();
let keys = Keys::vanity(vec!["0000", "yuk", "yuk0"], true, num_cores)?;
println!("Secret key: {}", keys.secret_key()?.to_bech32()?);
println!("Secret key: {}", keys.secret_key().to_bech32()?);
println!("Public key: {}", keys.public_key().to_bech32()?);
Ok(())
}
6 changes: 3 additions & 3 deletions crates/nostr/src/event/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ impl EventBuilder {
) -> Result<Self, Error> {
Ok(Self::new(
Kind::NostrConnect,
nip04::encrypt(sender_keys.secret_key()?, &receiver_pubkey, msg.as_json())?,
nip04::encrypt(sender_keys.secret_key(), &receiver_pubkey, msg.as_json())?,
[Tag::public_key(receiver_pubkey)],
))
}
Expand Down Expand Up @@ -1288,7 +1288,7 @@ impl EventBuilder {

// Encrypt content
let content: String = nip44::encrypt(
sender_keys.secret_key()?,
sender_keys.secret_key(),
receiver_pubkey,
rumor.as_json(),
Version::default(),
Expand Down Expand Up @@ -1317,7 +1317,7 @@ impl EventBuilder {

let keys: Keys = Keys::generate();
let content: String = nip44::encrypt(
keys.secret_key()?,
keys.secret_key(),
receiver,
seal.as_json(),
Version::default(),
Expand Down
4 changes: 2 additions & 2 deletions crates/nostr/src/event/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,7 @@ mod benches {
let json = r#"{"content":"uRuvYr585B80L6rSJiHocw==?iv=oh6LVqdsYYol3JfFnXTbPA==","created_at":1640839235,"id":"2be17aa3031bdcb006f0fce80c146dea9c1c0268b0af2398bb673365c6444d45","kind":4,"pubkey":"f86c44a2de95d9149b51c6a29afeabba264c18e2fa7c49de93424a0c56947785","sig":"a5d9290ef9659083c490b303eb7ee41356d8778ff19f2f91776c8dc4443388a64ffcf336e61af4c25c05ac3ae952d1ced889ed655b67790891222aaa15b99fdd","tags":[["p","13adc511de7e1cfcf1c6b7f6365fb5a03442d7bcacf565ea57fa7770912c023d"]]}"#;
let event = Event::from_json(json).unwrap();
bh.iter(|| {
black_box(event.verify_id()).unwrap();
black_box(event.verify_id());
});
}

Expand All @@ -890,7 +890,7 @@ mod benches {
let json = r#"{"content":"uRuvYr585B80L6rSJiHocw==?iv=oh6LVqdsYYol3JfFnXTbPA==","created_at":1640839235,"id":"2be17aa3031bdcb006f0fce80c146dea9c1c0268b0af2398bb673365c6444d45","kind":4,"pubkey":"f86c44a2de95d9149b51c6a29afeabba264c18e2fa7c49de93424a0c56947785","sig":"a5d9290ef9659083c490b303eb7ee41356d8778ff19f2f91776c8dc4443388a64ffcf336e61af4c25c05ac3ae952d1ced889ed655b67790891222aaa15b99fdd","tags":[["p","13adc511de7e1cfcf1c6b7f6365fb5a03442d7bcacf565ea57fa7770912c023d"]]}"#;
let event = Event::from_json(json).unwrap();
bh.iter(|| {
black_box(event.verify_signature()).unwrap();
black_box(event.verify_signature());
});
}
}
2 changes: 1 addition & 1 deletion crates/nostr/src/event/unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl UnsignedEvent {
let verify_id: bool = self.id.is_some();
let id: EventId = self.id.unwrap_or_else(|| self.compute_id());
let message: Message = Message::from_digest(id.to_bytes());
let sig: Signature = keys.sign_schnorr_with_ctx(secp, &message, rng)?;
let sig: Signature = keys.sign_schnorr_with_ctx(secp, &message, rng);
self.internal_add_signature(secp, id, sig, verify_id, false)
}

Expand Down
Loading

0 comments on commit fa6afe5

Please sign in to comment.