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

View File

@ -3434,7 +3434,7 @@ pub mod tests {
Hash::default(), Hash::default(),
); );
let txs = vec![account_not_found_tx, invalid_blockhash_tx]; 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 ( let (
TransactionResults { TransactionResults {
fee_collection_results, fee_collection_results,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,7 +14,6 @@ use {
transaction::{Result, Transaction, TransactionError, VersionedTransaction}, transaction::{Result, Transaction, TransactionError, VersionedTransaction},
}, },
solana_program::{system_instruction::SystemInstruction, system_program}, solana_program::{system_instruction::SystemInstruction, system_program},
std::convert::TryFrom,
std::sync::Arc, std::sync::Arc,
}; };
@ -35,23 +34,6 @@ pub struct TransactionAccountLocks<'a> {
pub writable: Vec<&'a Pubkey>, 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 { impl SanitizedTransaction {
/// Create a sanitized transaction from an unsanitized transaction. /// Create a sanitized transaction from an unsanitized transaction.
/// If the input transaction uses address maps, attempt to map the /// 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. /// Return the first signature for this transaction.
/// ///
/// Notes: /// Notes: