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