diff --git a/cli/src/cli.rs b/cli/src/cli.rs index f9a082d2baa73f..50ed961e429198 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -685,7 +685,6 @@ pub fn parse_create_address_with_seed( "STAKE" => solana_stake_program::id(), "VOTE" => solana_vote_program::id(), "STORAGE" => solana_storage_program::id(), - "NONCE" => solana_sdk::nonce_program::id(), _ => pubkey_of(matches, "program_id").unwrap(), }; @@ -1769,7 +1768,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, ' .required(true) .help( "The program_id that the address will ultimately be used for, \n\ - or one of STAKE, VOTE, NONCE, and STORAGE keywords", + or one of STAKE, VOTE, and STORAGE keywords", ), ) .arg( @@ -1985,9 +1984,9 @@ mod tests { }; use solana_sdk::{ account::Account, - nonce_program, nonce_state::{Meta as NonceMeta, NonceState}, signature::{read_keypair_file, write_keypair_file}, + system_program, transaction::TransactionError, }; use std::{collections::HashMap, path::PathBuf}; @@ -2123,7 +2122,6 @@ mod tests { for (name, program_id) in &[ ("STAKE", solana_stake_program::id()), ("VOTE", solana_vote_program::id()), - ("NONCE", solana_sdk::nonce_program::id()), ("STORAGE", solana_storage_program::id()), ] { let test_create_address_with_seed = test_commands.clone().get_matches_from(vec![ @@ -2665,7 +2663,7 @@ mod tests { value: json!(Account::new_data( 1, &NonceState::Initialized(NonceMeta::new(&config.keypair.pubkey()), blockhash), - &nonce_program::ID, + &system_program::ID, ) .unwrap()), }); @@ -2691,7 +2689,7 @@ mod tests { value: json!(Account::new_data( 1, &NonceState::Initialized(NonceMeta::new(&bob_pubkey), blockhash), - &nonce_program::ID, + &system_program::ID, ) .unwrap()), }); diff --git a/cli/src/nonce.rs b/cli/src/nonce.rs index d9d73691d6fe05..0927f798de6c57 100644 --- a/cli/src/nonce.rs +++ b/cli/src/nonce.rs @@ -10,12 +10,14 @@ use solana_sdk::{ account::Account, account_utils::State, hash::Hash, - nonce_instruction::{authorize, create_nonce_account, nonce, withdraw, NonceError}, - nonce_program, nonce_state::NonceState, pubkey::Pubkey, signature::{Keypair, KeypairUtil}, - system_instruction::SystemError, + system_instruction::{ + create_nonce_account, nonce_advance, nonce_authorize, nonce_withdraw, NonceError, + SystemError, + }, + system_program, transaction::Transaction, }; @@ -298,7 +300,7 @@ pub fn check_nonce_account( nonce_authority: &Pubkey, nonce_hash: &Hash, ) -> Result<(), Box> { - if nonce_account.owner != nonce_program::ID { + if nonce_account.owner != system_program::ID { return Err(CliError::InvalidNonce(CliNonceError::InvalidAccountOwner).into()); } let nonce_state: NonceState = nonce_account @@ -330,7 +332,7 @@ pub fn process_authorize_nonce_account( let (recent_blockhash, fee_calculator) = rpc_client.get_recent_blockhash()?; let nonce_authority = nonce_authority.unwrap_or(&config.keypair); - let ix = authorize(nonce_account, &nonce_authority.pubkey(), new_authority); + let ix = nonce_authorize(nonce_account, &nonce_authority.pubkey(), new_authority); let mut tx = Transaction::new_signed_with_payer( vec![ix], Some(&config.keypair.pubkey()), @@ -405,7 +407,7 @@ pub fn process_create_nonce_account( pub fn process_get_nonce(rpc_client: &RpcClient, nonce_account_pubkey: &Pubkey) -> ProcessResult { let nonce_account = rpc_client.get_account(nonce_account_pubkey)?; - if nonce_account.owner != nonce_program::id() { + if nonce_account.owner != system_program::id() { return Err(CliError::RpcRequestError(format!( "{:?} is not a nonce account", nonce_account_pubkey @@ -442,7 +444,7 @@ pub fn process_new_nonce( } let nonce_authority = nonce_authority.unwrap_or(&config.keypair); - let ix = nonce(&nonce_account, &nonce_authority.pubkey()); + let ix = nonce_advance(&nonce_account, &nonce_authority.pubkey()); let (recent_blockhash, fee_calculator) = rpc_client.get_recent_blockhash()?; let mut tx = Transaction::new_signed_with_payer( vec![ix], @@ -467,7 +469,7 @@ pub fn process_show_nonce_account( use_lamports_unit: bool, ) -> ProcessResult { let nonce_account = rpc_client.get_account(nonce_account_pubkey)?; - if nonce_account.owner != nonce_program::id() { + if nonce_account.owner != system_program::id() { return Err(CliError::RpcRequestError(format!( "{:?} is not a nonce account", nonce_account_pubkey @@ -515,7 +517,7 @@ pub fn process_withdraw_from_nonce_account( let (recent_blockhash, fee_calculator) = rpc_client.get_recent_blockhash()?; let nonce_authority = nonce_authority.unwrap_or(&config.keypair); - let ix = withdraw( + let ix = nonce_withdraw( nonce_account, &nonce_authority.pubkey(), destination_account_pubkey, @@ -802,14 +804,14 @@ mod tests { let valid = Account::new_data( 1, &NonceState::Initialized(NonceMeta::new(&nonce_pubkey), blockhash), - &nonce_program::ID, + &system_program::ID, ); assert!(check_nonce_account(&valid.unwrap(), &nonce_pubkey, &blockhash).is_ok()); let invalid_owner = Account::new_data( 1, &NonceState::Initialized(NonceMeta::new(&nonce_pubkey), blockhash), - &system_program::ID, + &Pubkey::new(&[1u8; 32]), ); assert_eq!( check_nonce_account(&invalid_owner.unwrap(), &nonce_pubkey, &blockhash), @@ -818,7 +820,7 @@ mod tests { ))), ); - let invalid_data = Account::new_data(1, &"invalid", &nonce_program::ID); + let invalid_data = Account::new_data(1, &"invalid", &system_program::ID); assert_eq!( check_nonce_account(&invalid_data.unwrap(), &nonce_pubkey, &blockhash), Err(Box::new(CliError::InvalidNonce( @@ -829,7 +831,7 @@ mod tests { let invalid_hash = Account::new_data( 1, &NonceState::Initialized(NonceMeta::new(&nonce_pubkey), hash(b"invalid")), - &nonce_program::ID, + &system_program::ID, ); assert_eq!( check_nonce_account(&invalid_hash.unwrap(), &nonce_pubkey, &blockhash), @@ -839,7 +841,7 @@ mod tests { let invalid_authority = Account::new_data( 1, &NonceState::Initialized(NonceMeta::new(&Pubkey::new_rand()), blockhash), - &nonce_program::ID, + &system_program::ID, ); assert_eq!( check_nonce_account(&invalid_authority.unwrap(), &nonce_pubkey, &blockhash), @@ -848,7 +850,7 @@ mod tests { ))), ); - let invalid_state = Account::new_data(1, &NonceState::Uninitialized, &nonce_program::ID); + let invalid_state = Account::new_data(1, &NonceState::Uninitialized, &system_program::ID); assert_eq!( check_nonce_account(&invalid_state.unwrap(), &nonce_pubkey, &blockhash), Err(Box::new(CliError::InvalidNonce( diff --git a/genesis-programs/src/lib.rs b/genesis-programs/src/lib.rs index a50660da36e45d..bd1e42c6c78c27 100644 --- a/genesis-programs/src/lib.rs +++ b/genesis-programs/src/lib.rs @@ -1,7 +1,6 @@ use solana_sdk::{ clock::Epoch, genesis_config::OperatingMode, inflation::Inflation, - move_loader::solana_move_loader_program, nonce_program::solana_nonce_program, pubkey::Pubkey, - system_program::solana_system_program, + move_loader::solana_move_loader_program, pubkey::Pubkey, system_program::solana_system_program, }; #[macro_use] @@ -59,7 +58,6 @@ pub fn get_programs(operating_mode: OperatingMode, epoch: Epoch) -> Option Option EnteredEpoch #[cfg(test)] mod tests { use super::*; - use solana_sdk::nonce_program::solana_nonce_program; use std::collections::HashSet; #[test] @@ -150,7 +146,7 @@ mod tests { fn test_development_programs() { assert_eq!( get_programs(OperatingMode::Development, 0).unwrap().len(), - 11 + 10 ); assert_eq!(get_programs(OperatingMode::Development, 1), None); } @@ -173,7 +169,6 @@ mod tests { assert_eq!( get_programs(OperatingMode::SoftLaunch, 0), Some(vec![ - solana_nonce_program(), solana_stake_program!(), solana_system_program(), solana_vote_program!(), diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index 71157b58c85953..a89a7090479482 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -5,6 +5,7 @@ use crate::bank::{HashAgeKind, TransactionProcessResult}; use crate::blockhash_queue::BlockhashQueue; use crate::message_processor::has_duplicates; use crate::rent_collector::RentCollector; +use crate::system_instruction_processor::{get_system_account_kind, SystemAccountKind}; use log::*; use rayon::slice::ParallelSliceMut; use solana_metrics::inc_new_counter_error; @@ -13,8 +14,8 @@ use solana_sdk::bank_hash::BankHash; use solana_sdk::clock::Slot; use solana_sdk::message::Message; use solana_sdk::native_loader; +use solana_sdk::nonce_state::NonceState; use solana_sdk::pubkey::Pubkey; -use solana_sdk::system_program; use solana_sdk::transaction::Result; use solana_sdk::transaction::{Transaction, TransactionError}; use std::collections::{HashMap, HashSet}; @@ -134,15 +135,24 @@ impl Accounts { if accounts.is_empty() || accounts[0].lamports == 0 { error_counters.account_not_found += 1; Err(TransactionError::AccountNotFound) - } else if accounts[0].owner != system_program::id() { - error_counters.invalid_account_for_fee += 1; - Err(TransactionError::InvalidAccountForFee) - } else if accounts[0].lamports < fee { - error_counters.insufficient_funds += 1; - Err(TransactionError::InsufficientFundsForFee) } else { - accounts[0].lamports -= fee; - Ok((accounts, tx_rent)) + let min_balance = match get_system_account_kind(&accounts[0]).ok_or_else(|| { + error_counters.invalid_account_for_fee += 1; + TransactionError::InvalidAccountForFee + })? { + SystemAccountKind::System => 0, + SystemAccountKind::Nonce => { + rent_collector.rent.minimum_balance(NonceState::size()) + } + }; + + if accounts[0].lamports < fee + min_balance { + error_counters.insufficient_funds += 1; + Err(TransactionError::InsufficientFundsForFee) + } else { + accounts[0].lamports -= fee; + Ok((accounts, tx_rent)) + } } } } @@ -619,13 +629,19 @@ mod tests { use crate::accounts_db::tests::copy_append_vecs; use crate::accounts_db::{get_temp_accounts_paths, AccountsDBSerialize}; use crate::bank::HashAgeKind; + use crate::rent_collector::RentCollector; use bincode::serialize_into; use rand::{thread_rng, Rng}; use solana_sdk::account::Account; + use solana_sdk::epoch_schedule::EpochSchedule; use solana_sdk::fee_calculator::FeeCalculator; use solana_sdk::hash::Hash; use solana_sdk::instruction::CompiledInstruction; + use solana_sdk::message::Message; + use solana_sdk::nonce_state; + use solana_sdk::rent::Rent; use solana_sdk::signature::{Keypair, KeypairUtil}; + use solana_sdk::system_program; use solana_sdk::sysvar; use solana_sdk::transaction::Transaction; use std::io::Cursor; @@ -633,10 +649,11 @@ mod tests { use std::{thread, time}; use tempfile::TempDir; - fn load_accounts_with_fee( + fn load_accounts_with_fee_and_rent( tx: Transaction, ka: &Vec<(Pubkey, Account)>, fee_calculator: &FeeCalculator, + rent_collector: &RentCollector, error_counters: &mut ErrorCounters, ) -> Vec<(Result, Option)> { let mut hash_queue = BlockhashQueue::new(100); @@ -647,7 +664,6 @@ mod tests { } let ancestors = vec![(0, 0)].into_iter().collect(); - let rent_collector = RentCollector::default(); let res = accounts.load_accounts( &ancestors, &[tx], @@ -655,11 +671,21 @@ mod tests { vec![(Ok(()), Some(HashAgeKind::Extant))], &hash_queue, error_counters, - &rent_collector, + rent_collector, ); res } + fn load_accounts_with_fee( + tx: Transaction, + ka: &Vec<(Pubkey, Account)>, + fee_calculator: &FeeCalculator, + error_counters: &mut ErrorCounters, + ) -> Vec<(Result, Option)> { + let rent_collector = RentCollector::default(); + load_accounts_with_fee_and_rent(tx, ka, fee_calculator, &rent_collector, error_counters) + } + fn load_accounts( tx: Transaction, ka: &Vec<(Pubkey, Account)>, @@ -734,7 +760,7 @@ mod tests { let key0 = keypair.pubkey(); let key1 = Pubkey::new(&[5u8; 32]); - let account = Account::new(1, 1, &Pubkey::default()); + let account = Account::new(1, 0, &Pubkey::default()); accounts.push((key0, account)); let account = Account::new(2, 1, &Pubkey::default()); @@ -770,7 +796,7 @@ mod tests { let keypair = Keypair::new(); let key0 = keypair.pubkey(); - let account = Account::new(1, 1, &Pubkey::default()); + let account = Account::new(1, 0, &Pubkey::default()); accounts.push((key0, account)); let instructions = vec![CompiledInstruction::new(1, &(), vec![0])]; @@ -832,6 +858,84 @@ mod tests { ); } + #[test] + fn test_load_accounts_fee_payer_is_nonce() { + let mut error_counters = ErrorCounters::default(); + let rent_collector = RentCollector::new( + 0, + &EpochSchedule::default(), + 500_000.0, + &Rent { + lamports_per_byte_year: 42, + ..Rent::default() + }, + ); + let min_balance = rent_collector + .rent + .minimum_balance(nonce_state::NonceState::size()); + let fee_calculator = FeeCalculator::new(min_balance, 0); + let nonce = Keypair::new(); + let mut accounts = vec![( + nonce.pubkey(), + Account::new_data( + min_balance * 2, + &nonce_state::NonceState::Initialized( + nonce_state::Meta::new(&Pubkey::default()), + Hash::default(), + ), + &system_program::id(), + ) + .unwrap(), + )]; + let instructions = vec![CompiledInstruction::new(1, &(), vec![0])]; + let tx = Transaction::new_with_compiled_instructions( + &[&nonce], + &[], + Hash::default(), + vec![native_loader::id()], + instructions, + ); + + // Fee leaves min_balance balance succeeds + let loaded_accounts = load_accounts_with_fee_and_rent( + tx.clone(), + &accounts, + &fee_calculator, + &rent_collector, + &mut error_counters, + ); + assert_eq!(loaded_accounts.len(), 1); + let (load_res, _hash_age_kind) = &loaded_accounts[0]; + let (tx_accounts, _loaders, _rents) = load_res.as_ref().unwrap(); + assert_eq!(tx_accounts[0].lamports, min_balance); + + // Fee leaves zero balance fails + accounts[0].1.lamports = min_balance; + let loaded_accounts = load_accounts_with_fee_and_rent( + tx.clone(), + &accounts, + &fee_calculator, + &rent_collector, + &mut error_counters, + ); + assert_eq!(loaded_accounts.len(), 1); + let (load_res, _hash_age_kind) = &loaded_accounts[0]; + assert_eq!(*load_res, Err(TransactionError::InsufficientFundsForFee)); + + // Fee leaves non-zero, but sub-min_balance balance fails + accounts[0].1.lamports = 3 * min_balance / 2; + let loaded_accounts = load_accounts_with_fee_and_rent( + tx.clone(), + &accounts, + &fee_calculator, + &rent_collector, + &mut error_counters, + ); + assert_eq!(loaded_accounts.len(), 1); + let (load_res, _hash_age_kind) = &loaded_accounts[0]; + assert_eq!(*load_res, Err(TransactionError::InsufficientFundsForFee)); + } + #[test] fn test_load_accounts_no_loaders() { let mut accounts: Vec<(Pubkey, Account)> = Vec::new(); @@ -841,7 +945,7 @@ mod tests { let key0 = keypair.pubkey(); let key1 = Pubkey::new(&[5u8; 32]); - let mut account = Account::new(1, 1, &Pubkey::default()); + let mut account = Account::new(1, 0, &Pubkey::default()); account.rent_epoch = 1; accounts.push((key0, account)); @@ -890,7 +994,7 @@ mod tests { let key5 = Pubkey::new(&[9u8; 32]); let key6 = Pubkey::new(&[10u8; 32]); - let account = Account::new(1, 1, &Pubkey::default()); + let account = Account::new(1, 0, &Pubkey::default()); accounts.push((key0, account)); let mut account = Account::new(40, 1, &Pubkey::default()); @@ -957,7 +1061,7 @@ mod tests { let account = Account::new(1, 1, &Pubkey::default()); accounts.push((key0, account)); - let mut account = Account::new(40, 1, &Pubkey::default()); + let mut account = Account::new(40, 0, &Pubkey::default()); account.executable = true; account.owner = Pubkey::default(); accounts.push((key1, account)); @@ -993,7 +1097,7 @@ mod tests { let key0 = keypair.pubkey(); let key1 = Pubkey::new(&[5u8; 32]); - let account = Account::new(1, 1, &Pubkey::default()); + let account = Account::new(1, 0, &Pubkey::default()); accounts.push((key0, account)); let mut account = Account::new(40, 1, &Pubkey::default()); @@ -1032,7 +1136,7 @@ mod tests { let key1 = Pubkey::new(&[5u8; 32]); let key2 = Pubkey::new(&[6u8; 32]); - let mut account = Account::new(1, 1, &Pubkey::default()); + let mut account = Account::new(1, 0, &Pubkey::default()); account.rent_epoch = 1; accounts.push((key0, account)); diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index ca6c1b7a3b6c47..dcf90de0eacfb3 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -16,6 +16,7 @@ use crate::{ status_cache::{SlotDelta, StatusCache}, storage_utils, storage_utils::StorageAccounts, + system_instruction_processor::{get_system_account_kind, SystemAccountKind}, transaction_batch::TransactionBatch, transaction_utils::OrderedIterator, }; @@ -37,6 +38,7 @@ use solana_sdk::{ hash::{hashv, Hash}, inflation::Inflation, native_loader, + nonce_state::NonceState, pubkey::Pubkey, signature::{Keypair, Signature}, slot_hashes::SlotHashes, @@ -1483,7 +1485,13 @@ impl Bank { pub fn withdraw(&self, pubkey: &Pubkey, lamports: u64) -> Result<()> { match self.get_account(pubkey) { Some(mut account) => { - if lamports > account.lamports { + let min_balance = match get_system_account_kind(&account) { + Some(SystemAccountKind::Nonce) => { + self.rent_collector.rent.minimum_balance(NonceState::size()) + } + _ => 0, + }; + if lamports + min_balance > account.lamports { return Err(TransactionError::InsufficientFundsForFee); } @@ -1861,7 +1869,7 @@ mod tests { genesis_config::create_genesis_config, instruction::{CompiledInstruction, Instruction, InstructionError}, message::{Message, MessageHeader}, - nonce_instruction, nonce_state, + nonce_state, poh_config::PohConfig, rent::Rent, signature::{Keypair, KeypairUtil}, @@ -2029,11 +2037,11 @@ mod tests { assert_eq!(bank.last_blockhash(), genesis_config.hash()); // Initialize credit-debit and credit only accounts - let account1 = Account::new(264, 1, &Pubkey::default()); + let account1 = Account::new(264, 0, &Pubkey::default()); let account2 = Account::new(264, 1, &Pubkey::default()); - let account3 = Account::new(264, 1, &Pubkey::default()); + let account3 = Account::new(264, 0, &Pubkey::default()); let account4 = Account::new(264, 1, &Pubkey::default()); - let account5 = Account::new(10, 1, &Pubkey::default()); + let account5 = Account::new(10, 0, &Pubkey::default()); let account6 = Account::new(10, 1, &Pubkey::default()); bank.store_account(&keypair1.pubkey(), &account1); @@ -2149,7 +2157,7 @@ mod tests { keypairs[0].pubkey(), Account::new( generic_rent_due_for_system_account + 2, - 1, + 0, &Pubkey::default(), ), )); @@ -2157,7 +2165,7 @@ mod tests { keypairs[1].pubkey(), Account::new( generic_rent_due_for_system_account + 2, - 1, + 0, &Pubkey::default(), ), )); @@ -2165,7 +2173,7 @@ mod tests { keypairs[2].pubkey(), Account::new( generic_rent_due_for_system_account + 2, - 1, + 0, &Pubkey::default(), ), )); @@ -2173,23 +2181,23 @@ mod tests { keypairs[3].pubkey(), Account::new( generic_rent_due_for_system_account + 2, - 1, + 0, &Pubkey::default(), ), )); account_pairs.push(( keypairs[4].pubkey(), - Account::new(10, 1, &Pubkey::default()), + Account::new(10, 0, &Pubkey::default()), )); account_pairs.push(( keypairs[5].pubkey(), - Account::new(10, 1, &Pubkey::default()), + Account::new(10, 0, &Pubkey::default()), )); account_pairs.push(( keypairs[6].pubkey(), Account::new( (2 * generic_rent_due_for_system_account) + 24, - 1, + 0, &Pubkey::default(), ), )); @@ -2198,13 +2206,13 @@ mod tests { keypairs[8].pubkey(), Account::new( generic_rent_due_for_system_account + 2 + 929, - 1, + 0, &Pubkey::default(), ), )); account_pairs.push(( keypairs[9].pubkey(), - Account::new(10, 1, &Pubkey::default()), + Account::new(10, 0, &Pubkey::default()), )); // Feeding to MockProgram to test read only rent behaviour @@ -2212,21 +2220,21 @@ mod tests { keypairs[10].pubkey(), Account::new( generic_rent_due_for_system_account + 3, - 1, + 0, &Pubkey::default(), ), )); account_pairs.push(( keypairs[11].pubkey(), - Account::new(generic_rent_due_for_system_account + 3, 1, &mock_program_id), + Account::new(generic_rent_due_for_system_account + 3, 0, &mock_program_id), )); account_pairs.push(( keypairs[12].pubkey(), - Account::new(generic_rent_due_for_system_account + 3, 1, &mock_program_id), + Account::new(generic_rent_due_for_system_account + 3, 0, &mock_program_id), )); account_pairs.push(( keypairs[13].pubkey(), - Account::new(14, 23, &mock_program_id), + Account::new(14, 22, &mock_program_id), )); for account_pair in account_pairs.iter() { @@ -2396,7 +2404,7 @@ mod tests { bank.rent_collector.slots_per_year = 192.0; let payer = Keypair::new(); - let payer_account = Account::new(400, 2, &system_program::id()); + let payer_account = Account::new(400, 0, &system_program::id()); bank.store_account(&payer.pubkey(), &payer_account); let payee = Keypair::new(); @@ -2412,9 +2420,9 @@ mod tests { let mut total_rent_deducted = 0; - // 400 - 130(Rent) - 180(Transfer) - assert_eq!(bank.get_balance(&payer.pubkey()), 90); - total_rent_deducted += 130; + // 400 - 128(Rent) - 180(Transfer) + assert_eq!(bank.get_balance(&payer.pubkey()), 92); + total_rent_deducted += 128; // 70 - 70(Rent) + 180(Transfer) - 21(Rent) assert_eq!(bank.get_balance(&payee.pubkey()), 159); @@ -2442,26 +2450,30 @@ mod tests { // Since, validator 1 and validator 2 has equal smallest stake, it comes down to comparison // between their pubkey. - let mut validator_1_portion = - ((validator_1_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64; - if validator_1_pubkey > validator_2_pubkey { - validator_1_portion += 1; - } + let tweak_1 = if validator_1_pubkey > validator_2_pubkey { + 1 + } else { + 0 + }; + let validator_1_portion = + ((validator_1_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64 + tweak_1; assert_eq!( bank.get_balance(&validator_1_pubkey), - validator_1_portion + 42 + validator_1_portion + 42 - tweak_1, ); // Since, validator 1 and validator 2 has equal smallest stake, it comes down to comparison // between their pubkey. - let mut validator_2_portion = - ((validator_2_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64; - if validator_2_pubkey > validator_1_pubkey { - validator_2_portion += 1; - } + let tweak_2 = if validator_2_pubkey > validator_1_pubkey { + 1 + } else { + 0 + }; + let validator_2_portion = + ((validator_2_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64 + tweak_2; assert_eq!( bank.get_balance(&validator_2_pubkey), - validator_2_portion + 42 + validator_2_portion + 42 - tweak_2, ); let validator_3_portion = @@ -2509,8 +2521,8 @@ mod tests { }) .sum(); let (generic_rent_due_for_system_account, _) = bank.rent_collector.rent.due( - bank.get_minimum_balance_for_rent_exemption(1) - 1, - 1, + bank.get_minimum_balance_for_rent_exemption(0) - 1, + 0, slots_elapsed as f64 / bank.rent_collector.slots_per_year, ); @@ -2542,7 +2554,7 @@ mod tests { let t4 = system_transaction::transfer( &keypairs[6], &keypairs[7].pubkey(), - 49373, + 48991, genesis_config.hash(), ); let t5 = system_transaction::transfer( @@ -2582,19 +2594,19 @@ mod tests { let mut rent_collected = 0; - // 49374 - 49372(Rent) - 1(transfer) + // 48992 - 48990(Rent) - 1(transfer) assert_eq!(bank.get_balance(&keypairs[0].pubkey()), 1); rent_collected += generic_rent_due_for_system_account; - // 49374 - 49372(Rent) - 1(transfer) + // 48992 - 48990(Rent) + 1(transfer) assert_eq!(bank.get_balance(&keypairs[1].pubkey()), 3); rent_collected += generic_rent_due_for_system_account; - // 49374 - 49372(Rent) - 1(transfer) + // 48992 - 48990(Rent) - 1(transfer) assert_eq!(bank.get_balance(&keypairs[2].pubkey()), 1); rent_collected += generic_rent_due_for_system_account; - // 49374 - 49372(Rent) - 1(transfer) + // 48992 - 48990(Rent) + 1(transfer) assert_eq!(bank.get_balance(&keypairs[3].pubkey()), 3); rent_collected += generic_rent_due_for_system_account; @@ -2602,11 +2614,11 @@ mod tests { assert_eq!(bank.get_balance(&keypairs[4].pubkey()), 10); assert_eq!(bank.get_balance(&keypairs[5].pubkey()), 10); - // 98768 - 49372(Rent) - 49373(transfer) + // 98004 - 48990(Rent) - 48991(transfer) assert_eq!(bank.get_balance(&keypairs[6].pubkey()), 23); rent_collected += generic_rent_due_for_system_account; - // 0 + 49373(transfer) - 917(Rent) + // 0 + 48990(transfer) - 917(Rent) assert_eq!( bank.get_balance(&keypairs[7].pubkey()), generic_rent_due_for_system_account + 1 - 917 @@ -2618,7 +2630,7 @@ mod tests { assert_eq!(account8.rent_epoch, bank.epoch + 1); rent_collected += 917; - // 50303 - 49372(Rent) - 929(Transfer) + // 49921 - 48900(Rent) - 929(Transfer) assert_eq!(bank.get_balance(&keypairs[8].pubkey()), 2); rent_collected += generic_rent_due_for_system_account; @@ -2632,15 +2644,15 @@ mod tests { assert_eq!(account10.lamports, 12); rent_collected += 927; - // 49375 - 49372(Rent) + // 48993 - 48990(Rent) assert_eq!(bank.get_balance(&keypairs[10].pubkey()), 3); rent_collected += generic_rent_due_for_system_account; - // 49375 - 49372(Rent) + 1(Addition by program) + // 48993 - 48990(Rent) + 1(Addition by program) assert_eq!(bank.get_balance(&keypairs[11].pubkey()), 4); rent_collected += generic_rent_due_for_system_account; - // 49375 - 49372(Rent) - 1(Deduction by program) + // 48993 - 48990(Rent) - 1(Deduction by program) assert_eq!(bank.get_balance(&keypairs[12].pubkey()), 2); rent_collected += generic_rent_due_for_system_account; @@ -2984,6 +2996,45 @@ mod tests { assert_eq!(bank.get_balance(&key.pubkey()), 1); } + #[test] + fn test_bank_withdraw_from_nonce_account() { + let (mut genesis_config, _mint_keypair) = create_genesis_config(100_000); + genesis_config.rent.lamports_per_byte_year = 42; + let bank = Bank::new(&genesis_config); + + let min_balance = + bank.get_minimum_balance_for_rent_exemption(nonce_state::NonceState::size()); + let nonce = Keypair::new(); + let nonce_account = Account::new_data( + min_balance + 42, + &nonce_state::NonceState::Initialized( + nonce_state::Meta::new(&Pubkey::default()), + Hash::default(), + ), + &system_program::id(), + ) + .unwrap(); + bank.store_account(&nonce.pubkey(), &nonce_account); + assert_eq!(bank.get_balance(&nonce.pubkey()), min_balance + 42); + + // Resulting in non-zero, but sub-min_balance balance fails + assert_eq!( + bank.withdraw(&nonce.pubkey(), min_balance / 2), + Err(TransactionError::InsufficientFundsForFee) + ); + assert_eq!(bank.get_balance(&nonce.pubkey()), min_balance + 42); + + // Resulting in exactly rent-exempt balance succeeds + bank.withdraw(&nonce.pubkey(), 42).unwrap(); + assert_eq!(bank.get_balance(&nonce.pubkey()), min_balance); + + // Account closure fails + assert_eq!( + bank.withdraw(&nonce.pubkey(), min_balance), + Err(TransactionError::InsufficientFundsForFee), + ); + } + #[test] fn test_bank_tx_fee() { let arbitrary_transfer_amount = 42; @@ -4526,7 +4577,7 @@ mod tests { custodian_lamports, )]; let nonce_authority = nonce_authority.unwrap_or(nonce_keypair.pubkey()); - setup_ixs.extend_from_slice(&nonce_instruction::create_nonce_account( + setup_ixs.extend_from_slice(&system_instruction::create_nonce_account( &custodian_keypair.pubkey(), &nonce_keypair.pubkey(), &nonce_authority, @@ -4576,7 +4627,7 @@ mod tests { let nonce_hash = get_nonce(&bank, &nonce_pubkey).unwrap(); let tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000), ], Some(&custodian_pubkey), @@ -4597,7 +4648,7 @@ mod tests { let tx = Transaction::new_signed_with_payer( vec![ system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000), - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), ], Some(&custodian_pubkey), &[&custodian_keypair, &nonce_keypair], @@ -4616,7 +4667,7 @@ mod tests { let nonce_hash = get_nonce(&bank, &nonce_pubkey).unwrap(); let mut tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000), ], Some(&custodian_pubkey), @@ -4639,7 +4690,7 @@ mod tests { let nonce_hash = get_nonce(&bank, &nonce_pubkey).unwrap(); let tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&missing_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&missing_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000), ], Some(&custodian_pubkey), @@ -4658,7 +4709,7 @@ mod tests { let tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000), ], Some(&custodian_pubkey), @@ -4668,6 +4719,39 @@ mod tests { assert!(!bank.check_tx_durable_nonce(&tx)); } + #[test] + fn test_assign_from_nonce_account_fail() { + let (genesis_config, _mint_keypair) = create_genesis_config(100_000_000); + let bank = Arc::new(Bank::new(&genesis_config)); + let nonce = Keypair::new(); + let nonce_account = Account::new_data( + 42424242, + &nonce_state::NonceState::Initialized( + nonce_state::Meta::new(&Pubkey::default()), + Hash::default(), + ), + &system_program::id(), + ) + .unwrap(); + let blockhash = bank.last_blockhash(); + bank.store_account(&nonce.pubkey(), &nonce_account); + + let tx = Transaction::new_signed_instructions( + &[&nonce], + vec![system_instruction::assign( + &nonce.pubkey(), + &Pubkey::new(&[9u8; 32]), + )], + blockhash, + ); + + let expect = Err(TransactionError::InstructionError( + 0, + InstructionError::ModifiedProgramId, + )); + assert_eq!(bank.process_transaction(&tx), expect); + } + #[test] fn test_durable_nonce_transaction() { let (mut bank, _mint_keypair, custodian_keypair, nonce_keypair) = setup_nonce_with_bank( @@ -4713,7 +4797,7 @@ mod tests { /* Durable Nonce transfer */ let durable_tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000), ], Some(&custodian_pubkey), @@ -4734,7 +4818,7 @@ mod tests { /* Durable Nonce re-use fails */ let durable_tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000), ], Some(&custodian_pubkey), @@ -4758,7 +4842,7 @@ mod tests { let durable_tx = Transaction::new_signed_with_payer( vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000_000), ], Some(&custodian_pubkey), diff --git a/runtime/src/genesis_utils.rs b/runtime/src/genesis_utils.rs index 05f8a0d1ae214d..d3312ba6185ec1 100644 --- a/runtime/src/genesis_utils.rs +++ b/runtime/src/genesis_utils.rs @@ -2,7 +2,6 @@ use solana_sdk::{ account::Account, fee_calculator::FeeCalculator, genesis_config::GenesisConfig, - nonce_program::solana_nonce_program, pubkey::Pubkey, rent::Rent, signature::{Keypair, KeypairUtil}, @@ -75,7 +74,6 @@ pub fn create_genesis_config_with_leader( // Bare minimum program set let native_instruction_processors = vec![ solana_system_program(), - solana_nonce_program(), solana_bpf_loader_program!(), solana_vote_program!(), solana_stake_program!(), diff --git a/runtime/src/message_processor.rs b/runtime/src/message_processor.rs index ec19d9eac0d6a3..580d4afc64d361 100644 --- a/runtime/src/message_processor.rs +++ b/runtime/src/message_processor.rs @@ -7,8 +7,6 @@ use solana_sdk::instruction::{CompiledInstruction, InstructionError}; use solana_sdk::instruction_processor_utils; use solana_sdk::loader_instruction::LoaderInstruction; use solana_sdk::message::Message; -use solana_sdk::nonce_instruction; -use solana_sdk::nonce_program; use solana_sdk::pubkey::Pubkey; use solana_sdk::system_program; use solana_sdk::transaction::TransactionError; @@ -200,13 +198,10 @@ pub struct MessageProcessor { impl Default for MessageProcessor { fn default() -> Self { - let instruction_processors: Vec<(Pubkey, ProcessInstruction)> = vec![ - ( - system_program::id(), - system_instruction_processor::process_instruction, - ), - (nonce_program::id(), nonce_instruction::process_instruction), - ]; + let instruction_processors: Vec<(Pubkey, ProcessInstruction)> = vec![( + system_program::id(), + system_instruction_processor::process_instruction, + )]; Self { instruction_processors, diff --git a/runtime/src/nonce_utils.rs b/runtime/src/nonce_utils.rs index 54156a2d62c9d5..1c9b4c976fa967 100644 --- a/runtime/src/nonce_utils.rs +++ b/runtime/src/nonce_utils.rs @@ -1,7 +1,7 @@ use solana_sdk::{ account::Account, account_utils::State, hash::Hash, instruction::CompiledInstruction, - instruction_processor_utils::limited_deserialize, nonce_instruction::NonceInstruction, - nonce_program, nonce_state::NonceState, pubkey::Pubkey, transaction::Transaction, + instruction_processor_utils::limited_deserialize, nonce_state::NonceState, pubkey::Pubkey, + system_instruction::SystemInstruction, system_program, transaction::Transaction, }; pub fn transaction_uses_durable_nonce(tx: &Transaction) -> Option<&CompiledInstruction> { @@ -12,12 +12,12 @@ pub fn transaction_uses_durable_nonce(tx: &Transaction) -> Option<&CompiledInstr .filter(|maybe_ix| { let prog_id_idx = maybe_ix.program_id_index as usize; match message.account_keys.get(prog_id_idx) { - Some(program_id) => nonce_program::check_id(&program_id), + Some(program_id) => system_program::check_id(&program_id), _ => false, } }) .filter(|maybe_ix| match limited_deserialize(&maybe_ix.data) { - Ok(NonceInstruction::Nonce) => true, + Ok(SystemInstruction::NonceAdvance) => true, _ => false, }) } @@ -44,7 +44,6 @@ mod tests { use super::*; use solana_sdk::{ hash::Hash, - nonce_instruction, nonce_state::{with_test_keyed_account, NonceAccount}, pubkey::Pubkey, signature::{Keypair, KeypairUtil}, @@ -61,7 +60,7 @@ mod tests { let tx = Transaction::new_signed_instructions( &[&from_keypair, &nonce_keypair], vec![ - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42), ], Hash::default(), @@ -99,7 +98,7 @@ mod tests { &[&from_keypair, &nonce_keypair], vec![ system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42), - nonce_instruction::nonce(&nonce_pubkey, &nonce_pubkey), + system_instruction::nonce_advance(&nonce_pubkey, &nonce_pubkey), ], Hash::default(), ); @@ -115,7 +114,7 @@ mod tests { let tx = Transaction::new_signed_instructions( &[&from_keypair, &nonce_keypair], vec![ - nonce_instruction::withdraw(&nonce_pubkey, &nonce_pubkey, &from_pubkey, 42), + system_instruction::nonce_withdraw(&nonce_pubkey, &nonce_pubkey, &from_pubkey, 42), system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42), ], Hash::default(), @@ -162,7 +161,7 @@ mod tests { let recent_blockhashes = create_test_recent_blockhashes(0); let authorized = nonce_account.unsigned_key().clone(); nonce_account - .initialize(&authorized, &recent_blockhashes, &Rent::free()) + .nonce_initialize(&authorized, &recent_blockhashes, &Rent::free()) .unwrap(); assert!(verify_nonce(&nonce_account.account, &recent_blockhashes[0])); }); @@ -186,7 +185,7 @@ mod tests { let recent_blockhashes = create_test_recent_blockhashes(0); let authorized = nonce_account.unsigned_key().clone(); nonce_account - .initialize(&authorized, &recent_blockhashes, &Rent::free()) + .nonce_initialize(&authorized, &recent_blockhashes, &Rent::free()) .unwrap(); assert!(!verify_nonce( &nonce_account.account, diff --git a/runtime/src/system_instruction_processor.rs b/runtime/src/system_instruction_processor.rs index fff9f0fa5d99a7..9e7642d19371d1 100644 --- a/runtime/src/system_instruction_processor.rs +++ b/runtime/src/system_instruction_processor.rs @@ -1,14 +1,17 @@ use log::*; use solana_sdk::{ - account::KeyedAccount, + account::{get_signers, Account, KeyedAccount}, + account_utils::State, instruction::InstructionError, instruction_processor_utils::{limited_deserialize, next_keyed_account}, + nonce_state::{NonceAccount, NonceState}, pubkey::Pubkey, system_instruction::{ create_address_with_seed, SystemError, SystemInstruction, MAX_PERMITTED_DATA_LENGTH, }, - system_program, sysvar, + system_program, + sysvar::{self, recent_blockhashes::RecentBlockhashes, rent::Rent, Sysvar}, }; fn create_account_with_seed( @@ -70,6 +73,12 @@ fn finish_create_account( data_length: u64, program_id: &Pubkey, ) -> Result<(), InstructionError> { + // if lamports == 0, the `from` account isn't touched + if lamports != 0 && !from.account.data.is_empty() { + debug!("CreateAccount: `from` must not carry data"); + return Err(InstructionError::InvalidArgument); + } + // if it looks like the `to` account is already in use, bail if to.account.lamports != 0 || !to.account.data.is_empty() @@ -108,6 +117,7 @@ fn finish_create_account( debug!("Assign: program id {} invalid", program_id); return Err(SystemError::InvalidProgramId.into()); } + to.account.owner = *program_id; from.account.lamports -= lamports; @@ -151,6 +161,11 @@ fn transfer_lamports( return Err(InstructionError::MissingRequiredSignature); } + if !from.account.data.is_empty() { + debug!("Transfer: `from` must not carry data"); + return Err(InstructionError::InvalidArgument); + } + if lamports > from.account.lamports { debug!( "Transfer: insufficient lamports ({}, need {})", @@ -158,6 +173,7 @@ fn transfer_lamports( ); return Err(SystemError::ResultWithNegativeLamports.into()); } + from.account.lamports -= lamports; to.account.lamports += lamports; Ok(()) @@ -173,6 +189,7 @@ pub fn process_instruction( trace!("process_instruction: {:?}", instruction); trace!("keyed_accounts: {:?}", keyed_accounts); + let signers = get_signers(keyed_accounts); let keyed_accounts_iter = &mut keyed_accounts.iter_mut(); match instruction { @@ -204,6 +221,56 @@ pub fn process_instruction( let to = next_keyed_account(keyed_accounts_iter)?; transfer_lamports(from, to, lamports) } + SystemInstruction::NonceAdvance => { + let me = &mut next_keyed_account(keyed_accounts_iter)?; + me.nonce_advance( + &RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts_iter)?)?, + &signers, + ) + } + SystemInstruction::NonceWithdraw(lamports) => { + let me = &mut next_keyed_account(keyed_accounts_iter)?; + let to = &mut next_keyed_account(keyed_accounts_iter)?; + me.nonce_withdraw( + lamports, + to, + &RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts_iter)?)?, + &Rent::from_keyed_account(next_keyed_account(keyed_accounts_iter)?)?, + &signers, + ) + } + SystemInstruction::NonceInitialize(authorized) => { + let me = &mut next_keyed_account(keyed_accounts_iter)?; + me.nonce_initialize( + &authorized, + &RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts_iter)?)?, + &Rent::from_keyed_account(next_keyed_account(keyed_accounts_iter)?)?, + ) + } + SystemInstruction::NonceAuthorize(nonce_authority) => { + let me = &mut next_keyed_account(keyed_accounts_iter)?; + me.nonce_authorize(&nonce_authority, &signers) + } + } +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SystemAccountKind { + System, + Nonce, +} + +pub fn get_system_account_kind(account: &Account) -> Option { + if system_program::check_id(&account.owner) { + if account.data.is_empty() { + Some(SystemAccountKind::System) + } else if let Ok(NonceState::Initialized(_, _)) = account.state() { + Some(SystemAccountKind::Nonce) + } else { + None + } + } else { + None } } @@ -216,9 +283,13 @@ mod tests { use solana_sdk::account::Account; use solana_sdk::client::SyncClient; use solana_sdk::genesis_config::create_genesis_config; + use solana_sdk::hash::{hash, Hash}; use solana_sdk::instruction::{AccountMeta, Instruction, InstructionError}; + use solana_sdk::nonce_state; use solana_sdk::signature::{Keypair, KeypairUtil}; + use solana_sdk::system_instruction; use solana_sdk::system_program; + use solana_sdk::sysvar; use solana_sdk::transaction::TransactionError; #[test] @@ -338,7 +409,7 @@ mod tests { // create account with zero lamports tranferred let new_program_owner = Pubkey::new(&[9; 32]); let from = Pubkey::new_rand(); - let mut from_account = Account::new(100, 0, &Pubkey::new_rand()); // not from system account + let mut from_account = Account::new(100, 1, &Pubkey::new_rand()); // not from system account let to = Pubkey::new_rand(); let mut to_account = Account::new(0, 0, &Pubkey::default()); @@ -572,6 +643,29 @@ mod tests { assert_eq!(populated_account, unchanged_account); } + #[test] + fn test_create_from_account_is_nonce_fail() { + let nonce = Pubkey::new_rand(); + let mut nonce_account = Account::new_data( + 42, + &nonce_state::NonceState::Initialized( + nonce_state::Meta::new(&Pubkey::default()), + Hash::default(), + ), + &system_program::id(), + ) + .unwrap(); + let mut from = KeyedAccount::new(&nonce, true, &mut nonce_account); + let new = Pubkey::new_rand(); + + let mut new_account = Account::default(); + let mut to = KeyedAccount::new(&new, true, &mut new_account); + assert_eq!( + create_account(&mut from, &mut to, 42, 0, &Pubkey::new_rand()), + Err(InstructionError::InvalidArgument), + ); + } + #[test] fn test_assign_account_to_program() { let new_program_owner = Pubkey::new(&[9; 32]); @@ -677,6 +771,31 @@ mod tests { assert_eq!(to_account.lamports, 51); } + #[test] + fn test_transfer_lamports_from_nonce_account_fail() { + let from = Pubkey::new_rand(); + let mut from_account = Account::new_data( + 100, + &nonce_state::NonceState::Initialized(nonce_state::Meta::new(&from), Hash::default()), + &system_program::id(), + ) + .unwrap(); + assert_eq!( + get_system_account_kind(&from_account), + Some(SystemAccountKind::Nonce) + ); + let to = Pubkey::new_rand(); + let mut to_account = Account::new(1, 0, &Pubkey::new(&[3; 32])); // account owner should not matter + assert_eq!( + transfer_lamports( + &mut KeyedAccount::new(&from, true, &mut from_account), + &mut KeyedAccount::new(&to, false, &mut to_account), + 50, + ), + Err(InstructionError::InvalidArgument), + ) + } + #[test] fn test_system_unsigned_transaction() { let (genesis_config, alice_keypair) = create_genesis_config(100); @@ -712,4 +831,469 @@ mod tests { assert_eq!(bank_client.get_balance(&alice_pubkey).unwrap(), 50); assert_eq!(bank_client.get_balance(&mallory_pubkey).unwrap(), 50); } + + fn process_nonce_instruction(instruction: &Instruction) -> Result<(), InstructionError> { + let mut accounts: Vec<_> = instruction + .accounts + .iter() + .map(|meta| { + if sysvar::recent_blockhashes::check_id(&meta.pubkey) { + sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ) + } else if sysvar::rent::check_id(&meta.pubkey) { + sysvar::rent::create_account(1, &Rent::free()) + } else { + Account::default() + } + }) + .collect(); + + { + let mut keyed_accounts_iter: Vec<_> = instruction + .accounts + .iter() + .zip(accounts.iter_mut()) + .map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account)) + .collect(); + super::process_instruction( + &Pubkey::default(), + &mut keyed_accounts_iter, + &instruction.data, + ) + } + } + + #[test] + fn test_process_nonce_ix_no_acc_data_fail() { + assert_eq!( + process_nonce_instruction(&system_instruction::nonce_advance( + &Pubkey::default(), + &Pubkey::default() + )), + Err(InstructionError::InvalidAccountData), + ); + } + + #[test] + fn test_process_nonce_ix_no_keyed_accs_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [], + &serialize(&SystemInstruction::NonceAdvance).unwrap() + ), + Err(InstructionError::NotEnoughAccountKeys), + ); + } + + #[test] + fn test_process_nonce_ix_only_nonce_acc_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [KeyedAccount::new( + &Pubkey::default(), + true, + &mut Account::default(), + ),], + &serialize(&SystemInstruction::NonceAdvance).unwrap(), + ), + Err(InstructionError::NotEnoughAccountKeys), + ); + } + + #[test] + fn test_process_nonce_ix_bad_recent_blockhash_state_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut Account::default(), + ), + ], + &serialize(&SystemInstruction::NonceAdvance).unwrap(), + ), + Err(InstructionError::InvalidArgument), + ); + } + + #[test] + fn test_process_nonce_ix_ok() { + let mut nonce_acc = nonce_state::create_account(1_000_000); + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ), + ), + KeyedAccount::new( + &sysvar::rent::id(), + false, + &mut sysvar::rent::create_account(1, &Rent::free()), + ), + ], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ) + .unwrap(); + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc,), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &hash(&serialize(&0).unwrap())); 32].into_iter(), + ), + ), + ], + &serialize(&SystemInstruction::NonceAdvance).unwrap(), + ), + Ok(()), + ); + } + + #[test] + fn test_process_withdraw_ix_no_acc_data_fail() { + assert_eq!( + process_nonce_instruction(&system_instruction::nonce_withdraw( + &Pubkey::default(), + &Pubkey::default(), + &Pubkey::default(), + 1, + )), + Err(InstructionError::InvalidAccountData), + ); + } + + #[test] + fn test_process_withdraw_ix_no_keyed_accs_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [], + &serialize(&SystemInstruction::NonceWithdraw(42)).unwrap(), + ), + Err(InstructionError::NotEnoughAccountKeys), + ); + } + + #[test] + fn test_process_withdraw_ix_only_nonce_acc_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [KeyedAccount::new( + &Pubkey::default(), + true, + &mut Account::default(), + ),], + &serialize(&SystemInstruction::NonceWithdraw(42)).unwrap(), + ), + Err(InstructionError::NotEnoughAccountKeys), + ); + } + + #[test] + fn test_process_withdraw_ix_bad_recent_blockhash_state_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), + KeyedAccount::new(&Pubkey::default(), false, &mut Account::default(),), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut Account::default(), + ), + ], + &serialize(&SystemInstruction::NonceWithdraw(42)).unwrap(), + ), + Err(InstructionError::InvalidArgument), + ); + } + + #[test] + fn test_process_withdraw_ix_bad_rent_state_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new( + &Pubkey::default(), + true, + &mut nonce_state::create_account(1_000_000), + ), + KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ), + ), + KeyedAccount::new(&sysvar::rent::id(), false, &mut Account::default(),), + ], + &serialize(&SystemInstruction::NonceWithdraw(42)).unwrap(), + ), + Err(InstructionError::InvalidArgument), + ); + } + + #[test] + fn test_process_withdraw_ix_ok() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new( + &Pubkey::default(), + true, + &mut nonce_state::create_account(1_000_000), + ), + KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ), + ), + KeyedAccount::new( + &sysvar::rent::id(), + false, + &mut sysvar::rent::create_account(1, &Rent::free()) + ), + ], + &serialize(&SystemInstruction::NonceWithdraw(42)).unwrap(), + ), + Ok(()), + ); + } + + #[test] + fn test_process_initialize_ix_no_keyed_accs_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ), + Err(InstructionError::NotEnoughAccountKeys), + ); + } + + #[test] + fn test_process_initialize_ix_only_nonce_acc_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [KeyedAccount::new( + &Pubkey::default(), + true, + &mut nonce_state::create_account(1_000_000), + ),], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ), + Err(InstructionError::NotEnoughAccountKeys), + ); + } + + #[test] + fn test_process_initialize_bad_recent_blockhash_state_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new( + &Pubkey::default(), + true, + &mut nonce_state::create_account(1_000_000), + ), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut Account::default(), + ), + ], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ), + Err(InstructionError::InvalidArgument), + ); + } + + #[test] + fn test_process_initialize_ix_bad_rent_state_fail() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new( + &Pubkey::default(), + true, + &mut nonce_state::create_account(1_000_000), + ), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ), + ), + KeyedAccount::new(&sysvar::rent::id(), false, &mut Account::default(),), + ], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ), + Err(InstructionError::InvalidArgument), + ); + } + + #[test] + fn test_process_initialize_ix_ok() { + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new( + &Pubkey::default(), + true, + &mut nonce_state::create_account(1_000_000), + ), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ), + ), + KeyedAccount::new( + &sysvar::rent::id(), + false, + &mut sysvar::rent::create_account(1, &Rent::free()) + ), + ], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ), + Ok(()), + ); + } + + #[test] + fn test_process_authorize_ix_ok() { + let mut nonce_acc = nonce_state::create_account(1_000_000); + super::process_instruction( + &Pubkey::default(), + &mut [ + KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc), + KeyedAccount::new( + &sysvar::recent_blockhashes::id(), + false, + &mut sysvar::recent_blockhashes::create_account_with_data( + 1, + vec![(0u64, &Hash::default()); 32].into_iter(), + ), + ), + KeyedAccount::new( + &sysvar::rent::id(), + false, + &mut sysvar::rent::create_account(1, &Rent::free()), + ), + ], + &serialize(&SystemInstruction::NonceInitialize(Pubkey::default())).unwrap(), + ) + .unwrap(); + assert_eq!( + super::process_instruction( + &Pubkey::default(), + &mut [KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc,),], + &serialize(&SystemInstruction::NonceAuthorize(Pubkey::default(),)).unwrap(), + ), + Ok(()), + ); + } + + #[test] + fn test_process_authorize_bad_account_data_fail() { + assert_eq!( + process_nonce_instruction(&system_instruction::nonce_authorize( + &Pubkey::default(), + &Pubkey::default(), + &Pubkey::default(), + )), + Err(InstructionError::InvalidAccountData), + ); + } + + #[test] + fn test_get_system_account_kind_system_ok() { + let system_account = Account::default(); + assert_eq!( + get_system_account_kind(&system_account), + Some(SystemAccountKind::System) + ); + } + + #[test] + fn test_get_system_account_kind_nonce_ok() { + let nonce_account = Account::new_data( + 42, + &nonce_state::NonceState::Initialized( + nonce_state::Meta::new(&Pubkey::default()), + Hash::default(), + ), + &system_program::id(), + ) + .unwrap(); + assert_eq!( + get_system_account_kind(&nonce_account), + Some(SystemAccountKind::Nonce) + ); + } + + #[test] + fn test_get_system_account_kind_uninitialized_nonce_account_fail() { + assert_eq!( + get_system_account_kind(&nonce_state::create_account(42)), + None + ); + } + + #[test] + fn test_get_system_account_kind_system_owner_nonzero_nonnonce_data_fail() { + let other_data_account = Account::new_data(42, b"other", &Pubkey::default()).unwrap(); + assert_eq!(get_system_account_kind(&other_data_account), None); + } + + #[test] + fn test_get_system_account_kind_nonsystem_owner_with_nonce_state_data_fail() { + let nonce_account = Account::new_data( + 42, + &nonce_state::NonceState::Initialized( + nonce_state::Meta::new(&Pubkey::default()), + Hash::default(), + ), + &Pubkey::new_rand(), + ) + .unwrap(); + assert_eq!(get_system_account_kind(&nonce_account), None); + } } diff --git a/sdk/src/genesis_config.rs b/sdk/src/genesis_config.rs index 300afde80fadc9..64743d087dbabf 100644 --- a/sdk/src/genesis_config.rs +++ b/sdk/src/genesis_config.rs @@ -7,7 +7,6 @@ use crate::{ fee_calculator::FeeCalculator, hash::{hash, Hash}, inflation::Inflation, - nonce_program::solana_nonce_program, poh_config::PohConfig, pubkey::Pubkey, rent::Rent, @@ -65,7 +64,7 @@ pub fn create_genesis_config(lamports: u64) -> (GenesisConfig, Keypair) { faucet_keypair.pubkey(), Account::new(lamports, 0, &system_program::id()), )], - &[solana_nonce_program(), solana_system_program()], + &[solana_system_program()], ), faucet_keypair, ) diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs index d2de4d0affafd7..483606e5c7feb5 100644 --- a/sdk/src/lib.rs +++ b/sdk/src/lib.rs @@ -16,8 +16,6 @@ pub mod message; pub mod move_loader; pub mod native_loader; pub mod native_token; -pub mod nonce_instruction; -pub mod nonce_program; pub mod nonce_state; pub mod packet; pub mod poh_config; diff --git a/sdk/src/nonce_instruction.rs b/sdk/src/nonce_instruction.rs deleted file mode 100644 index 6118ac90b82cbd..00000000000000 --- a/sdk/src/nonce_instruction.rs +++ /dev/null @@ -1,665 +0,0 @@ -use crate::{ - account::{get_signers, KeyedAccount}, - instruction::{AccountMeta, Instruction, InstructionError, WithSigner}, - instruction_processor_utils::{limited_deserialize, next_keyed_account, DecodeError}, - nonce_program::id, - nonce_state::{NonceAccount, NonceState}, - pubkey::Pubkey, - system_instruction, - sysvar::{ - recent_blockhashes::{self, RecentBlockhashes}, - rent::{self, Rent}, - Sysvar, - }, -}; -use num_derive::{FromPrimitive, ToPrimitive}; -use serde_derive::{Deserialize, Serialize}; -use thiserror::Error; - -#[derive(Error, Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)] -pub enum NonceError { - #[error("recent blockhash list is empty")] - NoRecentBlockhashes, - #[error("stored nonce is still in recent_blockhashes")] - NotExpired, - #[error("specified nonce does not match stored nonce")] - UnexpectedValue, - #[error("cannot handle request in current account state")] - BadAccountState, -} - -impl DecodeError for NonceError { - fn type_of() -> &'static str { - "NonceError" - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] -pub enum NonceInstruction { - /// `Nonce` consumes a stored nonce, replacing it with a successor - /// - /// Expects 2 Accounts: - /// 0 - A NonceAccount - /// 1 - RecentBlockhashes sysvar - /// - /// The current authority must sign a transaction executing this instrucion - Nonce, - - /// `Withdraw` transfers funds out of the nonce account - /// - /// Expects 4 Accounts: - /// 0 - A NonceAccount - /// 1 - A system account to which the lamports will be transferred - /// 2 - RecentBlockhashes sysvar - /// 3 - Rent sysvar - /// - /// The `u64` parameter is the lamports to withdraw, which must leave the - /// account balance above the rent exempt reserve or at zero. - /// - /// The current authority must sign a transaction executing this instruction - Withdraw(u64), - - /// `Initialize` drives state of Uninitalized NonceAccount to Initialized, - /// setting the nonce value. - /// - /// Expects 3 Accounts: - /// 0 - A NonceAccount in the Uninitialized state - /// 1 - RecentBlockHashes sysvar - /// 2 - Rent sysvar - /// - /// The `Pubkey` parameter specifies the entity authorized to execute nonce - /// instruction on the account - /// - /// No signatures are required to execute this instruction, enabling derived - /// nonce account addresses - Initialize(Pubkey), - - /// `Authorize` changes the entity authorized to execute nonce instructions - /// on the account - /// - /// Expects 1 Account: - /// 0 - A NonceAccount - /// - /// The `Pubkey` parameter identifies the entity to authorize - /// - /// The current authority must sign a transaction executing this instruction - Authorize(Pubkey), -} - -pub fn create_nonce_account( - from_pubkey: &Pubkey, - nonce_pubkey: &Pubkey, - authority: &Pubkey, - lamports: u64, -) -> Vec { - vec![ - system_instruction::create_account( - from_pubkey, - nonce_pubkey, - lamports, - NonceState::size() as u64, - &id(), - ), - initialize(nonce_pubkey, authority), - ] -} - -fn initialize(nonce_pubkey: &Pubkey, authority: &Pubkey) -> Instruction { - Instruction::new( - id(), - &NonceInstruction::Initialize(*authority), - vec![ - AccountMeta::new(*nonce_pubkey, false), - AccountMeta::new_readonly(recent_blockhashes::id(), false), - AccountMeta::new_readonly(rent::id(), false), - ], - ) -} - -pub fn nonce(nonce_pubkey: &Pubkey, authorized_pubkey: &Pubkey) -> Instruction { - let account_metas = vec![ - AccountMeta::new(*nonce_pubkey, false), - AccountMeta::new_readonly(recent_blockhashes::id(), false), - ] - .with_signer(authorized_pubkey); - Instruction::new(id(), &NonceInstruction::Nonce, account_metas) -} - -pub fn withdraw( - nonce_pubkey: &Pubkey, - authorized_pubkey: &Pubkey, - to_pubkey: &Pubkey, - lamports: u64, -) -> Instruction { - let account_metas = vec![ - AccountMeta::new(*nonce_pubkey, false), - AccountMeta::new(*to_pubkey, false), - AccountMeta::new_readonly(recent_blockhashes::id(), false), - AccountMeta::new_readonly(rent::id(), false), - ] - .with_signer(authorized_pubkey); - Instruction::new(id(), &NonceInstruction::Withdraw(lamports), account_metas) -} - -pub fn authorize( - nonce_pubkey: &Pubkey, - authorized_pubkey: &Pubkey, - new_authority: &Pubkey, -) -> Instruction { - let account_metas = vec![AccountMeta::new(*nonce_pubkey, false)].with_signer(authorized_pubkey); - Instruction::new( - id(), - &NonceInstruction::Authorize(*new_authority), - account_metas, - ) -} - -pub fn process_instruction( - _program_id: &Pubkey, - keyed_accounts: &mut [KeyedAccount], - data: &[u8], -) -> Result<(), InstructionError> { - let signers = get_signers(keyed_accounts); - - let keyed_accounts = &mut keyed_accounts.iter_mut(); - let me = &mut next_keyed_account(keyed_accounts)?; - - match limited_deserialize(data)? { - NonceInstruction::Nonce => me.nonce( - &RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts)?)?, - &signers, - ), - NonceInstruction::Withdraw(lamports) => { - let to = &mut next_keyed_account(keyed_accounts)?; - me.withdraw( - lamports, - to, - &RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts)?)?, - &Rent::from_keyed_account(next_keyed_account(keyed_accounts)?)?, - &signers, - ) - } - NonceInstruction::Initialize(authorized) => me.initialize( - &authorized, - &RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts)?)?, - &Rent::from_keyed_account(next_keyed_account(keyed_accounts)?)?, - ), - NonceInstruction::Authorize(nonce_authority) => me.authorize(&nonce_authority, &signers), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - account::Account, - hash::{hash, Hash}, - nonce_state, system_program, sysvar, - }; - use bincode::serialize; - - fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> { - let mut accounts: Vec<_> = instruction - .accounts - .iter() - .map(|meta| { - if sysvar::recent_blockhashes::check_id(&meta.pubkey) { - sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ) - } else if sysvar::rent::check_id(&meta.pubkey) { - sysvar::rent::create_account(1, &Rent::free()) - } else { - Account::default() - } - }) - .collect(); - - { - let mut keyed_accounts: Vec<_> = instruction - .accounts - .iter() - .zip(accounts.iter_mut()) - .map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account)) - .collect(); - super::process_instruction(&Pubkey::default(), &mut keyed_accounts, &instruction.data) - } - } - - #[test] - fn test_create_account() { - let from_pubkey = Pubkey::new_rand(); - let nonce_pubkey = Pubkey::new_rand(); - let authorized = nonce_pubkey; - let ixs = create_nonce_account(&from_pubkey, &nonce_pubkey, &authorized, 42); - assert_eq!(ixs.len(), 2); - let ix = &ixs[0]; - assert_eq!(ix.program_id, system_program::id()); - let pubkeys: Vec<_> = ix.accounts.iter().map(|am| am.pubkey).collect(); - assert!(pubkeys.contains(&from_pubkey)); - assert!(pubkeys.contains(&nonce_pubkey)); - } - - #[test] - fn test_process_nonce_ix_no_acc_data_fail() { - assert_eq!( - process_instruction(&nonce(&Pubkey::default(), &Pubkey::default())), - Err(InstructionError::InvalidAccountData), - ); - } - - #[test] - fn test_process_nonce_ix_no_keyed_accs_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [], - &serialize(&NonceInstruction::Nonce).unwrap() - ), - Err(InstructionError::NotEnoughAccountKeys), - ); - } - - #[test] - fn test_process_nonce_ix_only_nonce_acc_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [KeyedAccount::new( - &Pubkey::default(), - true, - &mut Account::default(), - ),], - &serialize(&NonceInstruction::Nonce).unwrap(), - ), - Err(InstructionError::NotEnoughAccountKeys), - ); - } - - #[test] - fn test_process_nonce_ix_bad_recent_blockhash_state_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut Account::default(), - ), - ], - &serialize(&NonceInstruction::Nonce).unwrap(), - ), - Err(InstructionError::InvalidArgument), - ); - } - - #[test] - fn test_process_nonce_ix_ok() { - let mut nonce_acc = nonce_state::create_account(1_000_000); - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ), - ), - KeyedAccount::new( - &sysvar::rent::id(), - false, - &mut sysvar::rent::create_account(1, &Rent::free()), - ), - ], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ) - .unwrap(); - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc,), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &hash(&serialize(&0).unwrap())); 32].into_iter(), - ), - ), - ], - &serialize(&NonceInstruction::Nonce).unwrap(), - ), - Ok(()), - ); - } - - #[test] - fn test_process_withdraw_ix_no_acc_data_fail() { - assert_eq!( - process_instruction(&withdraw( - &Pubkey::default(), - &Pubkey::default(), - &Pubkey::default(), - 1, - )), - Err(InstructionError::InvalidAccountData), - ); - } - - #[test] - fn test_process_withdraw_ix_no_keyed_accs_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [], - &serialize(&NonceInstruction::Withdraw(42)).unwrap(), - ), - Err(InstructionError::NotEnoughAccountKeys), - ); - } - - #[test] - fn test_process_withdraw_ix_only_nonce_acc_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [KeyedAccount::new( - &Pubkey::default(), - true, - &mut Account::default(), - ),], - &serialize(&NonceInstruction::Withdraw(42)).unwrap(), - ), - Err(InstructionError::NotEnoughAccountKeys), - ); - } - - #[test] - fn test_process_withdraw_ix_bad_recent_blockhash_state_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), - KeyedAccount::new(&Pubkey::default(), false, &mut Account::default(),), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut Account::default(), - ), - ], - &serialize(&NonceInstruction::Withdraw(42)).unwrap(), - ), - Err(InstructionError::InvalidArgument), - ); - } - - #[test] - fn test_process_withdraw_ix_bad_rent_state_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new( - &Pubkey::default(), - true, - &mut nonce_state::create_account(1_000_000), - ), - KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ), - ), - KeyedAccount::new(&sysvar::rent::id(), false, &mut Account::default(),), - ], - &serialize(&NonceInstruction::Withdraw(42)).unwrap(), - ), - Err(InstructionError::InvalidArgument), - ); - } - - #[test] - fn test_process_withdraw_ix_ok() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new( - &Pubkey::default(), - true, - &mut nonce_state::create_account(1_000_000), - ), - KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ), - ), - KeyedAccount::new( - &sysvar::rent::id(), - false, - &mut sysvar::rent::create_account(1, &Rent::free()) - ), - ], - &serialize(&NonceInstruction::Withdraw(42)).unwrap(), - ), - Ok(()), - ); - } - - #[test] - fn test_process_initialize_ix_invalid_acc_data_fail() { - let authorized = Pubkey::default(); - assert_eq!( - process_instruction(&initialize(&Pubkey::default(), &authorized)), - Err(InstructionError::InvalidAccountData), - ); - } - - #[test] - fn test_process_initialize_ix_no_keyed_accs_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ), - Err(InstructionError::NotEnoughAccountKeys), - ); - } - - #[test] - fn test_process_initialize_ix_only_nonce_acc_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [KeyedAccount::new( - &Pubkey::default(), - true, - &mut nonce_state::create_account(1_000_000), - ),], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ), - Err(InstructionError::NotEnoughAccountKeys), - ); - } - - #[test] - fn test_process_initialize_bad_recent_blockhash_state_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new( - &Pubkey::default(), - true, - &mut nonce_state::create_account(1_000_000), - ), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut Account::default(), - ), - ], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ), - Err(InstructionError::InvalidArgument), - ); - } - - #[test] - fn test_process_initialize_ix_bad_rent_state_fail() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new( - &Pubkey::default(), - true, - &mut nonce_state::create_account(1_000_000), - ), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ), - ), - KeyedAccount::new(&sysvar::rent::id(), false, &mut Account::default(),), - ], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ), - Err(InstructionError::InvalidArgument), - ); - } - - #[test] - fn test_process_initialize_ix_ok() { - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new( - &Pubkey::default(), - true, - &mut nonce_state::create_account(1_000_000), - ), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ), - ), - KeyedAccount::new( - &sysvar::rent::id(), - false, - &mut sysvar::rent::create_account(1, &Rent::free()) - ), - ], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ), - Ok(()), - ); - } - - #[test] - fn test_process_authorize_ix_ok() { - let mut nonce_acc = nonce_state::create_account(1_000_000); - super::process_instruction( - &Pubkey::default(), - &mut [ - KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc), - KeyedAccount::new( - &sysvar::recent_blockhashes::id(), - false, - &mut sysvar::recent_blockhashes::create_account_with_data( - 1, - vec![(0u64, &Hash::default()); 32].into_iter(), - ), - ), - KeyedAccount::new( - &sysvar::rent::id(), - false, - &mut sysvar::rent::create_account(1, &Rent::free()), - ), - ], - &serialize(&NonceInstruction::Initialize(Pubkey::default())).unwrap(), - ) - .unwrap(); - assert_eq!( - super::process_instruction( - &Pubkey::default(), - &mut [KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc,),], - &serialize(&NonceInstruction::Authorize(Pubkey::default(),)).unwrap(), - ), - Ok(()), - ); - } - - #[test] - fn test_process_authorize_bad_account_data_fail() { - assert_eq!( - process_instruction(&authorize( - &Pubkey::default(), - &Pubkey::default(), - &Pubkey::default(), - )), - Err(InstructionError::InvalidAccountData), - ); - } - - #[test] - fn test_custom_error_decode() { - use num_traits::FromPrimitive; - fn pretty_err(err: InstructionError) -> String - where - T: 'static + std::error::Error + DecodeError + FromPrimitive, - { - if let InstructionError::CustomError(code) = err { - let specific_error: T = T::decode_custom_error_to_enum(code).unwrap(); - format!( - "{:?}: {}::{:?} - {}", - err, - T::type_of(), - specific_error, - specific_error, - ) - } else { - "".to_string() - } - } - assert_eq!( - "CustomError(0): NonceError::NoRecentBlockhashes - recent blockhash list is empty", - pretty_err::(NonceError::NoRecentBlockhashes.into()) - ); - assert_eq!( - "CustomError(1): NonceError::NotExpired - stored nonce is still in recent_blockhashes", - pretty_err::(NonceError::NotExpired.into()) - ); - assert_eq!( - "CustomError(2): NonceError::UnexpectedValue - specified nonce does not match stored nonce", - pretty_err::(NonceError::UnexpectedValue.into()) - ); - assert_eq!( - "CustomError(3): NonceError::BadAccountState - cannot handle request in current account state", - pretty_err::(NonceError::BadAccountState.into()) - ); - } -} diff --git a/sdk/src/nonce_program.rs b/sdk/src/nonce_program.rs deleted file mode 100644 index 7e92a9e55981c4..00000000000000 --- a/sdk/src/nonce_program.rs +++ /dev/null @@ -1,5 +0,0 @@ -crate::declare_id!("Nonce11111111111111111111111111111111111111"); - -pub fn solana_nonce_program() -> (String, crate::pubkey::Pubkey) { - ("solana_nonce_program".to_string(), id()) -} diff --git a/sdk/src/nonce_state.rs b/sdk/src/nonce_state.rs index 87ce7d45b1159f..a56b632a6ee741 100644 --- a/sdk/src/nonce_state.rs +++ b/sdk/src/nonce_state.rs @@ -3,9 +3,9 @@ use crate::{ account_utils::State, hash::Hash, instruction::InstructionError, - nonce_instruction::NonceError, - nonce_program, pubkey::Pubkey, + system_instruction::NonceError, + system_program, sysvar::recent_blockhashes::RecentBlockhashes, sysvar::rent::Rent, }; @@ -45,12 +45,12 @@ impl NonceState { } pub trait NonceAccount { - fn nonce( + fn nonce_advance( &mut self, recent_blockhashes: &RecentBlockhashes, signers: &HashSet, ) -> Result<(), InstructionError>; - fn withdraw( + fn nonce_withdraw( &mut self, lamports: u64, to: &mut KeyedAccount, @@ -58,13 +58,13 @@ pub trait NonceAccount { rent: &Rent, signers: &HashSet, ) -> Result<(), InstructionError>; - fn initialize( + fn nonce_initialize( &mut self, nonce_authority: &Pubkey, recent_blockhashes: &RecentBlockhashes, rent: &Rent, ) -> Result<(), InstructionError>; - fn authorize( + fn nonce_authorize( &mut self, nonce_authority: &Pubkey, signers: &HashSet, @@ -72,7 +72,7 @@ pub trait NonceAccount { } impl<'a> NonceAccount for KeyedAccount<'a> { - fn nonce( + fn nonce_advance( &mut self, recent_blockhashes: &RecentBlockhashes, signers: &HashSet, @@ -97,7 +97,7 @@ impl<'a> NonceAccount for KeyedAccount<'a> { self.set_state(&NonceState::Initialized(meta, recent_blockhashes[0])) } - fn withdraw( + fn nonce_withdraw( &mut self, lamports: u64, to: &mut KeyedAccount, @@ -137,7 +137,7 @@ impl<'a> NonceAccount for KeyedAccount<'a> { Ok(()) } - fn initialize( + fn nonce_initialize( &mut self, nonce_authority: &Pubkey, recent_blockhashes: &RecentBlockhashes, @@ -161,7 +161,7 @@ impl<'a> NonceAccount for KeyedAccount<'a> { self.set_state(&NonceState::Initialized(meta, recent_blockhashes[0])) } - fn authorize( + fn nonce_authorize( &mut self, nonce_authority: &Pubkey, signers: &HashSet, @@ -183,7 +183,7 @@ pub fn create_account(lamports: u64) -> Account { lamports, &NonceState::Uninitialized, NonceState::size(), - &nonce_program::id(), + &system_program::id(), ) .expect("nonce_account") } @@ -205,7 +205,7 @@ mod test { use super::*; use crate::{ account::KeyedAccount, - nonce_instruction::NonceError, + system_instruction::NonceError, sysvar::recent_blockhashes::{create_test_recent_blockhashes, RecentBlockhashes}, }; use std::iter::FromIterator; @@ -238,20 +238,24 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(95); let authorized = keyed_account.unsigned_key().clone(); keyed_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let state: NonceState = keyed_account.state().unwrap(); let stored = recent_blockhashes[0]; // First nonce instruction drives state from Uninitialized to Initialized assert_eq!(state, NonceState::Initialized(meta, stored)); let recent_blockhashes = create_test_recent_blockhashes(63); - keyed_account.nonce(&recent_blockhashes, &signers).unwrap(); + keyed_account + .nonce_advance(&recent_blockhashes, &signers) + .unwrap(); let state: NonceState = keyed_account.state().unwrap(); let stored = recent_blockhashes[0]; // Second nonce instruction consumes and replaces stored nonce assert_eq!(state, NonceState::Initialized(meta, stored)); let recent_blockhashes = create_test_recent_blockhashes(31); - keyed_account.nonce(&recent_blockhashes, &signers).unwrap(); + keyed_account + .nonce_advance(&recent_blockhashes, &signers) + .unwrap(); let state: NonceState = keyed_account.state().unwrap(); let stored = recent_blockhashes[0]; // Third nonce instruction for fun and profit @@ -262,7 +266,7 @@ mod test { let expect_nonce_lamports = keyed_account.account.lamports - withdraw_lamports; let expect_to_lamports = to_keyed.account.lamports + withdraw_lamports; keyed_account - .withdraw( + .nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -291,7 +295,7 @@ mod test { let authorized = nonce_account.unsigned_key().clone(); let meta = Meta::new(&authorized); nonce_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let pubkey = nonce_account.account.owner.clone(); let mut nonce_account = KeyedAccount::new(&pubkey, false, nonce_account.account); @@ -299,7 +303,7 @@ mod test { assert_eq!(state, NonceState::Initialized(meta, stored)); let signers = HashSet::new(); let recent_blockhashes = create_test_recent_blockhashes(0); - let result = nonce_account.nonce(&recent_blockhashes, &signers); + let result = nonce_account.nonce_advance(&recent_blockhashes, &signers); assert_eq!(result, Err(InstructionError::MissingRequiredSignature),); }) } @@ -317,10 +321,10 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(0); let authorized = keyed_account.unsigned_key().clone(); keyed_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let recent_blockhashes = RecentBlockhashes::from_iter(vec![].into_iter()); - let result = keyed_account.nonce(&recent_blockhashes, &signers); + let result = keyed_account.nonce_advance(&recent_blockhashes, &signers); assert_eq!(result, Err(NonceError::NoRecentBlockhashes.into())); }) } @@ -338,9 +342,9 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(63); let authorized = keyed_account.unsigned_key().clone(); keyed_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); - let result = keyed_account.nonce(&recent_blockhashes, &signers); + let result = keyed_account.nonce_advance(&recent_blockhashes, &signers); assert_eq!(result, Err(NonceError::NotExpired.into())); }) } @@ -356,7 +360,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(keyed_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(63); - let result = keyed_account.nonce(&recent_blockhashes, &signers); + let result = keyed_account.nonce_advance(&recent_blockhashes, &signers); assert_eq!(result, Err(NonceError::BadAccountState.into())); }) } @@ -375,12 +379,12 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(63); let authorized = nonce_authority.unsigned_key().clone(); nonce_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let mut signers = HashSet::new(); signers.insert(nonce_authority.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(31); - let result = nonce_account.nonce(&recent_blockhashes, &signers); + let result = nonce_account.nonce_advance(&recent_blockhashes, &signers); assert_eq!(result, Ok(())); }); }); @@ -400,9 +404,9 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(63); let authorized = nonce_authority.unsigned_key().clone(); nonce_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); - let result = nonce_account.nonce(&recent_blockhashes, &signers); + let result = nonce_account.nonce_advance(&recent_blockhashes, &signers); assert_eq!(result, Err(InstructionError::MissingRequiredSignature),); }); }); @@ -426,7 +430,7 @@ mod test { let expect_nonce_lamports = nonce_keyed.account.lamports - withdraw_lamports; let expect_to_lamports = to_keyed.account.lamports + withdraw_lamports; nonce_keyed - .withdraw( + .nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -459,7 +463,7 @@ mod test { with_test_keyed_account(42, false, |mut to_keyed| { let signers = HashSet::new(); let recent_blockhashes = create_test_recent_blockhashes(0); - let result = nonce_keyed.withdraw( + let result = nonce_keyed.nonce_withdraw( nonce_keyed.account.lamports, &mut to_keyed, &recent_blockhashes, @@ -485,7 +489,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(nonce_keyed.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(0); - let result = nonce_keyed.withdraw( + let result = nonce_keyed.nonce_withdraw( nonce_keyed.account.lamports + 1, &mut to_keyed, &recent_blockhashes, @@ -513,7 +517,7 @@ mod test { let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports; let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports; nonce_keyed - .withdraw( + .nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -529,7 +533,7 @@ mod test { let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports; let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports; nonce_keyed - .withdraw( + .nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -559,7 +563,7 @@ mod test { let authorized = nonce_keyed.unsigned_key().clone(); let meta = Meta::new(&authorized); nonce_keyed - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let state: NonceState = nonce_keyed.state().unwrap(); let stored = recent_blockhashes[0]; @@ -569,7 +573,7 @@ mod test { let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports; let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports; nonce_keyed - .withdraw( + .nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -587,7 +591,7 @@ mod test { let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports; let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports; nonce_keyed - .withdraw( + .nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -612,13 +616,13 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(0); let authorized = nonce_keyed.unsigned_key().clone(); nonce_keyed - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); with_test_keyed_account(42, false, |mut to_keyed| { let mut signers = HashSet::new(); signers.insert(nonce_keyed.signer_key().unwrap().clone()); let withdraw_lamports = nonce_keyed.account.lamports; - let result = nonce_keyed.withdraw( + let result = nonce_keyed.nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -641,14 +645,14 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(95); let authorized = nonce_keyed.unsigned_key().clone(); nonce_keyed - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); with_test_keyed_account(42, false, |mut to_keyed| { let recent_blockhashes = create_test_recent_blockhashes(63); let mut signers = HashSet::new(); signers.insert(nonce_keyed.signer_key().unwrap().clone()); let withdraw_lamports = nonce_keyed.account.lamports + 1; - let result = nonce_keyed.withdraw( + let result = nonce_keyed.nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -671,14 +675,14 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(95); let authorized = nonce_keyed.unsigned_key().clone(); nonce_keyed - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); with_test_keyed_account(42, false, |mut to_keyed| { let recent_blockhashes = create_test_recent_blockhashes(63); let mut signers = HashSet::new(); signers.insert(nonce_keyed.signer_key().unwrap().clone()); let withdraw_lamports = nonce_keyed.account.lamports - min_lamports + 1; - let result = nonce_keyed.withdraw( + let result = nonce_keyed.nonce_withdraw( withdraw_lamports, &mut to_keyed, &recent_blockhashes, @@ -706,7 +710,7 @@ mod test { let stored = recent_blockhashes[0]; let authorized = keyed_account.unsigned_key().clone(); let meta = Meta::new(&authorized); - let result = keyed_account.initialize(&authorized, &recent_blockhashes, &rent); + let result = keyed_account.nonce_initialize(&authorized, &recent_blockhashes, &rent); assert_eq!(result, Ok(())); let state: NonceState = keyed_account.state().unwrap(); assert_eq!(state, NonceState::Initialized(meta, stored)); @@ -725,7 +729,7 @@ mod test { signers.insert(keyed_account.signer_key().unwrap().clone()); let recent_blockhashes = RecentBlockhashes::from_iter(vec![].into_iter()); let authorized = keyed_account.unsigned_key().clone(); - let result = keyed_account.initialize(&authorized, &recent_blockhashes, &rent); + let result = keyed_account.nonce_initialize(&authorized, &recent_blockhashes, &rent); assert_eq!(result, Err(NonceError::NoRecentBlockhashes.into())); }) } @@ -741,10 +745,10 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(31); let authorized = keyed_account.unsigned_key().clone(); keyed_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let recent_blockhashes = create_test_recent_blockhashes(0); - let result = keyed_account.initialize(&authorized, &recent_blockhashes, &rent); + let result = keyed_account.nonce_initialize(&authorized, &recent_blockhashes, &rent); assert_eq!(result, Err(NonceError::BadAccountState.into())); }) } @@ -759,7 +763,7 @@ mod test { with_test_keyed_account(min_lamports - 42, true, |keyed_account| { let recent_blockhashes = create_test_recent_blockhashes(63); let authorized = keyed_account.unsigned_key().clone(); - let result = keyed_account.initialize(&authorized, &recent_blockhashes, &rent); + let result = keyed_account.nonce_initialize(&authorized, &recent_blockhashes, &rent); assert_eq!(result, Err(InstructionError::InsufficientFunds)); }) } @@ -778,11 +782,11 @@ mod test { let stored = recent_blockhashes[0]; let authorized = nonce_account.unsigned_key().clone(); nonce_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); let authorized = &Pubkey::default().clone(); let meta = Meta::new(&authorized); - let result = nonce_account.authorize(&Pubkey::default(), &signers); + let result = nonce_account.nonce_authorize(&Pubkey::default(), &signers); assert_eq!(result, Ok(())); let state: NonceState = nonce_account.state().unwrap(); assert_eq!(state, NonceState::Initialized(meta, stored)); @@ -799,7 +803,7 @@ mod test { with_test_keyed_account(min_lamports + 42, true, |nonce_account| { let mut signers = HashSet::new(); signers.insert(nonce_account.signer_key().unwrap().clone()); - let result = nonce_account.authorize(&Pubkey::default(), &signers); + let result = nonce_account.nonce_authorize(&Pubkey::default(), &signers); assert_eq!(result, Err(NonceError::BadAccountState.into())); }) } @@ -817,9 +821,9 @@ mod test { let recent_blockhashes = create_test_recent_blockhashes(31); let authorized = &Pubkey::default().clone(); nonce_account - .initialize(&authorized, &recent_blockhashes, &rent) + .nonce_initialize(&authorized, &recent_blockhashes, &rent) .unwrap(); - let result = nonce_account.authorize(&Pubkey::default(), &signers); + let result = nonce_account.nonce_authorize(&Pubkey::default(), &signers); assert_eq!(result, Err(InstructionError::MissingRequiredSignature)); }) } diff --git a/sdk/src/system_instruction.rs b/sdk/src/system_instruction.rs index c0790e3fc1302a..c1ff9eda66973c 100644 --- a/sdk/src/system_instruction.rs +++ b/sdk/src/system_instruction.rs @@ -1,9 +1,12 @@ use crate::hash::hashv; -use crate::instruction::{AccountMeta, Instruction}; +use crate::instruction::{AccountMeta, Instruction, WithSigner}; use crate::instruction_processor_utils::DecodeError; +use crate::nonce_state::NonceState; use crate::pubkey::Pubkey; use crate::system_program; +use crate::sysvar::{recent_blockhashes, rent}; use num_derive::{FromPrimitive, ToPrimitive}; +use thiserror::Error; #[derive(Serialize, Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)] pub enum SystemError { @@ -30,6 +33,24 @@ impl std::fmt::Display for SystemError { } impl std::error::Error for SystemError {} +#[derive(Error, Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)] +pub enum NonceError { + #[error("recent blockhash list is empty")] + NoRecentBlockhashes, + #[error("stored nonce is still in recent_blockhashes")] + NotExpired, + #[error("specified nonce does not match stored nonce")] + UnexpectedValue, + #[error("cannot handle request in current account state")] + BadAccountState, +} + +impl DecodeError for NonceError { + fn type_of() -> &'static str { + "NonceError" + } +} + /// maximum length of derived address seed pub const MAX_ADDRESS_SEED_LEN: usize = 32; @@ -70,6 +91,51 @@ pub enum SystemInstruction { space: u64, program_id: Pubkey, }, + /// `NonceAdvance` consumes a stored nonce, replacing it with a successor + /// + /// Expects 2 Accounts: + /// 0 - A NonceAccount + /// 1 - RecentBlockhashes sysvar + /// + /// The current authority must sign a transaction executing this instrucion + NonceAdvance, + /// `NonceWithdraw` transfers funds out of the nonce account + /// + /// Expects 4 Accounts: + /// 0 - A NonceAccount + /// 1 - A system account to which the lamports will be transferred + /// 2 - RecentBlockhashes sysvar + /// 3 - Rent sysvar + /// + /// The `u64` parameter is the lamports to withdraw, which must leave the + /// account balance above the rent exempt reserve or at zero. + /// + /// The current authority must sign a transaction executing this instruction + NonceWithdraw(u64), + /// `NonceInitialize` drives state of Uninitalized NonceAccount to Initialized, + /// setting the nonce value. + /// + /// Expects 3 Accounts: + /// 0 - A NonceAccount in the Uninitialized state + /// 1 - RecentBlockHashes sysvar + /// 2 - Rent sysvar + /// + /// The `Pubkey` parameter specifies the entity authorized to execute nonce + /// instruction on the account + /// + /// No signatures are required to execute this instruction, enabling derived + /// nonce account addresses + NonceInitialize(Pubkey), + /// `NonceAuthorize` changes the entity authorized to execute nonce instructions + /// on the account + /// + /// Expects 1 Account: + /// 0 - A NonceAccount + /// + /// The `Pubkey` parameter identifies the entity to authorize + /// + /// The current authority must sign a transaction executing this instruction + NonceAuthorize(Pubkey), } pub fn create_account( @@ -164,9 +230,82 @@ pub fn create_address_with_seed( )) } +pub fn create_nonce_account( + from_pubkey: &Pubkey, + nonce_pubkey: &Pubkey, + authority: &Pubkey, + lamports: u64, +) -> Vec { + vec![ + create_account( + from_pubkey, + nonce_pubkey, + lamports, + NonceState::size() as u64, + &system_program::id(), + ), + Instruction::new( + system_program::id(), + &SystemInstruction::NonceInitialize(*authority), + vec![ + AccountMeta::new(*nonce_pubkey, false), + AccountMeta::new_readonly(recent_blockhashes::id(), false), + AccountMeta::new_readonly(rent::id(), false), + ], + ), + ] +} + +pub fn nonce_advance(nonce_pubkey: &Pubkey, authorized_pubkey: &Pubkey) -> Instruction { + let account_metas = vec![ + AccountMeta::new(*nonce_pubkey, false), + AccountMeta::new_readonly(recent_blockhashes::id(), false), + ] + .with_signer(authorized_pubkey); + Instruction::new( + system_program::id(), + &SystemInstruction::NonceAdvance, + account_metas, + ) +} + +pub fn nonce_withdraw( + nonce_pubkey: &Pubkey, + authorized_pubkey: &Pubkey, + to_pubkey: &Pubkey, + lamports: u64, +) -> Instruction { + let account_metas = vec![ + AccountMeta::new(*nonce_pubkey, false), + AccountMeta::new(*to_pubkey, false), + AccountMeta::new_readonly(recent_blockhashes::id(), false), + AccountMeta::new_readonly(rent::id(), false), + ] + .with_signer(authorized_pubkey); + Instruction::new( + system_program::id(), + &SystemInstruction::NonceWithdraw(lamports), + account_metas, + ) +} + +pub fn nonce_authorize( + nonce_pubkey: &Pubkey, + authorized_pubkey: &Pubkey, + new_authority: &Pubkey, +) -> Instruction { + let account_metas = vec![AccountMeta::new(*nonce_pubkey, false)].with_signer(authorized_pubkey); + Instruction::new( + system_program::id(), + &SystemInstruction::NonceAuthorize(*new_authority), + account_metas, + ) +} + #[cfg(test)] mod tests { use super::*; + use crate::instruction::{Instruction, InstructionError}; fn get_keys(instruction: &Instruction) -> Vec { instruction.accounts.iter().map(|x| x.pubkey).collect() @@ -236,4 +375,56 @@ mod tests { assert_eq!(get_keys(&instructions[0]), vec![alice_pubkey, bob_pubkey]); assert_eq!(get_keys(&instructions[1]), vec![alice_pubkey, carol_pubkey]); } + + #[test] + fn test_create_nonce_account() { + let from_pubkey = Pubkey::new_rand(); + let nonce_pubkey = Pubkey::new_rand(); + let authorized = nonce_pubkey; + let ixs = create_nonce_account(&from_pubkey, &nonce_pubkey, &authorized, 42); + assert_eq!(ixs.len(), 2); + let ix = &ixs[0]; + assert_eq!(ix.program_id, system_program::id()); + let pubkeys: Vec<_> = ix.accounts.iter().map(|am| am.pubkey).collect(); + assert!(pubkeys.contains(&from_pubkey)); + assert!(pubkeys.contains(&nonce_pubkey)); + } + + #[test] + fn test_nonce_error_decode() { + use num_traits::FromPrimitive; + fn pretty_err(err: InstructionError) -> String + where + T: 'static + std::error::Error + DecodeError + FromPrimitive, + { + if let InstructionError::CustomError(code) = err { + let specific_error: T = T::decode_custom_error_to_enum(code).unwrap(); + format!( + "{:?}: {}::{:?} - {}", + err, + T::type_of(), + specific_error, + specific_error, + ) + } else { + "".to_string() + } + } + assert_eq!( + "CustomError(0): NonceError::NoRecentBlockhashes - recent blockhash list is empty", + pretty_err::(NonceError::NoRecentBlockhashes.into()) + ); + assert_eq!( + "CustomError(1): NonceError::NotExpired - stored nonce is still in recent_blockhashes", + pretty_err::(NonceError::NotExpired.into()) + ); + assert_eq!( + "CustomError(2): NonceError::UnexpectedValue - specified nonce does not match stored nonce", + pretty_err::(NonceError::UnexpectedValue.into()) + ); + assert_eq!( + "CustomError(3): NonceError::BadAccountState - cannot handle request in current account state", + pretty_err::(NonceError::BadAccountState.into()) + ); + } } diff --git a/sdk/src/transaction.rs b/sdk/src/transaction.rs index 15dfa0be6ae44e..ad8974d618c95f 100644 --- a/sdk/src/transaction.rs +++ b/sdk/src/transaction.rs @@ -3,10 +3,10 @@ use crate::hash::Hash; use crate::instruction::{CompiledInstruction, Instruction, InstructionError}; use crate::message::Message; -use crate::nonce_instruction; use crate::pubkey::Pubkey; use crate::short_vec; use crate::signature::{KeypairUtil, Signature}; +use crate::system_instruction; use bincode::serialize; use std::result; @@ -103,7 +103,8 @@ impl Transaction { nonce_authority_pubkey: &Pubkey, nonce_hash: Hash, ) -> Self { - let nonce_ix = nonce_instruction::nonce(&nonce_account_pubkey, &nonce_authority_pubkey); + let nonce_ix = + system_instruction::nonce_advance(&nonce_account_pubkey, &nonce_authority_pubkey); instructions.insert(0, nonce_ix); Self::new_signed_with_payer(instructions, payer, signing_keypairs, nonce_hash) }