loader.rs 7.1 KB

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