loader.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. use crate::bpf_writer::BpfWriter;
  2. use crate::error::{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(Error::from(ErrorCode::AccountOwnedByWrongProgram)
  59. .with_pubkeys((*acc_info.owner, *program_id)));
  60. }
  61. let data: &[u8] = &acc_info.try_borrow_data()?;
  62. if data.len() < T::discriminator().len() {
  63. return Err(ErrorCode::AccountDiscriminatorNotFound.into());
  64. }
  65. // Discriminator must match.
  66. let disc_bytes = array_ref![data, 0, 8];
  67. if disc_bytes != &T::discriminator() {
  68. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  69. }
  70. Ok(Loader::new(acc_info.clone()))
  71. }
  72. /// Constructs a new `Loader` from an uninitialized account.
  73. #[allow(deprecated)]
  74. #[inline(never)]
  75. pub fn try_from_unchecked(
  76. program_id: &Pubkey,
  77. acc_info: &AccountInfo<'info>,
  78. ) -> Result<Loader<'info, T>> {
  79. if acc_info.owner != program_id {
  80. return Err(Error::from(ErrorCode::AccountOwnedByWrongProgram)
  81. .with_pubkeys((*acc_info.owner, *program_id)));
  82. }
  83. Ok(Loader::new(acc_info.clone()))
  84. }
  85. /// Returns a Ref to the account data structure for reading.
  86. #[allow(deprecated)]
  87. pub fn load(&self) -> Result<Ref<T>> {
  88. let data = self.acc_info.try_borrow_data()?;
  89. if data.len() < T::discriminator().len() {
  90. return Err(ErrorCode::AccountDiscriminatorNotFound.into());
  91. }
  92. let disc_bytes = array_ref![data, 0, 8];
  93. if disc_bytes != &T::discriminator() {
  94. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  95. }
  96. Ok(Ref::map(data, |data| bytemuck::from_bytes(&data[8..])))
  97. }
  98. /// Returns a `RefMut` to the account data structure for reading or writing.
  99. #[allow(deprecated)]
  100. pub fn load_mut(&self) -> Result<RefMut<T>> {
  101. // AccountInfo api allows you to borrow mut even if the account isn't
  102. // writable, so add this check for a better dev experience.
  103. if !self.acc_info.is_writable {
  104. return Err(ErrorCode::AccountNotMutable.into());
  105. }
  106. let data = self.acc_info.try_borrow_mut_data()?;
  107. if data.len() < T::discriminator().len() {
  108. return Err(ErrorCode::AccountDiscriminatorNotFound.into());
  109. }
  110. let disc_bytes = array_ref![data, 0, 8];
  111. if disc_bytes != &T::discriminator() {
  112. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  113. }
  114. Ok(RefMut::map(data, |data| {
  115. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..])
  116. }))
  117. }
  118. /// Returns a `RefMut` to the account data structure for reading or writing.
  119. /// Should only be called once, when the account is being initialized.
  120. #[allow(deprecated)]
  121. pub fn load_init(&self) -> Result<RefMut<T>> {
  122. // AccountInfo api allows you to borrow mut even if the account isn't
  123. // writable, so add this check for a better dev experience.
  124. if !self.acc_info.is_writable {
  125. return Err(ErrorCode::AccountNotMutable.into());
  126. }
  127. let data = self.acc_info.try_borrow_mut_data()?;
  128. // The discriminator should be zero, since we're initializing.
  129. let mut disc_bytes = [0u8; 8];
  130. disc_bytes.copy_from_slice(&data[..8]);
  131. let discriminator = u64::from_le_bytes(disc_bytes);
  132. if discriminator != 0 {
  133. return Err(ErrorCode::AccountDiscriminatorAlreadySet.into());
  134. }
  135. Ok(RefMut::map(data, |data| {
  136. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..])
  137. }))
  138. }
  139. }
  140. #[allow(deprecated)]
  141. impl<'info, T: ZeroCopy> Accounts<'info> for Loader<'info, T> {
  142. #[inline(never)]
  143. fn try_accounts(
  144. program_id: &Pubkey,
  145. accounts: &mut &[AccountInfo<'info>],
  146. _ix_data: &[u8],
  147. _bumps: &mut BTreeMap<String, u8>,
  148. ) -> Result<Self> {
  149. if accounts.is_empty() {
  150. return Err(ErrorCode::AccountNotEnoughKeys.into());
  151. }
  152. let account = &accounts[0];
  153. *accounts = &accounts[1..];
  154. let l = Loader::try_from(program_id, account)?;
  155. Ok(l)
  156. }
  157. }
  158. #[allow(deprecated)]
  159. impl<'info, T: ZeroCopy> AccountsExit<'info> for Loader<'info, T> {
  160. // The account *cannot* be loaded when this is called.
  161. fn exit(&self, _program_id: &Pubkey) -> Result<()> {
  162. let mut data = self.acc_info.try_borrow_mut_data()?;
  163. let dst: &mut [u8] = &mut data;
  164. let mut writer = BpfWriter::new(dst);
  165. writer.write_all(&T::discriminator()).unwrap();
  166. Ok(())
  167. }
  168. }
  169. /// This function is for INTERNAL USE ONLY.
  170. /// Do NOT use this function in a program.
  171. /// Manual closing of `Loader<'info, T>` types is NOT supported.
  172. ///
  173. /// Details: Using `close` with `Loader<'info, T>` is not safe because
  174. /// it requires the `mut` constraint but for that type the constraint
  175. /// overwrites the "closed account" discriminator at the end of the instruction.
  176. #[allow(deprecated)]
  177. impl<'info, T: ZeroCopy> AccountsClose<'info> for Loader<'info, T> {
  178. fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()> {
  179. crate::common::close(self.to_account_info(), sol_destination)
  180. }
  181. }
  182. #[allow(deprecated)]
  183. impl<'info, T: ZeroCopy> ToAccountMetas for Loader<'info, T> {
  184. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  185. let is_signer = is_signer.unwrap_or(self.acc_info.is_signer);
  186. let meta = match self.acc_info.is_writable {
  187. false => AccountMeta::new_readonly(*self.acc_info.key, is_signer),
  188. true => AccountMeta::new(*self.acc_info.key, is_signer),
  189. };
  190. vec![meta]
  191. }
  192. }
  193. #[allow(deprecated)]
  194. impl<'info, T: ZeroCopy> AsRef<AccountInfo<'info>> for Loader<'info, T> {
  195. fn as_ref(&self) -> &AccountInfo<'info> {
  196. &self.acc_info
  197. }
  198. }
  199. #[allow(deprecated)]
  200. impl<'info, T: ZeroCopy> ToAccountInfos<'info> for Loader<'info, T> {
  201. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  202. vec![self.acc_info.clone()]
  203. }
  204. }
  205. #[allow(deprecated)]
  206. impl<'info, T: ZeroCopy> Key for Loader<'info, T> {
  207. fn key(&self) -> Pubkey {
  208. *self.acc_info.key
  209. }
  210. }