Skip to content

chore(pubkey): (may be) proper serde json support (encode as base58 string, not as array) and json schema #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 66 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions pubkey/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "solana-pubkey"
description = "Solana account addresses"
documentation = "https://docs.rs/solana-pubkey"
version = "2.2.1"
version = "3.0"
authors = { workspace = true }
repository = { workspace = true }
homepage = { workspace = true }
Expand All @@ -19,6 +19,7 @@ bytemuck_derive = { workspace = true, optional = true }
five8_const = { workspace = true }
num-traits = { workspace = true }
rand = { workspace = true, optional = true }
schemars = { version = "0.8", default-features = false, optional = true, features = ["derive", "preserve_order"] }
serde = { workspace = true, optional = true }
serde_derive = { workspace = true, optional = true }
solana-atomic-u64 = { workspace = true }
Expand Down Expand Up @@ -48,6 +49,7 @@ wasm-bindgen = { workspace = true }
anyhow = { workspace = true }
arbitrary = { workspace = true, features = ["derive"] }
bs58 = { workspace = true, features = ["alloc"] }
serde_json = { workspace = true }
# circular dev deps need to be path deps for `cargo publish` to be happy,
# and for now the doc tests need solana-program
solana-program = { path = "../program" }
Expand All @@ -72,7 +74,8 @@ frozen-abi = [
"std",
]
rand = ["dep:rand", "std"]
serde = ["dep:serde", "dep:serde_derive"]
schemars = ["dep:schemars", "serde", "std"]
serde = ["dep:serde", "dep:serde_derive", "bs58/alloc"]
sha2 = ["dep:solana-sha256-hasher", "solana-sha256-hasher/sha2"]
std = []

Expand Down
76 changes: 75 additions & 1 deletion pubkey/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
#![allow(clippy::arithmetic_side_effects)]

#[cfg(all(feature = "serde", not(feature = "std")))]
extern crate alloc;

#[cfg(any(feature = "std", target_arch = "wasm32"))]
extern crate std;
#[cfg(feature = "dev-context-only-utils")]
Expand Down Expand Up @@ -156,11 +159,27 @@ impl From<u64> for PubkeyError {
borsh(crate = "borsh")
)]
#[cfg_attr(all(feature = "borsh", feature = "std"), derive(BorshSchema))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "bytemuck", derive(Pod, Zeroable))]
#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "dev-context-only-utils", derive(Arbitrary))]
pub struct Pubkey(pub(crate) [u8; 32]);
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Pubkey(
#[cfg_attr(
feature = "serde",
serde(serialize_with = "serialize", deserialize_with = "deserialize")
)]
#[cfg_attr(
feature = "schemars",
schemars(
with = "std::string::String",
title = "SolanaPubkey",
range(min = 32, max = 44)
)
)]
pub(crate) [u8; 32],
);

impl solana_sanitize::Sanitize for Pubkey {}

Expand Down Expand Up @@ -894,6 +913,35 @@ macro_rules! impl_borsh_serialize {
#[cfg(feature = "borsh")]
impl_borsh_serialize!(borsh0_10);

#[cfg(feature = "serde")]
fn serialize<S>(bytes: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let encoded = bs58::encode(bytes).into_string();
serializer.serialize_str(&encoded)
}

#[cfg(feature = "serde")]
fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
where
D: serde::Deserializer<'de>,
{
#[cfg(feature = "std")]
use std::{format, string::String};

#[cfg(not(feature = "std"))]
use alloc::{format, string::String};

let s: String = serde::Deserialize::deserialize(deserializer)
.map_err(|_| serde::de::Error::custom("Failed to read String"))?;
let b = bs58::decode(s)
.into_vec()
.map_err(|x| serde::de::Error::custom(format!("Failed to decode base58 {x}")))?;
b.try_into()
.map_err(|_| serde::de::Error::custom("Invalid length"))
}

#[cfg(all(target_arch = "wasm32", feature = "curve25519"))]
fn js_value_to_seeds_vec(array_of_uint8_arrays: &[JsValue]) -> Result<Vec<Vec<u8>>, JsValue> {
let vec_vec_u8 = array_of_uint8_arrays
Expand Down Expand Up @@ -1416,4 +1464,30 @@ mod tests {
// Sanity check: ensure the pointer is the same.
assert_eq!(key.as_array().as_ptr(), key.0.as_ptr());
}

#[test]
#[cfg(feature = "serde")]
fn json() {
let pubkey = Pubkey::new_unique();
let json = serde_json::to_string(&pubkey).unwrap();
let display = pubkey.to_string();
let back = serde_json::from_str::<Pubkey>(&json).unwrap();

assert_eq!(json, std::format!("\"{display}\""));
assert_eq!(pubkey, back);
}

#[test]
#[cfg(feature = "schemars")]
fn schemars() {
use schemars::{
schema::{InstanceType, SingleOrVec},
schema_for,
};
let schema = schema_for!(Pubkey);
assert_eq!(
schema.schema.instance_type.unwrap(),
SingleOrVec::Single(std::boxed::Box::new(InstanceType::String))
);
}
}