#[cfg(feature = "pubkey-str")]
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
use core::str::FromStr;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "solana-pubkey-convert-v2")]
use solana_pubkey_v2::Pubkey as SolanaPubkeyV2;
pub const PUBKEY_BYTES: usize = 32;
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
pub struct Pubkey(
#[cfg_attr(feature = "serde", serde(with = "serde_bytes"))] pub(crate) [u8; PUBKEY_BYTES],
);
impl Hash for Pubkey {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.as_array())
}
}
impl Pubkey {
pub const fn new_from_array(pubkey_array: [u8; PUBKEY_BYTES]) -> Self {
Self(pubkey_array)
}
#[cfg(feature = "pubkey-fromstr-const")]
pub const fn from_str_const(s: &str) -> Self {
let id_bytes = five8_const::decode_32_const(s);
Self::new_from_array(id_bytes)
}
pub const fn to_bytes(self) -> [u8; PUBKEY_BYTES] {
self.0
}
pub const fn as_array(&self) -> &[u8; PUBKEY_BYTES] {
&self.0
}
}
#[cfg(feature = "pubkey-fromstr-const")]
#[macro_export]
macro_rules! pubkey {
($input:literal) => {
$crate::common::Pubkey::from_str_const($input)
};
}
impl From<[u8; PUBKEY_BYTES]> for Pubkey {
#[inline]
fn from(value: [u8; PUBKEY_BYTES]) -> Self {
Self(value)
}
}
impl TryFrom<&[u8]> for Pubkey {
type Error = std::array::TryFromSliceError;
#[inline]
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
<[u8; PUBKEY_BYTES]>::try_from(value).map(Self::from)
}
}
#[cfg(feature = "solana-pubkey-convert-v2")]
impl From<SolanaPubkeyV2> for Pubkey {
#[inline]
fn from(value: SolanaPubkeyV2) -> Self {
Self(value.to_bytes())
}
}
#[cfg(feature = "solana-pubkey-convert-v2")]
impl From<Pubkey> for SolanaPubkeyV2 {
#[inline]
fn from(value: Pubkey) -> Self {
Self::new_from_array(value.0)
}
}
#[cfg(feature = "solana-address-convert-v1")]
impl From<Pubkey> for solana_address_v1::Address {
fn from(value: Pubkey) -> Self {
Self::new_from_array(value.0)
}
}
#[cfg(feature = "solana-address-convert-v1")]
impl From<solana_address_v1::Address> for Pubkey {
fn from(value: solana_address_v1::Address) -> Self {
Self::new_from_array(value.to_bytes())
}
}
#[cfg(feature = "pubkey-str")]
#[derive(Debug, Clone, Copy, PartialEq, thiserror::Error)]
pub enum DecodeError {
#[error("Invalid base58 character encountered: char number {0}")]
InvalidChar(u8),
#[error("Base58 string too long")]
TooLong,
#[error("Base58 string too short")]
TooShort,
#[error("Largest term greater than 2^32")]
LargestTermTooHigh,
#[error("Decoded output has too many bytes")]
OutputTooLong,
}
#[cfg(feature = "pubkey-str")]
impl From<five8::DecodeError> for DecodeError {
fn from(value: five8::DecodeError) -> Self {
match value {
five8::DecodeError::InvalidChar(c) => Self::InvalidChar(c),
five8::DecodeError::TooLong => Self::TooLong,
five8::DecodeError::TooShort => Self::TooShort,
five8::DecodeError::LargestTermTooHigh => Self::LargestTermTooHigh,
five8::DecodeError::OutputTooLong => Self::OutputTooLong,
}
}
}
#[cfg(feature = "pubkey-str")]
impl From<DecodeError> for five8::DecodeError {
fn from(value: DecodeError) -> Self {
match value {
DecodeError::InvalidChar(c) => Self::InvalidChar(c),
DecodeError::TooLong => Self::TooLong,
DecodeError::TooShort => Self::TooShort,
DecodeError::LargestTermTooHigh => Self::LargestTermTooHigh,
DecodeError::OutputTooLong => Self::OutputTooLong,
}
}
}
#[cfg(feature = "pubkey-str")]
impl FromStr for Pubkey {
type Err = DecodeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut out = [0u8; PUBKEY_BYTES];
five8::decode_32(s, &mut out)?;
Ok(Self::new_from_array(out))
}
}
#[cfg(feature = "pubkey-str")]
impl core::fmt::Display for Pubkey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut buf = [0u8; five8::BASE58_ENCODED_32_MAX_LEN];
let encoded_len = five8::encode_32(self.as_array(), &mut buf);
let as_str = std::str::from_utf8(&buf[..encoded_len as usize])
.expect("base58 string should be valid utf8");
f.write_str(as_str)
}
}
#[cfg(test)]
mod test {
use super::{Pubkey, PUBKEY_BYTES};
use crate::pubkey;
const SOL_ADDR_BYTES: [u8; PUBKEY_BYTES] = [
6, 155, 136, 87, 254, 171, 129, 132, 251, 104, 127, 99, 70, 24, 192, 53, 218, 196, 57, 220,
26, 235, 59, 85, 152, 160, 240, 0, 0, 0, 0, 0,
];
const SOL_ADDR_BASE58: &str = "So11111111111111111111111111111111111111111";
#[test]
fn test_construct() {
let pubkey = Pubkey::new_from_array(SOL_ADDR_BYTES);
assert_eq!(pubkey.as_array().len(), PUBKEY_BYTES);
assert_eq!(pubkey.as_array(), &SOL_ADDR_BYTES);
}
#[cfg(feature = "pubkey-fromstr-const")]
#[test]
fn test_base58_const() {
let expected = Pubkey::new_from_array(SOL_ADDR_BYTES);
let decoded = Pubkey::from_str_const(SOL_ADDR_BASE58);
assert_eq!(decoded, expected);
let decoded_macro = pubkey!("So11111111111111111111111111111111111111111");
assert_eq!(decoded_macro, expected);
}
#[cfg(feature = "pubkey-str")]
#[test]
fn test_from_str() {
use std::str::FromStr;
let expected = Pubkey::new_from_array(SOL_ADDR_BYTES);
let decoded = Pubkey::from_str(SOL_ADDR_BASE58).expect("should decode from base58");
assert_eq!(decoded, expected);
}
#[cfg(feature = "solana-pubkey-convert-v2")]
#[test]
fn test_convert_to_solana_pubkey_v2() {
use solana_pubkey_v2::Pubkey as SolanaPubkey;
let orig = SolanaPubkey::new_from_array(SOL_ADDR_BYTES);
let ours = Pubkey::from(orig);
assert_eq!(ours.as_array(), &SOL_ADDR_BYTES);
}
#[cfg(feature = "solana-address-convert-v1")]
#[test]
fn test_convert_to_solana_address_v1() {
use solana_address_v1::Address;
let orig = Address::new_from_array(SOL_ADDR_BYTES);
let ours = Pubkey::from(orig);
assert_eq!(ours.as_array(), &SOL_ADDR_BYTES);
}
#[cfg(feature = "serde")]
#[test]
fn test_serialize_messagepack() {
let pubkey = Pubkey::new_from_array(SOL_ADDR_BYTES);
let encoded = rmp_serde::encode::to_vec(&pubkey).expect("should encode via messagepack");
assert_eq!(encoded.len(), PUBKEY_BYTES + 2);
assert_eq!(encoded[0..2], [0xc4u8, 0x20u8]);
assert_eq!(encoded[2..], SOL_ADDR_BYTES)
}
#[cfg(feature = "serde")]
#[test]
fn test_deserialize_messagepack() {
let pubkey = Pubkey::new_from_array(SOL_ADDR_BYTES);
let mut encoded = [0u8; PUBKEY_BYTES + 2];
encoded[0] = 0xc4;
encoded[1] = 32;
encoded[2..].copy_from_slice(&SOL_ADDR_BYTES);
let decoded = rmp_serde::decode::from_slice::<Pubkey>(&encoded).expect("should decode");
assert_eq!(decoded, pubkey);
}
}