deprecates Pubkey::new in favor of Pubkey::{,try_}from (#29805)

The commit deprecates Pubkey::new which lacks type-safety and instead
implements TryFrom<&[u8]> and TryFrom<Vec<u8>> for Pubkey.
This commit is contained in:
behzad nouri 2023-01-21 18:06:27 +00:00 committed by GitHub
parent f4339bc0f2
commit 272e667cb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 258 additions and 237 deletions

View File

@ -282,11 +282,9 @@ pub struct UiMultisig {
}
pub fn get_token_account_mint(data: &[u8]) -> Option<Pubkey> {
if Account::valid_account_data(data) {
Some(Pubkey::new(&data[0..32]))
} else {
None
}
Account::valid_account_data(data)
.then(|| Pubkey::try_from(data.get(..32)?).ok())
.flatten()
}
#[cfg(test)]
@ -402,7 +400,7 @@ mod test {
account.state = AccountState::Initialized;
Account::pack(account, &mut account_data).unwrap();
let expected_mint_pubkey = Pubkey::new(&[2; 32]);
let expected_mint_pubkey = Pubkey::from([2; 32]);
assert_eq!(
get_token_account_mint(&account_data),
Some(expected_mint_pubkey)

View File

@ -2926,10 +2926,10 @@ mod tests {
}
let present: Box<dyn Signer> = Box::new(keypair_from_seed(&[2u8; 32]).unwrap());
let absent: Box<dyn Signer> = Box::new(NullSigner::new(&Pubkey::new(&[3u8; 32])));
let bad: Box<dyn Signer> = Box::new(BadSigner::new(Pubkey::new(&[4u8; 32])));
let to = Pubkey::new(&[5u8; 32]);
let nonce = Pubkey::new(&[6u8; 32]);
let absent: Box<dyn Signer> = Box::new(NullSigner::new(&Pubkey::from([3u8; 32])));
let bad: Box<dyn Signer> = Box::new(BadSigner::new(Pubkey::from([4u8; 32])));
let to = Pubkey::from([5u8; 32]);
let nonce = Pubkey::from([6u8; 32]);
let from = present.pubkey();
let fee_payer = absent.pubkey();
let nonce_auth = bad.pubkey();

View File

@ -185,8 +185,8 @@ mod tests {
});
let pubkey = solana_sdk::pubkey::new_rand();
let pubkey0 = Pubkey::new(&[0; 32]);
let pubkey1 = Pubkey::new(&[1; 32]);
let pubkey0 = Pubkey::from([0; 32]);
let pubkey1 = Pubkey::from([1; 32]);
let ix0 = system_instruction::transfer(&pubkey0, &pubkey1, 1);
let message0 = Message::new(&[ix0], Some(&pubkey0));
@ -290,8 +290,8 @@ mod tests {
assert_eq!(get_fee_for_messages(&rpc_client, &[]).unwrap(), 0);
// One message w/ one signature, a fee.
let pubkey0 = Pubkey::new(&[0; 32]);
let pubkey1 = Pubkey::new(&[1; 32]);
let pubkey0 = Pubkey::from([0; 32]);
let pubkey1 = Pubkey::from([1; 32]);
let ix0 = system_instruction::transfer(&pubkey0, &pubkey1, 1);
let message0 = Message::new(&[ix0], Some(&pubkey0));
assert_eq!(get_fee_for_messages(&rpc_client, &[&message0]).unwrap(), 1);

View File

@ -2563,7 +2563,7 @@ mod tests {
);
//Test Transfer Subcommand, with nonce
let nonce_address = Pubkey::new(&[1u8; 32]);
let nonce_address = Pubkey::from([1u8; 32]);
let nonce_address_string = nonce_address.to_string();
let nonce_authority = keypair_from_seed(&[2u8; 32]).unwrap();
let nonce_authority_file = make_tmp_path("nonce_authority_file");

View File

@ -12,7 +12,7 @@ impl WithMemo for Vec<Instruction> {
if let Some(memo) = &memo {
let memo = memo.as_ref();
let memo_ix = Instruction {
program_id: Pubkey::new(&id().to_bytes()),
program_id: Pubkey::from(id().to_bytes()),
accounts: vec![],
data: memo.as_bytes().to_vec(),
};

View File

@ -1079,7 +1079,7 @@ mod tests {
let valid = Account::new_data(1, &data, &system_program::ID);
assert!(check_nonce_account(&valid.unwrap(), &nonce_pubkey, &blockhash).is_ok());
let invalid_owner = Account::new_data(1, &data, &Pubkey::new(&[1u8; 32]));
let invalid_owner = Account::new_data(1, &data, &Pubkey::from([1u8; 32]));
if let CliError::InvalidNonce(err) =
check_nonce_account(&invalid_owner.unwrap(), &nonce_pubkey, &blockhash).unwrap_err()
{
@ -1151,7 +1151,7 @@ mod tests {
Err(Error::UnexpectedDataSize),
);
let other_program = Pubkey::new(&[1u8; 32]);
let other_program = Pubkey::from([1u8; 32]);
let other_account_no_data = Account::new(1, 0, &other_program);
assert_eq!(
account_identity_ok(&other_account_no_data),
@ -1165,7 +1165,7 @@ mod tests {
assert_eq!(state_from_account(&nonce_account), Ok(State::Uninitialized));
let durable_nonce = DurableNonce::from_blockhash(&Hash::new(&[42u8; 32]));
let data = nonce::state::Data::new(Pubkey::new(&[1u8; 32]), durable_nonce, 42);
let data = nonce::state::Data::new(Pubkey::from([1u8; 32]), durable_nonce, 42);
nonce_account
.set_state(&Versions::new(State::Initialized(data.clone())))
.unwrap();
@ -1195,7 +1195,7 @@ mod tests {
);
let durable_nonce = DurableNonce::from_blockhash(&Hash::new(&[42u8; 32]));
let data = nonce::state::Data::new(Pubkey::new(&[1u8; 32]), durable_nonce, 42);
let data = nonce::state::Data::new(Pubkey::from([1u8; 32]), durable_nonce, 42);
nonce_account
.set_state(&Versions::new(State::Initialized(data.clone())))
.unwrap();

View File

@ -2686,9 +2686,9 @@ mod tests {
// stake-authorize subcommand
let stake_account_string = stake_account_pubkey.to_string();
let new_stake_authority = Pubkey::new(&[1u8; 32]);
let new_stake_authority = Pubkey::from([1u8; 32]);
let new_stake_string = new_stake_authority.to_string();
let new_withdraw_authority = Pubkey::new(&[2u8; 32]);
let new_withdraw_authority = Pubkey::from([2u8; 32]);
let new_withdraw_string = new_withdraw_authority.to_string();
let test_stake_authorize = test_commands.clone().get_matches_from(vec![
"test",
@ -3537,7 +3537,7 @@ mod tests {
let pubkey2 = keypair2.pubkey();
let sig2 = keypair.sign_message(&[0u8]);
let signer2 = format!("{}={}", keypair2.pubkey(), sig2);
let nonce_account = Pubkey::new(&[1u8; 32]);
let nonce_account = Pubkey::from([1u8; 32]);
let test_authorize = test_commands.clone().get_matches_from(vec![
"test",
"stake-authorize",
@ -3914,7 +3914,7 @@ mod tests {
assert!(parse_command(&test_create_stake_account, &default_signer, &mut None).is_err());
// CreateStakeAccount offline and nonce
let nonce_account = Pubkey::new(&[1u8; 32]);
let nonce_account = Pubkey::from([1u8; 32]);
let nonce_account_string = nonce_account.to_string();
let offline = keypair_from_seed(&[2u8; 32]).unwrap();
let offline_pubkey = offline.pubkey();
@ -4829,7 +4829,7 @@ mod tests {
);
// Split stake offline nonced submission
let nonce_account = Pubkey::new(&[1u8; 32]);
let nonce_account = Pubkey::from([1u8; 32]);
let nonce_account_string = nonce_account.to_string();
let nonce_auth = keypair_from_seed(&[2u8; 32]).unwrap();
let nonce_auth_pubkey = nonce_auth.pubkey();

View File

@ -256,7 +256,7 @@ fn test_create_account_with_seed() {
let offline_nonce_authority_signer = keypair_from_seed(&[1u8; 32]).unwrap();
let online_nonce_creator_signer = keypair_from_seed(&[2u8; 32]).unwrap();
let to_address = Pubkey::new(&[3u8; 32]);
let to_address = Pubkey::from([3u8; 32]);
// Setup accounts
let rpc_client =

View File

@ -50,7 +50,7 @@ fn test_transfer() {
config.signers = vec![&default_signer];
let sender_pubkey = config.signers[0].pubkey();
let recipient_pubkey = Pubkey::new(&[1u8; 32]);
let recipient_pubkey = Pubkey::from([1u8; 32]);
request_and_confirm_airdrop(&rpc_client, &config, &sender_pubkey, sol_to_lamports(5.0))
.unwrap();
@ -336,7 +336,7 @@ fn test_transfer_multisession_signing() {
SocketAddrSpace::Unspecified,
);
let to_pubkey = Pubkey::new(&[1u8; 32]);
let to_pubkey = Pubkey::from([1u8; 32]);
let offline_from_signer = keypair_from_seed(&[2u8; 32]).unwrap();
let offline_fee_payer_signer = keypair_from_seed(&[3u8; 32]).unwrap();
let from_null_signer = NullSigner::new(&offline_from_signer.pubkey());
@ -498,7 +498,7 @@ fn test_transfer_all() {
config.signers = vec![&default_signer];
let sender_pubkey = config.signers[0].pubkey();
let recipient_pubkey = Pubkey::new(&[1u8; 32]);
let recipient_pubkey = Pubkey::from([1u8; 32]);
request_and_confirm_airdrop(&rpc_client, &config, &sender_pubkey, 500_000).unwrap();
check_balance!(500_000, &rpc_client, &sender_pubkey);
@ -552,7 +552,7 @@ fn test_transfer_unfunded_recipient() {
config.signers = vec![&default_signer];
let sender_pubkey = config.signers[0].pubkey();
let recipient_pubkey = Pubkey::new(&[1u8; 32]);
let recipient_pubkey = Pubkey::from([1u8; 32]);
request_and_confirm_airdrop(&rpc_client, &config, &sender_pubkey, 50_000).unwrap();
check_balance!(50_000, &rpc_client, &sender_pubkey);
@ -607,7 +607,7 @@ fn test_transfer_with_seed() {
config.signers = vec![&default_signer];
let sender_pubkey = config.signers[0].pubkey();
let recipient_pubkey = Pubkey::new(&[1u8; 32]);
let recipient_pubkey = Pubkey::from([1u8; 32]);
let derived_address_seed = "seed".to_string();
let derived_address_program_id = stake::program::id();
let derived_address = Pubkey::create_with_seed(

View File

@ -203,7 +203,7 @@ impl Faucet {
)
);
let memo_instruction = Instruction {
program_id: Pubkey::new(&spl_memo::id().to_bytes()),
program_id: Pubkey::from(spl_memo::id().to_bytes()),
accounts: vec![],
data: memo.as_bytes().to_vec(),
};
@ -635,7 +635,7 @@ mod tests {
assert_eq!(tx.signatures.len(), 1);
assert_eq!(
message.account_keys,
vec![mint_pubkey, Pubkey::new(&spl_memo::id().to_bytes())]
vec![mint_pubkey, Pubkey::from(spl_memo::id().to_bytes())]
);
assert_eq!(message.recent_blockhash, blockhash);

View File

@ -216,7 +216,7 @@ mod tests {
// print(
// "\n\"{}\", // {:?}",
// hex,
// Pubkey::new(&hex::decode(hex).unwrap())
// Pubkey::try_from(&hex::decode(hex).unwrap()).unwrap()
// );
// });
// println();

View File

@ -4188,7 +4188,7 @@ RPC Enabled Nodes: 1"#;
#[test]
fn test_tvu_peers_and_stakes() {
let d = ContactInfo::new_localhost(&Pubkey::new(&[0; 32]), timestamp());
let d = ContactInfo::new_localhost(&Pubkey::from([0; 32]), timestamp());
let cluster_info = ClusterInfo::new(
d.clone(),
Arc::new(Keypair::new()),
@ -4197,12 +4197,12 @@ RPC Enabled Nodes: 1"#;
let mut stakes = HashMap::new();
// no stake
let id = Pubkey::new(&[1u8; 32]);
let id = Pubkey::from([1u8; 32]);
let contact_info = ContactInfo::new_localhost(&id, timestamp());
cluster_info.insert_info(contact_info);
// normal
let id2 = Pubkey::new(&[2u8; 32]);
let id2 = Pubkey::from([2u8; 32]);
let mut contact_info = ContactInfo::new_localhost(&id2, timestamp());
cluster_info.insert_info(contact_info.clone());
stakes.insert(id2, 10);
@ -4212,14 +4212,14 @@ RPC Enabled Nodes: 1"#;
cluster_info.insert_info(contact_info);
// no tvu
let id3 = Pubkey::new(&[3u8; 32]);
let id3 = Pubkey::from([3u8; 32]);
let mut contact_info = ContactInfo::new_localhost(&id3, timestamp());
contact_info.tvu = "0.0.0.0:0".parse().unwrap();
cluster_info.insert_info(contact_info);
stakes.insert(id3, 10);
// normal but with different shred version
let id4 = Pubkey::new(&[4u8; 32]);
let id4 = Pubkey::from([4u8; 32]);
let mut contact_info = ContactInfo::new_localhost(&id4, timestamp());
contact_info.shred_version = 1;
assert_ne!(contact_info.shred_version, d.shred_version);

View File

@ -435,8 +435,8 @@ mod test {
let crds_gossip = CrdsGossip::default();
let keypair = Keypair::new();
let id = keypair.pubkey();
let ci = ContactInfo::new_localhost(&Pubkey::new(&[1; 32]), 0);
let prune_pubkey = Pubkey::new(&[2; 32]);
let ci = ContactInfo::new_localhost(&Pubkey::from([1; 32]), 0);
let prune_pubkey = Pubkey::from([2; 32]);
crds_gossip
.crds
.write()
@ -467,7 +467,7 @@ mod test {
let mut res = crds_gossip.process_prune_msg(
&id,
&ci.id,
&Pubkey::new(hash(&[1; 32]).as_ref()),
&Pubkey::from(hash(&[1; 32]).to_bytes()),
&[prune_pubkey],
now,
now,

View File

@ -732,8 +732,8 @@ fn test_prune_errors() {
let crds_gossip = CrdsGossip::default();
let keypair = Keypair::new();
let id = keypair.pubkey();
let ci = ContactInfo::new_localhost(&Pubkey::new(&[1; 32]), 0);
let prune_pubkey = Pubkey::new(&[2; 32]);
let ci = ContactInfo::new_localhost(&Pubkey::from([1; 32]), 0);
let prune_pubkey = Pubkey::from([2; 32]);
crds_gossip
.crds
.write()
@ -758,10 +758,10 @@ fn test_prune_errors() {
let stakes = HashMap::<Pubkey, u64>::default();
//incorrect dest
let mut res = crds_gossip.process_prune_msg(
&id, // self_pubkey
&ci.id, // peer
&Pubkey::new(hash(&[1; 32]).as_ref()), // destination
&[prune_pubkey], // origins
&id, // self_pubkey
&ci.id, // peer
&Pubkey::from(hash(&[1; 32]).to_bytes()), // destination
&[prune_pubkey], // origins
now,
now,
&stakes,

View File

@ -6979,8 +6979,8 @@ pub mod tests {
.write_transaction_status(
slot0,
Signature::new(&random_bytes),
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();
@ -7045,8 +7045,8 @@ pub mod tests {
.write_transaction_status(
slot1,
Signature::new(&random_bytes),
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();

View File

@ -476,8 +476,8 @@ pub mod tests {
.write_transaction_status(
x,
Signature::new(&random_bytes),
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();
@ -491,8 +491,8 @@ pub mod tests {
.write_transaction_status(
x,
Signature::new(&random_bytes),
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();
@ -526,8 +526,8 @@ pub mod tests {
.write_transaction_status(
slot,
Signature::new(&random_bytes),
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();
@ -726,8 +726,8 @@ pub mod tests {
.write_transaction_status(
x,
signature,
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();
@ -769,8 +769,8 @@ pub mod tests {
.write_transaction_status(
x,
signature,
vec![&Pubkey::new(&random_bytes[0..32])],
vec![&Pubkey::new(&random_bytes[32..])],
vec![&Pubkey::try_from(&random_bytes[..32]).unwrap()],
vec![&Pubkey::try_from(&random_bytes[32..]).unwrap()],
TransactionStatusMeta::default(),
)
.unwrap();

View File

@ -729,7 +729,7 @@ impl Column for columns::AddressSignatures {
fn index(key: &[u8]) -> (u64, Pubkey, Slot, Signature) {
let index = BigEndian::read_u64(&key[0..8]);
let pubkey = Pubkey::new(&key[8..40]);
let pubkey = Pubkey::try_from(&key[8..40]).unwrap();
let slot = BigEndian::read_u64(&key[40..48]);
let signature = Signature::new(&key[48..112]);
(index, pubkey, slot, signature)
@ -857,7 +857,7 @@ impl Column for columns::ProgramCosts {
}
fn index(key: &[u8]) -> Self::Index {
Pubkey::new(&key[0..32])
Pubkey::try_from(&key[..32]).unwrap()
}
fn primary_index(_index: Self::Index) -> u64 {

View File

@ -420,10 +420,7 @@ impl RemoteWallet<hidapi::DeviceInfo> for LedgerWallet {
0,
&derivation_path,
)?;
if key.len() != 32 {
return Err(RemoteWalletError::Protocol("Key packet size mismatch"));
}
Ok(Pubkey::new(&key))
Pubkey::try_from(key).map_err(|_| RemoteWalletError::Protocol("Key packet size mismatch"))
}
fn sign_message(

View File

@ -205,7 +205,7 @@ mod tests {
#[test]
fn test_blockhash_query_new_ok() {
let blockhash = hash(&[1u8]);
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
assert_eq!(
BlockhashQuery::new(Some(blockhash), true, None),
@ -246,7 +246,7 @@ mod tests {
#[test]
#[should_panic]
fn test_blockhash_query_new_nonce_fail() {
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
BlockhashQuery::new(None, true, Some(nonce_pubkey));
}
@ -287,7 +287,7 @@ mod tests {
BlockhashQuery::All(blockhash_query::Source::Cluster),
);
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
let nonce_string = nonce_pubkey.to_string();
let matches = test_commands.clone().get_matches_from(vec![
"blockhash_query_test",
@ -339,7 +339,7 @@ mod tests {
// We can really only hit this case if the arg requirements
// are broken, so unset the requires() to recreate that condition
.arg(sign_only_arg().requires(""));
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
let nonce_string = nonce_pubkey.to_string();
let matches = test_commands.get_matches_from(vec![
@ -418,7 +418,7 @@ mod tests {
let nonce_blockhash = *durable_nonce.as_hash();
let nonce_fee_calc = FeeCalculator::new(4242);
let data = nonce::state::Data {
authority: Pubkey::new(&[3u8; 32]),
authority: Pubkey::from([3u8; 32]),
durable_nonce,
fee_calculator: nonce_fee_calc,
};
@ -429,7 +429,7 @@ mod tests {
&system_program::id(),
)
.unwrap();
let nonce_pubkey = Pubkey::new(&[4u8; 32]);
let nonce_pubkey = Pubkey::from([4u8; 32]);
let rpc_nonce_account = UiAccount::encode(
&nonce_pubkey,
&nonce_account,

View File

@ -137,7 +137,7 @@ mod tests {
#[test]
fn test_blockhash_query_new_ok() {
let blockhash = hash(&[1u8]);
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
assert_eq!(
BlockhashQuery::new(Some(blockhash), true, None),
@ -178,7 +178,7 @@ mod tests {
#[test]
#[should_panic]
fn test_blockhash_query_new_nonce_fail() {
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
BlockhashQuery::new(None, true, Some(nonce_pubkey));
}
@ -219,7 +219,7 @@ mod tests {
BlockhashQuery::Rpc(blockhash_query::Source::Cluster),
);
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
let nonce_string = nonce_pubkey.to_string();
let matches = test_commands.clone().get_matches_from(vec![
"blockhash_query_test",
@ -271,7 +271,7 @@ mod tests {
// We can really only hit this case if the arg requirements
// are broken, so unset the requires() to recreate that condition
.arg(sign_only_arg().requires(""));
let nonce_pubkey = Pubkey::new(&[1u8; 32]);
let nonce_pubkey = Pubkey::from([1u8; 32]);
let nonce_string = nonce_pubkey.to_string();
let matches = test_commands.get_matches_from(vec![
@ -363,7 +363,7 @@ mod tests {
let nonce_blockhash = *durable_nonce.as_hash();
let nonce_fee_calc = FeeCalculator::new(4242);
let data = nonce::state::Data {
authority: Pubkey::new(&[3u8; 32]),
authority: Pubkey::from([3u8; 32]),
durable_nonce,
fee_calculator: nonce_fee_calc,
};
@ -374,7 +374,7 @@ mod tests {
&system_program::id(),
)
.unwrap();
let nonce_pubkey = Pubkey::new(&[4u8; 32]);
let nonce_pubkey = Pubkey::from([4u8; 32]);
let rpc_nonce_account = UiAccount::encode(
&nonce_pubkey,
&nonce_account,

View File

@ -2348,7 +2348,7 @@ fn get_spl_token_owner_filter(program_id: &Pubkey, filters: &[RpcFilterType]) ->
..
}) if *offset == SPL_TOKEN_ACCOUNT_OWNER_OFFSET => {
if bytes.len() == PUBKEY_BYTES {
owner_key = Some(Pubkey::new(bytes));
owner_key = Pubkey::try_from(&bytes[..]).ok();
} else {
incorrect_owner_len = Some(bytes.len());
}
@ -2404,7 +2404,7 @@ fn get_spl_token_mint_filter(program_id: &Pubkey, filters: &[RpcFilterType]) ->
..
}) if *offset == SPL_TOKEN_ACCOUNT_MINT_OFFSET => {
if bytes.len() == PUBKEY_BYTES {
mint = Some(Pubkey::new(bytes));
mint = Pubkey::try_from(&bytes[..]).ok();
} else {
incorrect_mint_len = Some(bytes.len());
}

View File

@ -357,7 +357,7 @@ pub(crate) mod tests {
let mut nonce_account = nonce_account::create_account(1).into_inner();
let durable_nonce = DurableNonce::from_blockhash(&Hash::new(&[42u8; 32]));
let data = nonce::state::Data::new(Pubkey::new(&[1u8; 32]), durable_nonce, 42);
let data = nonce::state::Data::new(Pubkey::from([1u8; 32]), durable_nonce, 42);
nonce_account
.set_state(&nonce::state::Versions::new(nonce::State::Initialized(
data,

View File

@ -48,7 +48,7 @@ pub fn create_builtin_transactions(
bank_client: &BankClient,
mint_keypair: &Keypair,
) -> Vec<Transaction> {
let program_id = Pubkey::new(&BUILTIN_PROGRAM_ID);
let program_id = Pubkey::from(BUILTIN_PROGRAM_ID);
(0..4096)
.map(|_| {
@ -70,7 +70,7 @@ pub fn create_native_loader_transactions(
bank_client: &BankClient,
mint_keypair: &Keypair,
) -> Vec<Transaction> {
let program_id = Pubkey::new(&NOOP_PROGRAM_ID);
let program_id = Pubkey::from(NOOP_PROGRAM_ID);
(0..4096)
.map(|_| {
@ -138,10 +138,10 @@ fn do_bench_transactions(
let mut bank = Bank::new_from_parent(&Arc::new(bank), &Pubkey::default(), 1);
bank.add_builtin(
"builtin_program",
&Pubkey::new(&BUILTIN_PROGRAM_ID),
&Pubkey::from(BUILTIN_PROGRAM_ID),
process_instruction,
);
bank.add_builtin_account("solana_noop_program", &Pubkey::new(&NOOP_PROGRAM_ID), false);
bank.add_builtin_account("solana_noop_program", &Pubkey::from(NOOP_PROGRAM_ID), false);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);
let transactions = create_transactions(&bank_client, &mint_keypair);

View File

@ -1473,7 +1473,7 @@ mod tests {
#[test]
fn test_hold_range_in_memory() {
let accts = Accounts::default_for_tests();
let range = Pubkey::new(&[0; 32])..=Pubkey::new(&[0xff; 32]);
let range = Pubkey::from([0; 32])..=Pubkey::from([0xff; 32]);
accts.hold_range_in_memory(&range, true, &test_thread_pool());
accts.hold_range_in_memory(&range, false, &test_thread_pool());
accts.hold_range_in_memory(&range, true, &test_thread_pool());
@ -1485,7 +1485,7 @@ mod tests {
#[test]
fn test_hold_range_in_memory2() {
let accts = Accounts::default_for_tests();
let range = Pubkey::new(&[0; 32])..=Pubkey::new(&[0xff; 32]);
let range = Pubkey::from([0; 32])..=Pubkey::from([0xff; 32]);
let idx = &accts.accounts_db.accounts_index;
let bins = idx.account_maps.len();
// use bins * 2 to get the first half of the range within bin 0
@ -1557,7 +1557,7 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let account = AccountSharedData::new(1, 0, &Pubkey::default());
accounts.push((key0, account));
@ -1748,7 +1748,7 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let mut account = AccountSharedData::new(1, 0, &Pubkey::default());
account.set_rent_epoch(1);
@ -1790,12 +1790,12 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key2 = Pubkey::new(&[6u8; 32]);
let key3 = Pubkey::new(&[7u8; 32]);
let key4 = Pubkey::new(&[8u8; 32]);
let key5 = Pubkey::new(&[9u8; 32]);
let key6 = Pubkey::new(&[10u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let key2 = Pubkey::from([6u8; 32]);
let key3 = Pubkey::from([7u8; 32]);
let key4 = Pubkey::from([8u8; 32]);
let key5 = Pubkey::from([9u8; 32]);
let key6 = Pubkey::from([10u8; 32]);
let account = AccountSharedData::new(1, 0, &Pubkey::default());
accounts.push((key0, account));
@ -1856,7 +1856,7 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let account = AccountSharedData::new(1, 0, &Pubkey::default());
accounts.push((key0, account));
@ -1891,7 +1891,7 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let account = AccountSharedData::new(1, 0, &Pubkey::default());
accounts.push((key0, account));
@ -1925,8 +1925,8 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key2 = Pubkey::new(&[6u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let key2 = Pubkey::from([6u8; 32]);
let mut account = AccountSharedData::new(1, 0, &Pubkey::default());
account.set_rent_epoch(1);
@ -2132,20 +2132,20 @@ mod tests {
// Load accounts owned by various programs into AccountsDb
let pubkey0 = solana_sdk::pubkey::new_rand();
let account0 = AccountSharedData::new(1, 0, &Pubkey::new(&[2; 32]));
let account0 = AccountSharedData::new(1, 0, &Pubkey::from([2; 32]));
accounts.store_slow_uncached(0, &pubkey0, &account0);
let pubkey1 = solana_sdk::pubkey::new_rand();
let account1 = AccountSharedData::new(1, 0, &Pubkey::new(&[2; 32]));
let account1 = AccountSharedData::new(1, 0, &Pubkey::from([2; 32]));
accounts.store_slow_uncached(0, &pubkey1, &account1);
let pubkey2 = solana_sdk::pubkey::new_rand();
let account2 = AccountSharedData::new(1, 0, &Pubkey::new(&[3; 32]));
let account2 = AccountSharedData::new(1, 0, &Pubkey::from([3; 32]));
accounts.store_slow_uncached(0, &pubkey2, &account2);
let loaded = accounts.load_by_program_slot(0, Some(&Pubkey::new(&[2; 32])));
let loaded = accounts.load_by_program_slot(0, Some(&Pubkey::from([2; 32])));
assert_eq!(loaded.len(), 2);
let loaded = accounts.load_by_program_slot(0, Some(&Pubkey::new(&[3; 32])));
let loaded = accounts.load_by_program_slot(0, Some(&Pubkey::from([3; 32])));
assert_eq!(loaded, vec![(pubkey2, account2)]);
let loaded = accounts.load_by_program_slot(0, Some(&Pubkey::new(&[4; 32])));
let loaded = accounts.load_by_program_slot(0, Some(&Pubkey::from([4; 32])));
assert_eq!(loaded, vec![]);
}
@ -2156,8 +2156,8 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key2 = Pubkey::new(&[6u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let key2 = Pubkey::from([6u8; 32]);
let mut account = AccountSharedData::new(1, 0, &Pubkey::default());
account.set_rent_epoch(1);
@ -2217,10 +2217,10 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key2 = Pubkey::new(&[6u8; 32]);
let programdata_key1 = Pubkey::new(&[7u8; 32]);
let programdata_key2 = Pubkey::new(&[8u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let key2 = Pubkey::from([6u8; 32]);
let programdata_key1 = Pubkey::from([7u8; 32]);
let programdata_key2 = Pubkey::from([8u8; 32]);
let mut account = AccountSharedData::new(1, 0, &Pubkey::default());
account.set_rent_epoch(1);
@ -2329,8 +2329,8 @@ mod tests {
let keypair = Keypair::new();
let key0 = keypair.pubkey();
let key1 = Pubkey::new(&[5u8; 32]);
let key2 = Pubkey::new(&[6u8; 32]);
let key1 = Pubkey::from([5u8; 32]);
let key2 = Pubkey::from([6u8; 32]);
let mut account = AccountSharedData::new(1, 0, &Pubkey::default());
account.set_rent_epoch(1);
@ -3276,7 +3276,7 @@ mod tests {
let expect_account = post_account.clone();
// Wrong key
assert!(run_prepare_if_nonce_account_test(
&Pubkey::new(&[1u8; 32]),
&Pubkey::from([1u8; 32]),
&mut post_account,
&Ok(()),
false,

View File

@ -8922,7 +8922,7 @@ impl AccountsDb {
#[allow(clippy::stable_sort_primitive)]
alive_roots.sort();
info!("{}: accounts_index alive_roots: {:?}", label, alive_roots,);
let full_pubkey_range = Pubkey::new(&[0; 32])..=Pubkey::new(&[0xff; 32]);
let full_pubkey_range = Pubkey::from([0; 32])..=Pubkey::from([0xff; 32]);
self.accounts_index.account_maps.iter().for_each(|map| {
for (pubkey, account_entry) in map.items(&full_pubkey_range) {
@ -9266,14 +9266,14 @@ pub mod tests {
let mut current_ancient = CurrentAncientAppendVec::default();
// setup 'to_store'
let pubkey = Pubkey::new(&[1; 32]);
let pubkey = Pubkey::from([1; 32]);
let account_size = 3;
let account = AccountSharedData::default();
let account_meta = AccountMeta {
lamports: 1,
owner: Pubkey::new(&[2; 32]),
owner: Pubkey::from([2; 32]),
executable: false,
rent_epoch: 0,
};
@ -9534,10 +9534,10 @@ pub mod tests {
Vec<Arc<AccountStorageEntry>>,
Vec<CalculateHashIntermediate>,
) {
let pubkey0 = Pubkey::new(&[0u8; 32]);
let pubkey127 = Pubkey::new(&[0x7fu8; 32]);
let pubkey128 = Pubkey::new(&[0x80u8; 32]);
let pubkey255 = Pubkey::new(&[0xffu8; 32]);
let pubkey0 = Pubkey::from([0u8; 32]);
let pubkey127 = Pubkey::from([0x7fu8; 32]);
let pubkey128 = Pubkey::from([0x80u8; 32]);
let pubkey255 = Pubkey::from([0xffu8; 32]);
let mut raw_expected = vec![
CalculateHashIntermediate::new(Hash::default(), 1, pubkey0),
@ -15373,8 +15373,8 @@ pub mod tests {
fn test_calculate_storage_count_and_alive_bytes_2_accounts() {
let accounts = AccountsDb::new_single_for_tests();
let keys = [
solana_sdk::pubkey::Pubkey::new(&[0; 32]),
solana_sdk::pubkey::Pubkey::new(&[255; 32]),
solana_sdk::pubkey::Pubkey::from([0; 32]),
solana_sdk::pubkey::Pubkey::from([255; 32]),
];
// make sure accounts are in 2 different bins
assert!(
@ -15758,7 +15758,7 @@ pub mod tests {
/// test 'unref' parameter 'pubkeys_removed_from_accounts_index'
fn test_unref_pubkeys_removed_from_accounts_index() {
let slot1 = 1;
let pk1 = Pubkey::new(&[1; 32]);
let pk1 = Pubkey::from([1; 32]);
for already_removed in [false, true] {
let mut pubkeys_removed_from_accounts_index =
PubkeysRemovedFromAccountsIndex::default();
@ -15816,8 +15816,8 @@ pub mod tests {
let slot1 = 1;
let slot2 = 2;
let pk1 = Pubkey::new(&[1; 32]);
let pk2 = Pubkey::new(&[2; 32]);
let pk1 = Pubkey::from([1; 32]);
let pk2 = Pubkey::from([2; 32]);
{
// pk1 in slot1, purge it
let db = AccountsDb::new_single_for_tests();
@ -15895,7 +15895,7 @@ pub mod tests {
let db = AccountsDb::new_single_for_tests();
let mut purged_stored_account_slots = AccountSlots::default();
let mut reclaims = SlotList::default();
let pk1 = Pubkey::new(&[1; 32]);
let pk1 = Pubkey::from([1; 32]);
// make sure we have > 1 batch. Bigger numbers cost more in test time here.
let n = (UNREF_ACCOUNTS_BATCH_SIZE + 1) as Slot;
// put the pubkey into the acct idx in 'n' slots
@ -16294,7 +16294,7 @@ pub mod tests {
fn test_add_uncleaned_pubkeys_after_shrink() {
let db = AccountsDb::new_single_for_tests();
let slot = 0;
let pubkey = Pubkey::new(&[1; 32]);
let pubkey = Pubkey::from([1; 32]);
db.add_uncleaned_pubkeys_after_shrink(slot, vec![pubkey].into_iter());
assert_eq!(&*db.uncleaned_pubkeys.get(&slot).unwrap(), &vec![pubkey]);
}

View File

@ -1244,13 +1244,13 @@ pub mod tests {
let mut account_maps = Vec::new();
let key = Pubkey::new(&[11u8; 32]);
let key = Pubkey::from([11u8; 32]);
let hash = Hash::new(&[1u8; 32]);
let val = CalculateHashIntermediate::new(hash, 88, key);
account_maps.push(val);
// 2nd key - zero lamports, so will be removed
let key = Pubkey::new(&[12u8; 32]);
let key = Pubkey::from([12u8; 32]);
let hash = Hash::new(&[2u8; 32]);
let val = CalculateHashIntermediate::new(hash, 0, key);
account_maps.push(val);
@ -1262,7 +1262,7 @@ pub mod tests {
assert_eq!((result.0, result.1), (expected_hash, 88));
// 3rd key - with pubkey value before 1st key so it will be sorted first
let key = Pubkey::new(&[10u8; 32]);
let key = Pubkey::from([10u8; 32]);
let hash = Hash::new(&[2u8; 32]);
let val = CalculateHashIntermediate::new(hash, 20, key);
account_maps.insert(0, val);
@ -1273,7 +1273,7 @@ pub mod tests {
assert_eq!((result.0, result.1), (expected_hash, 108));
// 3rd key - with later slot
let key = Pubkey::new(&[10u8; 32]);
let key = Pubkey::from([10u8; 32]);
let hash = Hash::new(&[99u8; 32]);
let val = CalculateHashIntermediate::new(hash, 30, key);
account_maps.insert(1, val);
@ -1352,9 +1352,9 @@ pub mod tests {
fn test_accountsdb_de_dup_accounts_from_stores() {
solana_logger::setup();
let key_a = Pubkey::new(&[1u8; 32]);
let key_b = Pubkey::new(&[2u8; 32]);
let key_c = Pubkey::new(&[3u8; 32]);
let key_a = Pubkey::from([1u8; 32]);
let key_b = Pubkey::from([2u8; 32]);
let key_c = Pubkey::from([3u8; 32]);
const COUNT: usize = 6;
let hashes = (0..COUNT).map(|i| Hash::new(&[i as u8; 32]));
// create this vector
@ -1876,7 +1876,7 @@ pub mod tests {
for count in start..iterations {
let mut input: Vec<_> = (0..count)
.map(|i| {
let key = Pubkey::new(&[(pass * iterations + count) as u8; 32]);
let key = Pubkey::from([(pass * iterations + count) as u8; 32]);
let hash = Hash::new(&[(pass * iterations + count + i + 1) as u8; 32]);
(key, hash)
})
@ -1971,7 +1971,7 @@ pub mod tests {
let data = [CalculateHashIntermediate::new(
Hash::default(),
1,
Pubkey::new(&[1u8; 32]),
Pubkey::from([1u8; 32]),
)];
let data2 = vec![&data[..]];
let bins = 1;
@ -1983,21 +1983,21 @@ pub mod tests {
let data = [CalculateHashIntermediate::new(
Hash::default(),
1,
Pubkey::new(&[255u8; 32]),
Pubkey::from([255u8; 32]),
)];
let data2 = vec![&data[..]];
let result = AccountsHasher::get_binned_data(&data2, bins, &(0..bins));
assert_eq!(result, vec![vec![&data[0..0], &data[..]]]);
let data = [
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::new(&[254u8; 32])),
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::new(&[255u8; 32])),
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::from([254u8; 32])),
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::from([255u8; 32])),
];
let data2 = vec![&data[..]];
let result = AccountsHasher::get_binned_data(&data2, bins, &(0..bins));
assert_eq!(result, vec![vec![&data[0..0], &data[..]]]);
let data = [
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::new(&[1u8; 32])),
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::new(&[255u8; 32])),
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::from([1u8; 32])),
CalculateHashIntermediate::new(Hash::default(), 1, Pubkey::from([255u8; 32])),
];
let data2 = vec![&data[..]];
let result = AccountsHasher::get_binned_data(&data2, bins, &(0..bins));

View File

@ -3929,8 +3929,8 @@ pub mod tests {
);
assert_eq!((0, usize::MAX), iter.bin_start_and_range());
let key_0 = Pubkey::new(&[0; 32]);
let key_ff = Pubkey::new(&[0xff; 32]);
let key_0 = Pubkey::from([0; 32]);
let key_ff = Pubkey::from([0xff; 32]);
let iter = AccountsIndexIterator::new(
&index,
@ -4207,7 +4207,7 @@ pub mod tests {
assert_eq!(iter.start_bin(), 0); // no range, so 0
assert_eq!(iter.end_bin_inclusive(), usize::MAX); // no range, so max
let key = Pubkey::new(&[0; 32]);
let key = Pubkey::from([0; 32]);
let iter = AccountsIndexIterator::new(
&index,
Some(&RangeInclusive::new(key, key)),
@ -4230,7 +4230,7 @@ pub mod tests {
assert_eq!(iter.start_bin(), 0); // start at pubkey 0, so 0
assert_eq!(iter.end_bin_inclusive(), 0); // end at pubkey 0, so 0
let key = Pubkey::new(&[0xff; 32]);
let key = Pubkey::from([0xff; 32]);
let iter = AccountsIndexIterator::new(
&index,
Some(&RangeInclusive::new(key, key)),

View File

@ -119,14 +119,14 @@ pub mod tests {
#[test]
fn test_accounts_to_store_more() {
let pubkey = Pubkey::new(&[1; 32]);
let pubkey = Pubkey::from([1; 32]);
let account_size = 3;
let account = AccountSharedData::default();
let account_meta = AccountMeta {
lamports: 1,
owner: Pubkey::new(&[2; 32]),
owner: Pubkey::from([2; 32]),
executable: false,
rent_epoch: 0,
};

View File

@ -848,7 +848,7 @@ pub mod tests {
// for (Slot, &'a [(&'a Pubkey, &'a T)], IncludeSlotInHash)
let account = AccountSharedData::default();
let slot = 0 as Slot;
let pubkeys = vec![Pubkey::new(&[5; 32]), Pubkey::new(&[6; 32])];
let pubkeys = vec![Pubkey::from([5; 32]), Pubkey::from([6; 32])];
let hashes = vec![Hash::new(&[3; 32]), Hash::new(&[4; 32])];
let write_versions = vec![42, 43];
let accounts = vec![(&pubkeys[0], &account), (&pubkeys[1], &account)];

View File

@ -9003,7 +9003,7 @@ pub(crate) mod tests {
#[allow(clippy::cognitive_complexity)]
fn test_rent_complex() {
solana_logger::setup();
let mock_program_id = Pubkey::new(&[2u8; 32]);
let mock_program_id = Pubkey::from([2u8; 32]);
#[derive(Serialize, Deserialize)]
enum MockInstruction {
@ -9977,7 +9977,7 @@ pub(crate) mod tests {
solana_logger::setup();
for skip_rewrites in [false, true] {
let zero_lamport_pubkey = Pubkey::new(&[0; 32]);
let zero_lamport_pubkey = Pubkey::from([0; 32]);
let genesis_bank = create_simple_test_arc_bank(100000);
let mut first_bank = new_from_parent(&genesis_bank);
@ -12612,7 +12612,7 @@ pub(crate) mod tests {
let bank0 = Arc::new(new_from_parent(&parent));
let pubkey0 = solana_sdk::pubkey::new_rand();
let program_id = Pubkey::new(&[2; 32]);
let program_id = Pubkey::from([2; 32]);
let account0 = AccountSharedData::new(1, 0, &program_id);
bank0.store_account(&pubkey0, &account0);
@ -12795,7 +12795,7 @@ pub(crate) mod tests {
let mut bank = Bank::new_for_tests(&genesis_config);
fn mock_vote_program_id() -> Pubkey {
Pubkey::new(&[42u8; 32])
Pubkey::from([42u8; 32])
}
fn mock_vote_processor(
_first_instruction_account: IndexOfAccount,
@ -13374,7 +13374,7 @@ pub(crate) mod tests {
let blockhash = bank.last_blockhash();
bank.store_account(&nonce.pubkey(), &nonce_account);
let ix = system_instruction::assign(&nonce.pubkey(), &Pubkey::new(&[9u8; 32]));
let ix = system_instruction::assign(&nonce.pubkey(), &Pubkey::from([9u8; 32]));
let message = Message::new(&[ix], Some(&nonce.pubkey()));
let tx = Transaction::new(&[&nonce], message, blockhash);
@ -14068,7 +14068,7 @@ pub(crate) mod tests {
let keypair = Keypair::new();
let pubkey0 = solana_sdk::pubkey::new_rand();
let pubkey1 = solana_sdk::pubkey::new_rand();
let program_id = Pubkey::new(&[2; 32]);
let program_id = Pubkey::from([2; 32]);
let keypair_account = AccountSharedData::new(8, 0, &program_id);
let account0 = AccountSharedData::new(11, 0, &program_id);
let program_account = AccountSharedData::new(1, 10, &Pubkey::default());
@ -14222,7 +14222,7 @@ pub(crate) mod tests {
Ok(())
}
let mock_program_id = Pubkey::new(&[2u8; 32]);
let mock_program_id = Pubkey::from([2u8; 32]);
bank.add_builtin("mock_program", &mock_program_id, mock_process_instruction);
let from_pubkey = solana_sdk::pubkey::new_rand();
@ -14266,7 +14266,7 @@ pub(crate) mod tests {
Ok(())
}
let mock_program_id = Pubkey::new(&[2u8; 32]);
let mock_program_id = Pubkey::from([2u8; 32]);
bank.add_builtin("mock_program", &mock_program_id, mock_process_instruction);
let from_pubkey = solana_sdk::pubkey::new_rand();
@ -14686,7 +14686,7 @@ pub(crate) mod tests {
let mut genesis_config = GenesisConfig::new(
&[(
Pubkey::new(&[42; 32]),
Pubkey::from([42; 32]),
AccountSharedData::new(1_000_000_000_000, 0, &system_program::id()),
)],
&[],
@ -14804,8 +14804,8 @@ pub(crate) mod tests {
solana_logger::setup();
let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000_000);
let pubkey0 = Pubkey::new(&[0; 32]);
let pubkey1 = Pubkey::new(&[1; 32]);
let pubkey0 = Pubkey::from([0; 32]);
let pubkey1 = Pubkey::from([1; 32]);
info!("pubkey0: {}", pubkey0);
info!("pubkey1: {}", pubkey1);
@ -17710,12 +17710,12 @@ pub(crate) mod tests {
);
let mut bank = Bank::new_for_tests(&genesis_config);
let mock_program_id = Pubkey::new(&[2u8; 32]);
let mock_program_id = Pubkey::from([2u8; 32]);
fn mock_process_instruction(
_first_instruction_account: IndexOfAccount,
invoke_context: &mut InvokeContext,
) -> result::Result<(), InstructionError> {
let mock_program_id = Pubkey::new(&[2u8; 32]);
let mock_program_id = Pubkey::from([2u8; 32]);
let transaction_context = &mut invoke_context.transaction_context;
let instruction_context = transaction_context.get_current_instruction_context()?;
let instruction_data = instruction_context.get_instruction_data();
@ -19981,8 +19981,8 @@ pub(crate) mod tests {
assert!(bank.get_rent_paying_pubkeys(&(0, 2, n)).is_none());
assert!(bank.get_rent_paying_pubkeys(&(0, 0, n)).is_none());
let pk1 = Pubkey::new(&[2; 32]);
let pk2 = Pubkey::new(&[3; 32]);
let pk1 = Pubkey::from([2; 32]);
let pk2 = Pubkey::from([3; 32]);
let index1 = Bank::partition_from_pubkey(&pk1, n);
let index2 = Bank::partition_from_pubkey(&pk2, n);
assert!(index1 > 0, "{}", index1);

View File

@ -795,12 +795,12 @@ impl<T: IndexValue> InMemAccountsIndex<T> {
assert!(!only_add_if_already_held || start_holding);
let start = match range.start_bound() {
Bound::Included(bound) | Bound::Excluded(bound) => *bound,
Bound::Unbounded => Pubkey::new(&[0; 32]),
Bound::Unbounded => Pubkey::from([0; 32]),
};
let end = match range.end_bound() {
Bound::Included(bound) | Bound::Excluded(bound) => *bound,
Bound::Unbounded => Pubkey::new(&[0xff; 32]),
Bound::Unbounded => Pubkey::from([0xff; 32]),
};
// this becomes inclusive - that is ok - we are just roughly holding a range of items.
@ -1593,10 +1593,10 @@ mod tests {
fn test_hold_range_in_memory() {
let bucket = new_disk_buckets_for_test::<u64>();
// 0x81 is just some other range
let all = Pubkey::new(&[0; 32])..=Pubkey::new(&[0xff; 32]);
let all = Pubkey::from([0; 32])..=Pubkey::from([0xff; 32]);
let ranges = [
all.clone(),
Pubkey::new(&[0x81; 32])..=Pubkey::new(&[0xff; 32]),
Pubkey::from([0x81; 32])..=Pubkey::from([0xff; 32]),
];
for range in ranges.clone() {
assert!(bucket.cache_ranges_held.read().unwrap().is_empty());

View File

@ -481,7 +481,7 @@ mod tests {
}
}
let mock_program_id = Pubkey::new(&[2u8; 32]);
let mock_program_id = Pubkey::from([2u8; 32]);
let rent_collector = RentCollector::default();
let builtin_programs = &[BuiltinProgram {
program_id: mock_program_id,

View File

@ -37,7 +37,7 @@ impl PubkeyBinCalculator24 {
pub fn lowest_pubkey_from_bin(&self, mut bin: usize, bins: usize) -> Pubkey {
assert!(bin < bins);
bin <<= self.shift_bits;
let mut pubkey = Pubkey::new(&[0; 32]);
let mut pubkey = Pubkey::from([0; 32]);
pubkey.as_mut()[0] = ((bin / 256 / 256) & 0xff) as u8;
pubkey.as_mut()[1] = ((bin / 256) & 0xff) as u8;
pubkey.as_mut()[2] = (bin & 0xff) as u8;
@ -75,7 +75,7 @@ pub mod tests {
#[test]
fn test_pubkey_bins_pubkeys() {
let mut pk = Pubkey::new(&[0; 32]);
let mut pk = Pubkey::from([0; 32]);
for i in 0..=8 {
let bins = 2usize.pow(i);
let calc = PubkeyBinCalculator24::new(bins);
@ -106,7 +106,7 @@ pub mod tests {
}
for i in 9..=16 {
let mut pk = Pubkey::new(&[0; 32]);
let mut pk = Pubkey::from([0; 32]);
let bins = 2usize.pow(i);
let calc = PubkeyBinCalculator24::new(bins);
@ -118,7 +118,7 @@ pub mod tests {
pk.as_mut()[1] = 0xff;
assert_eq!(bins - 1, calc.bin_from_pubkey(&pk));
let mut pk = Pubkey::new(&[0; 32]);
let mut pk = Pubkey::from([0; 32]);
for bin in 0..bins {
let mut target = (bin << shift_bits) as u16;
pk.as_mut()[0] = (target / 256) as u8;
@ -142,7 +142,7 @@ pub mod tests {
}
for i in 17..=24 {
let mut pk = Pubkey::new(&[0; 32]);
let mut pk = Pubkey::from([0; 32]);
let bins = 2usize.pow(i);
let calc = PubkeyBinCalculator24::new(bins);
@ -155,7 +155,7 @@ pub mod tests {
pk.as_mut()[2] = 0xff;
assert_eq!(bins - 1, calc.bin_from_pubkey(&pk));
let mut pk = Pubkey::new(&[0; 32]);
let mut pk = Pubkey::from([0; 32]);
for bin in 0..bins {
let mut target = (bin << shift_bits) as u32;
pk.as_mut()[0] = (target / 256 / 256) as u8;

View File

@ -64,7 +64,7 @@ pub(crate) mod tests {
#[test]
fn test_add() {
let mut test = RentPayingAccountsByPartition::new(&EpochSchedule::custom(32, 0, false));
let pk = Pubkey::new(&[1; 32]);
let pk = Pubkey::from([1; 32]);
test.add_account(&pk);
// make sure duplicate adds only result in a single item
test.add_account(&pk);

View File

@ -238,7 +238,7 @@ pub mod tests {
#[test]
fn test_contains_multiple_slots() {
let pk = Pubkey::new(&[1; 32]);
let pk = Pubkey::from([1; 32]);
let slot = 0;
let lamports = 1;
let owner = Pubkey::default();
@ -288,7 +288,7 @@ pub mod tests {
let mut raw = Vec::new();
let mut raw2 = Vec::new();
for entry in 0..entries {
let pk = Pubkey::new(&[entry; 32]);
let pk = Pubkey::from([entry; 32]);
let account = AccountSharedData::create(
(entry as u64) * starting_slot,
Vec::default(),

View File

@ -664,7 +664,7 @@ mod tests {
#[test]
fn test_create_account() {
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let to = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &system_program::id());
@ -701,7 +701,7 @@ mod tests {
#[test]
fn test_create_account_with_seed() {
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let seed = "shiny pepper";
let to = Pubkey::create_with_seed(&from, seed, &new_owner).unwrap();
@ -741,7 +741,7 @@ mod tests {
#[test]
fn test_create_account_with_seed_separate_base_account() {
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let base = Pubkey::new_unique();
let seed = "shiny pepper";
@ -804,7 +804,7 @@ mod tests {
#[test]
fn test_create_account_with_seed_missing_sig() {
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let seed = "dull boy";
let to = Pubkey::create_with_seed(&from, seed, &new_owner).unwrap();
@ -841,7 +841,7 @@ mod tests {
#[test]
fn test_create_with_zero_lamports() {
// create account with zero lamports transferred
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &Pubkey::new_unique()); // not from system account
let to = Pubkey::new_unique();
@ -879,7 +879,7 @@ mod tests {
#[test]
fn test_create_negative_lamports() {
// Attempt to create account with more lamports than from_account has
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &Pubkey::new_unique());
let to = Pubkey::new_unique();
@ -962,13 +962,13 @@ mod tests {
#[test]
fn test_create_already_in_use() {
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &system_program::id());
let owned_key = Pubkey::new_unique();
// Attempt to create system account in account already owned by another program
let original_program_owner = Pubkey::new(&[5; 32]);
let original_program_owner = Pubkey::from([5; 32]);
let owned_account = AccountSharedData::new(0, 0, &original_program_owner);
let unchanged_account = owned_account.clone();
let accounts = process_instruction(
@ -1059,7 +1059,7 @@ mod tests {
#[test]
fn test_create_unsigned() {
// Attempt to create an account without signing the transfer
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &system_program::id());
let owned_key = Pubkey::new_unique();
@ -1182,7 +1182,7 @@ mod tests {
#[test]
fn test_create_data_populated() {
// Attempt to create system account in account with populated data
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let from = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &system_program::id());
let populated_key = Pubkey::new_unique();
@ -1255,7 +1255,7 @@ mod tests {
#[test]
fn test_assign() {
let new_owner = Pubkey::new(&[9; 32]);
let new_owner = Pubkey::from([9; 32]);
let pubkey = Pubkey::new_unique();
let account = AccountSharedData::new(100, 0, &system_program::id());
@ -1354,7 +1354,7 @@ mod tests {
fn test_transfer_lamports() {
let from = Pubkey::new_unique();
let from_account = AccountSharedData::new(100, 0, &system_program::id());
let to = Pubkey::new(&[3; 32]);
let to = Pubkey::from([3; 32]);
let to_account = AccountSharedData::new(1, 0, &to); // account owner should not matter
let transaction_accounts = vec![(from, from_account), (to, to_account)];
let instruction_accounts = vec![
@ -1429,12 +1429,12 @@ mod tests {
#[test]
fn test_transfer_with_seed() {
let base = Pubkey::new_unique();
let base_account = AccountSharedData::new(100, 0, &Pubkey::new(&[2; 32])); // account owner should not matter
let base_account = AccountSharedData::new(100, 0, &Pubkey::from([2; 32])); // account owner should not matter
let from_seed = "42".to_string();
let from_owner = system_program::id();
let from = Pubkey::create_with_seed(&base, from_seed.as_str(), &from_owner).unwrap();
let from_account = AccountSharedData::new(100, 0, &system_program::id());
let to = Pubkey::new(&[3; 32]);
let to = Pubkey::from([3; 32]);
let to_account = AccountSharedData::new(1, 0, &to); // account owner should not matter
let transaction_accounts =
vec![(from, from_account), (base, base_account), (to, to_account)];
@ -1521,7 +1521,7 @@ mod tests {
get_system_account_kind(&from_account),
Some(SystemAccountKind::Nonce)
);
let to = Pubkey::new(&[3; 32]);
let to = Pubkey::from([3; 32]);
let to_account = AccountSharedData::new(1, 0, &to); // account owner should not matter
process_instruction(

View File

@ -213,8 +213,8 @@ mod tests {
assert_eq!(FeeCalculator::new(1).calculate_fee(&message), 0);
// One signature, a fee.
let pubkey0 = Pubkey::new(&[0; 32]);
let pubkey1 = Pubkey::new(&[1; 32]);
let pubkey0 = Pubkey::from([0; 32]);
let pubkey1 = Pubkey::from([1; 32]);
let ix0 = system_instruction::transfer(&pubkey0, &pubkey1, 1);
let message = Message::new(&[ix0], Some(&pubkey0));
assert_eq!(FeeCalculator::new(2).calculate_fee(&message), 2);
@ -230,8 +230,8 @@ mod tests {
#[allow(deprecated)]
fn test_fee_calculator_calculate_fee_secp256k1() {
use crate::instruction::Instruction;
let pubkey0 = Pubkey::new(&[0; 32]);
let pubkey1 = Pubkey::new(&[1; 32]);
let pubkey0 = Pubkey::from([0; 32]);
let pubkey1 = Pubkey::from([1; 32]);
let ix0 = system_instruction::transfer(&pubkey0, &pubkey1, 1);
let mut secp_instruction = Instruction {
program_id: crate::secp256k1_program::id(),

View File

@ -121,17 +121,36 @@ impl FromStr for Pubkey {
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
Err(ParsePubkeyError::WrongSize)
} else {
Ok(Pubkey::new(&pubkey_vec))
Pubkey::try_from(pubkey_vec).map_err(|_| ParsePubkeyError::Invalid)
}
}
}
impl From<[u8; 32]> for Pubkey {
#[inline]
fn from(from: [u8; 32]) -> Self {
Self(from)
}
}
impl TryFrom<&[u8]> for Pubkey {
type Error = std::array::TryFromSliceError;
#[inline]
fn try_from(pubkey: &[u8]) -> Result<Self, Self::Error> {
<[u8; 32]>::try_from(pubkey).map(Self::from)
}
}
impl TryFrom<Vec<u8>> for Pubkey {
type Error = Vec<u8>;
#[inline]
fn try_from(pubkey: Vec<u8>) -> Result<Self, Self::Error> {
<[u8; 32]>::try_from(pubkey).map(Self::from)
}
}
impl TryFrom<&str> for Pubkey {
type Error = ParsePubkeyError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
@ -151,11 +170,12 @@ pub fn bytes_are_curve_point<T: AsRef<[u8]>>(_bytes: T) -> bool {
}
impl Pubkey {
#[deprecated(
since = "1.14.14",
note = "Please use 'Pubkey::from' or 'Pubkey::try_from' instead"
)]
pub fn new(pubkey_vec: &[u8]) -> Self {
Self(
<[u8; 32]>::try_from(<&[u8]>::clone(&pubkey_vec))
.expect("Slice must be the same length as a Pubkey"),
)
Self::try_from(pubkey_vec).expect("Slice must be the same length as a Pubkey")
}
pub const fn new_from_array(pubkey_array: [u8; 32]) -> Self {
@ -166,7 +186,7 @@ impl Pubkey {
#[cfg(not(target_os = "solana"))]
pub fn new_rand() -> Self {
// Consider removing Pubkey::new_rand() entirely in the v1.5 or v1.6 timeframe
Pubkey::new(&rand::random::<[u8; 32]>())
Pubkey::from(rand::random::<[u8; 32]>())
}
/// unique Pubkey for tests and benchmarks.
@ -179,7 +199,7 @@ impl Pubkey {
// use big endian representation to ensure that recent unique pubkeys
// are always greater than less recent unique pubkeys
b[0..8].copy_from_slice(&i.to_be_bytes());
Self::new(&b)
Self::from(b)
}
pub fn create_with_seed(
@ -198,10 +218,8 @@ impl Pubkey {
return Err(PubkeyError::IllegalOwner);
}
}
Ok(Pubkey::new(
hashv(&[base.as_ref(), seed.as_ref(), owner]).as_ref(),
))
let hash = hashv(&[base.as_ref(), seed.as_ref(), owner]);
Ok(Pubkey::from(hash.to_bytes()))
}
/// Find a valid [program derived address][pda] and its corresponding bump seed.
@ -508,7 +526,7 @@ impl Pubkey {
)
};
match result {
crate::entrypoint::SUCCESS => Some((Pubkey::new(&bytes), bump_seed)),
crate::entrypoint::SUCCESS => Some((Pubkey::from(bytes), bump_seed)),
_ => None,
}
}
@ -584,7 +602,7 @@ impl Pubkey {
return Err(PubkeyError::InvalidSeeds);
}
Ok(Pubkey::new(hash.as_ref()))
Ok(Pubkey::from(hash.to_bytes()))
}
// Call via a system call to perform the calculation
#[cfg(target_os = "solana")]
@ -599,7 +617,7 @@ impl Pubkey {
)
};
match result {
crate::entrypoint::SUCCESS => Ok(Pubkey::new(&bytes)),
crate::entrypoint::SUCCESS => Ok(Pubkey::from(bytes)),
_ => Err(result.into()),
}
}

View File

@ -37,7 +37,8 @@ pub fn read_pubkey(current: &mut usize, data: &[u8]) -> Result<Pubkey, SanitizeE
if data.len() < *current + len {
return Err(SanitizeError::IndexOutOfBounds);
}
let e = Pubkey::new(&data[*current..*current + len]);
let e = Pubkey::try_from(&data[*current..*current + len])
.map_err(|_| SanitizeError::ValueOutOfBounds)?;
*current += len;
Ok(e)
}

View File

@ -34,7 +34,8 @@ impl Pubkey {
if let Some(base58_str) = value.as_string() {
base58_str.parse::<Pubkey>().map_err(display_to_jsvalue)
} else if let Some(uint8_array) = value.dyn_ref::<Uint8Array>() {
Ok(Pubkey::new(&uint8_array.to_vec()))
Pubkey::try_from(uint8_array.to_vec())
.map_err(|err| JsValue::from(format!("Invalid Uint8Array pubkey: {err:?}")))
} else if let Some(array) = value.dyn_ref::<Array>() {
let mut bytes = vec![];
let iterator = js_sys::try_iter(&array.values())?.expect("array to be iterable");
@ -49,7 +50,8 @@ impl Pubkey {
}
return Err(format!("Invalid array argument: {:?}", x).into());
}
Ok(Pubkey::new(&bytes))
Pubkey::try_from(bytes)
.map_err(|err| JsValue::from(format!("Invalid Array pubkey: {err:?}")))
} else if value.is_undefined() {
Ok(Pubkey::default())
} else {

View File

@ -5,7 +5,7 @@ pub use solana_program::pubkey::*;
/// New random Pubkey for tests and benchmarks.
#[cfg(feature = "full")]
pub fn new_rand() -> Pubkey {
Pubkey::new(&rand::random::<[u8; PUBKEY_BYTES]>())
Pubkey::from(rand::random::<[u8; PUBKEY_BYTES]>())
}
#[cfg(feature = "full")]

View File

@ -179,7 +179,7 @@ mod tests {
let off_curve_point = curve25519_dalek::edwards::CompressedEdwardsY(off_curve_bits);
assert_eq!(off_curve_point.decompress(), None);
let pubkey = Pubkey::new(&off_curve_bytes);
let pubkey = Pubkey::try_from(off_curve_bytes).unwrap();
let signature = Signature::default();
// Unfortunately, ed25519-dalek doesn't surface the internal error types that we'd ideally
// `source()` out of the `SignatureError` returned by `verify_strict()`. So the best we

View File

@ -83,7 +83,7 @@ impl Keypair {
impl Signer for Keypair {
fn pubkey(&self) -> Pubkey {
Pubkey::new(self.0.public.as_ref())
Pubkey::from(self.0.public.to_bytes())
}
fn try_pubkey(&self) -> Result<Pubkey, SignerError> {

View File

@ -1270,12 +1270,12 @@ mod tests {
62, 89, 99,
])
.unwrap();
let to = Pubkey::new(&[
let to = Pubkey::from([
1, 1, 1, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 7, 6, 5, 4,
1, 1, 1,
]);
let program_id = Pubkey::new(&[
let program_id = Pubkey::from([
2, 2, 2, 4, 5, 6, 7, 8, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 8, 7, 6, 5, 4,
2, 2, 2,
]);

View File

@ -304,7 +304,7 @@ impl From<generated::Message> for VersionedMessage {
let account_keys = value
.account_keys
.into_iter()
.map(|key| Pubkey::new(&key))
.map(|key| Pubkey::try_from(key).unwrap())
.collect();
let recent_blockhash = Hash::new(&value.recent_blockhash);
let instructions = value.instructions.into_iter().map(|ix| ix.into()).collect();
@ -496,12 +496,20 @@ impl TryFrom<generated::TransactionStatusMeta> for TransactionStatusMeta {
let loaded_addresses = LoadedAddresses {
writable: loaded_writable_addresses
.into_iter()
.map(|key| Pubkey::new(&key))
.collect(),
.map(Pubkey::try_from)
.collect::<Result<_, _>>()
.map_err(|err| {
let err = format!("Invalid writable address: {err:?}");
Self::Error::new(bincode::ErrorKind::Custom(err))
})?,
readonly: loaded_readonly_addresses
.into_iter()
.map(|key| Pubkey::new(&key))
.collect(),
.map(Pubkey::try_from)
.collect::<Result<_, _>>()
.map_err(|err| {
let err = format!("Invalid readonly address: {err:?}");
Self::Error::new(bincode::ErrorKind::Custom(err))
})?,
};
let return_data = if return_data_none {
None
@ -602,7 +610,7 @@ impl From<MessageAddressTableLookup> for generated::MessageAddressTableLookup {
impl From<generated::MessageAddressTableLookup> for MessageAddressTableLookup {
fn from(value: generated::MessageAddressTableLookup) -> Self {
Self {
account_key: Pubkey::new(&value.account_key),
account_key: Pubkey::try_from(value.account_key).unwrap(),
writable_indexes: value.writable_indexes,
readonly_indexes: value.readonly_indexes,
}
@ -621,7 +629,7 @@ impl From<TransactionReturnData> for generated::ReturnData {
impl From<generated::ReturnData> for TransactionReturnData {
fn from(value: generated::ReturnData) -> Self {
Self {
program_id: Pubkey::new(&value.program_id),
program_id: Pubkey::try_from(value.program_id).unwrap(),
data: value.data,
}
}

View File

@ -56,14 +56,11 @@ pub fn new_self_signed_tls_certificate(
}
pub fn get_pubkey_from_tls_certificate(der_cert: &rustls::Certificate) -> Option<Pubkey> {
X509Certificate::from_der(der_cert.as_ref())
.ok()
.and_then(|(_, cert)| {
cert.public_key().parsed().ok().and_then(|key| match key {
PublicKey::Unknown(inner_key) => Some(Pubkey::new(inner_key)),
_ => None,
})
})
let (_, cert) = X509Certificate::from_der(der_cert.as_ref()).ok()?;
match cert.public_key().parsed().ok()? {
PublicKey::Unknown(key) => Pubkey::try_from(key).ok(),
_ => None,
}
}
#[cfg(test)]

View File

@ -198,7 +198,7 @@ mod test {
}
);
let non_parsable_program_id = Pubkey::new(&[1; 32]);
let non_parsable_program_id = Pubkey::from([1; 32]);
assert!(parse(&non_parsable_program_id, &memo_instruction, &no_keys, None).is_err());
}