loader_account.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. use crate::error::ErrorCode;
  2. use crate::{
  3. Accounts, AccountsClose, AccountsExit, Key, Owner, ToAccountInfo, ToAccountInfos,
  4. ToAccountMetas, ZeroCopy,
  5. };
  6. use solana_program::account_info::AccountInfo;
  7. use solana_program::entrypoint::ProgramResult;
  8. use solana_program::instruction::AccountMeta;
  9. use solana_program::program_error::ProgramError;
  10. use solana_program::pubkey::Pubkey;
  11. use std::cell::{Ref, RefMut};
  12. use std::fmt;
  13. use std::io::Write;
  14. use std::marker::PhantomData;
  15. use std::ops::DerefMut;
  16. /// Account AccountLoader facilitating on demand zero copy deserialization.
  17. /// Note that using accounts in this way is distinctly different from using,
  18. /// for example, the [`ProgramAccount`](./struct.ProgramAccount.html). Namely,
  19. /// one must call `load`, `load_mut`, or `load_init`, before reading or writing
  20. /// to the account. For more details on zero-copy-deserialization, see the
  21. /// [`account`](./attr.account.html) attribute.
  22. ///
  23. /// When using it's important to be mindful of any calls to `load` so as not to
  24. /// induce a `RefCell` panic, especially when sharing accounts across CPI
  25. /// boundaries. When in doubt, one should make sure all refs resulting from a
  26. /// call to `load` are dropped before CPI.
  27. #[derive(Clone)]
  28. pub struct AccountLoader<'info, T: ZeroCopy + Owner> {
  29. acc_info: AccountInfo<'info>,
  30. phantom: PhantomData<&'info T>,
  31. }
  32. impl<'info, T: ZeroCopy + Owner + fmt::Debug> fmt::Debug for AccountLoader<'info, T> {
  33. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  34. f.debug_struct("AccountLoader")
  35. .field("acc_info", &self.acc_info)
  36. .field("phantom", &self.phantom)
  37. .finish()
  38. }
  39. }
  40. impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> {
  41. fn new(acc_info: AccountInfo<'info>) -> AccountLoader<'info, T> {
  42. Self {
  43. acc_info,
  44. phantom: PhantomData,
  45. }
  46. }
  47. /// Constructs a new `Loader` from a previously initialized account.
  48. #[inline(never)]
  49. pub fn try_from(
  50. acc_info: &AccountInfo<'info>,
  51. ) -> Result<AccountLoader<'info, T>, ProgramError> {
  52. if acc_info.owner != &T::owner() {
  53. return Err(ErrorCode::AccountNotProgramOwned.into());
  54. }
  55. let data: &[u8] = &acc_info.try_borrow_data()?;
  56. // Discriminator must match.
  57. let mut disc_bytes = [0u8; 8];
  58. disc_bytes.copy_from_slice(&data[..8]);
  59. if disc_bytes != T::discriminator() {
  60. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  61. }
  62. Ok(AccountLoader::new(acc_info.clone()))
  63. }
  64. /// Constructs a new `Loader` from an uninitialized account.
  65. #[inline(never)]
  66. pub fn try_from_unchecked(
  67. _program_id: &Pubkey,
  68. acc_info: &AccountInfo<'info>,
  69. ) -> Result<AccountLoader<'info, T>, ProgramError> {
  70. if acc_info.owner != &T::owner() {
  71. return Err(ErrorCode::AccountNotProgramOwned.into());
  72. }
  73. Ok(AccountLoader::new(acc_info.clone()))
  74. }
  75. /// Returns a Ref to the account data structure for reading.
  76. pub fn load(&self) -> Result<Ref<T>, ProgramError> {
  77. let data = self.acc_info.try_borrow_data()?;
  78. let mut disc_bytes = [0u8; 8];
  79. disc_bytes.copy_from_slice(&data[..8]);
  80. if disc_bytes != T::discriminator() {
  81. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  82. }
  83. Ok(Ref::map(data, |data| bytemuck::from_bytes(&data[8..])))
  84. }
  85. /// Returns a `RefMut` to the account data structure for reading or writing.
  86. pub fn load_mut(&self) -> Result<RefMut<T>, ProgramError> {
  87. // AccountInfo api allows you to borrow mut even if the account isn't
  88. // writable, so add this check for a better dev experience.
  89. if !self.acc_info.is_writable {
  90. return Err(ErrorCode::AccountNotMutable.into());
  91. }
  92. let data = self.acc_info.try_borrow_mut_data()?;
  93. let mut disc_bytes = [0u8; 8];
  94. disc_bytes.copy_from_slice(&data[..8]);
  95. if disc_bytes != T::discriminator() {
  96. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  97. }
  98. Ok(RefMut::map(data, |data| {
  99. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..])
  100. }))
  101. }
  102. /// Returns a `RefMut` to the account data structure for reading or writing.
  103. /// Should only be called once, when the account is being initialized.
  104. pub fn load_init(&self) -> Result<RefMut<T>, ProgramError> {
  105. // AccountInfo api allows you to borrow mut even if the account isn't
  106. // writable, so add this check for a better dev experience.
  107. if !self.acc_info.is_writable {
  108. return Err(ErrorCode::AccountNotMutable.into());
  109. }
  110. let data = self.acc_info.try_borrow_mut_data()?;
  111. // The discriminator should be zero, since we're initializing.
  112. let mut disc_bytes = [0u8; 8];
  113. disc_bytes.copy_from_slice(&data[..8]);
  114. let discriminator = u64::from_le_bytes(disc_bytes);
  115. if discriminator != 0 {
  116. return Err(ErrorCode::AccountDiscriminatorAlreadySet.into());
  117. }
  118. Ok(RefMut::map(data, |data| {
  119. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..])
  120. }))
  121. }
  122. }
  123. impl<'info, T: ZeroCopy + Owner> Accounts<'info> for AccountLoader<'info, T> {
  124. #[inline(never)]
  125. fn try_accounts(
  126. _program_id: &Pubkey,
  127. accounts: &mut &[AccountInfo<'info>],
  128. _ix_data: &[u8],
  129. ) -> Result<Self, ProgramError> {
  130. if accounts.is_empty() {
  131. return Err(ErrorCode::AccountNotEnoughKeys.into());
  132. }
  133. let account = &accounts[0];
  134. *accounts = &accounts[1..];
  135. let l = AccountLoader::try_from(account)?;
  136. Ok(l)
  137. }
  138. }
  139. impl<'info, T: ZeroCopy + Owner> AccountsExit<'info> for AccountLoader<'info, T> {
  140. // The account *cannot* be loaded when this is called.
  141. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  142. let mut data = self.acc_info.try_borrow_mut_data()?;
  143. let dst: &mut [u8] = &mut data;
  144. let mut cursor = std::io::Cursor::new(dst);
  145. cursor.write_all(&T::discriminator()).unwrap();
  146. Ok(())
  147. }
  148. }
  149. impl<'info, T: ZeroCopy + Owner> AccountsClose<'info> for AccountLoader<'info, T> {
  150. fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
  151. crate::common::close(self.to_account_info(), sol_destination)
  152. }
  153. }
  154. impl<'info, T: ZeroCopy + Owner> ToAccountMetas for AccountLoader<'info, T> {
  155. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  156. let is_signer = is_signer.unwrap_or(self.acc_info.is_signer);
  157. let meta = match self.acc_info.is_writable {
  158. false => AccountMeta::new_readonly(*self.acc_info.key, is_signer),
  159. true => AccountMeta::new(*self.acc_info.key, is_signer),
  160. };
  161. vec![meta]
  162. }
  163. }
  164. impl<'info, T: ZeroCopy + Owner> AsRef<AccountInfo<'info>> for AccountLoader<'info, T> {
  165. fn as_ref(&self) -> &AccountInfo<'info> {
  166. &self.acc_info
  167. }
  168. }
  169. impl<'info, T: ZeroCopy + Owner> ToAccountInfos<'info> for AccountLoader<'info, T> {
  170. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  171. vec![self.acc_info.clone()]
  172. }
  173. }
  174. impl<'info, T: ZeroCopy + Owner> ToAccountInfo<'info> for AccountLoader<'info, T> {
  175. fn to_account_info(&self) -> AccountInfo<'info> {
  176. self.acc_info.clone()
  177. }
  178. }
  179. impl<'info, T: ZeroCopy + Owner> Key for AccountLoader<'info, T> {
  180. fn key(&self) -> Pubkey {
  181. *self.acc_info.key
  182. }
  183. }