use alloc::string::String;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::str::{self, FromStr};
use secp256k1::{Secp256k1, Signing, XOnlyPublicKey};
use serde::{Deserialize, Deserializer, Serialize};
use super::{Error, SecretKey};
use crate::nips::nip19::{FromBech32, PREFIX_BECH32_PROFILE, PREFIX_BECH32_PUBLIC_KEY};
use crate::nips::nip21::{FromNostrUri, SCHEME_WITH_COLON};
#[derive(Clone, Copy)]
pub struct PublicKey {
buf: [u8; 32],
}
impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PublicKey({})", self.to_hex())
}
}
impl PartialEq for PublicKey {
fn eq(&self, other: &Self) -> bool {
self.buf == other.buf
}
}
impl Eq for PublicKey {}
impl PartialOrd for PublicKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PublicKey {
fn cmp(&self, other: &Self) -> Ordering {
self.buf.cmp(&other.buf)
}
}
impl Hash for PublicKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.buf.hash(state);
}
}
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_hex())
}
}
impl From<XOnlyPublicKey> for PublicKey {
fn from(inner: XOnlyPublicKey) -> Self {
Self {
buf: inner.serialize(),
}
}
}
impl PublicKey {
pub const LEN: usize = 32;
#[inline]
pub const fn from_byte_array(bytes: [u8; Self::LEN]) -> Self {
Self { buf: bytes }
}
pub fn parse(public_key: &str) -> Result<Self, Error> {
if public_key.starts_with(PREFIX_BECH32_PUBLIC_KEY)
|| public_key.starts_with(PREFIX_BECH32_PROFILE)
{
Self::from_bech32(public_key).map_err(|_| Error::InvalidPublicKey)
} else if public_key.starts_with(SCHEME_WITH_COLON) {
Self::from_nostr_uri(public_key).map_err(|_| Error::InvalidPublicKey)
} else {
Self::from_hex(public_key).map_err(|_| Error::InvalidPublicKey)
}
}
pub fn from_hex(hex: &str) -> Result<Self, Error> {
let mut bytes: [u8; Self::LEN] = [0u8; Self::LEN];
faster_hex::hex_decode(hex.as_bytes(), &mut bytes)?;
Ok(Self::from_byte_array(bytes))
}
pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {
if slice.len() != Self::LEN {
return Err(Error::InvalidPublicKey);
}
let mut bytes: [u8; Self::LEN] = [0u8; Self::LEN];
bytes.copy_from_slice(slice);
Ok(Self::from_byte_array(bytes))
}
pub fn from_secret_key<C>(secp: &Secp256k1<C>, secret_key: &SecretKey) -> Self
where
C: Signing,
{
let pk: secp256k1::PublicKey = secp256k1::PublicKey::from_secret_key(secp, secret_key);
let (xonly, _): (XOnlyPublicKey, _) = pk.x_only_public_key();
Self::from(xonly)
}
#[inline]
pub fn as_bytes(&self) -> &[u8; Self::LEN] {
&self.buf
}
#[inline]
pub fn to_bytes(self) -> [u8; Self::LEN] {
self.buf
}
#[inline]
pub fn to_hex(&self) -> String {
unsafe { String::from_utf8_unchecked(self.to_hex_byte_array().to_vec()) }
}
#[inline]
pub fn to_hex_byte_array(&self) -> [u8; Self::LEN * 2] {
let mut buf = [0u8; Self::LEN * 2];
faster_hex::hex_encode(self.as_bytes(), &mut buf).expect("Buffer size is correct");
buf
}
pub fn xonly(&self) -> Result<XOnlyPublicKey, Error> {
Ok(XOnlyPublicKey::from_slice(self.as_bytes())?)
}
}
impl FromStr for PublicKey {
type Err = Error;
#[inline]
fn from_str(public_key: &str) -> Result<Self, Self::Err> {
Self::parse(public_key)
}
}
impl From<PublicKey> for String {
fn from(public_key: PublicKey) -> Self {
public_key.to_hex()
}
}
impl Serialize for PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bytes: [u8; Self::LEN * 2] = self.to_hex_byte_array();
let encoded: &str = unsafe { str::from_utf8_unchecked(&bytes) };
serializer.serialize_str(encoded)
}
}
impl<'de> Deserialize<'de> for PublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let public_key: String = String::deserialize(deserializer)?;
Self::parse(&public_key).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_public_key_parse() {
let public_key = PublicKey::parse(
"nostr:npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy",
)
.unwrap();
assert_eq!(
public_key.to_hex(),
"aa4fc8665f5696e33db7e1a572e3b0f5b3d615837b0f362dcb1c8068b098c7b4"
);
}
#[test]
fn test_as_xonly() {
let hex_pk: &str = "aa4fc8665f5696e33db7e1a572e3b0f5b3d615837b0f362dcb1c8068b098c7b4";
let public_key = PublicKey::from_hex(hex_pk).unwrap();
let expected = XOnlyPublicKey::from_str(hex_pk).unwrap();
let xonly = public_key.xonly().unwrap();
assert_eq!(&xonly, &expected);
let public_key = PublicKey::from(expected);
let xonly = public_key.xonly().unwrap();
assert_eq!(&xonly, &expected);
}
}
#[cfg(bench)]
mod benches {
use test::{Bencher, black_box};
use super::*;
use crate::nips::nip19::ToBech32;
const NIP21_URI: &str = "nostr:npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy";
const HEX: &str = "aa4fc8665f5696e33db7e1a572e3b0f5b3d615837b0f362dcb1c8068b098c7b4";
const BECH32: &str = "npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy";
#[bench]
pub fn parse_public_key_nip21_uri(bh: &mut Bencher) {
bh.iter(|| {
black_box(PublicKey::parse(NIP21_URI)).unwrap();
});
}
#[bench]
pub fn parse_public_key_hex(bh: &mut Bencher) {
bh.iter(|| {
black_box(PublicKey::parse(HEX)).unwrap();
});
}
#[bench]
pub fn public_key_from_hex(bh: &mut Bencher) {
bh.iter(|| {
black_box(PublicKey::from_hex(HEX)).unwrap();
});
}
#[bench]
pub fn parse_public_key_bech32(bh: &mut Bencher) {
bh.iter(|| {
black_box(PublicKey::parse(BECH32)).unwrap();
});
}
#[bench]
pub fn public_key_from_bech32(bh: &mut Bencher) {
bh.iter(|| {
black_box(PublicKey::from_bech32(BECH32)).unwrap();
});
}
#[bench]
pub fn public_key_to_hex(bh: &mut Bencher) {
let public_key = PublicKey::from_hex(HEX).unwrap();
bh.iter(|| {
black_box(public_key.to_bech32()).unwrap();
});
}
#[bench]
pub fn public_key_to_bech32(bh: &mut Bencher) {
let public_key = PublicKey::from_hex(HEX).unwrap();
bh.iter(|| {
black_box(public_key.to_bech32()).unwrap();
});
}
}