Use bs58 strings to declare IDs rather then raw bytes (#7082)
This commit is contained in:
@@ -104,16 +104,52 @@ pub fn read_pubkey_file(infile: &str) -> Result<Pubkey, Box<dyn error::Error>> {
|
||||
Ok(Pubkey::from_str(&printable)?)
|
||||
}
|
||||
|
||||
/// Convenience macro to declare a static Pubkey and functions to interact with it
|
||||
///
|
||||
/// bs58_string: bs58 string representation the program's id
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// solana_sdk::declare_id!("My!!!11111111111111111111111111111111111111");
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! solana_id(
|
||||
($id:ident) => (
|
||||
macro_rules!
|
||||
declare_id(
|
||||
($bs58_string:expr) => (
|
||||
use std::str::FromStr;
|
||||
|
||||
$crate::lazy_static::lazy_static! {
|
||||
static ref _PUBKEY: $crate::pubkey::Pubkey = {
|
||||
match $crate::pubkey::Pubkey::from_str(&$bs58_string) {
|
||||
Ok(pubkey) => pubkey,
|
||||
Err(_) => {
|
||||
let pubkey_vec = $crate::bs58::decode(&$bs58_string)
|
||||
.into_vec()
|
||||
.map_err(|e| panic!("Error: {}, {}", $bs58_string, e))
|
||||
.unwrap();
|
||||
let expected_len = std::mem::size_of::<$crate::pubkey::Pubkey>();
|
||||
let len = pubkey_vec.len();
|
||||
if len != expected_len {
|
||||
panic!(
|
||||
"Error: {}, decoded length {}, expected {}",
|
||||
$bs58_string, len, expected_len);
|
||||
} else {
|
||||
panic!(
|
||||
"Error: {}, not a valid string, cannot determine reason",
|
||||
$bs58_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn check_id(id: &$crate::pubkey::Pubkey) -> bool {
|
||||
id.as_ref() == $id
|
||||
*id == *_PUBKEY
|
||||
}
|
||||
|
||||
pub fn id() -> $crate::pubkey::Pubkey {
|
||||
$crate::pubkey::Pubkey::new(&$id)
|
||||
*_PUBKEY
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -121,23 +157,6 @@ macro_rules! solana_id(
|
||||
fn test_id() {
|
||||
assert!(check_id(&id()));
|
||||
}
|
||||
|
||||
)
|
||||
);
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! solana_name_id(
|
||||
($id:ident, $name:expr) => (
|
||||
|
||||
$crate::solana_id!($id);
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn test_name_id() {
|
||||
if id().to_string() != $name {
|
||||
panic!("id for `{}` should be `{:?}`", $name, $crate::pubkey::bs58::decode($name).into_vec().unwrap());
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
|
Reference in New Issue
Block a user