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: Add ProgramData account #1095

Merged
Merged
Show file tree
Hide file tree
Changes from 15 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
2 changes: 2 additions & 0 deletions .github/actions/setup-solana/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ runs:
shell: bash
- run: solana-keygen new --no-bip39-passphrase
shell: bash
- run: solana config set --url localhost
shell: bash
40 changes: 40 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,46 @@ jobs:
- uses: ./.github/actions/setup-solana/
- run: cd client/example && ./run-test.sh

test-program-data:
needs: setup-anchor-cli
name: Test tests/program-data
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/setup/
- uses: ./.github/actions/setup-ts/
- uses: ./.github/actions/setup-solana/

- uses: actions/cache@v2
name: Cache Cargo registry + index
id: cache-anchor
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
./target/
key: cargo-${{ runner.os }}-anchor-${{ hashFiles('**/Cargo.lock') }}

- uses: actions/download-artifact@v2
with:
name: anchor-binary
path: ~/.cargo/bin/

- uses: actions/cache@v2
name: Cache tests/program-data target
id: cache-test-target
with:
path: tests/program-data/target
key: cargo-${{ runner.os }}-tests/program-data-${{ env.ANCHOR_VERSION }}

- run: solana-test-validator -r --quiet &
name: start validator
- run: cd tests/program-data && yarn
- run: cd tests/program-data && yarn link @project-serum/anchor
- run: cd tests/program-data && anchor build && cp program_data-keypair.json target/deploy/program_data-keypair.json && anchor deploy && anchor test --skip-deploy --skip-build

test-programs:
needs: setup-anchor-cli
name: Test ${{ matrix.node.path }}
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ incremented for features.

