Remove demote_program_write_locks feature (#19877)

* Remove demote_program_write_locks feature

* Update test
This commit is contained in:
Tyera Eulberg
2021-09-14 13:25:42 -05:00
committed by GitHub
parent bf7c2f79c1
commit a4ebbc9f55
11 changed files with 76 additions and 186 deletions

View File

@@ -140,7 +140,7 @@ fn format_account_mode(message: &Message, index: usize) -> String {
} else { } else {
"-" "-"
}, },
if message.is_writable(index, /*demote_program_write_locks=*/ true) { if message.is_writable(index) {
"w" // comment for consistent rust fmt (no joking; lol) "w" // comment for consistent rust fmt (no joking; lol)
} else { } else {
"-" "-"

View File

@@ -109,9 +109,8 @@ impl TransactionStatusService {
}) })
.expect("FeeCalculator must exist"); .expect("FeeCalculator must exist");
let fee = fee_calculator.calculate_fee(transaction.message()); let fee = fee_calculator.calculate_fee(transaction.message());
let (writable_keys, readonly_keys) = transaction let (writable_keys, readonly_keys) =
.message transaction.message.get_account_keys_by_lock_type();
.get_account_keys_by_lock_type(bank.demote_program_write_locks());
let inner_instructions = inner_instructions.map(|inner_instructions| { let inner_instructions = inner_instructions.map(|inner_instructions| {
inner_instructions inner_instructions

View File

@@ -19,7 +19,6 @@ use {
clock::{Clock, Slot}, clock::{Clock, Slot},
entrypoint::{ProgramResult, SUCCESS}, entrypoint::{ProgramResult, SUCCESS},
epoch_schedule::EpochSchedule, epoch_schedule::EpochSchedule,
feature_set::demote_program_write_locks,
fee_calculator::{FeeCalculator, FeeRateGovernor}, fee_calculator::{FeeCalculator, FeeRateGovernor},
genesis_config::{ClusterType, GenesisConfig}, genesis_config::{ClusterType, GenesisConfig},
hash::Hash, hash::Hash,
@@ -256,14 +255,12 @@ impl solana_sdk::program_stubs::SyscallStubs for SyscallStubs {
} }
panic!("Program id {} wasn't found in account_infos", program_id); panic!("Program id {} wasn't found in account_infos", program_id);
}; };
let demote_program_write_locks =
invoke_context.is_feature_active(&demote_program_write_locks::id());
// TODO don't have the caller's keyed_accounts so can't validate writer or signer escalation or deescalation yet // TODO don't have the caller's keyed_accounts so can't validate writer or signer escalation or deescalation yet
let caller_privileges = message let caller_privileges = message
.account_keys .account_keys
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, _)| message.is_writable(i, demote_program_write_locks)) .map(|(i, _)| message.is_writable(i))
.collect::<Vec<bool>>(); .collect::<Vec<bool>>();
stable_log::program_invoke(&logger, &program_id, invoke_context.invoke_depth()); stable_log::program_invoke(&logger, &program_id, invoke_context.invoke_depth());
@@ -334,7 +331,7 @@ impl solana_sdk::program_stubs::SyscallStubs for SyscallStubs {
// Copy writeable account modifications back into the caller's AccountInfos // Copy writeable account modifications back into the caller's AccountInfos
for (i, account_pubkey) in message.account_keys.iter().enumerate() { for (i, account_pubkey) in message.account_keys.iter().enumerate() {
if !message.is_writable(i, demote_program_write_locks) { if !message.is_writable(i) {
continue; continue;
} }

View File

@@ -19,9 +19,9 @@ use solana_sdk::{
entrypoint::{MAX_PERMITTED_DATA_INCREASE, SUCCESS}, entrypoint::{MAX_PERMITTED_DATA_INCREASE, SUCCESS},
epoch_schedule::EpochSchedule, epoch_schedule::EpochSchedule,
feature_set::{ feature_set::{
cpi_data_cost, cpi_share_ro_and_exec_accounts, demote_program_write_locks, cpi_data_cost, cpi_share_ro_and_exec_accounts, enforce_aligned_host_addrs,
enforce_aligned_host_addrs, keccak256_syscall_enabled, memory_ops_syscalls, keccak256_syscall_enabled, memory_ops_syscalls, set_upgrade_authority_via_cpi_enabled,
set_upgrade_authority_via_cpi_enabled, sysvar_via_syscall, update_data_on_realloc, sysvar_via_syscall, update_data_on_realloc,
}, },
hash::{Hasher, HASH_BYTES}, hash::{Hasher, HASH_BYTES},
ic_msg, ic_msg,
@@ -2140,14 +2140,7 @@ fn call<'a>(
signers_seeds_len: u64, signers_seeds_len: u64,
memory_mapping: &MemoryMapping, memory_mapping: &MemoryMapping,
) -> Result<u64, EbpfError<BpfError>> { ) -> Result<u64, EbpfError<BpfError>> {
let ( let (message, executables, accounts, account_refs, caller_write_privileges) = {
message,
executables,
accounts,
account_refs,
caller_write_privileges,
demote_program_write_locks,
) = {
let invoke_context = syscall.get_context()?; let invoke_context = syscall.get_context()?;
invoke_context invoke_context
@@ -2237,7 +2230,6 @@ fn call<'a>(
accounts, accounts,
account_refs, account_refs,
caller_write_privileges, caller_write_privileges,
invoke_context.is_feature_active(&demote_program_write_locks::id()),
) )
}; };
@@ -2263,7 +2255,7 @@ fn call<'a>(
for (i, (account, account_ref)) in accounts.iter().zip(account_refs).enumerate() { for (i, (account, account_ref)) in accounts.iter().zip(account_refs).enumerate() {
let account = account.borrow(); let account = account.borrow();
if let Some(mut account_ref) = account_ref { if let Some(mut account_ref) = account_ref {
if message.is_writable(i, demote_program_write_locks) && !account.executable() { if message.is_writable(i) && !account.executable() {
*account_ref.lamports = account.lamports(); *account_ref.lamports = account.lamports();
*account_ref.owner = *account.owner(); *account_ref.owner = *account.owner();
if account_ref.data.len() != account.data().len() { if account_ref.data.len() != account.data().len() {

View File

@@ -170,11 +170,8 @@ impl Accounts {
false false
} }
fn construct_instructions_account( fn construct_instructions_account(message: &Message) -> AccountSharedData {
message: &Message, let mut data = message.serialize_instructions();
demote_program_write_locks: bool,
) -> AccountSharedData {
let mut data = message.serialize_instructions(demote_program_write_locks);
// add room for current instruction index. // add room for current instruction index.
data.resize(data.len() + 2, 0); data.resize(data.len() + 2, 0);
AccountSharedData::from(Account { AccountSharedData::from(Account {
@@ -204,8 +201,6 @@ impl Accounts {
let mut accounts = Vec::with_capacity(message.account_keys.len()); let mut accounts = Vec::with_capacity(message.account_keys.len());
let mut account_deps = Vec::with_capacity(message.account_keys.len()); let mut account_deps = Vec::with_capacity(message.account_keys.len());
let mut rent_debits = RentDebits::default(); let mut rent_debits = RentDebits::default();
let demote_program_write_locks =
feature_set.is_active(&feature_set::demote_program_write_locks::id());
let is_upgradeable_loader_present = is_upgradeable_loader_present(message); let is_upgradeable_loader_present = is_upgradeable_loader_present(message);
for (i, key) in message.account_keys.iter().enumerate() { for (i, key) in message.account_keys.iter().enumerate() {
@@ -217,13 +212,13 @@ impl Accounts {
if solana_sdk::sysvar::instructions::check_id(key) if solana_sdk::sysvar::instructions::check_id(key)
&& feature_set.is_active(&feature_set::instructions_sysvar_enabled::id()) && feature_set.is_active(&feature_set::instructions_sysvar_enabled::id())
{ {
Self::construct_instructions_account(message, demote_program_write_locks) Self::construct_instructions_account(message)
} else { } else {
let (account, rent) = self let (account, rent) = self
.accounts_db .accounts_db
.load(ancestors, key) .load(ancestors, key)
.map(|(mut account, _)| { .map(|(mut account, _)| {
if message.is_writable(i, demote_program_write_locks) { if message.is_writable(i) {
let rent_due = rent_collector let rent_due = rent_collector
.collect_from_existing_account(&key, &mut account); .collect_from_existing_account(&key, &mut account);
(account, rent_due) (account, rent_due)
@@ -234,10 +229,7 @@ impl Accounts {
.unwrap_or_default(); .unwrap_or_default();
if bpf_loader_upgradeable::check_id(&account.owner) { if bpf_loader_upgradeable::check_id(&account.owner) {
if demote_program_write_locks if message.is_writable(i) && !is_upgradeable_loader_present {
&& message.is_writable(i, demote_program_write_locks)
&& !is_upgradeable_loader_present
{
error_counters.invalid_writable_account += 1; error_counters.invalid_writable_account += 1;
return Err(TransactionError::InvalidWritableAccount); return Err(TransactionError::InvalidWritableAccount);
} }
@@ -263,10 +255,7 @@ impl Accounts {
return Err(TransactionError::InvalidProgramForExecution); return Err(TransactionError::InvalidProgramForExecution);
} }
} }
} else if account.executable } else if account.executable && message.is_writable(i) {
&& demote_program_write_locks
&& message.is_writable(i, demote_program_write_locks)
{
error_counters.invalid_writable_account += 1; error_counters.invalid_writable_account += 1;
return Err(TransactionError::InvalidWritableAccount); return Err(TransactionError::InvalidWritableAccount);
} }
@@ -785,21 +774,13 @@ impl Accounts {
Ok(()) Ok(())
} }
fn unlock_account( fn unlock_account(&self, tx: &Transaction, result: &Result<()>, locks: &mut AccountLocks) {
&self,
tx: &Transaction,
result: &Result<()>,
locks: &mut AccountLocks,
demote_program_write_locks: bool,
) {
match result { match result {
Err(TransactionError::AccountInUse) => (), Err(TransactionError::AccountInUse) => (),
Err(TransactionError::SanitizeFailure) => (), Err(TransactionError::SanitizeFailure) => (),
Err(TransactionError::AccountLoadedTwice) => (), Err(TransactionError::AccountLoadedTwice) => (),
_ => { _ => {
let (writable_keys, readonly_keys) = &tx let (writable_keys, readonly_keys) = &tx.message().get_account_keys_by_lock_type();
.message()
.get_account_keys_by_lock_type(demote_program_write_locks);
for k in writable_keys { for k in writable_keys {
locks.unlock_write(k); locks.unlock_write(k);
} }
@@ -828,11 +809,7 @@ impl Accounts {
/// This function will prevent multiple threads from modifying the same account state at the /// This function will prevent multiple threads from modifying the same account state at the
/// same time /// same time
#[must_use] #[must_use]
pub fn lock_accounts<'a>( pub fn lock_accounts<'a>(&self, txs: impl Iterator<Item = &'a Transaction>) -> Vec<Result<()>> {
&self,
txs: impl Iterator<Item = &'a Transaction>,
demote_program_write_locks: bool,
) -> Vec<Result<()>> {
use solana_sdk::sanitize::Sanitize; use solana_sdk::sanitize::Sanitize;
let keys: Vec<Result<_>> = txs let keys: Vec<Result<_>> = txs
.map(|tx| { .map(|tx| {
@@ -842,9 +819,7 @@ impl Accounts {
return Err(TransactionError::AccountLoadedTwice); return Err(TransactionError::AccountLoadedTwice);
} }
Ok(tx Ok(tx.message().get_account_keys_by_lock_type())
.message()
.get_account_keys_by_lock_type(demote_program_write_locks))
}) })
.collect(); .collect();
let mut account_locks = &mut self.account_locks.lock().unwrap(); let mut account_locks = &mut self.account_locks.lock().unwrap();
@@ -863,17 +838,11 @@ impl Accounts {
&self, &self,
txs: impl Iterator<Item = &'a Transaction>, txs: impl Iterator<Item = &'a Transaction>,
results: &[Result<()>], results: &[Result<()>],
demote_program_write_locks: bool,
) { ) {
let mut account_locks = self.account_locks.lock().unwrap(); let mut account_locks = self.account_locks.lock().unwrap();
debug!("bank unlock accounts"); debug!("bank unlock accounts");
for (tx, lock_result) in txs.zip(results) { for (tx, lock_result) in txs.zip(results) {
self.unlock_account( self.unlock_account(tx, lock_result, &mut account_locks);
tx,
lock_result,
&mut account_locks,
demote_program_write_locks,
);
} }
} }
@@ -890,7 +859,6 @@ impl Accounts {
last_blockhash_with_fee_calculator: &(Hash, FeeCalculator), last_blockhash_with_fee_calculator: &(Hash, FeeCalculator),
fix_recent_blockhashes_sysvar_delay: bool, fix_recent_blockhashes_sysvar_delay: bool,
merge_nonce_error_into_system_error: bool, merge_nonce_error_into_system_error: bool,
demote_program_write_locks: bool,
) { ) {
let accounts_to_store = self.collect_accounts_to_store( let accounts_to_store = self.collect_accounts_to_store(
txs, txs,
@@ -900,7 +868,6 @@ impl Accounts {
last_blockhash_with_fee_calculator, last_blockhash_with_fee_calculator,
fix_recent_blockhashes_sysvar_delay, fix_recent_blockhashes_sysvar_delay,
merge_nonce_error_into_system_error, merge_nonce_error_into_system_error,
demote_program_write_locks,
); );
self.accounts_db.store_cached(slot, &accounts_to_store); self.accounts_db.store_cached(slot, &accounts_to_store);
} }
@@ -926,7 +893,6 @@ impl Accounts {
last_blockhash_with_fee_calculator: &(Hash, FeeCalculator), last_blockhash_with_fee_calculator: &(Hash, FeeCalculator),
fix_recent_blockhashes_sysvar_delay: bool, fix_recent_blockhashes_sysvar_delay: bool,
merge_nonce_error_into_system_error: bool, merge_nonce_error_into_system_error: bool,
demote_program_write_locks: bool,
) -> Vec<(&'a Pubkey, &'a AccountSharedData)> { ) -> Vec<(&'a Pubkey, &'a AccountSharedData)> {
let mut accounts = Vec::with_capacity(loaded.len()); let mut accounts = Vec::with_capacity(loaded.len());
for (i, ((raccs, _nonce_rollback), tx)) in loaded.iter_mut().zip(txs).enumerate() { for (i, ((raccs, _nonce_rollback), tx)) in loaded.iter_mut().zip(txs).enumerate() {
@@ -979,7 +945,7 @@ impl Accounts {
fee_payer_index = Some(i); fee_payer_index = Some(i);
} }
let is_fee_payer = Some(i) == fee_payer_index; let is_fee_payer = Some(i) == fee_payer_index;
if message.is_writable(i, demote_program_write_locks) if message.is_writable(i)
&& (res.is_ok() && (res.is_ok()
|| (maybe_nonce_rollback.is_some() && (is_nonce_account || is_fee_payer))) || (maybe_nonce_rollback.is_some() && (is_nonce_account || is_fee_payer)))
{ {
@@ -2022,8 +1988,6 @@ mod tests {
accounts.store_slow_uncached(0, &keypair2.pubkey(), &account2); accounts.store_slow_uncached(0, &keypair2.pubkey(), &account2);
accounts.store_slow_uncached(0, &keypair3.pubkey(), &account3); accounts.store_slow_uncached(0, &keypair3.pubkey(), &account3);
let demote_program_write_locks = true;
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])]; let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
let message = Message::new_with_compiled_instructions( let message = Message::new_with_compiled_instructions(
1, 1,
@@ -2034,7 +1998,7 @@ mod tests {
instructions, instructions,
); );
let tx = Transaction::new(&[&keypair0], message, Hash::default()); let tx = Transaction::new(&[&keypair0], message, Hash::default());
let results0 = accounts.lock_accounts([tx.clone()].iter(), demote_program_write_locks); let results0 = accounts.lock_accounts([tx.clone()].iter());
assert!(results0[0].is_ok()); assert!(results0[0].is_ok());
assert_eq!( assert_eq!(
@@ -2069,7 +2033,7 @@ mod tests {
); );
let tx1 = Transaction::new(&[&keypair1], message, Hash::default()); let tx1 = Transaction::new(&[&keypair1], message, Hash::default());
let txs = vec![tx0, tx1]; let txs = vec![tx0, tx1];
let results1 = accounts.lock_accounts(txs.iter(), demote_program_write_locks); let results1 = accounts.lock_accounts(txs.iter());
assert!(results1[0].is_ok()); // Read-only account (keypair1) can be referenced multiple times assert!(results1[0].is_ok()); // Read-only account (keypair1) can be referenced multiple times
assert!(results1[1].is_err()); // Read-only account (keypair1) cannot also be locked as writable assert!(results1[1].is_err()); // Read-only account (keypair1) cannot also be locked as writable
@@ -2084,8 +2048,8 @@ mod tests {
2 2
); );
accounts.unlock_accounts([tx].iter(), &results0, demote_program_write_locks); accounts.unlock_accounts([tx].iter(), &results0);
accounts.unlock_accounts(txs.iter(), &results1, demote_program_write_locks); accounts.unlock_accounts(txs.iter(), &results1);
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])]; let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
let message = Message::new_with_compiled_instructions( let message = Message::new_with_compiled_instructions(
1, 1,
@@ -2096,7 +2060,7 @@ mod tests {
instructions, instructions,
); );
let tx = Transaction::new(&[&keypair1], message, Hash::default()); let tx = Transaction::new(&[&keypair1], message, Hash::default());
let results2 = accounts.lock_accounts([tx].iter(), demote_program_write_locks); let results2 = accounts.lock_accounts([tx].iter());
assert!(results2[0].is_ok()); // Now keypair1 account can be locked as writable assert!(results2[0].is_ok()); // Now keypair1 account can be locked as writable
// Check that read-only lock with zero references is deleted // Check that read-only lock with zero references is deleted
@@ -2132,8 +2096,6 @@ mod tests {
accounts.store_slow_uncached(0, &keypair1.pubkey(), &account1); accounts.store_slow_uncached(0, &keypair1.pubkey(), &account1);
accounts.store_slow_uncached(0, &keypair2.pubkey(), &account2); accounts.store_slow_uncached(0, &keypair2.pubkey(), &account2);
let demote_program_write_locks = true;
let accounts_arc = Arc::new(accounts); let accounts_arc = Arc::new(accounts);
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])]; let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
@@ -2166,15 +2128,13 @@ mod tests {
let exit_clone = exit_clone.clone(); let exit_clone = exit_clone.clone();
loop { loop {
let txs = vec![writable_tx.clone()]; let txs = vec![writable_tx.clone()];
let results = accounts_clone let results = accounts_clone.clone().lock_accounts(txs.iter());
.clone()
.lock_accounts(txs.iter(), demote_program_write_locks);
for result in results.iter() { for result in results.iter() {
if result.is_ok() { if result.is_ok() {
counter_clone.clone().fetch_add(1, Ordering::SeqCst); counter_clone.clone().fetch_add(1, Ordering::SeqCst);
} }
} }
accounts_clone.unlock_accounts(txs.iter(), &results, demote_program_write_locks); accounts_clone.unlock_accounts(txs.iter(), &results);
if exit_clone.clone().load(Ordering::Relaxed) { if exit_clone.clone().load(Ordering::Relaxed) {
break; break;
} }
@@ -2183,15 +2143,13 @@ mod tests {
let counter_clone = counter; let counter_clone = counter;
for _ in 0..5 { for _ in 0..5 {
let txs = vec![readonly_tx.clone()]; let txs = vec![readonly_tx.clone()];
let results = accounts_arc let results = accounts_arc.clone().lock_accounts(txs.iter());
.clone()
.lock_accounts(txs.iter(), demote_program_write_locks);
if results[0].is_ok() { if results[0].is_ok() {
let counter_value = counter_clone.clone().load(Ordering::SeqCst); let counter_value = counter_clone.clone().load(Ordering::SeqCst);
thread::sleep(time::Duration::from_millis(50)); thread::sleep(time::Duration::from_millis(50));
assert_eq!(counter_value, counter_clone.clone().load(Ordering::SeqCst)); assert_eq!(counter_value, counter_clone.clone().load(Ordering::SeqCst));
} }
accounts_arc.unlock_accounts(txs.iter(), &results, demote_program_write_locks); accounts_arc.unlock_accounts(txs.iter(), &results);
thread::sleep(time::Duration::from_millis(50)); thread::sleep(time::Duration::from_millis(50));
} }
exit.store(true, Ordering::Relaxed); exit.store(true, Ordering::Relaxed);
@@ -2220,8 +2178,6 @@ mod tests {
accounts.store_slow_uncached(0, &keypair2.pubkey(), &account2); accounts.store_slow_uncached(0, &keypair2.pubkey(), &account2);
accounts.store_slow_uncached(0, &keypair3.pubkey(), &account3); accounts.store_slow_uncached(0, &keypair3.pubkey(), &account3);
let demote_program_write_locks = true;
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])]; let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
let message = Message::new_with_compiled_instructions( let message = Message::new_with_compiled_instructions(
1, 1,
@@ -2232,7 +2188,7 @@ mod tests {
instructions, instructions,
); );
let tx = Transaction::new(&[&keypair0], message, Hash::default()); let tx = Transaction::new(&[&keypair0], message, Hash::default());
let results0 = accounts.lock_accounts([tx].iter(), demote_program_write_locks); let results0 = accounts.lock_accounts([tx].iter());
assert!(results0[0].is_ok()); assert!(results0[0].is_ok());
// Instruction program-id account demoted to readonly // Instruction program-id account demoted to readonly
@@ -2349,7 +2305,6 @@ mod tests {
&(Hash::default(), FeeCalculator::default()), &(Hash::default(), FeeCalculator::default()),
true, true,
true, // merge_nonce_error_into_system_error true, // merge_nonce_error_into_system_error
true, // demote_program_write_locks
); );
assert_eq!(collected_accounts.len(), 2); assert_eq!(collected_accounts.len(), 2);
assert!(collected_accounts assert!(collected_accounts
@@ -2735,7 +2690,6 @@ mod tests {
&(next_blockhash, FeeCalculator::default()), &(next_blockhash, FeeCalculator::default()),
true, true,
true, // merge_nonce_error_into_system_error true, // merge_nonce_error_into_system_error
true, // demote_program_write_locks
); );
assert_eq!(collected_accounts.len(), 2); assert_eq!(collected_accounts.len(), 2);
assert_eq!( assert_eq!(
@@ -2852,7 +2806,6 @@ mod tests {
&(next_blockhash, FeeCalculator::default()), &(next_blockhash, FeeCalculator::default()),
true, true,
true, // merge_nonce_error_into_system_error true, // merge_nonce_error_into_system_error
true, // demote_program_write_locks
); );
assert_eq!(collected_accounts.len(), 1); assert_eq!(collected_accounts.len(), 1);
let collected_nonce_account = collected_accounts let collected_nonce_account = collected_accounts

View File

@@ -2473,10 +2473,10 @@ impl Bank {
txs: impl Iterator<Item = &'b Transaction>, txs: impl Iterator<Item = &'b Transaction>,
) -> TransactionBatch<'a, 'b> { ) -> TransactionBatch<'a, 'b> {
let hashed_txs: Vec<HashedTransaction> = txs.map(HashedTransaction::from).collect(); let hashed_txs: Vec<HashedTransaction> = txs.map(HashedTransaction::from).collect();
let lock_results = self.rc.accounts.lock_accounts( let lock_results = self
hashed_txs.as_transactions_iter(), .rc
self.demote_program_write_locks(), .accounts
); .lock_accounts(hashed_txs.as_transactions_iter());
TransactionBatch::new(lock_results, self, Cow::Owned(hashed_txs)) TransactionBatch::new(lock_results, self, Cow::Owned(hashed_txs))
} }
@@ -2484,10 +2484,10 @@ impl Bank {
&'a self, &'a self,
hashed_txs: &'b [HashedTransaction], hashed_txs: &'b [HashedTransaction],
) -> TransactionBatch<'a, 'b> { ) -> TransactionBatch<'a, 'b> {
let lock_results = self.rc.accounts.lock_accounts( let lock_results = self
hashed_txs.as_transactions_iter(), .rc
self.demote_program_write_locks(), .accounts
); .lock_accounts(hashed_txs.as_transactions_iter());
TransactionBatch::new(lock_results, self, Cow::Borrowed(hashed_txs)) TransactionBatch::new(lock_results, self, Cow::Borrowed(hashed_txs))
} }
@@ -2555,11 +2555,9 @@ impl Bank {
pub fn unlock_accounts(&self, batch: &mut TransactionBatch) { pub fn unlock_accounts(&self, batch: &mut TransactionBatch) {
if batch.needs_unlock { if batch.needs_unlock {
batch.needs_unlock = false; batch.needs_unlock = false;
self.rc.accounts.unlock_accounts( self.rc
batch.transactions_iter(), .accounts
batch.lock_results(), .unlock_accounts(batch.transactions_iter(), batch.lock_results())
self.demote_program_write_locks(),
)
} }
} }
@@ -3305,7 +3303,6 @@ impl Bank {
&self.last_blockhash_with_fee_calculator(), &self.last_blockhash_with_fee_calculator(),
self.fix_recent_blockhashes_sysvar_delay(), self.fix_recent_blockhashes_sysvar_delay(),
self.merge_nonce_error_into_system_error(), self.merge_nonce_error_into_system_error(),
self.demote_program_write_locks(),
); );
let rent_debits = self.collect_rent(executed, loaded_accounts); let rent_debits = self.collect_rent(executed, loaded_accounts);
@@ -4854,11 +4851,6 @@ impl Bank {
.is_active(&feature_set::merge_nonce_error_into_system_error::id()) .is_active(&feature_set::merge_nonce_error_into_system_error::id())
} }
pub fn demote_program_write_locks(&self) -> bool {
self.feature_set
.is_active(&feature_set::demote_program_write_locks::id())
}
// Check if the wallclock time from bank creation to now has exceeded the allotted // Check if the wallclock time from bank creation to now has exceeded the allotted
// time for transaction processing // time for transaction processing
pub fn should_bank_still_be_processing_txs( pub fn should_bank_still_be_processing_txs(
@@ -6093,10 +6085,7 @@ pub(crate) mod tests {
assert_eq!( assert_eq!(
bank.process_transaction(&tx), bank.process_transaction(&tx),
Err(TransactionError::InstructionError( Err(TransactionError::InvalidWritableAccount)
0,
InstructionError::ExecutableLamportChange
))
); );
assert_eq!(bank.get_balance(&account_pubkey), account_balance); assert_eq!(bank.get_balance(&account_pubkey), account_balance);
} }

View File

@@ -9,8 +9,8 @@ use solana_sdk::{
account_utils::StateMut, account_utils::StateMut,
bpf_loader_upgradeable::{self, UpgradeableLoaderState}, bpf_loader_upgradeable::{self, UpgradeableLoaderState},
feature_set::{ feature_set::{
cpi_share_ro_and_exec_accounts, demote_program_write_locks, instructions_sysvar_enabled, cpi_share_ro_and_exec_accounts, instructions_sysvar_enabled, updated_verify_policy,
updated_verify_policy, FeatureSet, FeatureSet,
}, },
ic_msg, ic_msg,
instruction::{CompiledInstruction, Instruction, InstructionError}, instruction::{CompiledInstruction, Instruction, InstructionError},
@@ -359,8 +359,6 @@ impl<'a> InvokeContext for ThisInvokeContext<'a> {
&self.rent, &self.rent,
caller_write_privileges, caller_write_privileges,
&mut self.timings, &mut self.timings,
self.feature_set
.is_active(&demote_program_write_locks::id()),
self.feature_set.is_active(&updated_verify_policy::id()), self.feature_set.is_active(&updated_verify_policy::id()),
), ),
None => Err(InstructionError::GenericError), // Should never happen None => Err(InstructionError::GenericError), // Should never happen
@@ -574,7 +572,6 @@ impl MessageProcessor {
instruction: &'a CompiledInstruction, instruction: &'a CompiledInstruction,
executable_accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)], executable_accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)],
accounts: &'a [Rc<RefCell<AccountSharedData>>], accounts: &'a [Rc<RefCell<AccountSharedData>>],
demote_program_write_locks: bool,
) -> Vec<KeyedAccount<'a>> { ) -> Vec<KeyedAccount<'a>> {
let mut keyed_accounts = create_keyed_readonly_accounts(&executable_accounts); let mut keyed_accounts = create_keyed_readonly_accounts(&executable_accounts);
let mut keyed_accounts2: Vec<_> = instruction let mut keyed_accounts2: Vec<_> = instruction
@@ -585,7 +582,7 @@ impl MessageProcessor {
let index = index as usize; let index = index as usize;
let key = &message.account_keys[index]; let key = &message.account_keys[index];
let account = &accounts[index]; let account = &accounts[index];
if message.is_writable(index, demote_program_write_locks) { if message.is_writable(index) {
KeyedAccount::new(key, is_signer, account) KeyedAccount::new(key, is_signer, account)
} else { } else {
KeyedAccount::new_readonly(key, is_signer, account) KeyedAccount::new_readonly(key, is_signer, account)
@@ -730,14 +727,7 @@ impl MessageProcessor {
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let invoke_context = RefCell::new(invoke_context); let invoke_context = RefCell::new(invoke_context);
let ( let (message, executables, accounts, account_refs, caller_write_privileges) = {
message,
executables,
accounts,
account_refs,
caller_write_privileges,
demote_program_write_locks,
) = {
let invoke_context = invoke_context.borrow(); let invoke_context = invoke_context.borrow();
let caller_program_id = invoke_context.get_caller()?; let caller_program_id = invoke_context.get_caller()?;
@@ -829,7 +819,6 @@ impl MessageProcessor {
accounts, accounts,
account_refs, account_refs,
caller_write_privileges, caller_write_privileges,
invoke_context.is_feature_active(&demote_program_write_locks::id()),
) )
}; };
@@ -848,7 +837,7 @@ impl MessageProcessor {
let invoke_context = invoke_context.borrow(); let invoke_context = invoke_context.borrow();
for (i, (account, account_ref)) in accounts.iter().zip(account_refs).enumerate() { for (i, (account, account_ref)) in accounts.iter().zip(account_refs).enumerate() {
let account = account.borrow(); let account = account.borrow();
if message.is_writable(i, demote_program_write_locks) && !account.executable { if message.is_writable(i) && !account.executable {
account_ref.try_account_ref_mut()?.lamports = account.lamports; account_ref.try_account_ref_mut()?.lamports = account.lamports;
account_ref.try_account_ref_mut()?.owner = account.owner; account_ref.try_account_ref_mut()?.owner = account.owner;
if account_ref.data_len()? != account.data().len() if account_ref.data_len()? != account.data().len()
@@ -892,15 +881,8 @@ impl MessageProcessor {
Some(caller_write_privileges), Some(caller_write_privileges),
)?; )?;
// Construct keyed accounts // Construct keyed accounts
let demote_program_write_locks = let keyed_accounts =
invoke_context.is_feature_active(&demote_program_write_locks::id()); Self::create_keyed_accounts(message, instruction, executable_accounts, accounts);
let keyed_accounts = Self::create_keyed_accounts(
message,
instruction,
executable_accounts,
accounts,
demote_program_write_locks,
);
// Invoke callee // Invoke callee
invoke_context.push(program_id)?; invoke_context.push(program_id)?;
@@ -972,7 +954,6 @@ impl MessageProcessor {
rent: &Rent, rent: &Rent,
timings: &mut ExecuteDetailsTimings, timings: &mut ExecuteDetailsTimings,
updated_verify_policy: bool, updated_verify_policy: bool,
demote_program_write_locks: bool,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// Verify all executable accounts have zero outstanding refs // Verify all executable accounts have zero outstanding refs
Self::verify_account_references(executable_accounts)?; Self::verify_account_references(executable_accounts)?;
@@ -991,7 +972,7 @@ impl MessageProcessor {
let account = accounts[account_index].borrow(); let account = accounts[account_index].borrow();
pre_accounts[unique_index].verify( pre_accounts[unique_index].verify(
&program_id, &program_id,
message.is_writable(account_index, demote_program_write_locks), message.is_writable(account_index),
rent, rent,
&account, &account,
timings, timings,
@@ -1022,7 +1003,6 @@ impl MessageProcessor {
rent: &Rent, rent: &Rent,
caller_write_privileges: Option<&[bool]>, caller_write_privileges: Option<&[bool]>,
timings: &mut ExecuteDetailsTimings, timings: &mut ExecuteDetailsTimings,
demote_program_write_locks: bool,
updated_verify_policy: bool, updated_verify_policy: bool,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// Verify the per-account instruction results // Verify the per-account instruction results
@@ -1034,7 +1014,7 @@ impl MessageProcessor {
let is_writable = if let Some(caller_write_privileges) = caller_write_privileges { let is_writable = if let Some(caller_write_privileges) = caller_write_privileges {
caller_write_privileges[account_index] caller_write_privileges[account_index]
} else { } else {
message.is_writable(account_index, demote_program_write_locks) message.is_writable(account_index)
}; };
// Find the matching PreAccount // Find the matching PreAccount
for pre_account in pre_accounts.iter_mut() { for pre_account in pre_accounts.iter_mut() {
@@ -1130,15 +1110,8 @@ impl MessageProcessor {
account_db, account_db,
ancestors, ancestors,
); );
let demote_program_write_locks = let keyed_accounts =
invoke_context.is_feature_active(&demote_program_write_locks::id()); Self::create_keyed_accounts(message, instruction, executable_accounts, accounts);
let keyed_accounts = Self::create_keyed_accounts(
message,
instruction,
executable_accounts,
accounts,
demote_program_write_locks,
);
self.process_instruction( self.process_instruction(
program_id, program_id,
&keyed_accounts, &keyed_accounts,
@@ -1154,7 +1127,6 @@ impl MessageProcessor {
&rent_collector.rent, &rent_collector.rent,
timings, timings,
invoke_context.is_feature_active(&updated_verify_policy::id()), invoke_context.is_feature_active(&updated_verify_policy::id()),
demote_program_write_locks,
)?; )?;
timings.accumulate(&invoke_context.timings); timings.accumulate(&invoke_context.timings);
@@ -2170,7 +2142,6 @@ mod tests {
let programs: Vec<(_, ProcessInstructionWithContext)> = let programs: Vec<(_, ProcessInstructionWithContext)> =
vec![(callee_program_id, mock_process_instruction)]; vec![(callee_program_id, mock_process_instruction)];
let feature_set = FeatureSet::all_enabled(); let feature_set = FeatureSet::all_enabled();
let demote_program_write_locks = feature_set.is_active(&demote_program_write_locks::id());
let ancestors = Ancestors::default(); let ancestors = Ancestors::default();
let mut invoke_context = ThisInvokeContext::new( let mut invoke_context = ThisInvokeContext::new(
@@ -2209,7 +2180,7 @@ mod tests {
.account_keys .account_keys
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, _)| message.is_writable(i, demote_program_write_locks)) .map(|(i, _)| message.is_writable(i))
.collect::<Vec<bool>>(); .collect::<Vec<bool>>();
assert_eq!( assert_eq!(
MessageProcessor::process_cross_program_instruction( MessageProcessor::process_cross_program_instruction(
@@ -2244,7 +2215,7 @@ mod tests {
.account_keys .account_keys
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, _)| message.is_writable(i, demote_program_write_locks)) .map(|(i, _)| message.is_writable(i))
.collect::<Vec<bool>>(); .collect::<Vec<bool>>();
assert_eq!( assert_eq!(
MessageProcessor::process_cross_program_instruction( MessageProcessor::process_cross_program_instruction(

View File

@@ -14,8 +14,6 @@ fn make_instructions() -> Vec<Instruction> {
vec![inst; 4] vec![inst; 4]
} }
const DEMOTE_PROGRAM_WRITE_LOCKS: bool = true;
#[bench] #[bench]
fn bench_bincode_instruction_serialize(b: &mut Bencher) { fn bench_bincode_instruction_serialize(b: &mut Bencher) {
let instructions = make_instructions(); let instructions = make_instructions();
@@ -29,7 +27,7 @@ fn bench_manual_instruction_serialize(b: &mut Bencher) {
let instructions = make_instructions(); let instructions = make_instructions();
let message = Message::new(&instructions, None); let message = Message::new(&instructions, None);
b.iter(|| { b.iter(|| {
test::black_box(message.serialize_instructions(DEMOTE_PROGRAM_WRITE_LOCKS)); test::black_box(message.serialize_instructions());
}); });
} }
@@ -46,7 +44,7 @@ fn bench_bincode_instruction_deserialize(b: &mut Bencher) {
fn bench_manual_instruction_deserialize(b: &mut Bencher) { fn bench_manual_instruction_deserialize(b: &mut Bencher) {
let instructions = make_instructions(); let instructions = make_instructions();
let message = Message::new(&instructions, None); let message = Message::new(&instructions, None);
let serialized = message.serialize_instructions(DEMOTE_PROGRAM_WRITE_LOCKS); let serialized = message.serialize_instructions();
b.iter(|| { b.iter(|| {
for i in 0..instructions.len() { for i in 0..instructions.len() {
test::black_box(instructions::load_instruction_at(i, &serialized).unwrap()); test::black_box(instructions::load_instruction_at(i, &serialized).unwrap());
@@ -58,7 +56,7 @@ fn bench_manual_instruction_deserialize(b: &mut Bencher) {
fn bench_manual_instruction_deserialize_single(b: &mut Bencher) { fn bench_manual_instruction_deserialize_single(b: &mut Bencher) {
let instructions = make_instructions(); let instructions = make_instructions();
let message = Message::new(&instructions, None); let message = Message::new(&instructions, None);
let serialized = message.serialize_instructions(DEMOTE_PROGRAM_WRITE_LOCKS); let serialized = message.serialize_instructions();
b.iter(|| { b.iter(|| {
test::black_box(instructions::load_instruction_at(3, &serialized).unwrap()); test::black_box(instructions::load_instruction_at(3, &serialized).unwrap());
}); });

View File

@@ -373,7 +373,7 @@ impl Message {
self.program_position(i).is_some() self.program_position(i).is_some()
} }
pub fn is_writable(&self, i: usize, demote_program_write_locks: bool) -> bool { pub fn is_writable(&self, i: usize) -> bool {
(i < (self.header.num_required_signatures - self.header.num_readonly_signed_accounts) (i < (self.header.num_required_signatures - self.header.num_readonly_signed_accounts)
as usize as usize
|| (i >= self.header.num_required_signatures as usize || (i >= self.header.num_required_signatures as usize
@@ -383,21 +383,18 @@ impl Message {
let key = self.account_keys[i]; let key = self.account_keys[i];
sysvar::is_sysvar_id(&key) || BUILTIN_PROGRAMS_KEYS.contains(&key) sysvar::is_sysvar_id(&key) || BUILTIN_PROGRAMS_KEYS.contains(&key)
} }
&& !(demote_program_write_locks && self.is_key_called_as_program(i)) && !self.is_key_called_as_program(i)
} }
pub fn is_signer(&self, i: usize) -> bool { pub fn is_signer(&self, i: usize) -> bool {
i < self.header.num_required_signatures as usize i < self.header.num_required_signatures as usize
} }
pub fn get_account_keys_by_lock_type( pub fn get_account_keys_by_lock_type(&self) -> (Vec<&Pubkey>, Vec<&Pubkey>) {
&self,
demote_program_write_locks: bool,
) -> (Vec<&Pubkey>, Vec<&Pubkey>) {
let mut writable_keys = vec![]; let mut writable_keys = vec![];
let mut readonly_keys = vec![]; let mut readonly_keys = vec![];
for (i, key) in self.account_keys.iter().enumerate() { for (i, key) in self.account_keys.iter().enumerate() {
if self.is_writable(i, demote_program_write_locks) { if self.is_writable(i) {
writable_keys.push(key); writable_keys.push(key);
} else { } else {
readonly_keys.push(key); readonly_keys.push(key);
@@ -419,7 +416,7 @@ impl Message {
// 35..67 - program_id // 35..67 - program_id
// 67..69 - data len - u16 // 67..69 - data len - u16
// 69..data_len - data // 69..data_len - data
pub fn serialize_instructions(&self, demote_program_write_locks: bool) -> Vec<u8> { pub fn serialize_instructions(&self) -> Vec<u8> {
// 64 bytes is a reasonable guess, calculating exactly is slower in benchmarks // 64 bytes is a reasonable guess, calculating exactly is slower in benchmarks
let mut data = Vec::with_capacity(self.instructions.len() * (32 * 2)); let mut data = Vec::with_capacity(self.instructions.len() * (32 * 2));
append_u16(&mut data, self.instructions.len() as u16); append_u16(&mut data, self.instructions.len() as u16);
@@ -434,7 +431,7 @@ impl Message {
for account_index in &instruction.accounts { for account_index in &instruction.accounts {
let account_index = *account_index as usize; let account_index = *account_index as usize;
let is_signer = self.is_signer(account_index); let is_signer = self.is_signer(account_index);
let is_writable = self.is_writable(account_index, demote_program_write_locks); let is_writable = self.is_writable(account_index);
let mut meta_byte = 0; let mut meta_byte = 0;
if is_signer { if is_signer {
meta_byte |= 1 << Self::IS_SIGNER_BIT; meta_byte |= 1 << Self::IS_SIGNER_BIT;
@@ -873,13 +870,12 @@ mod tests {
recent_blockhash: Hash::default(), recent_blockhash: Hash::default(),
instructions: vec![], instructions: vec![],
}; };
let demote_program_write_locks = true; assert!(message.is_writable(0));
assert!(message.is_writable(0, demote_program_write_locks)); assert!(!message.is_writable(1));
assert!(!message.is_writable(1, demote_program_write_locks)); assert!(!message.is_writable(2));
assert!(!message.is_writable(2, demote_program_write_locks)); assert!(message.is_writable(3));
assert!(message.is_writable(3, demote_program_write_locks)); assert!(message.is_writable(4));
assert!(message.is_writable(4, demote_program_write_locks)); assert!(!message.is_writable(5));
assert!(!message.is_writable(5, demote_program_write_locks));
} }
#[test] #[test]
@@ -907,7 +903,7 @@ mod tests {
Some(&id1), Some(&id1),
); );
assert_eq!( assert_eq!(
message.get_account_keys_by_lock_type(/*demote_program_write_locks=*/ true), message.get_account_keys_by_lock_type(),
(vec![&id1, &id0], vec![&id3, &id2, &program_id]) (vec![&id1, &id0], vec![&id3, &id2, &program_id])
); );
} }
@@ -937,7 +933,7 @@ mod tests {
]; ];
let message = Message::new(&instructions, Some(&id1)); let message = Message::new(&instructions, Some(&id1));
let serialized = message.serialize_instructions(/*demote_program_write_locks=*/ true); let serialized = message.serialize_instructions();
for (i, instruction) in instructions.iter().enumerate() { for (i, instruction) in instructions.iter().enumerate() {
assert_eq!( assert_eq!(
Message::deserialize_instruction(i, &serialized).unwrap(), Message::deserialize_instruction(i, &serialized).unwrap(),
@@ -958,7 +954,7 @@ mod tests {
]; ];
let message = Message::new(&instructions, Some(&id1)); let message = Message::new(&instructions, Some(&id1));
let serialized = message.serialize_instructions(/*demote_program_write_locks=*/ true); let serialized = message.serialize_instructions();
assert_eq!( assert_eq!(
Message::deserialize_instruction(instructions.len(), &serialized).unwrap_err(), Message::deserialize_instruction(instructions.len(), &serialized).unwrap_err(),
SanitizeError::IndexOutOfBounds, SanitizeError::IndexOutOfBounds,

View File

@@ -166,10 +166,6 @@ pub mod spl_token_v2_set_authority_fix {
solana_sdk::declare_id!("FToKNBYyiF4ky9s8WsmLBXHCht17Ek7RXaLZGHzzQhJ1"); solana_sdk::declare_id!("FToKNBYyiF4ky9s8WsmLBXHCht17Ek7RXaLZGHzzQhJ1");
} }
pub mod demote_program_write_locks {
solana_sdk::declare_id!("3E3jV7v9VcdJL8iYZUMax9DiDno8j7EWUVbhm9RtShj2");
}
lazy_static! { lazy_static! {
/// Map of feature identifiers to user-visible description /// Map of feature identifiers to user-visible description
pub static ref FEATURE_NAMES: HashMap<Pubkey, &'static str> = [ pub static ref FEATURE_NAMES: HashMap<Pubkey, &'static str> = [
@@ -210,7 +206,6 @@ lazy_static! {
(libsecp256k1_0_5_upgrade_enabled::id(), "upgrade libsecp256k1 to v0.5.0"), (libsecp256k1_0_5_upgrade_enabled::id(), "upgrade libsecp256k1 to v0.5.0"),
(merge_nonce_error_into_system_error::id(), "merge NonceError into SystemError"), (merge_nonce_error_into_system_error::id(), "merge NonceError into SystemError"),
(spl_token_v2_set_authority_fix::id(), "spl-token set_authority fix"), (spl_token_v2_set_authority_fix::id(), "spl-token set_authority fix"),
(demote_program_write_locks::id(), "demote program write locks to readonly #19593"),
/*************** ADD NEW FEATURES HERE ***************/ /*************** ADD NEW FEATURES HERE ***************/
] ]
.iter() .iter()

View File

@@ -13,7 +13,7 @@ pub fn parse_accounts(message: &Message) -> Vec<ParsedAccount> {
for (i, account_key) in message.account_keys.iter().enumerate() { for (i, account_key) in message.account_keys.iter().enumerate() {
accounts.push(ParsedAccount { accounts.push(ParsedAccount {
pubkey: account_key.to_string(), pubkey: account_key.to_string(),
writable: message.is_writable(i, /*demote_program_write_locks=*/ true), writable: message.is_writable(i),
signer: message.is_signer(i), signer: message.is_signer(i),
}); });
} }