diff --git a/account-decoder/src/parse_token.rs b/account-decoder/src/parse_token.rs index ca75ffe65bdf7b..90177ac66dc87b 100644 --- a/account-decoder/src/parse_token.rs +++ b/account-decoder/src/parse_token.rs @@ -282,11 +282,9 @@ pub struct UiMultisig { } pub fn get_token_account_mint(data: &[u8]) -> Option { - 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) diff --git a/cli-output/src/cli_output.rs b/cli-output/src/cli_output.rs index d8ffec92498549..142816bf11954d 100644 --- a/cli-output/src/cli_output.rs +++ b/cli-output/src/cli_output.rs @@ -2926,10 +2926,10 @@ mod tests { } let present: Box = Box::new(keypair_from_seed(&[2u8; 32]).unwrap()); - let absent: Box = Box::new(NullSigner::new(&Pubkey::new(&[3u8; 32]))); - let bad: Box = Box::new(BadSigner::new(Pubkey::new(&[4u8; 32]))); - let to = Pubkey::new(&[5u8; 32]); - let nonce = Pubkey::new(&[6u8; 32]); + let absent: Box = Box::new(NullSigner::new(&Pubkey::from([3u8; 32]))); + let bad: Box = 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(); diff --git a/cli/src/checks.rs b/cli/src/checks.rs index ea23c1b9cdfd13..bf31f9d51d64ff 100644 --- a/cli/src/checks.rs +++ b/cli/src/checks.rs @@ -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); diff --git a/cli/src/cli.rs b/cli/src/cli.rs index 99fb3ca00b80ed..59f38038a53387 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -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"); diff --git a/cli/src/memo.rs b/cli/src/memo.rs index 1043415357b338..53a126a450dad2 100644 --- a/cli/src/memo.rs +++ b/cli/src/memo.rs @@ -12,7 +12,7 @@ impl WithMemo for Vec { 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(), }; diff --git a/cli/src/nonce.rs b/cli/src/nonce.rs index 61a1824e9f1242..533f64139ff37a 100644 --- a/cli/src/nonce.rs +++ b/cli/src/nonce.rs @@ -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(); diff --git a/cli/src/stake.rs b/cli/src/stake.rs index a7731405381b8b..deddf382c486f3 100644 --- a/cli/src/stake.rs +++ b/cli/src/stake.rs @@ -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(); diff --git a/cli/tests/nonce.rs b/cli/tests/nonce.rs index d4160ad6abd9e5..3fd93e18576f41 100644 --- a/cli/tests/nonce.rs +++ b/cli/tests/nonce.rs @@ -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 = diff --git a/cli/tests/transfer.rs b/cli/tests/transfer.rs index 76d44f0c1197fc..03c731c723c294 100644 --- a/cli/tests/transfer.rs +++ b/cli/tests/transfer.rs @@ -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( diff --git a/faucet/src/faucet.rs b/faucet/src/faucet.rs index c38dc8d437e9cb..615b314d9bd852 100644 --- a/faucet/src/faucet.rs +++ b/faucet/src/faucet.rs @@ -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); diff --git a/genesis/src/stakes.rs b/genesis/src/stakes.rs index 4fbb6d34d68daf..c48a3ec86326d5 100644 --- a/genesis/src/stakes.rs +++ b/genesis/src/stakes.rs @@ -216,7 +216,7 @@ mod tests { // print( // "\n\"{}\", // {:?}", // hex, - // Pubkey::new(&hex::decode(hex).unwrap()) + // Pubkey::try_from(&hex::decode(hex).unwrap()).unwrap() // ); // }); // println(); diff --git a/gossip/src/cluster_info.rs b/gossip/src/cluster_info.rs index bcb1bd14861618..47a532f198725b 100644 --- a/gossip/src/cluster_info.rs +++ b/gossip/src/cluster_info.rs @@ -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); diff --git a/gossip/src/crds_gossip.rs b/gossip/src/crds_gossip.rs index 076fdb6b755712..a77d785c810281 100644 --- a/gossip/src/crds_gossip.rs +++ b/gossip/src/crds_gossip.rs @@ -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, diff --git a/gossip/tests/crds_gossip.rs b/gossip/tests/crds_gossip.rs index 0cac130cb75f6f..326713185a60fc 100644 --- a/gossip/tests/crds_gossip.rs +++ b/gossip/tests/crds_gossip.rs @@ -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::::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, diff --git a/ledger/src/blockstore.rs b/ledger/src/blockstore.rs index 6f8263e3f7740e..c0d59c8e011d31 100644 --- a/ledger/src/blockstore.rs +++ b/ledger/src/blockstore.rs @@ -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(); diff --git a/ledger/src/blockstore/blockstore_purge.rs b/ledger/src/blockstore/blockstore_purge.rs index 00b8ced4fac9de..8504842f06a972 100644 --- a/ledger/src/blockstore/blockstore_purge.rs +++ b/ledger/src/blockstore/blockstore_purge.rs @@ -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(); diff --git a/ledger/src/blockstore_db.rs b/ledger/src/blockstore_db.rs index c020986e0b693f..3945967fe68894 100644 --- a/ledger/src/blockstore_db.rs +++ b/ledger/src/blockstore_db.rs @@ -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 { diff --git a/remote-wallet/src/ledger.rs b/remote-wallet/src/ledger.rs index 93b90098f4f89c..6834a7afb4af34 100644 --- a/remote-wallet/src/ledger.rs +++ b/remote-wallet/src/ledger.rs @@ -420,10 +420,7 @@ impl RemoteWallet 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( diff --git a/rpc-client-nonce-utils/src/blockhash_query.rs b/rpc-client-nonce-utils/src/blockhash_query.rs index 158873bc5ce5a4..08a296a70b7125 100644 --- a/rpc-client-nonce-utils/src/blockhash_query.rs +++ b/rpc-client-nonce-utils/src/blockhash_query.rs @@ -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, diff --git a/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs b/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs index a7ca89dd36441d..879bfe5f622441 100644 --- a/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs +++ b/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs @@ -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, diff --git a/rpc/src/rpc.rs b/rpc/src/rpc.rs index 14af32ec643389..7a4ac47192de74 100644 --- a/rpc/src/rpc.rs +++ b/rpc/src/rpc.rs @@ -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()); } diff --git a/rpc/src/transaction_status_service.rs b/rpc/src/transaction_status_service.rs index dcf013b9883f3c..9fbfe879e271a0 100644 --- a/rpc/src/transaction_status_service.rs +++ b/rpc/src/transaction_status_service.rs @@ -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, diff --git a/runtime/benches/bank.rs b/runtime/benches/bank.rs index a946bcafa3f03f..f2c91ca93720d3 100644 --- a/runtime/benches/bank.rs +++ b/runtime/benches/bank.rs @@ -48,7 +48,7 @@ pub fn create_builtin_transactions( bank_client: &BankClient, mint_keypair: &Keypair, ) -> Vec { - 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 { - 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); diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index 9a7ffbde1e917c..ddf41e1ec27ada 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -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, diff --git a/runtime/src/accounts_db.rs b/runtime/src/accounts_db.rs index cc74cc3cad92d2..886fe69fbbefa5 100644 --- a/runtime/src/accounts_db.rs +++ b/runtime/src/accounts_db.rs @@ -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>, Vec, ) { - 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]); } diff --git a/runtime/src/accounts_hash.rs b/runtime/src/accounts_hash.rs index 78776ff140d3bf..ba298c26433c07 100644 --- a/runtime/src/accounts_hash.rs +++ b/runtime/src/accounts_hash.rs @@ -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)); diff --git a/runtime/src/accounts_index.rs b/runtime/src/accounts_index.rs index 80ae44da2741c8..a1a34df8da87c8 100644 --- a/runtime/src/accounts_index.rs +++ b/runtime/src/accounts_index.rs @@ -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)), diff --git a/runtime/src/ancient_append_vecs.rs b/runtime/src/ancient_append_vecs.rs index 959148f3fb7120..eb5b8114f4870f 100644 --- a/runtime/src/ancient_append_vecs.rs +++ b/runtime/src/ancient_append_vecs.rs @@ -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, }; diff --git a/runtime/src/append_vec.rs b/runtime/src/append_vec.rs index c4630a8ce351aa..bec1d344afd34f 100644 --- a/runtime/src/append_vec.rs +++ b/runtime/src/append_vec.rs @@ -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)]; diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index ce027b61dfbaa6..a942d8256ec4d1 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -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); diff --git a/runtime/src/in_mem_accounts_index.rs b/runtime/src/in_mem_accounts_index.rs index fe328880fd425c..c260d3f9f187d7 100644 --- a/runtime/src/in_mem_accounts_index.rs +++ b/runtime/src/in_mem_accounts_index.rs @@ -795,12 +795,12 @@ impl InMemAccountsIndex { 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::(); // 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()); diff --git a/runtime/src/message_processor.rs b/runtime/src/message_processor.rs index eae848b059a2ba..36e5b15cd92ffc 100644 --- a/runtime/src/message_processor.rs +++ b/runtime/src/message_processor.rs @@ -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, diff --git a/runtime/src/pubkey_bins.rs b/runtime/src/pubkey_bins.rs index c2191cfb731ff3..a3655a41beaa5f 100644 --- a/runtime/src/pubkey_bins.rs +++ b/runtime/src/pubkey_bins.rs @@ -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; diff --git a/runtime/src/rent_paying_accounts_by_partition.rs b/runtime/src/rent_paying_accounts_by_partition.rs index 2a67e2a234ebad..39295aadbf8fd6 100644 --- a/runtime/src/rent_paying_accounts_by_partition.rs +++ b/runtime/src/rent_paying_accounts_by_partition.rs @@ -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); diff --git a/runtime/src/storable_accounts.rs b/runtime/src/storable_accounts.rs index 34fb3eb5667172..312f5e801d5ee0 100644 --- a/runtime/src/storable_accounts.rs +++ b/runtime/src/storable_accounts.rs @@ -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(), diff --git a/runtime/src/system_instruction_processor.rs b/runtime/src/system_instruction_processor.rs index 448cd3b9333020..42b7542159ac0d 100644 --- a/runtime/src/system_instruction_processor.rs +++ b/runtime/src/system_instruction_processor.rs @@ -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( diff --git a/sdk/program/src/fee_calculator.rs b/sdk/program/src/fee_calculator.rs index 6529e1da2a85a1..2628466f713b1b 100644 --- a/sdk/program/src/fee_calculator.rs +++ b/sdk/program/src/fee_calculator.rs @@ -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(), diff --git a/sdk/program/src/pubkey.rs b/sdk/program/src/pubkey.rs index 4cdfe6688d95b0..8e8985b226fc8e 100644 --- a/sdk/program/src/pubkey.rs +++ b/sdk/program/src/pubkey.rs @@ -121,17 +121,36 @@ impl FromStr for Pubkey { if pubkey_vec.len() != mem::size_of::() { 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 { + <[u8; 32]>::try_from(pubkey).map(Self::from) + } +} + +impl TryFrom> for Pubkey { + type Error = Vec; + + #[inline] + fn try_from(pubkey: Vec) -> Result { + <[u8; 32]>::try_from(pubkey).map(Self::from) + } +} + impl TryFrom<&str> for Pubkey { type Error = ParsePubkeyError; fn try_from(s: &str) -> Result { @@ -151,11 +170,12 @@ pub fn bytes_are_curve_point>(_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()), } } diff --git a/sdk/program/src/serialize_utils.rs b/sdk/program/src/serialize_utils.rs index 78003f85777901..a2b61f75d06de9 100644 --- a/sdk/program/src/serialize_utils.rs +++ b/sdk/program/src/serialize_utils.rs @@ -37,7 +37,8 @@ pub fn read_pubkey(current: &mut usize, data: &[u8]) -> Result().map_err(display_to_jsvalue) } else if let Some(uint8_array) = value.dyn_ref::() { - 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::() { 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 { diff --git a/sdk/src/pubkey.rs b/sdk/src/pubkey.rs index 874710ba41cdfe..92d1365d03c5bf 100644 --- a/sdk/src/pubkey.rs +++ b/sdk/src/pubkey.rs @@ -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")] diff --git a/sdk/src/signature.rs b/sdk/src/signature.rs index 02bd3667ab9d33..a3f129ff9e620f 100644 --- a/sdk/src/signature.rs +++ b/sdk/src/signature.rs @@ -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 diff --git a/sdk/src/signer/keypair.rs b/sdk/src/signer/keypair.rs index 3818c5abd7d9f9..cc7af05bf471e8 100644 --- a/sdk/src/signer/keypair.rs +++ b/sdk/src/signer/keypair.rs @@ -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 { diff --git a/sdk/src/transaction/mod.rs b/sdk/src/transaction/mod.rs index 48dcdc695c04f9..e5eb9fdba5e66e 100644 --- a/sdk/src/transaction/mod.rs +++ b/sdk/src/transaction/mod.rs @@ -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, ]); diff --git a/storage-proto/src/convert.rs b/storage-proto/src/convert.rs index a3807a45fe6838..ce800cfe42976d 100644 --- a/storage-proto/src/convert.rs +++ b/storage-proto/src/convert.rs @@ -304,7 +304,7 @@ impl From 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 for TransactionStatusMeta { let loaded_addresses = LoadedAddresses { writable: loaded_writable_addresses .into_iter() - .map(|key| Pubkey::new(&key)) - .collect(), + .map(Pubkey::try_from) + .collect::>() + .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::>() + .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 for generated::MessageAddressTableLookup { impl From 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 for generated::ReturnData { impl From 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, } } diff --git a/streamer/src/tls_certificates.rs b/streamer/src/tls_certificates.rs index f7a1c4c4ac5e98..a5436b1d7c7b50 100644 --- a/streamer/src/tls_certificates.rs +++ b/streamer/src/tls_certificates.rs @@ -56,14 +56,11 @@ pub fn new_self_signed_tls_certificate( } pub fn get_pubkey_from_tls_certificate(der_cert: &rustls::Certificate) -> Option { - 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)] diff --git a/transaction-status/src/parse_instruction.rs b/transaction-status/src/parse_instruction.rs index 5e539ba94e4ec9..9cab2802d149cf 100644 --- a/transaction-status/src/parse_instruction.rs +++ b/transaction-status/src/parse_instruction.rs @@ -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()); }