Clean up sanitized tx creation for tests (#21006)

This commit is contained in:
Justin Starry 2021-10-27 13:09:16 -04:00 committed by GitHub
parent 9d330fc638
commit 036d7fcc81
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 134 additions and 144 deletions

View File

@ -1688,7 +1688,6 @@ mod tests {
use solana_transaction_status::TransactionWithStatusMeta;
use solana_vote_program::vote_transaction;
use std::{
convert::{TryFrom, TryInto},
net::SocketAddr,
path::Path,
sync::{
@ -2045,7 +2044,7 @@ mod tests {
fn sanitize_transactions(txs: Vec<Transaction>) -> Vec<SanitizedTransaction> {
txs.into_iter()
.map(|tx| SanitizedTransaction::try_from(tx).unwrap())
.map(SanitizedTransaction::from_transaction_for_tests)
.collect()
}
@ -2302,12 +2301,12 @@ mod tests {
let bank = Arc::new(Bank::new_no_wallclock_throttle_for_tests(&genesis_config));
let pubkey = solana_sdk::pubkey::new_rand();
let transactions =
vec![
system_transaction::transfer(&mint_keypair, &pubkey, 1, genesis_config.hash())
.try_into()
.unwrap(),
];
let transactions = sanitize_transactions(vec![system_transaction::transfer(
&mint_keypair,
&pubkey,
1,
genesis_config.hash(),
)]);
let ledger_path = get_tmp_ledger_path!();
{
@ -2366,14 +2365,12 @@ mod tests {
assert!(done);
let transactions = vec![system_transaction::transfer(
let transactions = sanitize_transactions(vec![system_transaction::transfer(
&mint_keypair,
&pubkey,
2,
genesis_config.hash(),
)
.try_into()
.unwrap()];
)]);
assert_matches!(
BankingStage::process_and_record_transactions(
@ -2433,14 +2430,10 @@ mod tests {
let pubkey = solana_sdk::pubkey::new_rand();
let pubkey1 = solana_sdk::pubkey::new_rand();
let transactions = vec![
system_transaction::transfer(&mint_keypair, &pubkey, 1, genesis_config.hash())
.try_into()
.unwrap(),
system_transaction::transfer(&mint_keypair, &pubkey1, 1, genesis_config.hash())
.try_into()
.unwrap(),
];
let transactions = sanitize_transactions(vec![
system_transaction::transfer(&mint_keypair, &pubkey, 1, genesis_config.hash()),
system_transaction::transfer(&mint_keypair, &pubkey1, 1, genesis_config.hash()),
]);
let ledger_path = get_tmp_ledger_path!();
{
@ -2542,12 +2535,12 @@ mod tests {
let pubkey = solana_sdk::pubkey::new_rand();
let transactions =
vec![
system_transaction::transfer(&mint_keypair, &pubkey, 1, genesis_config.hash())
.try_into()
.unwrap(),
];
let transactions = sanitize_transactions(vec![system_transaction::transfer(
&mint_keypair,
&pubkey,
1,
genesis_config.hash(),
)]);
let ledger_path = get_tmp_ledger_path!();
{
@ -2623,11 +2616,7 @@ mod tests {
let entry_3 = next_entry(&entry_2.hash, 1, vec![fail_tx.clone()]);
let entries = vec![entry_1, entry_2, entry_3];
let transactions = vec![
success_tx.try_into().unwrap(),
ix_error_tx.try_into().unwrap(),
fail_tx.try_into().unwrap(),
];
let transactions = sanitize_transactions(vec![success_tx, ix_error_tx, fail_tx]);
bank.transfer(4, &mint_keypair, &keypair1.pubkey()).unwrap();
let ledger_path = get_tmp_ledger_path!();

View File

@ -3434,7 +3434,7 @@ pub mod tests {
Hash::default(),
);
let txs = vec![account_not_found_tx, invalid_blockhash_tx];
let batch = bank.prepare_batch(txs).unwrap();
let batch = bank.prepare_batch_for_tests(txs);
let (
TransactionResults {
fee_collection_results,

View File

@ -49,15 +49,15 @@ use solana_sdk::{
system_instruction::{self, MAX_PERMITTED_DATA_LENGTH},
system_program, sysvar,
sysvar::{clock, rent},
transaction::{Transaction, TransactionError},
transaction::{SanitizedTransaction, Transaction, TransactionError},
};
use solana_transaction_status::{
token_balances::collect_token_balances, ConfirmedTransaction, InnerInstructions,
TransactionStatusMeta, TransactionWithStatusMeta, UiTransactionEncoding,
};
use std::{
cell::RefCell, collections::HashMap, convert::TryFrom, convert::TryInto, env, fs::File,
io::Read, path::PathBuf, str::FromStr, sync::Arc,
cell::RefCell, collections::HashMap, convert::TryFrom, env, fs::File, io::Read, path::PathBuf,
str::FromStr, sync::Arc,
};
/// BPF program file extension
@ -301,7 +301,7 @@ fn process_transaction_and_record_inner(
) -> (Result<(), TransactionError>, Vec<Vec<CompiledInstruction>>) {
let signature = tx.signatures.get(0).unwrap().clone();
let txs = vec![tx];
let tx_batch = bank.prepare_batch(txs).unwrap();
let tx_batch = bank.prepare_batch_for_tests(txs);
let (mut results, _, mut inner_instructions, _transaction_logs) = bank
.load_execute_and_commit_transactions(
&tx_batch,
@ -324,7 +324,7 @@ fn process_transaction_and_record_inner(
}
fn execute_transactions(bank: &Bank, txs: Vec<Transaction>) -> Vec<ConfirmedTransaction> {
let batch = bank.prepare_batch(txs.clone()).unwrap();
let batch = bank.prepare_batch_for_tests(txs.clone());
let mut timings = ExecuteTimings::default();
let mut mint_decimals = HashMap::new();
let tx_pre_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals);
@ -786,8 +786,9 @@ fn test_return_data_and_log_data_syscall() {
let blockhash = bank.last_blockhash();
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
let transaction = Transaction::new(&[&mint_keypair], message, blockhash);
let sanitized_tx = SanitizedTransaction::from_transaction_for_tests(transaction);
let result = bank.simulate_transaction(transaction.try_into().unwrap());
let result = bank.simulate_transaction(sanitized_tx);
assert!(result.result.is_ok());

View File

@ -1191,8 +1191,11 @@ mod tests {
message: Message,
recent_blockhash: Hash,
) -> SanitizedTransaction {
SanitizedTransaction::try_from(Transaction::new(from_keypairs, message, recent_blockhash))
.unwrap()
SanitizedTransaction::from_transaction_for_tests(Transaction::new(
from_keypairs,
message,
recent_blockhash,
))
}
fn load_accounts_with_fee_and_rent(
@ -1216,7 +1219,7 @@ mod tests {
}
let ancestors = vec![(0, 0)].into_iter().collect();
let sanitized_tx = SanitizedTransaction::try_from(tx).unwrap();
let sanitized_tx = SanitizedTransaction::from_transaction_for_tests(tx);
accounts.load_accounts(
&ancestors,
&[sanitized_tx],
@ -2460,7 +2463,7 @@ mod tests {
}
fn load_accounts_no_store(accounts: &Accounts, tx: Transaction) -> Vec<TransactionLoadResult> {
let tx = SanitizedTransaction::try_from(tx).unwrap();
let tx = SanitizedTransaction::from_transaction_for_tests(tx);
let rent_collector = RentCollector::default();
let mut hash_queue = BlockhashQueue::new(100);
hash_queue.register_hash(tx.message().recent_blockhash(), 10);

View File

@ -3246,21 +3246,17 @@ impl Bank {
tick_height % self.ticks_per_slot == 0
}
/// Prepare a transaction batch from a list of legacy transactionsy. Used for tests only.
pub fn prepare_batch(&self, txs: Vec<Transaction>) -> Result<TransactionBatch> {
/// Prepare a transaction batch from a list of legacy transactions. Used for tests only.
pub fn prepare_batch_for_tests(&self, txs: Vec<Transaction>) -> TransactionBatch {
let sanitized_txs = txs
.into_iter()
.map(SanitizedTransaction::try_from)
.collect::<Result<Vec<_>>>()?;
.map(SanitizedTransaction::from_transaction_for_tests)
.collect::<Vec<_>>();
let lock_results = self
.rc
.accounts
.lock_accounts(sanitized_txs.iter(), self.demote_program_write_locks());
Ok(TransactionBatch::new(
lock_results,
self,
Cow::Owned(sanitized_txs),
))
TransactionBatch::new(lock_results, self, Cow::Owned(sanitized_txs))
}
/// Prepare a transaction batch from a list of versioned transactions from
@ -9084,14 +9080,18 @@ pub(crate) mod tests {
let bank = Bank::new_for_tests(&genesis_config);
let key = Keypair::new();
let tx1 =
system_transaction::transfer(&mint_keypair, &key.pubkey(), 2, genesis_config.hash())
.try_into()
.unwrap();
let tx2 =
system_transaction::transfer(&mint_keypair, &key.pubkey(), 5, genesis_config.hash())
.try_into()
.unwrap();
let tx1 = SanitizedTransaction::from_transaction_for_tests(system_transaction::transfer(
&mint_keypair,
&key.pubkey(),
2,
genesis_config.hash(),
));
let tx2 = SanitizedTransaction::from_transaction_for_tests(system_transaction::transfer(
&mint_keypair,
&key.pubkey(),
5,
genesis_config.hash(),
));
let results = vec![
(Ok(()), None),
@ -9231,7 +9231,7 @@ pub(crate) mod tests {
system_transaction::transfer(&mint_keypair, &alice.pubkey(), 1, genesis_config.hash());
let pay_alice = vec![tx1];
let lock_result = bank.prepare_batch(pay_alice).unwrap();
let lock_result = bank.prepare_batch_for_tests(pay_alice);
let results_alice = bank
.load_execute_and_commit_transactions(
&lock_result,
@ -9284,7 +9284,7 @@ pub(crate) mod tests {
let tx = Transaction::new(&[&key0], message, genesis_config.hash());
let txs = vec![tx];
let batch0 = bank.prepare_batch(txs).unwrap();
let batch0 = bank.prepare_batch_for_tests(txs);
assert!(batch0.lock_results()[0].is_ok());
// Try locking accounts, locking a previously read-only account as writable
@ -9302,7 +9302,7 @@ pub(crate) mod tests {
let tx = Transaction::new(&[&key1], message, genesis_config.hash());
let txs = vec![tx];
let batch1 = bank.prepare_batch(txs).unwrap();
let batch1 = bank.prepare_batch_for_tests(txs);
assert!(batch1.lock_results()[0].is_err());
// Try locking a previously read-only account a 2nd time; should succeed
@ -9319,7 +9319,7 @@ pub(crate) mod tests {
let tx = Transaction::new(&[&key2], message, genesis_config.hash());
let txs = vec![tx];
let batch2 = bank.prepare_batch(txs).unwrap();
let batch2 = bank.prepare_batch_for_tests(txs);
assert!(batch2.lock_results()[0].is_ok());
}
@ -10851,7 +10851,7 @@ pub(crate) mod tests {
);
let nonce_account = bank.get_account(&nonce_pubkey).unwrap();
assert_eq!(
bank.check_tx_durable_nonce(&tx.try_into().unwrap()),
bank.check_tx_durable_nonce(&SanitizedTransaction::from_transaction_for_tests(tx)),
Some((nonce_pubkey, nonce_account))
);
}
@ -10874,7 +10874,7 @@ pub(crate) mod tests {
nonce_hash,
);
assert!(bank
.check_tx_durable_nonce(&tx.try_into().unwrap())
.check_tx_durable_nonce(&SanitizedTransaction::from_transaction_for_tests(tx,))
.is_none());
}
@ -10897,7 +10897,7 @@ pub(crate) mod tests {
);
tx.message.instructions[0].accounts.clear();
assert!(bank
.check_tx_durable_nonce(&tx.try_into().unwrap())
.check_tx_durable_nonce(&SanitizedTransaction::from_transaction_for_tests(tx))
.is_none());
}
@ -10921,7 +10921,7 @@ pub(crate) mod tests {
nonce_hash,
);
assert!(bank
.check_tx_durable_nonce(&tx.try_into().unwrap())
.check_tx_durable_nonce(&SanitizedTransaction::from_transaction_for_tests(tx))
.is_none());
}
@ -10942,7 +10942,7 @@ pub(crate) mod tests {
Hash::default(),
);
assert!(bank
.check_tx_durable_nonce(&tx.try_into().unwrap())
.check_tx_durable_nonce(&SanitizedTransaction::from_transaction_for_tests(tx))
.is_none());
}
@ -11293,14 +11293,14 @@ pub(crate) mod tests {
instructions,
);
let txs = vec![tx0, tx1];
let batch = bank0.prepare_batch(txs.clone()).unwrap();
let batch = bank0.prepare_batch_for_tests(txs.clone());
let balances = bank0.collect_balances(&batch);
assert_eq!(balances.len(), 2);
assert_eq!(balances[0], vec![8, 11, 1]);
assert_eq!(balances[1], vec![8, 0, 1]);
let txs: Vec<_> = txs.into_iter().rev().collect();
let batch = bank0.prepare_batch(txs).unwrap();
let batch = bank0.prepare_batch_for_tests(txs);
let balances = bank0.collect_balances(&batch);
assert_eq!(balances.len(), 2);
assert_eq!(balances[0], vec![8, 0, 1]);
@ -11334,7 +11334,7 @@ pub(crate) mod tests {
let tx2 = system_transaction::transfer(&keypair1, &pubkey2, 12, blockhash);
let txs = vec![tx0, tx1, tx2];
let lock_result = bank0.prepare_batch(txs).unwrap();
let lock_result = bank0.prepare_batch_for_tests(txs);
let (transaction_results, transaction_balances_set, inner_instructions, transaction_logs) =
bank0.load_execute_and_commit_transactions(
&lock_result,
@ -14511,7 +14511,7 @@ pub(crate) mod tests {
let failure_sig = tx1.signatures[0];
let tx2 = system_transaction::transfer(&sender0, &recipient0, 1, blockhash);
let txs = vec![tx0, tx1, tx2];
let batch = bank.prepare_batch(txs).unwrap();
let batch = bank.prepare_batch_for_tests(txs);
let log_results = bank
.load_execute_and_commit_transactions(

View File

@ -197,7 +197,6 @@ mod tests {
transaction::Transaction,
};
use std::{
convert::{TryFrom, TryInto},
str::FromStr,
sync::{Arc, RwLock},
thread::{self, JoinHandle},
@ -243,10 +242,9 @@ mod tests {
let (mint_keypair, start_hash) = test_setup();
let keypair = Keypair::new();
let simple_transaction: SanitizedTransaction =
system_transaction::transfer(&mint_keypair, &keypair.pubkey(), 2, start_hash)
.try_into()
.unwrap();
let simple_transaction = SanitizedTransaction::from_transaction_for_tests(
system_transaction::transfer(&mint_keypair, &keypair.pubkey(), 2, start_hash),
);
debug!(
"system_transaction simple_transaction {:?}",
simple_transaction
@ -274,9 +272,11 @@ mod tests {
let instructions =
system_instruction::transfer_many(&mint_keypair.pubkey(), &[(key1, 1), (key2, 1)]);
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let tx: SanitizedTransaction = Transaction::new(&[&mint_keypair], message, start_hash)
.try_into()
.unwrap();
let tx = SanitizedTransaction::from_transaction_for_tests(Transaction::new(
&[&mint_keypair],
message,
start_hash,
));
debug!("many transfer transaction {:?}", tx);
// expected cost for two system transfer instructions
@ -303,15 +303,15 @@ mod tests {
CompiledInstruction::new(3, &(), vec![0, 1]),
CompiledInstruction::new(4, &(), vec![0, 2]),
];
let tx: SanitizedTransaction = Transaction::new_with_compiled_instructions(
&[&mint_keypair],
&[key1, key2],
start_hash,
vec![prog1, prog2],
instructions,
)
.try_into()
.unwrap();
let tx = SanitizedTransaction::from_transaction_for_tests(
Transaction::new_with_compiled_instructions(
&[&mint_keypair],
&[key1, key2],
start_hash,
vec![prog1, prog2],
instructions,
),
);
debug!("many random transaction {:?}", tx);
let testee = CostModel::default();
@ -335,15 +335,15 @@ mod tests {
CompiledInstruction::new(4, &(), vec![0, 2]),
CompiledInstruction::new(5, &(), vec![1, 3]),
];
let tx: SanitizedTransaction = Transaction::new_with_compiled_instructions(
&[&signer1, &signer2],
&[key1, key2],
Hash::new_unique(),
vec![prog1, prog2],
instructions,
)
.try_into()
.unwrap();
let tx = SanitizedTransaction::from_transaction_for_tests(
Transaction::new_with_compiled_instructions(
&[&signer1, &signer2],
&[key1, key2],
Hash::new_unique(),
vec![prog1, prog2],
instructions,
),
);
let cost_model = CostModel::default();
let tx_cost = cost_model.calculate_cost(&tx, /*demote_program_write_locks=*/ true);
@ -376,10 +376,12 @@ mod tests {
#[test]
fn test_cost_model_calculate_cost() {
let (mint_keypair, start_hash) = test_setup();
let tx: SanitizedTransaction =
system_transaction::transfer(&mint_keypair, &Keypair::new().pubkey(), 2, start_hash)
.try_into()
.unwrap();
let tx = SanitizedTransaction::from_transaction_for_tests(system_transaction::transfer(
&mint_keypair,
&Keypair::new().pubkey(),
2,
start_hash,
));
let expected_account_cost = WRITE_LOCK_UNITS * 2;
let expected_execution_cost = 8;
@ -424,16 +426,15 @@ mod tests {
CompiledInstruction::new(3, &(), vec![0, 1]),
CompiledInstruction::new(4, &(), vec![0, 2]),
];
let tx = Arc::new(
SanitizedTransaction::try_from(Transaction::new_with_compiled_instructions(
let tx = Arc::new(SanitizedTransaction::from_transaction_for_tests(
Transaction::new_with_compiled_instructions(
&[&mint_keypair],
&[key1, key2],
start_hash,
vec![prog1, prog2],
instructions,
))
.unwrap(),
);
),
));
let number_threads = 10;
let expected_account_cost = WRITE_LOCK_UNITS * 3;

View File

@ -167,7 +167,7 @@ mod tests {
system_transaction,
transaction::Transaction,
};
use std::{cmp, convert::TryFrom, sync::Arc};
use std::{cmp, sync::Arc};
fn test_setup() -> (Keypair, Hash) {
solana_logger::setup();
@ -301,7 +301,7 @@ mod tests {
fn test_cost_tracker_try_add_is_atomic() {
let (mint_keypair, start_hash) = test_setup();
let (tx, _keys, _cost) = build_simple_transaction(&mint_keypair, &start_hash);
let tx = SanitizedTransaction::try_from(tx).unwrap();
let tx = SanitizedTransaction::from_transaction_for_tests(tx);
let acct1 = Pubkey::new_unique();
let acct2 = Pubkey::new_unique();

View File

@ -1868,7 +1868,7 @@ mod tests {
system_transaction,
transaction::SanitizedTransaction,
};
use std::{convert::TryFrom, mem::size_of};
use std::mem::size_of;
#[test]
fn test_serialize_snapshot_data_file_under_limit() {
@ -3042,13 +3042,12 @@ mod tests {
let slot = slot + 1;
let bank2 = Arc::new(Bank::new_from_parent(&bank1, &collector, slot));
let tx = SanitizedTransaction::try_from(system_transaction::transfer(
let tx = SanitizedTransaction::from_transaction_for_tests(system_transaction::transfer(
&key1,
&key2.pubkey(),
lamports_to_transfer,
bank2.last_blockhash(),
))
.unwrap();
));
let fee = bank2.get_fee_for_message(tx.message());
let tx = system_transaction::transfer(
&key1,

View File

@ -52,7 +52,6 @@ mod tests {
use super::*;
use crate::genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo};
use solana_sdk::{signature::Keypair, system_transaction};
use std::convert::TryInto;
#[test]
fn test_transaction_batch() {
@ -107,12 +106,18 @@ mod tests {
let pubkey2 = solana_sdk::pubkey::new_rand();
let txs = vec![
system_transaction::transfer(&mint_keypair, &pubkey, 1, genesis_config.hash())
.try_into()
.unwrap(),
system_transaction::transfer(&keypair2, &pubkey2, 1, genesis_config.hash())
.try_into()
.unwrap(),
SanitizedTransaction::from_transaction_for_tests(system_transaction::transfer(
&mint_keypair,
&pubkey,
1,
genesis_config.hash(),
)),
SanitizedTransaction::from_transaction_for_tests(system_transaction::transfer(
&keypair2,
&pubkey2,
1,
genesis_config.hash(),
)),
];
(bank, txs)

View File

@ -163,16 +163,11 @@ mod tests {
hash::Hash, message::Message, pubkey::Pubkey, signature::Keypair, signer::Signer,
transaction::Transaction,
};
use std::convert::TryInto;
fn sanitize_tx(tx: Transaction) -> SanitizedTransaction {
tx.try_into().unwrap()
}
macro_rules! test {
( $instructions: expr, $expected_error: expr, $expected_budget: expr ) => {
let payer_keypair = Keypair::new();
let tx = sanitize_tx(Transaction::new(
let tx = SanitizedTransaction::from_transaction_for_tests(Transaction::new(
&[&payer_keypair],
Message::new($instructions, Some(&payer_keypair.pubkey())),
Hash::default(),

View File

@ -14,7 +14,6 @@ use {
transaction::{Result, Transaction, TransactionError, VersionedTransaction},
},
solana_program::{system_instruction::SystemInstruction, system_program},
std::convert::TryFrom,
std::sync::Arc,
};
@ -35,23 +34,6 @@ pub struct TransactionAccountLocks<'a> {
pub writable: Vec<&'a Pubkey>,
}
impl TryFrom<Transaction> for SanitizedTransaction {
type Error = TransactionError;
fn try_from(tx: Transaction) -> Result<Self> {
tx.sanitize()?;
if tx.message.has_duplicates() {
return Err(TransactionError::AccountLoadedTwice);
}
Ok(Self {
message_hash: tx.message.hash(),
message: SanitizedMessage::Legacy(tx.message),
signatures: tx.signatures,
})
}
}
impl SanitizedTransaction {
/// Create a sanitized transaction from an unsanitized transaction.
/// If the input transaction uses address maps, attempt to map the
@ -83,6 +65,21 @@ impl SanitizedTransaction {
})
}
/// Create a sanitized transaction from a legacy transaction. Used for tests only.
pub fn from_transaction_for_tests(tx: Transaction) -> Self {
tx.sanitize().unwrap();
if tx.message.has_duplicates() {
Result::<Self>::Err(TransactionError::AccountLoadedTwice).unwrap();
}
Self {
message_hash: tx.message.hash(),
message: SanitizedMessage::Legacy(tx.message),
signatures: tx.signatures,
}
}
/// Return the first signature for this transaction.
///
/// Notes: