Use procedural macro to generate static public keys (#7219)

automerge
This commit is contained in:
Justin Starry
2019-12-03 20:55:18 -05:00
committed by Grimes
parent a66a49d384
commit 7cfff75c3e
13 changed files with 384 additions and 231 deletions

View File

@@ -47,6 +47,10 @@ impl Pubkey {
)
}
pub const fn new_from_array(pubkey_array: [u8; 32]) -> Self {
Self(pubkey_array)
}
#[cfg(not(feature = "program"))]
pub fn new_rand() -> Self {
Self::new(&rand::random::<[u8; 32]>())
@@ -104,62 +108,6 @@ 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!
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 == *_PUBKEY
}
pub fn id() -> $crate::pubkey::Pubkey {
*_PUBKEY
}
#[cfg(test)]
#[test]
fn test_id() {
assert!(check_id(&id()));
}
)
);
#[cfg(test)]
mod tests {
use super::*;