account.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //! Account container that checks ownership on deserialization.
  2. use crate::error::ErrorCode;
  3. use crate::*;
  4. use solana_program::account_info::AccountInfo;
  5. use solana_program::entrypoint::ProgramResult;
  6. use solana_program::instruction::AccountMeta;
  7. use solana_program::program_error::ProgramError;
  8. use solana_program::pubkey::Pubkey;
  9. use std::collections::BTreeMap;
  10. use std::fmt;
  11. use std::ops::{Deref, DerefMut};
  12. /// Wrapper around [`AccountInfo`](crate::solana_program::account_info::AccountInfo)
  13. /// that verifies program ownership and deserializes underlying data into a Rust type.
  14. ///
  15. /// # Table of Contents
  16. /// - [Basic Functionality](#basic-functionality)
  17. /// - [Using Account with non-anchor types](#using-account-with-non-anchor-types)
  18. /// - [Out of the box wrapper types](#out-of-the-box-wrapper-types)
  19. ///
  20. /// # Basic Functionality
  21. ///
  22. /// Account checks that `Account.info.owner == T::owner()`.
  23. /// This means that the data type that Accounts wraps around (`=T`) needs to
  24. /// implement the [Owner trait](crate::Owner).
  25. /// The `#[account]` attribute implements the Owner trait for
  26. /// a struct using the `crate::ID` declared by [`declareId`](crate::declare_id)
  27. /// in the same program. It follows that Account can also be used
  28. /// with a `T` that comes from a different program.
  29. ///
  30. /// Checks:
  31. ///
  32. /// - `Account.info.owner == T::owner()`
  33. /// - `!(Account.info.owner == SystemProgram && Account.info.lamports() == 0)`
  34. ///
  35. /// # Example
  36. /// ```ignore
  37. /// use anchor_lang::prelude::*;
  38. /// use other_program::Auth;
  39. ///
  40. /// declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
  41. ///
  42. /// #[program]
  43. /// mod hello_anchor {
  44. /// use super::*;
  45. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> ProgramResult {
  46. /// if (*ctx.accounts.auth_account).authorized {
  47. /// (*ctx.accounts.my_account).data = data;
  48. /// }
  49. /// Ok(())
  50. /// }
  51. /// }
  52. ///
  53. /// #[account]
  54. /// #[derive(Default)]
  55. /// pub struct MyData {
  56. /// pub data: u64
  57. /// }
  58. ///
  59. /// #[derive(Accounts)]
  60. /// pub struct SetData<'info> {
  61. /// #[account(mut)]
  62. /// pub my_account: Account<'info, MyData> // checks that my_account.info.owner == Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS
  63. /// pub auth_account: Account<'info, Auth> // checks that auth_account.info.owner == FEZGUxNhZWpYPj9MJCrZJvUo1iF9ys34UHx52y4SzVW9
  64. /// }
  65. ///
  66. /// // In a different program
  67. ///
  68. /// ...
  69. /// declare_id!("FEZGUxNhZWpYPj9MJCrZJvUo1iF9ys34UHx52y4SzVW9");
  70. /// #[account]
  71. /// #[derive(Default)]
  72. /// pub struct Auth {
  73. /// pub authorized: bool
  74. /// }
  75. /// ...
  76. /// ```
  77. ///
  78. /// # Using Account with non-anchor programs
  79. ///
  80. /// Account can also be used with non-anchor programs. The data types from
  81. /// those programs are not annotated with `#[account]` so you have to
  82. /// - create a wrapper type around the structs you want to wrap with Account
  83. /// - implement the functions required by Account yourself
  84. /// instead of using `#[account]`. You only have to implement a fraction of the
  85. /// functions `#[account]` generates. See the example below for the code you have
  86. /// to write.
  87. ///
  88. /// The mint wrapper type that Anchor provides out of the box for the token program ([source](https://github.com/project-serum/anchor/blob/master/spl/src/token.rs))
  89. /// ```ignore
  90. /// #[derive(Clone)]
  91. /// pub struct Mint(spl_token::state::Mint);
  92. ///
  93. /// // This is necessary so we can use "anchor_spl::token::Mint::LEN"
  94. /// // because rust does not resolve "anchor_spl::token::Mint::LEN" to
  95. /// // "spl_token::state::Mint::LEN" automatically
  96. /// impl Mint {
  97. /// pub const LEN: usize = spl_token::state::Mint::LEN;
  98. /// }
  99. ///
  100. /// // You don't have to implement the "try_deserialize" function
  101. /// // from this trait. It delegates to
  102. /// // "try_deserialize_unchecked" by default which is what we want here
  103. /// // because non-anchor accounts don't have a discriminator to check
  104. /// impl anchor_lang::AccountDeserialize for Mint {
  105. /// fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self, ProgramError> {
  106. /// spl_token::state::Mint::unpack(buf).map(Mint)
  107. /// }
  108. /// }
  109. /// // AccountSerialize defaults to a no-op which is what we want here
  110. /// // because it's a foreign program, so our program does not
  111. /// // have permission to write to the foreign program's accounts anyway
  112. /// impl anchor_lang::AccountSerialize for Mint {}
  113. ///
  114. /// impl anchor_lang::Owner for Mint {
  115. /// fn owner() -> Pubkey {
  116. /// // pub use spl_token::ID is used at the top of the file
  117. /// ID
  118. /// }
  119. /// }
  120. ///
  121. /// // Implement the "std::ops::Deref" trait for better user experience
  122. /// impl Deref for Mint {
  123. /// type Target = spl_token::state::Mint;
  124. ///
  125. /// fn deref(&self) -> &Self::Target {
  126. /// &self.0
  127. /// }
  128. /// }
  129. /// ```
  130. ///
  131. /// ## Out of the box wrapper types
  132. ///
  133. /// ### Accessing BPFUpgradeableLoader Data
  134. ///
  135. /// Anchor provides wrapper types to access data stored in programs owned by the BPFUpgradeableLoader
  136. /// such as the upgrade authority. If you're interested in the data of a program account, you can use
  137. /// ```ignore
  138. /// Account<'info, BpfUpgradeableLoaderState>
  139. /// ```
  140. /// and then match on its contents inside your instruction function.
  141. ///
  142. /// Alternatively, you can use
  143. /// ```ignore
  144. /// Account<'info, ProgramData>
  145. /// ```
  146. /// to let anchor do the matching for you and return the ProgramData variant of BpfUpgradeableLoaderState.
  147. ///
  148. /// # Example
  149. /// ```ignore
  150. /// use anchor_lang::prelude::*;
  151. /// use crate::program::MyProgram;
  152. ///
  153. /// declare_id!("Cum9tTyj5HwcEiAmhgaS7Bbj4UczCwsucrCkxRECzM4e");
  154. ///
  155. /// #[program]
  156. /// pub mod my_program {
  157. /// use super::*;
  158. ///
  159. /// pub fn set_initial_admin(
  160. /// ctx: Context<SetInitialAdmin>,
  161. /// admin_key: Pubkey
  162. /// ) -> ProgramResult {
  163. /// ctx.accounts.admin_settings.admin_key = admin_key;
  164. /// Ok(())
  165. /// }
  166. ///
  167. /// pub fn set_admin(...){...}
  168. ///
  169. /// pub fn set_settings(...){...}
  170. /// }
  171. ///
  172. /// #[account]
  173. /// #[derive(Default, Debug)]
  174. /// pub struct AdminSettings {
  175. /// admin_key: Pubkey
  176. /// }
  177. ///
  178. /// #[derive(Accounts)]
  179. /// pub struct SetInitialAdmin<'info> {
  180. /// #[account(init, payer = authority, seeds = [b"admin"], bump)]
  181. /// pub admin_settings: Account<'info, AdminSettings>,
  182. /// #[account(mut)]
  183. /// pub authority: Signer<'info>,
  184. /// #[account(constraint = program.programdata_address() == Some(program_data.key()))]
  185. /// pub program: Program<'info, MyProgram>,
  186. /// #[account(constraint = program_data.upgrade_authority_address == Some(authority.key()))]
  187. /// pub program_data: Account<'info, ProgramData>,
  188. /// pub system_program: Program<'info, System>,
  189. /// }
  190. /// ```
  191. ///
  192. /// This example solves a problem you may face if your program has admin settings: How do you set the
  193. /// admin key for restricted functionality after deployment? Setting the admin key itself should
  194. /// be a restricted action but how do you restrict it without having set an admin key?
  195. /// You're stuck in a loop.
  196. /// One solution is to use the upgrade authority of the program as the initial
  197. /// (or permanent) admin key.
  198. ///
  199. /// ### SPL Types
  200. ///
  201. /// Anchor provides wrapper types to access accounts owned by the token program. Use
  202. /// ```ignore
  203. /// use anchor_spl::token::TokenAccount;
  204. ///
  205. /// #[derive(Accounts)]
  206. /// pub struct Example {
  207. /// pub my_acc: Account<'info, TokenAccount>
  208. /// }
  209. /// ```
  210. /// to access token accounts and
  211. /// ```ignore
  212. /// use anchor_spl::token::Mint;
  213. ///
  214. /// #[derive(Accounts)]
  215. /// pub struct Example {
  216. /// pub my_acc: Account<'info, Mint>
  217. /// }
  218. /// ```
  219. /// to access mint accounts.
  220. #[derive(Clone)]
  221. pub struct Account<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> {
  222. account: T,
  223. info: AccountInfo<'info>,
  224. }
  225. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone + fmt::Debug> fmt::Debug
  226. for Account<'info, T>
  227. {
  228. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  229. f.debug_struct("Account")
  230. .field("account", &self.account)
  231. .field("info", &self.info)
  232. .finish()
  233. }
  234. }
  235. impl<'a, T: AccountSerialize + AccountDeserialize + Owner + Clone> Account<'a, T> {
  236. fn new(info: AccountInfo<'a>, account: T) -> Account<'a, T> {
  237. Self { info, account }
  238. }
  239. /// Deserializes the given `info` into a `Account`.
  240. #[inline(never)]
  241. pub fn try_from(info: &AccountInfo<'a>) -> Result<Account<'a, T>, ProgramError> {
  242. if info.owner == &system_program::ID && info.lamports() == 0 {
  243. return Err(ErrorCode::AccountNotInitialized.into());
  244. }
  245. if info.owner != &T::owner() {
  246. return Err(ErrorCode::AccountOwnedByWrongProgram.into());
  247. }
  248. let mut data: &[u8] = &info.try_borrow_data()?;
  249. Ok(Account::new(info.clone(), T::try_deserialize(&mut data)?))
  250. }
  251. /// Deserializes the given `info` into a `Account` without checking
  252. /// the account discriminator. Be careful when using this and avoid it if
  253. /// possible.
  254. #[inline(never)]
  255. pub fn try_from_unchecked(info: &AccountInfo<'a>) -> Result<Account<'a, T>, ProgramError> {
  256. if info.owner == &system_program::ID && info.lamports() == 0 {
  257. return Err(ErrorCode::AccountNotInitialized.into());
  258. }
  259. if info.owner != &T::owner() {
  260. return Err(ErrorCode::AccountOwnedByWrongProgram.into());
  261. }
  262. let mut data: &[u8] = &info.try_borrow_data()?;
  263. Ok(Account::new(
  264. info.clone(),
  265. T::try_deserialize_unchecked(&mut data)?,
  266. ))
  267. }
  268. /// Reloads the account from storage. This is useful, for example, when
  269. /// observing side effects after CPI.
  270. pub fn reload(&mut self) -> ProgramResult {
  271. let mut data: &[u8] = &self.info.try_borrow_data()?;
  272. self.account = T::try_deserialize(&mut data)?;
  273. Ok(())
  274. }
  275. pub fn into_inner(self) -> T {
  276. self.account
  277. }
  278. /// Sets the inner account.
  279. ///
  280. /// Instead of this:
  281. /// ```ignore
  282. /// pub fn new_user(ctx: Context<CreateUser>, new_user:User) -> ProgramResult {
  283. /// (*ctx.accounts.user_to_create).name = new_user.name;
  284. /// (*ctx.accounts.user_to_create).age = new_user.age;
  285. /// (*ctx.accounts.user_to_create).address = new_user.address;
  286. /// }
  287. /// ```
  288. /// You can do this:
  289. /// ```ignore
  290. /// pub fn new_user(ctx: Context<CreateUser>, new_user:User) -> ProgramResult {
  291. /// ctx.accounts.user_to_create.set_inner(new_user);
  292. /// }
  293. /// ```
  294. pub fn set_inner(&mut self, inner: T) {
  295. self.account = inner;
  296. }
  297. }
  298. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> Accounts<'info>
  299. for Account<'info, T>
  300. where
  301. T: AccountSerialize + AccountDeserialize + Owner + Clone,
  302. {
  303. #[inline(never)]
  304. fn try_accounts(
  305. _program_id: &Pubkey,
  306. accounts: &mut &[AccountInfo<'info>],
  307. _ix_data: &[u8],
  308. _bumps: &mut BTreeMap<String, u8>,
  309. ) -> Result<Self, ProgramError> {
  310. if accounts.is_empty() {
  311. return Err(ErrorCode::AccountNotEnoughKeys.into());
  312. }
  313. let account = &accounts[0];
  314. *accounts = &accounts[1..];
  315. Account::try_from(account)
  316. }
  317. }
  318. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> AccountsExit<'info>
  319. for Account<'info, T>
  320. {
  321. fn exit(&self, program_id: &Pubkey) -> ProgramResult {
  322. // Only persist if the owner is the current program.
  323. if &T::owner() == program_id {
  324. let info = self.to_account_info();
  325. let mut data = info.try_borrow_mut_data()?;
  326. // Chop off the header.
  327. let dst: &mut [u8] = &mut data[8..];
  328. let mut cursor = std::io::Cursor::new(dst);
  329. self.account.try_serialize(&mut cursor)?;
  330. }
  331. Ok(())
  332. }
  333. }
  334. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> AccountsClose<'info>
  335. for Account<'info, T>
  336. {
  337. fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
  338. crate::common::close(self.to_account_info(), sol_destination)
  339. }
  340. }
  341. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> ToAccountMetas
  342. for Account<'info, T>
  343. {
  344. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  345. let is_signer = is_signer.unwrap_or(self.info.is_signer);
  346. let meta = match self.info.is_writable {
  347. false => AccountMeta::new_readonly(*self.info.key, is_signer),
  348. true => AccountMeta::new(*self.info.key, is_signer),
  349. };
  350. vec![meta]
  351. }
  352. }
  353. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> ToAccountInfos<'info>
  354. for Account<'info, T>
  355. {
  356. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  357. vec![self.info.clone()]
  358. }
  359. }
  360. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> AsRef<AccountInfo<'info>>
  361. for Account<'info, T>
  362. {
  363. fn as_ref(&self) -> &AccountInfo<'info> {
  364. &self.info
  365. }
  366. }
  367. impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> AsRef<T>
  368. for Account<'info, T>
  369. {
  370. fn as_ref(&self) -> &T {
  371. &self.account
  372. }
  373. }
  374. impl<'a, T: AccountSerialize + AccountDeserialize + Owner + Clone> Deref for Account<'a, T> {
  375. type Target = T;
  376. fn deref(&self) -> &Self::Target {
  377. &(*self).account
  378. }
  379. }
  380. impl<'a, T: AccountSerialize + AccountDeserialize + Owner + Clone> DerefMut for Account<'a, T> {
  381. fn deref_mut(&mut self) -> &mut Self::Target {
  382. #[cfg(feature = "anchor-debug")]
  383. if !self.info.is_writable {
  384. solana_program::msg!("The given Account is not mutable");
  385. panic!();
  386. }
  387. &mut self.account
  388. }
  389. }
  390. #[cfg(not(feature = "deprecated-layout"))]
  391. impl<'a, T: AccountSerialize + AccountDeserialize + Owner + Clone> Bump for Account<'a, T> {
  392. fn seed(&self) -> u8 {
  393. self.info.data.borrow()[1]
  394. }
  395. }