* lang: Add `ErrorCode::AccountNotInitialized` error to separate the situation when the account has the wrong owner from when it does not exist (#[1024](https://github.com/project-serum/anchor/pull/1024))
* lang: Called instructions now log their name by default. This can be turned off with the `no-log-ix-name` flag ([#1057](https://github.com/project-serum/anchor/pull/1057))
* lang: Add `ProgramData` AccountInfo wrapper that checks that given AccountInfo is owned by the upgradable loader and that its deserialization is the `ProgramData` variant of [UpgradeableLoaderState](https://docs.rs/solana-program/latest/solana_program/bpf_loader_upgradeable/enum.UpgradeableLoaderState.html) ([#1095](https://github.com/project-serum/anchor/pull/1095))

## [0.18.2] - 2021-11-14

Expand Down
7 changes: 4 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lang/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ borsh = "0.9"
bytemuck = "1.4.0"
solana-program = "1.8.0"
thiserror = "1.0.20"
bincode = "1.3.3"
85 changes: 85 additions & 0 deletions lang/src/bpf_upgradable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use crate::{AccountDeserialize, AccountSerialize, Owner};
use solana_program::{
bpf_loader_upgradeable::{self, UpgradeableLoaderState},
program_error::ProgramError,
pubkey::Pubkey,
};

#[derive(Clone)]
pub struct ProgramData {
armaniferrante marked this conversation as resolved.
Show resolved Hide resolved
pub slot: u64,
pub upgrade_authority_address: Option<Pubkey>,
}

impl AccountDeserialize for ProgramData {
fn try_deserialize(
buf: &mut &[u8],
) -> Result<Self, solana_program::program_error::ProgramError> {
ProgramData::try_deserialize_unchecked(buf)
}

fn try_deserialize_unchecked(
buf: &mut &[u8],
) -> Result<Self, solana_program::program_error::ProgramError> {
let program_state: bpf_loader_upgradeable::UpgradeableLoaderState =
bincode::deserialize(buf).map_err(|_| ProgramError::InvalidAccountData)?;

match program_state {
UpgradeableLoaderState::Uninitialized => {
Err(anchor_lang::error::ErrorCode::AccountNotProgramData.into())
}
UpgradeableLoaderState::Buffer {
authority_address: _,
} => Err(anchor_lang::error::ErrorCode::AccountNotProgramData.into()),
UpgradeableLoaderState::Program {
programdata_address: _,
} => Err(anchor_lang::error::ErrorCode::AccountNotProgramData.into()),
UpgradeableLoaderState::ProgramData {
slot,
upgrade_authority_address,
} => Ok(ProgramData {
slot,
upgrade_authority_address,
}),
}
}
}

impl AccountSerialize for ProgramData {
fn try_serialize<W: std::io::Write>(
&self,
_writer: &mut W,
) -> Result<(), solana_program::program_error::ProgramError> {
// no-op
Ok(())
}
}

impl Owner for ProgramData {
fn owner() -> solana_program::pubkey::Pubkey {
anchor_lang::solana_program::bpf_loader_upgradeable::ID
}
}

impl Owner for UpgradeableLoaderState {
fn owner() -> Pubkey {
anchor_lang::solana_program::bpf_loader_upgradeable::ID
}
}

impl AccountSerialize for UpgradeableLoaderState {
fn try_serialize<W: std::io::Write>(&self, _writer: &mut W) -> Result<(), ProgramError> {
// no-op
Ok(())
}
}

impl AccountDeserialize for UpgradeableLoaderState {
fn try_deserialize(buf: &mut &[u8]) -> Result<Self, ProgramError> {
UpgradeableLoaderState::try_deserialize_unchecked(buf)
}

fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self, ProgramError> {
bincode::deserialize(buf).map_err(|_| ProgramError::InvalidAccountData)
}
}
4 changes: 4 additions & 0 deletions lang/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ pub enum ErrorCode {
AccountNotSystemOwned,
#[msg("The program expected this account to be already initialized")]
AccountNotInitialized,
#[msg("The given account is not a program data account")]
AccountNotProgramData,
#[msg("The given account is not a program")]
AccountNotProgram,

// State.
#[msg("The given state account does not have the correct address")]
Expand Down
6 changes: 4 additions & 2 deletions lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ mod account;
mod account_info;
mod account_meta;
mod boxed;
mod bpf_upgradable;
mod common;
mod context;
mod cpi_account;
Expand All @@ -56,6 +57,7 @@ mod unchecked_account;
mod vec;

pub use crate::account::Account;
pub use crate::bpf_upgradable::*;
#[doc(hidden)]
#[allow(deprecated)]
pub use crate::context::CpiStateContext;
Expand Down Expand Up @@ -254,8 +256,8 @@ pub mod prelude {
access_control, account, constant, declare_id, emit, error, event, interface, program,
require, state, zero_copy, Account, AccountDeserialize, AccountLoader, AccountSerialize,
Accounts, AccountsExit, AnchorDeserialize, AnchorSerialize, Context, CpiContext, Id, Key,
Owner, Program, Signer, System, SystemAccount, Sysvar, ToAccountInfo, ToAccountInfos,
ToAccountMetas, UncheckedAccount,
Owner, Program, ProgramData, Signer, System, SystemAccount, Sysvar, ToAccountInfo,
ToAccountInfos, ToAccountMetas, UncheckedAccount,
};

#[allow(deprecated)]
Expand Down
8 changes: 3 additions & 5 deletions lang/syn/src/codegen/program/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,11 +486,9 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
.methods
.iter()
.map(|ix| {
if state.is_zero_copy {
// Easy to implement. Just need to write a test.
// Feel free to open a PR.
panic!("Trait implementations not yet implemented for zero copy state structs. Please file an issue.");
}
// Easy to implement. Just need to write a test.
// Feel free to open a PR.
assert!(!state.is_zero_copy, "Trait implementations not yet implemented for zero copy state structs. Please file an issue.");
Copy link
Contributor Author

Choose a reason for hiding this comment

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

clippy asked for this


let ix_arg_names: Vec<&syn::Ident> =
ix.args.iter().map(|arg| &arg.name).collect();
Expand Down
8 changes: 8 additions & 0 deletions lang/syn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,9 @@ impl Field {
Ty::Signer => quote! {
Signer
},
Ty::ProgramData => quote! {
ProgramData
},
Ty::SystemAccount => quote! {
SystemAccount
},
Expand Down Expand Up @@ -298,6 +301,7 @@ impl Field {
Ty::UncheckedAccount => quote! {},
Ty::Signer => quote! {},
Ty::SystemAccount => quote! {},
Ty::ProgramData => quote! {},
}
}

Expand All @@ -316,6 +320,9 @@ impl Field {
Ty::SystemAccount => quote! {
SystemAccount
},
Ty::ProgramData => quote! {
ProgramData
},
Ty::ProgramAccount(ty) => {
let ident = &ty.account_type_path;
quote! {
Expand Down Expand Up @@ -405,6 +412,7 @@ pub enum Ty {
Program(ProgramTy),
Signer,
SystemAccount,
ProgramData,
}

#[derive(Debug, PartialEq)]
Expand Down
2 changes: 2 additions & 0 deletions lang/syn/src/parser/accounts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ fn is_field_primitive(f: &syn::Field) -> ParseResult<bool> {
| "Program"
| "Signer"
| "SystemAccount"
| "ProgramData"
);
Ok(r)
}
Expand All @@ -102,6 +103,7 @@ fn parse_ty(f: &syn::Field) -> ParseResult<Ty> {
"Program" => Ty::Program(parse_program_ty(&path)?),
"Signer" => Ty::Signer,
"SystemAccount" => Ty::SystemAccount,
"ProgramData" => Ty::ProgramData,
_ => return Err(ParseError::new(f.ty.span(), "invalid account type given")),
};

Expand Down
6 changes: 6 additions & 0 deletions tests/program-data/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

armaniferrante marked this conversation as resolved.
Show resolved Hide resolved
.anchor
Copy link
Member

Choose a reason for hiding this comment

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

Can remove this file.

Copy link
Contributor Author

@paul-schaaf paul-schaaf Dec 5, 2021

Choose a reason for hiding this comment

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

I removed it but added it back so it can gitignore yarn.lock in the test repo.

.DS_Store
target
**/*.rs.bk
node_modules
12 changes: 12 additions & 0 deletions tests/program-data/Anchor.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[programs.localnet]
program_data = "Cum9tTyj5HwcEiAmhgaS7Bbj4UczCwsucrCkxRECzM4e"

[registry]
url = "https://anchor.projectserum.com"

[provider]
cluster = "localnet"
wallet = "~/.config/solana/id.json"

[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
4 changes: 4 additions & 0 deletions tests/program-data/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[workspace]
members = [
"programs/*"
]
12 changes: 12 additions & 0 deletions tests/program-data/migrations/deploy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.

const anchor = require("@project-serum/anchor");

module.exports = async function (provider) {
// Configure client to use the provider.
anchor.setProvider(provider);

// Add your deploy script here.
}
12 changes: 12 additions & 0 deletions tests/program-data/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"dependencies": {
"@project-serum/anchor": "^0.18.2"
},
"devDependencies": {
"chai": "^4.3.4",
"mocha": "^9.0.3",
"ts-mocha": "^8.0.0",
"@types/mocha": "^9.0.0",
"typescript": "^4.3.5"
}
}
1 change: 1 addition & 0 deletions tests/program-data/program_data-keypair.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[114,99,192,17,48,208,90,184,231,46,220,91,47,115,132,253,218,163,228,101,8,121,220,138,41,140,176,127,254,91,51,28,176,244,174,182,223,57,57,125,117,201,31,213,9,39,207,212,100,173,88,252,61,235,89,156,53,86,4,90,16,251,191,219]
Copy link
Contributor Author

Choose a reason for hiding this comment

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

this exists so it can be copied into the target/deploy folder. see the github actions job test-program-data

18 changes: 18 additions & 0 deletions tests/program-data/programs/program-data/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "program-data"
version = "0.1.0"
description = "Created with Anchor"
edition = "2018"

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

[features]
no-entrypoint = []
no-idl = []
cpi = ["no-entrypoint"]
default = []

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

declare_id!("Cum9tTyj5HwcEiAmhgaS7Bbj4UczCwsucrCkxRECzM4e");

// TODO: Once anchor can deserialize program data, update this test.
Copy link
Member

Choose a reason for hiding this comment

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

Is this comment still relevant?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, we should have a test that checks that you can uses settings, program, program_data, and the upgrade authority together to set data. this use case was what got these issues created.

eventually we should have a test that can check the following

#[derive(Accounts)]
#[instruction(admin_data: u64)]
pub struct SetAdmin {
  upgrade_authority_address: Signer<'info>,
  #[account(has_one = programdata_address)
  program: Program<'info, <YOUR_PROGRAM>,
  #[account(has_opt = upgrade_authority_address)]
  programdata_address: ProgramData<'info>
}

(pending has_opt feature approval)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

program data in that comment was referring to the data of the Program (i.e. programdata_address), not the data of ProgramData.

// Add constraint that program.program_data_address == program_data.key()

#[program]
pub mod program_data {
use super::*;
pub fn set_admin_settings(ctx: Context<SetAdminSettings>, admin_data: u64) -> ProgramResult {
ctx.accounts.settings.admin_data = admin_data;
Ok(())
}
}

#[account]
#[derive(Default, Debug)]
pub struct Settings {
admin_data: u64
}

#[derive(Accounts)]
pub struct SetAdminSettings<'info> {
#[account(init, payer = authority)]
pub settings: Account<'info, Settings>,
#[account(mut)]
pub authority: Signer<'info>,
#[account(constraint = program_data.upgrade_authority_address == Some(authority.key()))]
pub program_data: Account<'info, ProgramData>,
pub system_program: Program<'info, System>
}
Loading