Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lang: Fix account try_from usage #2770

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,9 +393,10 @@ pub mod prelude {
context::Context, context::CpiContext, declare_id, emit, err, error, event, program,
require, require_eq, require_gt, require_gte, require_keys_eq, require_keys_neq,
require_neq, solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source,
system_program::System, zero_copy, AccountDeserialize, AccountSerialize, Accounts,
AccountsClose, AccountsExit, AnchorDeserialize, AnchorSerialize, Id, InitSpace, Key,
Lamports, Owner, ProgramData, Result, Space, ToAccountInfo, ToAccountInfos, ToAccountMetas,
system_program::System, try_from, zero_copy, AccountDeserialize, AccountSerialize,
Accounts, AccountsClose, AccountsExit, AnchorDeserialize, AnchorSerialize, Id, InitSpace,
Key, Lamports, Owner, ProgramData, Result, Space, ToAccountInfo, ToAccountInfos,
ToAccountMetas,
};
pub use anchor_attribute_error::*;
pub use borsh;
Expand Down Expand Up @@ -727,3 +728,10 @@ macro_rules! source {
}
};
}

#[macro_export]
macro_rules! try_from {
($ty: ty, $acc: expr) => {
<$ty>::try_from(unsafe { core::mem::transmute::<_, &AccountInfo<'_>>($acc.as_ref()) })
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is not correct to transmute AccountInfo<'a> into a shorter lifetime because it contains Rc<RefCell<&'a mut>>, making it invariant, the issue is explained in https://doc.rust-lang.org/nomicon/subtyping.html#variance . Basically, somewhere else in the code might still hold the reference to longer lifetime 'a, when you transmute it to a shorter lifetime 'b and write to it, you make a use-after-free bug.

I wonder why use RefCell holding a mutable reference at all? I did not dig into anchor code yet so I don't know why it is needed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is not correct to transmute AccountInfo<'a> into a shorter lifetime because it contains Rc<RefCell<&'a mut>>, making it invariant, the issue is explained in https://doc.rust-lang.org/nomicon/subtyping.html#variance . Basically, somewhere else in the code might still hold the reference to longer lifetime 'a, when you transmute it to a shorter lifetime 'b and write to it, you make a use-after-free bug.

Generally speaking, what you said is correct, but I don't think it applies here because the main reason for using this macro is to first declare an account as an UncheckedAccount, then convert it to a checked type, e.g. Account. When you do this, you're declaring you'll let Anchor handle the serialization of the data to the account (in the exit routine), meaning it would be incorrect to write to the raw account data yourself independent of the "use-after-free" bug you mentioned.

That being said, this PR is stale and won't get merged. #3340 helps this specific issue too, but it still requires declaring the lifetimes of the accounts struct and the context are the same (e.g. Context<'info, MyIx<'info>>). We can improve this further by handling the annotations automatically during macro generation.

I wonder why use RefCell holding a mutable reference at all? I did not dig into anchor code yet so I don't know why it is needed.

That part is not coming from Anchor code, as AccountInfo is defined in solana-program. I think mistakes were made in the initial days though, that type doesn't make much sense.

};
}
1 change: 1 addition & 0 deletions tests/misc/Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ misc = "3TEqcc8xhrhdspwbvoamUJe2borm4Nr72JxL66k6rgrh"
misc_optional = "FNqz6pqLAwvMSds2FYjR4nKV3moVpPNtvkfGFrqLKrgG"
overflow_checks = "overf1owChecks11111111111111111111111111111"
remaining_accounts = "RemainingAccounts11111111111111111111111111"
try_from = "TryFrom111111111111111111111111111111111111"

[workspace]
exclude = ["programs/shared"]
19 changes: 19 additions & 0 deletions tests/misc/programs/try-from/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "try-from"
version = "0.1.0"
description = "Created with Anchor"
edition = "2021"

[lib]
crate-type = ["cdylib", "lib"]
name = "try_from"

[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []

[dependencies]
anchor-lang = { path = "../../../../lang" }
2 changes: 2 additions & 0 deletions tests/misc/programs/try-from/Xargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.bpfel-unknown-unknown.dependencies.std]
features = []
40 changes: 40 additions & 0 deletions tests/misc/programs/try-from/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use anchor_lang::prelude::*;

declare_id!("TryFrom111111111111111111111111111111111111");

#[program]
pub mod try_from {
use super::*;

pub fn init(ctx: Context<Init>, field: u8) -> Result<()> {
ctx.accounts.my_account.field = field;
Ok(())
}

pub fn try_from(ctx: Context<TryFrom>, field: u8) -> Result<()> {
let my_account = try_from!(Account::<MyAccount>, ctx.accounts.my_account)?;
msg!("Field: {}", my_account.field);
require_eq!(my_account.field, field);

Ok(())
}
}

#[derive(Accounts)]
pub struct Init<'info> {
#[account(init, payer = payer, space = 8 + 1)]
pub my_account: Account<'info, MyAccount>,
#[account(mut)]
pub payer: Signer<'info>,
pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct TryFrom<'info> {
pub my_account: UncheckedAccount<'info>,
}

#[account]
pub struct MyAccount {
pub field: u8,
}
2 changes: 2 additions & 0 deletions tests/misc/tests/try-from/Test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[scripts]
test = "yarn run ts-mocha -t 1000000 ./tests/try-from/*.ts"
28 changes: 28 additions & 0 deletions tests/misc/tests/try-from/try-from.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as anchor from "@coral-xyz/anchor";

import { TryFrom, IDL } from "../../target/types/try_from";

describe(IDL.name, () => {
anchor.setProvider(anchor.AnchorProvider.env());

const program = anchor.workspace.TryFrom as anchor.Program<TryFrom>;

it("Can use `try_from`", async () => {
const myAccountKp = anchor.web3.Keypair.generate();
const FIELD = 5;
await program.methods
.init(FIELD)
.accounts({
myAccount: myAccountKp.publicKey,
})
.signers([myAccountKp])
.rpc();

await program.methods
.tryFrom(FIELD)
.accounts({
myAccount: myAccountKp.publicKey,
})
.rpc();
});
});
Loading