solana_runtime/
transaction_batch.rs

1use {
2    crate::bank::Bank, core::ops::Deref, solana_sdk::transaction::Result,
3    solana_svm_transaction::svm_message::SVMMessage,
4};
5
6pub enum OwnedOrBorrowed<'a, T> {
7    Owned(Vec<T>),
8    Borrowed(&'a [T]),
9}
10
11impl<T> Deref for OwnedOrBorrowed<'_, T> {
12    type Target = [T];
13
14    fn deref(&self) -> &Self::Target {
15        match self {
16            OwnedOrBorrowed::Owned(v) => v,
17            OwnedOrBorrowed::Borrowed(v) => v,
18        }
19    }
20}
21
22// Represents the results of trying to lock a set of accounts
23pub struct TransactionBatch<'a, 'b, Tx: SVMMessage> {
24    lock_results: Vec<Result<()>>,
25    bank: &'a Bank,
26    sanitized_txs: OwnedOrBorrowed<'b, Tx>,
27    needs_unlock: bool,
28}
29
30impl<'a, 'b, Tx: SVMMessage> TransactionBatch<'a, 'b, Tx> {
31    pub fn new(
32        lock_results: Vec<Result<()>>,
33        bank: &'a Bank,
34        sanitized_txs: OwnedOrBorrowed<'b, Tx>,
35    ) -> Self {
36        assert_eq!(lock_results.len(), sanitized_txs.len());
37        Self {
38            lock_results,
39            bank,
40            sanitized_txs,
41            needs_unlock: true,
42        }
43    }
44
45    pub fn lock_results(&self) -> &Vec<Result<()>> {
46        &self.lock_results
47    }
48
49    pub fn sanitized_transactions(&self) -> &[Tx] {
50        &self.sanitized_txs
51    }
52
53    pub fn bank(&self) -> &Bank {
54        self.bank
55    }
56
57    pub fn set_needs_unlock(&mut self, needs_unlock: bool) {
58        self.needs_unlock = needs_unlock;
59    }
60
61    pub fn needs_unlock(&self) -> bool {
62        self.needs_unlock
63    }
64
65    /// For every error result, if the corresponding transaction is
66    /// still locked, unlock the transaction and then record the new error.
67    pub fn unlock_failures(&mut self, transaction_results: Vec<Result<()>>) {
68        assert_eq!(self.lock_results.len(), transaction_results.len());
69        // Shouldn't happen but if a batch was marked as not needing an unlock,
70        // don't unlock failures.
71        if !self.needs_unlock() {
72            return;
73        }
74
75        let txs_and_results = transaction_results
76            .iter()
77            .enumerate()
78            .inspect(|(index, result)| {
79                // It's not valid to update a previously recorded lock error to
80                // become an "ok" result because this could lead to serious
81                // account lock violations where accounts are later unlocked
82                // when they were not currently locked.
83                assert!(!(result.is_ok() && self.lock_results[*index].is_err()))
84            })
85            .filter(|(index, result)| result.is_err() && self.lock_results[*index].is_ok())
86            .map(|(index, _)| (&self.sanitized_txs[index], &self.lock_results[index]));
87
88        // Unlock the accounts for all transactions which will be updated to an
89        // lock error below.
90        self.bank.unlock_accounts(txs_and_results);
91
92        // Record all new errors by overwriting lock results. Note that it's
93        // not valid to update from err -> ok and the assertion above enforces
94        // that validity constraint.
95        self.lock_results = transaction_results;
96    }
97}
98
99// Unlock all locked accounts in destructor.
100impl<Tx: SVMMessage> Drop for TransactionBatch<'_, '_, Tx> {
101    fn drop(&mut self) {
102        if self.needs_unlock() {
103            self.set_needs_unlock(false);
104            self.bank.unlock_accounts(
105                self.sanitized_transactions()
106                    .iter()
107                    .zip(self.lock_results()),
108            )
109        }
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use {
116        super::*,
117        crate::genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo},
118        solana_runtime_transaction::runtime_transaction::RuntimeTransaction,
119        solana_sdk::{
120            signature::Keypair,
121            system_transaction,
122            transaction::{SanitizedTransaction, TransactionError},
123        },
124    };
125
126    #[test]
127    fn test_transaction_batch() {
128        let (bank, txs) = setup(false);
129
130        // Test getting locked accounts
131        let batch = bank.prepare_sanitized_batch(&txs);
132
133        // Grab locks
134        assert!(batch.lock_results().iter().all(|x| x.is_ok()));
135
136        // Trying to grab locks again should fail
137        let batch2 = bank.prepare_sanitized_batch(&txs);
138        assert!(batch2.lock_results().iter().all(|x| x.is_err()));
139
140        // Drop the first set of locks
141        drop(batch);
142
143        // Now grabbing locks should work again
144        let batch2 = bank.prepare_sanitized_batch(&txs);
145        assert!(batch2.lock_results().iter().all(|x| x.is_ok()));
146    }
147
148    #[test]
149    fn test_simulation_batch() {
150        let (bank, txs) = setup(false);
151
152        // Prepare batch without locks
153        let batch = bank.prepare_unlocked_batch_from_single_tx(&txs[0]);
154        assert!(batch.lock_results().iter().all(|x| x.is_ok()));
155
156        // Grab locks
157        let batch2 = bank.prepare_sanitized_batch(&txs);
158        assert!(batch2.lock_results().iter().all(|x| x.is_ok()));
159
160        // Prepare another batch without locks
161        let batch3 = bank.prepare_unlocked_batch_from_single_tx(&txs[0]);
162        assert!(batch3.lock_results().iter().all(|x| x.is_ok()));
163    }
164
165    #[test]
166    fn test_unlock_failures() {
167        let (bank, txs) = setup(true);
168
169        // Test getting locked accounts
170        let mut batch = bank.prepare_sanitized_batch(&txs);
171        assert_eq!(
172            batch.lock_results,
173            vec![Ok(()), Err(TransactionError::AccountInUse), Ok(())]
174        );
175
176        let qos_results = vec![
177            Ok(()),
178            Err(TransactionError::AccountInUse),
179            Err(TransactionError::WouldExceedMaxBlockCostLimit),
180        ];
181        batch.unlock_failures(qos_results.clone());
182        assert_eq!(batch.lock_results, qos_results);
183
184        // Dropping the batch should unlock remaining locked transactions
185        drop(batch);
186
187        // The next batch should be able to lock all but the conflicting tx
188        let batch2 = bank.prepare_sanitized_batch(&txs);
189        assert_eq!(
190            batch2.lock_results,
191            vec![Ok(()), Err(TransactionError::AccountInUse), Ok(())]
192        );
193    }
194
195    fn setup(insert_conflicting_tx: bool) -> (Bank, Vec<RuntimeTransaction<SanitizedTransaction>>) {
196        let dummy_leader_pubkey = solana_pubkey::new_rand();
197        let GenesisConfigInfo {
198            genesis_config,
199            mint_keypair,
200            ..
201        } = create_genesis_config_with_leader(500, &dummy_leader_pubkey, 100);
202        let bank = Bank::new_for_tests(&genesis_config);
203
204        let pubkey = solana_pubkey::new_rand();
205        let keypair2 = Keypair::new();
206        let pubkey2 = solana_pubkey::new_rand();
207
208        let mut txs = vec![RuntimeTransaction::from_transaction_for_tests(
209            system_transaction::transfer(&mint_keypair, &pubkey, 1, genesis_config.hash()),
210        )];
211        if insert_conflicting_tx {
212            txs.push(RuntimeTransaction::from_transaction_for_tests(
213                system_transaction::transfer(&mint_keypair, &pubkey2, 1, genesis_config.hash()),
214            ));
215        }
216        txs.push(RuntimeTransaction::from_transaction_for_tests(
217            system_transaction::transfer(&keypair2, &pubkey2, 1, genesis_config.hash()),
218        ));
219
220        (bank, txs)
221    }
222}