loader.rs 7.6 KB

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