Skip to main content

solana_transaction_context/
transaction_accounts.rs

1#[cfg(feature = "dev-context-only-utils")]
2use qualifier_attr::qualifiers;
3use {
4    crate::{
5        DropOnBailOut, IndexOfAccount, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION,
6        MAX_ACCOUNT_DATA_LEN,
7        vm_addresses::{GUEST_ACCOUNT_PAYLOAD_BASE_ADDRESS, GUEST_REGION_SIZE},
8        vm_slice::VmSlice,
9    },
10    solana_account::{AccountSharedData, ReadableAccount, WritableAccount},
11    solana_instruction_error::InstructionError,
12    solana_pubkey::Pubkey,
13    std::{
14        cell::{Cell, UnsafeCell},
15        ops::{Deref, DerefMut},
16        ptr,
17        sync::Arc,
18    },
19};
20
21/// This struct is shared with programs. Do not alter its fields.
22#[repr(C)]
23#[derive(Debug, PartialEq)]
24struct AccountSharedFields {
25    key: Pubkey,
26    owner: Pubkey,
27    lamports: u64,
28    // The payload is going to be filled with the guest virtual address of the account payload
29    // vector.
30    payload: VmSlice<u8>,
31}
32
33#[derive(Debug, PartialEq)]
34#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
35struct AccountPrivateFields {
36    rent_epoch: u64,
37    executable: bool,
38    payload: Arc<Vec<u8>>,
39}
40
41#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
42impl AccountPrivateFields {
43    fn payload_len(&self) -> usize {
44        self.payload.len()
45    }
46}
47
48#[derive(Debug, PartialEq)]
49#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
50pub struct TransactionAccountView<'a> {
51    abi_account: &'a AccountSharedFields,
52    private_fields: &'a AccountPrivateFields,
53}
54
55#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
56impl ReadableAccount for TransactionAccountView<'_> {
57    fn lamports(&self) -> u64 {
58        self.abi_account.lamports
59    }
60
61    fn data(&self) -> &[u8] {
62        self.private_fields.payload.as_slice()
63    }
64
65    fn owner(&self) -> &Pubkey {
66        &self.abi_account.owner
67    }
68
69    fn executable(&self) -> bool {
70        self.private_fields.executable
71    }
72
73    fn rent_epoch(&self) -> u64 {
74        self.private_fields.rent_epoch
75    }
76}
77
78#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
79impl PartialEq<AccountSharedData> for TransactionAccountView<'_> {
80    fn eq(&self, other: &AccountSharedData) -> bool {
81        other.lamports() == self.lamports()
82            && other.data() == self.data()
83            && other.owner() == self.owner()
84            && other.executable() == self.executable()
85            && other.rent_epoch() == self.rent_epoch()
86    }
87}
88
89#[derive(Debug)]
90#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
91pub struct TransactionAccountViewMut<'a> {
92    abi_account: &'a mut AccountSharedFields,
93    private_fields: &'a mut AccountPrivateFields,
94}
95
96#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
97impl TransactionAccountViewMut<'_> {
98    fn data_mut(&mut self) -> &mut Vec<u8> {
99        Arc::make_mut(&mut self.private_fields.payload)
100    }
101
102    pub(crate) fn raw_mut_data_slice(&mut self) -> *mut [u8] {
103        &raw mut self.data_mut()[..]
104    }
105
106    pub(crate) fn resize(&mut self, new_len: usize, value: u8) {
107        match self.private_fields.payload.get(..new_len) {
108            // If the buffer is shared and doesn't grow, copy only the retained
109            // prefix instead of cloning the whole buffer and truncating it.
110            Some(prefix) if self.is_shared() => {
111                self.private_fields.payload = Arc::new(prefix.to_vec());
112            }
113            _ => self.data_mut().resize(new_len, value),
114        }
115        self.abi_account.payload.set_len(new_len as u64);
116    }
117
118    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
119    pub(crate) fn set_data_from_slice(&mut self, new_data: &[u8]) {
120        // If the buffer isn't shared, we're going to memcpy in place.
121        let Some(data) = Arc::get_mut(&mut self.private_fields.payload) else {
122            // If the buffer is shared, the cheapest thing to do is to clone the
123            // incoming slice and replace the buffer.
124            self.private_fields.payload = Arc::new(new_data.to_vec());
125            self.abi_account.payload.set_len(new_data.len() as u64);
126            return;
127        };
128
129        let new_len = new_data.len();
130
131        // Reserve additional capacity if needed. Here we make the assumption
132        // that growing the current buffer is cheaper than doing a whole new
133        // allocation to make `new_data` owned.
134        //
135        // This assumption holds true during CPI, especially when the account
136        // size doesn't change but the account is only changed in place. And
137        // it's also true when the account is grown by a small margin (the
138        // realloc limit is quite low), in which case the allocator can just
139        // update the allocation metadata without moving.
140        //
141        // Shrinking and copying in place is always faster than making
142        // `new_data` owned, since shrinking boils down to updating the Vec's
143        // length.
144
145        data.reserve(new_len.saturating_sub(data.len()));
146
147        // Safety:
148        // We just reserved enough capacity. We set data::len to 0 to avoid
149        // possible UB on panic (dropping uninitialized elements), do the copy,
150        // finally set the new length once everything is initialized.
151        unsafe {
152            data.set_len(0);
153            ptr::copy_nonoverlapping(new_data.as_ptr(), data.as_mut_ptr(), new_len);
154            data.set_len(new_len);
155            self.abi_account.payload.set_len(new_len as u64);
156        };
157    }
158
159    pub(crate) fn extend_from_slice(&mut self, data: &[u8]) {
160        self.data_mut().extend_from_slice(data);
161        self.abi_account
162            .payload
163            .set_len(self.private_fields.payload_len() as u64);
164    }
165
166    pub(crate) fn reserve(&mut self, additional: usize) {
167        if let Some(data) = Arc::get_mut(&mut self.private_fields.payload) {
168            data.reserve(additional)
169        } else {
170            let mut data =
171                Vec::with_capacity(self.private_fields.payload_len().saturating_add(additional));
172            data.extend_from_slice(self.private_fields.payload.as_slice());
173            self.private_fields.payload = Arc::new(data);
174        }
175    }
176
177    /// Encodes `state` over the start of the data, copying only the tail of a shared buffer.
178    #[cfg(feature = "wincode")]
179    pub(crate) fn set_state<T>(&mut self, state: &T) -> Result<(), InstructionError>
180    where
181        T: wincode::SchemaWrite<solana_account::WincodeConfig, Src = T>,
182    {
183        let Some(data) = Arc::get_mut(&mut self.private_fields.payload) else {
184            let old_data = &self.private_fields.payload;
185            let mut data = Vec::with_capacity(old_data.len());
186            wincode::config::serialize_into(&mut data, state, solana_account::WINCODE_CONFIG)
187                .map_err(|_| InstructionError::GenericError)?;
188            let tail = old_data
189                .get(data.len()..)
190                .ok_or(InstructionError::AccountDataTooSmall)?;
191            data.extend_from_slice(tail);
192            self.private_fields.payload = Arc::new(data);
193            return Ok(());
194        };
195        wincode::config::serialize_into(data.as_mut_slice(), state, solana_account::WINCODE_CONFIG)
196            .map_err(|_| InstructionError::GenericError)
197    }
198
199    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
200    pub(crate) fn is_shared(&self) -> bool {
201        Arc::strong_count(&self.private_fields.payload) > 1
202    }
203}
204
205#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
206impl ReadableAccount for TransactionAccountViewMut<'_> {
207    fn lamports(&self) -> u64 {
208        self.abi_account.lamports
209    }
210
211    fn data(&self) -> &[u8] {
212        self.private_fields.payload.as_slice()
213    }
214
215    fn owner(&self) -> &Pubkey {
216        &self.abi_account.owner
217    }
218
219    fn executable(&self) -> bool {
220        self.private_fields.executable
221    }
222
223    fn rent_epoch(&self) -> u64 {
224        self.private_fields.rent_epoch
225    }
226}
227
228#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
229impl WritableAccount for TransactionAccountViewMut<'_> {
230    fn set_lamports(&mut self, lamports: u64) {
231        self.abi_account.lamports = lamports;
232    }
233
234    fn data_as_mut_slice(&mut self) -> &mut [u8] {
235        Arc::make_mut(&mut self.private_fields.payload).as_mut_slice()
236    }
237
238    fn set_owner(&mut self, owner: Pubkey) {
239        self.abi_account.owner = owner;
240    }
241
242    fn copy_into_owner_from_slice(&mut self, source: &[u8]) {
243        self.abi_account.owner.as_mut().copy_from_slice(source);
244    }
245
246    fn set_executable(&mut self, executable: bool) {
247        self.private_fields.executable = executable;
248    }
249
250    fn set_rent_epoch(&mut self, epoch: u64) {
251        self.private_fields.rent_epoch = epoch;
252    }
253}
254
255/// An account key and the matching account
256#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
257pub type KeyedAccountSharedData = (Pubkey, AccountSharedData);
258#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
259pub(crate) type DeconstructedTransactionAccounts =
260    (Vec<KeyedAccountSharedData>, Box<[Cell<bool>]>, Cell<i64>);
261
262#[derive(Debug)]
263#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
264pub struct TransactionAccounts {
265    shared_account_fields: Box<[UnsafeCell<AccountSharedFields>]>,
266    private_account_fields: Box<[UnsafeCell<AccountPrivateFields>]>,
267    borrow_counters: Box<[BorrowCounter]>,
268    touched_flags: Box<[Cell<bool>]>,
269    resize_delta: Cell<i64>,
270    _drop_on_bail_out: DropOnBailOut,
271}
272
273#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
274impl TransactionAccounts {
275    pub(crate) fn new_with_feature_flags(
276        accounts: Vec<KeyedAccountSharedData>,
277        drop_on_bail_out: DropOnBailOut,
278    ) -> TransactionAccounts {
279        let touched_flags = vec![Cell::new(false); accounts.len()].into_boxed_slice();
280        let borrow_counters = vec![BorrowCounter::default(); accounts.len()].into_boxed_slice();
281        let (shared_accounts, private_fields) = accounts
282            .into_iter()
283            .enumerate()
284            .map(|(idx, item)| {
285                (
286                    UnsafeCell::new(AccountSharedFields {
287                        key: item.0,
288                        owner: *item.1.owner(),
289                        lamports: item.1.lamports(),
290                        payload: VmSlice::new(
291                            GUEST_ACCOUNT_PAYLOAD_BASE_ADDRESS
292                                .saturating_add(GUEST_REGION_SIZE.saturating_mul(idx as u64)),
293                            item.1.data().len() as u64,
294                        ),
295                    }),
296                    UnsafeCell::new(AccountPrivateFields {
297                        rent_epoch: item.1.rent_epoch(),
298                        executable: item.1.executable(),
299                        payload: item.1.data_clone(),
300                    }),
301                )
302            })
303            .collect::<(
304                Vec<UnsafeCell<AccountSharedFields>>,
305                Vec<UnsafeCell<AccountPrivateFields>>,
306            )>();
307
308        TransactionAccounts {
309            shared_account_fields: shared_accounts.into_boxed_slice(),
310            private_account_fields: private_fields.into_boxed_slice(),
311            borrow_counters,
312            touched_flags,
313            resize_delta: Cell::new(0),
314            _drop_on_bail_out: drop_on_bail_out,
315        }
316    }
317
318    #[cfg(feature = "dev-context-only-utils")]
319    pub fn new(accounts: Vec<KeyedAccountSharedData>) -> TransactionAccounts {
320        TransactionAccounts::new_with_feature_flags(accounts, DropOnBailOut::Disabled)
321    }
322
323    pub(crate) fn len(&self) -> usize {
324        self.shared_account_fields.len()
325    }
326
327    pub fn touch(&self, index: IndexOfAccount) -> Result<(), InstructionError> {
328        self.touched_flags
329            .get(index as usize)
330            .ok_or(InstructionError::MissingAccount)?
331            .set(true);
332        Ok(())
333    }
334
335    pub(crate) fn update_accounts_resize_delta(
336        &self,
337        old_len: usize,
338        new_len: usize,
339    ) -> Result<(), InstructionError> {
340        let accounts_resize_delta = self.resize_delta.get();
341        self.resize_delta.set(
342            accounts_resize_delta.saturating_add((new_len as i64).saturating_sub(old_len as i64)),
343        );
344        Ok(())
345    }
346
347    pub(crate) fn can_data_be_resized(
348        &self,
349        old_len: usize,
350        new_len: usize,
351    ) -> Result<(), InstructionError> {
352        // The new length can not exceed the maximum permitted length
353        if new_len > MAX_ACCOUNT_DATA_LEN as usize {
354            return Err(InstructionError::InvalidRealloc);
355        }
356        // The resize can not exceed the per-transaction maximum
357        let length_delta = (new_len as i64).saturating_sub(old_len as i64);
358        if self.resize_delta.get().saturating_add(length_delta)
359            > MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION
360        {
361            return Err(InstructionError::MaxAccountsDataAllocationsExceeded);
362        }
363        Ok(())
364    }
365
366    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
367    pub(crate) fn try_borrow_mut(
368        &self,
369        index: IndexOfAccount,
370    ) -> Result<AccountRefMut<'_>, InstructionError> {
371        let borrow_counter = self
372            .borrow_counters
373            .get(index as usize)
374            .ok_or(InstructionError::MissingAccount)?;
375        borrow_counter.try_borrow_mut()?;
376
377        // SAFETY: The borrow counter guarantees this is the only mutable borrow of this account.
378        // The unwrap is safe because accounts.len() == borrow_counters.len(), so the missing
379        // account error should have been returned above.
380        let svm_account = unsafe {
381            &mut *self
382                .shared_account_fields
383                .get(index as usize)
384                .unwrap()
385                .get()
386        };
387
388        let private_fields = unsafe {
389            &mut *self
390                .private_account_fields
391                .get(index as usize)
392                .unwrap()
393                .get()
394        };
395
396        let account = TransactionAccountViewMut {
397            abi_account: svm_account,
398            private_fields,
399        };
400
401        Ok(AccountRefMut {
402            account,
403            borrow_counter,
404        })
405    }
406
407    pub fn try_borrow(&self, index: IndexOfAccount) -> Result<AccountRef<'_>, InstructionError> {
408        let borrow_counter = self
409            .borrow_counters
410            .get(index as usize)
411            .ok_or(InstructionError::MissingAccount)?;
412        borrow_counter.try_borrow()?;
413
414        // SAFETY: The borrow counter guarantees there are no mutable borrow of this account.
415        // The unwrap is safe because accounts.len() == borrow_counters.len(), so the missing
416        // account error should have been returned above.
417        let svm_account = unsafe {
418            &*self
419                .shared_account_fields
420                .get(index as usize)
421                .unwrap()
422                .get()
423        };
424
425        let private_fields = unsafe {
426            &*self
427                .private_account_fields
428                .get(index as usize)
429                .unwrap()
430                .get()
431        };
432
433        let account = TransactionAccountView {
434            abi_account: svm_account,
435            private_fields,
436        };
437
438        Ok(AccountRef {
439            account,
440            borrow_counter,
441        })
442    }
443
444    fn deconstruct_into_keyed_account_shared_data(&mut self) -> Vec<KeyedAccountSharedData> {
445        let shared_account_fields = std::mem::take(&mut self.shared_account_fields);
446        let private_account_fields = std::mem::take(&mut self.private_account_fields);
447        shared_account_fields
448            .into_iter()
449            .zip(private_account_fields)
450            .map(|(shared_fields_cell, private_fields_cell)| {
451                let shared_fields = shared_fields_cell.into_inner();
452                let private_fields = private_fields_cell.into_inner();
453                (
454                    shared_fields.key,
455                    AccountSharedData::create_from_existing_shared_data(
456                        shared_fields.lamports,
457                        private_fields.payload,
458                        shared_fields.owner,
459                        private_fields.executable,
460                        private_fields.rent_epoch,
461                    ),
462                )
463            })
464            .collect()
465    }
466
467    pub(crate) fn deconstruct_into_account_shared_data(&mut self) -> Vec<AccountSharedData> {
468        let shared_account_fields = std::mem::take(&mut self.shared_account_fields);
469        let private_account_fields = std::mem::take(&mut self.private_account_fields);
470        shared_account_fields
471            .into_iter()
472            .zip(private_account_fields)
473            .map(|(shared_fields_cell, private_fields_cell)| {
474                let shared_fields = shared_fields_cell.into_inner();
475                let private_fields = private_fields_cell.into_inner();
476                AccountSharedData::create_from_existing_shared_data(
477                    shared_fields.lamports,
478                    private_fields.payload,
479                    shared_fields.owner,
480                    private_fields.executable,
481                    private_fields.rent_epoch,
482                )
483            })
484            .collect()
485    }
486
487    pub(crate) fn take(mut self) -> DeconstructedTransactionAccounts {
488        let shared_data = self.deconstruct_into_keyed_account_shared_data();
489        (shared_data, self.touched_flags, self.resize_delta)
490    }
491
492    pub fn resize_delta(&self) -> i64 {
493        self.resize_delta.get()
494    }
495
496    pub(crate) fn account_key(&self, index: IndexOfAccount) -> Option<&Pubkey> {
497        // SAFETY: We never modify an account key, so returning a reference to it is safe.
498        unsafe {
499            self.shared_account_fields
500                .get(index as usize)
501                .map(|acc| &(*acc.get()).key)
502        }
503    }
504
505    pub(crate) fn account_keys_iter(&self) -> impl Iterator<Item = &Pubkey> {
506        // SAFETY: We never modify account keys, so returning an immutable reference to them is safe.
507        unsafe {
508            self.shared_account_fields
509                .iter()
510                .map(|item| &(*item.get()).key)
511        }
512    }
513}
514
515#[derive(Default, Debug, Clone)]
516#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
517struct BorrowCounter {
518    counter: Cell<i8>,
519}
520
521#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
522impl BorrowCounter {
523    #[inline]
524    fn is_writing(&self) -> bool {
525        self.counter.get() < 0
526    }
527
528    #[inline]
529    fn is_reading(&self) -> bool {
530        self.counter.get() > 0
531    }
532
533    #[inline]
534    fn try_borrow(&self) -> Result<(), InstructionError> {
535        if self.is_writing() {
536            return Err(InstructionError::AccountBorrowFailed);
537        }
538
539        if let Some(counter) = self.counter.get().checked_add(1) {
540            self.counter.set(counter);
541            return Ok(());
542        }
543
544        Err(InstructionError::AccountBorrowFailed)
545    }
546
547    #[inline]
548    fn try_borrow_mut(&self) -> Result<(), InstructionError> {
549        if self.is_writing() || self.is_reading() {
550            return Err(InstructionError::AccountBorrowFailed);
551        }
552
553        self.counter.set(self.counter.get().saturating_sub(1));
554
555        Ok(())
556    }
557
558    #[inline]
559    fn release_borrow(&self) {
560        self.counter.set(self.counter.get().saturating_sub(1));
561    }
562
563    #[inline]
564    fn release_borrow_mut(&self) {
565        self.counter.set(self.counter.get().saturating_add(1));
566    }
567}
568
569#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
570pub struct AccountRef<'a> {
571    account: TransactionAccountView<'a>,
572    borrow_counter: &'a BorrowCounter,
573}
574
575#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
576impl Drop for AccountRef<'_> {
577    fn drop(&mut self) {
578        self.borrow_counter.release_borrow();
579    }
580}
581
582#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
583impl<'a> Deref for AccountRef<'a> {
584    type Target = TransactionAccountView<'a>;
585    fn deref(&self) -> &Self::Target {
586        &self.account
587    }
588}
589
590#[derive(Debug)]
591#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
592pub struct AccountRefMut<'a> {
593    account: TransactionAccountViewMut<'a>,
594    borrow_counter: &'a BorrowCounter,
595}
596
597#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
598impl Drop for AccountRefMut<'_> {
599    fn drop(&mut self) {
600        self.account
601            .abi_account
602            .payload
603            .set_len(self.account.private_fields.payload_len() as u64);
604        self.borrow_counter.release_borrow_mut();
605    }
606}
607
608#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
609impl<'a> Deref for AccountRefMut<'a> {
610    type Target = TransactionAccountViewMut<'a>;
611    fn deref(&self) -> &Self::Target {
612        &self.account
613    }
614}
615
616#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
617impl DerefMut for AccountRefMut<'_> {
618    fn deref_mut(&mut self) -> &mut Self::Target {
619        &mut self.account
620    }
621}
622
623#[cfg(all(test, not(target_arch = "sbf"), not(target_arch = "bpf")))]
624mod tests {
625    use {
626        crate::transaction_accounts::TransactionAccounts,
627        solana_account::{AccountSharedData, ReadableAccount},
628        solana_instruction_error::InstructionError,
629        solana_pubkey::Pubkey,
630        std::sync::Arc,
631        test_case::test_case,
632    };
633
634    #[test_case(true, 4; "shrink_shared")]
635    #[test_case(false, 4; "shrink_unshared")]
636    #[test_case(true, 0; "shrink_shared_to_empty")]
637    #[test_case(true, 200; "grow_shared")]
638    #[test_case(false, 200; "grow_unshared")]
639    #[test_case(true, 100; "same_length_shared")]
640    #[test_case(false, 100; "same_length_unshared")]
641    fn test_resize(shared: bool, new_len: usize) {
642        let data = (0..100).collect::<Vec<u8>>();
643        let account = AccountSharedData::new_with_data(1, data.clone(), &Pubkey::new_unique());
644        let original = shared.then(|| account.data_clone());
645        let tx_accounts = TransactionAccounts::new(vec![(Pubkey::new_unique(), account)]);
646        let mut expected = data.clone();
647        expected.resize(new_len, 0);
648
649        let mut acc = tx_accounts.try_borrow_mut(0).unwrap();
650        assert_eq!(acc.is_shared(), shared);
651        acc.resize(new_len, 0);
652        assert_eq!(acc.data(), expected);
653        assert_eq!(acc.account.abi_account.payload.len(), new_len as u64);
654        assert!(!acc.is_shared());
655        if let Some(original) = original {
656            assert!(!Arc::ptr_eq(&original, &acc.account.private_fields.payload));
657            if new_len <= data.len() {
658                assert_eq!(acc.account.private_fields.payload.capacity(), new_len);
659            }
660            assert_eq!(*original, data);
661        }
662    }
663
664    #[test]
665    fn test_missing_account() {
666        let accounts = vec![
667            (
668                Pubkey::new_unique(),
669                AccountSharedData::new_with_data(2, vec![0; 1], &Pubkey::new_unique()),
670            ),
671            (
672                Pubkey::new_unique(),
673                AccountSharedData::new_with_data(2, vec![0; 1], &Pubkey::new_unique()),
674            ),
675        ];
676
677        let tx_accounts = TransactionAccounts::new(accounts);
678
679        let res = tx_accounts.try_borrow(3);
680        assert_eq!(res.err(), Some(InstructionError::MissingAccount));
681
682        let res = tx_accounts.try_borrow_mut(3);
683        assert_eq!(res.err(), Some(InstructionError::MissingAccount));
684    }
685
686    #[test]
687    fn test_invalid_borrow() {
688        let accounts = vec![
689            (
690                Pubkey::new_unique(),
691                AccountSharedData::new_with_data(2, vec![0; 1], &Pubkey::new_unique()),
692            ),
693            (
694                Pubkey::new_unique(),
695                AccountSharedData::new_with_data(2, vec![0; 1], &Pubkey::new_unique()),
696            ),
697        ];
698
699        let tx_accounts = TransactionAccounts::new(accounts);
700
701        // Two immutable borrows are valid
702        {
703            let acc_1 = tx_accounts.try_borrow(0);
704            assert!(acc_1.is_ok());
705
706            let acc_2 = tx_accounts.try_borrow(1);
707            assert!(acc_2.is_ok());
708
709            let acc_1_new = tx_accounts.try_borrow(0);
710            assert!(acc_1_new.is_ok());
711
712            assert_eq!(acc_1.unwrap().account, acc_1_new.unwrap().account);
713        }
714
715        // Two mutable borrows are invalid
716        {
717            let acc_1 = tx_accounts.try_borrow_mut(0);
718            assert!(acc_1.is_ok());
719
720            let acc_2 = tx_accounts.try_borrow_mut(1);
721            assert!(acc_2.is_ok());
722
723            let acc_1_new = tx_accounts.try_borrow_mut(0);
724            assert_eq!(acc_1_new.err(), Some(InstructionError::AccountBorrowFailed));
725        }
726
727        // Mutable after immutable must fail
728        {
729            let acc_1 = tx_accounts.try_borrow(0);
730            assert!(acc_1.is_ok());
731
732            let acc_2 = tx_accounts.try_borrow(1);
733            assert!(acc_2.is_ok());
734
735            let acc_1_new = tx_accounts.try_borrow_mut(0);
736            assert_eq!(acc_1_new.err(), Some(InstructionError::AccountBorrowFailed));
737        }
738
739        // Immutable after mutable must fail
740        {
741            let acc_1 = tx_accounts.try_borrow_mut(0);
742            assert!(acc_1.is_ok());
743
744            let acc_2 = tx_accounts.try_borrow_mut(1);
745            assert!(acc_2.is_ok());
746
747            let acc_1_new = tx_accounts.try_borrow(0);
748            assert_eq!(acc_1_new.err(), Some(InstructionError::AccountBorrowFailed));
749        }
750
751        // Different scopes are good
752        {
753            let acc_1 = tx_accounts.try_borrow_mut(0);
754            assert!(acc_1.is_ok());
755        }
756
757        {
758            let acc_1 = tx_accounts.try_borrow_mut(0);
759            assert!(acc_1.is_ok());
760        }
761    }
762
763    #[test]
764    fn too_many_borrows() {
765        let accounts = vec![
766            (
767                Pubkey::new_unique(),
768                AccountSharedData::new_with_data(2, vec![0; 1], &Pubkey::new_unique()),
769            ),
770            (
771                Pubkey::new_unique(),
772                AccountSharedData::new_with_data(2, vec![0; 1], &Pubkey::new_unique()),
773            ),
774        ];
775
776        let tx_accounts = TransactionAccounts::new(accounts);
777        let mut borrows = Vec::new();
778        for i in 0..129 {
779            let acc = tx_accounts.try_borrow(1);
780            if i < 127 {
781                assert!(acc.is_ok());
782                borrows.push(acc.unwrap());
783            } else {
784                assert_eq!(acc.err(), Some(InstructionError::AccountBorrowFailed));
785            }
786        }
787    }
788}