account.rs 13 KB

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