repo_id
stringclasses 279
values | file_path
stringlengths 43
179
| content
stringlengths 1
4.18M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/verify_signer.rs
|
use account_compression::{
utils::{check_discrimininator::check_discriminator, constants::CPI_AUTHORITY_PDA_SEED},
AddressMerkleTreeAccount, StateMerkleTreeAccount,
};
use anchor_lang::prelude::*;
use light_concurrent_merkle_tree::zero_copy::ConcurrentMerkleTreeZeroCopy;
use light_hasher::Poseidon;
use light_heap::{bench_sbf_end, bench_sbf_start};
use light_macros::heap_neutral;
use std::mem;
use crate::{
errors::SystemProgramError, sdk::compressed_account::PackedCompressedAccountWithMerkleContext,
OutputCompressedAccountWithPackedContext,
};
/// Checks:
/// 1. Invoking program is signer (cpi_signer_check)
/// 2. Input compressed accounts with data are owned by the invoking program
/// (input_compressed_accounts_signer_check)
/// 3. Output compressed accounts with data are owned by the invoking program
/// (output_compressed_accounts_write_access_check)
pub fn cpi_signer_checks(
invoking_programid: &Pubkey,
authority: &Pubkey,
input_compressed_accounts_with_merkle_context: &[PackedCompressedAccountWithMerkleContext],
output_compressed_accounts: &[OutputCompressedAccountWithPackedContext],
) -> Result<()> {
bench_sbf_start!("cpda_cpi_signer_checks");
cpi_signer_check(invoking_programid, authority)?;
bench_sbf_end!("cpda_cpi_signer_checks");
bench_sbf_start!("cpd_input_checks");
input_compressed_accounts_signer_check(
input_compressed_accounts_with_merkle_context,
invoking_programid,
)?;
bench_sbf_end!("cpd_input_checks");
bench_sbf_start!("cpda_cpi_write_checks");
output_compressed_accounts_write_access_check(output_compressed_accounts, invoking_programid)?;
bench_sbf_end!("cpda_cpi_write_checks");
Ok(())
}
/// Cpi signer check, validates that the provided invoking program
/// is the actual invoking program.
#[heap_neutral]
pub fn cpi_signer_check(invoking_program: &Pubkey, authority: &Pubkey) -> Result<()> {
let seeds = [CPI_AUTHORITY_PDA_SEED];
let derived_signer = Pubkey::try_find_program_address(&seeds, invoking_program)
.ok_or(ProgramError::InvalidSeeds)?
.0;
if derived_signer != *authority {
msg!(
"Cpi signer check failed. Derived cpi signer {} != authority {}",
derived_signer,
authority
);
return err!(SystemProgramError::CpiSignerCheckFailed);
}
Ok(())
}
/// Checks that the invoking program owns all input compressed accounts.
pub fn input_compressed_accounts_signer_check(
input_compressed_accounts_with_merkle_context: &[PackedCompressedAccountWithMerkleContext],
invoking_program_id: &Pubkey,
) -> Result<()> {
input_compressed_accounts_with_merkle_context
.iter()
.try_for_each(
|compressed_account_with_context: &PackedCompressedAccountWithMerkleContext| {
let invoking_program_id = invoking_program_id.key();
if invoking_program_id == compressed_account_with_context.compressed_account.owner {
Ok(())
} else {
msg!(
"Input signer check failed. Program cannot invalidate an account it doesn't own. Owner {} != invoking_program_id {}",
compressed_account_with_context.compressed_account.owner,
invoking_program_id
);
err!(SystemProgramError::SignerCheckFailed)
}
},
)
}
/// Write access check for output compressed accounts.
/// - Only program-owned output accounts can hold data.
/// - Every output account that holds data has to be owned by the
/// invoking_program.
/// - outputs without data can be owned by any pubkey.
#[inline(never)]
pub fn output_compressed_accounts_write_access_check(
output_compressed_accounts: &[OutputCompressedAccountWithPackedContext],
invoking_program_id: &Pubkey,
) -> Result<()> {
for compressed_account in output_compressed_accounts.iter() {
if compressed_account.compressed_account.data.is_some()
&& compressed_account.compressed_account.owner != invoking_program_id.key()
{
msg!(
"Signer/Program cannot write into an account it doesn't own. Write access check failed compressed account owner {} != invoking_program_id {}",
compressed_account.compressed_account.owner,
invoking_program_id.key()
);
msg!("compressed_account: {:?}", compressed_account);
return err!(SystemProgramError::WriteAccessCheckFailed);
}
if compressed_account.compressed_account.data.is_none()
&& compressed_account.compressed_account.owner == invoking_program_id.key()
{
msg!("For program owned compressed accounts the data field needs to be defined.");
msg!("compressed_account: {:?}", compressed_account);
return err!(SystemProgramError::DataFieldUndefined);
}
}
Ok(())
}
pub fn check_program_owner_state_merkle_tree<'a, 'b: 'a>(
merkle_tree_acc_info: &'b AccountInfo<'a>,
invoking_program: &Option<Pubkey>,
) -> Result<(u32, Option<u64>, u64)> {
let (seq, next_index) = {
let merkle_tree = merkle_tree_acc_info.try_borrow_data()?;
check_discriminator::<StateMerkleTreeAccount>(&merkle_tree).map_err(ProgramError::from)?;
let merkle_tree = ConcurrentMerkleTreeZeroCopy::<Poseidon, 26>::from_bytes_zero_copy(
&merkle_tree[8 + mem::size_of::<StateMerkleTreeAccount>()..],
)
.map_err(ProgramError::from)?;
let seq = merkle_tree.sequence_number() as u64 + 1;
let next_index: u32 = merkle_tree.next_index().try_into().unwrap();
(seq, next_index)
};
let merkle_tree =
AccountLoader::<StateMerkleTreeAccount>::try_from(merkle_tree_acc_info).unwrap();
let merkle_tree_unpacked = merkle_tree.load()?;
let network_fee = if merkle_tree_unpacked.metadata.rollover_metadata.network_fee != 0 {
Some(merkle_tree_unpacked.metadata.rollover_metadata.network_fee)
} else {
None
};
if merkle_tree_unpacked.metadata.access_metadata.program_owner != Pubkey::default() {
if let Some(invoking_program) = invoking_program {
if *invoking_program == merkle_tree_unpacked.metadata.access_metadata.program_owner {
return Ok((next_index, network_fee, seq));
}
}
msg!(
"invoking_program.key() {:?} == merkle_tree_unpacked.program_owner {:?}",
invoking_program,
merkle_tree_unpacked.metadata.access_metadata.program_owner
);
return Err(SystemProgramError::InvalidMerkleTreeOwner.into());
}
Ok((next_index, network_fee, seq))
}
pub fn check_program_owner_address_merkle_tree<'a, 'b: 'a>(
merkle_tree_acc_info: &'b AccountInfo<'a>,
invoking_program: &Option<Pubkey>,
) -> Result<Option<u64>> {
let merkle_tree =
AccountLoader::<AddressMerkleTreeAccount>::try_from(merkle_tree_acc_info).unwrap();
let merkle_tree_unpacked = merkle_tree.load()?;
let network_fee = if merkle_tree_unpacked.metadata.rollover_metadata.network_fee != 0 {
Some(merkle_tree_unpacked.metadata.rollover_metadata.network_fee)
} else {
None
};
if merkle_tree_unpacked.metadata.access_metadata.program_owner != Pubkey::default() {
if let Some(invoking_program) = invoking_program {
if *invoking_program == merkle_tree_unpacked.metadata.access_metadata.program_owner {
msg!(
"invoking_program.key() {:?} == merkle_tree_unpacked.program_owner {:?}",
invoking_program,
merkle_tree_unpacked.metadata.access_metadata.program_owner
);
return Ok(network_fee);
}
}
msg!(
"invoking_program.key() {:?} == merkle_tree_unpacked.program_owner {:?}",
invoking_program,
merkle_tree_unpacked.metadata.access_metadata.program_owner
);
err!(SystemProgramError::InvalidMerkleTreeOwner)
} else {
Ok(network_fee)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::sdk::compressed_account::{CompressedAccount, CompressedAccountData};
#[test]
fn test_cpi_signer_check() {
for _ in 0..1000 {
let seeds = [CPI_AUTHORITY_PDA_SEED];
let invoking_program = Pubkey::new_unique();
let (derived_signer, _) = Pubkey::find_program_address(&seeds[..], &invoking_program);
assert_eq!(cpi_signer_check(&invoking_program, &derived_signer), Ok(()));
let authority = Pubkey::new_unique();
let invoking_program = Pubkey::new_unique();
assert!(
cpi_signer_check(&invoking_program, &authority)
== Err(ProgramError::InvalidSeeds.into())
|| cpi_signer_check(&invoking_program, &authority)
== Err(SystemProgramError::CpiSignerCheckFailed.into())
);
}
}
#[test]
fn test_input_compressed_accounts_signer_check() {
let authority = Pubkey::new_unique();
let mut compressed_account_with_context = PackedCompressedAccountWithMerkleContext {
compressed_account: CompressedAccount {
owner: authority,
..CompressedAccount::default()
},
..PackedCompressedAccountWithMerkleContext::default()
};
assert_eq!(
input_compressed_accounts_signer_check(
&[compressed_account_with_context.clone()],
&authority
),
Ok(())
);
compressed_account_with_context.compressed_account.owner = Pubkey::new_unique();
assert_eq!(
input_compressed_accounts_signer_check(&[compressed_account_with_context], &authority),
Err(SystemProgramError::SignerCheckFailed.into())
);
}
#[test]
fn test_output_compressed_accounts_write_access_check() {
let authority = Pubkey::new_unique();
let compressed_account = CompressedAccount {
owner: authority,
data: Some(CompressedAccountData::default()),
..CompressedAccount::default()
};
let output_compressed_account = OutputCompressedAccountWithPackedContext {
compressed_account,
..OutputCompressedAccountWithPackedContext::default()
};
assert_eq!(
output_compressed_accounts_write_access_check(&[output_compressed_account], &authority),
Ok(())
);
// Invalid program owner but no data should succeed
let compressed_account = CompressedAccount {
owner: Pubkey::new_unique(),
..CompressedAccount::default()
};
let mut output_compressed_account = OutputCompressedAccountWithPackedContext {
compressed_account,
..OutputCompressedAccountWithPackedContext::default()
};
assert_eq!(
output_compressed_accounts_write_access_check(
&[output_compressed_account.clone()],
&authority
),
Ok(())
);
// Invalid program owner and data should fail
output_compressed_account.compressed_account.data = Some(CompressedAccountData::default());
assert_eq!(
output_compressed_accounts_write_access_check(&[output_compressed_account], &authority),
Err(SystemProgramError::WriteAccessCheckFailed.into())
);
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/mod.rs
|
pub mod instruction;
pub use instruction::*;
pub mod account;
pub mod initialize;
pub mod process_cpi_context;
pub mod processor;
pub mod verify_signer;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/account.rs
|
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
use crate::InstructionDataInvokeCpi;
/// Collects instruction data without executing a compressed transaction.
/// Signer checks are performed on instruction data.
/// Collected instruction data is combined with the instruction data of the executing cpi,
/// and executed as a single transaction.
/// This enables to use input compressed accounts that are owned by multiple programs,
/// with one zero-knowledge proof.
#[aligned_sized(anchor)]
#[derive(Debug, PartialEq, Default)]
#[account]
pub struct CpiContextAccount {
pub fee_payer: Pubkey,
pub associated_merkle_tree: Pubkey,
pub context: Vec<InstructionDataInvokeCpi>,
}
impl CpiContextAccount {
pub fn init(&mut self, associated_merkle_tree: Pubkey) {
self.associated_merkle_tree = associated_merkle_tree;
self.context = Vec::new();
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/instruction.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::{
prelude::*, solana_program::pubkey::Pubkey, system_program::System, AnchorDeserialize,
AnchorSerialize,
};
use super::account::CpiContextAccount;
use crate::{
invoke::{processor::CompressedProof, sol_compression::SOL_POOL_PDA_SEED},
sdk::{
accounts::{InvokeAccounts, SignerAccounts},
compressed_account::PackedCompressedAccountWithMerkleContext,
CompressedCpiContext,
},
NewAddressParamsPacked, OutputCompressedAccountWithPackedContext,
};
#[derive(Accounts)]
pub struct InvokeCpiInstruction<'info> {
/// Fee payer needs to be mutable to pay rollover and protocol fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
/// CHECK:
#[account(
seeds = [&crate::ID.to_bytes()], bump, seeds::program = &account_compression::ID,
)]
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: checked in emit_event.rs.
pub noop_program: UncheckedAccount<'info>,
/// CHECK:
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub account_compression_authority: UncheckedAccount<'info>,
/// CHECK:
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: checked in cpi_signer_check.
pub invoking_program: UncheckedAccount<'info>,
#[account(
mut,
seeds = [SOL_POOL_PDA_SEED], bump
)]
pub sol_pool_pda: Option<AccountInfo<'info>>,
#[account(mut)]
pub decompression_recipient: Option<AccountInfo<'info>>,
pub system_program: Program<'info, System>,
#[account(mut)]
pub cpi_context_account: Option<Account<'info, CpiContextAccount>>,
}
impl<'info> SignerAccounts<'info> for InvokeCpiInstruction<'info> {
fn get_fee_payer(&self) -> &Signer<'info> {
&self.fee_payer
}
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
}
impl<'info> InvokeAccounts<'info> for InvokeCpiInstruction<'info> {
fn get_registered_program_pda(&self) -> &AccountInfo<'info> {
&self.registered_program_pda
}
fn get_noop_program(&self) -> &UncheckedAccount<'info> {
&self.noop_program
}
fn get_account_compression_authority(&self) -> &UncheckedAccount<'info> {
&self.account_compression_authority
}
fn get_account_compression_program(&self) -> &Program<'info, AccountCompression> {
&self.account_compression_program
}
fn get_sol_pool_pda(&self) -> Option<&AccountInfo<'info>> {
self.sol_pool_pda.as_ref()
}
fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>> {
self.decompression_recipient.as_ref()
}
fn get_system_program(&self) -> &Program<'info, System> {
&self.system_program
}
}
#[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct InstructionDataInvokeCpi {
pub proof: Option<CompressedProof>,
pub new_address_params: Vec<NewAddressParamsPacked>,
pub input_compressed_accounts_with_merkle_context:
Vec<PackedCompressedAccountWithMerkleContext>,
pub output_compressed_accounts: Vec<OutputCompressedAccountWithPackedContext>,
pub relay_fee: Option<u64>,
pub compress_or_decompress_lamports: Option<u64>,
pub is_compress: bool,
pub cpi_context: Option<CompressedCpiContext>,
}
impl InstructionDataInvokeCpi {
pub fn combine(&mut self, other: &[InstructionDataInvokeCpi]) {
for other in other {
self.new_address_params
.extend_from_slice(&other.new_address_params);
self.input_compressed_accounts_with_merkle_context
.extend_from_slice(&other.input_compressed_accounts_with_merkle_context);
self.output_compressed_accounts
.extend_from_slice(&other.output_compressed_accounts);
}
}
}
#[cfg(test)]
mod tests {
use std::vec;
use crate::{
invoke::processor::CompressedProof,
sdk::compressed_account::PackedCompressedAccountWithMerkleContext,
InstructionDataInvokeCpi, NewAddressParamsPacked, OutputCompressedAccountWithPackedContext,
};
// test combine instruction data transfer
#[test]
fn test_combine_instruction_data_transfer() {
let mut instruction_data_transfer = InstructionDataInvokeCpi {
proof: Some(CompressedProof {
a: [0; 32],
b: [0; 64],
c: [0; 32],
}),
new_address_params: vec![NewAddressParamsPacked::default()],
input_compressed_accounts_with_merkle_context: vec![
PackedCompressedAccountWithMerkleContext::default(),
],
output_compressed_accounts: vec![OutputCompressedAccountWithPackedContext::default()],
relay_fee: Some(1),
compress_or_decompress_lamports: Some(1),
is_compress: true,
cpi_context: None,
};
let other = InstructionDataInvokeCpi {
proof: Some(CompressedProof {
a: [0; 32],
b: [0; 64],
c: [0; 32],
}),
input_compressed_accounts_with_merkle_context: vec![
PackedCompressedAccountWithMerkleContext::default(),
],
output_compressed_accounts: vec![OutputCompressedAccountWithPackedContext::default()],
relay_fee: Some(1),
compress_or_decompress_lamports: Some(1),
is_compress: true,
new_address_params: vec![NewAddressParamsPacked::default()],
cpi_context: None,
};
instruction_data_transfer.combine(&[other]);
assert_eq!(instruction_data_transfer.new_address_params.len(), 2);
assert_eq!(
instruction_data_transfer
.input_compressed_accounts_with_merkle_context
.len(),
2
);
assert_eq!(
instruction_data_transfer.output_compressed_accounts.len(),
2
);
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/Cargo.toml
|
[package]
name = "light-registry"
version = "1.2.0"
description = "Light core protocol logic"
repository = "https://github.com/Lightprotocol/light-protocol"
license = "Apache-2.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "light_registry"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
custom-heap = ["light-heap"]
mem-profiling = []
default = ["custom-heap", "mem-profiling"]
test-sbf = []
bench-sbf = []
sdk = []
[dependencies]
aligned-sized = { version = "1.1.0", path = "../../macros/aligned-sized" }
anchor-lang = { workspace = true , features = ["init-if-needed"]}
anchor-spl = { workspace = true }
bytemuck = "1.17"
light-hasher = { version = "1.1.0", path = "../../merkle-tree/hasher" }
light-heap = { version = "1.1.0", path = "../../heap", optional = true }
account-compression = { workspace = true }
light-system-program = { version = "1.2.0", path = "../system", features = ["cpi"] }
light-utils = { version = "1.1.0", path = "../../utils" }
num-bigint = "0.4.5"
num-traits = "0.2.19"
solana-security-txt = "1.1.0"
[target.'cfg(not(target_os = "solana"))'.dependencies]
solana-sdk = { workspace = true }
[dev-dependencies]
solana-program-test = { workspace = true }
tokio = { workspace = true }
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/constants.rs
|
use anchor_lang::prelude::*;
#[constant]
pub const FORESTER_SEED: &[u8] = b"forester";
#[constant]
pub const FORESTER_EPOCH_SEED: &[u8] = b"forester_epoch";
#[constant]
pub const PROTOCOL_CONFIG_PDA_SEED: &[u8] = b"authority";
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/sdk.rs
|
#![cfg(not(target_os = "solana"))]
use crate::{
protocol_config::state::ProtocolConfig,
utils::{
get_cpi_authority_pda, get_epoch_pda_address, get_forester_epoch_pda_from_authority,
get_forester_epoch_pda_from_derivation, get_forester_pda, get_protocol_config_pda_address,
},
ForesterConfig,
};
use account_compression::{self, ID};
use anchor_lang::{system_program, InstructionData, ToAccountMetas};
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
};
pub fn create_initialize_group_authority_instruction(
signer_pubkey: Pubkey,
group_accounts: Pubkey,
seed_pubkey: Pubkey,
authority: Pubkey,
) -> Instruction {
let instruction_data = account_compression::instruction::InitializeGroupAuthority { authority };
Instruction {
program_id: ID,
accounts: vec![
AccountMeta::new(signer_pubkey, true),
AccountMeta::new(seed_pubkey, true),
AccountMeta::new(group_accounts, false),
AccountMeta::new_readonly(system_program::ID, false),
],
data: instruction_data.data(),
}
}
pub fn create_update_protocol_config_instruction(
signer_pubkey: Pubkey,
new_authority: Option<Pubkey>,
protocol_config: Option<ProtocolConfig>,
) -> Instruction {
let protocol_config_pda = get_protocol_config_pda_address();
let update_authority_ix = crate::instruction::UpdateProtocolConfig { protocol_config };
let accounts = crate::accounts::UpdateProtocolConfig {
protocol_config_pda: protocol_config_pda.0,
authority: signer_pubkey,
fee_payer: signer_pubkey,
new_authority,
};
// update with new authority
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: update_authority_ix.data(),
}
}
pub fn create_register_program_instruction(
signer_pubkey: Pubkey,
protocol_config_pda: (Pubkey, u8),
group_account: Pubkey,
program_id_to_be_registered: Pubkey,
) -> (Instruction, Pubkey) {
let cpi_authority_pda = get_cpi_authority_pda();
let registered_program_pda =
Pubkey::find_program_address(&[program_id_to_be_registered.to_bytes().as_slice()], &ID).0;
let register_program_ix = crate::instruction::RegisterSystemProgram {
bump: cpi_authority_pda.1,
};
let register_program_accounts = crate::accounts::RegisterProgram {
authority: signer_pubkey,
program_to_be_registered: program_id_to_be_registered,
registered_program_pda,
protocol_config_pda: protocol_config_pda.0,
group_pda: group_account,
cpi_authority: cpi_authority_pda.0,
account_compression_program: ID,
system_program: system_program::ID,
};
let instruction = Instruction {
program_id: crate::ID,
accounts: register_program_accounts.to_account_metas(Some(true)),
data: register_program_ix.data(),
};
(instruction, registered_program_pda)
}
pub fn create_deregister_program_instruction(
signer_pubkey: Pubkey,
protocol_config_pda: (Pubkey, u8),
group_account: Pubkey,
program_id_to_be_deregistered: Pubkey,
) -> (Instruction, Pubkey) {
let cpi_authority_pda = get_cpi_authority_pda();
let registered_program_pda =
Pubkey::find_program_address(&[program_id_to_be_deregistered.to_bytes().as_slice()], &ID).0;
let register_program_ix = crate::instruction::DeregisterSystemProgram {
bump: cpi_authority_pda.1,
};
let register_program_accounts = crate::accounts::DeregisterProgram {
authority: signer_pubkey,
registered_program_pda,
protocol_config_pda: protocol_config_pda.0,
group_pda: group_account,
cpi_authority: cpi_authority_pda.0,
account_compression_program: ID,
};
let instruction = Instruction {
program_id: crate::ID,
accounts: register_program_accounts.to_account_metas(Some(true)),
data: register_program_ix.data(),
};
(instruction, registered_program_pda)
}
pub fn create_initialize_governance_authority_instruction(
fee_payer: Pubkey,
authority: Pubkey,
protocol_config: ProtocolConfig,
) -> Instruction {
let protocol_config_pda = get_protocol_config_pda_address();
let ix = crate::instruction::InitializeProtocolConfig {
bump: protocol_config_pda.1,
protocol_config,
};
let accounts = crate::accounts::InitializeProtocolConfig {
protocol_config_pda: protocol_config_pda.0,
fee_payer,
authority,
system_program: system_program::ID,
self_program: crate::ID,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: ix.data(),
}
}
pub fn create_register_forester_instruction(
fee_payer: &Pubkey,
governance_authority: &Pubkey,
forester_authority: &Pubkey,
config: ForesterConfig,
) -> Instruction {
let (forester_pda, _bump) = get_forester_pda(forester_authority);
let instruction_data = crate::instruction::RegisterForester {
_bump,
authority: *forester_authority,
config,
weight: Some(1),
};
let (protocol_config_pda, _) = get_protocol_config_pda_address();
let accounts = crate::accounts::RegisterForester {
forester_pda,
fee_payer: *fee_payer,
authority: *governance_authority,
protocol_config_pda,
system_program: solana_sdk::system_program::id(),
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_update_forester_pda_weight_instruction(
forester_authority: &Pubkey,
protocol_authority: &Pubkey,
new_weight: u64,
) -> Instruction {
let (forester_pda, _bump) = get_forester_pda(forester_authority);
let protocol_config_pda = get_protocol_config_pda_address().0;
let instruction_data = crate::instruction::UpdateForesterPdaWeight { new_weight };
let accounts = crate::accounts::UpdateForesterPdaWeight {
forester_pda,
authority: *protocol_authority,
protocol_config_pda,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_update_forester_pda_instruction(
forester_authority: &Pubkey,
derivation_key: &Pubkey,
new_authority: Option<Pubkey>,
config: Option<ForesterConfig>,
) -> Instruction {
let (forester_pda, _) = get_forester_pda(derivation_key);
let instruction_data = crate::instruction::UpdateForesterPda { config };
let accounts = crate::accounts::UpdateForesterPda {
forester_pda,
authority: *forester_authority,
new_authority,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_register_forester_epoch_pda_instruction(
authority: &Pubkey,
derivation: &Pubkey,
epoch: u64,
) -> Instruction {
let (forester_epoch_pda, _bump) = get_forester_epoch_pda_from_authority(derivation, epoch);
let (forester_pda, _) = get_forester_pda(derivation);
let epoch_pda = get_epoch_pda_address(epoch);
let protocol_config_pda = get_protocol_config_pda_address().0;
let instruction_data = crate::instruction::RegisterForesterEpoch { epoch };
let accounts = crate::accounts::RegisterForesterEpoch {
fee_payer: *authority,
forester_epoch_pda,
forester_pda,
authority: *authority,
epoch_pda,
protocol_config: protocol_config_pda,
system_program: solana_sdk::system_program::id(),
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_finalize_registration_instruction(
authority: &Pubkey,
derivation: &Pubkey,
epoch: u64,
) -> Instruction {
let (forester_epoch_pda, _bump) = get_forester_epoch_pda_from_derivation(derivation, epoch);
let epoch_pda = get_epoch_pda_address(epoch);
let instruction_data = crate::instruction::FinalizeRegistration {};
let accounts = crate::accounts::FinalizeRegistration {
forester_epoch_pda,
authority: *authority,
epoch_pda,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_report_work_instruction(
authority: &Pubkey,
derivation: &Pubkey,
epoch: u64,
) -> Instruction {
let (forester_epoch_pda, _bump) = get_forester_epoch_pda_from_authority(derivation, epoch);
let epoch_pda = get_epoch_pda_address(epoch);
let instruction_data = crate::instruction::ReportWork {};
let accounts = crate::accounts::ReportWork {
authority: *authority,
forester_epoch_pda,
epoch_pda,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/lib.rs
|
#![allow(clippy::too_many_arguments)]
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED;
use account_compression::{AddressMerkleTreeConfig, AddressQueueConfig};
use account_compression::{NullifierQueueConfig, StateMerkleTreeConfig};
use anchor_lang::prelude::*;
pub mod account_compression_cpi;
pub mod errors;
pub use crate::epoch::{finalize_registration::*, register_epoch::*, report_work::*};
pub use account_compression_cpi::{
initialize_tree_and_queue::*, nullify::*, register_program::*, rollover_state_tree::*,
update_address_tree::*,
};
pub use protocol_config::{initialize::*, update::*};
pub mod constants;
pub mod epoch;
pub mod protocol_config;
pub mod selection;
pub mod utils;
use account_compression::MerkleTreeMetadata;
pub use selection::forester::*;
use anchor_lang::solana_program::pubkey::Pubkey;
use errors::RegistryError;
use protocol_config::state::ProtocolConfig;
#[cfg(not(target_os = "solana"))]
pub mod sdk;
#[cfg(not(feature = "no-entrypoint"))]
solana_security_txt::security_txt! {
name: "light-registry",
project_url: "lightprotocol.com",
contacts: "email:security@lightprotocol.com",
policy: "https://github.com/Lightprotocol/light-protocol/blob/main/SECURITY.md",
source_code: "https://github.com/Lightprotocol/light-protocol"
}
declare_id!("Lighton6oQpVkeewmo2mcPTQQp7kYHr4fWpAgJyEmDX");
#[program]
pub mod light_registry {
use super::*;
/// Initializes the protocol config pda. Can only be called once by the
/// program account keypair.
pub fn initialize_protocol_config(
ctx: Context<InitializeProtocolConfig>,
bump: u8,
protocol_config: ProtocolConfig,
) -> Result<()> {
ctx.accounts.protocol_config_pda.authority = ctx.accounts.authority.key();
ctx.accounts.protocol_config_pda.bump = bump;
check_protocol_config(protocol_config)?;
ctx.accounts.protocol_config_pda.config = protocol_config;
Ok(())
}
pub fn update_protocol_config(
ctx: Context<UpdateProtocolConfig>,
protocol_config: Option<ProtocolConfig>,
) -> Result<()> {
if let Some(new_authority) = ctx.accounts.new_authority.as_ref() {
ctx.accounts.protocol_config_pda.authority = new_authority.key();
}
if let Some(protocol_config) = protocol_config {
if protocol_config.genesis_slot != ctx.accounts.protocol_config_pda.config.genesis_slot
{
msg!("Genesis slot cannot be changed.");
return err!(RegistryError::InvalidConfigUpdate);
}
if protocol_config.active_phase_length
!= ctx.accounts.protocol_config_pda.config.active_phase_length
{
msg!(
"Active phase length must not be changed, otherwise epochs will repeat {} {}.",
protocol_config.active_phase_length,
ctx.accounts.protocol_config_pda.config.active_phase_length
);
return err!(RegistryError::InvalidConfigUpdate);
}
check_protocol_config(protocol_config)?;
ctx.accounts.protocol_config_pda.config = protocol_config;
}
Ok(())
}
pub fn register_system_program(ctx: Context<RegisterProgram>, bump: u8) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::RegisterProgramToGroup {
authority: ctx.accounts.cpi_authority.to_account_info(),
program_to_be_registered: ctx.accounts.program_to_be_registered.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
group_authority_pda: ctx.accounts.group_pda.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::register_program_to_group(cpi_ctx)
}
pub fn deregister_system_program(ctx: Context<DeregisterProgram>, bump: u8) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::DeregisterProgram {
authority: ctx.accounts.cpi_authority.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
group_authority_pda: ctx.accounts.group_pda.to_account_info(),
close_recipient: ctx.accounts.authority.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::deregister_program(cpi_ctx)
}
pub fn register_forester(
ctx: Context<RegisterForester>,
_bump: u8,
authority: Pubkey,
config: ForesterConfig,
weight: Option<u64>,
) -> Result<()> {
ctx.accounts.forester_pda.authority = authority;
ctx.accounts.forester_pda.config = config;
if let Some(weight) = weight {
ctx.accounts.forester_pda.active_weight = weight;
}
Ok(())
}
pub fn update_forester_pda(
ctx: Context<UpdateForesterPda>,
config: Option<ForesterConfig>,
) -> Result<()> {
if let Some(authority) = ctx.accounts.new_authority.as_ref() {
ctx.accounts.forester_pda.authority = authority.key();
}
if let Some(config) = config {
ctx.accounts.forester_pda.config = config;
}
Ok(())
}
pub fn update_forester_pda_weight(
ctx: Context<UpdateForesterPdaWeight>,
new_weight: u64,
) -> Result<()> {
ctx.accounts.forester_pda.active_weight = new_weight;
Ok(())
}
/// Registers the forester for the epoch.
/// 1. Only the forester can register herself for the epoch.
/// 2. Protocol config is copied.
/// 3. Epoch account is created if needed.
pub fn register_forester_epoch<'info>(
ctx: Context<'_, '_, '_, 'info, RegisterForesterEpoch<'info>>,
epoch: u64,
) -> Result<()> {
// Only init if not initialized
if ctx.accounts.epoch_pda.registered_weight == 0 {
(*ctx.accounts.epoch_pda).clone_from(&EpochPda {
epoch,
protocol_config: ctx.accounts.protocol_config.config,
total_work: 0,
registered_weight: 0,
});
}
let current_solana_slot = anchor_lang::solana_program::clock::Clock::get()?.slot;
// Init epoch account if not initialized
let current_epoch = ctx
.accounts
.epoch_pda
.protocol_config
.get_latest_register_epoch(current_solana_slot)?;
if current_epoch != epoch {
return err!(RegistryError::InvalidEpoch);
}
// check that epoch is in registration phase is in process_register_for_epoch
process_register_for_epoch(
&ctx.accounts.authority.key(),
&mut ctx.accounts.forester_pda,
&mut ctx.accounts.forester_epoch_pda,
&mut ctx.accounts.epoch_pda,
current_solana_slot,
)?;
Ok(())
}
/// This transaction can be included as additional instruction in the first
/// work instructions during the active phase.
/// Registration Period must be over.
pub fn finalize_registration<'info>(
ctx: Context<'_, '_, '_, 'info, FinalizeRegistration<'info>>,
) -> Result<()> {
let current_solana_slot = anchor_lang::solana_program::clock::Clock::get()?.slot;
let current_active_epoch = ctx
.accounts
.epoch_pda
.protocol_config
.get_current_active_epoch(current_solana_slot)?;
if current_active_epoch != ctx.accounts.epoch_pda.epoch {
return err!(RegistryError::InvalidEpoch);
}
ctx.accounts.forester_epoch_pda.total_epoch_weight =
Some(ctx.accounts.epoch_pda.registered_weight);
ctx.accounts.forester_epoch_pda.finalize_counter += 1;
// Check limit for finalize counter to throw if exceeded
// Is a safeguard so that noone can block parallelism.
// This instruction can be passed with nullify instructions, to prevent
// read locking the epoch account for more than X transactions limit
// the number of syncs without failing the tx to X
if ctx.accounts.forester_epoch_pda.finalize_counter
> ctx
.accounts
.forester_epoch_pda
.protocol_config
.finalize_counter_limit
{
return err!(RegistryError::FinalizeCounterExceeded);
}
Ok(())
}
pub fn report_work<'info>(ctx: Context<'_, '_, '_, 'info, ReportWork<'info>>) -> Result<()> {
let current_solana_slot = anchor_lang::solana_program::clock::Clock::get()?.slot;
ctx.accounts
.epoch_pda
.protocol_config
.is_report_work_phase(current_solana_slot, ctx.accounts.epoch_pda.epoch)?;
if ctx.accounts.epoch_pda.epoch != ctx.accounts.forester_epoch_pda.epoch {
return err!(RegistryError::InvalidEpoch);
}
if ctx.accounts.forester_epoch_pda.has_reported_work {
return err!(RegistryError::ForesterAlreadyReportedWork);
}
ctx.accounts.epoch_pda.total_work += ctx.accounts.forester_epoch_pda.work_counter;
ctx.accounts.forester_epoch_pda.has_reported_work = true;
Ok(())
}
pub fn initialize_address_merkle_tree(
ctx: Context<InitializeMerkleTreeAndQueue>,
bump: u8,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
merkle_tree_config: AddressMerkleTreeConfig,
queue_config: AddressQueueConfig,
) -> Result<()> {
// The network fee must be either zero or the same as the protocol config.
// Only trees with a network fee will be serviced by light foresters.
if let Some(network_fee) = merkle_tree_config.network_fee {
if network_fee != ctx.accounts.protocol_config_pda.config.network_fee {
return err!(RegistryError::InvalidNetworkFee);
}
if forester.is_some() {
msg!("Forester pubkey must not be defined for trees serviced by light foresters.");
return err!(RegistryError::ForesterDefined);
}
} else if forester.is_none() {
msg!("Forester pubkey required for trees without a network fee.");
msg!("Trees without a network fee will not be serviced by light foresters.");
return err!(RegistryError::ForesterUndefined);
}
// Unused parameter
if queue_config.network_fee.is_some() {
return err!(RegistryError::InvalidNetworkFee);
}
process_initialize_address_merkle_tree(
ctx,
bump,
0,
program_owner,
forester,
merkle_tree_config,
queue_config,
)
}
pub fn initialize_state_merkle_tree(
ctx: Context<InitializeMerkleTreeAndQueue>,
bump: u8,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
merkle_tree_config: StateMerkleTreeConfig,
queue_config: NullifierQueueConfig,
) -> Result<()> {
// The network fee must be either zero or the same as the protocol config.
// Only trees with a network fee will be serviced by light foresters.
if let Some(network_fee) = merkle_tree_config.network_fee {
if network_fee != ctx.accounts.protocol_config_pda.config.network_fee {
return err!(RegistryError::InvalidNetworkFee);
}
} else if forester.is_none() {
msg!("Forester pubkey required for trees without a network fee.");
msg!("Trees without a network fee will not be serviced by light foresters.");
return err!(RegistryError::ForesterUndefined);
}
// Unused parameter
if queue_config.network_fee.is_some() {
return err!(RegistryError::InvalidNetworkFee);
}
check_cpi_context(
ctx.accounts
.cpi_context_account
.as_ref()
.unwrap()
.to_account_info(),
&ctx.accounts.protocol_config_pda.config,
)?;
process_initialize_state_merkle_tree(
&ctx,
bump,
0,
program_owner,
forester,
merkle_tree_config,
queue_config,
)?;
process_initialize_cpi_context(
bump,
ctx.accounts.authority.to_account_info(),
ctx.accounts
.cpi_context_account
.as_ref()
.unwrap()
.to_account_info(),
ctx.accounts.merkle_tree.to_account_info(),
ctx.accounts
.light_system_program
.as_ref()
.unwrap()
.to_account_info(),
)
}
pub fn nullify<'info>(
ctx: Context<'_, '_, '_, 'info, NullifyLeaves<'info>>,
bump: u8,
change_log_indices: Vec<u64>,
leaves_queue_indices: Vec<u16>,
indices: Vec<u64>,
proofs: Vec<Vec<[u8; 32]>>,
) -> Result<()> {
let metadata = ctx.accounts.merkle_tree.load()?.metadata;
check_forester(
&metadata,
ctx.accounts.authority.key(),
ctx.accounts.nullifier_queue.key(),
&mut ctx.accounts.registered_forester_pda,
)?;
process_nullify(
&ctx,
bump,
change_log_indices,
leaves_queue_indices,
indices,
proofs,
)
}
#[allow(clippy::too_many_arguments)]
pub fn update_address_merkle_tree(
ctx: Context<UpdateAddressMerkleTree>,
bump: u8,
changelog_index: u16,
indexed_changelog_index: u16,
value: u16,
low_address_index: u64,
low_address_value: [u8; 32],
low_address_next_index: u64,
low_address_next_value: [u8; 32],
low_address_proof: [[u8; 32]; 16],
) -> Result<()> {
let metadata = ctx.accounts.merkle_tree.load()?.metadata;
check_forester(
&metadata,
ctx.accounts.authority.key(),
ctx.accounts.queue.key(),
&mut ctx.accounts.registered_forester_pda,
)?;
process_update_address_merkle_tree(
&ctx,
bump,
changelog_index,
indexed_changelog_index,
value,
low_address_index,
low_address_value,
low_address_next_index,
low_address_next_value,
low_address_proof,
)
}
pub fn rollover_address_merkle_tree_and_queue<'info>(
ctx: Context<'_, '_, '_, 'info, RolloverAddressMerkleTreeAndQueue<'info>>,
bump: u8,
) -> Result<()> {
let metadata = ctx.accounts.old_merkle_tree.load()?.metadata;
check_forester(
&metadata,
ctx.accounts.authority.key(),
ctx.accounts.old_queue.key(),
&mut ctx.accounts.registered_forester_pda,
)?;
process_rollover_address_merkle_tree_and_queue(&ctx, bump)
}
pub fn rollover_state_merkle_tree_and_queue<'info>(
ctx: Context<'_, '_, '_, 'info, RolloverStateMerkleTreeAndQueue<'info>>,
bump: u8,
) -> Result<()> {
let metadata = ctx.accounts.old_merkle_tree.load()?.metadata;
check_forester(
&metadata,
ctx.accounts.authority.key(),
ctx.accounts.old_queue.key(),
&mut ctx.accounts.registered_forester_pda,
)?;
check_cpi_context(
ctx.accounts.cpi_context_account.as_ref().to_account_info(),
&ctx.accounts.protocol_config_pda.config,
)?;
process_rollover_state_merkle_tree_and_queue(&ctx, bump)?;
process_initialize_cpi_context(
bump,
ctx.accounts.authority.to_account_info(),
ctx.accounts.cpi_context_account.as_ref().to_account_info(),
ctx.accounts.new_merkle_tree.to_account_info(),
ctx.accounts.light_system_program.as_ref().to_account_info(),
)
}
}
/// if registered_forester_pda is not None check forester eligibility and network_fee is not 0
/// if metadata.forester == authority can forest
/// else throw error
pub fn check_forester(
metadata: &MerkleTreeMetadata,
authority: Pubkey,
queue: Pubkey,
registered_forester_pda: &mut Option<Account<'_, ForesterEpochPda>>,
) -> Result<()> {
if let Some(forester_pda) = registered_forester_pda.as_mut() {
// Checks forester:
// - signer
// - eligibility
// - increments work counter
ForesterEpochPda::check_forester_in_program(forester_pda, &authority, &queue)?;
if metadata.rollover_metadata.network_fee == 0 {
return err!(RegistryError::InvalidNetworkFee);
}
Ok(())
} else if metadata.access_metadata.forester == authority {
Ok(())
} else {
err!(RegistryError::InvalidSigner)
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/errors.rs
|
use anchor_lang::prelude::*;
#[error_code]
pub enum RegistryError {
#[msg("InvalidForester")]
InvalidForester,
NotInReportWorkPhase,
StakeAccountAlreadySynced,
EpochEnded,
ForesterNotEligible,
NotInRegistrationPeriod,
WeightInsuffient,
ForesterAlreadyRegistered,
InvalidEpochAccount,
InvalidEpoch,
EpochStillInProgress,
NotInActivePhase,
ForesterAlreadyReportedWork,
InvalidNetworkFee,
FinalizeCounterExceeded,
CpiContextAccountMissing,
ArithmeticUnderflow,
RegistrationNotFinalized,
CpiContextAccountInvalidDataLen,
InvalidConfigUpdate,
InvalidSigner,
GetLatestRegisterEpochFailed,
GetCurrentActiveEpochFailed,
ForesterUndefined,
ForesterDefined,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/utils.rs
|
use anchor_lang::solana_program::pubkey::Pubkey;
use crate::constants::{FORESTER_EPOCH_SEED, FORESTER_SEED, PROTOCOL_CONFIG_PDA_SEED};
pub fn get_protocol_config_pda_address() -> (Pubkey, u8) {
Pubkey::find_program_address(&[PROTOCOL_CONFIG_PDA_SEED], &crate::ID)
}
pub fn get_cpi_authority_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[crate::CPI_AUTHORITY_PDA_SEED], &crate::ID)
}
pub fn get_forester_epoch_pda_from_authority(authority: &Pubkey, epoch: u64) -> (Pubkey, u8) {
println!(
"get_forester_epoch_pda_from_authority: authority: {}, epoch: {}",
authority, epoch
);
let forester_pda = get_forester_pda(authority);
get_forester_epoch_pda(&forester_pda.0, epoch)
}
pub fn get_forester_epoch_pda_from_derivation(derivation: &Pubkey, epoch: u64) -> (Pubkey, u8) {
println!(
"get_forester_epoch_pda_from_derivation: derivation: {}, epoch: {}",
derivation, epoch
);
let forester_pda = get_forester_pda(derivation);
get_forester_epoch_pda(&forester_pda.0, epoch)
}
pub fn get_forester_epoch_pda(forester_pda: &Pubkey, epoch: u64) -> (Pubkey, u8) {
Pubkey::find_program_address(
&[
FORESTER_EPOCH_SEED,
forester_pda.as_ref(),
epoch.to_le_bytes().as_slice(),
],
&crate::ID,
)
}
pub fn get_forester_pda(authority: &Pubkey) -> (Pubkey, u8) {
Pubkey::find_program_address(&[FORESTER_SEED, authority.as_ref()], &crate::ID)
}
pub fn get_epoch_pda_address(epoch: u64) -> Pubkey {
Pubkey::find_program_address(&[&epoch.to_le_bytes()], &crate::ID).0
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/protocol_config/initialize.rs
|
use crate::{
constants::PROTOCOL_CONFIG_PDA_SEED, program::LightRegistry,
protocol_config::state::ProtocolConfigPda,
};
use anchor_lang::prelude::*;
#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct InitializeProtocolConfig<'info> {
#[account(mut)]
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
#[account(init, seeds = [PROTOCOL_CONFIG_PDA_SEED], bump, space = ProtocolConfigPda::LEN, payer = fee_payer)]
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
pub system_program: Program<'info, System>,
pub self_program: Program<'info, LightRegistry>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/protocol_config/update.rs
|
use anchor_lang::prelude::*;
use crate::errors::RegistryError;
use super::state::{ProtocolConfig, ProtocolConfigPda};
#[derive(Accounts)]
pub struct UpdateProtocolConfig<'info> {
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
/// CHECK: authority is protocol config authority.
#[account(mut, has_one=authority)]
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
/// CHECK: is signer to reduce risk of updating with a wrong authority.
pub new_authority: Option<Signer<'info>>,
}
pub fn check_protocol_config(protocol_config: ProtocolConfig) -> Result<()> {
if protocol_config.min_weight == 0 {
msg!("Min weight cannot be zero.");
return err!(RegistryError::InvalidConfigUpdate);
}
if protocol_config.active_phase_length < protocol_config.registration_phase_length {
msg!(
"Active phase length must be greater or equal than registration phase length. {} {}",
protocol_config.active_phase_length,
protocol_config.registration_phase_length
);
return err!(RegistryError::InvalidConfigUpdate);
}
if protocol_config.active_phase_length < protocol_config.report_work_phase_length {
msg!(
"Active phase length must be greater or equal than report work phase length. {} {}",
protocol_config.active_phase_length,
protocol_config.report_work_phase_length
);
return err!(RegistryError::InvalidConfigUpdate);
}
if protocol_config.active_phase_length < protocol_config.slot_length {
msg!(
"Active phase length is less than slot length, active phase length {} < slot length {}. (Active phase lenght must be greater than slot length.)",
protocol_config.active_phase_length,
protocol_config.slot_length
);
return err!(RegistryError::InvalidConfigUpdate);
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/protocol_config/mod.rs
|
pub mod initialize;
pub mod state;
pub mod update;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/protocol_config/state.rs
|
use crate::errors::RegistryError;
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
#[aligned_sized(anchor)]
#[derive(Debug)]
#[account]
pub struct ProtocolConfigPda {
pub authority: Pubkey,
pub bump: u8,
pub config: ProtocolConfig,
}
/// Epoch Phases:
/// 1. Registration
/// 2. Active
/// 3. Report Work
/// 4. Post (Epoch has ended, and rewards can be claimed.)
/// - There is always an active phase in progress, registration and report work
/// phases run in parallel to a currently active phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, AnchorSerialize, AnchorDeserialize)]
pub struct ProtocolConfig {
/// Solana slot when the protocol starts operating.
pub genesis_slot: u64,
/// Minimum weight required for a forester to register to an epoch.
pub min_weight: u64,
/// Light protocol slot length.
pub slot_length: u64,
/// Foresters can register for this phase.
pub registration_phase_length: u64,
/// Foresters can perform work in this phase.
pub active_phase_length: u64,
/// Foresters can report work to receive performance based rewards in this
/// phase.
pub report_work_phase_length: u64,
pub network_fee: u64,
pub cpi_context_size: u64,
pub finalize_counter_limit: u64,
/// Placeholder for future protocol updates.
pub place_holder: Pubkey,
pub place_holder_a: u64,
pub place_holder_b: u64,
pub place_holder_c: u64,
pub place_holder_d: u64,
pub place_holder_e: u64,
pub place_holder_f: u64,
}
impl Default for ProtocolConfig {
fn default() -> Self {
Self {
genesis_slot: 0,
min_weight: 1,
slot_length: 10,
registration_phase_length: 100,
active_phase_length: 1000,
report_work_phase_length: 100,
network_fee: 5000,
cpi_context_size: 20 * 1024 + 8,
finalize_counter_limit: 100,
place_holder: Pubkey::default(),
place_holder_a: 0,
place_holder_b: 0,
place_holder_c: 0,
place_holder_d: 0,
place_holder_e: 0,
place_holder_f: 0,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub enum EpochState {
Registration,
Active,
ReportWork,
Post,
#[default]
Pre,
}
/// Light Epoch Example:
///
/// Diagram of epochs 0 and 1.
/// Registration 0 starts at genesis slot.
/// |---- Registration 0 ----|------------------ Active 0 ------|---- Report Work 0 ----|---- Post 0 ----
/// |-- Registration 1 --|------------------ Active 1 -----------------
/// (Post epoch does not end unlike the other phases.)
///
/// let genesis = 0;
/// let registration_phase_length = 100;
/// let active_phase_length = 1000;
/// let report_work_phase_length = 100;
/// let slot = 10;
///
/// To get the latest registry epoch:
/// - slot = 0;
/// let current_registry_epoch = (slot - genesis) / active_phase_length;
/// current_registry_epoch = (0 - 0) / 1000 = 0;
/// first active phase starts at genesis + registration_phase_length
/// = 0 + 100 = 100;
///
/// To get the current active epoch:
/// - slot = 100;
/// let current_active_epoch =
/// (slot - genesis - registration_phase_length) / active_phase_length;
/// current_active_epoch = (100 - 0 - 100) / 1000 = 0;
///
/// Epoch 0:
/// - Registration 0: 0 - 100
/// - Active 0: 100 - 1100
/// - Report Work 0: 1100 - 1200
/// - Post 0: 1200 - inf
///
/// Epoch 1:
/// - Registration 1: 1000 - 1100
/// - Active 1: 1100 - 2100
/// - Report Work 1: 2100 - 2200
/// - Post 1: 2200 - inf
///
/// Epoch 2:
/// - Registration 2: 2000 - 2100
/// - Active 2: 2100 - 3100
/// - Report Work 2: 3100 - 3200
/// - Post 2: 3200 - inf
///
impl ProtocolConfig {
/// Current epoch including registration phase.
pub fn get_latest_register_epoch(&self, slot: u64) -> Result<u64> {
let slot = slot
.checked_sub(self.genesis_slot)
.ok_or(RegistryError::GetLatestRegisterEpochFailed)?;
Ok(slot / self.active_phase_length)
}
pub fn get_current_epoch(&self, slot: u64) -> u64 {
(slot.saturating_sub(self.genesis_slot)) / self.active_phase_length
}
pub fn get_current_active_epoch(&self, slot: u64) -> Result<u64> {
let slot = slot
.checked_sub(self.genesis_slot + self.registration_phase_length)
.ok_or(RegistryError::GetCurrentActiveEpochFailed)?;
Ok(slot / self.active_phase_length)
}
pub fn get_latest_register_epoch_progress(&self, slot: u64) -> Result<u64> {
Ok(slot
.checked_sub(self.genesis_slot)
.ok_or(RegistryError::ArithmeticUnderflow)?
% self.active_phase_length)
}
pub fn get_current_active_epoch_progress(&self, slot: u64) -> u64 {
(slot
.checked_sub(self.genesis_slot + self.registration_phase_length)
.unwrap())
% self.active_phase_length
}
/// In the last part of the active phase the registration phase starts.
/// Returns end slot of the registration phase/start slot of the next active phase.
pub fn is_registration_phase(&self, slot: u64) -> Result<u64> {
let latest_register_epoch = self.get_latest_register_epoch(slot)?;
let latest_register_epoch_progress = self.get_latest_register_epoch_progress(slot)?;
if latest_register_epoch_progress >= self.registration_phase_length {
return err!(RegistryError::NotInRegistrationPeriod);
}
Ok((latest_register_epoch) * self.active_phase_length
+ self.genesis_slot
+ self.registration_phase_length)
}
pub fn is_active_phase(&self, slot: u64, epoch: u64) -> Result<()> {
if self.get_current_active_epoch(slot)? != epoch {
return err!(RegistryError::NotInActivePhase);
}
Ok(())
}
pub fn is_report_work_phase(&self, slot: u64, epoch: u64) -> Result<()> {
self.is_active_phase(slot, epoch + 1)?;
let current_epoch_progress = self.get_current_active_epoch_progress(slot);
if current_epoch_progress >= self.report_work_phase_length {
return err!(RegistryError::NotInReportWorkPhase);
}
Ok(())
}
pub fn is_post_epoch(&self, slot: u64, epoch: u64) -> Result<()> {
if self.get_current_active_epoch(slot)? <= epoch {
return err!(RegistryError::InvalidEpoch);
}
Ok(())
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/epoch/report_work.rs
|
use crate::errors::RegistryError;
use super::register_epoch::{EpochPda, ForesterEpochPda};
use anchor_lang::prelude::*;
/// Report work:
/// - work is reported so that relative performance of foresters can be assessed
/// 1. Check that we are in the report work phase
/// 2. Check that forester has registered for the epoch
/// 3. Check that forester has not already reported work
/// 4. Add work to total work
pub fn report_work_instruction(
forester_epoch_pda: &mut ForesterEpochPda,
epoch_pda: &mut EpochPda,
current_slot: u64,
) -> Result<()> {
epoch_pda
.protocol_config
.is_report_work_phase(current_slot, epoch_pda.epoch)?;
if forester_epoch_pda.epoch != epoch_pda.epoch {
return err!(RegistryError::InvalidEpochAccount);
}
if forester_epoch_pda.has_reported_work {
return err!(RegistryError::ForesterAlreadyRegistered);
}
forester_epoch_pda.has_reported_work = true;
epoch_pda.total_work += forester_epoch_pda.work_counter;
Ok(())
}
#[derive(Accounts)]
pub struct ReportWork<'info> {
authority: Signer<'info>,
#[account(mut, has_one = authority)]
pub forester_epoch_pda: Account<'info, ForesterEpochPda>,
#[account(mut)]
pub epoch_pda: Account<'info, EpochPda>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/epoch/finalize_registration.rs
|
use anchor_lang::prelude::*;
use crate::{EpochPda, ForesterEpochPda};
#[derive(Accounts)]
pub struct FinalizeRegistration<'info> {
pub authority: Signer<'info>,
#[account(mut,has_one = authority)]
pub forester_epoch_pda: Account<'info, ForesterEpochPda>,
/// CHECK: instruction checks that the epoch is the current epoch.
#[account(constraint = epoch_pda.epoch == forester_epoch_pda.epoch)]
pub epoch_pda: Account<'info, EpochPda>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/epoch/mod.rs
|
pub mod finalize_registration;
pub mod register_epoch;
pub mod report_work;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/epoch/register_epoch.rs
|
use crate::constants::FORESTER_EPOCH_SEED;
use crate::errors::RegistryError;
use crate::protocol_config::state::{ProtocolConfig, ProtocolConfigPda};
use crate::selection::forester::{ForesterConfig, ForesterPda};
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
use anchor_lang::solana_program::pubkey::Pubkey;
/// Is used for tallying and rewards calculation
#[account]
#[aligned_sized(anchor)]
#[derive(Debug, Default, PartialEq, Eq)]
pub struct EpochPda {
pub epoch: u64,
pub protocol_config: ProtocolConfig,
pub total_work: u64,
pub registered_weight: u64,
}
#[aligned_sized(anchor)]
#[account]
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ForesterEpochPda {
pub authority: Pubkey,
pub config: ForesterConfig,
pub epoch: u64,
pub weight: u64,
pub work_counter: u64,
/// Work can be reported in an extra round to earn extra performance based
/// rewards.
pub has_reported_work: bool,
/// Start index of the range that determines when the forester is eligible to perform work.
/// End index is forester_start_index + weight
pub forester_index: u64,
pub epoch_active_phase_start_slot: u64,
/// Total epoch weight is registered weight of the epoch account after
/// registration is concluded and active epoch period starts.
pub total_epoch_weight: Option<u64>,
pub protocol_config: ProtocolConfig,
/// Incremented every time finalize registration is called.
pub finalize_counter: u64,
}
impl ForesterEpochPda {
pub fn get_current_light_slot(&self, current_solana_slot: u64) -> Result<u64> {
let epoch_progres =
match current_solana_slot.checked_sub(self.epoch_active_phase_start_slot) {
Some(epoch_progres) => epoch_progres,
None => return err!(RegistryError::EpochEnded),
};
Ok(epoch_progres / self.protocol_config.slot_length)
}
/// Returns the forester index for the current slot. The forester whose
/// weighted range [total_registered_weight_at_registration,
/// total_registered_weight_at_registration + forester_weight ) contains the
/// forester index is eligible to perform work. If a forester has more
/// weight the range is larger -> the forester is eligible for more slots.
/// The forester index is a random number, derived from queue pubkey, epoch,
/// and current light slot, between 0 and total_epoch_weight.
pub fn get_eligible_forester_index(
current_light_slot: u64,
pubkey: &Pubkey,
total_epoch_weight: u64,
epoch: u64,
) -> Result<u64> {
// Domain separation using the pubkey and current_light_slot.
let mut hasher = anchor_lang::solana_program::hash::Hasher::default();
hasher.hashv(&[
pubkey.to_bytes().as_slice(),
&epoch.to_be_bytes(),
¤t_light_slot.to_be_bytes(),
]);
let hash_value = u64::from_be_bytes(hasher.result().to_bytes()[0..8].try_into().unwrap());
let forester_index = hash_value % total_epoch_weight;
Ok(forester_index)
}
pub fn is_eligible(&self, forester_range_start: u64) -> bool {
forester_range_start >= self.forester_index
&& forester_range_start < self.forester_index + self.weight
}
/// Check forester account is:
/// - of correct epoch
/// - eligible to perform work in the current slot
pub fn check_eligibility(&self, current_slot: u64, pubkey: &Pubkey) -> Result<()> {
self.protocol_config
.is_active_phase(current_slot, self.epoch)?;
let current_light_slot = self.get_current_light_slot(current_slot)?;
let total_epoch_weight = self
.total_epoch_weight
.ok_or(RegistryError::RegistrationNotFinalized)?;
let forester_slot = Self::get_eligible_forester_index(
current_light_slot,
pubkey,
total_epoch_weight,
self.epoch,
)?;
if self.is_eligible(forester_slot) {
Ok(())
} else {
err!(RegistryError::ForesterNotEligible)
}
}
/// Checks forester:
/// - signer
/// - eligibility
/// - increments work counter
pub fn check_forester(
forester_epoch_pda: &mut ForesterEpochPda,
authority: &Pubkey,
queue_pubkey: &Pubkey,
current_solana_slot: u64,
) -> Result<()> {
if forester_epoch_pda.authority != *authority {
msg!(
"Invalid forester: forester_epoch_pda authority {} != provided {}",
forester_epoch_pda.authority,
authority
);
return err!(RegistryError::InvalidForester);
}
forester_epoch_pda.check_eligibility(current_solana_slot, queue_pubkey)?;
forester_epoch_pda.work_counter += 1;
Ok(())
}
pub fn check_forester_in_program(
forester_epoch_pda: &mut ForesterEpochPda,
authority: &Pubkey,
queue_pubkey: &Pubkey,
) -> Result<()> {
let current_solana_slot = anchor_lang::solana_program::sysvar::clock::Clock::get()?.slot;
Self::check_forester(
forester_epoch_pda,
authority,
queue_pubkey,
current_solana_slot,
)
}
}
/// This instruction needs to be executed once the active period starts.
pub fn set_total_registered_weight_instruction(
forester_epoch_pda: &mut ForesterEpochPda,
epoch_pda: &EpochPda,
) {
forester_epoch_pda.total_epoch_weight = Some(epoch_pda.registered_weight);
}
#[derive(Accounts)]
#[instruction(current_epoch: u64)]
pub struct RegisterForesterEpoch<'info> {
#[account(mut)]
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
#[account(has_one = authority)]
pub forester_pda: Account<'info, ForesterPda>,
/// Instruction checks that current_epoch is the the current epoch and that
/// the epoch is in registration phase.
#[account(init, seeds = [FORESTER_EPOCH_SEED, forester_pda.key().to_bytes().as_slice(), current_epoch.to_le_bytes().as_slice()], bump, space =ForesterEpochPda::LEN , payer = fee_payer)]
pub forester_epoch_pda: Account<'info, ForesterEpochPda>,
pub protocol_config: Account<'info, ProtocolConfigPda>,
#[account(init_if_needed, seeds = [current_epoch.to_le_bytes().as_slice()], bump, space =EpochPda::LEN, payer = fee_payer)]
pub epoch_pda: Account<'info, EpochPda>,
system_program: Program<'info, System>,
}
/// Register Forester for epoch:
/// 1. initialize epoch account if not initialized
/// 2. check that forester has enough weight
/// 3. check that forester has not already registered for the epoch
/// 4. check that we are in the registration period
/// 5. sync pending weight to active weight if weight hasn't been synced yet
/// 6. Initialize forester epoch account.
/// 7. Add forester active weight to epoch registered weight.
///
/// Epoch account:
/// - should only be created in epoch registration period
/// - should only be created once
/// - contains the protocol config to set the protocol config for that epoch
/// (changes to protocol config take effect with next epoch)
/// - collectes the active weight of registered foresters
///
/// Forester Epoch Account:
/// - should only be created in epoch registration period
/// - should only be created once per epoch per forester
#[inline(never)]
pub fn process_register_for_epoch(
authority: &Pubkey,
forester_pda: &mut ForesterPda,
forester_epoch_pda: &mut ForesterEpochPda,
epoch_pda: &mut EpochPda,
current_slot: u64,
) -> Result<()> {
if forester_pda.active_weight < epoch_pda.protocol_config.min_weight {
return err!(RegistryError::WeightInsuffient);
}
// Check whether we are in an epoch registration phase and which epoch we are in
let current_epoch_start_slot = epoch_pda
.protocol_config
.is_registration_phase(current_slot)?;
forester_pda.last_registered_epoch = epoch_pda.epoch;
let initialized_forester_epoch_pda = ForesterEpochPda {
authority: *authority,
config: forester_pda.config,
epoch: epoch_pda.epoch,
weight: forester_pda.active_weight,
work_counter: 0,
has_reported_work: false,
epoch_active_phase_start_slot: current_epoch_start_slot,
forester_index: epoch_pda.registered_weight,
total_epoch_weight: None,
protocol_config: epoch_pda.protocol_config,
finalize_counter: 0,
};
forester_epoch_pda.clone_from(&initialized_forester_epoch_pda);
epoch_pda.registered_weight += forester_pda.active_weight;
Ok(())
}
#[cfg(test)]
mod test {
use solana_sdk::signature::{Keypair, Signer};
use std::collections::HashMap;
use super::*;
fn setup_forester_epoch_pda(
forester_start_range: u64,
forester_weight: u64,
active_phase_length: u64,
slot_length: u64,
epoch_active_phase_start_slot: u64,
total_epoch_weight: u64,
) -> ForesterEpochPda {
ForesterEpochPda {
authority: Pubkey::new_unique(),
config: ForesterConfig::default(),
epoch: 0,
weight: forester_weight,
work_counter: 0,
has_reported_work: false,
forester_index: forester_start_range,
epoch_active_phase_start_slot,
total_epoch_weight: Some(total_epoch_weight),
finalize_counter: 0,
protocol_config: ProtocolConfig {
genesis_slot: 0,
registration_phase_length: 1,
active_phase_length,
report_work_phase_length: 2,
min_weight: 0,
slot_length,
network_fee: 5000,
..Default::default()
},
}
}
#[test]
fn test_eligibility_check_within_epoch() {
let mut eligible = HashMap::<u8, (u64, u64)>::new();
let slot_length = 20;
let num_foresters = 5;
let epoch_active_phase_start_slot = 10;
let epoch_len = 2000;
let queue_pubkey = Keypair::new().pubkey();
let mut total_weight = 0;
for forester_index in 0..num_foresters {
let forester_weight = 10_000 * (forester_index + 1);
total_weight += forester_weight;
}
let mut current_total_weight = 0;
for forester_index in 0..num_foresters {
let forester_weight = 10_000 * (forester_index + 1);
let account = setup_forester_epoch_pda(
current_total_weight,
forester_weight,
epoch_len,
slot_length,
epoch_active_phase_start_slot,
total_weight,
);
current_total_weight += forester_weight;
// Check eligibility within and outside the epoch
for i in 0..epoch_len {
let index = account.check_eligibility(i, &queue_pubkey);
if index.is_ok() {
match eligible.get_mut(&(forester_index as u8)) {
Some((_, count)) => {
*count += 1;
}
None => {
eligible.insert(forester_index as u8, (forester_weight, 1));
}
};
}
}
}
println!("stats --------------------------------");
for (forester_index, num_eligible_slots) in eligible.iter() {
println!("forester_index = {:?}", forester_index);
println!("num_eligible_slots = {:?}", num_eligible_slots);
}
let sum = eligible.values().map(|x| x.1).sum::<u64>();
let total_slots: u64 = epoch_len - epoch_active_phase_start_slot;
assert_eq!(sum, total_slots);
}
#[test]
fn test_epoch_phases() {
let registration_phase_length = 1;
let active_phase_length = 7;
let report_work_phase_length = 2;
let protocol_config = ProtocolConfig {
genesis_slot: 20,
registration_phase_length,
active_phase_length,
report_work_phase_length,
min_weight: 0,
slot_length: 1,
network_fee: 5000,
..Default::default()
};
// Diagram of epochs 0 and 1.
// Registration 0 starts at genesis slot.
// |---- Registration 0 ----|------------------ Active 0 ------|---- Report Work 0 ----|---- Post 0 ----
// |-- Registration 1 --|------------------ Active 1 -----------------
let mut current_slot = protocol_config.genesis_slot;
for epoch in 0..1000 {
if epoch == 0 {
for _ in 0..protocol_config.registration_phase_length {
assert!(protocol_config.is_registration_phase(current_slot).is_ok());
assert!(protocol_config
.is_active_phase(current_slot, epoch)
.is_err());
assert!(protocol_config.is_post_epoch(current_slot, epoch).is_err());
assert!(protocol_config
.is_report_work_phase(current_slot, epoch)
.is_err());
current_slot += 1;
}
}
for i in 0..protocol_config.active_phase_length {
assert!(protocol_config.is_active_phase(current_slot, epoch).is_ok());
if protocol_config.active_phase_length.saturating_sub(i)
<= protocol_config.registration_phase_length
{
assert!(protocol_config.is_registration_phase(current_slot).is_ok());
} else {
assert!(protocol_config.is_registration_phase(current_slot).is_err());
}
if epoch == 0 {
assert!(protocol_config.is_post_epoch(current_slot, epoch).is_err());
} else {
assert!(protocol_config
.is_post_epoch(current_slot, epoch - 1)
.is_ok());
}
if epoch == 0 {
assert!(protocol_config
.is_report_work_phase(current_slot, epoch)
.is_err());
} else if i < protocol_config.report_work_phase_length {
assert!(protocol_config
.is_report_work_phase(current_slot, epoch - 1)
.is_ok());
} else {
assert!(protocol_config
.is_report_work_phase(current_slot, epoch - 1)
.is_err());
}
assert!(protocol_config
.is_report_work_phase(current_slot, epoch)
.is_err());
current_slot += 1;
}
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/rollover_state_tree.rs
|
use account_compression::{
program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED,
AddressMerkleTreeAccount, StateMerkleTreeAccount,
};
use anchor_lang::prelude::*;
use light_system_program::program::LightSystemProgram;
use crate::{epoch::register_epoch::ForesterEpochPda, protocol_config::state::ProtocolConfigPda};
#[derive(Accounts)]
pub struct RolloverStateMerkleTreeAndQueue<'info> {
/// CHECK: only eligible foresters can nullify leaves. Is checked in ix.
#[account(mut)]
pub registered_forester_pda: Option<Account<'info, ForesterEpochPda>>,
/// CHECK:
#[account(mut)]
pub authority: Signer<'info>,
/// CHECK: only eligible foresters can nullify leaves. Is checked in ix.
pub cpi_authority: AccountInfo<'info>,
/// CHECK: (account compression program) group access control.
pub registered_program_pda: AccountInfo<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (account compression program).
#[account(zero)]
pub new_merkle_tree: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(zero)]
pub new_queue: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(mut)]
pub old_merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>,
/// CHECK: (account compression program).
#[account(mut)]
pub old_queue: AccountInfo<'info>,
/// CHECK: (system program) new cpi context account.
pub cpi_context_account: AccountInfo<'info>,
pub light_system_program: Program<'info, LightSystemProgram>,
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
}
#[derive(Accounts)]
pub struct RolloverAddressMerkleTreeAndQueue<'info> {
/// CHECK: only eligible foresters can nullify leaves. Is checked in ix.
#[account(mut)]
pub registered_forester_pda: Option<Account<'info, ForesterEpochPda>>,
/// CHECK:
#[account(mut)]
pub authority: Signer<'info>,
/// CHECK: only eligible foresters can nullify leaves. Is checked in ix.
pub cpi_authority: AccountInfo<'info>,
/// CHECK: (account compression program) group access control.
pub registered_program_pda: AccountInfo<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (account compression program).
#[account(zero)]
pub new_merkle_tree: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(zero)]
pub new_queue: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(mut)]
pub old_merkle_tree: AccountLoader<'info, AddressMerkleTreeAccount>,
/// CHECK: (account compression program).
#[account(mut)]
pub old_queue: AccountInfo<'info>,
}
pub fn process_rollover_address_merkle_tree_and_queue(
ctx: &Context<RolloverAddressMerkleTreeAndQueue>,
bump: u8,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::RolloverAddressMerkleTreeAndQueue {
fee_payer: ctx.accounts.authority.to_account_info(),
authority: ctx.accounts.cpi_authority.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
new_address_merkle_tree: ctx.accounts.new_merkle_tree.to_account_info(),
new_queue: ctx.accounts.new_queue.to_account_info(),
old_address_merkle_tree: ctx.accounts.old_merkle_tree.to_account_info(),
old_queue: ctx.accounts.old_queue.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::rollover_address_merkle_tree_and_queue(cpi_ctx)
}
pub fn process_rollover_state_merkle_tree_and_queue(
ctx: &Context<RolloverStateMerkleTreeAndQueue>,
bump: u8,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::RolloverStateMerkleTreeAndNullifierQueue {
fee_payer: ctx.accounts.authority.to_account_info(),
authority: ctx.accounts.cpi_authority.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
new_state_merkle_tree: ctx.accounts.new_merkle_tree.to_account_info(),
new_nullifier_queue: ctx.accounts.new_queue.to_account_info(),
old_state_merkle_tree: ctx.accounts.old_merkle_tree.to_account_info(),
old_nullifier_queue: ctx.accounts.old_queue.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::rollover_state_merkle_tree_and_nullifier_queue(cpi_ctx)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/register_program.rs
|
use account_compression::{
program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED, GroupAuthority,
};
use anchor_lang::prelude::*;
use crate::protocol_config::state::ProtocolConfigPda;
#[derive(Accounts)]
pub struct RegisterProgram<'info> {
/// CHECK: only the protocol authority can register new programs.
#[account(mut)]
pub authority: Signer<'info>,
#[account(mut, has_one = authority)]
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
/// CHECK: (seed constraints) used to invoke account compression program via cpi.
#[account(mut, seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(mut ,constraint = group_pda.authority == cpi_authority.key())]
pub group_pda: Account<'info, GroupAuthority>,
pub account_compression_program: Program<'info, AccountCompression>,
pub system_program: Program<'info, System>,
/// CHECK: (account compression program).
#[account(mut)]
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: (account compression program). TODO: check that a signer is the upgrade authority.
/// - is signer so that only the program deployer can register a program.
pub program_to_be_registered: Signer<'info>,
}
#[derive(Accounts)]
pub struct DeregisterProgram<'info> {
/// CHECK: only the protocol authority can register new programs.
#[account(mut)]
pub authority: Signer<'info>,
#[account(mut, has_one = authority)]
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
/// CHECK: (seed constraints) used to invoke account compression program via cpi.
#[account(mut, seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(mut ,constraint = group_pda.authority == cpi_authority.key())]
pub group_pda: Account<'info, GroupAuthority>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (account compression program).
#[account(mut)]
pub registered_program_pda: AccountInfo<'info>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/initialize_tree_and_queue.rs
|
use account_compression::{
program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED, AddressMerkleTreeConfig,
AddressQueueConfig, NullifierQueueConfig, StateMerkleTreeConfig,
};
use anchor_lang::prelude::*;
use light_system_program::program::LightSystemProgram;
use crate::{
errors::RegistryError,
protocol_config::state::{ProtocolConfig, ProtocolConfigPda},
};
#[derive(Accounts)]
pub struct InitializeMerkleTreeAndQueue<'info> {
/// Anyone can create new trees just the fees cannot be set arbitrarily.
#[account(mut)]
pub authority: Signer<'info>,
/// CHECK: (account compression program).
#[account(mut)]
pub merkle_tree: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(mut)]
pub queue: AccountInfo<'info>,
/// CHECK: (account compression program) access control.
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: (seed constraints) used to invoke account compression program via cpi.
#[account(mut, seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority: AccountInfo<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
/// CHECK: (system program) new cpi context account.
pub cpi_context_account: Option<AccountInfo<'info>>,
pub light_system_program: Option<Program<'info, LightSystemProgram>>,
}
pub fn process_initialize_state_merkle_tree(
ctx: &Context<InitializeMerkleTreeAndQueue>,
bump: u8,
index: u64,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
merkle_tree_config: StateMerkleTreeConfig,
queue_config: NullifierQueueConfig,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::InitializeStateMerkleTreeAndNullifierQueue {
authority: ctx.accounts.cpi_authority.to_account_info(),
merkle_tree: ctx.accounts.merkle_tree.to_account_info(),
nullifier_queue: ctx.accounts.queue.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.clone()),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::initialize_state_merkle_tree_and_nullifier_queue(
cpi_ctx,
index,
program_owner,
forester,
merkle_tree_config,
queue_config,
0,
)
}
pub fn process_initialize_address_merkle_tree(
ctx: Context<InitializeMerkleTreeAndQueue>,
bump: u8,
index: u64,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
merkle_tree_config: AddressMerkleTreeConfig,
queue_config: AddressQueueConfig,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::InitializeAddressMerkleTreeAndQueue {
authority: ctx.accounts.cpi_authority.to_account_info(),
merkle_tree: ctx.accounts.merkle_tree.to_account_info(),
queue: ctx.accounts.queue.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.clone()),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::initialize_address_merkle_tree_and_queue(
cpi_ctx,
index,
program_owner,
forester,
merkle_tree_config,
queue_config,
)
}
pub fn process_initialize_cpi_context<'info>(
bump: u8,
fee_payer: AccountInfo<'info>,
cpi_context_account: AccountInfo<'info>,
associated_merkle_tree: AccountInfo<'info>,
light_system_program: AccountInfo<'info>,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = light_system_program::cpi::accounts::InitializeCpiContextAccount {
fee_payer,
cpi_context_account,
associated_merkle_tree,
};
let cpi_ctx = CpiContext::new_with_signer(light_system_program, accounts, signer_seeds);
light_system_program::cpi::init_cpi_context_account(cpi_ctx)
}
pub fn check_cpi_context(
account: AccountInfo<'_>,
protocol_config: &ProtocolConfig,
) -> Result<u64> {
let config_cpi_context_account_len = protocol_config.cpi_context_size as usize;
if account.data_len() != config_cpi_context_account_len {
return err!(RegistryError::CpiContextAccountInvalidDataLen);
}
let rent = Rent::get()?;
Ok(rent.minimum_balance(config_cpi_context_account_len))
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/nullify.rs
|
use account_compression::{
program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED, StateMerkleTreeAccount,
};
use anchor_lang::prelude::*;
use crate::epoch::register_epoch::ForesterEpochPda;
#[derive(Accounts)]
pub struct NullifyLeaves<'info> {
/// CHECK: only eligible foresters can nullify leaves. Is checked in ix.
#[account(mut)]
pub registered_forester_pda: Option<Account<'info, ForesterEpochPda>>,
pub authority: Signer<'info>,
/// CHECK: (seed constraints) used to invoke account compression program via cpi.
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority: AccountInfo<'info>,
/// CHECK: (account compression program) group access control.
pub registered_program_pda: AccountInfo<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (account compression program) when emitting event.
pub log_wrapper: UncheckedAccount<'info>,
/// CHECK: (account compression program).
#[account(mut)]
pub merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>,
/// CHECK: (account compression program).
#[account(mut)]
pub nullifier_queue: AccountInfo<'info>,
}
pub fn process_nullify(
ctx: &Context<NullifyLeaves>,
bump: u8,
change_log_indices: Vec<u64>,
leaves_queue_indices: Vec<u16>,
indices: Vec<u64>,
proofs: Vec<Vec<[u8; 32]>>,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::NullifyLeaves {
authority: ctx.accounts.cpi_authority.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
log_wrapper: ctx.accounts.log_wrapper.to_account_info(),
merkle_tree: ctx.accounts.merkle_tree.to_account_info(),
nullifier_queue: ctx.accounts.nullifier_queue.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::nullify_leaves(
cpi_ctx,
change_log_indices,
leaves_queue_indices,
indices,
proofs,
)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/sdk.rs
|
#![cfg(not(target_os = "solana"))]
use crate::utils::{
get_cpi_authority_pda, get_forester_epoch_pda_from_authority, get_protocol_config_pda_address,
};
use account_compression::utils::constants::NOOP_PUBKEY;
use account_compression::{
AddressMerkleTreeConfig, AddressQueueConfig, NullifierQueueConfig, StateMerkleTreeConfig,
};
use anchor_lang::prelude::*;
use anchor_lang::InstructionData;
use light_system_program::program::LightSystemProgram;
use solana_sdk::instruction::Instruction;
pub struct CreateNullifyInstructionInputs {
pub authority: Pubkey,
pub nullifier_queue: Pubkey,
pub merkle_tree: Pubkey,
pub change_log_indices: Vec<u64>,
pub leaves_queue_indices: Vec<u16>,
pub indices: Vec<u64>,
pub proofs: Vec<Vec<[u8; 32]>>,
pub derivation: Pubkey,
pub is_metadata_forester: bool,
}
pub fn create_nullify_instruction(
inputs: CreateNullifyInstructionInputs,
epoch: u64,
) -> Instruction {
let register_program_pda = get_registered_program_pda(&crate::ID);
let registered_forester_pda = if inputs.is_metadata_forester {
None
} else {
Some(get_forester_epoch_pda_from_authority(&inputs.derivation, epoch).0)
};
let (cpi_authority, bump) = get_cpi_authority_pda();
let instruction_data = crate::instruction::Nullify {
bump,
change_log_indices: inputs.change_log_indices,
leaves_queue_indices: inputs.leaves_queue_indices,
indices: inputs.indices,
proofs: inputs.proofs,
};
let accounts = crate::accounts::NullifyLeaves {
authority: inputs.authority,
registered_forester_pda,
registered_program_pda: register_program_pda,
nullifier_queue: inputs.nullifier_queue,
merkle_tree: inputs.merkle_tree,
log_wrapper: NOOP_PUBKEY.into(),
cpi_authority,
account_compression_program: account_compression::ID,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn get_registered_program_pda(program_id: &Pubkey) -> Pubkey {
Pubkey::find_program_address(
&[program_id.to_bytes().as_slice()],
&account_compression::ID,
)
.0
}
pub struct CreateRolloverMerkleTreeInstructionInputs {
pub authority: Pubkey,
pub derivation: Pubkey,
pub new_queue: Pubkey,
pub new_merkle_tree: Pubkey,
pub old_queue: Pubkey,
pub old_merkle_tree: Pubkey,
pub cpi_context_account: Option<Pubkey>,
pub is_metadata_forester: bool,
}
pub fn create_rollover_address_merkle_tree_instruction(
inputs: CreateRolloverMerkleTreeInstructionInputs,
epoch: u64,
) -> Instruction {
let (_, bump) = get_cpi_authority_pda();
let instruction_data = crate::instruction::RolloverAddressMerkleTreeAndQueue { bump };
let (cpi_authority, _) = get_cpi_authority_pda();
let registered_program_pda = get_registered_program_pda(&crate::ID);
let registered_forester_pda = if inputs.is_metadata_forester {
None
} else {
Some(get_forester_epoch_pda_from_authority(&inputs.derivation, epoch).0)
};
let accounts = crate::accounts::RolloverAddressMerkleTreeAndQueue {
account_compression_program: account_compression::ID,
registered_forester_pda,
cpi_authority,
authority: inputs.authority,
registered_program_pda,
new_merkle_tree: inputs.new_merkle_tree,
new_queue: inputs.new_queue,
old_merkle_tree: inputs.old_merkle_tree,
old_queue: inputs.old_queue,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_rollover_state_merkle_tree_instruction(
inputs: CreateRolloverMerkleTreeInstructionInputs,
epoch: u64,
) -> Instruction {
let (_, bump) = get_cpi_authority_pda();
let instruction_data = crate::instruction::RolloverStateMerkleTreeAndQueue { bump };
let (cpi_authority, _) = get_cpi_authority_pda();
let registered_program_pda = get_registered_program_pda(&crate::ID);
let registered_forester_pda = if inputs.is_metadata_forester {
None
} else {
Some(get_forester_epoch_pda_from_authority(&inputs.derivation, epoch).0)
};
let protocol_config_pda = get_protocol_config_pda_address().0;
let accounts = crate::accounts::RolloverStateMerkleTreeAndQueue {
account_compression_program: account_compression::ID,
registered_forester_pda,
cpi_authority,
authority: inputs.authority,
registered_program_pda,
new_merkle_tree: inputs.new_merkle_tree,
new_queue: inputs.new_queue,
old_merkle_tree: inputs.old_merkle_tree,
old_queue: inputs.old_queue,
cpi_context_account: inputs.cpi_context_account.unwrap(),
light_system_program: LightSystemProgram::id(),
protocol_config_pda,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub struct UpdateAddressMerkleTreeInstructionInputs {
pub authority: Pubkey,
pub derivation: Pubkey,
pub address_merkle_tree: Pubkey,
pub address_queue: Pubkey,
pub changelog_index: u16,
pub indexed_changelog_index: u16,
pub value: u16,
pub low_address_index: u64,
pub low_address_value: [u8; 32],
pub low_address_next_index: u64,
pub low_address_next_value: [u8; 32],
pub low_address_proof: [[u8; 32]; 16],
pub is_metadata_forester: bool,
}
pub fn create_update_address_merkle_tree_instruction(
inputs: UpdateAddressMerkleTreeInstructionInputs,
epoch: u64,
) -> Instruction {
let register_program_pda = get_registered_program_pda(&crate::ID);
let registered_forester_pda = if inputs.is_metadata_forester {
None
} else {
Some(get_forester_epoch_pda_from_authority(&inputs.derivation, epoch).0)
};
let (cpi_authority, bump) = get_cpi_authority_pda();
let instruction_data = crate::instruction::UpdateAddressMerkleTree {
bump,
changelog_index: inputs.changelog_index,
indexed_changelog_index: inputs.indexed_changelog_index,
value: inputs.value,
low_address_index: inputs.low_address_index,
low_address_value: inputs.low_address_value,
low_address_next_index: inputs.low_address_next_index,
low_address_next_value: inputs.low_address_next_value,
low_address_proof: inputs.low_address_proof,
};
let accounts = crate::accounts::UpdateAddressMerkleTree {
authority: inputs.authority,
registered_forester_pda,
registered_program_pda: register_program_pda,
merkle_tree: inputs.address_merkle_tree,
queue: inputs.address_queue,
log_wrapper: NOOP_PUBKEY.into(),
cpi_authority,
account_compression_program: account_compression::ID,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_initialize_address_merkle_tree_and_queue_instruction(
payer: Pubkey,
forester: Option<Pubkey>,
program_owner: Option<Pubkey>,
merkle_tree_pubkey: Pubkey,
queue_pubkey: Pubkey,
address_merkle_tree_config: AddressMerkleTreeConfig,
address_queue_config: AddressQueueConfig,
) -> Instruction {
let register_program_pda = get_registered_program_pda(&crate::ID);
let (cpi_authority, bump) = get_cpi_authority_pda();
let instruction_data = crate::instruction::InitializeAddressMerkleTree {
bump,
program_owner,
forester,
merkle_tree_config: address_merkle_tree_config,
queue_config: address_queue_config,
};
let protocol_config_pda = get_protocol_config_pda_address().0;
let accounts = crate::accounts::InitializeMerkleTreeAndQueue {
authority: payer,
registered_program_pda: register_program_pda,
merkle_tree: merkle_tree_pubkey,
queue: queue_pubkey,
cpi_authority,
account_compression_program: account_compression::ID,
protocol_config_pda,
light_system_program: None,
cpi_context_account: None,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_initialize_merkle_tree_instruction(
payer: Pubkey,
merkle_tree_pubkey: Pubkey,
nullifier_queue_pubkey: Pubkey,
cpi_context_pubkey: Pubkey,
state_merkle_tree_config: StateMerkleTreeConfig,
nullifier_queue_config: NullifierQueueConfig,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
) -> Instruction {
let register_program_pda = get_registered_program_pda(&crate::ID);
let (cpi_authority, bump) = get_cpi_authority_pda();
let protocol_config_pda = get_protocol_config_pda_address().0;
let instruction_data = crate::instruction::InitializeStateMerkleTree {
bump,
program_owner,
forester,
merkle_tree_config: state_merkle_tree_config,
queue_config: nullifier_queue_config,
};
let accounts = crate::accounts::InitializeMerkleTreeAndQueue {
authority: payer,
registered_program_pda: register_program_pda,
merkle_tree: merkle_tree_pubkey,
queue: nullifier_queue_pubkey,
cpi_authority,
account_compression_program: account_compression::ID,
protocol_config_pda,
light_system_program: Some(LightSystemProgram::id()),
cpi_context_account: Some(cpi_context_pubkey),
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/mod.rs
|
pub mod initialize_tree_and_queue;
pub mod nullify;
pub mod register_program;
pub mod rollover_state_tree;
pub mod sdk;
pub mod update_address_tree;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/account_compression_cpi/update_address_tree.rs
|
use account_compression::{
program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED, AddressMerkleTreeAccount,
};
use anchor_lang::prelude::*;
use crate::epoch::register_epoch::ForesterEpochPda;
#[derive(Accounts)]
pub struct UpdateAddressMerkleTree<'info> {
/// CHECK: only eligible foresters can nullify leaves. Is checked in ix.
#[account(mut)]
pub registered_forester_pda: Option<Account<'info, ForesterEpochPda>>,
/// CHECK:
pub authority: Signer<'info>,
/// CHECK: (seed constraints) used to invoke account compression program via cpi.
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority: AccountInfo<'info>,
/// CHECK: (account compression program) group access control.
pub registered_program_pda: AccountInfo<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (account compression program).
#[account(mut)]
pub queue: AccountInfo<'info>,
/// CHECK: (account compression program).
#[account(mut)]
pub merkle_tree: AccountLoader<'info, AddressMerkleTreeAccount>,
/// CHECK: when emitting event.
pub log_wrapper: UncheckedAccount<'info>,
}
pub fn process_update_address_merkle_tree(
ctx: &Context<UpdateAddressMerkleTree>,
bump: u8,
changelog_index: u16,
indexed_changelog_index: u16,
value: u16,
low_address_index: u64,
low_address_value: [u8; 32],
low_address_next_index: u64,
low_address_next_value: [u8; 32],
low_address_proof: [[u8; 32]; 16],
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::UpdateAddressMerkleTree {
authority: ctx.accounts.cpi_authority.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
log_wrapper: ctx.accounts.log_wrapper.to_account_info(),
queue: ctx.accounts.queue.to_account_info(),
merkle_tree: ctx.accounts.merkle_tree.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::update_address_merkle_tree(
cpi_ctx,
changelog_index,
indexed_changelog_index,
value,
low_address_index,
low_address_value,
low_address_next_index,
low_address_next_value,
low_address_proof,
)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/selection/forester.rs
|
use anchor_lang::prelude::*;
use anchor_lang::solana_program::pubkey::Pubkey;
use crate::constants::FORESTER_SEED;
use crate::protocol_config::state::ProtocolConfigPda;
use aligned_sized::aligned_sized;
#[aligned_sized(anchor)]
#[account]
#[derive(Debug, Default, Copy, PartialEq, Eq)]
pub struct ForesterPda {
pub authority: Pubkey,
pub config: ForesterConfig,
pub active_weight: u64,
/// Pending weight which will get active once the next epoch starts.
pub pending_weight: u64,
pub current_epoch: u64,
/// Link to previous compressed forester epoch account hash.
pub last_compressed_forester_epoch_pda_hash: [u8; 32],
pub last_registered_epoch: u64,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, AnchorDeserialize, AnchorSerialize)]
pub struct ForesterConfig {
/// Fee in percentage points.
pub fee: u64,
}
#[derive(Accounts)]
#[instruction(bump: u8, forester_authority: Pubkey)]
pub struct RegisterForester<'info> {
#[account(mut)]
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
#[account(has_one = authority)]
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
#[account(init, seeds = [FORESTER_SEED, forester_authority.as_ref()], bump, space =ForesterPda::LEN , payer = fee_payer)]
pub forester_pda: Account<'info, ForesterPda>,
system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateForesterPda<'info> {
pub authority: Signer<'info>,
/// CHECK:
#[account(mut, has_one = authority)]
pub forester_pda: Account<'info, ForesterPda>,
pub new_authority: Option<Signer<'info>>,
}
#[derive(Accounts)]
pub struct UpdateForesterPdaWeight<'info> {
pub authority: Signer<'info>,
#[account(has_one = authority)]
pub protocol_config_pda: Account<'info, ProtocolConfigPda>,
#[account(mut)]
pub forester_pda: Account<'info, ForesterPda>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/registry/src/selection/mod.rs
|
pub mod forester;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/Cargo.toml
|
[package]
name = "light-compressed-token"
version = "1.2.0"
description = "Generalized token compression on Solana"
repository = "https://github.com/Lightprotocol/light-protocol"
license = "Apache-2.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "light_compressed_token"
[features]
no-entrypoint = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
custom-heap = ["light-heap"]
mem-profiling = []
default = ["custom-heap", "idl-build"]
test-sbf = []
bench-sbf = []
cpi-context = []
idl-build = ["anchor-lang/idl-build", "anchor-spl/idl-build"]
[dependencies]
anchor-lang = { workspace = true }
anchor-spl = { workspace = true }
spl-token = { workspace = true, features = ["no-entrypoint"]}
aligned-sized = { version = "1.1.0", path = "../../macros/aligned-sized" }
account-compression = { version = "1.2.0", path = "../account-compression", features = ["cpi", "no-idl"] }
light-system-program = { version = "1.2.0", path = "../system", features = ["cpi"] }
solana-security-txt = "1.1.0"
light-hasher = { version = "1.1.0", path = "../../merkle-tree/hasher" }
light-heap = { version = "1.1.0", path = "../../heap", optional = true }
light-utils = { version = "1.1.0", path = "../../utils" }
spl-token-2022 = { workspace = true }
[target.'cfg(not(target_os = "solana"))'.dependencies]
solana-sdk = { workspace = true }
[dev-dependencies]
rand = "0.8.5"
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/README.md
|
# Compressed Token Program
A token program on the Solana blockchain using ZK Compression.
This program provides an interface and implementation that third parties can utilize to create and use compressed tokens on Solana.
Documentation is available at https://zkcompression.com
Source code: https://github.com/Lightprotocol/light-protocol/tree/main/programs/compressed-token
## Audit
This code is unaudited. Use at your own risk.
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/constants.rs
|
// 2 in little endian
pub const TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR: [u8; 8] = [2, 0, 0, 0, 0, 0, 0, 0];
pub const BUMP_CPI_AUTHORITY: u8 = 254;
pub const NOT_FROZEN: bool = false;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/token_data.rs
|
use std::vec;
use anchor_lang::{
prelude::borsh, solana_program::pubkey::Pubkey, AnchorDeserialize, AnchorSerialize,
};
use light_hasher::{errors::HasherError, DataHasher};
use light_utils::hash_to_bn254_field_size_be;
#[derive(Clone, Copy, Debug, PartialEq, Eq, AnchorSerialize, AnchorDeserialize)]
#[repr(u8)]
pub enum AccountState {
Initialized,
Frozen,
}
#[derive(Debug, PartialEq, Eq, AnchorSerialize, AnchorDeserialize, Clone)]
pub struct TokenData {
/// The mint associated with this account
pub mint: Pubkey,
/// The owner of this account.
pub owner: Pubkey,
/// The amount of tokens this account holds.
pub amount: u64,
/// If `delegate` is `Some` then `delegated_amount` represents
/// the amount authorized by the delegate
pub delegate: Option<Pubkey>,
/// The account's state
pub state: AccountState,
/// Placeholder for TokenExtension tlv data (unimplemented)
pub tlv: Option<Vec<u8>>,
}
/// Hashing schema: H(mint, owner, amount, delegate, delegated_amount,
/// is_native, state)
///
/// delegate, delegated_amount, is_native and state have dynamic positions.
/// Always hash mint, owner and amount If delegate hash delegate and
/// delegated_amount together. If is native hash is_native else is omitted.
/// If frozen hash AccountState::Frozen else is omitted.
///
/// Security: to prevent the possibility that different fields with the same
/// value to result in the same hash we add a prefix to the delegated amount, is
/// native and state fields. This way we can have a dynamic hashing schema and
/// hash only used values.
impl TokenData {
/// Only the spl representation of native tokens (wrapped SOL) is
/// compressed.
/// The sol value is stored in the token pool account.
/// The sol value in the compressed account is independent from
/// the wrapped sol amount.
pub fn is_native(&self) -> bool {
self.mint == spl_token::native_mint::id()
}
pub fn hash_with_hashed_values<H: light_hasher::Hasher>(
hashed_mint: &[u8; 32],
hashed_owner: &[u8; 32],
amount_bytes: &[u8; 8],
hashed_delegate: &Option<&[u8; 32]>,
) -> std::result::Result<[u8; 32], HasherError> {
Self::hash_inputs_with_hashed_values::<H, false>(
hashed_mint,
hashed_owner,
amount_bytes,
hashed_delegate,
)
}
pub fn hash_frozen_with_hashed_values<H: light_hasher::Hasher>(
hashed_mint: &[u8; 32],
hashed_owner: &[u8; 32],
amount_bytes: &[u8; 8],
hashed_delegate: &Option<&[u8; 32]>,
) -> std::result::Result<[u8; 32], HasherError> {
Self::hash_inputs_with_hashed_values::<H, true>(
hashed_mint,
hashed_owner,
amount_bytes,
hashed_delegate,
)
}
/// We should not hash pubkeys multiple times. For all we can assume mints
/// are equal. For all input compressed accounts we assume owners are
/// equal.
pub fn hash_inputs_with_hashed_values<H: light_hasher::Hasher, const FROZEN_INPUTS: bool>(
mint: &[u8; 32],
owner: &[u8; 32],
amount_bytes: &[u8; 8],
hashed_delegate: &Option<&[u8; 32]>,
) -> std::result::Result<[u8; 32], HasherError> {
let mut hash_inputs = vec![mint.as_slice(), owner.as_slice(), amount_bytes.as_slice()];
if let Some(hashed_delegate) = hashed_delegate {
hash_inputs.push(hashed_delegate.as_slice());
}
let state_bytes = [AccountState::Frozen as u8];
if FROZEN_INPUTS {
hash_inputs.push(&state_bytes[..]);
}
H::hashv(hash_inputs.as_slice())
}
}
impl DataHasher for TokenData {
fn hash<H: light_hasher::Hasher>(&self) -> std::result::Result<[u8; 32], HasherError> {
let hashed_mint = hash_to_bn254_field_size_be(self.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(self.owner.to_bytes().as_slice())
.unwrap()
.0;
let amount_bytes = self.amount.to_le_bytes();
let hashed_delegate;
let hashed_delegate_option = if let Some(delegate) = self.delegate {
hashed_delegate = hash_to_bn254_field_size_be(delegate.to_bytes().as_slice())
.unwrap()
.0;
Some(&hashed_delegate)
} else {
None
};
if self.state != AccountState::Initialized {
Self::hash_inputs_with_hashed_values::<H, true>(
&hashed_mint,
&hashed_owner,
&amount_bytes,
&hashed_delegate_option,
)
} else {
Self::hash_inputs_with_hashed_values::<H, false>(
&hashed_mint,
&hashed_owner,
&amount_bytes,
&hashed_delegate_option,
)
}
}
}
#[cfg(test)]
pub mod test {
use super::*;
use light_hasher::{Keccak, Poseidon};
use rand::Rng;
#[test]
fn equivalency_of_hash_functions() {
let token_data = TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
amount: 100,
delegate: Some(Pubkey::new_unique()),
state: AccountState::Initialized,
tlv: None,
};
let hashed_token_data = token_data.hash::<Poseidon>().unwrap();
let hashed_mint = hash_to_bn254_field_size_be(token_data.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(token_data.owner.to_bytes().as_slice())
.unwrap()
.0;
let hashed_delegate =
hash_to_bn254_field_size_be(token_data.delegate.unwrap().to_bytes().as_slice())
.unwrap()
.0;
let hashed_token_data_with_hashed_values =
TokenData::hash_inputs_with_hashed_values::<Poseidon, false>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&Some(&hashed_delegate),
)
.unwrap();
assert_eq!(hashed_token_data, hashed_token_data_with_hashed_values);
let token_data = TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
amount: 101,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let hashed_token_data = token_data.hash::<Poseidon>().unwrap();
let hashed_mint = hash_to_bn254_field_size_be(token_data.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(token_data.owner.to_bytes().as_slice())
.unwrap()
.0;
let hashed_token_data_with_hashed_values = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&None,
)
.unwrap();
assert_eq!(hashed_token_data, hashed_token_data_with_hashed_values);
}
fn equivalency_of_hash_functions_rnd_iters<H: light_hasher::Hasher, const ITERS: usize>() {
let mut rng = rand::thread_rng();
for _ in 0..ITERS {
let token_data = TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
amount: rng.gen(),
delegate: Some(Pubkey::new_unique()),
state: AccountState::Initialized,
tlv: None,
};
let hashed_token_data = token_data.hash::<H>().unwrap();
let hashed_mint = hash_to_bn254_field_size_be(token_data.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(token_data.owner.to_bytes().as_slice())
.unwrap()
.0;
let hashed_delegate =
hash_to_bn254_field_size_be(token_data.delegate.unwrap().to_bytes().as_slice())
.unwrap()
.0;
let hashed_token_data_with_hashed_values = TokenData::hash_with_hashed_values::<H>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&Some(&hashed_delegate),
)
.unwrap();
assert_eq!(hashed_token_data, hashed_token_data_with_hashed_values);
let token_data = TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
amount: rng.gen(),
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let hashed_token_data = token_data.hash::<H>().unwrap();
let hashed_mint = hash_to_bn254_field_size_be(token_data.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(token_data.owner.to_bytes().as_slice())
.unwrap()
.0;
let hashed_token_data_with_hashed_values: [u8; 32] =
TokenData::hash_with_hashed_values::<H>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&None,
)
.unwrap();
assert_eq!(hashed_token_data, hashed_token_data_with_hashed_values);
}
}
#[test]
fn equivalency_of_hash_functions_iters_poseidon() {
equivalency_of_hash_functions_rnd_iters::<Poseidon, 10_000>();
}
#[test]
fn equivalency_of_hash_functions_iters_keccak() {
equivalency_of_hash_functions_rnd_iters::<Keccak, 100_000>();
}
#[test]
fn test_frozen_equivalence() {
let token_data = TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
amount: 100,
delegate: Some(Pubkey::new_unique()),
state: AccountState::Initialized,
tlv: None,
};
let hashed_mint = hash_to_bn254_field_size_be(token_data.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(token_data.owner.to_bytes().as_slice())
.unwrap()
.0;
let hashed_delegate =
hash_to_bn254_field_size_be(token_data.delegate.unwrap().to_bytes().as_slice())
.unwrap()
.0;
let hash = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&Some(&hashed_delegate),
)
.unwrap();
let other_hash = token_data.hash::<Poseidon>().unwrap();
assert_eq!(hash, other_hash);
}
#[test]
fn failing_tests_hashing() {
let mut vec_previous_hashes = Vec::new();
let token_data = TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
amount: 100,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let hashed_mint = hash_to_bn254_field_size_be(token_data.mint.to_bytes().as_slice())
.unwrap()
.0;
let hashed_owner = hash_to_bn254_field_size_be(token_data.owner.to_bytes().as_slice())
.unwrap()
.0;
let hash = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&None,
)
.unwrap();
vec_previous_hashes.push(hash);
// different mint
let hashed_mint_2 = hash_to_bn254_field_size_be(Pubkey::new_unique().to_bytes().as_slice())
.unwrap()
.0;
let hash2 = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint_2,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&None,
)
.unwrap();
assert_to_previous_hashes(hash2, &mut vec_previous_hashes);
// different owner
let hashed_owner_2 =
hash_to_bn254_field_size_be(Pubkey::new_unique().to_bytes().as_slice())
.unwrap()
.0;
let hash3 = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint,
&hashed_owner_2,
&token_data.amount.to_le_bytes(),
&None,
)
.unwrap();
assert_to_previous_hashes(hash3, &mut vec_previous_hashes);
// different amount
let different_amount: u64 = 101;
let hash4 = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint,
&hashed_owner,
&different_amount.to_le_bytes(),
&None,
)
.unwrap();
assert_to_previous_hashes(hash4, &mut vec_previous_hashes);
// different delegate
let delegate = Some(Pubkey::new_unique());
let hashed_delegate = hash_to_bn254_field_size_be(delegate.unwrap().to_bytes().as_slice())
.unwrap()
.0;
let hash7 = TokenData::hash_with_hashed_values::<Poseidon>(
&hashed_mint,
&hashed_owner,
&token_data.amount.to_le_bytes(),
&Some(&hashed_delegate),
)
.unwrap();
assert_to_previous_hashes(hash7, &mut vec_previous_hashes);
// different account state
let mut token_data = token_data;
token_data.state = AccountState::Frozen;
let hash9 = token_data.hash::<Poseidon>().unwrap();
assert_to_previous_hashes(hash9, &mut vec_previous_hashes);
// different account state with delegate
token_data.delegate = delegate;
let hash10 = token_data.hash::<Poseidon>().unwrap();
assert_to_previous_hashes(hash10, &mut vec_previous_hashes);
}
fn assert_to_previous_hashes(hash: [u8; 32], previous_hashes: &mut Vec<[u8; 32]>) {
for previous_hash in previous_hashes.iter() {
assert_ne!(hash, *previous_hash);
}
println!("len previous hashes: {}", previous_hashes.len());
previous_hashes.push(hash);
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/lib.rs
|
use anchor_lang::prelude::*;
pub mod constants;
pub mod process_compress_spl_token_account;
pub mod process_mint;
pub mod process_transfer;
use process_compress_spl_token_account::process_compress_spl_token_account;
pub mod spl_compression;
pub use process_mint::*;
pub mod token_data;
pub use token_data::TokenData;
pub mod delegation;
pub mod freeze;
pub mod instructions;
pub use instructions::*;
pub mod burn;
use crate::process_transfer::CompressedTokenInstructionDataTransfer;
pub use burn::*;
use light_system_program::sdk::CompressedCpiContext;
declare_id!("cTokenmWW8bLPjZEBAUgYy3zKxQZW6VKi7bqNFEVv3m");
#[cfg(not(feature = "no-entrypoint"))]
solana_security_txt::security_txt! {
name: "light-compressed-token",
project_url: "lightprotocol.com",
contacts: "email:security@lightprotocol.com",
policy: "https://github.com/Lightprotocol/light-protocol/blob/main/SECURITY.md",
source_code: "https://github.com/Lightprotocol/light-protocol"
}
#[program]
pub mod light_compressed_token {
use super::*;
use constants::NOT_FROZEN;
/// This instruction creates a token pool for a given mint. Every spl mint
/// can have one token pool. When a token is compressed the tokens are
/// transferrred to the token pool, and their compressed equivalent is
/// minted into a Merkle tree.
pub fn create_token_pool<'info>(
ctx: Context<'_, '_, '_, 'info, CreateTokenPoolInstruction<'info>>,
) -> Result<()> {
create_token_pool::assert_mint_extensions(
&ctx.accounts.mint.to_account_info().try_borrow_data()?,
)
}
/// Mints tokens from an spl token mint to a list of compressed accounts.
/// Minted tokens are transferred to a pool account owned by the compressed
/// token program. The instruction creates one compressed output account for
/// every amount and pubkey input pair. A constant amount of lamports can be
/// transferred to each output account to enable. A use case to add lamports
/// to a compressed token account is to prevent spam. This is the only way
/// to add lamports to a compressed token account.
pub fn mint_to<'info>(
ctx: Context<'_, '_, '_, 'info, MintToInstruction<'info>>,
public_keys: Vec<Pubkey>,
amounts: Vec<u64>,
lamports: Option<u64>,
) -> Result<()> {
process_mint_to(ctx, public_keys, amounts, lamports)
}
/// Compresses the balance of an spl token account sub an optional remaining
/// amount. This instruction does not close the spl token account. To close
/// the account bundle a close spl account instruction in your transaction.
pub fn compress_spl_token_account<'info>(
ctx: Context<'_, '_, '_, 'info, TransferInstruction<'info>>,
owner: Pubkey,
remaining_amount: Option<u64>,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
process_compress_spl_token_account(ctx, owner, remaining_amount, cpi_context)
}
/// Transfers compressed tokens from one account to another. All accounts
/// must be of the same mint. Additional spl tokens can be compressed or
/// decompressed. In one transaction only compression or decompression is
/// possible. Lamports can be transferred alongside tokens. If output token
/// accounts specify less lamports than inputs the remaining lamports are
/// transferred to an output compressed account. Signer must be owner or
/// delegate. If a delegated token account is transferred the delegate is
/// not preserved.
pub fn transfer<'info>(
ctx: Context<'_, '_, '_, 'info, TransferInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
let inputs: CompressedTokenInstructionDataTransfer =
CompressedTokenInstructionDataTransfer::deserialize(&mut inputs.as_slice())?;
process_transfer::process_transfer(ctx, inputs)
}
/// Delegates an amount to a delegate. A compressed token account is either
/// completely delegated or not. Prior delegates are not preserved. Cannot
/// be called by a delegate.
/// The instruction creates two output accounts:
/// 1. one account with delegated amount
/// 2. one account with remaining(change) amount
pub fn approve<'info>(
ctx: Context<'_, '_, '_, 'info, GenericInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
delegation::process_approve(ctx, inputs)
}
/// Revokes a delegation. The instruction merges all inputs into one output
/// account. Cannot be called by a delegate. Delegates are not preserved.
pub fn revoke<'info>(
ctx: Context<'_, '_, '_, 'info, GenericInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
delegation::process_revoke(ctx, inputs)
}
/// Freezes compressed token accounts. Inputs must not be frozen. Creates as
/// many outputs as inputs. Balances and delegates are preserved.
pub fn freeze<'info>(
ctx: Context<'_, '_, '_, 'info, FreezeInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
// Inputs are not frozen, outputs are frozen.
freeze::process_freeze_or_thaw::<NOT_FROZEN, true>(ctx, inputs)
}
/// Thaws frozen compressed token accounts. Inputs must be frozen. Creates
/// as many outputs as inputs. Balances and delegates are preserved.
pub fn thaw<'info>(
ctx: Context<'_, '_, '_, 'info, FreezeInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
// Inputs are frozen, outputs are not frozen.
freeze::process_freeze_or_thaw::<true, NOT_FROZEN>(ctx, inputs)
}
/// Burns compressed tokens and spl tokens from the pool account. Delegates
/// can burn tokens. The output compressed token account remains delegated.
/// Creates one output compressed token account.
pub fn burn<'info>(
ctx: Context<'_, '_, '_, 'info, BurnInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
burn::process_burn(ctx, inputs)
}
/// This function is a stub to allow Anchor to include the input types in
/// the IDL. It should not be included in production builds nor be called in
/// practice.
#[cfg(feature = "idl-build")]
pub fn stub_idl_build<'info>(
_ctx: Context<'_, '_, '_, 'info, TransferInstruction<'info>>,
_inputs1: CompressedTokenInstructionDataTransfer,
_inputs2: TokenData,
) -> Result<()> {
Err(ErrorCode::InstructionNotCallable.into())
}
}
#[error_code]
pub enum ErrorCode {
#[msg("public keys and amounts must be of same length")]
PublicKeyAmountMissmatch,
#[msg("ComputeInputSumFailed")]
ComputeInputSumFailed,
#[msg("ComputeOutputSumFailed")]
ComputeOutputSumFailed,
#[msg("ComputeCompressSumFailed")]
ComputeCompressSumFailed,
#[msg("ComputeDecompressSumFailed")]
ComputeDecompressSumFailed,
#[msg("SumCheckFailed")]
SumCheckFailed,
#[msg("DecompressRecipientUndefinedForDecompress")]
DecompressRecipientUndefinedForDecompress,
#[msg("CompressedPdaUndefinedForDecompress")]
CompressedPdaUndefinedForDecompress,
#[msg("DeCompressAmountUndefinedForDecompress")]
DeCompressAmountUndefinedForDecompress,
#[msg("CompressedPdaUndefinedForCompress")]
CompressedPdaUndefinedForCompress,
#[msg("DeCompressAmountUndefinedForCompress")]
DeCompressAmountUndefinedForCompress,
#[msg("DelegateSignerCheckFailed")]
DelegateSignerCheckFailed,
#[msg("Minted amount greater than u64::MAX")]
MintTooLarge,
#[msg("SplTokenSupplyMismatch")]
SplTokenSupplyMismatch,
#[msg("HeapMemoryCheckFailed")]
HeapMemoryCheckFailed,
#[msg("The instruction is not callable")]
InstructionNotCallable,
#[msg("ArithmeticUnderflow")]
ArithmeticUnderflow,
#[msg("HashToFieldError")]
HashToFieldError,
#[msg("Expected the authority to be also a mint authority")]
InvalidAuthorityMint,
#[msg("Provided authority is not the freeze authority")]
InvalidFreezeAuthority,
InvalidDelegateIndex,
TokenPoolPdaUndefined,
#[msg("Compress or decompress recipient is the same account as the token pool pda.")]
IsTokenPoolPda,
InvalidTokenPoolPda,
NoInputTokenAccountsProvided,
NoInputsProvided,
MintHasNoFreezeAuthority,
MintWithInvalidExtension,
#[msg("The token account balance is less than the remaining amount.")]
InsufficientTokenAccountBalance,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/process_compress_spl_token_account.rs
|
use super::TransferInstruction;
use crate::{
process_transfer::{
process_transfer, CompressedTokenInstructionDataTransfer, PackedTokenTransferOutputData,
},
ErrorCode,
};
use anchor_lang::prelude::*;
use light_system_program::sdk::CompressedCpiContext;
pub fn process_compress_spl_token_account<'info>(
ctx: Context<'_, '_, '_, 'info, TransferInstruction<'info>>,
owner: Pubkey,
remaining_amount: Option<u64>,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
let compression_token_account =
if let Some(token_account) = ctx.accounts.compress_or_decompress_token_account.as_ref() {
token_account
} else {
return err!(ErrorCode::CompressedPdaUndefinedForCompress);
};
let compress_amount = compression_token_account
.amount
.checked_sub(remaining_amount.unwrap_or_default())
.ok_or(crate::ErrorCode::InsufficientTokenAccountBalance)?;
let compressed_output_account = PackedTokenTransferOutputData {
owner,
lamports: None,
amount: compress_amount,
tlv: None,
merkle_tree_index: 0,
};
let inputs = CompressedTokenInstructionDataTransfer {
proof: None,
mint: compression_token_account.mint,
delegated_transfer: None,
is_compress: true,
input_token_data_with_context: Vec::new(),
output_compressed_accounts: vec![compressed_output_account],
cpi_context,
lamports_change_account_merkle_tree_index: None,
compress_or_decompress_amount: Some(compress_amount),
};
process_transfer(ctx, inputs)
}
#[cfg(not(target_os = "solana"))]
pub mod sdk {
use crate::get_token_pool_pda;
use anchor_lang::prelude::AccountMeta;
use anchor_lang::InstructionData;
use anchor_lang::ToAccountMetas;
use anchor_spl::token::ID as TokenProgramId;
use light_system_program::sdk::CompressedCpiContext;
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
#[allow(clippy::too_many_arguments)]
pub fn create_compress_spl_token_account_instruction(
owner: &Pubkey,
remaining_amount: Option<u64>,
cpi_context: Option<CompressedCpiContext>,
fee_payer: &Pubkey,
authority: &Pubkey,
mint: &Pubkey,
output_merkle_tree: &Pubkey,
token_account: &Pubkey,
is_token_22: bool,
) -> Instruction {
let instruction_data = crate::instruction::CompressSplTokenAccount {
owner: *owner,
remaining_amount,
cpi_context,
};
let (cpi_authority_pda, _) = crate::process_transfer::get_cpi_authority_pda();
let token_pool_pda = get_token_pool_pda(mint);
let token_program = if is_token_22 {
Some(anchor_spl::token_2022::ID)
} else {
Some(TokenProgramId)
};
let accounts = crate::accounts::TransferInstruction {
fee_payer: *fee_payer,
authority: *authority,
cpi_authority_pda,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
self_program: crate::ID,
token_pool_pda: Some(token_pool_pda),
compress_or_decompress_token_account: Some(*token_account),
token_program,
system_program: solana_sdk::system_program::ID,
};
let remaining_accounts = vec![AccountMeta::new(*output_merkle_tree, false)];
Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/process_mint.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{Mint, TokenAccount, TokenInterface};
use light_system_program::{program::LightSystemProgram, OutputCompressedAccountWithPackedContext};
use crate::{program::LightCompressedToken, POOL_SEED};
#[cfg(target_os = "solana")]
use {
crate::process_transfer::create_output_compressed_accounts,
crate::process_transfer::get_cpi_signer_seeds,
light_heap::{bench_sbf_end, bench_sbf_start, GLOBAL_ALLOCATOR},
light_utils::hash_to_bn254_field_size_be,
};
/// Mints tokens from an spl token mint to a list of compressed accounts and
/// stores minted tokens in spl token pool account.
///
/// Steps:
/// 1. Allocate memory for cpi instruction data. We allocate memory in the
/// beginning so that we can free all memory of the allocation prior to the
/// cpi in cpi_execute_compressed_transaction_mint_to.
/// 2. Mint SPL tokens to pool account.
/// 3. Create output compressed accounts, one for every pubkey and amount pair.
/// 4. Serialize cpi instruction data and free memory up to
/// pre_compressed_acounts_pos.
/// 5. Invoke system program to execute the compressed transaction.
#[allow(unused_variables)]
pub fn process_mint_to(
ctx: Context<MintToInstruction>,
recipient_pubkeys: Vec<Pubkey>,
amounts: Vec<u64>,
lamports: Option<u64>,
) -> Result<()> {
if recipient_pubkeys.len() != amounts.len() {
msg!(
"recipient_pubkeys.len() {} != {} amounts.len()",
recipient_pubkeys.len(),
amounts.len()
);
return err!(crate::ErrorCode::PublicKeyAmountMissmatch);
} else if recipient_pubkeys.is_empty() {
msg!("recipient_pubkeys is empty");
return err!(crate::ErrorCode::NoInputsProvided);
}
#[cfg(target_os = "solana")]
{
let option_compression_lamports = if lamports.unwrap_or(0) == 0 { 0 } else { 8 };
let inputs_len =
1 + 4 + 4 + 4 + amounts.len() * 162 + 1 + 1 + 1 + 1 + option_compression_lamports;
// inputs_len =
// 1 Option<Proof>
// + 4 Vec::new()
// + 4 Vec::new()
// + 4 + amounts.len() * 162 Vec<OutputCompressedAccountWithPackedContext>
// + 1 Option<relay_fee>
// + 1 + 8 Option<compression_lamports>
// + 1 is_compress
// + 1 Option<CpiContextAccount>
let mut inputs = Vec::<u8>::with_capacity(inputs_len);
// # SAFETY: the inputs vector needs to be allocated before this point.
// All heap memory from this point on is freed prior to the cpi call.
let pre_compressed_acounts_pos = GLOBAL_ALLOCATOR.get_heap_pos();
bench_sbf_start!("tm_mint_spl_to_pool_pda");
// 7,912 CU
mint_spl_to_pool_pda(&ctx, &amounts)?;
bench_sbf_end!("tm_mint_spl_to_pool_pda");
let hashed_mint = hash_to_bn254_field_size_be(ctx.accounts.mint.key().as_ref())
.unwrap()
.0;
bench_sbf_start!("tm_output_compressed_accounts");
let mut output_compressed_accounts =
vec![OutputCompressedAccountWithPackedContext::default(); recipient_pubkeys.len()];
let lamports_vec = lamports.map(|_| vec![lamports; amounts.len()]);
create_output_compressed_accounts(
&mut output_compressed_accounts,
ctx.accounts.mint.key(),
recipient_pubkeys.as_slice(),
None,
None,
&amounts,
lamports_vec,
&hashed_mint,
// We ensure that the Merkle tree account is the first
// remaining account in the cpi to the system program.
&vec![0; amounts.len()],
)?;
bench_sbf_end!("tm_output_compressed_accounts");
cpi_execute_compressed_transaction_mint_to(
&ctx,
output_compressed_accounts,
&mut inputs,
pre_compressed_acounts_pos,
)?;
// # SAFETY: the inputs vector needs to be allocated before this point.
// This error should never be triggered.
if inputs.len() != inputs_len {
msg!(
"Used memory {} is unequal allocated {} memory",
inputs.len(),
inputs_len
);
return err!(crate::ErrorCode::HeapMemoryCheckFailed);
}
}
Ok(())
}
#[cfg(target_os = "solana")]
#[inline(never)]
pub fn cpi_execute_compressed_transaction_mint_to<'info>(
ctx: &Context<'_, '_, '_, 'info, MintToInstruction>,
output_compressed_accounts: Vec<OutputCompressedAccountWithPackedContext>,
inputs: &mut Vec<u8>,
pre_compressed_acounts_pos: usize,
) -> Result<()> {
bench_sbf_start!("tm_cpi");
let signer_seeds = get_cpi_signer_seeds();
// 4300 CU for 10 accounts
// 6700 CU for 20 accounts
// 7,978 CU for 25 accounts
serialize_mint_to_cpi_instruction_data(inputs, &output_compressed_accounts);
GLOBAL_ALLOCATOR.free_heap(pre_compressed_acounts_pos)?;
use anchor_lang::InstructionData;
// 826 CU
let instructiondata = light_system_program::instruction::InvokeCpi {
inputs: inputs.to_owned(),
};
let (sol_pool_pda, is_writable) = if let Some(pool_pda) = ctx.accounts.sol_pool_pda.as_ref() {
// Account is some
(pool_pda.to_account_info(), true)
} else {
// Account is None
(ctx.accounts.light_system_program.to_account_info(), false)
};
// 1300 CU
let account_infos = vec![
ctx.accounts.fee_payer.to_account_info(),
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts.registered_program_pda.to_account_info(),
ctx.accounts.noop_program.to_account_info(),
ctx.accounts.account_compression_authority.to_account_info(),
ctx.accounts.account_compression_program.to_account_info(),
ctx.accounts.self_program.to_account_info(),
sol_pool_pda,
ctx.accounts.light_system_program.to_account_info(), // none compression_recipient
ctx.accounts.system_program.to_account_info(),
ctx.accounts.light_system_program.to_account_info(), // none cpi_context_account
ctx.accounts.merkle_tree.to_account_info(), // first remaining account
];
// account_metas take 1k cu
let accounts = vec![
AccountMeta {
pubkey: account_infos[0].key(),
is_signer: true,
is_writable: true,
},
AccountMeta {
pubkey: account_infos[1].key(),
is_signer: true,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[2].key(),
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[3].key(),
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[4].key(),
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[5].key(),
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[6].key(),
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[7].key(),
is_signer: false,
is_writable,
},
AccountMeta {
pubkey: account_infos[8].key(),
is_signer: false,
is_writable: false,
},
AccountMeta::new_readonly(account_infos[9].key(), false),
AccountMeta {
pubkey: account_infos[10].key(),
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: account_infos[11].key(),
is_signer: false,
is_writable: true,
},
];
let instruction = anchor_lang::solana_program::instruction::Instruction {
program_id: light_system_program::ID,
accounts,
data: instructiondata.data(),
};
bench_sbf_end!("tm_cpi");
bench_sbf_start!("tm_invoke");
anchor_lang::solana_program::program::invoke_signed(
&instruction,
account_infos.as_slice(),
&[&signer_seeds[..]],
)?;
bench_sbf_end!("tm_invoke");
Ok(())
}
#[inline(never)]
pub fn serialize_mint_to_cpi_instruction_data(
inputs: &mut Vec<u8>,
output_compressed_accounts: &[OutputCompressedAccountWithPackedContext],
) {
let len = output_compressed_accounts.len();
// proof (option None)
inputs.extend_from_slice(&[0u8]);
// two empty vecs 4 bytes of zeroes each: address_params,
// input_compressed_accounts_with_merkle_context
inputs.extend_from_slice(&[0u8; 8]);
// lenght of output_compressed_accounts vec as u32
inputs.extend_from_slice(&[(len as u8), 0, 0, 0]);
let mut sum_lamports = 0u64;
// output_compressed_accounts
for compressed_account in output_compressed_accounts.iter() {
compressed_account.serialize(inputs).unwrap();
sum_lamports = sum_lamports
.checked_add(compressed_account.compressed_account.lamports)
.unwrap();
}
// None relay_fee
inputs.extend_from_slice(&[0u8; 1]);
if sum_lamports != 0 {
inputs.extend_from_slice(&[1u8; 1]);
inputs.extend_from_slice(&sum_lamports.to_le_bytes());
inputs.extend_from_slice(&[1u8; 1]); // is compress bool = true
} else {
inputs.extend_from_slice(&[0u8; 2]); // None compression lamports, is compress bool = false
}
// None compressed_cpi_context
inputs.extend_from_slice(&[0u8]);
}
#[inline(never)]
pub fn mint_spl_to_pool_pda(ctx: &Context<MintToInstruction>, amounts: &[u64]) -> Result<()> {
let mut mint_amount: u64 = 0;
for amount in amounts.iter() {
mint_amount = mint_amount
.checked_add(*amount)
.ok_or(crate::ErrorCode::MintTooLarge)?;
}
let pre_token_balance = ctx.accounts.token_pool_pda.amount;
let cpi_accounts = anchor_spl::token_interface::MintTo {
mint: ctx.accounts.mint.to_account_info(),
to: ctx.accounts.token_pool_pda.to_account_info(),
authority: ctx.accounts.authority.to_account_info(),
};
let cpi_ctx = CpiContext::new(ctx.accounts.token_program.to_account_info(), cpi_accounts);
anchor_spl::token_interface::mint_to(cpi_ctx, mint_amount)?;
let post_token_balance = TokenAccount::try_deserialize(
&mut &ctx.accounts.token_pool_pda.to_account_info().data.borrow()[..],
)?
.amount;
// Guard against unexpected behavior of the SPL token program.
if post_token_balance != pre_token_balance + mint_amount {
msg!(
"post_token_balance {} != pre_token_balance {} + mint_amount {}",
post_token_balance,
pre_token_balance,
mint_amount
);
return err!(crate::ErrorCode::SplTokenSupplyMismatch);
}
Ok(())
}
#[derive(Accounts)]
pub struct MintToInstruction<'info> {
/// UNCHECKED: only pays fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
/// CHECK: is checked by mint account macro.
pub authority: Signer<'info>,
/// CHECK:
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority_pda: UncheckedAccount<'info>,
#[account(
mut,
constraint = mint.mint_authority.unwrap() == authority.key()
@ crate::ErrorCode::InvalidAuthorityMint
)]
pub mint: InterfaceAccount<'info, Mint>,
#[account(mut, seeds = [POOL_SEED, mint.key().as_ref()], bump)]
pub token_pool_pda: InterfaceAccount<'info, TokenAccount>,
pub token_program: Interface<'info, TokenInterface>,
pub light_system_program: Program<'info, LightSystemProgram>,
/// CHECK: (different program) checked in account compression program
pub registered_program_pda: UncheckedAccount<'info>,
/// CHECK: (different program) checked in system and account compression
/// programs
pub noop_program: UncheckedAccount<'info>,
/// CHECK: this account in account compression program
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump, seeds::program = light_system_program::ID)]
pub account_compression_authority: UncheckedAccount<'info>,
/// CHECK: this account in account compression program
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (different program) will be checked by the system program
#[account(mut)]
pub merkle_tree: UncheckedAccount<'info>,
/// CHECK: (different program) will be checked by the system program
pub self_program: Program<'info, LightCompressedToken>,
pub system_program: Program<'info, System>,
/// CHECK: (different program) will be checked by the system program
#[account(mut)]
pub sol_pool_pda: Option<AccountInfo<'info>>,
}
#[cfg(not(target_os = "solana"))]
pub mod mint_sdk {
use crate::{get_token_pool_pda, process_transfer::get_cpi_authority_pda};
use anchor_lang::{system_program, InstructionData, ToAccountMetas};
use light_system_program::sdk::invoke::get_sol_pool_pda;
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
pub fn create_create_token_pool_instruction(
fee_payer: &Pubkey,
mint: &Pubkey,
is_token_22: bool,
) -> Instruction {
let token_pool_pda = get_token_pool_pda(mint);
let instruction_data = crate::instruction::CreateTokenPool {};
let token_program: Pubkey = if is_token_22 {
anchor_spl::token_2022::ID
} else {
anchor_spl::token::ID
};
let accounts = crate::accounts::CreateTokenPoolInstruction {
fee_payer: *fee_payer,
token_pool_pda,
system_program: system_program::ID,
mint: *mint,
token_program,
cpi_authority_pda: get_cpi_authority_pda().0,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
#[allow(clippy::too_many_arguments)]
pub fn create_mint_to_instruction(
fee_payer: &Pubkey,
authority: &Pubkey,
mint: &Pubkey,
merkle_tree: &Pubkey,
amounts: Vec<u64>,
public_keys: Vec<Pubkey>,
lamports: Option<u64>,
token_2022: bool,
) -> Instruction {
let token_pool_pda = get_token_pool_pda(mint);
let instruction_data = crate::instruction::MintTo {
amounts,
public_keys,
lamports,
};
let sol_pool_pda = if lamports.is_some() {
Some(get_sol_pool_pda())
} else {
None
};
let token_program = if token_2022 {
anchor_spl::token_2022::ID
} else {
anchor_spl::token::ID
};
let accounts = crate::accounts::MintToInstruction {
fee_payer: *fee_payer,
authority: *authority,
cpi_authority_pda: get_cpi_authority_pda().0,
mint: *mint,
token_pool_pda,
token_program,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
merkle_tree: *merkle_tree,
self_program: crate::ID,
system_program: system_program::ID,
sol_pool_pda,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
constants::TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
token_data::{AccountState, TokenData},
};
use light_hasher::Poseidon;
use light_system_program::{
sdk::compressed_account::{CompressedAccount, CompressedAccountData},
OutputCompressedAccountWithPackedContext,
};
#[test]
fn test_manual_ix_data_serialization_borsh_compat() {
let pubkeys = vec![Pubkey::new_unique(), Pubkey::new_unique()];
let amounts = vec![1, 2];
let mint_pubkey = Pubkey::new_unique();
let mut output_compressed_accounts =
vec![OutputCompressedAccountWithPackedContext::default(); pubkeys.len()];
for (i, (pubkey, amount)) in pubkeys.iter().zip(amounts.iter()).enumerate() {
let mut token_data_bytes = Vec::with_capacity(std::mem::size_of::<TokenData>());
let token_data = TokenData {
mint: mint_pubkey,
owner: *pubkey,
amount: *amount,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
token_data.serialize(&mut token_data_bytes).unwrap();
use light_hasher::DataHasher;
let data: CompressedAccountData = CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data: token_data_bytes,
data_hash: token_data.hash::<Poseidon>().unwrap(),
};
let lamports = 0;
output_compressed_accounts[i] = OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: crate::ID,
lamports,
data: Some(data),
address: None,
},
merkle_tree_index: 0,
};
}
let mut inputs = Vec::<u8>::new();
serialize_mint_to_cpi_instruction_data(&mut inputs, &output_compressed_accounts);
let inputs_struct = light_system_program::InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context: Vec::with_capacity(0),
output_compressed_accounts: output_compressed_accounts.clone(),
proof: None,
new_address_params: Vec::with_capacity(0),
compress_or_decompress_lamports: None,
is_compress: false,
cpi_context: None,
};
let mut reference = Vec::<u8>::new();
inputs_struct.serialize(&mut reference).unwrap();
assert_eq!(inputs.len(), reference.len());
for (j, i) in inputs.iter().zip(reference.iter()).enumerate() {
println!("j: {} i: {} {}", j, i.0, i.1);
assert_eq!(i.0, i.1);
}
assert_eq!(inputs, reference);
}
#[test]
fn test_manual_ix_data_serialization_borsh_compat_random() {
use rand::Rng;
for _ in 0..10000 {
let mut rng = rand::thread_rng();
let pubkeys = vec![Pubkey::new_unique(), Pubkey::new_unique()];
let amounts = vec![rng.gen_range(0..1_000_000_000_000), rng.gen_range(1..100)];
let mint_pubkey = Pubkey::new_unique();
let mut output_compressed_accounts =
vec![OutputCompressedAccountWithPackedContext::default(); pubkeys.len()];
for (i, (pubkey, amount)) in pubkeys.iter().zip(amounts.iter()).enumerate() {
let mut token_data_bytes = Vec::with_capacity(std::mem::size_of::<TokenData>());
let token_data = TokenData {
mint: mint_pubkey,
owner: *pubkey,
amount: *amount,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
token_data.serialize(&mut token_data_bytes).unwrap();
use light_hasher::DataHasher;
let data: CompressedAccountData = CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data: token_data_bytes,
data_hash: token_data.hash::<Poseidon>().unwrap(),
};
let lamports = rng.gen_range(0..1_000_000_000_000);
output_compressed_accounts[i] = OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: crate::ID,
lamports,
data: Some(data),
address: None,
},
merkle_tree_index: 0,
};
}
let mut inputs = Vec::<u8>::new();
serialize_mint_to_cpi_instruction_data(&mut inputs, &output_compressed_accounts);
let sum = output_compressed_accounts
.iter()
.map(|x| x.compressed_account.lamports)
.sum::<u64>();
let inputs_struct = light_system_program::InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context: Vec::with_capacity(0),
output_compressed_accounts: output_compressed_accounts.clone(),
proof: None,
new_address_params: Vec::with_capacity(0),
compress_or_decompress_lamports: Some(sum),
is_compress: true,
cpi_context: None,
};
let mut reference = Vec::<u8>::new();
inputs_struct.serialize(&mut reference).unwrap();
assert_eq!(inputs.len(), reference.len());
for (_, i) in inputs.iter().zip(reference.iter()).enumerate() {
assert_eq!(i.0, i.1);
}
assert_eq!(inputs, reference);
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/process_transfer.rs
|
use crate::{
constants::{BUMP_CPI_AUTHORITY, NOT_FROZEN, TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR},
spl_compression::process_compression_or_decompression,
token_data::{AccountState, TokenData},
ErrorCode, TransferInstruction,
};
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED;
use anchor_lang::{prelude::*, solana_program::program_error::ProgramError, AnchorDeserialize};
use light_hasher::Poseidon;
use light_heap::{bench_sbf_end, bench_sbf_start};
use light_system_program::{
invoke::processor::CompressedProof,
sdk::{
accounts::{InvokeAccounts, SignerAccounts},
compressed_account::{
CompressedAccount, CompressedAccountData, PackedCompressedAccountWithMerkleContext,
PackedMerkleContext,
},
CompressedCpiContext,
},
InstructionDataInvokeCpi, OutputCompressedAccountWithPackedContext,
};
use light_utils::hash_to_bn254_field_size_be;
/// Process a token transfer instruction
/// build inputs -> sum check -> build outputs -> add token data to inputs -> invoke cpi
/// 1. Unpack compressed input accounts and input token data, this uses
/// standardized signer / delegate and will fail in proof verification in
/// case either is invalid.
/// 2. Check that compressed accounts are of same mint.
/// 3. Check that sum of input compressed accounts is equal to sum of output
/// compressed accounts
/// 4. create_output_compressed_accounts
/// 5. Serialize and add token_data data to in compressed_accounts.
/// 6. Invoke light_system_program::execute_compressed_transaction.
#[inline(always)]
pub fn process_transfer<'a, 'b, 'c, 'info: 'b + 'c>(
ctx: Context<'a, 'b, 'c, 'info, TransferInstruction<'info>>,
inputs: CompressedTokenInstructionDataTransfer,
) -> Result<()> {
bench_sbf_start!("t_context_and_check_sig");
if inputs.input_token_data_with_context.is_empty()
&& inputs.compress_or_decompress_amount.is_none()
{
return err!(crate::ErrorCode::NoInputTokenAccountsProvided);
}
let (mut compressed_input_accounts, input_token_data, input_lamports) =
get_input_compressed_accounts_with_merkle_context_and_check_signer::<NOT_FROZEN>(
&ctx.accounts.authority.key(),
&inputs.delegated_transfer,
ctx.remaining_accounts,
&inputs.input_token_data_with_context,
&inputs.mint,
)?;
bench_sbf_end!("t_context_and_check_sig");
bench_sbf_start!("t_sum_check");
sum_check(
&input_token_data,
&inputs
.output_compressed_accounts
.iter()
.map(|data| data.amount)
.collect::<Vec<u64>>(),
inputs.compress_or_decompress_amount.as_ref(),
inputs.is_compress,
)?;
bench_sbf_end!("t_sum_check");
bench_sbf_start!("t_process_compression");
if inputs.compress_or_decompress_amount.is_some() {
process_compression_or_decompression(&inputs, &ctx)?;
}
bench_sbf_end!("t_process_compression");
bench_sbf_start!("t_create_output_compressed_accounts");
let hashed_mint = match hash_to_bn254_field_size_be(&inputs.mint.to_bytes()) {
Some(hashed_mint) => hashed_mint.0,
None => return err!(ErrorCode::HashToFieldError),
};
let mut output_compressed_accounts = vec![
OutputCompressedAccountWithPackedContext::default();
inputs.output_compressed_accounts.len()
];
// If delegate is signer of the transaction determine whether there is a
// change account which remains delegated and mark its position.
let (is_delegate, delegate) = if let Some(delegated_transfer) = inputs.delegated_transfer {
let mut vec = vec![false; inputs.output_compressed_accounts.len()];
if let Some(index) = delegated_transfer.delegate_change_account_index {
vec[index as usize] = true;
(Some(vec), Some(ctx.accounts.authority.key()))
} else {
(None, None)
}
} else {
(None, None)
};
inputs.output_compressed_accounts.iter().for_each(|data| {
if data.tlv.is_some() {
unimplemented!("Tlv is unimplemented");
}
});
let output_lamports = create_output_compressed_accounts(
&mut output_compressed_accounts,
inputs.mint,
inputs
.output_compressed_accounts
.iter()
.map(|data| data.owner)
.collect::<Vec<Pubkey>>()
.as_slice(),
delegate,
is_delegate,
inputs
.output_compressed_accounts
.iter()
.map(|data: &PackedTokenTransferOutputData| data.amount)
.collect::<Vec<u64>>()
.as_slice(),
Some(
inputs
.output_compressed_accounts
.iter()
.map(|data: &PackedTokenTransferOutputData| data.lamports)
.collect::<Vec<Option<u64>>>(),
),
&hashed_mint,
&inputs
.output_compressed_accounts
.iter()
.map(|data| data.merkle_tree_index)
.collect::<Vec<u8>>(),
)?;
bench_sbf_end!("t_create_output_compressed_accounts");
bench_sbf_start!("t_add_token_data_to_input_compressed_accounts");
if !compressed_input_accounts.is_empty() {
add_token_data_to_input_compressed_accounts::<false>(
&mut compressed_input_accounts,
input_token_data.as_slice(),
&hashed_mint,
)?;
}
bench_sbf_end!("t_add_token_data_to_input_compressed_accounts");
// If input and output lamports are unbalanced create a change account
// without token data.
let change_lamports = input_lamports - output_lamports;
if change_lamports > 0 {
let new_len = output_compressed_accounts.len() + 1;
// Resize vector to new_len so that no unnecessary memory is allocated.
// (Rust doubles the size of the vector when pushing to a full vector.)
output_compressed_accounts.resize(
new_len,
OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: ctx.accounts.authority.key(),
lamports: change_lamports,
data: None,
address: None,
},
merkle_tree_index: inputs.output_compressed_accounts[0].merkle_tree_index,
},
);
}
cpi_execute_compressed_transaction_transfer(
ctx.accounts,
compressed_input_accounts,
&output_compressed_accounts,
inputs.proof,
inputs.cpi_context,
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts.light_system_program.to_account_info(),
ctx.accounts.self_program.to_account_info(),
ctx.remaining_accounts,
)
}
/// Creates output compressed accounts.
/// Steps:
/// 1. Allocate memory for token data.
/// 2. Create, hash and serialize token data.
/// 3. Create compressed account data.
/// 4. Repeat for every pubkey.
#[allow(clippy::too_many_arguments)]
pub fn create_output_compressed_accounts(
output_compressed_accounts: &mut [OutputCompressedAccountWithPackedContext],
mint_pubkey: Pubkey,
pubkeys: &[Pubkey],
delegate: Option<Pubkey>,
is_delegate: Option<Vec<bool>>,
amounts: &[u64],
lamports: Option<Vec<Option<u64>>>,
hashed_mint: &[u8; 32],
merkle_tree_indices: &[u8],
) -> Result<u64> {
let mut sum_lamports = 0;
let hashed_delegate_store = if let Some(delegate) = delegate {
hash_to_bn254_field_size_be(delegate.to_bytes().as_slice())
.unwrap()
.0
} else {
[0u8; 32]
};
for (i, (owner, amount)) in pubkeys.iter().zip(amounts.iter()).enumerate() {
let (delegate, hashed_delegate) = if is_delegate
.as_ref()
.map(|is_delegate| is_delegate[i])
.unwrap_or(false)
{
(
delegate.as_ref().map(|delegate_pubkey| *delegate_pubkey),
Some(&hashed_delegate_store),
)
} else {
(None, None)
};
// 107/75 =
// 32 mint
// + 32 owner
// + 8 amount
// + 1 + 32 option + delegate (optional)
// + 1 state
// + 1 tlv (None)
let capacity = if delegate.is_some() { 107 } else { 75 };
let mut token_data_bytes = Vec::with_capacity(capacity);
// 1,000 CU token data and serialize
let token_data = TokenData {
mint: mint_pubkey,
owner: *owner,
amount: *amount,
delegate,
state: AccountState::Initialized,
tlv: None,
};
token_data.serialize(&mut token_data_bytes).unwrap();
bench_sbf_start!("token_data_hash");
let hashed_owner = hash_to_bn254_field_size_be(owner.as_ref()).unwrap().0;
let amount_bytes = amount.to_le_bytes();
let data_hash = TokenData::hash_with_hashed_values::<Poseidon>(
hashed_mint,
&hashed_owner,
&amount_bytes,
&hashed_delegate,
)
.map_err(ProgramError::from)?;
let data: CompressedAccountData = CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data: token_data_bytes,
data_hash,
};
bench_sbf_end!("token_data_hash");
let lamports = lamports
.as_ref()
.and_then(|lamports| lamports[i])
.unwrap_or(0);
sum_lamports += lamports;
output_compressed_accounts[i] = OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: crate::ID,
lamports,
data: Some(data),
address: None,
},
merkle_tree_index: merkle_tree_indices[i],
};
}
Ok(sum_lamports)
}
/// Create output compressed accounts
/// 1. enforces discriminator
/// 2. hashes token data
pub fn add_token_data_to_input_compressed_accounts<const FROZEN_INPUTS: bool>(
input_compressed_accounts_with_merkle_context: &mut [PackedCompressedAccountWithMerkleContext],
input_token_data: &[TokenData],
hashed_mint: &[u8; 32],
) -> Result<()> {
for (i, compressed_account_with_context) in input_compressed_accounts_with_merkle_context
.iter_mut()
.enumerate()
{
let hashed_owner = hash_to_bn254_field_size_be(&input_token_data[i].owner.to_bytes())
.unwrap()
.0;
let mut data = Vec::new();
input_token_data[i].serialize(&mut data)?;
let amount = input_token_data[i].amount.to_le_bytes();
let delegate_store;
let hashed_delegate = if let Some(delegate) = input_token_data[i].delegate {
delegate_store = hash_to_bn254_field_size_be(&delegate.to_bytes()).unwrap().0;
Some(&delegate_store)
} else {
None
};
compressed_account_with_context.compressed_account.data = if !FROZEN_INPUTS {
Some(CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data,
data_hash: TokenData::hash_with_hashed_values::<Poseidon>(
hashed_mint,
&hashed_owner,
&amount,
&hashed_delegate,
)
.map_err(ProgramError::from)?,
})
} else {
Some(CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data,
data_hash: TokenData::hash_frozen_with_hashed_values::<Poseidon>(
hashed_mint,
&hashed_owner,
&amount,
&hashed_delegate,
)
.map_err(ProgramError::from)?,
})
};
}
Ok(())
}
/// Get static cpi signer seeds
pub fn get_cpi_signer_seeds() -> [&'static [u8]; 2] {
let bump: &[u8; 1] = &[BUMP_CPI_AUTHORITY];
let seeds: [&'static [u8]; 2] = [CPI_AUTHORITY_PDA_SEED, bump];
seeds
}
#[inline(never)]
#[allow(clippy::too_many_arguments)]
pub fn cpi_execute_compressed_transaction_transfer<
'info,
A: InvokeAccounts<'info> + SignerAccounts<'info>,
>(
ctx: &A,
input_compressed_accounts_with_merkle_context: Vec<PackedCompressedAccountWithMerkleContext>,
output_compressed_accounts: &[OutputCompressedAccountWithPackedContext],
proof: Option<CompressedProof>,
cpi_context: Option<CompressedCpiContext>,
cpi_authority_pda: AccountInfo<'info>,
system_program_account_info: AccountInfo<'info>,
invoking_program_account_info: AccountInfo<'info>,
remaining_accounts: &[AccountInfo<'info>],
) -> Result<()> {
bench_sbf_start!("t_cpi_prep");
let signer_seeds = get_cpi_signer_seeds();
let signer_seeds_ref = &[&signer_seeds[..]];
let cpi_context_account = cpi_context.map(|cpi_context| {
remaining_accounts[cpi_context.cpi_context_account_index as usize].to_account_info()
});
let inputs_struct = light_system_program::invoke_cpi::instruction::InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context,
output_compressed_accounts: output_compressed_accounts.to_vec(),
proof,
new_address_params: Vec::new(),
compress_or_decompress_lamports: None,
is_compress: false,
cpi_context,
};
let mut inputs = Vec::new();
InstructionDataInvokeCpi::serialize(&inputs_struct, &mut inputs).map_err(ProgramError::from)?;
let cpi_accounts = light_system_program::cpi::accounts::InvokeCpiInstruction {
fee_payer: ctx.get_fee_payer().to_account_info(),
authority: cpi_authority_pda,
registered_program_pda: ctx.get_registered_program_pda().to_account_info(),
noop_program: ctx.get_noop_program().to_account_info(),
account_compression_authority: ctx.get_account_compression_authority().to_account_info(),
account_compression_program: ctx.get_account_compression_program().to_account_info(),
invoking_program: invoking_program_account_info,
system_program: ctx.get_system_program().to_account_info(),
sol_pool_pda: None,
decompression_recipient: None,
cpi_context_account,
};
let mut cpi_ctx =
CpiContext::new_with_signer(system_program_account_info, cpi_accounts, signer_seeds_ref);
cpi_ctx.remaining_accounts = remaining_accounts.to_vec();
bench_sbf_end!("t_cpi_prep");
bench_sbf_start!("t_invoke_cpi");
light_system_program::cpi::invoke_cpi(cpi_ctx, inputs)?;
bench_sbf_end!("t_invoke_cpi");
Ok(())
}
pub fn sum_check(
input_token_data_elements: &[TokenData],
output_amounts: &[u64],
compress_or_decompress_amount: Option<&u64>,
is_compress: bool,
) -> Result<()> {
let mut sum: u64 = 0;
for input_token_data in input_token_data_elements.iter() {
sum = sum
.checked_add(input_token_data.amount)
.ok_or(ProgramError::ArithmeticOverflow)
.map_err(|_| ErrorCode::ComputeInputSumFailed)?;
}
if let Some(compress_or_decompress_amount) = compress_or_decompress_amount {
if is_compress {
sum = sum
.checked_add(*compress_or_decompress_amount)
.ok_or(ProgramError::ArithmeticOverflow)
.map_err(|_| ErrorCode::ComputeCompressSumFailed)?;
} else {
sum = sum
.checked_sub(*compress_or_decompress_amount)
.ok_or(ProgramError::ArithmeticOverflow)
.map_err(|_| ErrorCode::ComputeDecompressSumFailed)?;
}
}
for amount in output_amounts.iter() {
sum = sum
.checked_sub(*amount)
.ok_or(ProgramError::ArithmeticOverflow)
.map_err(|_| ErrorCode::ComputeOutputSumFailed)?;
}
if sum == 0 {
Ok(())
} else {
Err(ErrorCode::SumCheckFailed.into())
}
}
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct InputTokenDataWithContext {
pub amount: u64,
pub delegate_index: Option<u8>,
pub merkle_context: PackedMerkleContext,
pub root_index: u16,
pub lamports: Option<u64>,
/// Placeholder for TokenExtension tlv data (unimplemented)
pub tlv: Option<Vec<u8>>,
}
/// Struct to provide the owner when the delegate is signer of the transaction.
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct DelegatedTransfer {
pub owner: Pubkey,
/// Index of change compressed account in output compressed accounts. In
/// case that the delegate didn't spend the complete delegated compressed
/// account balance the change compressed account will be delegated to her
/// as well.
pub delegate_change_account_index: Option<u8>,
}
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct CompressedTokenInstructionDataTransfer {
pub proof: Option<CompressedProof>,
pub mint: Pubkey,
/// Is required if the signer is delegate,
/// -> delegate is authority account,
/// owner = Some(owner) is the owner of the token account.
pub delegated_transfer: Option<DelegatedTransfer>,
pub input_token_data_with_context: Vec<InputTokenDataWithContext>,
pub output_compressed_accounts: Vec<PackedTokenTransferOutputData>,
pub is_compress: bool,
pub compress_or_decompress_amount: Option<u64>,
pub cpi_context: Option<CompressedCpiContext>,
pub lamports_change_account_merkle_tree_index: Option<u8>,
}
pub fn get_input_compressed_accounts_with_merkle_context_and_check_signer<const IS_FROZEN: bool>(
signer: &Pubkey,
signer_is_delegate: &Option<DelegatedTransfer>,
remaining_accounts: &[AccountInfo<'_>],
input_token_data_with_context: &[InputTokenDataWithContext],
mint: &Pubkey,
) -> Result<(
Vec<PackedCompressedAccountWithMerkleContext>,
Vec<TokenData>,
u64,
)> {
// Collect the total number of lamports to check whether inputs and outputs
// are unbalanced. If unbalanced create a non token compressed change
// account owner by the sender.
let mut sum_lamports = 0;
let mut input_compressed_accounts_with_merkle_context: Vec<
PackedCompressedAccountWithMerkleContext,
> = Vec::<PackedCompressedAccountWithMerkleContext>::with_capacity(
input_token_data_with_context.len(),
);
let mut input_token_data_vec: Vec<TokenData> =
Vec::with_capacity(input_token_data_with_context.len());
for input_token_data in input_token_data_with_context.iter() {
let owner = if input_token_data.delegate_index.is_none() {
*signer
} else if let Some(signer_is_delegate) = signer_is_delegate {
signer_is_delegate.owner
} else {
*signer
};
// This is a check for convenience to throw a meaningful error.
// The actual security results from the proof verification.
if signer_is_delegate.is_some()
&& input_token_data.delegate_index.is_some()
&& *signer
!= remaining_accounts[input_token_data.delegate_index.unwrap() as usize].key()
{
msg!(
"signer {:?} != delegate in remaining accounts {:?}",
signer,
remaining_accounts[input_token_data.delegate_index.unwrap() as usize].key()
);
msg!(
"delegate index {:?}",
input_token_data.delegate_index.unwrap() as usize
);
return err!(ErrorCode::DelegateSignerCheckFailed);
}
let compressed_account = CompressedAccount {
owner: crate::ID,
lamports: input_token_data.lamports.unwrap_or_default(),
data: None,
address: None,
};
sum_lamports += compressed_account.lamports;
let state = if IS_FROZEN {
AccountState::Frozen
} else {
AccountState::Initialized
};
if input_token_data.tlv.is_some() {
unimplemented!("Tlv is unimplemented.");
}
let token_data = TokenData {
mint: *mint,
owner,
amount: input_token_data.amount,
delegate: input_token_data.delegate_index.map(|_| {
remaining_accounts[input_token_data.delegate_index.unwrap() as usize].key()
}),
state,
tlv: None,
};
input_token_data_vec.push(token_data);
input_compressed_accounts_with_merkle_context.push(
PackedCompressedAccountWithMerkleContext {
compressed_account,
merkle_context: input_token_data.merkle_context,
root_index: input_token_data.root_index,
read_only: false,
},
);
}
Ok((
input_compressed_accounts_with_merkle_context,
input_token_data_vec,
sum_lamports,
))
}
#[derive(Clone, Debug, PartialEq, Eq, AnchorSerialize, AnchorDeserialize)]
pub struct PackedTokenTransferOutputData {
pub owner: Pubkey,
pub amount: u64,
pub lamports: Option<u64>,
pub merkle_tree_index: u8,
/// Placeholder for TokenExtension tlv data (unimplemented)
pub tlv: Option<Vec<u8>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, AnchorSerialize, AnchorDeserialize)]
pub struct TokenTransferOutputData {
pub owner: Pubkey,
pub amount: u64,
pub lamports: Option<u64>,
pub merkle_tree: Pubkey,
}
pub fn get_cpi_authority_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &crate::ID)
}
#[cfg(not(target_os = "solana"))]
pub mod transfer_sdk {
use std::collections::HashMap;
use anchor_lang::{AnchorSerialize, Id, InstructionData, ToAccountMetas};
use anchor_spl::{token::Token, token_2022::Token2022};
use light_system_program::{
invoke::processor::CompressedProof,
sdk::compressed_account::{CompressedAccount, MerkleContext, PackedMerkleContext},
};
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
};
use crate::{token_data::TokenData, CompressedTokenInstructionDataTransfer};
use anchor_lang::error_code;
use super::{
DelegatedTransfer, InputTokenDataWithContext, PackedTokenTransferOutputData,
TokenTransferOutputData,
};
#[error_code]
pub enum TransferSdkError {
#[msg("Signer check failed")]
SignerCheckFailed,
#[msg("Create transfer instruction failed")]
CreateTransferInstructionFailed,
#[msg("Account not found")]
AccountNotFound,
#[msg("Serialization error")]
SerializationError,
}
#[allow(clippy::too_many_arguments)]
pub fn create_transfer_instruction(
fee_payer: &Pubkey,
owner: &Pubkey,
input_merkle_context: &[MerkleContext],
output_compressed_accounts: &[TokenTransferOutputData],
root_indices: &[u16],
proof: &Option<CompressedProof>,
input_token_data: &[TokenData],
input_compressed_accounts: &[CompressedAccount],
mint: Pubkey,
delegate: Option<Pubkey>,
is_compress: bool,
compress_or_decompress_amount: Option<u64>,
token_pool_pda: Option<Pubkey>,
compress_or_decompress_token_account: Option<Pubkey>,
sort: bool,
delegate_change_account_index: Option<u8>,
lamports_change_account_merkle_tree: Option<Pubkey>,
is_token_22: bool,
) -> Result<Instruction, TransferSdkError> {
let (remaining_accounts, mut inputs_struct) = create_inputs_and_remaining_accounts(
input_token_data,
input_compressed_accounts,
input_merkle_context,
delegate,
output_compressed_accounts,
root_indices,
proof,
mint,
is_compress,
compress_or_decompress_amount,
delegate_change_account_index,
lamports_change_account_merkle_tree,
);
if sort {
inputs_struct
.output_compressed_accounts
.sort_by_key(|data| data.merkle_tree_index);
}
let remaining_accounts = to_account_metas(remaining_accounts);
let mut inputs = Vec::new();
CompressedTokenInstructionDataTransfer::serialize(&inputs_struct, &mut inputs)
.map_err(|_| TransferSdkError::SerializationError)?;
let (cpi_authority_pda, _) = crate::process_transfer::get_cpi_authority_pda();
let instruction_data = crate::instruction::Transfer { inputs };
let authority = if let Some(delegate) = delegate {
delegate
} else {
*owner
};
let token_program = if compress_or_decompress_token_account.is_none() {
None
} else if is_token_22 {
Some(Token2022::id())
} else {
Some(Token::id())
};
let accounts = crate::accounts::TransferInstruction {
fee_payer: *fee_payer,
authority,
cpi_authority_pda,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
self_program: crate::ID,
token_pool_pda,
compress_or_decompress_token_account,
token_program,
system_program: solana_sdk::system_program::ID,
};
Ok(Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
})
}
#[allow(clippy::too_many_arguments)]
pub fn create_inputs_and_remaining_accounts_checked(
input_token_data: &[TokenData],
input_compressed_accounts: &[CompressedAccount],
input_merkle_context: &[MerkleContext],
owner_if_delegate_is_signer: Option<Pubkey>,
output_compressed_accounts: &[TokenTransferOutputData],
root_indices: &[u16],
proof: &Option<CompressedProof>,
mint: Pubkey,
owner: &Pubkey,
is_compress: bool,
compress_or_decompress_amount: Option<u64>,
delegate_change_account_index: Option<u8>,
lamports_change_account_merkle_tree: Option<Pubkey>,
) -> Result<
(
HashMap<Pubkey, usize>,
CompressedTokenInstructionDataTransfer,
),
TransferSdkError,
> {
for token_data in input_token_data {
// convenience signer check to throw a meaningful error
if token_data.owner != *owner {
println!(
"owner: {:?}, token_data.owner: {:?}",
owner, token_data.owner
);
return Err(TransferSdkError::SignerCheckFailed);
}
}
let (remaining_accounts, compressed_accounts_ix_data) =
create_inputs_and_remaining_accounts(
input_token_data,
input_compressed_accounts,
input_merkle_context,
owner_if_delegate_is_signer,
output_compressed_accounts,
root_indices,
proof,
mint,
is_compress,
compress_or_decompress_amount,
delegate_change_account_index,
lamports_change_account_merkle_tree,
);
Ok((remaining_accounts, compressed_accounts_ix_data))
}
#[allow(clippy::too_many_arguments)]
pub fn create_inputs_and_remaining_accounts(
input_token_data: &[TokenData],
input_compressed_accounts: &[CompressedAccount],
input_merkle_context: &[MerkleContext],
delegate: Option<Pubkey>,
output_compressed_accounts: &[TokenTransferOutputData],
root_indices: &[u16],
proof: &Option<CompressedProof>,
mint: Pubkey,
is_compress: bool,
compress_or_decompress_amount: Option<u64>,
delegate_change_account_index: Option<u8>,
lamports_change_account_merkle_tree: Option<Pubkey>,
) -> (
HashMap<Pubkey, usize>,
CompressedTokenInstructionDataTransfer,
) {
let mut additonal_accounts = Vec::new();
if let Some(delegate) = delegate {
additonal_accounts.push(delegate);
for account in input_token_data.iter() {
if account.delegate.is_some() && delegate != account.delegate.unwrap() {
println!("delegate: {:?}", delegate);
println!("account.delegate: {:?}", account.delegate.unwrap());
panic!("Delegate is not the same as the signer");
}
}
}
let lamports_change_account_merkle_tree_index = if let Some(
lamports_change_account_merkle_tree,
) = lamports_change_account_merkle_tree
{
additonal_accounts.push(lamports_change_account_merkle_tree);
Some(additonal_accounts.len() as u8 - 1)
} else {
None
};
let (remaining_accounts, input_token_data_with_context, _output_compressed_accounts) =
create_input_output_and_remaining_accounts(
additonal_accounts.as_slice(),
input_token_data,
input_compressed_accounts,
input_merkle_context,
root_indices,
output_compressed_accounts,
);
let delegated_transfer = if delegate.is_some() {
let delegated_transfer = DelegatedTransfer {
owner: input_token_data[0].owner,
delegate_change_account_index,
};
Some(delegated_transfer)
} else {
None
};
let inputs_struct = CompressedTokenInstructionDataTransfer {
output_compressed_accounts: _output_compressed_accounts.to_vec(),
proof: proof.clone(),
input_token_data_with_context,
delegated_transfer,
mint,
is_compress,
compress_or_decompress_amount,
cpi_context: None,
lamports_change_account_merkle_tree_index,
};
(remaining_accounts, inputs_struct)
}
pub fn create_input_output_and_remaining_accounts(
additional_accounts: &[Pubkey],
input_token_data: &[TokenData],
input_compressed_accounts: &[CompressedAccount],
input_merkle_context: &[MerkleContext],
root_indices: &[u16],
output_compressed_accounts: &[TokenTransferOutputData],
) -> (
HashMap<Pubkey, usize>,
Vec<InputTokenDataWithContext>,
Vec<PackedTokenTransferOutputData>,
) {
let mut remaining_accounts = HashMap::<Pubkey, usize>::new();
let mut index = 0;
for account in additional_accounts {
match remaining_accounts.get(account) {
Some(_) => {}
None => {
remaining_accounts.insert(*account, index);
index += 1;
}
};
}
let mut input_token_data_with_context: Vec<InputTokenDataWithContext> = Vec::new();
for (i, token_data) in input_token_data.iter().enumerate() {
match remaining_accounts.get(&input_merkle_context[i].merkle_tree_pubkey) {
Some(_) => {}
None => {
remaining_accounts.insert(input_merkle_context[i].merkle_tree_pubkey, index);
index += 1;
}
};
let delegate_index = match token_data.delegate {
Some(delegate) => match remaining_accounts.get(&delegate) {
Some(delegate_index) => Some(*delegate_index as u8),
None => {
remaining_accounts.insert(delegate, index);
index += 1;
Some((index - 1) as u8)
}
},
None => None,
};
let lamports = if input_compressed_accounts[i].lamports != 0 {
Some(input_compressed_accounts[i].lamports)
} else {
None
};
let token_data_with_context = InputTokenDataWithContext {
amount: token_data.amount,
delegate_index,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: *remaining_accounts
.get(&input_merkle_context[i].merkle_tree_pubkey)
.unwrap() as u8,
nullifier_queue_pubkey_index: 0,
leaf_index: input_merkle_context[i].leaf_index,
queue_index: None,
},
root_index: root_indices[i],
lamports,
tlv: None,
};
input_token_data_with_context.push(token_data_with_context);
}
for (i, _) in input_token_data.iter().enumerate() {
match remaining_accounts.get(&input_merkle_context[i].nullifier_queue_pubkey) {
Some(_) => {}
None => {
remaining_accounts
.insert(input_merkle_context[i].nullifier_queue_pubkey, index);
index += 1;
}
};
input_token_data_with_context[i]
.merkle_context
.nullifier_queue_pubkey_index = *remaining_accounts
.get(&input_merkle_context[i].nullifier_queue_pubkey)
.unwrap() as u8;
}
let mut _output_compressed_accounts: Vec<PackedTokenTransferOutputData> =
Vec::with_capacity(output_compressed_accounts.len());
for (i, mt) in output_compressed_accounts.iter().enumerate() {
match remaining_accounts.get(&mt.merkle_tree) {
Some(_) => {}
None => {
remaining_accounts.insert(mt.merkle_tree, index);
index += 1;
}
};
_output_compressed_accounts.push(PackedTokenTransferOutputData {
owner: output_compressed_accounts[i].owner,
amount: output_compressed_accounts[i].amount,
lamports: output_compressed_accounts[i].lamports,
merkle_tree_index: *remaining_accounts.get(&mt.merkle_tree).unwrap() as u8,
tlv: None,
});
}
(
remaining_accounts,
input_token_data_with_context,
_output_compressed_accounts,
)
}
pub fn to_account_metas(remaining_accounts: HashMap<Pubkey, usize>) -> Vec<AccountMeta> {
let mut remaining_accounts = remaining_accounts
.iter()
.map(|(k, i)| {
(
AccountMeta {
pubkey: *k,
is_signer: false,
is_writable: true,
},
*i,
)
})
.collect::<Vec<(AccountMeta, usize)>>();
// hash maps are not sorted so we need to sort manually and collect into a vector again
remaining_accounts.sort_by(|a, b| a.1.cmp(&b.1));
let remaining_accounts = remaining_accounts
.iter()
.map(|(k, _)| k.clone())
.collect::<Vec<AccountMeta>>();
remaining_accounts
}
}
#[cfg(test)]
mod test {
use crate::token_data::AccountState;
use super::*;
#[test]
fn test_sum_check() {
// SUCCEED: no relay fee, compression
sum_check_test(&[100, 50], &[150], None, false).unwrap();
sum_check_test(&[75, 25, 25], &[25, 25, 25, 25, 12, 13], None, false).unwrap();
// FAIL: no relay fee, compression
sum_check_test(&[100, 50], &[150 + 1], None, false).unwrap_err();
sum_check_test(&[100, 50], &[150 - 1], None, false).unwrap_err();
sum_check_test(&[100, 50], &[], None, false).unwrap_err();
sum_check_test(&[], &[100, 50], None, false).unwrap_err();
// SUCCEED: empty
sum_check_test(&[], &[], None, true).unwrap();
sum_check_test(&[], &[], None, false).unwrap();
// FAIL: empty
sum_check_test(&[], &[], Some(1), false).unwrap_err();
sum_check_test(&[], &[], Some(1), true).unwrap_err();
// SUCCEED: with compress
sum_check_test(&[100], &[123], Some(23), true).unwrap();
sum_check_test(&[], &[150], Some(150), true).unwrap();
// FAIL: compress
sum_check_test(&[], &[150], Some(150 - 1), true).unwrap_err();
sum_check_test(&[], &[150], Some(150 + 1), true).unwrap_err();
// SUCCEED: with decompress
sum_check_test(&[100, 50], &[100], Some(50), false).unwrap();
sum_check_test(&[100, 50], &[], Some(150), false).unwrap();
// FAIL: decompress
sum_check_test(&[100, 50], &[], Some(150 - 1), false).unwrap_err();
sum_check_test(&[100, 50], &[], Some(150 + 1), false).unwrap_err();
}
fn sum_check_test(
input_amounts: &[u64],
output_amounts: &[u64],
compress_or_decompress_amount: Option<u64>,
is_compress: bool,
) -> Result<()> {
let mut inputs = Vec::new();
for i in input_amounts.iter() {
inputs.push(TokenData {
mint: Pubkey::new_unique(),
owner: Pubkey::new_unique(),
delegate: None,
state: AccountState::Initialized,
amount: *i,
tlv: None,
});
}
let ref_amount;
let compress_or_decompress_amount = match compress_or_decompress_amount {
Some(amount) => {
ref_amount = amount;
Some(&ref_amount)
}
None => None,
};
sum_check(
inputs.as_slice(),
&output_amounts,
compress_or_decompress_amount,
is_compress,
)
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/delegation.rs
|
use anchor_lang::prelude::*;
use light_system_program::{
invoke::processor::CompressedProof,
sdk::{compressed_account::PackedCompressedAccountWithMerkleContext, CompressedCpiContext},
OutputCompressedAccountWithPackedContext,
};
use light_utils::hash_to_bn254_field_size_be;
use crate::{
constants::NOT_FROZEN,
process_transfer::{
add_token_data_to_input_compressed_accounts, cpi_execute_compressed_transaction_transfer,
create_output_compressed_accounts,
get_input_compressed_accounts_with_merkle_context_and_check_signer,
InputTokenDataWithContext,
},
ErrorCode, GenericInstruction,
};
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct CompressedTokenInstructionDataApprove {
pub proof: CompressedProof,
pub mint: Pubkey,
pub input_token_data_with_context: Vec<InputTokenDataWithContext>,
pub cpi_context: Option<CompressedCpiContext>,
pub delegate: Pubkey,
pub delegated_amount: u64,
/// Index in remaining accounts.
pub delegate_merkle_tree_index: u8,
/// Index in remaining accounts.
pub change_account_merkle_tree_index: u8,
pub delegate_lamports: Option<u64>,
}
/// Processes an approve instruction.
/// - creates an output compressed acount which is delegated to the delegate.
/// - creates a change account for the remaining amount (sum inputs - delegated amount).
/// - ignores prior delegations.
/// 1. unpack instruction data and input compressed accounts
/// 2. calculate change amount
/// 3. create output compressed accounts
/// 4. pack token data into input compressed accounts
/// 5. execute compressed transaction
pub fn process_approve<'a, 'b, 'c, 'info: 'b + 'c>(
ctx: Context<'a, 'b, 'c, 'info, GenericInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
let inputs: CompressedTokenInstructionDataApprove =
CompressedTokenInstructionDataApprove::deserialize(&mut inputs.as_slice())?;
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_approve(
&inputs,
&ctx.accounts.authority.key(),
ctx.remaining_accounts,
)?;
cpi_execute_compressed_transaction_transfer(
ctx.accounts,
compressed_input_accounts,
&output_compressed_accounts,
Some(inputs.proof),
inputs.cpi_context,
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts.light_system_program.to_account_info(),
ctx.accounts.self_program.to_account_info(),
ctx.remaining_accounts,
)
}
pub fn create_input_and_output_accounts_approve(
inputs: &CompressedTokenInstructionDataApprove,
authority: &Pubkey,
remaining_accounts: &[AccountInfo<'_>],
) -> Result<(
Vec<PackedCompressedAccountWithMerkleContext>,
Vec<OutputCompressedAccountWithPackedContext>,
)> {
if inputs.input_token_data_with_context.is_empty() {
return err!(ErrorCode::NoInputTokenAccountsProvided);
}
let (mut compressed_input_accounts, input_token_data, sum_lamports) =
get_input_compressed_accounts_with_merkle_context_and_check_signer::<NOT_FROZEN>(
authority,
&None,
remaining_accounts,
&inputs.input_token_data_with_context,
&inputs.mint,
)?;
let sum_inputs = input_token_data.iter().map(|x| x.amount).sum::<u64>();
let change_amount = match sum_inputs.checked_sub(inputs.delegated_amount) {
Some(change_amount) => change_amount,
None => return err!(ErrorCode::ArithmeticUnderflow),
};
let delegated_lamports = inputs.delegate_lamports.unwrap_or(0);
let change_lamports = match sum_lamports.checked_sub(delegated_lamports) {
Some(change_lamports) => change_lamports,
None => return err!(ErrorCode::ArithmeticUnderflow),
};
let hashed_mint = match hash_to_bn254_field_size_be(&inputs.mint.to_bytes()) {
Some(hashed_mint) => hashed_mint.0,
None => return err!(ErrorCode::HashToFieldError),
};
let lamports = if sum_lamports != 0 {
let change_lamports = if change_lamports != 0 {
Some(change_lamports)
} else {
None
};
Some(vec![inputs.delegate_lamports, change_lamports])
} else {
None
};
// Only create outputs if the change amount is not zero.
let (
mut output_compressed_accounts,
pubkeys,
is_delegate,
amounts,
lamports,
merkle_tree_indices,
) = if change_amount > 0 || change_lamports > 0 {
(
vec![OutputCompressedAccountWithPackedContext::default(); 2],
vec![*authority, *authority],
Some(vec![true, false]),
vec![inputs.delegated_amount, change_amount],
lamports,
vec![
inputs.delegate_merkle_tree_index,
inputs.change_account_merkle_tree_index,
],
)
} else {
(
vec![OutputCompressedAccountWithPackedContext::default(); 1],
vec![*authority],
Some(vec![true]),
vec![inputs.delegated_amount],
lamports,
vec![inputs.delegate_merkle_tree_index],
)
};
create_output_compressed_accounts(
&mut output_compressed_accounts,
inputs.mint,
pubkeys.as_slice(),
Some(inputs.delegate),
is_delegate,
amounts.as_slice(),
lamports,
&hashed_mint,
&merkle_tree_indices,
)?;
add_token_data_to_input_compressed_accounts::<NOT_FROZEN>(
&mut compressed_input_accounts,
input_token_data.as_slice(),
&hashed_mint,
)?;
Ok((compressed_input_accounts, output_compressed_accounts))
}
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct CompressedTokenInstructionDataRevoke {
pub proof: CompressedProof,
pub mint: Pubkey,
pub input_token_data_with_context: Vec<InputTokenDataWithContext>,
pub cpi_context: Option<CompressedCpiContext>,
pub output_account_merkle_tree_index: u8,
}
pub fn process_revoke<'a, 'b, 'c, 'info: 'b + 'c>(
ctx: Context<'a, 'b, 'c, 'info, GenericInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
let inputs: CompressedTokenInstructionDataRevoke =
CompressedTokenInstructionDataRevoke::deserialize(&mut inputs.as_slice())?;
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_revoke(
&inputs,
&ctx.accounts.authority.key(),
ctx.remaining_accounts,
)?;
cpi_execute_compressed_transaction_transfer(
ctx.accounts,
compressed_input_accounts,
&output_compressed_accounts,
Some(inputs.proof),
inputs.cpi_context,
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts.light_system_program.to_account_info(),
ctx.accounts.self_program.to_account_info(),
ctx.remaining_accounts,
)?;
Ok(())
}
pub fn create_input_and_output_accounts_revoke(
inputs: &CompressedTokenInstructionDataRevoke,
authority: &Pubkey,
remaining_accounts: &[AccountInfo<'_>],
) -> Result<(
Vec<PackedCompressedAccountWithMerkleContext>,
Vec<OutputCompressedAccountWithPackedContext>,
)> {
if inputs.input_token_data_with_context.is_empty() {
return err!(ErrorCode::NoInputTokenAccountsProvided);
}
let (mut compressed_input_accounts, input_token_data, sum_lamports) =
get_input_compressed_accounts_with_merkle_context_and_check_signer::<NOT_FROZEN>(
authority,
&None,
remaining_accounts,
&inputs.input_token_data_with_context,
&inputs.mint,
)?;
let sum_inputs = input_token_data.iter().map(|x| x.amount).sum::<u64>();
let lamports = if sum_lamports != 0 {
Some(vec![Some(sum_lamports)])
} else {
None
};
let mut output_compressed_accounts =
vec![OutputCompressedAccountWithPackedContext::default(); 1];
let hashed_mint = match hash_to_bn254_field_size_be(&inputs.mint.to_bytes()) {
Some(hashed_mint) => hashed_mint.0,
None => return err!(ErrorCode::HashToFieldError),
};
create_output_compressed_accounts(
&mut output_compressed_accounts,
inputs.mint,
&[*authority; 1],
None,
None,
&[sum_inputs],
lamports,
&hashed_mint,
&[inputs.output_account_merkle_tree_index],
)?;
add_token_data_to_input_compressed_accounts::<NOT_FROZEN>(
&mut compressed_input_accounts,
input_token_data.as_slice(),
&hashed_mint,
)?;
Ok((compressed_input_accounts, output_compressed_accounts))
}
#[cfg(not(target_os = "solana"))]
pub mod sdk {
use anchor_lang::{AnchorSerialize, InstructionData, ToAccountMetas};
use light_system_program::{
invoke::processor::CompressedProof,
sdk::compressed_account::{CompressedAccount, MerkleContext},
};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
use crate::{
process_transfer::{
get_cpi_authority_pda,
transfer_sdk::{
create_input_output_and_remaining_accounts, to_account_metas, TransferSdkError,
},
},
token_data::TokenData,
};
use super::{CompressedTokenInstructionDataApprove, CompressedTokenInstructionDataRevoke};
pub struct CreateApproveInstructionInputs {
pub fee_payer: Pubkey,
pub authority: Pubkey,
pub root_indices: Vec<u16>,
pub proof: CompressedProof,
pub input_token_data: Vec<TokenData>,
pub input_compressed_accounts: Vec<CompressedAccount>,
pub input_merkle_contexts: Vec<MerkleContext>,
pub mint: Pubkey,
pub delegated_amount: u64,
pub delegate_lamports: Option<u64>,
pub delegated_compressed_account_merkle_tree: Pubkey,
pub change_compressed_account_merkle_tree: Pubkey,
pub delegate: Pubkey,
}
pub fn create_approve_instruction(
inputs: CreateApproveInstructionInputs,
) -> Result<Instruction, TransferSdkError> {
let (remaining_accounts, input_token_data_with_context, _) =
create_input_output_and_remaining_accounts(
&[
inputs.delegated_compressed_account_merkle_tree,
inputs.change_compressed_account_merkle_tree,
],
&inputs.input_token_data,
&inputs.input_compressed_accounts,
&inputs.input_merkle_contexts,
&inputs.root_indices,
&Vec::new(),
);
let delegated_merkle_tree_index =
match remaining_accounts.get(&inputs.delegated_compressed_account_merkle_tree) {
Some(delegated_merkle_tree_index) => delegated_merkle_tree_index,
None => return Err(TransferSdkError::AccountNotFound),
};
let change_account_merkle_tree_index =
match remaining_accounts.get(&inputs.change_compressed_account_merkle_tree) {
Some(change_account_merkle_tree_index) => change_account_merkle_tree_index,
None => return Err(TransferSdkError::AccountNotFound),
};
let inputs_struct = CompressedTokenInstructionDataApprove {
proof: inputs.proof,
mint: inputs.mint,
input_token_data_with_context,
cpi_context: None,
delegate: inputs.delegate,
delegated_amount: inputs.delegated_amount,
delegate_merkle_tree_index: *delegated_merkle_tree_index as u8,
change_account_merkle_tree_index: *change_account_merkle_tree_index as u8,
delegate_lamports: inputs.delegate_lamports,
};
let remaining_accounts = to_account_metas(remaining_accounts);
let mut serialized_ix_data = Vec::new();
CompressedTokenInstructionDataApprove::serialize(&inputs_struct, &mut serialized_ix_data)
.map_err(|_| TransferSdkError::SerializationError)?;
let (cpi_authority_pda, _) = get_cpi_authority_pda();
let instruction_data = crate::instruction::Approve {
inputs: serialized_ix_data,
};
let accounts = crate::accounts::GenericInstruction {
fee_payer: inputs.fee_payer,
authority: inputs.authority,
cpi_authority_pda,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
self_program: crate::ID,
system_program: solana_sdk::system_program::ID,
};
Ok(Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
})
}
pub struct CreateRevokeInstructionInputs {
pub fee_payer: Pubkey,
pub authority: Pubkey,
pub root_indices: Vec<u16>,
pub proof: CompressedProof,
pub input_token_data: Vec<TokenData>,
pub input_compressed_accounts: Vec<CompressedAccount>,
pub input_merkle_contexts: Vec<MerkleContext>,
pub mint: Pubkey,
pub output_account_merkle_tree: Pubkey,
}
pub fn create_revoke_instruction(
inputs: CreateRevokeInstructionInputs,
) -> Result<Instruction, TransferSdkError> {
let (remaining_accounts, input_token_data_with_context, _) =
create_input_output_and_remaining_accounts(
&[inputs.output_account_merkle_tree],
&inputs.input_token_data,
&inputs.input_compressed_accounts,
&inputs.input_merkle_contexts,
&inputs.root_indices,
&Vec::new(),
);
let output_account_merkle_tree_index =
match remaining_accounts.get(&inputs.output_account_merkle_tree) {
Some(output_account_merkle_tree_index) => output_account_merkle_tree_index,
None => return Err(TransferSdkError::AccountNotFound),
};
let inputs_struct = CompressedTokenInstructionDataRevoke {
proof: inputs.proof,
mint: inputs.mint,
input_token_data_with_context,
cpi_context: None,
output_account_merkle_tree_index: *output_account_merkle_tree_index as u8,
};
let remaining_accounts = to_account_metas(remaining_accounts);
let mut serialized_ix_data = Vec::new();
CompressedTokenInstructionDataRevoke::serialize(&inputs_struct, &mut serialized_ix_data)
.map_err(|_| TransferSdkError::SerializationError)?;
let (cpi_authority_pda, _) = get_cpi_authority_pda();
let instruction_data = crate::instruction::Revoke {
inputs: serialized_ix_data,
};
let accounts = crate::accounts::GenericInstruction {
fee_payer: inputs.fee_payer,
authority: inputs.authority,
cpi_authority_pda,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
self_program: crate::ID,
system_program: solana_sdk::system_program::ID,
};
Ok(Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
})
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
freeze::test_freeze::create_expected_token_output_accounts, token_data::AccountState,
TokenData,
};
use anchor_lang::solana_program::account_info::AccountInfo;
use light_system_program::sdk::compressed_account::PackedMerkleContext;
// TODO: add randomized and edge case tests
#[test]
fn test_approve() {
let merkle_tree_pubkey = Pubkey::new_unique();
let mut merkle_tree_account_lamports = 0;
let mut merkle_tree_account_data = Vec::new();
let nullifier_queue_pubkey = Pubkey::new_unique();
let mut nullifier_queue_account_lamports = 0;
let mut nullifier_queue_account_data = Vec::new();
let remaining_accounts = vec![
AccountInfo::new(
&merkle_tree_pubkey,
false,
false,
&mut merkle_tree_account_lamports,
&mut merkle_tree_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&nullifier_queue_pubkey,
false,
false,
&mut nullifier_queue_account_lamports,
&mut nullifier_queue_account_data,
&account_compression::ID,
false,
0,
),
];
let authority = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let delegate = Pubkey::new_unique();
let input_token_data_with_context = vec![
InputTokenDataWithContext {
amount: 100,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 1,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1),
lamports: None,
tlv: None,
},
InputTokenDataWithContext {
amount: 101,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 2,
queue_index: None,
},
root_index: 0,
delegate_index: None,
lamports: None,
tlv: None,
},
];
let inputs = CompressedTokenInstructionDataApprove {
proof: CompressedProof::default(),
mint,
input_token_data_with_context,
cpi_context: None,
delegate,
delegated_amount: 50,
delegate_merkle_tree_index: 0,
change_account_merkle_tree_index: 1,
delegate_lamports: None,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_approve(&inputs, &authority, &remaining_accounts)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 2);
assert_eq!(output_compressed_accounts.len(), 2);
let expected_change_token_data = TokenData {
mint,
owner: authority,
amount: 151,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_delegated_token_data = TokenData {
mint,
owner: authority,
amount: 50,
delegate: Some(delegate),
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts = create_expected_token_output_accounts(
vec![expected_delegated_token_data, expected_change_token_data],
vec![0, 1],
);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
#[test]
fn test_revoke() {
let merkle_tree_pubkey = Pubkey::new_unique();
let mut merkle_tree_account_lamports = 0;
let mut merkle_tree_account_data = Vec::new();
let nullifier_queue_pubkey = Pubkey::new_unique();
let mut nullifier_queue_account_lamports = 0;
let mut nullifier_queue_account_data = Vec::new();
let remaining_accounts = vec![
AccountInfo::new(
&merkle_tree_pubkey,
false,
false,
&mut merkle_tree_account_lamports,
&mut merkle_tree_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&nullifier_queue_pubkey,
false,
false,
&mut nullifier_queue_account_lamports,
&mut nullifier_queue_account_data,
&account_compression::ID,
false,
0,
),
];
let authority = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let input_token_data_with_context = vec![
InputTokenDataWithContext {
amount: 100,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 1,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1), // Doesn't matter it is not checked if the proof is not verified
lamports: None,
tlv: None,
},
InputTokenDataWithContext {
amount: 101,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 2,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1), // Doesn't matter it is not checked if the proof is not verified
lamports: None,
tlv: None,
},
];
let inputs = CompressedTokenInstructionDataRevoke {
proof: CompressedProof::default(),
mint,
input_token_data_with_context,
cpi_context: None,
output_account_merkle_tree_index: 1,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_revoke(&inputs, &authority, &remaining_accounts)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 2);
assert_eq!(output_compressed_accounts.len(), 1);
let expected_change_token_data = TokenData {
mint,
owner: authority,
amount: 201,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts =
create_expected_token_output_accounts(vec![expected_change_token_data], vec![1]);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
let lamports_amount = 2;
let input_token_data_with_context = vec![
InputTokenDataWithContext {
amount: 100,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 1,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1), // Doesn't matter it is not checked if the proof is not verified
lamports: Some(lamports_amount / 2),
tlv: None,
},
InputTokenDataWithContext {
amount: 101,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 2,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1), // Doesn't matter it is not checked if the proof is not verified
lamports: Some(lamports_amount / 2),
tlv: None,
},
];
let inputs = CompressedTokenInstructionDataRevoke {
proof: CompressedProof::default(),
mint,
input_token_data_with_context,
cpi_context: None,
output_account_merkle_tree_index: 1,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_revoke(&inputs, &authority, &remaining_accounts)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 2);
assert_eq!(output_compressed_accounts.len(), 1);
let expected_change_token_data = TokenData {
mint,
owner: authority,
amount: 201,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let mut expected_compressed_output_accounts =
create_expected_token_output_accounts(vec![expected_change_token_data], vec![1]);
expected_compressed_output_accounts[0]
.compressed_account
.lamports = lamports_amount;
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/spl_compression.rs
|
#![allow(deprecated)]
use anchor_lang::{prelude::*, solana_program::account_info::AccountInfo};
use anchor_spl::token_interface;
use crate::{
process_transfer::get_cpi_signer_seeds, CompressedTokenInstructionDataTransfer,
TransferInstruction, POOL_SEED,
};
pub fn process_compression_or_decompression(
inputs: &CompressedTokenInstructionDataTransfer,
ctx: &Context<TransferInstruction>,
) -> Result<()> {
if inputs.is_compress {
compress_spl_tokens(inputs, ctx)
} else {
decompress_spl_tokens(inputs, ctx)
}
}
pub fn spl_token_pool_derivation(
mint: &Pubkey,
program_id: &Pubkey,
token_pool_pubkey: &Pubkey,
) -> Result<()> {
let seeds = &[POOL_SEED, &mint.to_bytes()[..]];
let (pda, _bump_seed) = Pubkey::find_program_address(seeds, program_id);
if pda == *token_pool_pubkey {
Ok(())
} else {
err!(crate::ErrorCode::InvalidTokenPoolPda)
}
}
pub fn decompress_spl_tokens(
inputs: &CompressedTokenInstructionDataTransfer,
ctx: &Context<TransferInstruction>,
) -> Result<()> {
let recipient = match ctx.accounts.compress_or_decompress_token_account.as_ref() {
Some(compression_recipient) => compression_recipient.to_account_info(),
None => return err!(crate::ErrorCode::DecompressRecipientUndefinedForDecompress),
};
let token_pool_pda = match ctx.accounts.token_pool_pda.as_ref() {
Some(token_pool_pda) => token_pool_pda.to_account_info(),
None => return err!(crate::ErrorCode::CompressedPdaUndefinedForDecompress),
};
spl_token_pool_derivation(&inputs.mint, &crate::ID, &token_pool_pda.key())?;
let amount = match inputs.compress_or_decompress_amount {
Some(amount) => amount,
None => return err!(crate::ErrorCode::DeCompressAmountUndefinedForDecompress),
};
transfer(
token_pool_pda,
recipient,
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts
.token_program
.as_ref()
.unwrap()
.to_account_info(),
amount,
)
}
pub fn compress_spl_tokens(
inputs: &CompressedTokenInstructionDataTransfer,
ctx: &Context<TransferInstruction>,
) -> Result<()> {
let recipient_token_pool = match ctx.accounts.token_pool_pda.as_ref() {
Some(token_pool_pda) => token_pool_pda,
None => return err!(crate::ErrorCode::CompressedPdaUndefinedForCompress),
};
spl_token_pool_derivation(&inputs.mint, &crate::ID, &recipient_token_pool.key())?;
let amount = match inputs.compress_or_decompress_amount {
Some(amount) => amount,
None => return err!(crate::ErrorCode::DeCompressAmountUndefinedForCompress),
};
transfer_compress(
ctx.accounts
.compress_or_decompress_token_account
.as_ref()
.unwrap()
.to_account_info(),
recipient_token_pool.to_account_info(),
ctx.accounts.authority.to_account_info(),
ctx.accounts
.token_program
.as_ref()
.unwrap()
.to_account_info(),
amount,
)
}
pub fn transfer<'info>(
from: AccountInfo<'info>,
to: AccountInfo<'info>,
authority: AccountInfo<'info>,
token_program: AccountInfo<'info>,
amount: u64,
) -> Result<()> {
let signer_seeds = get_cpi_signer_seeds();
let signer_seeds_ref = &[&signer_seeds[..]];
let accounts = token_interface::Transfer {
from,
to,
authority,
};
let cpi_ctx = CpiContext::new_with_signer(token_program, accounts, signer_seeds_ref);
anchor_spl::token_interface::transfer(cpi_ctx, amount)
}
pub fn transfer_compress<'info>(
from: AccountInfo<'info>,
to: AccountInfo<'info>,
authority: AccountInfo<'info>,
token_program: AccountInfo<'info>,
amount: u64,
) -> Result<()> {
let accounts = token_interface::Transfer {
from,
to,
authority,
};
let cpi_ctx = CpiContext::new(token_program, accounts);
anchor_spl::token_interface::transfer(cpi_ctx, amount)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/burn.rs
|
use anchor_lang::prelude::*;
use anchor_spl::token::TokenAccount;
use light_system_program::{
invoke::processor::CompressedProof,
sdk::{compressed_account::PackedCompressedAccountWithMerkleContext, CompressedCpiContext},
OutputCompressedAccountWithPackedContext,
};
use light_utils::hash_to_bn254_field_size_be;
use crate::{
constants::NOT_FROZEN,
process_transfer::{
add_token_data_to_input_compressed_accounts, cpi_execute_compressed_transaction_transfer,
create_output_compressed_accounts, get_cpi_signer_seeds,
get_input_compressed_accounts_with_merkle_context_and_check_signer, DelegatedTransfer,
InputTokenDataWithContext,
},
BurnInstruction, ErrorCode,
};
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct CompressedTokenInstructionDataBurn {
pub proof: CompressedProof,
pub input_token_data_with_context: Vec<InputTokenDataWithContext>,
pub cpi_context: Option<CompressedCpiContext>,
pub burn_amount: u64,
pub change_account_merkle_tree_index: u8,
pub delegated_transfer: Option<DelegatedTransfer>,
}
pub fn process_burn<'a, 'b, 'c, 'info: 'b + 'c>(
ctx: Context<'a, 'b, 'c, 'info, BurnInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
let inputs: CompressedTokenInstructionDataBurn =
CompressedTokenInstructionDataBurn::deserialize(&mut inputs.as_slice())?;
burn_spl_from_pool_pda(&ctx, &inputs)?;
let mint = ctx.accounts.mint.key();
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_burn(
&inputs,
&ctx.accounts.authority.key(),
ctx.remaining_accounts,
&mint,
)?;
cpi_execute_compressed_transaction_transfer(
ctx.accounts,
compressed_input_accounts,
&output_compressed_accounts,
Some(inputs.proof),
inputs.cpi_context,
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts.light_system_program.to_account_info(),
ctx.accounts.self_program.to_account_info(),
ctx.remaining_accounts,
)?;
Ok(())
}
#[inline(never)]
pub fn burn_spl_from_pool_pda<'info>(
ctx: &Context<'_, '_, '_, 'info, BurnInstruction<'info>>,
inputs: &CompressedTokenInstructionDataBurn,
) -> Result<()> {
let pre_token_balance = ctx.accounts.token_pool_pda.amount;
let cpi_accounts = anchor_spl::token_interface::Burn {
mint: ctx.accounts.mint.to_account_info(),
from: ctx.accounts.token_pool_pda.to_account_info(),
authority: ctx.accounts.cpi_authority_pda.to_account_info(),
};
let signer_seeds = get_cpi_signer_seeds();
let signer_seeds_ref = &[&signer_seeds[..]];
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
cpi_accounts,
signer_seeds_ref,
);
anchor_spl::token_interface::burn(cpi_ctx, inputs.burn_amount)?;
let post_token_balance = TokenAccount::try_deserialize(
&mut &ctx.accounts.token_pool_pda.to_account_info().data.borrow()[..],
)?
.amount;
// Guard against unexpected behavior of the SPL token program.
if post_token_balance != pre_token_balance - inputs.burn_amount {
msg!(
"post_token_balance {} != pre_token_balance {} - burn_amount {}",
post_token_balance,
pre_token_balance,
inputs.burn_amount
);
return err!(crate::ErrorCode::SplTokenSupplyMismatch);
}
Ok(())
}
pub fn create_input_and_output_accounts_burn(
inputs: &CompressedTokenInstructionDataBurn,
authority: &Pubkey,
remaining_accounts: &[AccountInfo<'_>],
mint: &Pubkey,
) -> Result<(
Vec<PackedCompressedAccountWithMerkleContext>,
Vec<OutputCompressedAccountWithPackedContext>,
)> {
let (mut compressed_input_accounts, input_token_data, sum_lamports) =
get_input_compressed_accounts_with_merkle_context_and_check_signer::<NOT_FROZEN>(
authority,
&inputs.delegated_transfer,
remaining_accounts,
&inputs.input_token_data_with_context,
mint,
)?;
let sum_inputs = input_token_data.iter().map(|x| x.amount).sum::<u64>();
let change_amount = match sum_inputs.checked_sub(inputs.burn_amount) {
Some(change_amount) => change_amount,
None => return err!(ErrorCode::ArithmeticUnderflow),
};
let hashed_mint = match hash_to_bn254_field_size_be(&mint.to_bytes()) {
Some(hashed_mint) => hashed_mint.0,
None => return err!(ErrorCode::HashToFieldError),
};
let output_compressed_accounts = if change_amount > 0 || sum_lamports > 0 {
let (is_delegate, authority, delegate) =
if let Some(delegated_transfer) = inputs.delegated_transfer.as_ref() {
let mut vec = vec![false; 1];
if let Some(index) = delegated_transfer.delegate_change_account_index {
vec[index as usize] = true;
} else {
return err!(crate::ErrorCode::InvalidDelegateIndex);
}
(Some(vec), delegated_transfer.owner, Some(*authority))
} else {
(None, *authority, None)
};
let mut output_compressed_accounts =
vec![OutputCompressedAccountWithPackedContext::default(); 1];
let lamports = if sum_lamports > 0 {
Some(vec![Some(sum_lamports)])
} else {
None
};
create_output_compressed_accounts(
&mut output_compressed_accounts,
*mint,
&[authority; 1],
delegate,
is_delegate,
&[change_amount],
lamports,
&hashed_mint,
&[inputs.change_account_merkle_tree_index],
)?;
output_compressed_accounts
} else {
Vec::new()
};
add_token_data_to_input_compressed_accounts::<NOT_FROZEN>(
&mut compressed_input_accounts,
input_token_data.as_slice(),
&hashed_mint,
)?;
Ok((compressed_input_accounts, output_compressed_accounts))
}
#[cfg(not(target_os = "solana"))]
pub mod sdk {
use anchor_lang::{AnchorSerialize, InstructionData, ToAccountMetas};
use light_system_program::{
invoke::processor::CompressedProof,
sdk::compressed_account::{CompressedAccount, MerkleContext},
};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
use crate::{
get_token_pool_pda,
process_transfer::{
get_cpi_authority_pda,
transfer_sdk::{
create_input_output_and_remaining_accounts, to_account_metas, TransferSdkError,
},
DelegatedTransfer,
},
token_data::TokenData,
};
use super::CompressedTokenInstructionDataBurn;
pub struct CreateBurnInstructionInputs {
pub fee_payer: Pubkey,
pub authority: Pubkey,
pub root_indices: Vec<u16>,
pub proof: CompressedProof,
pub input_token_data: Vec<TokenData>,
pub input_compressed_accounts: Vec<CompressedAccount>,
pub input_merkle_contexts: Vec<MerkleContext>,
pub change_account_merkle_tree: Pubkey,
pub mint: Pubkey,
pub burn_amount: u64,
pub signer_is_delegate: bool,
pub is_token_22: bool,
}
pub fn create_burn_instruction(
inputs: CreateBurnInstructionInputs,
) -> Result<Instruction, TransferSdkError> {
let (remaining_accounts, input_token_data_with_context, _) =
create_input_output_and_remaining_accounts(
&[inputs.change_account_merkle_tree],
&inputs.input_token_data,
&inputs.input_compressed_accounts,
&inputs.input_merkle_contexts,
&inputs.root_indices,
&Vec::new(),
);
let outputs_merkle_tree_index =
match remaining_accounts.get(&inputs.change_account_merkle_tree) {
Some(index) => index,
None => return Err(TransferSdkError::AccountNotFound),
};
let delegated_transfer = if inputs.signer_is_delegate {
let delegated_transfer = DelegatedTransfer {
owner: inputs.input_token_data[0].owner,
delegate_change_account_index: Some(0),
};
Some(delegated_transfer)
} else {
None
};
let inputs_struct = CompressedTokenInstructionDataBurn {
proof: inputs.proof,
input_token_data_with_context,
cpi_context: None,
change_account_merkle_tree_index: *outputs_merkle_tree_index as u8,
delegated_transfer,
burn_amount: inputs.burn_amount,
};
let remaining_accounts = to_account_metas(remaining_accounts);
let mut serialized_ix_data = Vec::new();
CompressedTokenInstructionDataBurn::serialize(&inputs_struct, &mut serialized_ix_data)
.map_err(|_| TransferSdkError::SerializationError)?;
let (cpi_authority_pda, _) = get_cpi_authority_pda();
let data = crate::instruction::Burn {
inputs: serialized_ix_data,
}
.data();
let token_pool_pda = get_token_pool_pda(&inputs.mint);
let token_program = if inputs.is_token_22 {
anchor_spl::token_2022::ID
} else {
spl_token::ID
};
let accounts = crate::accounts::BurnInstruction {
fee_payer: inputs.fee_payer,
authority: inputs.authority,
cpi_authority_pda,
mint: inputs.mint,
token_pool_pda,
token_program,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
self_program: crate::ID,
system_program: solana_sdk::system_program::ID,
};
Ok(Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data,
})
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
freeze::test_freeze::{
create_expected_input_accounts, create_expected_token_output_accounts,
get_rnd_input_token_data_with_contexts,
},
token_data::AccountState,
TokenData,
};
use anchor_lang::solana_program::account_info::AccountInfo;
use light_system_program::sdk::compressed_account::PackedMerkleContext;
use rand::Rng;
// TODO: add randomized and edge case tests
#[test]
fn test_burn() {
let merkle_tree_pubkey = Pubkey::new_unique();
let mut merkle_tree_account_lamports = 0;
let mut merkle_tree_account_data = Vec::new();
let nullifier_queue_pubkey = Pubkey::new_unique();
let mut nullifier_queue_account_lamports = 0;
let mut nullifier_queue_account_data = Vec::new();
let remaining_accounts = vec![
AccountInfo::new(
&merkle_tree_pubkey,
false,
false,
&mut merkle_tree_account_lamports,
&mut merkle_tree_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&nullifier_queue_pubkey,
false,
false,
&mut nullifier_queue_account_lamports,
&mut nullifier_queue_account_data,
&account_compression::ID,
false,
0,
),
];
let authority = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let test_amounts = vec![0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000];
for test_amount in test_amounts {
let input_token_data_with_context = vec![InputTokenDataWithContext {
amount: test_amount,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 1,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1),
lamports: None,
tlv: None,
}];
let inputs = CompressedTokenInstructionDataBurn {
proof: CompressedProof::default(),
input_token_data_with_context,
cpi_context: None,
burn_amount: std::cmp::min(50, test_amount),
change_account_merkle_tree_index: 0,
delegated_transfer: None,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_burn(
&inputs,
&authority,
&remaining_accounts,
&mint,
)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 1);
let change_amount = test_amount.saturating_sub(inputs.burn_amount);
assert_eq!(
output_compressed_accounts.len(),
std::cmp::min(1, change_amount) as usize
);
if change_amount != 0 {
let expected_change_token_data = TokenData {
mint,
owner: authority,
amount: change_amount,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts = create_expected_token_output_accounts(
vec![expected_change_token_data],
vec![0],
);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
}
}
#[test]
fn test_rnd_burn() {
let mut rng = rand::rngs::ThreadRng::default();
let merkle_tree_pubkey = Pubkey::new_unique();
let mut merkle_tree_account_lamports = 0;
let mut merkle_tree_account_data = Vec::new();
let nullifier_queue_pubkey = Pubkey::new_unique();
let mut nullifier_queue_account_lamports = 0;
let mut nullifier_queue_account_data = Vec::new();
let remaining_accounts = vec![
AccountInfo::new(
&merkle_tree_pubkey,
false,
false,
&mut merkle_tree_account_lamports,
&mut merkle_tree_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&nullifier_queue_pubkey,
false,
false,
&mut nullifier_queue_account_lamports,
&mut nullifier_queue_account_data,
&account_compression::ID,
false,
0,
),
];
let iter = 1_000;
for _ in 0..iter {
let authority = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let num_inputs = rng.gen_range(1..=8);
let input_token_data_with_context =
get_rnd_input_token_data_with_contexts(&mut rng, num_inputs);
let sum_inputs = input_token_data_with_context
.iter()
.map(|x| x.amount)
.sum::<u64>();
let burn_amount = rng.gen_range(0..sum_inputs);
let inputs = CompressedTokenInstructionDataBurn {
proof: CompressedProof::default(),
input_token_data_with_context: input_token_data_with_context.clone(),
cpi_context: None,
burn_amount,
change_account_merkle_tree_index: 0,
delegated_transfer: None,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_burn(
&inputs,
&authority,
&remaining_accounts,
&mint,
)
.unwrap();
let expected_input_accounts = create_expected_input_accounts(
&input_token_data_with_context,
&mint,
&authority,
remaining_accounts
.iter()
.map(|x| x.key)
.cloned()
.collect::<Vec<_>>()
.as_slice(),
);
assert_eq!(compressed_input_accounts, expected_input_accounts);
assert_eq!(compressed_input_accounts.len(), num_inputs);
assert_eq!(output_compressed_accounts.len(), 1);
let expected_change_token_data = TokenData {
mint,
owner: authority,
amount: sum_inputs - burn_amount,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts =
create_expected_token_output_accounts(vec![expected_change_token_data], vec![0]);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
}
#[test]
fn failing_tests_burn() {
let merkle_tree_pubkey = Pubkey::new_unique();
let mut merkle_tree_account_lamports = 0;
let mut merkle_tree_account_data = Vec::new();
let nullifier_queue_pubkey = Pubkey::new_unique();
let mut nullifier_queue_account_lamports = 0;
let mut nullifier_queue_account_data = Vec::new();
let remaining_accounts = vec![
AccountInfo::new(
&merkle_tree_pubkey,
false,
false,
&mut merkle_tree_account_lamports,
&mut merkle_tree_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&nullifier_queue_pubkey,
false,
false,
&mut nullifier_queue_account_lamports,
&mut nullifier_queue_account_data,
&account_compression::ID,
false,
0,
),
];
let authority = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let input_token_data_with_context = vec![InputTokenDataWithContext {
amount: 100,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 1,
queue_index: None,
},
root_index: 0,
delegate_index: Some(1),
lamports: None,
tlv: None,
}];
// Burn amount too high
{
let mut invalid_input_token_data_with_context = input_token_data_with_context.clone();
invalid_input_token_data_with_context[0].amount = 0;
let inputs = CompressedTokenInstructionDataBurn {
proof: CompressedProof::default(),
input_token_data_with_context: invalid_input_token_data_with_context,
cpi_context: None,
burn_amount: 50,
change_account_merkle_tree_index: 1,
delegated_transfer: None,
};
let result = create_input_and_output_accounts_burn(
&inputs,
&authority,
&remaining_accounts,
&mint,
);
let error_code = ErrorCode::ArithmeticUnderflow as u32 + 6000;
assert!(matches!(
result.unwrap_err(),
anchor_lang::error::Error::AnchorError(error) if error.error_code_number == error_code
));
}
// invalid authority
{
let invalid_authority = Pubkey::new_unique();
let inputs = CompressedTokenInstructionDataBurn {
proof: CompressedProof::default(),
input_token_data_with_context: input_token_data_with_context.clone(),
cpi_context: None,
burn_amount: 50,
change_account_merkle_tree_index: 1,
delegated_transfer: None,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_burn(
&inputs,
&invalid_authority,
&remaining_accounts,
&mint,
)
.unwrap();
let expected_input_accounts = create_expected_input_accounts(
&input_token_data_with_context,
&mint,
&invalid_authority,
remaining_accounts
.iter()
.map(|x| x.key)
.cloned()
.collect::<Vec<_>>()
.as_slice(),
);
assert_eq!(compressed_input_accounts, expected_input_accounts);
let expected_change_token_data = TokenData {
mint,
owner: invalid_authority,
amount: 50,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts =
create_expected_token_output_accounts(vec![expected_change_token_data], vec![1]);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
// Invalid Mint
{
let mut invalid_input_token_data_with_context = input_token_data_with_context.clone();
invalid_input_token_data_with_context[0].amount = 0;
let invalid_mint = Pubkey::new_unique();
let inputs = CompressedTokenInstructionDataBurn {
proof: CompressedProof::default(),
input_token_data_with_context: input_token_data_with_context.clone(),
cpi_context: None,
burn_amount: 50,
change_account_merkle_tree_index: 1,
delegated_transfer: None,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_burn(
&inputs,
&authority,
&remaining_accounts,
&invalid_mint,
)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 1);
assert_eq!(output_compressed_accounts.len(), 1);
let expected_input_accounts = create_expected_input_accounts(
&input_token_data_with_context,
&invalid_mint,
&authority,
remaining_accounts
.iter()
.map(|x| x.key)
.cloned()
.collect::<Vec<_>>()
.as_slice(),
);
assert_eq!(compressed_input_accounts, expected_input_accounts);
let expected_change_token_data = TokenData {
mint: invalid_mint,
owner: authority,
amount: 50,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts =
create_expected_token_output_accounts(vec![expected_change_token_data], vec![1]);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/freeze.rs
|
use anchor_lang::prelude::*;
use light_hasher::DataHasher;
use light_hasher::Poseidon;
use light_system_program::{
invoke::processor::CompressedProof,
sdk::{
compressed_account::{
CompressedAccount, CompressedAccountData, PackedCompressedAccountWithMerkleContext,
},
CompressedCpiContext,
},
OutputCompressedAccountWithPackedContext,
};
use light_utils::hash_to_bn254_field_size_be;
use crate::{
constants::TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
process_transfer::{
add_token_data_to_input_compressed_accounts, cpi_execute_compressed_transaction_transfer,
get_input_compressed_accounts_with_merkle_context_and_check_signer,
InputTokenDataWithContext,
},
token_data::{AccountState, TokenData},
FreezeInstruction,
};
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct CompressedTokenInstructionDataFreeze {
pub proof: CompressedProof,
pub owner: Pubkey,
pub input_token_data_with_context: Vec<InputTokenDataWithContext>,
pub cpi_context: Option<CompressedCpiContext>,
pub outputs_merkle_tree_index: u8,
}
pub fn process_freeze_or_thaw<
'a,
'b,
'c,
'info: 'b + 'c,
const FROZEN_INPUTS: bool,
const FROZEN_OUTPUTS: bool,
>(
ctx: Context<'a, 'b, 'c, 'info, FreezeInstruction<'info>>,
inputs: Vec<u8>,
) -> Result<()> {
let inputs: CompressedTokenInstructionDataFreeze =
CompressedTokenInstructionDataFreeze::deserialize(&mut inputs.as_slice())?;
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_freeze_or_thaw::<FROZEN_INPUTS, FROZEN_OUTPUTS>(
&inputs,
&ctx.accounts.mint.key(),
ctx.remaining_accounts,
)?;
cpi_execute_compressed_transaction_transfer(
ctx.accounts,
compressed_input_accounts,
&output_compressed_accounts,
Some(inputs.proof),
inputs.cpi_context,
ctx.accounts.cpi_authority_pda.to_account_info(),
ctx.accounts.light_system_program.to_account_info(),
ctx.accounts.self_program.to_account_info(),
ctx.remaining_accounts,
)
}
pub fn create_input_and_output_accounts_freeze_or_thaw<
const FROZEN_INPUTS: bool,
const FROZEN_OUTPUTS: bool,
>(
inputs: &CompressedTokenInstructionDataFreeze,
mint: &Pubkey,
remaining_accounts: &[AccountInfo<'_>],
) -> Result<(
Vec<PackedCompressedAccountWithMerkleContext>,
Vec<OutputCompressedAccountWithPackedContext>,
)> {
if inputs.input_token_data_with_context.is_empty() {
return err!(crate::ErrorCode::NoInputTokenAccountsProvided);
}
let (mut compressed_input_accounts, input_token_data, _) =
get_input_compressed_accounts_with_merkle_context_and_check_signer::<FROZEN_INPUTS>(
// The signer in this case is the freeze authority. The owner is not
// required to sign for this instruction. Hence, we pass the owner
// from a variable instead of an account to still reproduce value
// token data hashes for the input accounts.
&inputs.owner,
&None,
remaining_accounts,
&inputs.input_token_data_with_context,
mint,
)?;
let output_len = compressed_input_accounts.len();
let mut output_compressed_accounts =
vec![OutputCompressedAccountWithPackedContext::default(); output_len];
let hashed_mint = hash_to_bn254_field_size_be(mint.to_bytes().as_slice())
.unwrap()
.0;
create_token_output_accounts::<FROZEN_OUTPUTS>(
inputs.input_token_data_with_context.as_slice(),
remaining_accounts,
mint,
// The signer in this case is the freeze authority. The owner is not
// required to sign for this instruction. Hence, we pass the owner
// from a variable instead of an account to still reproduce value
// token data hashes for the input accounts.
&inputs.owner,
&inputs.outputs_merkle_tree_index,
&mut output_compressed_accounts,
)?;
add_token_data_to_input_compressed_accounts::<FROZEN_INPUTS>(
&mut compressed_input_accounts,
input_token_data.as_slice(),
&hashed_mint,
)?;
Ok((compressed_input_accounts, output_compressed_accounts))
}
/// This is a separate function from create_output_compressed_accounts to allow
/// for a flexible number of delegates. create_output_compressed_accounts only
/// supports one delegate.
fn create_token_output_accounts<const IS_FROZEN: bool>(
input_token_data_with_context: &[InputTokenDataWithContext],
remaining_accounts: &[AccountInfo],
mint: &Pubkey,
owner: &Pubkey,
outputs_merkle_tree_index: &u8,
output_compressed_accounts: &mut [OutputCompressedAccountWithPackedContext],
) -> Result<()> {
for (i, token_data_with_context) in input_token_data_with_context.iter().enumerate() {
// 106/74 =
// 32 mint
// + 32 owner
// + 8 amount
// + 1 + 32 option + delegate (optional)
// + 1 state
// + 1 tlv
let capacity = if token_data_with_context.delegate_index.is_some() {
107
} else {
75
};
let mut token_data_bytes = Vec::with_capacity(capacity);
let delegate = token_data_with_context
.delegate_index
.map(|index| remaining_accounts[index as usize].key());
let state = if IS_FROZEN {
AccountState::Frozen
} else {
AccountState::Initialized
};
// 1,000 CU token data and serialize
let token_data = TokenData {
mint: *mint,
owner: *owner,
amount: token_data_with_context.amount,
delegate,
state,
tlv: None,
};
token_data.serialize(&mut token_data_bytes).unwrap();
let data_hash = token_data.hash::<Poseidon>().map_err(ProgramError::from)?;
let data: CompressedAccountData = CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data: token_data_bytes,
data_hash,
};
output_compressed_accounts[i] = OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: crate::ID,
lamports: token_data_with_context.lamports.unwrap_or(0),
data: Some(data),
address: None,
},
merkle_tree_index: *outputs_merkle_tree_index,
};
}
Ok(())
}
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct CompressedTokenInstructionDataThaw {
pub proof: CompressedProof,
pub owner: Pubkey,
pub input_token_data_with_context: Vec<InputTokenDataWithContext>,
pub cpi_context: Option<CompressedCpiContext>,
pub outputs_merkle_tree_index: u8,
}
#[cfg(not(target_os = "solana"))]
pub mod sdk {
use anchor_lang::{AnchorSerialize, InstructionData, ToAccountMetas};
use light_system_program::{
invoke::processor::CompressedProof,
sdk::compressed_account::{CompressedAccount, MerkleContext},
};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
use crate::{
process_transfer::transfer_sdk::{
create_input_output_and_remaining_accounts, to_account_metas, TransferSdkError,
},
token_data::TokenData,
};
use super::CompressedTokenInstructionDataFreeze;
pub struct CreateInstructionInputs {
pub fee_payer: Pubkey,
pub authority: Pubkey,
pub root_indices: Vec<u16>,
pub proof: CompressedProof,
pub input_token_data: Vec<TokenData>,
pub input_compressed_accounts: Vec<CompressedAccount>,
pub input_merkle_contexts: Vec<MerkleContext>,
pub outputs_merkle_tree: Pubkey,
}
pub fn create_instruction<const FREEZE: bool>(
inputs: CreateInstructionInputs,
) -> Result<Instruction, TransferSdkError> {
let (remaining_accounts, input_token_data_with_context, _) =
create_input_output_and_remaining_accounts(
&[inputs.outputs_merkle_tree],
&inputs.input_token_data,
&inputs.input_compressed_accounts,
&inputs.input_merkle_contexts,
&inputs.root_indices,
&Vec::new(),
);
let outputs_merkle_tree_index =
remaining_accounts.get(&inputs.outputs_merkle_tree).unwrap();
let inputs_struct = CompressedTokenInstructionDataFreeze {
proof: inputs.proof,
input_token_data_with_context,
cpi_context: None,
outputs_merkle_tree_index: *outputs_merkle_tree_index as u8,
owner: inputs.input_token_data[0].owner,
};
let remaining_accounts = to_account_metas(remaining_accounts);
let mut serialized_ix_data = Vec::new();
CompressedTokenInstructionDataFreeze::serialize(&inputs_struct, &mut serialized_ix_data)
.unwrap();
let (cpi_authority_pda, _) = crate::process_transfer::get_cpi_authority_pda();
let data = if FREEZE {
crate::instruction::Freeze {
inputs: serialized_ix_data,
}
.data()
} else {
crate::instruction::Thaw {
inputs: serialized_ix_data,
}
.data()
};
let accounts = crate::accounts::FreezeInstruction {
fee_payer: inputs.fee_payer,
authority: inputs.authority,
cpi_authority_pda,
light_system_program: light_system_program::ID,
registered_program_pda: light_system_program::utils::get_registered_program_pda(
&light_system_program::ID,
),
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_authority: light_system_program::utils::get_cpi_authority_pda(
&light_system_program::ID,
),
account_compression_program: account_compression::ID,
self_program: crate::ID,
system_program: solana_sdk::system_program::ID,
mint: inputs.input_token_data[0].mint,
};
Ok(Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data,
})
}
pub fn create_freeze_instruction(
inputs: CreateInstructionInputs,
) -> Result<Instruction, TransferSdkError> {
create_instruction::<true>(inputs)
}
pub fn create_thaw_instruction(
inputs: CreateInstructionInputs,
) -> Result<Instruction, TransferSdkError> {
create_instruction::<false>(inputs)
}
}
#[cfg(test)]
pub mod test_freeze {
use crate::{
constants::TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR, token_data::AccountState, TokenData,
};
use rand::Rng;
use super::*;
use anchor_lang::solana_program::account_info::AccountInfo;
use light_hasher::{DataHasher, Poseidon};
use light_system_program::sdk::compressed_account::{
CompressedAccount, CompressedAccountData, PackedMerkleContext,
};
// TODO: add randomized and edge case tests
#[test]
fn test_freeze() {
let merkle_tree_pubkey = Pubkey::new_unique();
let mut merkle_tree_account_lamports = 0;
let mut merkle_tree_account_data = Vec::new();
let nullifier_queue_pubkey = Pubkey::new_unique();
let mut nullifier_queue_account_lamports = 0;
let mut nullifier_queue_account_data = Vec::new();
let delegate = Pubkey::new_unique();
let mut delegate_account_lamports = 0;
let mut delegate_account_data = Vec::new();
let remaining_accounts = vec![
AccountInfo::new(
&merkle_tree_pubkey,
false,
false,
&mut merkle_tree_account_lamports,
&mut merkle_tree_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&nullifier_queue_pubkey,
false,
false,
&mut nullifier_queue_account_lamports,
&mut nullifier_queue_account_data,
&account_compression::ID,
false,
0,
),
AccountInfo::new(
&delegate,
false,
false,
&mut delegate_account_lamports,
&mut delegate_account_data,
&account_compression::ID,
false,
0,
),
];
let owner = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let input_token_data_with_context = vec![
InputTokenDataWithContext {
amount: 100,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 1,
queue_index: None,
},
root_index: 0,
delegate_index: None,
lamports: None,
tlv: None,
},
InputTokenDataWithContext {
amount: 101,
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: 2,
queue_index: None,
},
root_index: 0,
delegate_index: Some(2),
lamports: None,
tlv: None,
},
];
// Freeze
{
let inputs = CompressedTokenInstructionDataFreeze {
proof: CompressedProof::default(),
owner,
input_token_data_with_context: input_token_data_with_context.clone(),
cpi_context: None,
outputs_merkle_tree_index: 1,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_freeze_or_thaw::<false, true>(
&inputs,
&mint,
&remaining_accounts,
)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 2);
assert_eq!(output_compressed_accounts.len(), 2);
let expected_change_token_data = TokenData {
mint,
owner,
amount: 100,
delegate: None,
state: AccountState::Frozen,
tlv: None,
};
let expected_delegated_token_data = TokenData {
mint,
owner,
amount: 101,
delegate: Some(delegate),
state: AccountState::Frozen,
tlv: None,
};
let expected_compressed_output_accounts = create_expected_token_output_accounts(
vec![expected_change_token_data, expected_delegated_token_data],
vec![1u8; 2],
);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
}
// Thaw
{
let inputs = CompressedTokenInstructionDataFreeze {
proof: CompressedProof::default(),
owner,
input_token_data_with_context,
cpi_context: None,
outputs_merkle_tree_index: 1,
};
let (compressed_input_accounts, output_compressed_accounts) =
create_input_and_output_accounts_freeze_or_thaw::<true, false>(
&inputs,
&mint,
&remaining_accounts,
)
.unwrap();
assert_eq!(compressed_input_accounts.len(), 2);
assert_eq!(output_compressed_accounts.len(), 2);
let expected_change_token_data = TokenData {
mint,
owner,
amount: 100,
delegate: None,
state: AccountState::Initialized,
tlv: None,
};
let expected_delegated_token_data = TokenData {
mint,
owner,
amount: 101,
delegate: Some(delegate),
state: AccountState::Initialized,
tlv: None,
};
let expected_compressed_output_accounts = create_expected_token_output_accounts(
vec![expected_change_token_data, expected_delegated_token_data],
vec![1u8; 2],
);
assert_eq!(
output_compressed_accounts,
expected_compressed_output_accounts
);
for account in compressed_input_accounts {
let account_data = account.compressed_account.data.unwrap();
let token_data = TokenData::try_from_slice(&account_data.data).unwrap();
assert_eq!(token_data.state, AccountState::Frozen);
}
}
}
pub fn create_expected_token_output_accounts(
expected_token_data: Vec<TokenData>,
merkle_tree_indices: Vec<u8>,
) -> Vec<OutputCompressedAccountWithPackedContext> {
let mut expected_compressed_output_accounts = Vec::new();
for (token_data, merkle_tree_index) in
expected_token_data.iter().zip(merkle_tree_indices.iter())
{
let serialized_expected_token_data = token_data.try_to_vec().unwrap();
let change_data_struct = CompressedAccountData {
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
data: serialized_expected_token_data.clone(),
data_hash: token_data.hash::<Poseidon>().unwrap(),
};
expected_compressed_output_accounts.push(OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: crate::ID,
lamports: 0,
data: Some(change_data_struct),
address: None,
},
merkle_tree_index: *merkle_tree_index,
});
}
expected_compressed_output_accounts
}
pub fn get_rnd_input_token_data_with_contexts(
rng: &mut rand::rngs::ThreadRng,
num: usize,
) -> Vec<InputTokenDataWithContext> {
let mut vec = Vec::with_capacity(num);
for _ in 0..num {
let delegate_index = if rng.gen_bool(0.5) { Some(1) } else { None };
vec.push(InputTokenDataWithContext {
amount: rng.gen_range(0..1_000_000_000),
merkle_context: PackedMerkleContext {
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
leaf_index: rng.gen_range(0..1_000_000_000),
queue_index: None,
},
root_index: rng.gen_range(0..=65_535),
delegate_index,
lamports: None,
tlv: None,
});
}
vec
}
pub fn create_expected_input_accounts(
input_token_data_with_context: &Vec<InputTokenDataWithContext>,
mint: &Pubkey,
owner: &Pubkey,
remaining_accounts: &[Pubkey],
) -> Vec<PackedCompressedAccountWithMerkleContext> {
use light_hasher::DataHasher;
input_token_data_with_context
.iter()
.map(|x| {
let delegate = if let Some(index) = x.delegate_index {
Some(remaining_accounts[index as usize])
} else {
None
};
let token_data = TokenData {
mint: *mint,
owner: *owner,
amount: x.amount,
delegate,
state: AccountState::Initialized,
tlv: None,
};
let mut data = Vec::new();
token_data.serialize(&mut data).unwrap();
let data_hash = token_data.hash::<Poseidon>().unwrap();
PackedCompressedAccountWithMerkleContext {
compressed_account: CompressedAccount {
owner: crate::ID,
lamports: 0,
address: None,
data: Some(CompressedAccountData {
data,
data_hash,
discriminator: TOKEN_COMPRESSED_ACCOUNT_DISCRIMINATOR,
}),
},
root_index: x.root_index,
merkle_context: x.merkle_context,
read_only: false,
}
})
.collect()
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/instructions/generic.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use light_system_program::{
program::LightSystemProgram,
sdk::accounts::{InvokeAccounts, SignerAccounts},
};
use crate::program::LightCompressedToken;
#[derive(Accounts)]
pub struct GenericInstruction<'info> {
/// UNCHECKED: only pays fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
/// CHECK:
/// Authority is verified through proof since both owner and delegate
/// are included in the token data hash, which is a public input to the
/// validity proof.
pub authority: Signer<'info>,
/// CHECK: (seed constraint).
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump,)]
pub cpi_authority_pda: UncheckedAccount<'info>,
pub light_system_program: Program<'info, LightSystemProgram>,
/// CHECK: (account compression program).
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: (account compression program) when emitting event.
pub noop_program: UncheckedAccount<'info>,
/// CHECK: (different program) is used to cpi account compression program from light system program.
pub account_compression_authority: UncheckedAccount<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK:(system program) used to derive cpi_authority_pda and check that
/// this program is the signer of the cpi.
pub self_program: Program<'info, LightCompressedToken>,
pub system_program: Program<'info, System>,
}
impl<'info> InvokeAccounts<'info> for GenericInstruction<'info> {
fn get_registered_program_pda(&self) -> &AccountInfo<'info> {
&self.registered_program_pda
}
fn get_noop_program(&self) -> &UncheckedAccount<'info> {
&self.noop_program
}
fn get_account_compression_authority(&self) -> &UncheckedAccount<'info> {
&self.account_compression_authority
}
fn get_account_compression_program(&self) -> &Program<'info, AccountCompression> {
&self.account_compression_program
}
fn get_system_program(&self) -> &Program<'info, System> {
&self.system_program
}
fn get_sol_pool_pda(&self) -> Option<&AccountInfo<'info>> {
None
}
fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>> {
None
}
}
impl<'info> SignerAccounts<'info> for GenericInstruction<'info> {
fn get_fee_payer(&self) -> &Signer<'info> {
&self.fee_payer
}
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/instructions/mod.rs
|
pub mod burn;
pub mod create_token_pool;
pub mod freeze;
pub mod generic;
pub mod transfer;
pub use burn::*;
pub use create_token_pool::*;
pub use freeze::*;
pub use generic::*;
pub use transfer::*;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/instructions/create_token_pool.rs
|
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED;
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{Mint, TokenAccount, TokenInterface};
use spl_token_2022::{
extension::{BaseStateWithExtensions, ExtensionType, PodStateWithExtensions},
pod::PodMint,
};
pub const POOL_SEED: &[u8] = b"pool";
/// Creates an SPL or token-2022 token pool account, which is owned by the token authority PDA.
#[derive(Accounts)]
pub struct CreateTokenPoolInstruction<'info> {
/// UNCHECKED: only pays fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
#[account(
init,
seeds = [
POOL_SEED, &mint.key().to_bytes(),
],
bump,
payer = fee_payer,
token::mint = mint,
token::authority = cpi_authority_pda,
)]
pub token_pool_pda: InterfaceAccount<'info, TokenAccount>,
pub system_program: Program<'info, System>,
/// CHECK: is mint account.
#[account(mut)]
pub mint: InterfaceAccount<'info, Mint>,
pub token_program: Interface<'info, TokenInterface>,
/// CHECK: (seeds anchor constraint).
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
pub cpi_authority_pda: AccountInfo<'info>,
}
pub fn get_token_pool_pda(mint: &Pubkey) -> Pubkey {
let seeds = &[POOL_SEED, mint.as_ref()];
let (address, _) = Pubkey::find_program_address(seeds, &crate::ID);
address
}
const ALLOWED_EXTENSION_TYPES: [ExtensionType; 7] = [
ExtensionType::MetadataPointer,
ExtensionType::TokenMetadata,
ExtensionType::InterestBearingConfig,
ExtensionType::GroupPointer,
ExtensionType::GroupMemberPointer,
ExtensionType::TokenGroup,
ExtensionType::TokenGroupMember,
];
pub fn assert_mint_extensions(account_data: &[u8]) -> Result<()> {
let mint = PodStateWithExtensions::<PodMint>::unpack(account_data).unwrap();
let mint_extensions = mint.get_extension_types().unwrap();
if !mint_extensions
.iter()
.all(|item| ALLOWED_EXTENSION_TYPES.contains(item))
{
return err!(crate::ErrorCode::MintWithInvalidExtension);
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/instructions/burn.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{Mint, TokenAccount, TokenInterface};
use light_system_program::{
program::LightSystemProgram,
sdk::accounts::{InvokeAccounts, SignerAccounts},
};
use crate::{program::LightCompressedToken, POOL_SEED};
#[derive(Accounts)]
pub struct BurnInstruction<'info> {
/// UNCHECKED: only pays fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
/// CHECK:
/// Authority is verified through proof since both owner and delegate
/// are included in the token data hash, which is a public input to the
/// validity proof.
pub authority: Signer<'info>,
/// CHECK: (seed constraint).
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump,)]
pub cpi_authority_pda: UncheckedAccount<'info>,
/// CHECK: is used to burn tokens.
#[account(mut)]
pub mint: InterfaceAccount<'info, Mint>,
/// CHECK: (seed constraint) is derived from mint account.
#[account(mut, seeds = [POOL_SEED, mint.key().as_ref()], bump)]
pub token_pool_pda: InterfaceAccount<'info, TokenAccount>,
pub token_program: Interface<'info, TokenInterface>,
pub light_system_program: Program<'info, LightSystemProgram>,
/// CHECK: (account compression program).
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: (system program) when emitting event.
pub noop_program: UncheckedAccount<'info>,
/// CHECK: (system program) to cpi account compression program.
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump, seeds::program = light_system_program::ID,)]
pub account_compression_authority: UncheckedAccount<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
pub self_program: Program<'info, LightCompressedToken>,
pub system_program: Program<'info, System>,
}
impl<'info> InvokeAccounts<'info> for BurnInstruction<'info> {
fn get_registered_program_pda(&self) -> &AccountInfo<'info> {
&self.registered_program_pda
}
fn get_noop_program(&self) -> &UncheckedAccount<'info> {
&self.noop_program
}
fn get_account_compression_authority(&self) -> &UncheckedAccount<'info> {
&self.account_compression_authority
}
fn get_account_compression_program(&self) -> &Program<'info, AccountCompression> {
&self.account_compression_program
}
fn get_system_program(&self) -> &Program<'info, System> {
&self.system_program
}
fn get_sol_pool_pda(&self) -> Option<&AccountInfo<'info>> {
None
}
fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>> {
None
}
}
impl<'info> SignerAccounts<'info> for BurnInstruction<'info> {
fn get_fee_payer(&self) -> &Signer<'info> {
&self.fee_payer
}
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/instructions/freeze.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use anchor_spl::token_interface::Mint;
use light_system_program::{
program::LightSystemProgram,
sdk::accounts::{InvokeAccounts, SignerAccounts},
};
use crate::program::LightCompressedToken;
#[derive(Accounts)]
pub struct FreezeInstruction<'info> {
/// UNCHECKED: only pays fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
#[account(constraint= authority.key() == mint.freeze_authority.ok_or(crate::ErrorCode::MintHasNoFreezeAuthority)?
@ crate::ErrorCode::InvalidFreezeAuthority)]
pub authority: Signer<'info>,
/// CHECK: (seed constraint).
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump,)]
pub cpi_authority_pda: UncheckedAccount<'info>,
pub light_system_program: Program<'info, LightSystemProgram>,
/// CHECK: (account compression program).
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: (account compression program) when emitting event.
pub noop_program: UncheckedAccount<'info>,
/// CHECK: (different program) is used to cpi account compression program from light system program.
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump, seeds::program = light_system_program::ID,)]
pub account_compression_authority: UncheckedAccount<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK: (different system program) to derive cpi_authority_pda and check
/// that this program is the signer of the cpi.
pub self_program: Program<'info, LightCompressedToken>,
pub system_program: Program<'info, System>,
pub mint: InterfaceAccount<'info, Mint>,
}
impl<'info> InvokeAccounts<'info> for FreezeInstruction<'info> {
fn get_registered_program_pda(&self) -> &AccountInfo<'info> {
&self.registered_program_pda
}
fn get_noop_program(&self) -> &UncheckedAccount<'info> {
&self.noop_program
}
fn get_account_compression_authority(&self) -> &UncheckedAccount<'info> {
&self.account_compression_authority
}
fn get_account_compression_program(&self) -> &Program<'info, AccountCompression> {
&self.account_compression_program
}
fn get_system_program(&self) -> &Program<'info, System> {
&self.system_program
}
fn get_sol_pool_pda(&self) -> Option<&AccountInfo<'info>> {
None
}
fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>> {
None
}
}
impl<'info> SignerAccounts<'info> for FreezeInstruction<'info> {
fn get_fee_payer(&self) -> &Signer<'info> {
&self.fee_payer
}
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/compressed-token/src/instructions/transfer.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{TokenAccount, TokenInterface};
use light_system_program::{
self,
program::LightSystemProgram,
sdk::accounts::{InvokeAccounts, SignerAccounts},
};
use crate::program::LightCompressedToken;
#[derive(Accounts)]
pub struct TransferInstruction<'info> {
/// UNCHECKED: only pays fees.
#[account(mut)]
pub fee_payer: Signer<'info>,
/// CHECK:
/// Authority is verified through proof since both owner and delegate
/// are included in the token data hash, which is a public input to the
/// validity proof.
pub authority: Signer<'info>,
/// CHECK: (seed constraint).
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump,)]
pub cpi_authority_pda: UncheckedAccount<'info>,
pub light_system_program: Program<'info, LightSystemProgram>,
/// CHECK: (account compression program).
pub registered_program_pda: AccountInfo<'info>,
/// CHECK: (account compression program) when emitting event.
pub noop_program: UncheckedAccount<'info>,
/// CHECK: (different program) is used to cpi account compression program from light system program.
pub account_compression_authority: UncheckedAccount<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK:(system program) used to derive cpi_authority_pda and check that
/// this program is the signer of the cpi.
pub self_program: Program<'info, LightCompressedToken>,
#[account(mut)]
pub token_pool_pda: Option<InterfaceAccount<'info, TokenAccount>>,
#[account(mut, constraint= if token_pool_pda.is_some() {Ok(token_pool_pda.as_ref().unwrap().key() != compress_or_decompress_token_account.key())}else {err!(crate::ErrorCode::TokenPoolPdaUndefined)}? @crate::ErrorCode::IsTokenPoolPda)]
pub compress_or_decompress_token_account: Option<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Option<Interface<'info, TokenInterface>>,
pub system_program: Program<'info, System>,
}
// TODO: transform all to account info
impl<'info> InvokeAccounts<'info> for TransferInstruction<'info> {
fn get_registered_program_pda(&self) -> &AccountInfo<'info> {
&self.registered_program_pda
}
fn get_noop_program(&self) -> &UncheckedAccount<'info> {
&self.noop_program
}
fn get_account_compression_authority(&self) -> &UncheckedAccount<'info> {
&self.account_compression_authority
}
fn get_account_compression_program(&self) -> &Program<'info, AccountCompression> {
&self.account_compression_program
}
fn get_system_program(&self) -> &Program<'info, System> {
&self.system_program
}
fn get_sol_pool_pda(&self) -> Option<&AccountInfo<'info>> {
None
}
fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>> {
None
}
}
impl<'info> SignerAccounts<'info> for TransferInstruction<'info> {
fn get_fee_payer(&self) -> &Signer<'info> {
&self.fee_payer
}
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/Cargo.toml
|
[package]
name = "account-compression"
version = "1.2.0"
description = "Solana account compression program"
repository = "https://github.com/Lightprotocol/light-protocol"
license = "Apache-2.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "account_compression"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
custom-heap = ["light-heap"]
mem-profiling = []
default = ["custom-heap"]
test-sbf = []
bench-sbf = []
[dependencies]
aligned-sized = { version = "1.1.0", path = "../../macros/aligned-sized" }
anchor-lang = { workspace = true }
bytemuck = { version = "1.17", features = ["min_const_generics"] }
light-bounded-vec = { version = "1.1.0", path = "../../merkle-tree/bounded-vec", features = ["solana"] }
light-hash-set = { workspace = true, features = ["solana"] }
light-hasher = { version = "1.1.0", path = "../../merkle-tree/hasher", features = ["solana"] }
light-heap = { version = "1.1.0", path = "../../heap", optional = true }
light-concurrent-merkle-tree = { version = "1.1.0", path = "../../merkle-tree/concurrent", features = ["solana"] }
light-indexed-merkle-tree = { version = "1.1.0", path = "../../merkle-tree/indexed", features = ["solana"] }
light-utils = { version = "1.1.0", path = "../../utils" }
num-bigint = "0.4"
num-traits = "0.2.19"
solana-security-txt = "1.1.0"
[target.'cfg(not(target_os = "solana"))'.dependencies]
solana-sdk = { workspace = true }
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/sdk.rs
|
#![cfg(not(target_os = "solana"))]
use anchor_lang::{system_program, InstructionData, ToAccountMetas};
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
};
use crate::{
instruction::{
InitializeAddressMerkleTreeAndQueue, InitializeStateMerkleTreeAndNullifierQueue,
},
AddressMerkleTreeConfig, AddressQueueConfig, NullifierQueueConfig, StateMerkleTreeConfig,
};
pub fn create_initialize_merkle_tree_instruction(
payer: Pubkey,
registered_program_pda: Option<Pubkey>,
merkle_tree_pubkey: Pubkey,
nullifier_queue_pubkey: Pubkey,
state_merkle_tree_config: StateMerkleTreeConfig,
nullifier_queue_config: NullifierQueueConfig,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
index: u64,
) -> Instruction {
let instruction_data = InitializeStateMerkleTreeAndNullifierQueue {
index,
program_owner,
forester,
state_merkle_tree_config,
nullifier_queue_config,
additional_bytes: 0,
};
let registered_program = match registered_program_pda {
Some(registered_program_pda) => AccountMeta::new(registered_program_pda, false),
None => AccountMeta::new(crate::ID, false),
};
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(payer, true),
AccountMeta::new(merkle_tree_pubkey, false),
AccountMeta::new(nullifier_queue_pubkey, false),
registered_program,
],
data: instruction_data.data(),
}
}
pub fn create_insert_leaves_instruction(
leaves: Vec<(u8, [u8; 32])>,
fee_payer: Pubkey,
authority: Pubkey,
merkle_tree_pubkeys: Vec<Pubkey>,
) -> Instruction {
let instruction_data = crate::instruction::AppendLeavesToMerkleTrees { leaves };
let accounts = crate::accounts::AppendLeaves {
fee_payer,
authority,
registered_program_pda: None,
system_program: system_program::ID,
};
let merkle_tree_account_metas = merkle_tree_pubkeys
.iter()
.map(|pubkey| AccountMeta::new(*pubkey, false))
.collect::<Vec<AccountMeta>>();
Instruction {
program_id: crate::ID,
accounts: [
accounts.to_account_metas(Some(true)),
merkle_tree_account_metas,
]
.concat(),
data: instruction_data.data(),
}
}
pub fn create_initialize_address_merkle_tree_and_queue_instruction(
index: u64,
payer: Pubkey,
registered_program_pda: Option<Pubkey>,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
merkle_tree_pubkey: Pubkey,
queue_pubkey: Pubkey,
address_merkle_tree_config: AddressMerkleTreeConfig,
address_queue_config: AddressQueueConfig,
) -> Instruction {
let instruction_data = InitializeAddressMerkleTreeAndQueue {
index,
program_owner,
forester,
address_merkle_tree_config,
address_queue_config,
};
let registered_program = match registered_program_pda {
Some(registered_program_pda) => AccountMeta::new(registered_program_pda, false),
None => AccountMeta::new(crate::ID, false),
};
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(payer, true),
AccountMeta::new(merkle_tree_pubkey, false),
AccountMeta::new(queue_pubkey, false),
registered_program,
],
data: instruction_data.data(),
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/lib.rs
|
#![allow(clippy::too_many_arguments)]
#![allow(unexpected_cfgs)]
pub mod errors;
pub mod instructions;
pub use instructions::*;
pub mod state;
pub use state::*;
pub mod processor;
pub mod utils;
pub use processor::*;
pub mod sdk;
use anchor_lang::prelude::*;
declare_id!("compr6CUsB5m2jS4Y3831ztGSTnDpnKJTKS95d64XVq");
#[cfg(not(feature = "no-entrypoint"))]
solana_security_txt::security_txt! {
name: "account-compression",
project_url: "lightprotocol.com",
contacts: "email:security@lightprotocol.com",
policy: "https://github.com/Lightprotocol/light-protocol/blob/main/SECURITY.md",
source_code: "https://github.com/Lightprotocol/light-protocol"
}
#[program]
pub mod account_compression {
use errors::AccountCompressionErrorCode;
use self::{
initialize_state_merkle_tree_and_nullifier_queue::process_initialize_state_merkle_tree_and_nullifier_queue,
insert_into_queues::{process_insert_into_queues, InsertIntoQueues},
};
use super::*;
pub fn initialize_address_merkle_tree_and_queue<'info>(
ctx: Context<'_, '_, '_, 'info, InitializeAddressMerkleTreeAndQueue<'info>>,
index: u64,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
address_merkle_tree_config: AddressMerkleTreeConfig,
address_queue_config: AddressQueueConfig,
) -> Result<()> {
process_initialize_address_merkle_tree_and_queue(
ctx,
index,
program_owner,
forester,
address_merkle_tree_config,
address_queue_config,
)
}
pub fn insert_addresses<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, InsertIntoQueues<'info>>,
addresses: Vec<[u8; 32]>,
) -> Result<()> {
process_insert_into_queues::<AddressMerkleTreeAccount>(
ctx,
addresses.as_slice(),
QueueType::AddressQueue,
)
}
/// Updates the address Merkle tree with a new address.
pub fn update_address_merkle_tree<'info>(
ctx: Context<'_, '_, '_, 'info, UpdateAddressMerkleTree<'info>>,
// Index of the Merkle tree changelog.
changelog_index: u16,
indexed_changelog_index: u16,
// Index of the address to dequeue.
value: u16,
// Low address.
low_address_index: u64,
low_address_value: [u8; 32],
low_address_next_index: u64,
// Value of the next address.
low_address_next_value: [u8; 32],
// Merkle proof for updating the low address.
low_address_proof: [[u8; 32]; 16],
) -> Result<()> {
process_update_address_merkle_tree(
ctx,
changelog_index,
indexed_changelog_index,
value,
low_address_value,
low_address_next_index,
low_address_next_value,
low_address_index,
low_address_proof,
)
}
pub fn rollover_address_merkle_tree_and_queue<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, RolloverAddressMerkleTreeAndQueue<'info>>,
) -> Result<()> {
process_rollover_address_merkle_tree_and_queue(ctx)
}
/// initialize group (a group can be used to give multiple programs access
/// to the same Merkle trees by registering the programs to the group)
pub fn initialize_group_authority<'info>(
ctx: Context<'_, '_, '_, 'info, InitializeGroupAuthority<'info>>,
authority: Pubkey,
) -> Result<()> {
let seed_pubkey = ctx.accounts.seed.key();
set_group_authority(
&mut ctx.accounts.group_authority,
authority,
Some(seed_pubkey),
)?;
Ok(())
}
pub fn update_group_authority<'info>(
ctx: Context<'_, '_, '_, 'info, UpdateGroupAuthority<'info>>,
authority: Pubkey,
) -> Result<()> {
set_group_authority(&mut ctx.accounts.group_authority, authority, None)
}
pub fn register_program_to_group<'info>(
ctx: Context<'_, '_, '_, 'info, RegisterProgramToGroup<'info>>,
) -> Result<()> {
process_register_program(ctx)
}
pub fn deregister_program(_ctx: Context<DeregisterProgram>) -> Result<()> {
Ok(())
}
/// Initializes a new Merkle tree from config bytes.
/// Index is an optional identifier and not checked by the program.
pub fn initialize_state_merkle_tree_and_nullifier_queue<'info>(
ctx: Context<'_, '_, '_, 'info, InitializeStateMerkleTreeAndNullifierQueue<'info>>,
index: u64,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
state_merkle_tree_config: StateMerkleTreeConfig,
nullifier_queue_config: NullifierQueueConfig,
// additional rent for the cpi context account
// so that it can be rolled over as well
additional_bytes: u64,
) -> Result<()> {
if additional_bytes != 0 {
msg!("additional_bytes is not supported yet");
return err!(AccountCompressionErrorCode::UnsupportedAdditionalBytes);
}
process_initialize_state_merkle_tree_and_nullifier_queue(
ctx,
index,
program_owner,
forester,
state_merkle_tree_config,
nullifier_queue_config,
additional_bytes,
)
}
pub fn append_leaves_to_merkle_trees<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, AppendLeaves<'info>>,
leaves: Vec<(u8, [u8; 32])>,
) -> Result<()> {
process_append_leaves_to_merkle_trees(ctx, leaves)
}
pub fn nullify_leaves<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, NullifyLeaves<'info>>,
change_log_indices: Vec<u64>,
leaves_queue_indices: Vec<u16>,
leaf_indices: Vec<u64>,
proofs: Vec<Vec<[u8; 32]>>,
) -> Result<()> {
process_nullify_leaves(
&ctx,
&change_log_indices,
&leaves_queue_indices,
&leaf_indices,
&proofs,
)
}
pub fn insert_into_nullifier_queues<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, InsertIntoQueues<'info>>,
nullifiers: Vec<[u8; 32]>,
) -> Result<()> {
process_insert_into_queues::<StateMerkleTreeAccount>(
ctx,
&nullifiers,
QueueType::NullifierQueue,
)
}
pub fn rollover_state_merkle_tree_and_nullifier_queue<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, RolloverStateMerkleTreeAndNullifierQueue<'info>>,
) -> Result<()> {
process_rollover_state_merkle_tree_nullifier_queue_pair(ctx)
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/errors.rs
|
use anchor_lang::prelude::*;
#[error_code]
pub enum AccountCompressionErrorCode {
#[msg("Integer overflow")]
IntegerOverflow,
#[msg("InvalidAuthority")]
InvalidAuthority,
#[msg(
"Leaves <> remaining accounts mismatch. The number of remaining accounts must match the number of leaves."
)]
NumberOfLeavesMismatch,
#[msg("Provided noop program public key is invalid")]
InvalidNoopPubkey,
#[msg("Number of change log indices mismatch")]
NumberOfChangeLogIndicesMismatch,
#[msg("Number of indices mismatch")]
NumberOfIndicesMismatch,
#[msg("NumberOfProofsMismatch")]
NumberOfProofsMismatch,
#[msg("InvalidMerkleProof")]
InvalidMerkleProof,
#[msg("Could not find the leaf in the queue")]
LeafNotFound,
#[msg("MerkleTreeAndQueueNotAssociated")]
MerkleTreeAndQueueNotAssociated,
#[msg("MerkleTreeAlreadyRolledOver")]
MerkleTreeAlreadyRolledOver,
#[msg("NotReadyForRollover")]
NotReadyForRollover,
#[msg("RolloverNotConfigured")]
RolloverNotConfigured,
#[msg("NotAllLeavesProcessed")]
NotAllLeavesProcessed,
#[msg("InvalidQueueType")]
InvalidQueueType,
#[msg("InputElementsEmpty")]
InputElementsEmpty,
#[msg("NoLeavesForMerkleTree")]
NoLeavesForMerkleTree,
#[msg("InvalidAccountSize")]
InvalidAccountSize,
#[msg("InsufficientRolloverFee")]
InsufficientRolloverFee,
#[msg("Unsupported Merkle tree height")]
UnsupportedHeight,
#[msg("Unsupported canopy depth")]
UnsupportedCanopyDepth,
#[msg("Invalid sequence threshold")]
InvalidSequenceThreshold,
#[msg("Unsupported close threshold")]
UnsupportedCloseThreshold,
#[msg("InvalidAccountBalance")]
InvalidAccountBalance,
UnsupportedAdditionalBytes,
InvalidGroup,
ProofLengthMismatch,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/nullify_leaves.rs
|
use crate::{
emit_indexer_event,
errors::AccountCompressionErrorCode,
state::{
queue::{queue_from_bytes_zero_copy_mut, QueueAccount},
StateMerkleTreeAccount,
},
state_merkle_tree_from_bytes_zero_copy_mut,
utils::check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccounts,
},
RegisteredProgram,
};
use anchor_lang::prelude::*;
use light_bounded_vec::BoundedVec;
use light_concurrent_merkle_tree::event::{MerkleTreeEvent, NullifierEvent};
use light_hasher::zero_bytes::poseidon::ZERO_BYTES;
#[derive(Accounts)]
pub struct NullifyLeaves<'info> {
/// CHECK: should only be accessed by a registered program or owner.
pub authority: Signer<'info>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
/// CHECK: when emitting event.
pub log_wrapper: UncheckedAccount<'info>,
#[account(mut)]
pub merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>,
#[account(mut)]
pub nullifier_queue: AccountLoader<'info, QueueAccount>,
}
impl<'info> GroupAccounts<'info> for NullifyLeaves<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
// TODO: implement for multiple nullifiers got a stack frame error with a loop
pub fn process_nullify_leaves<'a, 'b, 'c: 'info, 'info>(
ctx: &'a Context<'a, 'b, 'c, 'info, NullifyLeaves<'info>>,
change_log_indices: &'a [u64],
leaves_queue_indices: &'a [u16],
leaf_indices: &'a [u64],
proofs: &'a [Vec<[u8; 32]>],
) -> Result<()> {
if change_log_indices.len() != 1 {
msg!("only implemented for 1 nullifier update");
return Err(AccountCompressionErrorCode::NumberOfChangeLogIndicesMismatch.into());
}
if leaves_queue_indices.len() != change_log_indices.len() {
msg!("only implemented for 1 nullifier update");
return Err(AccountCompressionErrorCode::NumberOfLeavesMismatch.into());
}
if leaf_indices.len() != change_log_indices.len() {
msg!("only implemented for 1 nullifier update");
return Err(AccountCompressionErrorCode::NumberOfIndicesMismatch.into());
}
if proofs.len() != change_log_indices.len() {
msg!("only implemented for 1 nullifier update");
return Err(AccountCompressionErrorCode::NumberOfProofsMismatch.into());
}
if proofs.len() > 1 && proofs[0].len() != proofs[1].len() {
msg!(
"Proofs length mismatch {} {}",
proofs[0].len(),
proofs[1].len()
);
return Err(AccountCompressionErrorCode::ProofLengthMismatch.into());
}
insert_nullifier(
proofs,
change_log_indices,
leaves_queue_indices,
leaf_indices,
ctx,
)?;
Ok(())
}
#[inline(never)]
fn insert_nullifier<'a, 'c: 'info, 'info>(
proofs: &[Vec<[u8; 32]>],
change_log_indices: &[u64],
leaves_queue_indices: &[u16],
leaf_indices: &[u64],
ctx: &Context<'a, '_, 'c, 'info, NullifyLeaves<'info>>,
) -> Result<()> {
{
let merkle_tree = ctx.accounts.merkle_tree.load()?;
if merkle_tree.metadata.associated_queue != ctx.accounts.nullifier_queue.key() {
msg!(
"Merkle tree and nullifier queue are not associated. Merkle tree associated nullifier queue {} != nullifier queue {}",
merkle_tree.metadata.associated_queue,
ctx.accounts.nullifier_queue.key()
);
return err!(AccountCompressionErrorCode::MerkleTreeAndQueueNotAssociated);
}
check_signer_is_registered_or_authority::<NullifyLeaves, StateMerkleTreeAccount>(
ctx,
&merkle_tree,
)?;
}
let merkle_tree = ctx.accounts.merkle_tree.to_account_info();
let mut merkle_tree = merkle_tree.try_borrow_mut_data()?;
let mut merkle_tree = state_merkle_tree_from_bytes_zero_copy_mut(&mut merkle_tree)?;
let nullifier_queue = ctx.accounts.nullifier_queue.to_account_info();
let mut nullifier_queue = nullifier_queue.try_borrow_mut_data()?;
let mut nullifier_queue = unsafe { queue_from_bytes_zero_copy_mut(&mut nullifier_queue)? };
let allowed_proof_size = merkle_tree.height - merkle_tree.canopy_depth;
if proofs[0].len() != allowed_proof_size {
msg!(
"Invalid Proof Length {} allowed height {} - canopy {} {}",
proofs[0].len(),
merkle_tree.height,
merkle_tree.canopy_depth,
allowed_proof_size,
);
return err!(AccountCompressionErrorCode::InvalidMerkleProof);
}
let seq = (merkle_tree.sequence_number() + 1) as u64;
for (i, leaf_queue_index) in leaves_queue_indices.iter().enumerate() {
let leaf_cell = nullifier_queue
.get_unmarked_bucket(*leaf_queue_index as usize)
.ok_or(AccountCompressionErrorCode::LeafNotFound)?
.ok_or(AccountCompressionErrorCode::LeafNotFound)?;
let mut proof =
from_vec(proofs[i].as_slice(), merkle_tree.height).map_err(ProgramError::from)?;
merkle_tree
.update(
change_log_indices[i] as usize,
&leaf_cell.value_bytes(),
&ZERO_BYTES[0],
leaf_indices[i] as usize,
&mut proof,
)
.map_err(ProgramError::from)?;
nullifier_queue
.mark_with_sequence_number(*leaf_queue_index as usize, merkle_tree.sequence_number())
.map_err(ProgramError::from)?;
}
let nullify_event = NullifierEvent {
id: ctx.accounts.merkle_tree.key().to_bytes(),
nullified_leaves_indices: leaf_indices.to_vec(),
seq,
};
let nullify_event = MerkleTreeEvent::V2(nullify_event);
emit_indexer_event(nullify_event.try_to_vec()?, &ctx.accounts.log_wrapper)?;
Ok(())
}
#[inline(never)]
pub fn from_vec(vec: &[[u8; 32]], height: usize) -> Result<BoundedVec<[u8; 32]>> {
let proof: [[u8; 32]; 16] = vec.try_into().unwrap();
let mut bounded_vec = BoundedVec::with_capacity(height);
bounded_vec.extend(proof).map_err(ProgramError::from)?;
Ok(bounded_vec)
}
#[cfg(not(target_os = "solana"))]
pub mod sdk_nullify {
use anchor_lang::{InstructionData, ToAccountMetas};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
use crate::utils::constants::NOOP_PUBKEY;
pub fn create_nullify_instruction(
change_log_indices: &[u64],
leaves_queue_indices: &[u16],
leaf_indices: &[u64],
proofs: &[Vec<[u8; 32]>],
payer: &Pubkey,
merkle_tree_pubkey: &Pubkey,
nullifier_queue_pubkey: &Pubkey,
) -> Instruction {
let instruction_data = crate::instruction::NullifyLeaves {
leaves_queue_indices: leaves_queue_indices.to_vec(),
leaf_indices: leaf_indices.to_vec(),
change_log_indices: change_log_indices.to_vec(),
proofs: proofs.to_vec(),
};
let accounts = crate::accounts::NullifyLeaves {
authority: *payer,
registered_program_pda: None,
log_wrapper: Pubkey::new_from_array(NOOP_PUBKEY),
merkle_tree: *merkle_tree_pubkey,
nullifier_queue: *nullifier_queue_pubkey,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/register_program.rs
|
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
use crate::{errors::AccountCompressionErrorCode, GroupAuthority};
#[derive(Debug)]
#[account]
#[aligned_sized(anchor)]
pub struct RegisteredProgram {
pub registered_program_id: Pubkey,
pub group_authority_pda: Pubkey,
}
#[derive(Accounts)]
pub struct RegisterProgramToGroup<'info> {
/// CHECK: Signer is checked according to authority pda in instruction.
#[account( mut, constraint= authority.key() == group_authority_pda.authority @AccountCompressionErrorCode::InvalidAuthority)]
pub authority: Signer<'info>,
/// CHECK: TODO: check that upgrade authority is signer.
pub program_to_be_registered: Signer<'info>,
#[account(
init,
payer = authority,
seeds = [&program_to_be_registered.key().to_bytes()],
bump,
space = RegisteredProgram::LEN,
)]
pub registered_program_pda: Account<'info, RegisteredProgram>,
pub group_authority_pda: Account<'info, GroupAuthority>,
pub system_program: Program<'info, System>,
}
pub fn process_register_program(ctx: Context<RegisterProgramToGroup>) -> Result<()> {
ctx.accounts.registered_program_pda.registered_program_id =
ctx.accounts.program_to_be_registered.key();
ctx.accounts.registered_program_pda.group_authority_pda =
ctx.accounts.group_authority_pda.key();
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/insert_into_queues.rs
|
use crate::{
check_queue_type,
errors::AccountCompressionErrorCode,
state::queue::{queue_from_bytes_zero_copy_mut, QueueAccount},
state_merkle_tree_from_bytes_zero_copy,
utils::{
check_signer_is_registered_or_authority::check_signer_is_registered_or_authority,
queue::{QueueBundle, QueueMap},
transfer_lamports::transfer_lamports_cpi,
},
QueueType, RegisteredProgram,
};
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey, ZeroCopy};
use num_bigint::BigUint;
#[derive(Accounts)]
pub struct InsertIntoQueues<'info> {
/// Fee payer pays rollover fee.
#[account(mut)]
pub fee_payer: Signer<'info>,
/// CHECK: should only be accessed by a registered program or owner.
pub authority: Signer<'info>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
pub system_program: Program<'info, System>,
}
/// Inserts every element into the indexed array.
/// Throws an error if the element already exists.
/// Expects an indexed queue account as for every index as remaining account.
pub fn process_insert_into_queues<'a, 'b, 'c: 'info, 'info, MerkleTreeAccount: Owner + ZeroCopy>(
ctx: Context<'a, 'b, 'c, 'info, InsertIntoQueues<'info>>,
elements: &'a [[u8; 32]],
queue_type: QueueType,
) -> Result<()> {
if elements.is_empty() {
return err!(AccountCompressionErrorCode::InputElementsEmpty);
}
let expected_remaining_accounts = elements.len() * 2;
if expected_remaining_accounts != ctx.remaining_accounts.len() {
msg!(
"Number of remaining accounts does not match, expected {}, got {}",
expected_remaining_accounts,
ctx.remaining_accounts.len()
);
return err!(crate::errors::AccountCompressionErrorCode::NumberOfLeavesMismatch);
}
light_heap::bench_sbf_start!("acp_create_queue_map");
let mut queue_map = QueueMap::new();
// Deduplicate tree and queue pairs.
// So that we iterate over every pair only once,
// and pay rollover fees only once.
for i in (0..ctx.remaining_accounts.len()).step_by(2) {
let queue: &AccountInfo<'info> = ctx.remaining_accounts.get(i).unwrap();
let merkle_tree = ctx.remaining_accounts.get(i + 1).unwrap();
let associated_merkle_tree = {
let queue = AccountLoader::<QueueAccount>::try_from(queue)?;
let queue = queue.load()?;
check_queue_type(&queue.metadata.queue_type, &queue_type)?;
queue.metadata.associated_merkle_tree
};
if merkle_tree.key() != associated_merkle_tree {
msg!(
"Queue account {:?} is not associated with any address Merkle tree. Provided accounts {:?}",
queue.key(), ctx.remaining_accounts);
return err!(AccountCompressionErrorCode::MerkleTreeAndQueueNotAssociated);
}
queue_map
.entry(queue.key())
.or_insert_with(|| QueueBundle::new(queue, merkle_tree))
.elements
.push(elements[i / 2]);
}
light_heap::bench_sbf_end!("acp_create_queue_map");
for queue_bundle in queue_map.values() {
let rollover_fee: u64;
let queue = AccountLoader::<QueueAccount>::try_from(queue_bundle.queue)?;
light_heap::bench_sbf_start!("acp_prep_insertion");
{
let queue = queue.load()?;
check_signer_is_registered_or_authority::<InsertIntoQueues, QueueAccount>(
&ctx, &queue,
)?;
rollover_fee =
queue.metadata.rollover_metadata.rollover_fee * queue_bundle.elements.len() as u64;
}
{
let sequence_number = {
let merkle_tree = queue_bundle.merkle_tree.try_borrow_data()?;
let merkle_tree = state_merkle_tree_from_bytes_zero_copy(&merkle_tree)?;
merkle_tree.sequence_number()
};
let queue = queue.to_account_info();
let mut queue = queue.try_borrow_mut_data()?;
let mut queue = unsafe { queue_from_bytes_zero_copy_mut(&mut queue).unwrap() };
light_heap::bench_sbf_end!("acp_prep_insertion");
light_heap::bench_sbf_start!("acp_insert_nf_into_queue");
for element in queue_bundle.elements.iter() {
let element = BigUint::from_bytes_be(element.as_slice());
queue
.insert(&element, sequence_number)
.map_err(ProgramError::from)?;
}
light_heap::bench_sbf_end!("acp_insert_nf_into_queue");
}
if rollover_fee > 0 {
transfer_lamports_cpi(
&ctx.accounts.fee_payer,
&queue_bundle.queue.to_account_info(),
rollover_fee,
)?;
}
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/deregister_program.rs
|
use anchor_lang::prelude::*;
use crate::{errors::AccountCompressionErrorCode, GroupAuthority, RegisteredProgram};
#[derive(Accounts)]
pub struct DeregisterProgram<'info> {
/// CHECK: Signer is checked according to authority pda in instruction.
#[account(mut, constraint= authority.key() == group_authority_pda.authority @AccountCompressionErrorCode::InvalidAuthority)]
pub authority: Signer<'info>,
#[account(
mut, close=close_recipient
)]
pub registered_program_pda: Account<'info, RegisteredProgram>,
#[account( constraint= group_authority_pda.key() == registered_program_pda.group_authority_pda @AccountCompressionErrorCode::InvalidGroup)]
pub group_authority_pda: Account<'info, GroupAuthority>,
/// CHECK: recipient is not checked.
#[account(mut)]
pub close_recipient: AccountInfo<'info>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/rollover_state_merkle_tree_and_queue.rs
|
use crate::{
processor::{
initialize_concurrent_merkle_tree::process_initialize_state_merkle_tree,
initialize_nullifier_queue::process_initialize_nullifier_queue,
},
state::{
queue::{queue_from_bytes_zero_copy_mut, QueueAccount},
StateMerkleTreeAccount,
},
state_merkle_tree_from_bytes_zero_copy,
utils::{
check_account::check_account_balance_is_rent_exempt,
check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccounts,
},
transfer_lamports::transfer_lamports,
},
RegisteredProgram,
};
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
#[derive(Accounts)]
pub struct RolloverStateMerkleTreeAndNullifierQueue<'info> {
#[account(mut)]
/// Signer used to receive rollover accounts rentexemption reimbursement.
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
#[account(zero)]
pub new_state_merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>,
#[account(zero)]
pub new_nullifier_queue: AccountLoader<'info, QueueAccount>,
#[account(mut)]
pub old_state_merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>,
#[account(mut)]
pub old_nullifier_queue: AccountLoader<'info, QueueAccount>,
}
impl<'info> GroupAccounts<'info> for RolloverStateMerkleTreeAndNullifierQueue<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
/// Checks:
/// 1. Size of new accounts matches size old accounts
/// 2. Merkle tree is ready to be rolled over
/// 3. Merkle tree and nullifier queue are associated
/// 4. Merkle tree is not already rolled over Actions:
/// 1. mark Merkle tree as rolled over in this slot
/// 2. initialize new Merkle tree and nullifier queue with the same parameters
pub fn process_rollover_state_merkle_tree_nullifier_queue_pair<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, RolloverStateMerkleTreeAndNullifierQueue<'info>>,
) -> Result<()> {
// TODO: rollover additional rent as well. (need to add a field to the metadata for this)
let new_merkle_tree_account_info = ctx.accounts.new_state_merkle_tree.to_account_info();
let merkle_tree_rent = check_account_balance_is_rent_exempt(
&new_merkle_tree_account_info,
ctx.accounts
.old_state_merkle_tree
.to_account_info()
.data_len(),
)?;
let new_queue_account_info = ctx.accounts.new_nullifier_queue.to_account_info();
let queue_rent = check_account_balance_is_rent_exempt(
&new_queue_account_info,
ctx.accounts
.old_nullifier_queue
.to_account_info()
.data_len(),
)?;
let queue_metadata = {
let (merkle_tree_metadata, queue_metadata) = {
let mut merkle_tree_account_loaded = ctx.accounts.old_state_merkle_tree.load_mut()?;
let mut queue_account_loaded = ctx.accounts.old_nullifier_queue.load_mut()?;
check_signer_is_registered_or_authority::<
RolloverStateMerkleTreeAndNullifierQueue,
StateMerkleTreeAccount,
>(&ctx, &merkle_tree_account_loaded)?;
merkle_tree_account_loaded.metadata.rollover(
ctx.accounts.old_nullifier_queue.key(),
ctx.accounts.new_state_merkle_tree.key(),
)?;
queue_account_loaded.metadata.rollover(
ctx.accounts.old_state_merkle_tree.key(),
ctx.accounts.new_nullifier_queue.key(),
)?;
let merkle_tree_metadata = merkle_tree_account_loaded.metadata;
let queue_metadata = queue_account_loaded.metadata;
(merkle_tree_metadata, queue_metadata)
};
let merkle_tree = ctx.accounts.old_state_merkle_tree.to_account_info();
let merkle_tree = merkle_tree.try_borrow_data()?;
let merkle_tree = state_merkle_tree_from_bytes_zero_copy(&merkle_tree)?;
let height = merkle_tree.height;
if merkle_tree.next_index()
< ((1 << height) * merkle_tree_metadata.rollover_metadata.rollover_threshold / 100)
as usize
{
return err!(crate::errors::AccountCompressionErrorCode::NotReadyForRollover);
}
process_initialize_state_merkle_tree(
&ctx.accounts.new_state_merkle_tree,
merkle_tree_metadata.rollover_metadata.index,
merkle_tree_metadata.access_metadata.owner,
Some(merkle_tree_metadata.access_metadata.program_owner),
Some(merkle_tree_metadata.access_metadata.forester),
&(merkle_tree.height as u32),
&(merkle_tree.changelog.capacity() as u64),
&(merkle_tree.roots.capacity() as u64),
&(merkle_tree.canopy_depth as u64),
ctx.accounts.new_nullifier_queue.key(),
merkle_tree_metadata.rollover_metadata.network_fee,
Some(merkle_tree_metadata.rollover_metadata.rollover_threshold),
Some(merkle_tree_metadata.rollover_metadata.close_threshold),
merkle_tree_rent,
queue_rent,
)?;
queue_metadata
};
{
let nullifier_queue_account = ctx.accounts.old_nullifier_queue.to_account_info();
let mut nullifier_queue = nullifier_queue_account.try_borrow_mut_data()?;
let nullifier_queue = unsafe { queue_from_bytes_zero_copy_mut(&mut nullifier_queue)? };
process_initialize_nullifier_queue(
ctx.accounts.new_nullifier_queue.to_account_info(),
&ctx.accounts.new_nullifier_queue,
queue_metadata.rollover_metadata.index,
queue_metadata.access_metadata.owner,
Some(queue_metadata.access_metadata.program_owner),
Some(queue_metadata.access_metadata.forester),
ctx.accounts.new_state_merkle_tree.key(),
nullifier_queue.hash_set.get_capacity() as u16,
nullifier_queue.hash_set.sequence_threshold as u64,
Some(queue_metadata.rollover_metadata.rollover_threshold),
Some(queue_metadata.rollover_metadata.close_threshold),
queue_metadata.rollover_metadata.network_fee,
)?;
}
let lamports = merkle_tree_rent + queue_rent;
transfer_lamports(
&ctx.accounts.old_state_merkle_tree.to_account_info(),
&ctx.accounts.fee_payer.to_account_info(),
lamports,
)?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/update_group_authority.rs
|
use crate::GroupAuthority;
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
#[derive(Accounts)]
pub struct UpdateGroupAuthority<'info> {
pub authority: Signer<'info>,
#[account(
mut,
constraint = group_authority.authority == *authority.key,
)]
pub group_authority: Account<'info, GroupAuthority>,
}
pub fn set_group_authority(
group_authority: &mut Account<'_, GroupAuthority>,
authority: Pubkey,
seed: Option<Pubkey>,
) -> Result<()> {
group_authority.authority = authority;
if let Some(seed) = seed {
group_authority.seed = seed;
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/rollover_address_merkle_tree_and_queue.rs
|
use crate::{
address_merkle_tree_from_bytes_zero_copy,
initialize_address_merkle_tree::process_initialize_address_merkle_tree,
initialize_address_queue::process_initialize_address_queue,
state::{queue_from_bytes_zero_copy_mut, QueueAccount},
utils::{
check_account::check_account_balance_is_rent_exempt,
check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccounts,
},
transfer_lamports::transfer_lamports,
},
AddressMerkleTreeAccount, RegisteredProgram,
};
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
#[derive(Accounts)]
pub struct RolloverAddressMerkleTreeAndQueue<'info> {
#[account(mut)]
/// Signer used to receive rollover accounts rentexemption reimbursement.
pub fee_payer: Signer<'info>,
pub authority: Signer<'info>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
#[account(zero)]
pub new_address_merkle_tree: AccountLoader<'info, AddressMerkleTreeAccount>,
#[account(zero)]
pub new_queue: AccountLoader<'info, QueueAccount>,
#[account(mut)]
pub old_address_merkle_tree: AccountLoader<'info, AddressMerkleTreeAccount>,
#[account(mut)]
pub old_queue: AccountLoader<'info, QueueAccount>,
}
impl<'info> GroupAccounts<'info> for RolloverAddressMerkleTreeAndQueue<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
/// Checks:
/// 1. Merkle tree is ready to be rolled over
/// 2. Merkle tree and nullifier queue are associated
/// 3. Merkle tree is not already rolled over
/// 4. Rollover threshold is configured, if not tree cannot be rolled over
///
/// Actions:
/// 1. mark Merkle tree as rolled over in this slot
/// 2. initialize new Merkle tree and nullifier queue with the same parameters
pub fn process_rollover_address_merkle_tree_and_queue<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, RolloverAddressMerkleTreeAndQueue<'info>>,
) -> Result<()> {
let new_merkle_tree_account_info = ctx.accounts.new_address_merkle_tree.to_account_info();
let merkle_tree_rent = check_account_balance_is_rent_exempt(
&new_merkle_tree_account_info,
ctx.accounts
.old_address_merkle_tree
.to_account_info()
.data_len(),
)?;
let new_queue_account_info = ctx.accounts.new_queue.to_account_info();
let queue_rent = check_account_balance_is_rent_exempt(
&new_queue_account_info,
ctx.accounts.old_queue.to_account_info().data_len(),
)?;
let (queue_metadata, height) = {
let (merkle_tree_metadata, queue_metadata) = {
let mut merkle_tree_account_loaded = ctx.accounts.old_address_merkle_tree.load_mut()?;
let mut queue_account_loaded = ctx.accounts.old_queue.load_mut()?;
check_signer_is_registered_or_authority::<
RolloverAddressMerkleTreeAndQueue,
AddressMerkleTreeAccount,
>(&ctx, &merkle_tree_account_loaded)?;
merkle_tree_account_loaded.metadata.rollover(
ctx.accounts.old_queue.key(),
ctx.accounts.new_address_merkle_tree.key(),
)?;
queue_account_loaded.metadata.rollover(
ctx.accounts.old_address_merkle_tree.key(),
ctx.accounts.new_queue.key(),
)?;
let merkle_tree_metadata = merkle_tree_account_loaded.metadata;
let queue_metadata = queue_account_loaded.metadata;
(merkle_tree_metadata, queue_metadata)
};
let merkle_tree = ctx.accounts.old_address_merkle_tree.to_account_info();
let merkle_tree = merkle_tree.try_borrow_data()?;
let merkle_tree = address_merkle_tree_from_bytes_zero_copy(&merkle_tree)?;
let height = merkle_tree.height;
if merkle_tree.next_index()
< ((1 << height) * merkle_tree_metadata.rollover_metadata.rollover_threshold / 100)
as usize
{
return err!(crate::errors::AccountCompressionErrorCode::NotReadyForRollover);
}
process_initialize_address_merkle_tree(
&ctx.accounts.new_address_merkle_tree,
merkle_tree_metadata.rollover_metadata.index,
merkle_tree_metadata.access_metadata.owner,
Some(merkle_tree_metadata.access_metadata.program_owner),
Some(merkle_tree_metadata.access_metadata.forester),
merkle_tree.height as u32,
merkle_tree.changelog.capacity() as u64,
merkle_tree.roots.capacity() as u64,
merkle_tree.canopy_depth as u64,
merkle_tree.indexed_changelog.capacity() as u64,
ctx.accounts.new_queue.key(),
merkle_tree_metadata.rollover_metadata.network_fee,
Some(merkle_tree_metadata.rollover_metadata.rollover_threshold),
Some(merkle_tree_metadata.rollover_metadata.close_threshold),
)?;
(queue_metadata, height)
};
{
let queue_account = ctx.accounts.old_queue.to_account_info();
let mut queue = queue_account.try_borrow_mut_data()?;
let queue = unsafe { queue_from_bytes_zero_copy_mut(&mut queue)? };
process_initialize_address_queue(
&ctx.accounts.new_queue.to_account_info(),
&ctx.accounts.new_queue,
queue_metadata.rollover_metadata.index,
queue_metadata.access_metadata.owner,
Some(queue_metadata.access_metadata.program_owner),
Some(queue_metadata.access_metadata.forester),
ctx.accounts.new_address_merkle_tree.key(),
queue.hash_set.get_capacity() as u16,
queue.hash_set.sequence_threshold as u64,
queue_metadata.rollover_metadata.network_fee,
Some(queue_metadata.rollover_metadata.rollover_threshold),
Some(queue_metadata.rollover_metadata.close_threshold),
height as u32,
merkle_tree_rent,
)?;
}
let lamports = merkle_tree_rent + queue_rent;
transfer_lamports(
&ctx.accounts.old_queue.to_account_info(),
&ctx.accounts.fee_payer.to_account_info(),
lamports,
)?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/mod.rs
|
pub mod initialize_address_merkle_tree_and_queue;
pub use initialize_address_merkle_tree_and_queue::*;
pub mod update_address_merkle_tree;
pub use update_address_merkle_tree::*;
pub mod insert_into_queues;
pub use insert_into_queues::*;
pub mod initialize_state_merkle_tree_and_nullifier_queue;
pub use initialize_state_merkle_tree_and_nullifier_queue::*;
pub mod append_leaves;
pub use append_leaves::*;
pub mod nullify_leaves;
pub use nullify_leaves::*;
pub mod initialize_group_authority;
pub use initialize_group_authority::*;
pub mod update_group_authority;
pub use update_group_authority::*;
pub mod register_program;
pub use register_program::*;
pub mod rollover_state_merkle_tree_and_queue;
pub use rollover_state_merkle_tree_and_queue::*;
pub mod rollover_address_merkle_tree_and_queue;
pub use rollover_address_merkle_tree_and_queue::*;
pub mod deregister_program;
pub use deregister_program::*;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/append_leaves.rs
|
use crate::{
errors::AccountCompressionErrorCode,
state::StateMerkleTreeAccount,
state_merkle_tree_from_bytes_zero_copy_mut,
utils::{
check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccess, GroupAccounts,
},
transfer_lamports::transfer_lamports_cpi,
},
RegisteredProgram,
};
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
#[derive(Accounts)]
pub struct AppendLeaves<'info> {
#[account(mut)]
/// Fee payer pays rollover fee.
pub fee_payer: Signer<'info>,
/// Checked whether instruction is accessed by a registered program or owner = authority.
pub authority: Signer<'info>,
/// Some assumes that the Merkle trees are accessed by a registered program.
/// None assumes that the Merkle trees are accessed by its owner.
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
pub system_program: Program<'info, System>,
}
impl GroupAccess for StateMerkleTreeAccount {
fn get_owner(&self) -> &Pubkey {
&self.metadata.access_metadata.owner
}
fn get_program_owner(&self) -> &Pubkey {
&self.metadata.access_metadata.program_owner
}
}
impl<'info> GroupAccounts<'info> for AppendLeaves<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
pub fn process_append_leaves_to_merkle_trees<'a, 'b, 'c: 'info, 'info>(
ctx: Context<'a, 'b, 'c, 'info, AppendLeaves<'info>>,
leaves: Vec<(u8, [u8; 32])>,
) -> Result<()> {
let leaves_processed = batch_append_leaves(&ctx, &leaves)?;
if leaves_processed != leaves.len() {
return err!(crate::errors::AccountCompressionErrorCode::NotAllLeavesProcessed);
}
Ok(())
}
/// Perform batch appends to Merkle trees provided as remaining accounts. Leaves
/// are assumed to be ordered by Merkle tree account.
/// 1. Iterate over all remaining accounts (Merkle tree accounts)
/// 2. get first leaves that points to current Merkle tree account
/// 3. get last leaf that points to current Merkle tree account
/// 4. check Merkle tree account discriminator (AccountLoader)
/// 5. check signer elibility to write into Merkle tree account
/// (check_signer_is_registered_or_authority)
/// 6. append batch to Merkle tree
/// 7. transfer rollover fee
/// 8. get next Merkle tree account
fn batch_append_leaves<'a, 'c: 'info, 'info>(
ctx: &Context<'a, '_, 'c, 'info, AppendLeaves<'info>>,
leaves: &'a [(u8, [u8; 32])],
) -> Result<usize> {
let mut leaves_processed: usize = 0;
let len = ctx.remaining_accounts.len();
for i in 0..len {
let merkle_tree_acc_info = &ctx.remaining_accounts[i];
let rollover_fee: u64 = {
let start = match leaves.iter().position(|x| x.0 as usize == i) {
Some(pos) => Ok(pos),
None => err!(AccountCompressionErrorCode::NoLeavesForMerkleTree),
}?;
let end = match leaves[start..].iter().position(|x| x.0 as usize != i) {
Some(pos) => pos + start,
None => leaves.len(),
};
let batch_size = end - start;
leaves_processed += batch_size;
let rollover_fee = {
let merkle_tree_account =
AccountLoader::<StateMerkleTreeAccount>::try_from(merkle_tree_acc_info)
.map_err(ProgramError::from)?;
{
let merkle_tree_account = merkle_tree_account.load()?;
let rollover_fee = merkle_tree_account.metadata.rollover_metadata.rollover_fee
* batch_size as u64;
check_signer_is_registered_or_authority::<AppendLeaves, StateMerkleTreeAccount>(
ctx,
&merkle_tree_account,
)?;
rollover_fee
}
};
let mut merkle_tree = merkle_tree_acc_info.try_borrow_mut_data()?;
let mut merkle_tree = state_merkle_tree_from_bytes_zero_copy_mut(&mut merkle_tree)?;
merkle_tree
.append_batch(
leaves[start..end]
.iter()
.map(|x| &x.1)
.collect::<Vec<&[u8; 32]>>()
.as_slice(),
)
.map_err(ProgramError::from)?;
rollover_fee
};
transfer_lamports_cpi(&ctx.accounts.fee_payer, merkle_tree_acc_info, rollover_fee)?;
}
Ok(leaves_processed)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/update_address_merkle_tree.rs
|
use anchor_lang::prelude::*;
use light_concurrent_merkle_tree::event::{IndexedMerkleTreeEvent, MerkleTreeEvent};
use light_indexed_merkle_tree::array::IndexedElement;
use num_bigint::BigUint;
use crate::{
address_merkle_tree_from_bytes_zero_copy_mut, emit_indexer_event,
errors::AccountCompressionErrorCode,
from_vec,
state::{queue_from_bytes_zero_copy_mut, QueueAccount},
utils::check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccounts,
},
AddressMerkleTreeAccount, RegisteredProgram,
};
#[derive(Accounts)]
pub struct UpdateAddressMerkleTree<'info> {
pub authority: Signer<'info>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
#[account(mut)]
pub queue: AccountLoader<'info, QueueAccount>,
#[account(mut)]
pub merkle_tree: AccountLoader<'info, AddressMerkleTreeAccount>,
/// CHECK: when emitting event.
pub log_wrapper: UncheckedAccount<'info>,
}
impl<'info> GroupAccounts<'info> for UpdateAddressMerkleTree<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
#[allow(clippy::too_many_arguments)]
pub fn process_update_address_merkle_tree<'info>(
ctx: Context<'_, '_, '_, 'info, UpdateAddressMerkleTree<'info>>,
// Index of the Merkle tree changelog.
changelog_index: u16,
indexed_changelog_index: u16,
// Address to dequeue.
value_index: u16,
// Low address.
low_address_value: [u8; 32], // included in leaf hash
low_address_next_index: u64, // included in leaf hash
low_address_next_value: [u8; 32], // included in leaf hash
low_address_index: u64, // leaf index of low element
low_address_proof: [[u8; 32]; 16], // Merkle proof for updating the low address.
) -> Result<()> {
let address_queue = ctx.accounts.queue.to_account_info();
let mut address_queue = address_queue.try_borrow_mut_data()?;
let mut address_queue = unsafe { queue_from_bytes_zero_copy_mut(&mut address_queue)? };
{
let merkle_tree = ctx.accounts.merkle_tree.load_mut()?;
if merkle_tree.metadata.associated_queue != ctx.accounts.queue.key() {
msg!(
"Merkle tree and nullifier queue are not associated. Merkle tree associated address queue {} != provided queue {}",
merkle_tree.metadata.associated_queue,
ctx.accounts.queue.key()
);
return err!(AccountCompressionErrorCode::MerkleTreeAndQueueNotAssociated);
}
check_signer_is_registered_or_authority::<UpdateAddressMerkleTree, AddressMerkleTreeAccount>(
&ctx,
&merkle_tree,
)?;
}
let merkle_tree = ctx.accounts.merkle_tree.to_account_info();
let mut merkle_tree = merkle_tree.try_borrow_mut_data()?;
let mut merkle_tree = address_merkle_tree_from_bytes_zero_copy_mut(&mut merkle_tree)?;
let value = address_queue
.get_unmarked_bucket(value_index as usize)
.ok_or(AccountCompressionErrorCode::LeafNotFound)?
.ok_or(AccountCompressionErrorCode::LeafNotFound)?
.value_biguint();
// Indexed Merkle tree update:
// - the range represented by the low element is split into two ranges
// - the new low element(lower range, next value is address) and the address
// element (higher range, next value is low_element.next_value)
// - the new low element is updated, and the address element is appended
// Lower range
let low_address: IndexedElement<usize> = IndexedElement {
index: low_address_index as usize,
value: BigUint::from_bytes_be(&low_address_value),
next_index: low_address_next_index as usize,
};
let low_address_next_value = BigUint::from_bytes_be(&low_address_next_value);
let mut proof =
from_vec(low_address_proof.as_slice(), merkle_tree.height).map_err(ProgramError::from)?;
// Update the Merkle tree.
// Inputs check:
// - address is element of (value, next_value)
// - changelog index gets values from account
// - indexed changelog index gets values from account
// - address is selected by value index from hashset
// - low address and low address next value are validated with low address Merkle proof
let indexed_merkle_tree_update = merkle_tree
.update(
usize::from(changelog_index),
usize::from(indexed_changelog_index),
value.clone(),
low_address,
low_address_next_value,
&mut proof,
)
.map_err(ProgramError::from)?;
// Mark the address with the current sequence number.
address_queue
.mark_with_sequence_number(value_index as usize, merkle_tree.sequence_number())
.map_err(ProgramError::from)?;
let address_event = MerkleTreeEvent::V3(IndexedMerkleTreeEvent {
id: ctx.accounts.merkle_tree.key().to_bytes(),
updates: vec![indexed_merkle_tree_update],
// Address Merkle tree update does one update and one append,
// thus the first seq number is final seq - 1.
seq: merkle_tree.sequence_number() as u64 - 1,
});
emit_indexer_event(
address_event.try_to_vec()?,
&ctx.accounts.log_wrapper.to_account_info(),
)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/initialize_state_merkle_tree_and_nullifier_queue.rs
|
use crate::{
errors::AccountCompressionErrorCode,
initialize_concurrent_merkle_tree::process_initialize_state_merkle_tree,
initialize_nullifier_queue::process_initialize_nullifier_queue,
state::{QueueAccount, StateMerkleTreeAccount},
utils::{
check_account::check_account_balance_is_rent_exempt,
check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccounts,
},
constants::{
STATE_MERKLE_TREE_CANOPY_DEPTH, STATE_MERKLE_TREE_CHANGELOG, STATE_MERKLE_TREE_HEIGHT,
STATE_MERKLE_TREE_ROOTS, STATE_NULLIFIER_QUEUE_SEQUENCE_THRESHOLD,
STATE_NULLIFIER_QUEUE_VALUES,
},
},
RegisteredProgram,
};
use anchor_lang::prelude::*;
use std::default;
#[derive(Accounts)]
pub struct InitializeStateMerkleTreeAndNullifierQueue<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(zero)]
pub merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>,
#[account(zero)]
pub nullifier_queue: AccountLoader<'info, QueueAccount>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
}
#[derive(Debug, Clone, AnchorDeserialize, AnchorSerialize, PartialEq)]
pub struct StateMerkleTreeConfig {
pub height: u32,
pub changelog_size: u64,
pub roots_size: u64,
pub canopy_depth: u64,
pub network_fee: Option<u64>,
pub rollover_threshold: Option<u64>,
pub close_threshold: Option<u64>,
}
impl default::Default for StateMerkleTreeConfig {
fn default() -> Self {
Self {
height: STATE_MERKLE_TREE_HEIGHT as u32,
changelog_size: STATE_MERKLE_TREE_CHANGELOG,
roots_size: STATE_MERKLE_TREE_ROOTS,
canopy_depth: STATE_MERKLE_TREE_CANOPY_DEPTH,
network_fee: Some(5000),
rollover_threshold: Some(95),
close_threshold: None,
}
}
}
impl<'info> GroupAccounts<'info> for InitializeStateMerkleTreeAndNullifierQueue<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
#[derive(Debug, Clone, AnchorDeserialize, AnchorSerialize, PartialEq)]
pub struct NullifierQueueConfig {
pub capacity: u16,
pub sequence_threshold: u64,
pub network_fee: Option<u64>,
}
// Arbitrary safety margin.
pub const SAFETY_MARGIN: u64 = 10;
impl default::Default for NullifierQueueConfig {
fn default() -> Self {
Self {
capacity: STATE_NULLIFIER_QUEUE_VALUES,
sequence_threshold: STATE_NULLIFIER_QUEUE_SEQUENCE_THRESHOLD + SAFETY_MARGIN,
network_fee: None,
}
}
}
pub fn process_initialize_state_merkle_tree_and_nullifier_queue<'info>(
ctx: Context<'_, '_, '_, 'info, InitializeStateMerkleTreeAndNullifierQueue<'info>>,
index: u64,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
state_merkle_tree_config: StateMerkleTreeConfig,
nullifier_queue_config: NullifierQueueConfig,
_additional_bytes: u64,
) -> Result<()> {
if state_merkle_tree_config.height as u64 != STATE_MERKLE_TREE_HEIGHT {
msg!(
"Unsupported Merkle tree height: {}. The only currently supported height is: {}",
state_merkle_tree_config.height,
STATE_MERKLE_TREE_HEIGHT
);
return err!(AccountCompressionErrorCode::UnsupportedHeight);
}
if state_merkle_tree_config.canopy_depth != STATE_MERKLE_TREE_CANOPY_DEPTH {
msg!(
"Unsupported canopy depth: {}. The only currently supported depth is: {}",
state_merkle_tree_config.canopy_depth,
STATE_MERKLE_TREE_CANOPY_DEPTH
);
return err!(AccountCompressionErrorCode::UnsupportedCanopyDepth);
}
if state_merkle_tree_config.close_threshold.is_some() {
msg!("close_threshold is not supported yet");
return err!(AccountCompressionErrorCode::UnsupportedCloseThreshold);
}
let minimum_sequence_threshold = state_merkle_tree_config.roots_size + SAFETY_MARGIN;
if nullifier_queue_config.sequence_threshold < minimum_sequence_threshold {
msg!(
"Invalid sequence threshold: {}. Should be at least: {}",
nullifier_queue_config.sequence_threshold,
minimum_sequence_threshold
);
return err!(AccountCompressionErrorCode::InvalidSequenceThreshold);
}
let merkle_tree_expected_size = StateMerkleTreeAccount::size(
state_merkle_tree_config.height as usize,
state_merkle_tree_config.changelog_size as usize,
state_merkle_tree_config.roots_size as usize,
state_merkle_tree_config.canopy_depth as usize,
);
let queue_expected_size = QueueAccount::size(nullifier_queue_config.capacity as usize)?;
let merkle_tree_rent = check_account_balance_is_rent_exempt(
&ctx.accounts.merkle_tree.to_account_info(),
merkle_tree_expected_size,
)?;
let queue_rent = check_account_balance_is_rent_exempt(
&ctx.accounts.nullifier_queue.to_account_info(),
queue_expected_size,
)?;
let owner = match ctx.accounts.registered_program_pda.as_ref() {
Some(registered_program_pda) => {
check_signer_is_registered_or_authority::<
InitializeStateMerkleTreeAndNullifierQueue,
RegisteredProgram,
>(&ctx, registered_program_pda)?;
registered_program_pda.group_authority_pda
}
None => ctx.accounts.authority.key(),
};
process_initialize_state_merkle_tree(
&ctx.accounts.merkle_tree,
index,
owner,
program_owner,
forester,
&state_merkle_tree_config.height,
&state_merkle_tree_config.changelog_size,
&state_merkle_tree_config.roots_size,
&state_merkle_tree_config.canopy_depth,
ctx.accounts.nullifier_queue.key(),
state_merkle_tree_config.network_fee.unwrap_or(0),
state_merkle_tree_config.rollover_threshold,
state_merkle_tree_config.close_threshold,
merkle_tree_rent,
queue_rent,
)?;
process_initialize_nullifier_queue(
ctx.accounts.nullifier_queue.to_account_info(),
&ctx.accounts.nullifier_queue,
index,
owner,
program_owner,
forester,
ctx.accounts.merkle_tree.key(),
nullifier_queue_config.capacity,
nullifier_queue_config.sequence_threshold,
state_merkle_tree_config.rollover_threshold,
state_merkle_tree_config.close_threshold,
nullifier_queue_config.network_fee.unwrap_or(0),
)?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/initialize_group_authority.rs
|
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
use crate::{state::GroupAuthority, utils::constants::GROUP_AUTHORITY_SEED};
#[derive(Accounts)]
pub struct InitializeGroupAuthority<'info> {
#[account(mut)]
pub authority: Signer<'info>,
/// Seed public key used to derive the group authority.
pub seed: Signer<'info>,
#[account(
init,
payer = authority,
seeds = [GROUP_AUTHORITY_SEED, seed.key().to_bytes().as_slice()],
bump,
space = GroupAuthority::LEN,
)]
pub group_authority: Account<'info, GroupAuthority>,
pub system_program: Program<'info, System>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/instructions/initialize_address_merkle_tree_and_queue.rs
|
use anchor_lang::prelude::*;
use crate::{
errors::AccountCompressionErrorCode,
initialize_address_merkle_tree::process_initialize_address_merkle_tree,
initialize_address_queue::process_initialize_address_queue,
state::QueueAccount,
utils::{
check_account::check_account_balance_is_rent_exempt,
check_signer_is_registered_or_authority::{
check_signer_is_registered_or_authority, GroupAccess, GroupAccounts,
},
constants::{
ADDRESS_MERKLE_TREE_CANOPY_DEPTH, ADDRESS_MERKLE_TREE_CHANGELOG,
ADDRESS_MERKLE_TREE_HEIGHT, ADDRESS_MERKLE_TREE_INDEXED_CHANGELOG,
ADDRESS_MERKLE_TREE_ROOTS,
},
},
AddressMerkleTreeAccount, NullifierQueueConfig, RegisteredProgram, SAFETY_MARGIN,
};
#[derive(Debug, Clone, AnchorDeserialize, AnchorSerialize, PartialEq)]
pub struct AddressMerkleTreeConfig {
pub height: u32,
pub changelog_size: u64,
pub roots_size: u64,
pub canopy_depth: u64,
pub address_changelog_size: u64,
pub network_fee: Option<u64>,
pub rollover_threshold: Option<u64>,
pub close_threshold: Option<u64>,
}
impl Default for AddressMerkleTreeConfig {
fn default() -> Self {
Self {
height: ADDRESS_MERKLE_TREE_HEIGHT as u32,
changelog_size: ADDRESS_MERKLE_TREE_CHANGELOG,
roots_size: ADDRESS_MERKLE_TREE_ROOTS,
canopy_depth: ADDRESS_MERKLE_TREE_CANOPY_DEPTH,
address_changelog_size: ADDRESS_MERKLE_TREE_INDEXED_CHANGELOG,
network_fee: Some(5000),
rollover_threshold: Some(95),
close_threshold: None,
}
}
}
pub type AddressQueueConfig = NullifierQueueConfig;
#[derive(Accounts)]
pub struct InitializeAddressMerkleTreeAndQueue<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(zero)]
pub merkle_tree: AccountLoader<'info, AddressMerkleTreeAccount>,
#[account(zero)]
pub queue: AccountLoader<'info, QueueAccount>,
pub registered_program_pda: Option<Account<'info, RegisteredProgram>>,
}
impl<'info> GroupAccounts<'info> for InitializeAddressMerkleTreeAndQueue<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
impl GroupAccess for RegisteredProgram {
fn get_owner(&self) -> &Pubkey {
&self.group_authority_pda
}
fn get_program_owner(&self) -> &Pubkey {
&self.registered_program_id
}
}
pub fn process_initialize_address_merkle_tree_and_queue<'info>(
ctx: Context<'_, '_, '_, 'info, InitializeAddressMerkleTreeAndQueue<'info>>,
index: u64,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
merkle_tree_config: AddressMerkleTreeConfig,
queue_config: AddressQueueConfig,
) -> Result<()> {
if merkle_tree_config.height as u64 != ADDRESS_MERKLE_TREE_HEIGHT {
msg!(
"Unsupported Merkle tree height: {}. The only currently supported height is: {}",
merkle_tree_config.height,
ADDRESS_MERKLE_TREE_HEIGHT
);
return err!(AccountCompressionErrorCode::UnsupportedHeight);
}
if merkle_tree_config.canopy_depth != ADDRESS_MERKLE_TREE_CANOPY_DEPTH {
msg!(
"Unsupported canopy depth: {}. The only currently supported depth is: {}",
merkle_tree_config.canopy_depth,
ADDRESS_MERKLE_TREE_CANOPY_DEPTH
);
return err!(AccountCompressionErrorCode::UnsupportedCanopyDepth);
}
if merkle_tree_config.close_threshold.is_some() {
msg!("close_threshold is not supported yet");
return err!(AccountCompressionErrorCode::UnsupportedCloseThreshold);
}
let minimum_sequence_threshold = merkle_tree_config.roots_size + SAFETY_MARGIN;
if queue_config.sequence_threshold < minimum_sequence_threshold {
msg!(
"Invalid sequence threshold: {}. Should be at least {}",
queue_config.sequence_threshold,
minimum_sequence_threshold
);
return err!(AccountCompressionErrorCode::InvalidSequenceThreshold);
}
let owner = match ctx.accounts.registered_program_pda.as_ref() {
Some(registered_program_pda) => {
check_signer_is_registered_or_authority::<
InitializeAddressMerkleTreeAndQueue,
RegisteredProgram,
>(&ctx, registered_program_pda)?;
registered_program_pda.group_authority_pda
}
None => ctx.accounts.authority.key(),
};
let merkle_tree_expected_size = AddressMerkleTreeAccount::size(
merkle_tree_config.height as usize,
merkle_tree_config.changelog_size as usize,
merkle_tree_config.roots_size as usize,
merkle_tree_config.canopy_depth as usize,
merkle_tree_config.address_changelog_size as usize,
);
let queue_expected_size = QueueAccount::size(queue_config.capacity as usize)?;
let merkle_tree_rent = check_account_balance_is_rent_exempt(
&ctx.accounts.merkle_tree.to_account_info(),
merkle_tree_expected_size,
)?;
check_account_balance_is_rent_exempt(
&ctx.accounts.queue.to_account_info(),
queue_expected_size,
)?;
process_initialize_address_queue(
&ctx.accounts.queue.to_account_info(),
&ctx.accounts.queue,
index,
owner,
program_owner,
forester,
ctx.accounts.merkle_tree.key(),
queue_config.capacity,
queue_config.sequence_threshold,
queue_config.network_fee.unwrap_or_default(),
merkle_tree_config.rollover_threshold,
merkle_tree_config.close_threshold,
merkle_tree_config.height,
merkle_tree_rent,
)?;
process_initialize_address_merkle_tree(
&ctx.accounts.merkle_tree,
index,
owner,
program_owner,
forester,
merkle_tree_config.height,
merkle_tree_config.changelog_size,
merkle_tree_config.roots_size,
merkle_tree_config.canopy_depth,
merkle_tree_config.address_changelog_size,
ctx.accounts.queue.key(),
merkle_tree_config.network_fee.unwrap_or_default(),
merkle_tree_config.rollover_threshold,
merkle_tree_config.close_threshold,
)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/processor/initialize_concurrent_merkle_tree.rs
|
use anchor_lang::prelude::*;
use light_utils::fee::compute_rollover_fee;
use crate::{
initialize_address_queue::check_rollover_fee_sufficient, state::StateMerkleTreeAccount,
state_merkle_tree_from_bytes_zero_copy_init, AccessMetadata, RolloverMetadata,
};
#[allow(unused_variables)]
pub fn process_initialize_state_merkle_tree(
merkle_tree_account_loader: &AccountLoader<'_, StateMerkleTreeAccount>,
index: u64,
owner: Pubkey,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
height: &u32,
changelog_size: &u64,
roots_size: &u64,
canopy_depth: &u64,
associated_queue: Pubkey,
network_fee: u64,
rollover_threshold: Option<u64>,
close_threshold: Option<u64>,
merkle_tree_rent: u64,
queue_rent: u64,
) -> Result<()> {
// Initialize new Merkle trees.
{
let mut merkle_tree = merkle_tree_account_loader.load_init()?;
let rollover_fee = match rollover_threshold {
Some(rollover_threshold) => {
let rollover_fee =
compute_rollover_fee(rollover_threshold, *height, merkle_tree_rent)
.map_err(ProgramError::from)?
+ compute_rollover_fee(rollover_threshold, *height, queue_rent)
.map_err(ProgramError::from)?;
check_rollover_fee_sufficient(
rollover_fee,
queue_rent,
merkle_tree_rent,
rollover_threshold,
*height,
)?;
msg!(" state Merkle tree rollover_fee: {}", rollover_fee);
rollover_fee
}
None => 0,
};
merkle_tree.init(
AccessMetadata::new(owner, program_owner, forester),
RolloverMetadata::new(
index,
rollover_fee,
rollover_threshold,
network_fee,
close_threshold,
None,
),
associated_queue,
);
}
let merkle_tree = merkle_tree_account_loader.to_account_info();
let mut merkle_tree = merkle_tree.try_borrow_mut_data()?;
let mut merkle_tree = state_merkle_tree_from_bytes_zero_copy_init(
&mut merkle_tree,
*height as usize,
*canopy_depth as usize,
*changelog_size as usize,
*roots_size as usize,
)?;
merkle_tree.init().map_err(ProgramError::from)?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/processor/initialize_nullifier_queue.rs
|
use crate::{
queue_from_bytes_zero_copy_init, AccessMetadata, QueueAccount, QueueType, RolloverMetadata,
};
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
pub fn process_initialize_nullifier_queue<'a, 'b, 'c: 'info, 'info>(
nullifier_queue_account_info: AccountInfo<'info>,
nullifier_queue_account_loader: &'a AccountLoader<'info, QueueAccount>,
index: u64,
owner: Pubkey,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
associated_merkle_tree: Pubkey,
capacity: u16,
sequence_threshold: u64,
rollover_threshold: Option<u64>,
close_threshold: Option<u64>,
network_fee: u64,
) -> Result<()> {
{
let mut nullifier_queue = nullifier_queue_account_loader.load_init()?;
let rollover_meta_data = RolloverMetadata {
index,
rollover_threshold: rollover_threshold.unwrap_or_default(),
close_threshold: close_threshold.unwrap_or(u64::MAX),
rolledover_slot: u64::MAX,
network_fee,
// The rollover fee is charged at append with the Merkle tree. The
// rollover that is defined in the Merkle tree is calculated to
// rollover the tree, queue and cpi context account.
rollover_fee: 0,
additional_bytes: 0,
};
nullifier_queue.init(
AccessMetadata {
owner,
program_owner: program_owner.unwrap_or_default(),
forester: forester.unwrap_or_default(),
},
rollover_meta_data,
associated_merkle_tree,
QueueType::NullifierQueue,
);
drop(nullifier_queue);
}
let nullifier_queue = nullifier_queue_account_info;
let mut nullifier_queue = nullifier_queue.try_borrow_mut_data()?;
unsafe {
queue_from_bytes_zero_copy_init(
&mut nullifier_queue,
capacity.into(),
sequence_threshold as usize,
)
.map_err(ProgramError::from)?;
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/processor/mod.rs
|
pub mod initialize_address_merkle_tree;
pub mod initialize_address_queue;
pub mod initialize_concurrent_merkle_tree;
pub mod initialize_nullifier_queue;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/processor/initialize_address_merkle_tree.rs
|
use crate::{
address_merkle_tree_from_bytes_zero_copy_init, state::AddressMerkleTreeAccount, AccessMetadata,
RolloverMetadata,
};
pub use anchor_lang::prelude::*;
pub fn process_initialize_address_merkle_tree(
address_merkle_tree_loader: &AccountLoader<'_, AddressMerkleTreeAccount>,
index: u64,
owner: Pubkey,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
height: u32,
changelog_size: u64,
roots_size: u64,
canopy_depth: u64,
address_changelog_size: u64,
associated_queue: Pubkey,
network_fee: u64,
rollover_threshold: Option<u64>,
close_threshold: Option<u64>,
) -> Result<()> {
{
let mut merkle_tree = address_merkle_tree_loader.load_init()?;
// The address Merkle tree is never directly called by the user.
// All rollover fees are collected by the address queue.
let rollover_fee = 0;
merkle_tree.init(
AccessMetadata::new(owner, program_owner, forester),
RolloverMetadata::new(
index,
rollover_fee,
rollover_threshold,
network_fee,
close_threshold,
None,
),
associated_queue,
);
}
let merkle_tree = address_merkle_tree_loader.to_account_info();
let mut merkle_tree = merkle_tree.try_borrow_mut_data()?;
let mut merkle_tree = address_merkle_tree_from_bytes_zero_copy_init(
&mut merkle_tree,
height as usize,
canopy_depth as usize,
changelog_size as usize,
roots_size as usize,
address_changelog_size as usize,
)?;
msg!("Initialized address merkle tree");
merkle_tree.init().map_err(ProgramError::from)?;
// Initialize the address merkle tree with the bn254 Fr field size - 1
// This is the highest value that you can poseidon hash with poseidon syscalls.
// Initializing the indexed Merkle tree enables non-inclusion proofs without handling the first case specifically.
// However, it does reduce the available address space by 1.
merkle_tree
.add_highest_element()
.map_err(ProgramError::from)?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/processor/initialize_address_queue.rs
|
use anchor_lang::prelude::*;
use light_utils::fee::compute_rollover_fee;
use crate::{
state::{queue_from_bytes_zero_copy_init, QueueAccount},
AccessMetadata, QueueType, RolloverMetadata,
};
pub fn process_initialize_address_queue<'info>(
queue_account_info: &AccountInfo<'info>,
queue_loader: &AccountLoader<'info, QueueAccount>,
index: u64,
owner: Pubkey,
program_owner: Option<Pubkey>,
forester: Option<Pubkey>,
associated_merkle_tree: Pubkey,
capacity: u16,
sequence_threshold: u64,
network_fee: u64,
rollover_threshold: Option<u64>,
close_threshold: Option<u64>,
height: u32,
merkle_tree_rent: u64,
) -> Result<()> {
{
let mut address_queue = queue_loader.load_init()?;
// Since the user doesn't interact with the address Merkle tree
// directly, we need to charge a `rollover_fee` both for the queue and
// Merkle tree.
let queue_rent = queue_account_info.lamports();
let rollover_fee = if let Some(rollover_threshold) = rollover_threshold {
let rollover_fee = compute_rollover_fee(rollover_threshold, height, merkle_tree_rent)
.map_err(ProgramError::from)?
+ compute_rollover_fee(rollover_threshold, height, queue_rent)
.map_err(ProgramError::from)?;
check_rollover_fee_sufficient(
rollover_fee,
queue_rent,
merkle_tree_rent,
rollover_threshold,
height,
)?;
msg!("address queue rollover_fee: {}", rollover_fee);
rollover_fee
} else {
0
};
address_queue.init(
AccessMetadata::new(owner, program_owner, forester),
RolloverMetadata::new(
index,
rollover_fee,
rollover_threshold,
network_fee,
close_threshold,
None,
),
associated_merkle_tree,
QueueType::AddressQueue,
);
drop(address_queue);
}
unsafe {
queue_from_bytes_zero_copy_init(
&mut queue_account_info.try_borrow_mut_data()?,
capacity as usize,
sequence_threshold as usize,
)
.map_err(ProgramError::from)?;
}
Ok(())
}
pub fn check_rollover_fee_sufficient(
rollover_fee: u64,
queue_rent: u64,
merkle_tree_rent: u64,
rollover_threshold: u64,
height: u32,
) -> Result<()> {
if rollover_fee != queue_rent + merkle_tree_rent
&& (rollover_fee * rollover_threshold * (2u64.pow(height))) / 100
< queue_rent + merkle_tree_rent
{
msg!("rollover_fee: {}", rollover_fee);
msg!("rollover_threshold: {}", rollover_threshold);
msg!("height: {}", height);
msg!("merkle_tree_rent: {}", merkle_tree_rent);
msg!("queue_rent: {}", queue_rent);
msg!(
"((rollover_fee * rollover_threshold * (2u64.pow(height))) / 100): {} < {} rent",
((rollover_fee * rollover_threshold * (2u64.pow(height))) / 100),
queue_rent + merkle_tree_rent
);
return err!(crate::errors::AccountCompressionErrorCode::InsufficientRolloverFee);
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/check_account.rs
|
use crate::errors::AccountCompressionErrorCode;
use anchor_lang::prelude::*;
use anchor_lang::solana_program::{account_info::AccountInfo, msg, rent::Rent};
/// Checks that the account balance is equal to rent exemption.
pub fn check_account_balance_is_rent_exempt(
account_info: &AccountInfo,
expected_size: usize,
) -> Result<u64> {
let account_size = account_info.data_len();
if account_size != expected_size {
msg!(
"Account {:?} size not equal to expected size. size: {}, expected size {}",
account_info.key(),
account_size,
expected_size
);
return err!(AccountCompressionErrorCode::InvalidAccountSize);
}
let lamports = account_info.lamports();
let rent_exemption = (Rent::get()?).minimum_balance(expected_size);
if lamports != rent_exemption {
msg!(
"Account {:?} lamports is not equal to rentexemption: lamports {}, rent exemption {}",
account_info.key(),
lamports,
rent_exemption
);
return err!(AccountCompressionErrorCode::InvalidAccountBalance);
}
Ok(lamports)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/check_signer_is_registered_or_authority.rs
|
use crate::{errors::AccountCompressionErrorCode, RegisteredProgram};
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
use super::constants::CPI_AUTHORITY_PDA_SEED;
pub trait GroupAccess {
fn get_owner(&self) -> &Pubkey;
fn get_program_owner(&self) -> &Pubkey;
}
pub trait GroupAccounts<'info> {
fn get_authority(&self) -> &Signer<'info>;
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>>;
}
/// if there is a registered program pda check whether the authority is derived from the registered program pda
/// else check whether the authority is the signing address
pub fn check_signer_is_registered_or_authority<
'a,
'b,
'c,
'info,
C: GroupAccounts<'info> + anchor_lang::Bumps,
A: GroupAccess,
>(
ctx: &'a Context<'a, 'b, 'c, 'info, C>,
checked_account: &'a A,
) -> Result<()> {
match ctx.accounts.get_registered_program_pda() {
Some(registered_program_pda) => {
let derived_address = Pubkey::find_program_address(
&[CPI_AUTHORITY_PDA_SEED],
®istered_program_pda.registered_program_id,
)
.0;
if ctx.accounts.get_authority().key() == derived_address
&& checked_account.get_owner().key() == registered_program_pda.group_authority_pda
{
Ok(())
} else {
msg!("Registered program check failed.");
msg!("owner address: {:?}", checked_account.get_owner());
msg!("derived_address: {:?}", derived_address);
msg!("signing_address: {:?}", ctx.accounts.get_authority().key());
msg!(
"registered_program_id: {:?}",
registered_program_pda.registered_program_id
);
Err(AccountCompressionErrorCode::InvalidAuthority.into())
}
}
None => {
if ctx.accounts.get_authority().key() == *checked_account.get_owner() {
Ok(())
} else {
Err(AccountCompressionErrorCode::InvalidAuthority.into())
}
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/constants.rs
|
// This file stores constants which do not have to be configured.
use anchor_lang::constant;
#[constant]
pub const CPI_AUTHORITY_PDA_SEED: &[u8] = b"cpi_authority";
#[constant]
pub const GROUP_AUTHORITY_SEED: &[u8] = b"group_authority";
#[constant]
pub const STATE_MERKLE_TREE_HEIGHT: u64 = 26;
#[constant]
pub const STATE_MERKLE_TREE_CHANGELOG: u64 = 1400;
#[constant]
pub const STATE_MERKLE_TREE_ROOTS: u64 = 2400;
#[constant]
pub const STATE_MERKLE_TREE_CANOPY_DEPTH: u64 = 10;
#[constant]
pub const STATE_NULLIFIER_QUEUE_VALUES: u16 = 28_807;
#[constant]
pub const STATE_NULLIFIER_QUEUE_SEQUENCE_THRESHOLD: u64 = 2400;
#[constant]
pub const ADDRESS_MERKLE_TREE_HEIGHT: u64 = 26;
#[constant]
pub const ADDRESS_MERKLE_TREE_CHANGELOG: u64 = 1400;
#[constant]
pub const ADDRESS_MERKLE_TREE_ROOTS: u64 = 2400;
#[constant]
pub const ADDRESS_MERKLE_TREE_CANOPY_DEPTH: u64 = 10;
#[constant]
pub const ADDRESS_MERKLE_TREE_INDEXED_CHANGELOG: u64 = 1400;
#[constant]
pub const ADDRESS_QUEUE_VALUES: u16 = 28_807;
#[constant]
pub const ADDRESS_QUEUE_SEQUENCE_THRESHOLD: u64 = 2400;
// noopb9bkMVfRPU8AsbpTUg8AQkHtKwMYZiFUjNRtMmV
#[constant]
pub const NOOP_PUBKEY: [u8; 32] = [
11, 188, 15, 192, 187, 71, 202, 47, 116, 196, 17, 46, 148, 171, 19, 207, 163, 198, 52, 229,
220, 23, 234, 203, 3, 205, 26, 35, 205, 126, 120, 124,
];
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/queue.rs
|
use std::collections::HashMap;
use anchor_lang::prelude::{AccountInfo, Pubkey};
/// Mapping of address queue public keys to a bundle containing:
///
/// * The queue.
/// * Associated Merkle tree.
/// * Addresses to insert.
pub type QueueMap<'info> = HashMap<Pubkey, QueueBundle<'info>>;
/// A bundle containing:
///
/// * Address queue.
/// * Merkle tree associated with that queue.
/// * Addresses to insert to that queue.
pub struct QueueBundle<'info> {
pub queue: &'info AccountInfo<'info>,
pub merkle_tree: &'info AccountInfo<'info>,
pub elements: Vec<[u8; 32]>,
}
impl<'info> QueueBundle<'info> {
pub fn new(queue: &'info AccountInfo<'info>, merkle_tree: &'info AccountInfo<'info>) -> Self {
Self {
queue,
merkle_tree,
elements: Vec::new(),
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/check_discrimininator.rs
|
use anchor_lang::{error::ErrorCode, Owner, Result, ZeroCopy};
pub fn check_discriminator<T: ZeroCopy + Owner + std::fmt::Debug>(data: &[u8]) -> Result<()> {
let disc_bytes: [u8; 8] = data[0..8].try_into().unwrap();
if disc_bytes != T::discriminator() {
return Err(ErrorCode::AccountDiscriminatorMismatch.into());
}
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/mod.rs
|
pub mod check_account;
pub mod check_discrimininator;
pub mod check_signer_is_registered_or_authority;
pub mod constants;
pub mod queue;
pub mod transfer_lamports;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/utils/transfer_lamports.rs
|
use crate::errors::AccountCompressionErrorCode;
use anchor_lang::prelude::*;
pub fn transfer_lamports<'info>(
from: &AccountInfo<'info>,
to: &AccountInfo<'info>,
lamports: u64,
) -> Result<()> {
let compressed_sol_pda_lamports = from.lamports();
**from.as_ref().try_borrow_mut_lamports()? =
match compressed_sol_pda_lamports.checked_sub(lamports) {
Some(lamports) => lamports,
None => return err!(AccountCompressionErrorCode::IntegerOverflow),
};
let recipient_lamports = to.lamports();
**to.as_ref().try_borrow_mut_lamports()? = match recipient_lamports.checked_add(lamports) {
Some(lamports) => lamports,
None => return err!(AccountCompressionErrorCode::IntegerOverflow),
};
Ok(())
}
pub fn transfer_lamports_cpi<'info>(
from: &AccountInfo<'info>,
to: &AccountInfo<'info>,
lamports: u64,
) -> Result<()> {
let instruction =
anchor_lang::solana_program::system_instruction::transfer(from.key, to.key, lamports);
anchor_lang::solana_program::program::invoke(&instruction, &[from.clone(), to.clone()])?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/access.rs
|
use anchor_lang::prelude::*;
#[account(zero_copy)]
#[derive(AnchorDeserialize, Debug, PartialEq, Default)]
pub struct AccessMetadata {
/// Owner of the Merkle tree.
pub owner: Pubkey,
/// Program owner of the Merkle tree. This will be used for program owned Merkle trees.
pub program_owner: Pubkey,
/// Optional privileged forester pubkey, can be set for custom Merkle trees
/// without a network fee. Merkle trees without network fees are not
/// forested by light foresters. The variable is not used in the account
/// compression program but the registry program. The registry program
/// implements access control to prevent contention during forester. The
/// forester pubkey specified in this struct can bypass contention checks.
pub forester: Pubkey,
}
impl AccessMetadata {
pub fn new(owner: Pubkey, program_owner: Option<Pubkey>, forester: Option<Pubkey>) -> Self {
Self {
owner,
program_owner: program_owner.unwrap_or_default(),
forester: forester.unwrap_or_default(),
}
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/group_authority.rs
|
use aligned_sized::aligned_sized;
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey};
#[account]
#[aligned_sized(anchor)]
#[derive(Debug)]
pub struct GroupAuthority {
pub authority: Pubkey,
pub seed: Pubkey,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/address.rs
|
use std::mem;
use crate::{
utils::check_signer_is_registered_or_authority::GroupAccess, AccessMetadata,
MerkleTreeMetadata, RolloverMetadata,
};
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
use light_hasher::Poseidon;
use light_indexed_merkle_tree::{
zero_copy::{IndexedMerkleTreeZeroCopy, IndexedMerkleTreeZeroCopyMut},
IndexedMerkleTree,
};
#[account(zero_copy)]
#[aligned_sized(anchor)]
#[derive(AnchorDeserialize, Debug)]
pub struct AddressMerkleTreeAccount {
pub metadata: MerkleTreeMetadata,
}
impl GroupAccess for AddressMerkleTreeAccount {
fn get_owner(&self) -> &Pubkey {
&self.metadata.access_metadata.owner
}
fn get_program_owner(&self) -> &Pubkey {
&self.metadata.access_metadata.program_owner
}
}
impl AddressMerkleTreeAccount {
pub fn size(
height: usize,
changelog_size: usize,
roots_size: usize,
canopy_depth: usize,
indexed_changelog_size: usize,
) -> usize {
8 + mem::size_of::<Self>()
+ IndexedMerkleTree::<Poseidon, usize, 26, 16>::size_in_account(
height,
changelog_size,
roots_size,
canopy_depth,
indexed_changelog_size,
)
}
pub fn init(
&mut self,
access_metadata: AccessMetadata,
rollover_metadata: RolloverMetadata,
associated_queue: Pubkey,
) {
self.metadata
.init(access_metadata, rollover_metadata, associated_queue)
}
}
pub fn address_merkle_tree_from_bytes_zero_copy(
data: &[u8],
) -> Result<IndexedMerkleTreeZeroCopy<Poseidon, usize, 26, 16>> {
let data = &data[8 + mem::size_of::<AddressMerkleTreeAccount>()..];
let merkle_tree =
IndexedMerkleTreeZeroCopy::from_bytes_zero_copy(data).map_err(ProgramError::from)?;
Ok(merkle_tree)
}
pub fn address_merkle_tree_from_bytes_zero_copy_init(
data: &mut [u8],
height: usize,
canopy_depth: usize,
changelog_capacity: usize,
roots_capacity: usize,
indexed_changelog_capacity: usize,
) -> Result<IndexedMerkleTreeZeroCopyMut<Poseidon, usize, 26, 16>> {
let data = &mut data[8 + mem::size_of::<AddressMerkleTreeAccount>()..];
let merkle_tree = IndexedMerkleTreeZeroCopyMut::from_bytes_zero_copy_init(
data,
height,
canopy_depth,
changelog_capacity,
roots_capacity,
indexed_changelog_capacity,
)
.map_err(ProgramError::from)?;
Ok(merkle_tree)
}
pub fn address_merkle_tree_from_bytes_zero_copy_mut(
data: &mut [u8],
) -> Result<IndexedMerkleTreeZeroCopyMut<Poseidon, usize, 26, 16>> {
let data = &mut data[8 + mem::size_of::<AddressMerkleTreeAccount>()..];
let merkle_tree =
IndexedMerkleTreeZeroCopyMut::from_bytes_zero_copy_mut(data).map_err(ProgramError::from)?;
Ok(merkle_tree)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/queue.rs
|
use crate::InsertIntoQueues;
use crate::{errors::AccountCompressionErrorCode, AccessMetadata, RolloverMetadata};
use crate::{
utils::check_signer_is_registered_or_authority::{GroupAccess, GroupAccounts},
RegisteredProgram,
};
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
use light_hash_set::{zero_copy::HashSetZeroCopy, HashSet};
use std::mem;
#[account(zero_copy)]
#[derive(AnchorDeserialize, Debug, PartialEq)]
pub struct QueueMetadata {
pub access_metadata: AccessMetadata,
pub rollover_metadata: RolloverMetadata,
// Queue associated with this Merkle tree.
pub associated_merkle_tree: Pubkey,
// Next queue to be used after rollover.
pub next_queue: Pubkey,
pub queue_type: u64,
}
#[derive(AnchorDeserialize, AnchorSerialize, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum QueueType {
NullifierQueue = 1,
AddressQueue = 2,
}
pub fn check_queue_type(queue_type: &u64, expected_queue_type: &QueueType) -> Result<()> {
if *queue_type != (*expected_queue_type) as u64 {
err!(AccountCompressionErrorCode::InvalidQueueType)
} else {
Ok(())
}
}
impl QueueMetadata {
pub fn init(
&mut self,
access_metadata: AccessMetadata,
rollover_metadata: RolloverMetadata,
associated_merkle_tree: Pubkey,
queue_type: QueueType,
) {
self.access_metadata = access_metadata;
self.rollover_metadata = rollover_metadata;
self.associated_merkle_tree = associated_merkle_tree;
self.queue_type = queue_type as u64;
}
pub fn rollover(
&mut self,
old_associated_merkle_tree: Pubkey,
next_queue: Pubkey,
) -> Result<()> {
if self.associated_merkle_tree != old_associated_merkle_tree {
return err!(AccountCompressionErrorCode::MerkleTreeAndQueueNotAssociated);
}
self.rollover_metadata.rollover()?;
self.next_queue = next_queue;
Ok(())
}
}
#[account(zero_copy)]
#[derive(AnchorDeserialize, Debug, PartialEq)]
#[aligned_sized(anchor)]
pub struct QueueAccount {
pub metadata: QueueMetadata,
}
impl QueueAccount {
pub fn init(
&mut self,
access_metadata: AccessMetadata,
rollover_meta_data: RolloverMetadata,
associated_merkle_tree: Pubkey,
queue_type: QueueType,
) {
self.metadata.init(
access_metadata,
rollover_meta_data,
associated_merkle_tree,
queue_type,
)
}
}
impl GroupAccess for QueueAccount {
fn get_owner(&self) -> &Pubkey {
&self.metadata.access_metadata.owner
}
fn get_program_owner(&self) -> &Pubkey {
&self.metadata.access_metadata.program_owner
}
}
impl<'info> GroupAccounts<'info> for InsertIntoQueues<'info> {
fn get_authority(&self) -> &Signer<'info> {
&self.authority
}
fn get_registered_program_pda(&self) -> &Option<Account<'info, RegisteredProgram>> {
&self.registered_program_pda
}
}
impl QueueAccount {
pub fn size(capacity: usize) -> Result<usize> {
Ok(8 + mem::size_of::<Self>() + HashSet::size_in_account(capacity))
}
}
/// Creates a copy of `HashSet` from the given account data.
///
/// # Safety
///
/// This operation is unsafe. It's the caller's responsibility to ensure that
/// the provided account data have correct size and alignment.
pub unsafe fn queue_from_bytes_copy(data: &mut [u8]) -> Result<HashSet> {
let data = &mut data[8 + mem::size_of::<QueueAccount>()..];
let queue = HashSet::from_bytes_copy(data).map_err(ProgramError::from)?;
Ok(queue)
}
/// Casts the given account data to an `HashSetZeroCopy` instance.
///
/// # Safety
///
/// This operation is unsafe. It's the caller's responsibility to ensure that
/// the provided account data have correct size and alignment.
pub unsafe fn queue_from_bytes_zero_copy_mut(data: &mut [u8]) -> Result<HashSetZeroCopy> {
let data = &mut data[8 + mem::size_of::<QueueAccount>()..];
let queue = HashSetZeroCopy::from_bytes_zero_copy_mut(data).map_err(ProgramError::from)?;
Ok(queue)
}
/// Casts the given account data to an `HashSetZeroCopy` instance.
///
/// # Safety
///
/// This operation is unsafe. It's the caller's responsibility to ensure that
/// the provided account data have correct size and alignment.
pub unsafe fn queue_from_bytes_zero_copy_init(
data: &mut [u8],
capacity: usize,
sequence_threshold: usize,
) -> Result<HashSetZeroCopy> {
let data = &mut data[8 + mem::size_of::<QueueAccount>()..];
let queue = HashSetZeroCopy::from_bytes_zero_copy_init(data, capacity, sequence_threshold)
.map_err(ProgramError::from)?;
Ok(queue)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/rollover.rs
|
use anchor_lang::prelude::*;
#[account(zero_copy)]
#[derive(AnchorDeserialize, Debug, PartialEq, Default)]
pub struct RolloverMetadata {
/// Unique index.
pub index: u64,
/// This fee is used for rent for the next account.
/// It accumulates in the account so that once the corresponding Merkle tree account is full it can be rolled over
pub rollover_fee: u64,
/// The threshold in percentage points when the account should be rolled over (95 corresponds to 95% filled).
pub rollover_threshold: u64,
/// Tip for maintaining the account.
pub network_fee: u64,
/// The slot when the account was rolled over, a rolled over account should not be written to.
pub rolledover_slot: u64,
/// If current slot is greater than rolledover_slot + close_threshold and
/// the account is empty it can be closed. No 'close' functionality has been
/// implemented yet.
pub close_threshold: u64,
/// Placeholder for bytes of additional accounts which are tied to the
/// Merkle trees operation and need to be rolled over as well.
pub additional_bytes: u64,
}
impl RolloverMetadata {
pub fn new(
index: u64,
rollover_fee: u64,
rollover_threshold: Option<u64>,
network_fee: u64,
close_threshold: Option<u64>,
additional_bytes: Option<u64>,
) -> Self {
Self {
index,
rollover_fee,
rollover_threshold: rollover_threshold.unwrap_or(u64::MAX),
network_fee,
rolledover_slot: u64::MAX,
close_threshold: close_threshold.unwrap_or(u64::MAX),
additional_bytes: additional_bytes.unwrap_or_default(),
}
}
pub fn rollover(&mut self) -> Result<()> {
if self.rollover_threshold == u64::MAX {
return err!(crate::errors::AccountCompressionErrorCode::RolloverNotConfigured);
}
if self.rolledover_slot != u64::MAX {
return err!(crate::errors::AccountCompressionErrorCode::MerkleTreeAlreadyRolledOver);
}
#[cfg(target_os = "solana")]
{
self.rolledover_slot = Clock::get()?.slot;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rollover_metadata() {
let mut metadata = RolloverMetadata::new(0, 0, Some(95), 0, Some(100), Some(1));
assert_eq!(metadata.rollover_threshold, 95);
assert_eq!(metadata.close_threshold, 100);
assert_eq!(metadata.rolledover_slot, u64::MAX);
assert_eq!(metadata.additional_bytes, 1);
metadata.rollover().unwrap();
let mut metadata = RolloverMetadata::new(0, 0, None, 0, None, None);
assert_eq!(metadata.rollover_threshold, u64::MAX);
assert_eq!(metadata.close_threshold, u64::MAX);
assert_eq!(metadata.additional_bytes, 0);
assert_eq!(
metadata.rollover(),
Err(crate::errors::AccountCompressionErrorCode::RolloverNotConfigured.into())
);
let mut metadata = RolloverMetadata::new(0, 0, Some(95), 0, None, None);
assert_eq!(metadata.close_threshold, u64::MAX);
metadata.rollover().unwrap();
let mut metadata = RolloverMetadata::new(0, 0, Some(95), 0, None, None);
metadata.rolledover_slot = 0;
assert_eq!(metadata.close_threshold, u64::MAX);
assert_eq!(
metadata.rollover(),
Err(crate::errors::AccountCompressionErrorCode::MerkleTreeAlreadyRolledOver.into())
);
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/public_state_merkle_tree.rs
|
use std::mem;
use aligned_sized::aligned_sized;
use anchor_lang::prelude::*;
use light_concurrent_merkle_tree::{
zero_copy::{ConcurrentMerkleTreeZeroCopy, ConcurrentMerkleTreeZeroCopyMut},
ConcurrentMerkleTree,
};
use light_hasher::Poseidon;
use crate::{AccessMetadata, MerkleTreeMetadata, RolloverMetadata};
/// Concurrent state Merkle tree used for public compressed transactions.
#[account(zero_copy)]
#[aligned_sized(anchor)]
#[derive(AnchorDeserialize, Debug, Default)]
pub struct StateMerkleTreeAccount {
pub metadata: MerkleTreeMetadata,
}
impl StateMerkleTreeAccount {
pub fn size(
height: usize,
changelog_size: usize,
roots_size: usize,
canopy_depth: usize,
) -> usize {
8 + mem::size_of::<Self>()
+ ConcurrentMerkleTree::<Poseidon, 26>::size_in_account(
height,
changelog_size,
roots_size,
canopy_depth,
)
}
pub fn init(
&mut self,
access_metadata: AccessMetadata,
rollover_metadata: RolloverMetadata,
associated_queue: Pubkey,
) {
self.metadata
.init(access_metadata, rollover_metadata, associated_queue)
}
}
pub fn state_merkle_tree_from_bytes_zero_copy_init(
data: &mut [u8],
height: usize,
canopy_depth: usize,
changelog_capacity: usize,
roots_capacity: usize,
) -> Result<ConcurrentMerkleTreeZeroCopyMut<Poseidon, 26>> {
let data = &mut data[8 + mem::size_of::<StateMerkleTreeAccount>()..];
let merkle_tree = ConcurrentMerkleTreeZeroCopyMut::from_bytes_zero_copy_init(
data,
height,
canopy_depth,
changelog_capacity,
roots_capacity,
)
.map_err(ProgramError::from)?;
Ok(merkle_tree)
}
pub fn state_merkle_tree_from_bytes_zero_copy(
data: &[u8],
) -> Result<ConcurrentMerkleTreeZeroCopy<Poseidon, 26>> {
let data = &data[8 + mem::size_of::<StateMerkleTreeAccount>()..];
let merkle_tree =
ConcurrentMerkleTreeZeroCopy::from_bytes_zero_copy(data).map_err(ProgramError::from)?;
Ok(merkle_tree)
}
pub fn state_merkle_tree_from_bytes_zero_copy_mut(
data: &mut [u8],
) -> Result<ConcurrentMerkleTreeZeroCopyMut<Poseidon, 26>> {
let data = &mut data[8 + mem::size_of::<StateMerkleTreeAccount>()..];
let merkle_tree = ConcurrentMerkleTreeZeroCopyMut::from_bytes_zero_copy_mut(data)
.map_err(ProgramError::from)?;
Ok(merkle_tree)
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/change_log_event.rs
|
use anchor_lang::{
prelude::*,
solana_program::{instruction::Instruction, program::invoke},
};
use crate::{errors::AccountCompressionErrorCode, utils::constants::NOOP_PUBKEY};
#[inline(never)]
pub fn emit_indexer_event(data: Vec<u8>, noop_program: &AccountInfo) -> Result<()> {
if noop_program.key() != Pubkey::new_from_array(NOOP_PUBKEY) || !noop_program.executable {
return err!(AccountCompressionErrorCode::InvalidNoopPubkey);
}
let instruction = Instruction {
program_id: noop_program.key(),
accounts: vec![],
data,
};
invoke(&instruction, &[noop_program.to_account_info()])?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/mod.rs
|
pub mod access;
pub use access::*;
pub mod address;
pub use address::*;
pub mod merkle_tree;
pub use merkle_tree::*;
pub mod public_state_merkle_tree;
pub use public_state_merkle_tree::*;
pub mod change_log_event;
pub use change_log_event::*;
pub mod queue;
pub use queue::*;
pub mod rollover;
pub use rollover::*;
pub mod group_authority;
pub use group_authority::*;
| 0
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src
|
solana_public_repos/Lightprotocol/light-protocol/programs/account-compression/src/state/merkle_tree.rs
|
use anchor_lang::prelude::*;
use crate::{errors::AccountCompressionErrorCode, AccessMetadata, RolloverMetadata};
#[account(zero_copy)]
#[derive(AnchorDeserialize, Debug, PartialEq, Default)]
pub struct MerkleTreeMetadata {
pub access_metadata: AccessMetadata,
pub rollover_metadata: RolloverMetadata,
// Queue associated with this Merkle tree.
pub associated_queue: Pubkey,
// Next Merkle tree to be used after rollover.
pub next_merkle_tree: Pubkey,
}
impl MerkleTreeMetadata {
pub fn init(
&mut self,
access_metadata: AccessMetadata,
rollover_metadata: RolloverMetadata,
associated_queue: Pubkey,
) {
self.access_metadata = access_metadata;
self.rollover_metadata = rollover_metadata;
self.associated_queue = associated_queue;
}
pub fn rollover(
&mut self,
old_associated_queue: Pubkey,
next_merkle_tree: Pubkey,
) -> Result<()> {
if self.associated_queue != old_associated_queue {
return err!(AccountCompressionErrorCode::MerkleTreeAndQueueNotAssociated);
}
self.rollover_metadata.rollover()?;
self.next_merkle_tree = next_merkle_tree;
Ok(())
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/Cargo.toml
|
[package]
name = "system-cpi-test"
version = "1.1.0"
description = "Test program using generalized account compression"
repository = "https://github.com/Lightprotocol/light-protocol"
license = "Apache-2.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "system_cpi_test"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
test-sbf = []
custom-heap = []
default = ["custom-heap"]
[dependencies]
anchor-lang = { workspace = true }
anchor-spl = { workspace = true }
light-compressed-token = { workspace = true }
light-system-program = { workspace = true }
light-registry = { workspace = true }
account-compression = { workspace = true }
light-hasher = { path = "../../merkle-tree/hasher", version = "1.1.0" }
light-utils = { path = "../../utils", version = "1.1.0" }
[target.'cfg(not(target_os = "solana"))'.dependencies]
solana-sdk = { workspace = true }
[dev-dependencies]
solana-program-test = { workspace = true }
light-program-test = { workspace = true, features=["devenv"]}
light-test-utils = { version = "1.2.0", path = "../../test-utils", features=["devenv"] }
reqwest = "0.11.26"
tokio = { workspace = true }
light-prover-client = { path = "../../circuit-lib/light-prover-client", version = "1.2.0" }
num-bigint = "0.4.6"
num-traits = "0.2.19"
spl-token = { workspace = true }
anchor-spl = { workspace = true }
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/tests/test.rs
|
#![cfg(feature = "test-sbf")]
use anchor_lang::AnchorDeserialize;
use light_compressed_token::process_transfer::InputTokenDataWithContext;
use light_compressed_token::token_data::AccountState;
use light_hasher::{Hasher, Poseidon};
use light_program_test::test_env::{setup_test_programs_with_accounts, EnvAccounts};
use light_prover_client::gnark::helpers::{ProverConfig, ProverMode};
use light_system_program::errors::SystemProgramError;
use light_system_program::sdk::address::derive_address;
use light_system_program::sdk::compressed_account::{
CompressedAccountWithMerkleContext, PackedCompressedAccountWithMerkleContext,
PackedMerkleContext,
};
use light_system_program::sdk::event::PublicTransactionEvent;
use light_system_program::sdk::CompressedCpiContext;
use light_system_program::NewAddressParams;
use light_test_utils::indexer::TestIndexer;
use light_test_utils::spl::{create_mint_helper, mint_tokens_helper};
use light_test_utils::system_program::transfer_compressed_sol_test;
use light_test_utils::{assert_rpc_error, Indexer, RpcConnection, RpcError, TokenDataWithContext};
use light_utils::hash_to_bn254_field_size_be;
use solana_sdk::signature::Keypair;
use solana_sdk::{pubkey::Pubkey, signer::Signer, transaction::Transaction};
use system_cpi_test::sdk::{
create_invalidate_not_owned_account_instruction, create_pda_instruction,
CreateCompressedPdaInstructionInputs, InvalidateNotOwnedCompressedAccountInstructionInputs,
};
use system_cpi_test::{self, RegisteredUser, TokenTransferData, WithInputAccountsMode};
use system_cpi_test::{CreatePdaMode, ID};
/// Test:
/// Functional:
/// 1. Create pda
/// Failing tests To add:
/// 1. invalid signer seeds (CpiSignerCheckFailed)
/// 2. invalid invoking program (CpiSignerCheckFailed)
/// 3. write data to an account that it doesn't own (WriteAccessCheckFailed)
/// 4. input account that is not owned by signer(SignerCheckFailed)
/// Failing tests with cpi context:
/// 5. provide cpi context but no cpi context account (CpiContextMissing)
/// 6. provide cpi context account but no cpi context (CpiContextAccountUndefined)
/// 7. provide cpi context account but cpi context is empty (CpiContextEmpty)
/// 8. test signer checks trying to insert into cpi context account (invalid invoking program)
/// 10. provide cpi context account but cpi context has a different fee payer (CpiContextFeePayerMismatch)
/// 11. write data to an account that it doesn't own (WriteAccessCheckFailed)
/// 12. Spend Program owned account with program keypair (SignerCheckFailed)
/// 13. Create program owned account without data (DataFieldUndefined)
#[tokio::test]
async fn only_test_create_pda() {
let (mut rpc, env) =
setup_test_programs_with_accounts(Some(vec![(String::from("system_cpi_test"), ID)])).await;
let payer = rpc.get_payer().insecure_clone();
let mut test_indexer = TestIndexer::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
let seed = [1u8; 32];
let data = [2u8; 31];
// Functional test 1 ----------------------------------------------
perform_create_pda_with_event(
&mut test_indexer,
&mut rpc,
&env,
&payer,
seed,
&data,
&ID,
CreatePdaMode::ProgramIsSigner,
)
.await
.unwrap();
assert_created_pda(&mut test_indexer, &env, &payer, &seed, &data).await;
let seed = [2u8; 32];
let data = [3u8; 31];
// Failing 2 invoking program ----------------------------------------------
perform_create_pda_failing(
&mut test_indexer,
&mut rpc,
&env,
&payer,
seed,
&data,
&ID,
CreatePdaMode::InvalidInvokingProgram,
SystemProgramError::CpiSignerCheckFailed.into(),
)
.await
.unwrap();
// Failing 3 write to account not owned ----------------------------------------------
perform_create_pda_failing(
&mut test_indexer,
&mut rpc,
&env,
&payer,
seed,
&data,
&ID,
CreatePdaMode::WriteToAccountNotOwned,
SystemProgramError::WriteAccessCheckFailed.into(),
)
.await
.unwrap();
// create a token program owned Merkle tree
// mint tokens to that tree
let program_owned_merkle_tree_keypair = Keypair::new();
let program_owned_queue_keypair = Keypair::new();
let program_owned_cpi_context_keypair = Keypair::new();
test_indexer
.add_state_merkle_tree(
&mut rpc,
&program_owned_merkle_tree_keypair,
&program_owned_queue_keypair,
&program_owned_cpi_context_keypair,
Some(light_compressed_token::ID),
None,
)
.await;
let mint = create_mint_helper(&mut rpc, &payer).await;
let amount = 10000u64;
mint_tokens_helper(
&mut rpc,
&mut test_indexer,
&program_owned_merkle_tree_keypair.pubkey(),
&payer,
&mint,
vec![amount],
vec![payer.pubkey()],
)
.await;
let compressed_account = test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())
[0]
.compressed_account
.clone();
// Failing 4 input account that is not owned by signer ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
None,
SystemProgramError::SignerCheckFailed.into(),
WithInputAccountsMode::NotOwnedCompressedAccount,
)
.await
.unwrap();
{
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
// Failing 5 provide cpi context but no cpi context account ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
None,
SystemProgramError::CpiContextMissing.into(),
WithInputAccountsMode::CpiContextMissing,
)
.await
.unwrap();
// Failing 6 provide cpi context account but no cpi context ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
None,
SystemProgramError::CpiContextAccountUndefined.into(),
WithInputAccountsMode::CpiContextAccountMissing,
)
.await
.unwrap();
// Failing 7 provide cpi context account but cpi context is empty ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
None,
SystemProgramError::CpiContextEmpty.into(),
WithInputAccountsMode::CpiContextEmpty,
)
.await
.unwrap();
// Failing 8 test signer checks trying to insert into cpi context account (invalid invoking program) ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
None,
SystemProgramError::CpiSignerCheckFailed.into(),
WithInputAccountsMode::CpiContextInvalidInvokingProgram,
)
.await
.unwrap();
let compressed_token_account_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
// Failing 10 provide cpi context account but cpi context has a different proof ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
Some(compressed_token_account_data),
SystemProgramError::CpiContextFeePayerMismatch.into(),
WithInputAccountsMode::CpiContextFeePayerMismatch,
)
.await
.unwrap();
// Failing 11 write to account not owned ----------------------------------------------
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
None,
SystemProgramError::WriteAccessCheckFailed.into(),
WithInputAccountsMode::CpiContextWriteToNotOwnedAccount,
)
.await
.unwrap();
// Failing 12 Spend with program keypair
{
const CPI_SYSTEM_TEST_PROGRAM_ID_KEYPAIR: [u8; 64] = [
57, 80, 188, 3, 162, 80, 232, 181, 222, 192, 247, 98, 140, 227, 70, 15, 169, 202,
73, 184, 23, 90, 69, 95, 211, 74, 128, 232, 155, 216, 5, 230, 213, 158, 155, 203,
26, 211, 193, 195, 11, 219, 9, 155, 58, 172, 58, 200, 254, 75, 231, 106, 31, 168,
183, 76, 179, 113, 234, 101, 191, 99, 156, 98,
];
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
let keypair = Keypair::from_bytes(&CPI_SYSTEM_TEST_PROGRAM_ID_KEYPAIR).unwrap();
let result = transfer_compressed_sol_test(
&mut rpc,
&mut test_indexer,
&keypair,
&[compressed_account],
&[Pubkey::new_unique()],
&[env.merkle_tree_pubkey],
None,
)
.await;
assert_rpc_error(result, 0, SystemProgramError::SignerCheckFailed.into()).unwrap();
}
// Failing 13 DataFieldUndefined ----------------------------------------------
perform_create_pda_failing(
&mut test_indexer,
&mut rpc,
&env,
&payer,
seed,
&data,
&ID,
CreatePdaMode::NoData,
SystemProgramError::DataFieldUndefined.into(),
)
.await
.unwrap();
}
}
// TODO: add transfer and burn with delegate
// TODO: create a cleaner function than perform_with_input_accounts which was
// build for failing tests to execute the instructions
/// Functional Tests:
/// - tests the following methods with cpi context:
/// 1. Approve
/// 2. Revoke
/// 3. Freeze
/// 4. Thaw
/// 5. Burn
#[tokio::test]
async fn test_approve_revoke_burn_freeze_thaw_with_cpi_context() {
let (mut rpc, env) =
setup_test_programs_with_accounts(Some(vec![(String::from("system_cpi_test"), ID)])).await;
let payer = rpc.get_payer().insecure_clone();
let mut test_indexer = TestIndexer::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
let mint = create_mint_helper(&mut rpc, &payer).await;
let amount = 10000u64;
mint_tokens_helper(
&mut rpc,
&mut test_indexer,
&env.merkle_tree_pubkey,
&payer,
&mint,
vec![amount],
vec![payer.pubkey()],
)
.await;
let seed = [1u8; 32];
let data = [2u8; 31];
perform_create_pda_with_event(
&mut test_indexer,
&mut rpc,
&env,
&payer,
seed,
&data,
&ID,
CreatePdaMode::ProgramIsSigner,
)
.await
.unwrap();
let delegate = Keypair::new();
let ref_compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
// 1. Approve functional with cpi context
{
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
Some(&delegate),
&compressed_account,
Some(compressed_token_data),
u32::MAX,
WithInputAccountsMode::Approve,
)
.await
.unwrap();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
let mut ref_data = ref_compressed_token_data.token_data.clone();
ref_data.delegate = Some(delegate.pubkey());
assert_eq!(compressed_token_data.token_data, ref_data);
assert_ne!(
ref_compressed_token_data.compressed_account.merkle_context,
compressed_token_data.compressed_account.merkle_context
);
}
// 2. Revoke functional with cpi context
{
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
let compressed_token_data = test_indexer
.get_compressed_token_accounts_by_owner(&payer.pubkey())
.iter()
.filter(|x| x.token_data.delegate.is_some())
.collect::<Vec<_>>()[0]
.clone();
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
Some(&delegate),
&compressed_account,
Some(compressed_token_data),
u32::MAX,
WithInputAccountsMode::Revoke,
)
.await
.unwrap();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
let ref_data = ref_compressed_token_data.token_data.clone();
assert_eq!(compressed_token_data.token_data, ref_data);
}
// 3. Freeze functional with cpi context
{
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
Some(compressed_token_data),
u32::MAX,
WithInputAccountsMode::Freeze,
)
.await
.unwrap();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
let mut ref_data = ref_compressed_token_data.token_data.clone();
ref_data.state = AccountState::Frozen;
assert_eq!(compressed_token_data.token_data, ref_data);
}
// 4. Thaw functional with cpi context
{
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
Some(compressed_token_data),
u32::MAX,
WithInputAccountsMode::Thaw,
)
.await
.unwrap();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
let ref_data = ref_compressed_token_data.token_data.clone();
assert_eq!(compressed_token_data.token_data, ref_data);
}
// 5. Burn functional with cpi context
{
let compressed_account = test_indexer.get_compressed_accounts_by_owner(&ID)[0].clone();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
perform_with_input_accounts(
&mut test_indexer,
&mut rpc,
&payer,
None,
&compressed_account,
Some(compressed_token_data),
u32::MAX,
WithInputAccountsMode::Burn,
)
.await
.unwrap();
let compressed_token_data =
test_indexer.get_compressed_token_accounts_by_owner(&payer.pubkey())[0].clone();
let mut ref_data = ref_compressed_token_data.token_data.clone();
ref_data.amount = 1;
assert_eq!(compressed_token_data.token_data, ref_data);
}
}
/// Test:
/// 1. Cannot create an address in a program owned address Merkle tree owned by a different program (InvalidMerkleTreeOwner)
/// 2. Cannot create a compressed account in a program owned state Merkle tree owned by a different program (InvalidMerkleTreeOwner)
/// 3. Create a compressed account and address in program owned state and address Merkle trees
#[tokio::test]
async fn test_create_pda_in_program_owned_merkle_trees() {
let (mut rpc, env) =
setup_test_programs_with_accounts(Some(vec![(String::from("system_cpi_test"), ID)])).await;
let payer = rpc.get_payer().insecure_clone();
let mut test_indexer = TestIndexer::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
// Failing test 1 invalid address Merkle tree ----------------------------------------------
let program_owned_address_merkle_tree_keypair = Keypair::new();
let program_owned_address_queue_keypair = Keypair::new();
test_indexer
.add_address_merkle_tree(
&mut rpc,
&program_owned_address_merkle_tree_keypair,
&program_owned_address_queue_keypair,
Some(light_compressed_token::ID),
)
.await;
let env_with_program_owned_address_merkle_tree = EnvAccounts {
address_merkle_tree_pubkey: program_owned_address_merkle_tree_keypair.pubkey(),
address_merkle_tree_queue_pubkey: program_owned_address_queue_keypair.pubkey(),
merkle_tree_pubkey: env.merkle_tree_pubkey,
nullifier_queue_pubkey: env.nullifier_queue_pubkey,
cpi_context_account_pubkey: env.cpi_context_account_pubkey,
governance_authority: env.governance_authority.insecure_clone(),
governance_authority_pda: env.governance_authority_pda,
group_pda: env.group_pda,
registered_program_pda: env.registered_program_pda,
registered_registry_program_pda: env.registered_registry_program_pda,
forester: env.forester.insecure_clone(),
registered_forester_pda: env.registered_forester_pda,
forester_epoch: env.forester_epoch.clone(),
};
perform_create_pda_failing(
&mut test_indexer,
&mut rpc,
&env_with_program_owned_address_merkle_tree,
&payer,
[3u8; 32],
&[4u8; 31],
&ID,
CreatePdaMode::ProgramIsSigner,
SystemProgramError::InvalidMerkleTreeOwner.into(),
)
.await
.unwrap();
// Failing test 2 invalid state Merkle tree ----------------------------------------------
let program_owned_state_merkle_tree_keypair = Keypair::new();
let program_owned_state_queue_keypair = Keypair::new();
let program_owned_cpi_context_keypair = Keypair::new();
test_indexer
.add_state_merkle_tree(
&mut rpc,
&program_owned_state_merkle_tree_keypair,
&program_owned_state_queue_keypair,
&program_owned_cpi_context_keypair,
Some(light_compressed_token::ID),
None,
)
.await;
let env_with_program_owned_state_merkle_tree = EnvAccounts {
address_merkle_tree_pubkey: env.address_merkle_tree_pubkey,
address_merkle_tree_queue_pubkey: env.address_merkle_tree_queue_pubkey,
merkle_tree_pubkey: program_owned_state_merkle_tree_keypair.pubkey(),
nullifier_queue_pubkey: program_owned_state_queue_keypair.pubkey(),
cpi_context_account_pubkey: program_owned_cpi_context_keypair.pubkey(),
governance_authority: env.governance_authority.insecure_clone(),
governance_authority_pda: env.governance_authority_pda,
group_pda: env.group_pda,
registered_program_pda: env.registered_program_pda,
registered_registry_program_pda: env.registered_registry_program_pda,
forester: env.forester.insecure_clone(),
registered_forester_pda: env.registered_forester_pda,
forester_epoch: env.forester_epoch.clone(),
};
perform_create_pda_failing(
&mut test_indexer,
&mut rpc,
&env_with_program_owned_state_merkle_tree,
&payer,
[3u8; 32],
&[4u8; 31],
&ID,
CreatePdaMode::ProgramIsSigner,
SystemProgramError::InvalidMerkleTreeOwner.into(),
)
.await
.unwrap();
// Functional test ----------------------------------------------
let program_owned_state_merkle_tree_keypair = Keypair::new();
let program_owned_state_queue_keypair = Keypair::new();
let program_owned_cpi_context_keypair = Keypair::new();
test_indexer
.add_state_merkle_tree(
&mut rpc,
&program_owned_state_merkle_tree_keypair,
&program_owned_state_queue_keypair,
&program_owned_cpi_context_keypair,
Some(ID),
None,
)
.await;
let program_owned_address_merkle_tree_keypair = Keypair::new();
let program_owned_address_queue_keypair = Keypair::new();
test_indexer
.add_address_merkle_tree(
&mut rpc,
&program_owned_address_merkle_tree_keypair,
&program_owned_address_queue_keypair,
Some(ID),
)
.await;
let env_with_program_owned_state_merkle_tree = EnvAccounts {
address_merkle_tree_pubkey: program_owned_address_merkle_tree_keypair.pubkey(),
address_merkle_tree_queue_pubkey: program_owned_address_queue_keypair.pubkey(),
merkle_tree_pubkey: program_owned_state_merkle_tree_keypair.pubkey(),
nullifier_queue_pubkey: program_owned_state_queue_keypair.pubkey(),
cpi_context_account_pubkey: program_owned_cpi_context_keypair.pubkey(),
governance_authority: env.governance_authority.insecure_clone(),
governance_authority_pda: env.governance_authority_pda,
group_pda: env.group_pda,
registered_program_pda: env.registered_program_pda,
registered_registry_program_pda: env.registered_registry_program_pda,
forester: env.forester.insecure_clone(),
registered_forester_pda: env.registered_forester_pda,
forester_epoch: env.forester_epoch.clone(),
};
let seed = [4u8; 32];
let data = [5u8; 31];
perform_create_pda_with_event(
&mut test_indexer,
&mut rpc,
&env_with_program_owned_state_merkle_tree,
&payer,
seed,
&data,
&ID,
CreatePdaMode::ProgramIsSigner,
)
.await
.unwrap();
assert_created_pda(
&mut test_indexer,
&env_with_program_owned_state_merkle_tree,
&payer,
&seed,
&data,
)
.await;
}
#[allow(clippy::too_many_arguments)]
pub async fn perform_create_pda_failing<R: RpcConnection>(
test_indexer: &mut TestIndexer<R>,
rpc: &mut R,
env: &EnvAccounts,
payer: &Keypair,
seed: [u8; 32],
data: &[u8; 31],
owner_program: &Pubkey,
signer_is_program: CreatePdaMode,
expected_error_code: u32,
) -> Result<(), RpcError> {
let payer_pubkey = payer.pubkey();
let instruction = perform_create_pda(
env,
seed,
test_indexer,
rpc,
data,
payer_pubkey,
owner_program,
signer_is_program,
)
.await;
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer_pubkey),
&[&payer],
rpc.get_latest_blockhash().await.unwrap(),
);
let result = rpc.process_transaction(transaction).await;
assert_rpc_error(result, 0, expected_error_code)
}
#[allow(clippy::too_many_arguments)]
pub async fn perform_create_pda_with_event<R: RpcConnection>(
test_indexer: &mut TestIndexer<R>,
rpc: &mut R,
env: &EnvAccounts,
payer: &Keypair,
seed: [u8; 32],
data: &[u8; 31],
owner_program: &Pubkey,
signer_is_program: CreatePdaMode,
) -> Result<(), RpcError> {
let payer_pubkey = payer.pubkey();
let instruction = perform_create_pda(
env,
seed,
test_indexer,
rpc,
data,
payer_pubkey,
owner_program,
signer_is_program,
)
.await;
let event = rpc
.create_and_send_transaction_with_event(&[instruction], &payer_pubkey, &[payer], None)
.await?
.unwrap();
test_indexer.add_compressed_accounts_with_token_data(&event.0);
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn perform_create_pda<R: RpcConnection>(
env: &EnvAccounts,
seed: [u8; 32],
test_indexer: &mut TestIndexer<R>,
rpc: &mut R,
data: &[u8; 31],
payer_pubkey: Pubkey,
owner_program: &Pubkey,
signer_is_program: CreatePdaMode,
) -> solana_sdk::instruction::Instruction {
let address = derive_address(&env.address_merkle_tree_pubkey, &seed).unwrap();
let rpc_result = test_indexer
.create_proof_for_compressed_accounts(
None,
None,
Some(&[address]),
Some(vec![env.address_merkle_tree_pubkey]),
rpc,
)
.await;
let new_address_params = NewAddressParams {
seed,
address_merkle_tree_pubkey: env.address_merkle_tree_pubkey,
address_queue_pubkey: env.address_merkle_tree_queue_pubkey,
address_merkle_tree_root_index: rpc_result.address_root_indices[0],
};
let create_ix_inputs = CreateCompressedPdaInstructionInputs {
data: *data,
signer: &payer_pubkey,
output_compressed_account_merkle_tree_pubkey: &env.merkle_tree_pubkey,
proof: &rpc_result.proof,
new_address_params,
cpi_context_account: &env.cpi_context_account_pubkey,
owner_program,
signer_is_program: signer_is_program.clone(),
registered_program_pda: &env.registered_program_pda,
};
create_pda_instruction(create_ix_inputs.clone())
}
pub async fn assert_created_pda<R: RpcConnection>(
test_indexer: &mut TestIndexer<R>,
env: &EnvAccounts,
payer: &Keypair,
seed: &[u8; 32],
data: &[u8; 31],
) {
let compressed_escrow_pda = test_indexer
.compressed_accounts
.iter()
.find(|x| x.compressed_account.owner == ID)
.unwrap()
.clone();
let address = derive_address(&env.address_merkle_tree_pubkey, seed).unwrap();
assert_eq!(
compressed_escrow_pda.compressed_account.address.unwrap(),
address
);
assert_eq!(compressed_escrow_pda.compressed_account.owner, ID);
let compressed_escrow_pda_deserialized = compressed_escrow_pda
.compressed_account
.data
.as_ref()
.unwrap();
let compressed_escrow_pda_data =
RegisteredUser::deserialize_reader(&mut &compressed_escrow_pda_deserialized.data[..])
.unwrap();
assert_eq!(compressed_escrow_pda_data.user_pubkey, payer.pubkey());
assert_eq!(compressed_escrow_pda_data.data, *data);
assert_eq!(
compressed_escrow_pda_deserialized.discriminator,
1u64.to_le_bytes(),
);
let truncated_user_pubkey =
hash_to_bn254_field_size_be(&compressed_escrow_pda_data.user_pubkey.to_bytes())
.unwrap()
.0;
assert_eq!(
compressed_escrow_pda_deserialized.data_hash,
Poseidon::hashv(&[truncated_user_pubkey.as_slice(), data.as_slice()]).unwrap(),
);
}
#[allow(clippy::too_many_arguments)]
pub async fn perform_with_input_accounts<R: RpcConnection>(
test_indexer: &mut TestIndexer<R>,
rpc: &mut R,
payer: &Keypair,
fee_payer: Option<&Keypair>,
compressed_account: &CompressedAccountWithMerkleContext,
token_account: Option<TokenDataWithContext>,
expected_error_code: u32,
mode: WithInputAccountsMode,
) -> Result<(), RpcError> {
let payer_pubkey = payer.pubkey();
let hash = compressed_account.hash().unwrap();
let mut hashes = vec![hash];
let mut merkle_tree_pubkeys = vec![compressed_account.merkle_context.merkle_tree_pubkey];
if let Some(token_account) = token_account.as_ref() {
hashes.push(token_account.compressed_account.hash().unwrap());
merkle_tree_pubkeys.push(
token_account
.compressed_account
.merkle_context
.merkle_tree_pubkey,
);
}
let merkle_tree_pubkey = compressed_account.merkle_context.merkle_tree_pubkey;
let nullifier_pubkey = compressed_account.merkle_context.nullifier_queue_pubkey;
let cpi_context = match mode {
WithInputAccountsMode::Freeze
| WithInputAccountsMode::Thaw
| WithInputAccountsMode::Burn
| WithInputAccountsMode::Approve
| WithInputAccountsMode::Revoke
| WithInputAccountsMode::CpiContextMissing
| WithInputAccountsMode::CpiContextAccountMissing
| WithInputAccountsMode::CpiContextInvalidInvokingProgram
| WithInputAccountsMode::CpiContextFeePayerMismatch
| WithInputAccountsMode::CpiContextWriteToNotOwnedAccount => Some(CompressedCpiContext {
cpi_context_account_index: 2,
set_context: true,
first_set_context: true,
}),
WithInputAccountsMode::CpiContextEmpty => Some(CompressedCpiContext {
cpi_context_account_index: 2,
set_context: false,
first_set_context: false,
}),
_ => None,
};
let cpi_context_account_pubkey = test_indexer
.state_merkle_trees
.iter()
.find(|x| x.accounts.merkle_tree == merkle_tree_pubkey)
.unwrap()
.accounts
.cpi_context;
let rpc_result = test_indexer
.create_proof_for_compressed_accounts(
Some(&hashes),
Some(&merkle_tree_pubkeys),
None,
None,
rpc,
)
.await;
let token_transfer_data = match token_account {
Some(token_account) => Some(TokenTransferData {
mint: token_account.token_data.mint,
input_token_data_with_context: InputTokenDataWithContext {
amount: token_account.token_data.amount,
delegate_index: if token_account.token_data.delegate.is_some() {
Some(3)
} else {
None
},
root_index: rpc_result.root_indices[0],
merkle_context: PackedMerkleContext {
leaf_index: token_account.compressed_account.merkle_context.leaf_index,
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
queue_index: None,
},
lamports: if token_account.compressed_account.compressed_account.lamports != 0 {
Some(token_account.compressed_account.compressed_account.lamports)
} else {
None
},
tlv: None,
},
}),
_ => None,
};
let invalid_fee_payer = if let Some(fee_payer) = fee_payer {
fee_payer
} else {
&Keypair::new()
};
let create_ix_inputs = InvalidateNotOwnedCompressedAccountInstructionInputs {
signer: &payer_pubkey,
input_merkle_tree_pubkey: &merkle_tree_pubkey,
input_nullifier_pubkey: &nullifier_pubkey,
cpi_context_account: &cpi_context_account_pubkey,
cpi_context,
proof: &rpc_result.proof,
compressed_account: &PackedCompressedAccountWithMerkleContext {
compressed_account: compressed_account.compressed_account.clone(),
merkle_context: PackedMerkleContext {
leaf_index: compressed_account.merkle_context.leaf_index,
merkle_tree_pubkey_index: 0,
nullifier_queue_pubkey_index: 1,
queue_index: None,
},
root_index: rpc_result.root_indices[0],
read_only: false,
},
token_transfer_data,
invalid_fee_payer: &invalid_fee_payer.pubkey(),
};
let instruction =
create_invalidate_not_owned_account_instruction(create_ix_inputs.clone(), mode);
let result = rpc
.create_and_send_transaction_with_event::<PublicTransactionEvent>(
&[instruction],
&payer_pubkey,
&[payer, invalid_fee_payer],
None,
)
.await;
if expected_error_code == u32::MAX {
let result = result?.unwrap();
test_indexer.add_compressed_accounts_with_token_data(&result.0);
Ok(())
} else {
assert_rpc_error(result, 0, expected_error_code)
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/tests/test_program_owned_trees.rs
|
#![cfg(feature = "test-sbf")]
use account_compression::sdk::create_insert_leaves_instruction;
use account_compression::utils::constants::{CPI_AUTHORITY_PDA_SEED, STATE_NULLIFIER_QUEUE_VALUES};
use account_compression::{
AddressMerkleTreeConfig, AddressQueueConfig, NullifierQueueConfig, QueueAccount,
StateMerkleTreeAccount, StateMerkleTreeConfig,
};
use anchor_lang::{system_program, InstructionData, ToAccountMetas};
use light_compressed_token::mint_sdk::create_mint_to_instruction;
use light_hasher::Poseidon;
use light_program_test::test_env::{
initialize_new_group, register_program_with_registry_program,
setup_test_programs_with_accounts, NOOP_PROGRAM_ID,
};
use light_program_test::test_rpc::ProgramTestRpcConnection;
use light_prover_client::gnark::helpers::{ProverConfig, ProverMode};
use light_registry::account_compression_cpi::sdk::{
create_nullify_instruction, get_registered_program_pda, CreateNullifyInstructionInputs,
};
use light_registry::protocol_config::state::ProtocolConfig;
use light_registry::utils::{
get_cpi_authority_pda, get_forester_epoch_pda_from_authority, get_protocol_config_pda_address,
};
use light_test_utils::spl::create_mint_helper;
use light_test_utils::{
airdrop_lamports, assert_rpc_error, create_account_instruction, get_concurrent_merkle_tree,
FeeConfig, RpcConnection, RpcError, TransactionParams,
};
use light_test_utils::{assert_custom_error_or_program_error, indexer::TestIndexer};
use solana_sdk::instruction::Instruction;
use solana_sdk::signature::Signature;
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::Transaction};
use system_cpi_test::sdk::{
create_initialize_address_merkle_tree_and_queue_instruction,
create_initialize_merkle_tree_instruction,
};
#[tokio::test]
async fn test_program_owned_merkle_tree() {
let (mut rpc, env) = setup_test_programs_with_accounts(Some(vec![(
String::from("system_cpi_test"),
system_cpi_test::ID,
)]))
.await;
let payer = rpc.get_payer().insecure_clone();
let payer_pubkey = payer.pubkey();
let program_owned_merkle_tree_keypair = Keypair::new();
let program_owned_merkle_tree_pubkey = program_owned_merkle_tree_keypair.pubkey();
let program_owned_nullifier_queue_keypair = Keypair::new();
let cpi_context_keypair = Keypair::new();
let mut test_indexer = TestIndexer::<ProgramTestRpcConnection>::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
test_indexer
.add_state_merkle_tree(
&mut rpc,
&program_owned_merkle_tree_keypair,
&program_owned_nullifier_queue_keypair,
&cpi_context_keypair,
Some(light_compressed_token::ID),
None,
)
.await;
let recipient_keypair = Keypair::new();
let mint = create_mint_helper(&mut rpc, &payer).await;
let amount = 10000u64;
let instruction = create_mint_to_instruction(
&payer_pubkey,
&payer_pubkey,
&mint,
&program_owned_merkle_tree_pubkey,
vec![amount; 1],
vec![recipient_keypair.pubkey(); 1],
None,
false,
);
let pre_merkle_tree = get_concurrent_merkle_tree::<
StateMerkleTreeAccount,
ProgramTestRpcConnection,
Poseidon,
26,
>(&mut rpc, program_owned_merkle_tree_pubkey)
.await;
let event = rpc
.create_and_send_transaction_with_event(
&[instruction],
&payer_pubkey,
&[&payer],
Some(TransactionParams {
num_new_addresses: 0,
num_input_compressed_accounts: 0,
num_output_compressed_accounts: 1,
compress: 0,
fee_config: FeeConfig::default(),
}),
)
.await
.unwrap()
.unwrap();
let post_merkle_tree = get_concurrent_merkle_tree::<
StateMerkleTreeAccount,
ProgramTestRpcConnection,
Poseidon,
26,
>(&mut rpc, program_owned_merkle_tree_pubkey)
.await;
test_indexer.add_compressed_accounts_with_token_data(&event.0);
assert_ne!(post_merkle_tree.root(), pre_merkle_tree.root());
assert_eq!(
post_merkle_tree.root(),
test_indexer.state_merkle_trees[1].merkle_tree.root()
);
let invalid_program_owned_merkle_tree_keypair = Keypair::new();
let invalid_program_owned_merkle_tree_pubkey =
invalid_program_owned_merkle_tree_keypair.pubkey();
let invalid_program_owned_nullifier_queue_keypair = Keypair::new();
let cpi_context_keypair = Keypair::new();
test_indexer
.add_state_merkle_tree(
&mut rpc,
&invalid_program_owned_merkle_tree_keypair,
&invalid_program_owned_nullifier_queue_keypair,
&cpi_context_keypair,
Some(Keypair::new().pubkey()),
None,
)
.await;
let recipient_keypair = Keypair::new();
let instruction = create_mint_to_instruction(
&payer_pubkey,
&payer_pubkey,
&mint,
&invalid_program_owned_merkle_tree_pubkey,
vec![amount + 1; 1],
vec![recipient_keypair.pubkey(); 1],
None,
false,
);
let latest_blockhash = rpc.get_latest_blockhash().await.unwrap();
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer_pubkey),
&[&payer],
latest_blockhash,
);
let res = rpc.process_transaction(transaction).await;
assert_custom_error_or_program_error(
res,
light_system_program::errors::SystemProgramError::InvalidMerkleTreeOwner.into(),
)
.unwrap();
}
const CPI_SYSTEM_TEST_PROGRAM_ID_KEYPAIR: [u8; 64] = [
57, 80, 188, 3, 162, 80, 232, 181, 222, 192, 247, 98, 140, 227, 70, 15, 169, 202, 73, 184, 23,
90, 69, 95, 211, 74, 128, 232, 155, 216, 5, 230, 213, 158, 155, 203, 26, 211, 193, 195, 11,
219, 9, 155, 58, 172, 58, 200, 254, 75, 231, 106, 31, 168, 183, 76, 179, 113, 234, 101, 191,
99, 156, 98,
];
/// Test:
/// - Register the test program
/// - failing test registered program signer check
/// 1. FAIL: try to append leaves to the merkle tree from test program with invalid registered program account
/// 2. try to append leaves to the merkle tree from account compression program
/// - register the test program to the correct group
/// 3. SUCCEED: append leaves to the merkle tree from test program
/// - register the token program to the correct group
/// 4. FAIL: try to append leaves to the merkle tree from test program with invalid registered program account
/// 5. FAIL: rollover state Merkle tree with invalid group
/// 6. FAIL: rollover address Merkle tree with invalid group
/// 7. FAIL: update address Merkle tree with invalid group
/// 8. FAIL: nullify leaves with invalid group
/// 9. FAIL: insert into address queue with invalid group
/// 10. FAIL: insert into nullifier queue with invalid group
/// 11. FAIL: create address Merkle tree with invalid group
/// 12. FAIL: create state Merkle tree with invalid group
#[tokio::test]
async fn test_invalid_registered_program() {
let (mut rpc, env) = setup_test_programs_with_accounts(Some(vec![(
String::from("system_cpi_test"),
system_cpi_test::ID,
)]))
.await;
let payer = env.forester.insecure_clone();
airdrop_lamports(&mut rpc, &payer.pubkey(), 100_000_000_000)
.await
.unwrap();
let group_seed_keypair = Keypair::new();
let program_id_keypair = Keypair::from_bytes(&CPI_SYSTEM_TEST_PROGRAM_ID_KEYPAIR).unwrap();
println!("program_id_keypair: {:?}", program_id_keypair.pubkey());
let invalid_group_pda =
initialize_new_group(&group_seed_keypair, &payer, &mut rpc, payer.pubkey()).await;
let invalid_group_registered_program_pda =
register_program(&mut rpc, &payer, &program_id_keypair, &invalid_group_pda)
.await
.unwrap();
let invalid_group_state_merkle_tree = Keypair::new();
let invalid_group_nullifier_queue = Keypair::new();
create_state_merkle_tree_and_queue_account(
&payer,
&mut rpc,
&invalid_group_state_merkle_tree,
&invalid_group_nullifier_queue,
None,
3,
&StateMerkleTreeConfig::default(),
&NullifierQueueConfig::default(),
false,
)
.await
.unwrap();
let invalid_group_address_merkle_tree = Keypair::new();
let invalid_group_address_queue = Keypair::new();
create_address_merkle_tree_and_queue_account(
&payer,
&mut rpc,
&invalid_group_address_merkle_tree,
&invalid_group_address_queue,
None,
&AddressMerkleTreeConfig::default(),
&AddressQueueConfig::default(),
3,
false,
)
.await
.unwrap();
let merkle_tree_pubkey = env.merkle_tree_pubkey;
// invoke account compression program through system cpi test
// 1. the program is registered with a different group than the Merkle tree
{
let derived_address =
Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &system_cpi_test::ID).0;
let accounts = system_cpi_test::accounts::AppendLeavesAccountCompressionProgram {
signer: payer.pubkey(),
registered_program_pda: invalid_group_registered_program_pda,
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_program: account_compression::ID,
cpi_signer: derived_address,
system_program: system_program::ID,
merkle_tree: merkle_tree_pubkey,
queue: merkle_tree_pubkey, // not used in this ix
};
let instruction_data =
system_cpi_test::instruction::AppendLeavesAccountCompressionProgram {};
let instruction = Instruction {
program_id: system_cpi_test::ID,
accounts: [accounts.to_account_metas(Some(true))].concat(),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
// 2. directly invoke account compression program
{
let instruction = create_insert_leaves_instruction(
vec![(0, [1u8; 32])],
payer.pubkey(),
payer.pubkey(),
vec![merkle_tree_pubkey],
);
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
let result = rpc
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
let other_program_id_keypair = Keypair::new();
let token_program_registered_program_pda = register_program_with_registry_program(
&mut rpc,
&env.governance_authority,
&env.group_pda,
&other_program_id_keypair,
)
.await
.unwrap();
// 4. use registered_program_pda of other program
{
let derived_address =
Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &system_cpi_test::ID).0;
let accounts = system_cpi_test::accounts::AppendLeavesAccountCompressionProgram {
signer: payer.pubkey(),
registered_program_pda: token_program_registered_program_pda,
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_program: account_compression::ID,
cpi_signer: derived_address,
system_program: system_program::ID,
merkle_tree: merkle_tree_pubkey,
queue: merkle_tree_pubkey, // not used in this ix
};
let instruction_data =
system_cpi_test::instruction::AppendLeavesAccountCompressionProgram {};
let instruction = Instruction {
program_id: system_cpi_test::ID,
accounts: [accounts.to_account_metas(Some(true))].concat(),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
// 6. rollover state Merkle tree with invalid group
{
let new_merkle_tree_keypair = Keypair::new();
let new_queue_keypair = Keypair::new();
let new_cpi_context_keypair = Keypair::new();
let (cpi_authority, bump) = get_cpi_authority_pda();
let registered_program_pda = get_registered_program_pda(&light_registry::ID);
let registered_forester_pda =
get_forester_epoch_pda_from_authority(&env.forester.pubkey(), 0).0;
let protocol_config_pda = get_protocol_config_pda_address().0;
let instruction_data =
light_registry::instruction::RolloverStateMerkleTreeAndQueue { bump };
let accounts = light_registry::accounts::RolloverStateMerkleTreeAndQueue {
account_compression_program: account_compression::ID,
registered_forester_pda: Some(registered_forester_pda),
cpi_authority,
authority: payer.pubkey(),
registered_program_pda,
new_merkle_tree: new_merkle_tree_keypair.pubkey(),
new_queue: new_queue_keypair.pubkey(),
old_merkle_tree: invalid_group_state_merkle_tree.pubkey(),
old_queue: invalid_group_nullifier_queue.pubkey(),
cpi_context_account: new_cpi_context_keypair.pubkey(),
light_system_program: light_system_program::ID,
protocol_config_pda,
};
let size = QueueAccount::size(STATE_NULLIFIER_QUEUE_VALUES as usize).unwrap();
let create_nullifier_queue_instruction = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(&new_queue_keypair),
);
let size = StateMerkleTreeAccount::size(
account_compression::utils::constants::STATE_MERKLE_TREE_HEIGHT as usize,
account_compression::utils::constants::STATE_MERKLE_TREE_CHANGELOG as usize,
account_compression::utils::constants::STATE_MERKLE_TREE_ROOTS as usize,
account_compression::utils::constants::STATE_MERKLE_TREE_CANOPY_DEPTH as usize,
);
let create_state_merkle_tree_instruction = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(&new_merkle_tree_keypair),
);
let size = ProtocolConfig::default().cpi_context_size as usize;
let create_cpi_context_account_instruction = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&light_system_program::ID,
Some(&new_cpi_context_keypair),
);
let instruction = Instruction {
program_id: light_registry::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(
&[
create_nullifier_queue_instruction,
create_state_merkle_tree_instruction,
create_cpi_context_account_instruction,
instruction,
],
&payer.pubkey(),
&[
&payer,
&new_merkle_tree_keypair,
&new_queue_keypair,
&new_cpi_context_keypair,
],
)
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 3, expected_error_code).unwrap();
}
// 6. rollover address Merkle tree with invalid group
{
let new_merkle_tree_keypair = Keypair::new();
let new_queue_keypair = Keypair::new();
let (cpi_authority, bump) = get_cpi_authority_pda();
let registered_program_pda = get_registered_program_pda(&light_registry::ID);
let instruction_data =
light_registry::instruction::RolloverAddressMerkleTreeAndQueue { bump };
let registered_forester_pda =
get_forester_epoch_pda_from_authority(&env.forester.pubkey(), 0).0;
let accounts = light_registry::accounts::RolloverAddressMerkleTreeAndQueue {
account_compression_program: account_compression::ID,
registered_forester_pda: Some(registered_forester_pda),
cpi_authority,
authority: payer.pubkey(),
registered_program_pda,
new_merkle_tree: new_merkle_tree_keypair.pubkey(),
new_queue: new_queue_keypair.pubkey(),
old_merkle_tree: invalid_group_address_merkle_tree.pubkey(),
old_queue: invalid_group_address_queue.pubkey(),
};
let size = QueueAccount::size(
account_compression::utils::constants::ADDRESS_QUEUE_VALUES as usize,
)
.unwrap();
let create_nullifier_queue_instruction = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(&new_queue_keypair),
);
let size = account_compression::state::AddressMerkleTreeAccount::size(
account_compression::utils::constants::ADDRESS_MERKLE_TREE_HEIGHT as usize,
account_compression::utils::constants::ADDRESS_MERKLE_TREE_CHANGELOG as usize,
account_compression::utils::constants::ADDRESS_MERKLE_TREE_ROOTS as usize,
account_compression::utils::constants::ADDRESS_MERKLE_TREE_CANOPY_DEPTH as usize,
account_compression::utils::constants::ADDRESS_MERKLE_TREE_INDEXED_CHANGELOG as usize,
);
let create_state_merkle_tree_instruction = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(&new_merkle_tree_keypair),
);
let instruction = Instruction {
program_id: light_registry::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(
&[
create_nullifier_queue_instruction,
create_state_merkle_tree_instruction,
instruction,
],
&payer.pubkey(),
&[&payer, &new_merkle_tree_keypair, &new_queue_keypair],
)
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 2, expected_error_code).unwrap();
}
// 7. nullify with invalid group
{
let inputs = CreateNullifyInstructionInputs {
authority: payer.pubkey(),
nullifier_queue: invalid_group_nullifier_queue.pubkey(),
merkle_tree: invalid_group_state_merkle_tree.pubkey(),
change_log_indices: vec![1],
leaves_queue_indices: vec![1u16],
indices: vec![0u64],
proofs: vec![vec![[0u8; 32]; 26]],
derivation: env.forester.pubkey(),
is_metadata_forester: false,
};
let ix = create_nullify_instruction(inputs, 0);
let result = rpc
.create_and_send_transaction(&[ix], &payer.pubkey(), &[&payer])
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
// 8. update address with invalid group
{
let register_program_pda = get_registered_program_pda(&light_registry::ID);
let registered_forester_pda =
get_forester_epoch_pda_from_authority(&env.forester.pubkey(), 0).0;
let (cpi_authority, bump) = get_cpi_authority_pda();
let instruction_data = light_registry::instruction::UpdateAddressMerkleTree {
bump,
changelog_index: 1,
indexed_changelog_index: 1,
value: 1u16,
low_address_index: 1,
low_address_proof: [[0u8; 32]; 16],
low_address_next_index: 1,
low_address_next_value: [0u8; 32],
low_address_value: [0u8; 32],
};
let accounts = light_registry::accounts::UpdateAddressMerkleTree {
authority: payer.pubkey(),
registered_forester_pda: Some(registered_forester_pda),
registered_program_pda: register_program_pda,
queue: invalid_group_address_queue.pubkey(),
merkle_tree: invalid_group_address_merkle_tree.pubkey(),
log_wrapper: NOOP_PROGRAM_ID,
cpi_authority,
account_compression_program: account_compression::ID,
};
let ix = Instruction {
program_id: light_registry::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(&[ix], &payer.pubkey(), &[&payer])
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
// 9. insert into address queue with invalid group
{
let derived_address =
Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &system_cpi_test::ID).0;
let accounts = system_cpi_test::accounts::AppendLeavesAccountCompressionProgram {
signer: payer.pubkey(),
registered_program_pda: token_program_registered_program_pda,
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_program: account_compression::ID,
cpi_signer: derived_address,
system_program: system_program::ID,
merkle_tree: env.address_merkle_tree_pubkey,
queue: env.address_merkle_tree_queue_pubkey,
};
let instruction_data = system_cpi_test::instruction::InsertIntoAddressQueue {};
let instruction = Instruction {
program_id: system_cpi_test::ID,
accounts: [accounts.to_account_metas(Some(true))].concat(),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
// 10. insert into nullifier queue with invalid group
{
let derived_address =
Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &system_cpi_test::ID).0;
let accounts = system_cpi_test::accounts::AppendLeavesAccountCompressionProgram {
signer: payer.pubkey(),
registered_program_pda: token_program_registered_program_pda,
noop_program: Pubkey::new_from_array(
account_compression::utils::constants::NOOP_PUBKEY,
),
account_compression_program: account_compression::ID,
cpi_signer: derived_address,
system_program: system_program::ID,
merkle_tree: env.merkle_tree_pubkey,
queue: env.nullifier_queue_pubkey,
};
let instruction_data = system_cpi_test::instruction::InsertIntoNullifierQueue {};
let instruction = Instruction {
program_id: system_cpi_test::ID,
accounts: [accounts.to_account_metas(Some(true))].concat(),
data: instruction_data.data(),
};
let result = rpc
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 0, expected_error_code).unwrap();
}
// 11. create address Merkle tree with invalid group
{
let invalid_group_state_merkle_tree = Keypair::new();
let invalid_group_nullifier_queue = Keypair::new();
let result = create_state_merkle_tree_and_queue_account(
&payer,
&mut rpc,
&invalid_group_state_merkle_tree,
&invalid_group_nullifier_queue,
None,
3,
&StateMerkleTreeConfig::default(),
&NullifierQueueConfig::default(),
true,
)
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 2, expected_error_code).unwrap();
}
{
let invalid_group_address_merkle_tree = Keypair::new();
let invalid_group_address_queue = Keypair::new();
let result = create_address_merkle_tree_and_queue_account(
&payer,
&mut rpc,
&invalid_group_address_merkle_tree,
&invalid_group_address_queue,
None,
&AddressMerkleTreeConfig::default(),
&AddressQueueConfig::default(),
3,
true,
)
.await;
let expected_error_code =
account_compression::errors::AccountCompressionErrorCode::InvalidAuthority.into();
assert_rpc_error(result, 2, expected_error_code).unwrap();
}
}
pub async fn register_program(
rpc: &mut ProgramTestRpcConnection,
authority: &Keypair,
program_id_keypair: &Keypair,
group_account: &Pubkey,
) -> Result<Pubkey, RpcError> {
let registered_program_pda = Pubkey::find_program_address(
&[program_id_keypair.pubkey().to_bytes().as_slice()],
&account_compression::ID,
)
.0;
let accounts = account_compression::accounts::RegisterProgramToGroup {
authority: authority.pubkey(),
program_to_be_registered: program_id_keypair.pubkey(),
system_program: system_program::ID,
registered_program_pda,
group_authority_pda: *group_account,
};
let instruction = Instruction {
program_id: account_compression::ID,
accounts: accounts.to_account_metas(Some(true)),
data: account_compression::instruction::RegisterProgramToGroup {}.data(),
};
rpc.create_and_send_transaction(
&[instruction],
&authority.pubkey(),
&[authority, program_id_keypair],
)
.await?;
Ok(registered_program_pda)
}
#[allow(clippy::too_many_arguments)]
pub async fn create_state_merkle_tree_and_queue_account<R: RpcConnection>(
payer: &Keypair,
rpc: &mut R,
merkle_tree_keypair: &Keypair,
nullifier_queue_keypair: &Keypair,
program_owner: Option<Pubkey>,
index: u64,
merkle_tree_config: &StateMerkleTreeConfig,
queue_config: &NullifierQueueConfig,
invalid_group: bool,
) -> Result<Signature, RpcError> {
let size = StateMerkleTreeAccount::size(
merkle_tree_config.height as usize,
merkle_tree_config.changelog_size as usize,
merkle_tree_config.roots_size as usize,
merkle_tree_config.canopy_depth as usize,
);
let merkle_tree_account_create_ix = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(merkle_tree_keypair),
);
let size = QueueAccount::size(queue_config.capacity as usize).unwrap();
let nullifier_queue_account_create_ix = create_account_instruction(
&payer.pubkey(),
size,
rpc.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(nullifier_queue_keypair),
);
let instruction = create_initialize_merkle_tree_instruction(
payer.pubkey(),
merkle_tree_keypair.pubkey(),
nullifier_queue_keypair.pubkey(),
merkle_tree_config.clone(),
queue_config.clone(),
program_owner,
index,
0, // TODO: replace with CPI_CONTEXT_ACCOUNT_RENT
invalid_group,
);
let transaction = Transaction::new_signed_with_payer(
&[
merkle_tree_account_create_ix,
nullifier_queue_account_create_ix,
instruction,
],
Some(&payer.pubkey()),
&vec![payer, merkle_tree_keypair, nullifier_queue_keypair],
rpc.get_latest_blockhash().await.unwrap(),
);
rpc.process_transaction(transaction.clone()).await
}
#[allow(clippy::too_many_arguments)]
#[inline(never)]
pub async fn create_address_merkle_tree_and_queue_account<R: RpcConnection>(
payer: &Keypair,
context: &mut R,
address_merkle_tree_keypair: &Keypair,
address_queue_keypair: &Keypair,
program_owner: Option<Pubkey>,
merkle_tree_config: &AddressMerkleTreeConfig,
queue_config: &AddressQueueConfig,
index: u64,
invalid_group: bool,
) -> Result<Signature, RpcError> {
let size = QueueAccount::size(queue_config.capacity as usize).unwrap();
let account_create_ix = create_account_instruction(
&payer.pubkey(),
size,
context
.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(address_queue_keypair),
);
let size = account_compression::state::AddressMerkleTreeAccount::size(
merkle_tree_config.height as usize,
merkle_tree_config.changelog_size as usize,
merkle_tree_config.roots_size as usize,
merkle_tree_config.canopy_depth as usize,
merkle_tree_config.address_changelog_size as usize,
);
let mt_account_create_ix = create_account_instruction(
&payer.pubkey(),
size,
context
.get_minimum_balance_for_rent_exemption(size)
.await
.unwrap(),
&account_compression::ID,
Some(address_merkle_tree_keypair),
);
let instruction = create_initialize_address_merkle_tree_and_queue_instruction(
index,
payer.pubkey(),
program_owner,
address_merkle_tree_keypair.pubkey(),
address_queue_keypair.pubkey(),
merkle_tree_config.clone(),
queue_config.clone(),
invalid_group,
);
let transaction = Transaction::new_signed_with_payer(
&[account_create_ix, mt_account_create_ix, instruction],
Some(&payer.pubkey()),
&vec![&payer, &address_queue_keypair, &address_merkle_tree_keypair],
context.get_latest_blockhash().await.unwrap(),
);
context.process_transaction(transaction.clone()).await
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/src/invalidate_not_owned_account.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use light_compressed_token::{
delegation::{CompressedTokenInstructionDataApprove, CompressedTokenInstructionDataRevoke},
freeze::{CompressedTokenInstructionDataFreeze, CompressedTokenInstructionDataThaw},
process_transfer::{
CompressedTokenInstructionDataTransfer, InputTokenDataWithContext,
PackedTokenTransferOutputData,
},
CompressedTokenInstructionDataBurn,
};
use light_system_program::{
invoke::processor::CompressedProof,
program::LightSystemProgram,
sdk::{
compressed_account::{CompressedAccount, PackedCompressedAccountWithMerkleContext},
CompressedCpiContext,
},
InstructionDataInvokeCpi, OutputCompressedAccountWithPackedContext,
};
use crate::ID;
#[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone)]
pub enum WithInputAccountsMode {
NotOwnedCompressedAccount,
CpiContextMissing,
CpiContextAccountMissing,
CpiContextFeePayerMismatch,
CpiContextEmpty,
CpiContextInvalidInvokingProgram,
CpiContextWriteAccessCheckFailed,
CpiContextWriteToNotOwnedAccount,
Approve,
Revoke,
Freeze,
Thaw,
Burn,
}
// TODO: Functional tests with cpi context:
// - ability to store multiple accounts in cpi context account and combine them successfully (can check with multiple token program invocations)
pub fn process_with_input_accounts<'info>(
ctx: Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
compressed_account: PackedCompressedAccountWithMerkleContext,
proof: Option<CompressedProof>,
bump: u8,
mode: WithInputAccountsMode,
cpi_context: Option<CompressedCpiContext>,
token_transfer_data: Option<TokenTransferData>,
) -> Result<()> {
match mode {
WithInputAccountsMode::NotOwnedCompressedAccount => {
process_invalidate_not_owned_compressed_account(
&ctx,
compressed_account,
proof,
bump,
mode,
cpi_context,
)
}
WithInputAccountsMode::CpiContextMissing
| WithInputAccountsMode::CpiContextAccountMissing
| WithInputAccountsMode::CpiContextEmpty
| WithInputAccountsMode::CpiContextInvalidInvokingProgram
| WithInputAccountsMode::CpiContextWriteToNotOwnedAccount => {
process_invalidate_not_owned_compressed_account(
&ctx,
compressed_account,
proof,
bump,
mode,
cpi_context,
)
}
WithInputAccountsMode::CpiContextFeePayerMismatch
| WithInputAccountsMode::Burn
| WithInputAccountsMode::Freeze
| WithInputAccountsMode::Revoke
| WithInputAccountsMode::Thaw
| WithInputAccountsMode::Approve => cpi_context_tx(
&ctx,
compressed_account,
proof.unwrap(),
bump,
token_transfer_data.unwrap(),
mode,
cpi_context.unwrap(),
),
_ => panic!("Invalid mode"),
}
}
/// create compressed pda data
/// transfer tokens
/// execute complete transaction
pub fn process_invalidate_not_owned_compressed_account<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
compressed_account: PackedCompressedAccountWithMerkleContext,
proof: Option<CompressedProof>,
bump: u8,
mode: WithInputAccountsMode,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
let cpi_context_account = cpi_context.map(|cpi_context| {
ctx.remaining_accounts
.get(cpi_context.cpi_context_account_index as usize)
.unwrap()
.to_account_info()
});
let cpi_context = match mode {
WithInputAccountsMode::CpiContextMissing => None,
WithInputAccountsMode::CpiContextEmpty
| WithInputAccountsMode::CpiContextFeePayerMismatch => Some(CompressedCpiContext {
cpi_context_account_index: cpi_context.unwrap().cpi_context_account_index,
set_context: false,
first_set_context: false,
}),
_ => cpi_context,
};
let cpi_context_account = match mode {
WithInputAccountsMode::CpiContextAccountMissing => None,
_ => cpi_context_account,
};
let output_compressed_accounts = match mode {
WithInputAccountsMode::CpiContextWriteToNotOwnedAccount => {
vec![OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
data: compressed_account.compressed_account.data.clone(),
owner: light_compressed_token::ID,
lamports: 0,
address: compressed_account.compressed_account.address,
},
merkle_tree_index: 0,
}]
}
_ => Vec::new(),
};
let invoking_program = match mode {
WithInputAccountsMode::CpiContextInvalidInvokingProgram => {
ctx.accounts.signer.to_account_info()
}
_ => ctx.accounts.self_program.to_account_info(),
};
let inputs_struct = InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context: vec![compressed_account],
output_compressed_accounts,
proof,
new_address_params: Vec::new(),
compress_or_decompress_lamports: None,
is_compress: false,
cpi_context,
};
let mut inputs = Vec::new();
InstructionDataInvokeCpi::serialize(&inputs_struct, &mut inputs).unwrap();
let seeds: [&[u8]; 2] = [CPI_AUTHORITY_PDA_SEED, &[bump]];
let cpi_accounts = light_system_program::cpi::accounts::InvokeCpiInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.cpi_signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
invoking_program,
sol_pool_pda: None,
decompression_recipient: None,
system_program: ctx.accounts.system_program.to_account_info(),
cpi_context_account,
};
let signer_seeds: [&[&[u8]]; 1] = [&seeds[..]];
let mut cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.light_system_program.to_account_info(),
cpi_accounts,
&signer_seeds,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
light_system_program::cpi::invoke_cpi(cpi_ctx, inputs)?;
Ok(())
}
#[derive(Accounts)]
pub struct InvalidateNotOwnedCompressedAccount<'info> {
#[account(mut)]
pub signer: Signer<'info>,
pub light_system_program: Program<'info, LightSystemProgram>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK:
pub account_compression_authority: AccountInfo<'info>,
/// CHECK:
pub compressed_token_cpi_authority_pda: AccountInfo<'info>,
/// CHECK:
pub registered_program_pda: AccountInfo<'info>,
/// CHECK:
pub noop_program: AccountInfo<'info>,
pub self_program: Program<'info, crate::program::SystemCpiTest>,
/// CHECK:
pub cpi_signer: AccountInfo<'info>,
pub system_program: Program<'info, System>,
pub compressed_token_program:
Program<'info, light_compressed_token::program::LightCompressedToken>,
#[account(mut)]
pub invalid_fee_payer: Signer<'info>,
/// CHECK:
#[account(mut)]
pub mint: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
pub token_pool_account: AccountInfo<'info>,
/// CHECK:
pub token_program: AccountInfo<'info>,
}
#[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone)]
pub struct TokenTransferData {
pub mint: Pubkey,
pub input_token_data_with_context: InputTokenDataWithContext,
}
#[inline(never)]
pub fn cpi_context_tx<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
compressed_account: PackedCompressedAccountWithMerkleContext,
proof: CompressedProof,
bump: u8,
token_transfer_data: TokenTransferData,
mode: WithInputAccountsMode,
mut cpi_context: CompressedCpiContext,
) -> Result<()> {
match mode {
WithInputAccountsMode::CpiContextFeePayerMismatch => cpi_compressed_token_transfer(
ctx,
proof.clone(),
token_transfer_data,
mode.clone(),
Some(cpi_context),
)?,
WithInputAccountsMode::Approve => cpi_compressed_token_approve_revoke(
ctx,
proof.clone(),
token_transfer_data,
mode.clone(),
Some(cpi_context),
)?,
WithInputAccountsMode::Revoke => cpi_compressed_token_approve_revoke(
ctx,
proof.clone(),
token_transfer_data,
mode.clone(),
Some(cpi_context),
)?,
WithInputAccountsMode::Freeze | WithInputAccountsMode::Thaw => {
cpi_compressed_token_freeze_or_thaw(
ctx,
proof.clone(),
token_transfer_data,
mode.clone(),
Some(cpi_context),
)?
}
WithInputAccountsMode::Burn => {
cpi_compressed_token_burn(ctx, proof.clone(), token_transfer_data, Some(cpi_context))?
}
_ => panic!("Invalid mode"),
}
match mode {
WithInputAccountsMode::CpiContextFeePayerMismatch
| WithInputAccountsMode::Burn
| WithInputAccountsMode::Freeze
| WithInputAccountsMode::Revoke
| WithInputAccountsMode::Thaw
| WithInputAccountsMode::Approve => {
cpi_context.set_context = false;
cpi_context.first_set_context = false;
}
_ => {}
}
write_into_cpi_account(
ctx,
compressed_account,
Some(proof),
bump,
Some(cpi_context),
)
}
#[inline(never)]
pub fn cpi_compressed_token_transfer<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
proof: CompressedProof,
token_transfer_data: TokenTransferData,
mode: WithInputAccountsMode,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
let fee_payer = match mode {
WithInputAccountsMode::CpiContextFeePayerMismatch => {
// This does not fail because the cpi context is initialized with this fee payer
ctx.accounts.invalid_fee_payer.to_account_info()
}
_ => ctx.accounts.signer.to_account_info(),
};
msg!("cpi_context: {:?}", cpi_context);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize].key()
);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize]
);
let mint = token_transfer_data.mint;
let input_token_data_with_context = token_transfer_data.input_token_data_with_context;
let output_token = PackedTokenTransferOutputData {
amount: input_token_data_with_context.amount,
owner: crate::ID,
lamports: None,
tlv: None,
merkle_tree_index: input_token_data_with_context
.merkle_context
.merkle_tree_pubkey_index,
};
let inputs_struct = CompressedTokenInstructionDataTransfer {
proof: Some(proof),
mint,
delegated_transfer: None,
input_token_data_with_context: vec![input_token_data_with_context],
output_compressed_accounts: vec![output_token],
is_compress: false,
compress_or_decompress_amount: None,
cpi_context,
lamports_change_account_merkle_tree_index: None,
};
let mut inputs = Vec::new();
CompressedTokenInstructionDataTransfer::serialize(&inputs_struct, &mut inputs).unwrap();
let cpi_accounts = light_compressed_token::cpi::accounts::TransferInstruction {
fee_payer,
authority: ctx.accounts.signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
self_program: ctx.accounts.compressed_token_program.to_account_info(),
cpi_authority_pda: ctx
.accounts
.compressed_token_cpi_authority_pda
.to_account_info(),
light_system_program: ctx.accounts.light_system_program.to_account_info(),
token_pool_pda: None,
compress_or_decompress_token_account: None,
token_program: None,
system_program: ctx.accounts.system_program.to_account_info(),
};
let mut cpi_ctx = CpiContext::new(
ctx.accounts.compressed_token_program.to_account_info(),
cpi_accounts,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
light_compressed_token::cpi::transfer(cpi_ctx, inputs)?;
Ok(())
}
#[inline(never)]
pub fn cpi_compressed_token_approve_revoke<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
proof: CompressedProof,
token_transfer_data: TokenTransferData,
mode: WithInputAccountsMode,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
msg!("cpi_context: {:?}", cpi_context);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize].key()
);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize]
);
let mint = token_transfer_data.mint;
let input_token_data_with_context = token_transfer_data.input_token_data_with_context;
let merkle_tree_index = input_token_data_with_context
.merkle_context
.merkle_tree_pubkey_index;
let mut inputs = Vec::new();
match mode {
WithInputAccountsMode::Approve => {
let inputs_struct = CompressedTokenInstructionDataApprove {
proof,
mint,
delegated_amount: input_token_data_with_context.amount,
input_token_data_with_context: vec![input_token_data_with_context],
delegate: ctx.accounts.invalid_fee_payer.key(),
delegate_lamports: None,
change_account_merkle_tree_index: merkle_tree_index,
delegate_merkle_tree_index: merkle_tree_index,
cpi_context,
};
msg!("cpi test program calling approve");
CompressedTokenInstructionDataApprove::serialize(&inputs_struct, &mut inputs).unwrap();
}
WithInputAccountsMode::Revoke => {
let inputs_struct = CompressedTokenInstructionDataRevoke {
proof,
mint,
input_token_data_with_context: vec![input_token_data_with_context],
output_account_merkle_tree_index: merkle_tree_index,
cpi_context,
};
msg!("cpi test program calling revoke");
CompressedTokenInstructionDataRevoke::serialize(&inputs_struct, &mut inputs).unwrap();
}
_ => panic!("Invalid mode"),
}
let cpi_accounts = light_compressed_token::cpi::accounts::GenericInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
self_program: ctx.accounts.compressed_token_program.to_account_info(),
cpi_authority_pda: ctx
.accounts
.compressed_token_cpi_authority_pda
.to_account_info(),
light_system_program: ctx.accounts.light_system_program.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
};
let mut cpi_ctx = CpiContext::new(
ctx.accounts.compressed_token_program.to_account_info(),
cpi_accounts,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
match mode {
WithInputAccountsMode::Approve => {
light_compressed_token::cpi::approve(cpi_ctx, inputs)?;
}
WithInputAccountsMode::Revoke => {
light_compressed_token::cpi::revoke(cpi_ctx, inputs)?;
}
_ => panic!("Invalid mode"),
}
Ok(())
}
#[inline(never)]
pub fn cpi_compressed_token_burn<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
proof: CompressedProof,
token_transfer_data: TokenTransferData,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
msg!("cpi_context: {:?}", cpi_context);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize].key()
);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize]
);
let input_token_data_with_context = token_transfer_data.input_token_data_with_context;
let merkle_tree_index = input_token_data_with_context
.merkle_context
.merkle_tree_pubkey_index;
let mut inputs = Vec::new();
let inputs_struct = CompressedTokenInstructionDataBurn {
proof,
delegated_transfer: None,
input_token_data_with_context: vec![input_token_data_with_context.clone()],
burn_amount: input_token_data_with_context.amount - 1,
change_account_merkle_tree_index: merkle_tree_index,
cpi_context,
};
CompressedTokenInstructionDataBurn::serialize(&inputs_struct, &mut inputs).unwrap();
let cpi_accounts = light_compressed_token::cpi::accounts::BurnInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
self_program: ctx.accounts.compressed_token_program.to_account_info(),
cpi_authority_pda: ctx
.accounts
.compressed_token_cpi_authority_pda
.to_account_info(),
light_system_program: ctx.accounts.light_system_program.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
token_pool_pda: ctx.accounts.token_pool_account.to_account_info(),
token_program: ctx.accounts.token_program.to_account_info(),
mint: ctx.accounts.mint.to_account_info(),
};
let mut cpi_ctx = CpiContext::new(
ctx.accounts.compressed_token_program.to_account_info(),
cpi_accounts,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
light_compressed_token::cpi::burn(cpi_ctx, inputs)?;
Ok(())
}
#[inline(never)]
pub fn cpi_compressed_token_freeze_or_thaw<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
proof: CompressedProof,
token_transfer_data: TokenTransferData,
mode: WithInputAccountsMode,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
msg!("cpi_context: {:?}", cpi_context);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize].key()
);
msg!(
"cpi context account: {:?}",
ctx.remaining_accounts[cpi_context.unwrap().cpi_context_account_index as usize]
);
let input_token_data_with_context = token_transfer_data.input_token_data_with_context;
let merkle_tree_index = input_token_data_with_context
.merkle_context
.merkle_tree_pubkey_index;
let mut inputs = Vec::new();
match mode {
WithInputAccountsMode::Freeze => {
let inputs_struct = CompressedTokenInstructionDataFreeze {
proof,
input_token_data_with_context: vec![input_token_data_with_context],
owner: ctx.accounts.signer.key(),
cpi_context,
outputs_merkle_tree_index: merkle_tree_index,
};
CompressedTokenInstructionDataFreeze::serialize(&inputs_struct, &mut inputs).unwrap();
}
WithInputAccountsMode::Thaw => {
let inputs_struct = CompressedTokenInstructionDataThaw {
proof,
input_token_data_with_context: vec![input_token_data_with_context],
outputs_merkle_tree_index: merkle_tree_index,
cpi_context,
owner: ctx.accounts.signer.key(),
};
CompressedTokenInstructionDataThaw::serialize(&inputs_struct, &mut inputs).unwrap();
}
_ => panic!("Invalid mode"),
}
let cpi_accounts = light_compressed_token::cpi::accounts::FreezeInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
self_program: ctx.accounts.compressed_token_program.to_account_info(),
cpi_authority_pda: ctx
.accounts
.compressed_token_cpi_authority_pda
.to_account_info(),
light_system_program: ctx.accounts.light_system_program.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
mint: ctx.accounts.mint.to_account_info(),
};
let mut cpi_ctx = CpiContext::new(
ctx.accounts.compressed_token_program.to_account_info(),
cpi_accounts,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
match mode {
WithInputAccountsMode::Freeze => {
light_compressed_token::cpi::freeze(cpi_ctx, inputs)?;
}
WithInputAccountsMode::Thaw => {
light_compressed_token::cpi::thaw(cpi_ctx, inputs)?;
}
_ => panic!("Invalid mode"),
}
Ok(())
}
fn write_into_cpi_account<'info>(
ctx: &Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
compressed_account: PackedCompressedAccountWithMerkleContext,
proof: Option<CompressedProof>,
bump: u8,
// compressed_pda: OutputCompressedAccountWithPackedContext,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
let compressed_pda = OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
data: compressed_account.compressed_account.data.clone(),
owner: ID,
lamports: 0,
address: compressed_account.compressed_account.address,
},
merkle_tree_index: 0,
};
let seeds: [&[u8]; 2] = [CPI_AUTHORITY_PDA_SEED, &[bump]];
let inputs_struct = InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context: vec![compressed_account],
output_compressed_accounts: vec![compressed_pda],
proof,
new_address_params: Vec::new(),
compress_or_decompress_lamports: None,
is_compress: false,
cpi_context,
};
let mut inputs = Vec::new();
InstructionDataInvokeCpi::serialize(&inputs_struct, &mut inputs).unwrap();
let cpi_context_account = cpi_context.map(|cpi_context| {
ctx.remaining_accounts
.get(cpi_context.cpi_context_account_index as usize)
.unwrap()
.to_account_info()
});
let cpi_accounts = light_system_program::cpi::accounts::InvokeCpiInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.cpi_signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
invoking_program: ctx.accounts.self_program.to_account_info(),
sol_pool_pda: None,
decompression_recipient: None,
system_program: ctx.accounts.system_program.to_account_info(),
cpi_context_account,
};
let signer_seeds: [&[&[u8]]; 1] = [&seeds[..]];
let mut cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.light_system_program.to_account_info(),
cpi_accounts,
&signer_seeds,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
light_system_program::cpi::invoke_cpi(cpi_ctx, inputs)?;
Ok(())
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/src/sdk.rs
|
#![cfg(not(target_os = "solana"))]
use std::collections::HashMap;
use account_compression::{
utils::constants::CPI_AUTHORITY_PDA_SEED, AddressMerkleTreeConfig, AddressQueueConfig,
NullifierQueueConfig, StateMerkleTreeConfig,
};
use anchor_lang::{InstructionData, ToAccountMetas};
use light_compressed_token::{
get_token_pool_pda, process_transfer::transfer_sdk::to_account_metas,
};
use light_system_program::{
invoke::processor::CompressedProof,
sdk::{
address::pack_new_address_params,
compressed_account::PackedCompressedAccountWithMerkleContext,
},
utils::get_registered_program_pda,
NewAddressParams,
};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
use crate::CreatePdaMode;
#[derive(Debug, Clone)]
pub struct CreateCompressedPdaInstructionInputs<'a> {
pub data: [u8; 31],
pub signer: &'a Pubkey,
pub output_compressed_account_merkle_tree_pubkey: &'a Pubkey,
pub proof: &'a CompressedProof,
pub new_address_params: NewAddressParams,
pub cpi_context_account: &'a Pubkey,
pub owner_program: &'a Pubkey,
pub signer_is_program: CreatePdaMode,
pub registered_program_pda: &'a Pubkey,
}
pub fn create_pda_instruction(input_params: CreateCompressedPdaInstructionInputs) -> Instruction {
let (cpi_signer, bump) = Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &crate::id());
let mut remaining_accounts = HashMap::new();
remaining_accounts.insert(
*input_params.output_compressed_account_merkle_tree_pubkey,
0,
);
let new_address_params =
pack_new_address_params(&[input_params.new_address_params], &mut remaining_accounts);
let instruction_data = crate::instruction::CreateCompressedPda {
data: input_params.data,
proof: Some(input_params.proof.clone()),
new_address_parameters: new_address_params[0],
owner_program: *input_params.owner_program,
bump,
signer_is_program: input_params.signer_is_program,
cpi_context: None,
};
let compressed_token_cpi_authority_pda = get_cpi_authority_pda().0;
let account_compression_authority =
light_system_program::utils::get_cpi_authority_pda(&light_system_program::ID);
let accounts = crate::accounts::CreateCompressedPda {
signer: *input_params.signer,
noop_program: Pubkey::new_from_array(account_compression::utils::constants::NOOP_PUBKEY),
light_system_program: light_system_program::ID,
account_compression_program: account_compression::ID,
registered_program_pda: *input_params.registered_program_pda,
compressed_token_cpi_authority_pda,
account_compression_authority,
self_program: crate::ID,
cpi_signer,
system_program: solana_sdk::system_program::id(),
};
let remaining_accounts = to_account_metas(remaining_accounts);
Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
}
}
#[derive(Debug, Clone)]
pub struct InvalidateNotOwnedCompressedAccountInstructionInputs<'a> {
pub signer: &'a Pubkey,
pub proof: &'a CompressedProof,
pub input_merkle_tree_pubkey: &'a Pubkey,
pub input_nullifier_pubkey: &'a Pubkey,
pub cpi_context_account: &'a Pubkey,
pub compressed_account: &'a PackedCompressedAccountWithMerkleContext,
pub token_transfer_data: Option<crate::TokenTransferData>,
pub cpi_context: Option<crate::CompressedCpiContext>,
pub invalid_fee_payer: &'a Pubkey,
}
pub fn create_invalidate_not_owned_account_instruction(
input_params: InvalidateNotOwnedCompressedAccountInstructionInputs,
mode: crate::WithInputAccountsMode,
) -> Instruction {
let (cpi_signer, bump) = Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &crate::id());
let cpi_context = input_params.cpi_context;
let mut remaining_accounts = HashMap::new();
remaining_accounts.insert(*input_params.input_merkle_tree_pubkey, 0);
remaining_accounts.insert(*input_params.input_nullifier_pubkey, 1);
remaining_accounts.insert(*input_params.cpi_context_account, 2);
remaining_accounts.insert(*input_params.invalid_fee_payer, 3);
let instruction_data = crate::instruction::WithInputAccounts {
proof: Some(input_params.proof.clone()),
compressed_account: input_params.compressed_account.clone(),
bump,
mode,
cpi_context,
token_transfer_data: input_params.token_transfer_data.clone(),
};
let registered_program_pda = Pubkey::find_program_address(
&[light_system_program::ID.to_bytes().as_slice()],
&account_compression::ID,
)
.0;
let compressed_token_cpi_authority_pda =
light_compressed_token::process_transfer::get_cpi_authority_pda().0;
let account_compression_authority =
light_system_program::utils::get_cpi_authority_pda(&light_system_program::ID);
let mint = match input_params.token_transfer_data.as_ref() {
Some(data) => data.mint,
None => Pubkey::new_unique(),
};
let token_pool_account = get_token_pool_pda(&mint);
let accounts = crate::accounts::InvalidateNotOwnedCompressedAccount {
signer: *input_params.signer,
noop_program: Pubkey::new_from_array(account_compression::utils::constants::NOOP_PUBKEY),
light_system_program: light_system_program::ID,
account_compression_program: account_compression::ID,
registered_program_pda,
compressed_token_cpi_authority_pda,
account_compression_authority,
self_program: crate::ID,
cpi_signer,
system_program: solana_sdk::system_program::id(),
compressed_token_program: light_compressed_token::ID,
invalid_fee_payer: *input_params.invalid_fee_payer,
token_pool_account,
mint,
token_program: anchor_spl::token::ID,
};
let remaining_accounts = to_account_metas(remaining_accounts);
Instruction {
program_id: crate::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
}
}
pub fn get_cpi_authority_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &crate::ID)
}
pub fn create_initialize_address_merkle_tree_and_queue_instruction(
index: u64,
payer: Pubkey,
program_owner: Option<Pubkey>,
merkle_tree_pubkey: Pubkey,
queue_pubkey: Pubkey,
address_merkle_tree_config: AddressMerkleTreeConfig,
address_queue_config: AddressQueueConfig,
invalid_group: bool,
) -> Instruction {
let register_program_pda = if invalid_group {
get_registered_program_pda(&light_registry::ID)
} else {
get_registered_program_pda(&crate::ID)
};
let (cpi_authority, bump) = crate::sdk::get_cpi_authority_pda();
let instruction_data = crate::instruction::InitializeAddressMerkleTree {
bump,
index,
program_owner,
merkle_tree_config: address_merkle_tree_config,
queue_config: address_queue_config,
};
let accounts = crate::accounts::InitializeAddressMerkleTreeAndQueue {
authority: payer,
registered_program_pda: register_program_pda,
merkle_tree: merkle_tree_pubkey,
queue: queue_pubkey,
cpi_authority,
account_compression_program: account_compression::ID,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
pub fn create_initialize_merkle_tree_instruction(
payer: Pubkey,
merkle_tree_pubkey: Pubkey,
nullifier_queue_pubkey: Pubkey,
state_merkle_tree_config: StateMerkleTreeConfig,
nullifier_queue_config: NullifierQueueConfig,
program_owner: Option<Pubkey>,
index: u64,
additional_bytes: u64,
invalid_group: bool,
) -> Instruction {
let register_program_pda = if invalid_group {
get_registered_program_pda(&light_registry::ID)
} else {
get_registered_program_pda(&crate::ID)
};
let (cpi_authority, bump) = crate::sdk::get_cpi_authority_pda();
let instruction_data = crate::instruction::InitializeStateMerkleTree {
bump,
index,
program_owner,
merkle_tree_config: state_merkle_tree_config,
queue_config: nullifier_queue_config,
additional_bytes,
};
let accounts = crate::accounts::InitializeAddressMerkleTreeAndQueue {
authority: payer,
registered_program_pda: register_program_pda,
merkle_tree: merkle_tree_pubkey,
queue: nullifier_queue_pubkey,
cpi_authority,
account_compression_program: account_compression::ID,
};
Instruction {
program_id: crate::ID,
accounts: accounts.to_account_metas(Some(true)),
data: instruction_data.data(),
}
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/src/lib.rs
|
#![allow(clippy::too_many_arguments)]
use account_compression::program::AccountCompression;
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED;
use anchor_lang::prelude::*;
use anchor_lang::solana_program::pubkey::Pubkey;
use light_system_program::invoke::processor::CompressedProof;
pub mod create_pda;
pub use create_pda::*;
pub mod sdk;
use light_system_program::NewAddressParamsPacked;
pub mod invalidate_not_owned_account;
use account_compression::{
AddressMerkleTreeConfig, AddressQueueConfig, NullifierQueueConfig, StateMerkleTreeConfig,
};
pub use invalidate_not_owned_account::*;
use light_system_program::sdk::compressed_account::PackedCompressedAccountWithMerkleContext;
use light_system_program::sdk::CompressedCpiContext;
declare_id!("FNt7byTHev1k5x2cXZLBr8TdWiC3zoP5vcnZR4P682Uy");
#[program]
pub mod system_cpi_test {
use super::*;
pub fn create_compressed_pda<'info>(
ctx: Context<'_, '_, '_, 'info, CreateCompressedPda<'info>>,
data: [u8; 31],
proof: Option<CompressedProof>,
new_address_parameters: NewAddressParamsPacked,
owner_program: Pubkey,
signer_is_program: CreatePdaMode,
bump: u8,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
process_create_pda(
ctx,
data,
proof,
new_address_parameters,
owner_program,
cpi_context,
signer_is_program,
bump,
)
}
pub fn with_input_accounts<'info>(
ctx: Context<'_, '_, '_, 'info, InvalidateNotOwnedCompressedAccount<'info>>,
compressed_account: PackedCompressedAccountWithMerkleContext,
proof: Option<CompressedProof>,
bump: u8,
mode: WithInputAccountsMode,
cpi_context: Option<CompressedCpiContext>,
token_transfer_data: Option<TokenTransferData>,
) -> Result<()> {
process_with_input_accounts(
ctx,
compressed_account,
proof,
bump,
mode,
cpi_context,
token_transfer_data,
)
}
pub fn append_leaves_account_compression_program<'info>(
ctx: Context<'_, '_, '_, 'info, AppendLeavesAccountCompressionProgram<'info>>,
) -> Result<()> {
let (_, bump) = Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &ID);
let accounts = account_compression::cpi::accounts::AppendLeaves {
authority: ctx.accounts.cpi_signer.to_account_info(),
fee_payer: ctx.accounts.signer.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
system_program: ctx.accounts.system_program.to_account_info(),
};
let bump = &[bump];
let seeds = [&[CPI_AUTHORITY_PDA_SEED, bump][..]];
let mut cpi_context = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
&seeds,
);
cpi_context.remaining_accounts = vec![ctx.accounts.merkle_tree.to_account_info()];
account_compression::cpi::append_leaves_to_merkle_trees(cpi_context, vec![(0, [1u8; 32])])?;
Ok(())
}
pub fn insert_into_address_queue<'info>(
ctx: Context<'_, '_, '_, 'info, AppendLeavesAccountCompressionProgram<'info>>,
) -> Result<()> {
let (_, bump) = Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &ID);
let accounts = account_compression::cpi::accounts::InsertIntoQueues {
authority: ctx.accounts.cpi_signer.to_account_info(),
fee_payer: ctx.accounts.signer.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
system_program: ctx.accounts.system_program.to_account_info(),
};
let bump = &[bump];
let seeds = [&[CPI_AUTHORITY_PDA_SEED, bump][..]];
let mut cpi_context = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
&seeds,
);
cpi_context.remaining_accounts = vec![
ctx.accounts.queue.to_account_info(),
ctx.accounts.merkle_tree.to_account_info(),
];
account_compression::cpi::insert_addresses(cpi_context, vec![[1u8; 32]])?;
Ok(())
}
pub fn insert_into_nullifier_queue<'info>(
ctx: Context<'_, '_, '_, 'info, AppendLeavesAccountCompressionProgram<'info>>,
) -> Result<()> {
let (_, bump) = Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], &ID);
let accounts = account_compression::cpi::accounts::InsertIntoQueues {
authority: ctx.accounts.cpi_signer.to_account_info(),
fee_payer: ctx.accounts.signer.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.to_account_info()),
system_program: ctx.accounts.system_program.to_account_info(),
};
let bump = &[bump];
let seeds = [&[CPI_AUTHORITY_PDA_SEED, bump][..]];
let mut cpi_context = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
&seeds,
);
cpi_context.remaining_accounts = vec![
ctx.accounts.queue.to_account_info(),
ctx.accounts.merkle_tree.to_account_info(),
];
account_compression::cpi::insert_into_nullifier_queues(cpi_context, vec![[1u8; 32]])?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn initialize_address_merkle_tree(
ctx: Context<InitializeAddressMerkleTreeAndQueue>,
bump: u8,
index: u64, // TODO: replace with counter from pda
program_owner: Option<Pubkey>,
merkle_tree_config: AddressMerkleTreeConfig, // TODO: check config with protocol config
queue_config: AddressQueueConfig,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts = account_compression::cpi::accounts::InitializeAddressMerkleTreeAndQueue {
authority: ctx.accounts.cpi_authority.to_account_info(),
merkle_tree: ctx.accounts.merkle_tree.to_account_info(),
queue: ctx.accounts.queue.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.clone()),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::initialize_address_merkle_tree_and_queue(
cpi_ctx,
index,
program_owner,
None,
merkle_tree_config,
queue_config,
)
}
#[allow(clippy::too_many_arguments)]
pub fn initialize_state_merkle_tree(
ctx: Context<InitializeAddressMerkleTreeAndQueue>,
bump: u8,
index: u64, // TODO: replace with counter from pda
program_owner: Option<Pubkey>,
merkle_tree_config: StateMerkleTreeConfig, // TODO: check config with protocol config
queue_config: NullifierQueueConfig,
additional_bytes: u64,
) -> Result<()> {
let bump = &[bump];
let seeds = [CPI_AUTHORITY_PDA_SEED, bump];
let signer_seeds = &[&seeds[..]];
let accounts =
account_compression::cpi::accounts::InitializeStateMerkleTreeAndNullifierQueue {
authority: ctx.accounts.cpi_authority.to_account_info(),
merkle_tree: ctx.accounts.merkle_tree.to_account_info(),
nullifier_queue: ctx.accounts.queue.to_account_info(),
registered_program_pda: Some(ctx.accounts.registered_program_pda.clone()),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.account_compression_program.to_account_info(),
accounts,
signer_seeds,
);
account_compression::cpi::initialize_state_merkle_tree_and_nullifier_queue(
cpi_ctx,
index,
program_owner,
None,
merkle_tree_config,
queue_config,
additional_bytes,
)
}
}
#[derive(Accounts)]
pub struct InitializeAddressMerkleTreeAndQueue<'info> {
#[account(mut)]
pub authority: Signer<'info>,
/// CHECK:
#[account(mut)]
pub merkle_tree: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
pub queue: AccountInfo<'info>,
/// CHECK:
pub registered_program_pda: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
cpi_authority: AccountInfo<'info>,
account_compression_program: Program<'info, AccountCompression>,
}
#[derive(Accounts)]
pub struct InitializeStateMerkleTreeAndQueue<'info> {
#[account(mut)]
pub authority: Signer<'info>,
/// CHECK:
#[account(mut)]
pub merkle_tree: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
pub queue: AccountInfo<'info>,
/// CHECK:
pub registered_program_pda: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
#[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)]
cpi_authority: AccountInfo<'info>,
account_compression_program: Program<'info, AccountCompression>,
}
#[derive(Accounts)]
pub struct AppendLeavesAccountCompressionProgram<'info> {
#[account(mut)]
pub signer: Signer<'info>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK:
pub registered_program_pda: AccountInfo<'info>,
/// CHECK:
pub noop_program: UncheckedAccount<'info>,
pub system_program: Program<'info, System>,
/// CHECK:
pub cpi_signer: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
pub merkle_tree: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
pub queue: AccountInfo<'info>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-cpi-test/src/create_pda.rs
|
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED};
use anchor_lang::prelude::*;
use light_hasher::{errors::HasherError, DataHasher, Poseidon};
use light_system_program::{
invoke::processor::CompressedProof,
program::LightSystemProgram,
sdk::{
address::derive_address,
compressed_account::{CompressedAccount, CompressedAccountData},
CompressedCpiContext,
},
InstructionDataInvokeCpi, NewAddressParamsPacked, OutputCompressedAccountWithPackedContext,
};
#[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone, PartialEq)]
pub enum CreatePdaMode {
ProgramIsSigner,
ProgramIsNotSigner,
InvalidSignerSeeds,
InvalidInvokingProgram,
WriteToAccountNotOwned,
NoData,
}
pub fn process_create_pda<'info>(
ctx: Context<'_, '_, '_, 'info, CreateCompressedPda<'info>>,
data: [u8; 31],
proof: Option<CompressedProof>,
new_address_params: NewAddressParamsPacked,
owner_program: Pubkey,
cpi_context: Option<CompressedCpiContext>,
is_program_signer: CreatePdaMode,
bump: u8,
) -> Result<()> {
let compressed_pda =
create_compressed_pda_data(data, &ctx, &new_address_params, &owner_program)?;
match is_program_signer {
CreatePdaMode::ProgramIsNotSigner => {
cpi_compressed_pda_transfer_as_non_program(
&ctx,
proof,
new_address_params,
compressed_pda,
cpi_context,
)?;
}
// functional test
CreatePdaMode::ProgramIsSigner => {
cpi_compressed_pda_transfer_as_program(
&ctx,
proof,
new_address_params,
compressed_pda,
cpi_context,
bump,
CreatePdaMode::ProgramIsSigner,
)?;
}
CreatePdaMode::InvalidSignerSeeds => {
cpi_compressed_pda_transfer_as_program(
&ctx,
proof,
new_address_params,
compressed_pda,
cpi_context,
bump,
CreatePdaMode::InvalidSignerSeeds,
)?;
}
CreatePdaMode::InvalidInvokingProgram => {
cpi_compressed_pda_transfer_as_program(
&ctx,
proof,
new_address_params,
compressed_pda,
cpi_context,
bump,
CreatePdaMode::InvalidInvokingProgram,
)?;
}
CreatePdaMode::WriteToAccountNotOwned => {
cpi_compressed_pda_transfer_as_program(
&ctx,
proof,
new_address_params,
compressed_pda,
cpi_context,
bump,
CreatePdaMode::WriteToAccountNotOwned,
)?;
}
CreatePdaMode::NoData => {
cpi_compressed_pda_transfer_as_program(
&ctx,
proof,
new_address_params,
compressed_pda,
cpi_context,
bump,
CreatePdaMode::NoData,
)?;
}
}
Ok(())
}
/// Functional:
/// 1. ProgramIsSigner
fn cpi_compressed_pda_transfer_as_non_program<'info>(
ctx: &Context<'_, '_, '_, 'info, CreateCompressedPda<'info>>,
proof: Option<CompressedProof>,
new_address_params: NewAddressParamsPacked,
compressed_pda: OutputCompressedAccountWithPackedContext,
cpi_context: Option<CompressedCpiContext>,
) -> Result<()> {
let inputs_struct = InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context: Vec::new(),
output_compressed_accounts: vec![compressed_pda],
proof,
new_address_params: vec![new_address_params],
compress_or_decompress_lamports: None,
is_compress: false,
cpi_context,
};
let mut inputs = Vec::new();
InstructionDataInvokeCpi::serialize(&inputs_struct, &mut inputs).unwrap();
let cpi_accounts = light_system_program::cpi::accounts::InvokeCpiInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
invoking_program: ctx.accounts.self_program.to_account_info(),
sol_pool_pda: None,
decompression_recipient: None,
system_program: ctx.accounts.system_program.to_account_info(),
cpi_context_account: None,
};
let mut cpi_ctx = CpiContext::new(
ctx.accounts.light_system_program.to_account_info(),
cpi_accounts,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
light_system_program::cpi::invoke_cpi(cpi_ctx, inputs)?;
Ok(())
}
fn cpi_compressed_pda_transfer_as_program<'info>(
ctx: &Context<'_, '_, '_, 'info, CreateCompressedPda<'info>>,
proof: Option<CompressedProof>,
new_address_params: NewAddressParamsPacked,
compressed_pda: OutputCompressedAccountWithPackedContext,
cpi_context: Option<CompressedCpiContext>,
bump: u8,
mode: CreatePdaMode,
) -> Result<()> {
let invoking_program = match mode {
CreatePdaMode::InvalidInvokingProgram => ctx.accounts.signer.to_account_info(),
_ => ctx.accounts.self_program.to_account_info(),
};
let compressed_pda = match mode {
CreatePdaMode::WriteToAccountNotOwned => {
// account with data needs to be owned by the program
let mut compressed_pda = compressed_pda;
compressed_pda.compressed_account.owner = ctx.accounts.signer.key();
compressed_pda
}
CreatePdaMode::NoData => {
let mut compressed_pda = compressed_pda;
compressed_pda.compressed_account.data = None;
compressed_pda
}
_ => compressed_pda,
};
let inputs_struct = InstructionDataInvokeCpi {
relay_fee: None,
input_compressed_accounts_with_merkle_context: Vec::new(),
output_compressed_accounts: vec![compressed_pda],
proof,
new_address_params: vec![new_address_params],
compress_or_decompress_lamports: None,
is_compress: false,
cpi_context,
};
// defining seeds again so that the cpi doesn't fail we want to test the check in the compressed pda program
let seeds: [&[u8]; 2] = [CPI_AUTHORITY_PDA_SEED, &[bump]];
let mut inputs = Vec::new();
InstructionDataInvokeCpi::serialize(&inputs_struct, &mut inputs).unwrap();
let cpi_accounts = light_system_program::cpi::accounts::InvokeCpiInstruction {
fee_payer: ctx.accounts.signer.to_account_info(),
authority: ctx.accounts.cpi_signer.to_account_info(),
registered_program_pda: ctx.accounts.registered_program_pda.to_account_info(),
noop_program: ctx.accounts.noop_program.to_account_info(),
account_compression_authority: ctx.accounts.account_compression_authority.to_account_info(),
account_compression_program: ctx.accounts.account_compression_program.to_account_info(),
invoking_program,
sol_pool_pda: None,
decompression_recipient: None,
system_program: ctx.accounts.system_program.to_account_info(),
cpi_context_account: None,
};
let signer_seeds: [&[&[u8]]; 1] = [&seeds[..]];
let mut cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.light_system_program.to_account_info(),
cpi_accounts,
&signer_seeds,
);
cpi_ctx.remaining_accounts = ctx.remaining_accounts.to_vec();
light_system_program::cpi::invoke_cpi(cpi_ctx, inputs)?;
Ok(())
}
fn create_compressed_pda_data(
data: [u8; 31],
ctx: &Context<'_, '_, '_, '_, CreateCompressedPda<'_>>,
new_address_params: &NewAddressParamsPacked,
owner_program: &Pubkey,
) -> Result<OutputCompressedAccountWithPackedContext> {
let timelock_compressed_pda = RegisteredUser {
user_pubkey: *ctx.accounts.signer.key,
data,
};
let compressed_account_data = CompressedAccountData {
discriminator: 1u64.to_le_bytes(),
data: timelock_compressed_pda.try_to_vec().unwrap(),
data_hash: timelock_compressed_pda
.hash::<Poseidon>()
.map_err(ProgramError::from)?,
};
let derive_address = derive_address(
&ctx.remaining_accounts[new_address_params.address_merkle_tree_account_index as usize]
.key(),
&new_address_params.seed,
)
.map_err(|_| ProgramError::InvalidArgument)?;
Ok(OutputCompressedAccountWithPackedContext {
compressed_account: CompressedAccount {
owner: *owner_program, // should be crate::ID, test provides an invalid owner
lamports: 0,
address: Some(derive_address),
data: Some(compressed_account_data),
},
merkle_tree_index: 0,
})
}
#[derive(AnchorDeserialize, AnchorSerialize, Debug, Clone)]
pub struct RegisteredUser {
pub user_pubkey: Pubkey,
pub data: [u8; 31],
}
impl light_hasher::DataHasher for RegisteredUser {
fn hash<H: light_hasher::Hasher>(&self) -> std::result::Result<[u8; 32], HasherError> {
let truncated_user_pubkey =
light_utils::hash_to_bn254_field_size_be(&self.user_pubkey.to_bytes())
.unwrap()
.0;
H::hashv(&[truncated_user_pubkey.as_slice(), self.data.as_slice()])
}
}
#[derive(Accounts)]
pub struct CreateCompressedPda<'info> {
#[account(mut)]
pub signer: Signer<'info>,
pub light_system_program: Program<'info, LightSystemProgram>,
pub account_compression_program: Program<'info, AccountCompression>,
/// CHECK:
pub account_compression_authority: AccountInfo<'info>,
/// CHECK:
pub compressed_token_cpi_authority_pda: AccountInfo<'info>,
/// CHECK:
pub registered_program_pda: AccountInfo<'info>,
/// CHECK:
pub noop_program: AccountInfo<'info>,
pub self_program: Program<'info, crate::program::SystemCpiTest>,
/// CHECK:
pub cpi_signer: AccountInfo<'info>,
pub system_program: Program<'info, System>,
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-test/Cargo.toml
|
[package]
name = "system-test"
version = "1.1.0"
description = "Created with Anchor"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "system_test"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
test-sbf = []
custom-heap = []
default = ["custom-heap"]
[dependencies]
[dev-dependencies]
solana-program-test = { workspace = true }
light-program-test = { workspace = true, features=["devenv"] }
light-test-utils = { version = "1.2.0", path = "../../test-utils", features=["devenv"]}
reqwest = "0.11.26"
tokio = { workspace = true }
light-prover-client = {path = "../../circuit-lib/light-prover-client" }
num-bigint = "0.4.6"
num-traits = "0.2.19"
spl-token = { workspace = true }
anchor-spl = { workspace = true }
anchor-lang = { workspace = true }
light-compressed-token = { workspace = true }
light-system-program = { workspace = true }
account-compression = { workspace = true }
light-hasher = {path = "../../merkle-tree/hasher"}
light-concurrent-merkle-tree = {path = "../../merkle-tree/concurrent"}
light-indexed-merkle-tree = {path = "../../merkle-tree/indexed"}
light-utils = {path = "../../utils"}
light-verifier = {path = "../../circuit-lib/verifier"}
light-registry = { workspace = true}
solana-cli-output = { workspace = true }
serde_json = "1.0.133"
solana-sdk = { workspace = true }
quote.workspace = true
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-test/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-test/tests/test.rs
|
#![cfg(feature = "test-sbf")]
use account_compression::errors::AccountCompressionErrorCode;
use anchor_lang::error::ErrorCode;
use anchor_lang::{AnchorSerialize, InstructionData, ToAccountMetas};
use light_hasher::Poseidon;
use light_program_test::test_env::{
initialize_accounts, setup_test_programs, setup_test_programs_with_accounts,
EnvAccountKeypairs, EnvAccounts, FORESTER_TEST_KEYPAIR, PAYER_KEYPAIR,
};
use light_program_test::test_rpc::ProgramTestRpcConnection;
use light_prover_client::gnark::helpers::{ProofType, ProverConfig, ProverMode};
use light_registry::protocol_config::state::ProtocolConfig;
use light_system_program::{
errors::SystemProgramError,
sdk::{
address::derive_address,
compressed_account::{CompressedAccount, CompressedAccountData, MerkleContext},
invoke::{
create_invoke_instruction, create_invoke_instruction_data_and_remaining_accounts,
},
},
utils::{get_cpi_authority_pda, get_registered_program_pda},
InstructionDataInvoke, NewAddressParams,
};
use light_test_utils::{
airdrop_lamports, assert_rpc_error, FeeConfig, Indexer, RpcConnection, RpcError,
TransactionParams,
};
use light_test_utils::{
assert_compressed_tx::assert_created_compressed_accounts,
assert_custom_error_or_program_error,
indexer::TestIndexer,
system_program::{
compress_sol_test, create_addresses_test, decompress_sol_test, transfer_compressed_sol_test,
},
};
use light_utils::hash_to_bn254_field_size_be;
use light_verifier::VerifierError;
use quote::format_ident;
use solana_cli_output::CliAccount;
use solana_sdk::{
instruction::{AccountMeta, Instruction, InstructionError},
pubkey::Pubkey,
signer::Signer,
transaction::Transaction,
};
use solana_sdk::{signature::Keypair, transaction::TransactionError};
use tokio::fs::write as async_write;
// TODO: use lazy_static to spawn the server once
/// invoke_failing_test
/// - inputs, outputs, new addresses, (fail with every possible input)
/// Test(outputs):
/// 1. invalid lamports (ComputeOutputSumFailed)
/// 2.1 all accounts have data but signer is not a program (InvokingProgramNotProvided)
/// 2.2 one of multiple accounts has data but signer is not a program (InvokingProgramNotProvided)
/// 3. invalid output Merkle tree (AccountDiscriminatorMismatch)
/// 4. address (InvalidAddress)
/// Test(address):
/// 1. inconsistent address seed (ProofVerificationFailed)
/// 2. invalid proof (ProofVerificationFailed)
/// 3. invalid root index (ProofVerificationFailed)
/// 4.1 invalid address queue account (InvalidQueueType)
/// 4.2 invalid address queue account (AccountDiscriminatorMismatch)
/// 5. invalid address Merkle tree account (AccountDiscriminatorMismatch)
/// Test(inputs):
/// 1. invalid proof (ProofVerificationFailed)
/// 2. invalid root index (ProofVerificationFailed)
/// 3. invalid leaf index (ProofVerificationFailed)
/// 4.1 invalid account data lamports (ProofVerificationFailed)
/// 4.2 invalid account data address (ProofVerificationFailed)
/// 4.3 invalid account data owner (SignerCheckFailed)
/// - invalid data is not tested because a compressed account that is not program-owned cannot have data
/// 5. invalid Merkle tree account (AccountDiscriminatorMismatch)
/// 6.1 invalid queue account (InvalidQueueType)
/// 6.2 invalid queue account (AccountDiscriminatorMismatch)
#[tokio::test]
async fn invoke_failing_test() {
let (mut context, env) = setup_test_programs_with_accounts(None).await;
let payer = context.get_payer().insecure_clone();
// no inputs
let (remaining_accounts, inputs_struct) = create_invoke_instruction_data_and_remaining_accounts(
&Vec::new(),
&Vec::new(),
&Vec::new(),
&Vec::new(),
&Vec::new(),
&Vec::new(),
None,
None,
false,
);
create_instruction_and_failing_transaction(
&mut context,
&payer,
inputs_struct,
remaining_accounts,
SystemProgramError::EmptyInputs.into(),
)
.await
.unwrap();
let mut test_indexer = TestIndexer::<ProgramTestRpcConnection>::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
// circuit instantiations allow for 1, 2, 3, 4, 8 inclusion proofs
let options = [0usize, 1usize, 2usize, 3usize, 4usize, 8usize];
for mut num_addresses in 0..=2 {
for j in 0..6 {
// there is no combined circuit instantiation for 8 inputs and addresses
if j == 5 {
num_addresses = 0;
}
for num_outputs in 1..8 {
failing_transaction_inputs(
&mut context,
&mut test_indexer,
&payer,
&env,
options[j],
1_000_000,
num_addresses,
num_outputs,
false,
)
.await
.unwrap();
}
}
}
for mut num_addresses in 0..=2 {
for j in 0..6 {
// there is no combined circuit instantiation for 8 inputs and addresses
if j == 5 {
num_addresses = 0;
}
for num_outputs in 0..8 {
failing_transaction_inputs(
&mut context,
&mut test_indexer,
&payer,
&env,
options[j],
0,
num_addresses,
num_outputs,
false,
)
.await
.unwrap();
}
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn failing_transaction_inputs(
context: &mut ProgramTestRpcConnection,
test_indexer: &mut TestIndexer<ProgramTestRpcConnection>,
payer: &Keypair,
env: &EnvAccounts,
num_inputs: usize,
amount: u64,
num_addresses: usize,
num_outputs: usize,
output_compressed_accounts_with_address: bool,
) -> Result<(), RpcError> {
// create compressed accounts that can be used as inputs
for _ in 0..num_inputs {
compress_sol_test(
context,
test_indexer,
payer,
&[],
false,
amount,
&env.merkle_tree_pubkey,
None,
)
.await
.unwrap();
}
let (mut new_address_params, derived_addresses) =
create_address_test_inputs(env, num_addresses);
let input_compressed_accounts =
test_indexer.get_compressed_accounts_by_owner(&payer.pubkey())[0..num_inputs].to_vec();
let hashes = input_compressed_accounts
.iter()
.map(|x| x.hash().unwrap())
.collect::<Vec<_>>();
let input_compressed_account_hashes = if num_inputs != 0 {
Some(hashes.as_slice())
} else {
None
};
let mts = input_compressed_accounts
.iter()
.map(|x| x.merkle_context.merkle_tree_pubkey)
.collect::<Vec<_>>();
let input_state_merkle_trees = if num_inputs != 0 {
Some(mts.as_slice())
} else {
None
};
let proof_input_derived_addresses = if num_addresses != 0 {
Some(derived_addresses.as_slice())
} else {
None
};
let proof_input_address_merkle_tree_pubkeys = if num_addresses != 0 {
Some(vec![env.address_merkle_tree_pubkey; num_addresses])
} else {
None
};
let (root_indices, proof) =
if input_compressed_account_hashes.is_some() || proof_input_derived_addresses.is_some() {
let proof_rpc_res = test_indexer
.create_proof_for_compressed_accounts(
input_compressed_account_hashes,
input_state_merkle_trees,
proof_input_derived_addresses,
proof_input_address_merkle_tree_pubkeys,
context,
)
.await;
for (i, root_index) in proof_rpc_res.address_root_indices.iter().enumerate() {
new_address_params[i].address_merkle_tree_root_index = *root_index;
}
(proof_rpc_res.root_indices, Some(proof_rpc_res.proof))
} else {
(Vec::new(), None)
};
let (output_compressed_accounts, output_merkle_tree_pubkeys) = if num_outputs > 0 {
let mut output_compressed_accounts = vec![];
let mut output_merkle_tree_pubkeys = vec![];
let sum_lamports = input_compressed_accounts
.iter()
.map(|x| x.compressed_account.lamports)
.sum::<u64>();
let output_amount = sum_lamports / num_outputs as u64;
let remainder = sum_lamports % num_outputs as u64;
for i in 0..num_outputs {
let address = if output_compressed_accounts_with_address && i < num_addresses {
Some(derived_addresses[i])
} else {
None
};
output_compressed_accounts.push(CompressedAccount {
lamports: output_amount,
owner: payer.pubkey(),
data: None,
address,
});
output_merkle_tree_pubkeys.push(env.merkle_tree_pubkey);
}
output_compressed_accounts[0].lamports += remainder;
(output_compressed_accounts, output_merkle_tree_pubkeys)
} else {
(Vec::new(), Vec::new())
};
let (remaining_accounts, inputs_struct) = create_invoke_instruction_data_and_remaining_accounts(
&new_address_params,
&input_compressed_accounts
.iter()
.map(|x| x.merkle_context)
.collect::<Vec<_>>(),
&input_compressed_accounts
.iter()
.map(|x| x.compressed_account.clone())
.collect::<Vec<_>>(),
&root_indices,
&output_merkle_tree_pubkeys,
&output_compressed_accounts,
proof,
None,
false,
);
if num_addresses > 0 {
failing_transaction_address(
context,
payer,
env,
&inputs_struct,
remaining_accounts.clone(),
)
.await?;
}
if num_inputs > 0 {
failing_transaction_inputs_inner(
context,
payer,
env,
&inputs_struct,
remaining_accounts.clone(),
)
.await?;
}
if num_outputs > 0 {
failing_transaction_output(
context,
payer,
env,
inputs_struct,
remaining_accounts.clone(),
)
.await?;
}
Ok(())
}
pub async fn failing_transaction_inputs_inner(
context: &mut ProgramTestRpcConnection,
payer: &Keypair,
env: &EnvAccounts,
inputs_struct: &InstructionDataInvoke,
remaining_accounts: Vec<AccountMeta>,
) -> Result<(), RpcError> {
let num_inputs = inputs_struct
.input_compressed_accounts_with_merkle_context
.len();
let num_outputs = inputs_struct.output_compressed_accounts.len();
// invalid proof
{
println!("invalid proof");
let mut inputs_struct = inputs_struct.clone();
inputs_struct.proof.as_mut().unwrap().a = inputs_struct.proof.as_ref().unwrap().c.clone();
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid root index
{
println!("invalid root index");
let mut inputs_struct = inputs_struct.clone();
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1].root_index = 0;
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid leaf index
{
println!(
"leaf index: {}",
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.merkle_context
.leaf_index
);
let mut inputs_struct = inputs_struct.clone();
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.merkle_context
.leaf_index += 1;
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid account data (lamports)
if !inputs_struct.output_compressed_accounts.is_empty() {
let mut inputs_struct = inputs_struct.clone();
let amount = inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.compressed_account
.lamports;
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.compressed_account
.lamports = amount + 1;
let error_code = if !inputs_struct.output_compressed_accounts.is_empty() {
// adapting compressed output account so that sumcheck passes
inputs_struct.output_compressed_accounts[0]
.compressed_account
.lamports += 1;
VerifierError::ProofVerificationFailed.into()
} else {
SystemProgramError::SumCheckFailed.into()
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
error_code,
)
.await
.unwrap();
}
// invalid account data (address)
{
let mut inputs_struct = inputs_struct.clone();
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.compressed_account
.address = Some(hash_to_bn254_field_size_be([1u8; 32].as_slice()).unwrap().0);
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid account data (owner)
{
let mut inputs_struct = inputs_struct.clone();
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.compressed_account
.owner = Keypair::new().pubkey();
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
SystemProgramError::SignerCheckFailed.into(),
)
.await
.unwrap();
}
// invalid account data (data)
{
let data = CompressedAccountData {
discriminator: [1u8; 8],
data: vec![1u8; 1],
data_hash: hash_to_bn254_field_size_be([1u8; 32].as_slice()).unwrap().0,
};
let mut inputs_struct = inputs_struct.clone();
inputs_struct.input_compressed_accounts_with_merkle_context[num_inputs - 1]
.compressed_account
.data = Some(data);
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
SystemProgramError::SignerCheckFailed.into(),
)
.await
.unwrap();
}
// invalid Merkle tree account
{
let inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts[inputs_struct.input_compressed_accounts_with_merkle_context
[num_inputs - 1]
.merkle_context
.merkle_tree_pubkey_index as usize] = AccountMeta {
pubkey: env.address_merkle_tree_pubkey,
is_signer: false,
is_writable: false,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
ErrorCode::AccountDiscriminatorMismatch.into(),
)
.await
.unwrap();
}
// invalid queue account
{
let inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts[inputs_struct.input_compressed_accounts_with_merkle_context
[num_inputs - 1]
.merkle_context
.nullifier_queue_pubkey_index as usize] = AccountMeta {
pubkey: env.address_merkle_tree_queue_pubkey,
is_signer: false,
is_writable: true,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
AccountCompressionErrorCode::InvalidQueueType.into(),
)
.await
.unwrap();
}
// invalid queue account
{
let inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts[inputs_struct.input_compressed_accounts_with_merkle_context
[num_inputs - 1]
.merkle_context
.nullifier_queue_pubkey_index as usize] = AccountMeta {
pubkey: env.address_merkle_tree_pubkey,
is_signer: false,
is_writable: true,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
ErrorCode::AccountDiscriminatorMismatch.into(),
)
.await
.unwrap();
}
// output Merkle tree is not unique (we need at least 2 outputs for this test)
if num_outputs > 1 {
let mut inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
let remaining_mt_acc = remaining_accounts
[inputs_struct.output_compressed_accounts[1].merkle_tree_index as usize]
.clone();
remaining_accounts.push(remaining_mt_acc);
inputs_struct.output_compressed_accounts[1].merkle_tree_index =
(remaining_accounts.len() - 1) as u8;
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
SystemProgramError::OutputMerkleTreeNotUnique.into(),
)
.await
.unwrap();
}
Ok(())
}
fn create_address_test_inputs(
env: &EnvAccounts,
num_addresses: usize,
) -> (Vec<NewAddressParams>, Vec<[u8; 32]>) {
let mut address_seeds = vec![];
for i in 1..=num_addresses {
address_seeds.push([i as u8; 32]);
}
let mut new_address_params = vec![];
let mut derived_addresses = Vec::new();
for (_, address_seed) in address_seeds.iter().enumerate() {
new_address_params.push(NewAddressParams {
seed: *address_seed,
address_queue_pubkey: env.address_merkle_tree_queue_pubkey,
address_merkle_tree_pubkey: env.address_merkle_tree_pubkey,
address_merkle_tree_root_index: 0,
});
let derived_address =
derive_address(&env.address_merkle_tree_pubkey, address_seed).unwrap();
derived_addresses.push(derived_address);
}
(new_address_params, derived_addresses)
}
pub async fn failing_transaction_address(
context: &mut ProgramTestRpcConnection,
payer: &Keypair,
env: &EnvAccounts,
inputs_struct: &InstructionDataInvoke,
remaining_accounts: Vec<AccountMeta>,
) -> Result<(), RpcError> {
// inconsistent seed
{
let mut inputs_struct = inputs_struct.clone();
inputs_struct.new_address_params[0].seed = [100u8; 32];
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid proof
{
let mut inputs_struct = inputs_struct.clone();
inputs_struct.proof.as_mut().unwrap().a = inputs_struct.proof.as_ref().unwrap().c.clone();
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid root index
{
let mut inputs_struct = inputs_struct.clone();
inputs_struct.new_address_params[0].address_merkle_tree_root_index = 0;
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
VerifierError::ProofVerificationFailed.into(),
)
.await
.unwrap();
}
// invalid address queue account
{
let inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts
[inputs_struct.new_address_params[0].address_queue_account_index as usize] =
AccountMeta {
pubkey: env.nullifier_queue_pubkey,
is_signer: false,
is_writable: false,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
AccountCompressionErrorCode::InvalidQueueType.into(),
)
.await
.unwrap();
}
// invalid address queue account
{
let inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts
[inputs_struct.new_address_params[0].address_queue_account_index as usize] =
AccountMeta {
pubkey: env.merkle_tree_pubkey,
is_signer: false,
is_writable: false,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
ErrorCode::AccountDiscriminatorMismatch.into(),
)
.await
.unwrap();
}
// invalid address Merkle tree account
{
let inputs_struct = inputs_struct.clone();
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts
[inputs_struct.new_address_params[0].address_merkle_tree_account_index as usize] =
AccountMeta {
pubkey: env.merkle_tree_pubkey,
is_signer: false,
is_writable: false,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct,
remaining_accounts.clone(),
ErrorCode::AccountDiscriminatorMismatch.into(),
)
.await
.unwrap();
}
Ok(())
}
/// Output compressed accounts no inputs:
/// 1. invalid lamports (for no input compressed accounts lamports can only be 0)
/// 2. data but signer is not a program
/// 3. invalid output Merkle tree
/// 4. address that doesn't exist
pub async fn failing_transaction_output(
context: &mut ProgramTestRpcConnection,
payer: &Keypair,
env: &EnvAccounts,
inputs_struct: InstructionDataInvoke,
remaining_accounts: Vec<AccountMeta>,
) -> Result<(), RpcError> {
let num_output_compressed_accounts = inputs_struct.output_compressed_accounts.len();
// invalid lamports
{
let mut inputs_struct = inputs_struct.clone();
let error_code = if inputs_struct
.input_compressed_accounts_with_merkle_context
.iter()
.map(|x| x.compressed_account.lamports)
.sum::<u64>()
== 0
{
SystemProgramError::ComputeOutputSumFailed.into()
} else {
SystemProgramError::SumCheckFailed.into()
};
inputs_struct.output_compressed_accounts[num_output_compressed_accounts - 1]
.compressed_account
.lamports = 1;
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct.clone(),
remaining_accounts.clone(),
error_code,
)
.await
.unwrap();
}
// Data but signer is not a program
{
let mut inputs_struct = inputs_struct.clone();
for (i, account) in inputs_struct
.output_compressed_accounts
.iter_mut()
.enumerate()
{
let data = CompressedAccountData {
discriminator: [i as u8; 8],
data: vec![i as u8; i],
data_hash: [i as u8; 32],
};
account.compressed_account.data = Some(data);
}
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct.clone(),
remaining_accounts.clone(),
SystemProgramError::InvokingProgramNotProvided.into(),
)
.await
.unwrap();
}
// Invalid output Merkle tree
{
let mut remaining_accounts = remaining_accounts.clone();
remaining_accounts[inputs_struct.output_compressed_accounts
[num_output_compressed_accounts - 1]
.merkle_tree_index as usize] = AccountMeta {
pubkey: env.address_merkle_tree_pubkey,
is_signer: false,
is_writable: false,
};
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct.clone(),
remaining_accounts.clone(),
ErrorCode::AccountDiscriminatorMismatch.into(),
)
.await
.unwrap();
}
// Address that doesn't exist
{
let mut inputs_struct = inputs_struct.clone();
for account in inputs_struct.output_compressed_accounts.iter_mut() {
let address = Some(
hash_to_bn254_field_size_be(Keypair::new().pubkey().to_bytes().as_slice())
.unwrap()
.0,
);
account.compressed_account.address = address;
}
create_instruction_and_failing_transaction(
context,
payer,
inputs_struct.clone(),
remaining_accounts.clone(),
SystemProgramError::InvalidAddress.into(),
)
.await
.unwrap();
}
Ok(())
}
pub async fn perform_tx_with_output_compressed_accounts(
context: &mut ProgramTestRpcConnection,
payer: &Keypair,
payer_pubkey: Pubkey,
output_compressed_accounts: Vec<CompressedAccount>,
output_merkle_tree_pubkeys: Vec<Pubkey>,
expected_error_code: u32,
) -> Result<(), RpcError> {
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&Vec::new(),
&output_compressed_accounts,
&Vec::new(),
output_merkle_tree_pubkeys.as_slice(),
&Vec::new(),
&Vec::new(),
None,
None,
false,
None,
true,
);
let result = context
.create_and_send_transaction(&[instruction], &payer_pubkey, &[payer])
.await;
assert_rpc_error(result, 0, expected_error_code)
}
pub async fn create_instruction_and_failing_transaction(
context: &mut ProgramTestRpcConnection,
payer: &Keypair,
inputs_struct: InstructionDataInvoke,
remaining_accounts: Vec<AccountMeta>,
expected_error_code: u32,
) -> Result<(), RpcError> {
let mut inputs = Vec::new();
InstructionDataInvoke::serialize(&inputs_struct, &mut inputs).unwrap();
let instruction_data = light_system_program::instruction::Invoke { inputs };
let sol_pool_pda = None;
let accounts = light_system_program::accounts::InvokeInstruction {
fee_payer: payer.pubkey(),
authority: payer.pubkey(),
registered_program_pda: get_registered_program_pda(&light_system_program::ID),
noop_program: Pubkey::new_from_array(account_compression::utils::constants::NOOP_PUBKEY),
account_compression_program: account_compression::ID,
account_compression_authority: get_cpi_authority_pda(&light_system_program::ID),
sol_pool_pda,
decompression_recipient: None,
system_program: solana_sdk::system_program::ID,
};
let instruction = Instruction {
program_id: light_system_program::ID,
accounts: [accounts.to_account_metas(Some(true)), remaining_accounts].concat(),
data: instruction_data.data(),
};
let result = match context
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[payer])
.await
{
Ok(_) => {
println!("inputs_struct: {:?}", inputs_struct);
println!("expected_error_code: {}", expected_error_code);
panic!("Transaction should have failed");
}
Err(e) => e,
};
assert_rpc_error::<()>(Err(result), 0, expected_error_code)
}
/// Tests Execute compressed transaction:
/// 1. should succeed: without compressed account(0 lamports), no in compressed account
/// 2. should fail: in compressed account and invalid zkp
/// 3. should fail: in compressed account and invalid signer
/// 4. should succeed: in compressed account inserted in (1.) and valid zkp
#[tokio::test]
async fn invoke_test() {
let (mut context, env) = setup_test_programs_with_accounts(None).await;
let payer = context.get_payer().insecure_clone();
let mut test_indexer = TestIndexer::<ProgramTestRpcConnection>::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
let payer_pubkey = payer.pubkey();
let merkle_tree_pubkey = env.merkle_tree_pubkey;
let nullifier_queue_pubkey = env.nullifier_queue_pubkey;
let output_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: payer_pubkey,
data: None,
address: None,
}];
let output_merkle_tree_pubkeys = vec![merkle_tree_pubkey];
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&Vec::new(),
&output_compressed_accounts,
&Vec::new(),
output_merkle_tree_pubkeys.as_slice(),
&Vec::new(),
&Vec::new(),
None,
None,
false,
None,
true,
);
let event = context
.create_and_send_transaction_with_event(
&[instruction],
&payer_pubkey,
&[&payer],
Some(TransactionParams {
num_input_compressed_accounts: 0,
num_output_compressed_accounts: 1,
num_new_addresses: 0,
compress: 0,
fee_config: FeeConfig::default(),
}),
)
.await
.unwrap()
.unwrap();
let (created_compressed_accounts, _) = test_indexer.add_event_and_compressed_accounts(&event.0);
assert_created_compressed_accounts(
output_compressed_accounts.as_slice(),
output_merkle_tree_pubkeys.as_slice(),
created_compressed_accounts.as_slice(),
false,
);
let input_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: payer_pubkey,
data: None,
address: None,
}];
// check invalid proof
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&input_compressed_accounts,
&output_compressed_accounts,
&[MerkleContext {
merkle_tree_pubkey,
leaf_index: 0,
nullifier_queue_pubkey,
queue_index: None,
}],
&[merkle_tree_pubkey],
&[0u16],
&Vec::new(),
None,
None,
false,
None,
true,
);
let res = context
.create_and_send_transaction(&[instruction], &payer_pubkey, &[&payer])
.await;
assert!(res.is_err());
// check invalid signer for in compressed_account
let invalid_signer_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: Keypair::new().pubkey(),
data: None,
address: None,
}];
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&invalid_signer_compressed_accounts,
&output_compressed_accounts,
&[MerkleContext {
merkle_tree_pubkey,
leaf_index: 0,
nullifier_queue_pubkey,
queue_index: None,
}],
&[merkle_tree_pubkey],
&[0u16],
&Vec::new(),
None,
None,
false,
None,
true,
);
let res = context
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
assert!(res.is_err());
// create Merkle proof
// get zkp from server
// create instruction as usual with correct zkp
let compressed_account_with_context = test_indexer.compressed_accounts[0].clone();
let proof_rpc_res = test_indexer
.create_proof_for_compressed_accounts(
Some(&[compressed_account_with_context
.compressed_account
.hash::<Poseidon>(
&merkle_tree_pubkey,
&compressed_account_with_context.merkle_context.leaf_index,
)
.unwrap()]),
Some(&[compressed_account_with_context
.merkle_context
.merkle_tree_pubkey]),
None,
None,
&mut context,
)
.await;
let input_compressed_accounts = vec![compressed_account_with_context.compressed_account];
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&input_compressed_accounts,
&output_compressed_accounts,
&[MerkleContext {
merkle_tree_pubkey,
leaf_index: 0,
nullifier_queue_pubkey,
queue_index: None,
}],
&[merkle_tree_pubkey],
&proof_rpc_res.root_indices,
&Vec::new(),
Some(proof_rpc_res.proof.clone()),
None,
false,
None,
true,
);
println!("Transaction with zkp -------------------------");
let event = context
.create_and_send_transaction_with_event(
&[instruction],
&payer_pubkey,
&[&payer],
Some(TransactionParams {
num_input_compressed_accounts: 1,
num_output_compressed_accounts: 1,
num_new_addresses: 0,
compress: 0,
fee_config: FeeConfig::default(),
}),
)
.await
.unwrap()
.unwrap();
test_indexer.add_event_and_compressed_accounts(&event.0);
println!("Double spend -------------------------");
let output_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: Keypair::new().pubkey(),
data: None,
address: None,
}];
// double spend
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&input_compressed_accounts,
&output_compressed_accounts,
&[MerkleContext {
merkle_tree_pubkey,
leaf_index: 0,
nullifier_queue_pubkey,
queue_index: None,
}],
&[merkle_tree_pubkey],
&proof_rpc_res.root_indices,
&Vec::new(),
Some(proof_rpc_res.proof.clone()),
None,
false,
None,
true,
);
let res = context
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
assert!(res.is_err());
let output_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: Keypair::new().pubkey(),
data: None,
address: None,
}];
// invalid compressed_account
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&input_compressed_accounts,
&output_compressed_accounts,
&[MerkleContext {
merkle_tree_pubkey,
leaf_index: 1,
nullifier_queue_pubkey,
queue_index: None,
}],
&[merkle_tree_pubkey],
&proof_rpc_res.root_indices,
&Vec::new(),
Some(proof_rpc_res.proof.clone()),
None,
false,
None,
true,
);
let res = context
.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
.await;
assert!(res.is_err());
}
/// Tests Execute compressed transaction with address:
/// 1. should fail: create out compressed account with address without input compressed account with address or created address
/// 2. should succeed: create out compressed account with new created address
/// 3. should fail: create two addresses with the same seeds
/// 4. should succeed: create two addresses with different seeds
/// 5. should succeed: create multiple addresses with different seeds and spend input compressed accounts
/// testing: (input accounts, new addresses) (1, 1), (1, 2), (2, 1), (2, 2)
#[tokio::test]
async fn test_with_address() {
let (mut context, env) = setup_test_programs_with_accounts(None).await;
let payer = context.get_payer().insecure_clone();
let mut test_indexer = TestIndexer::<ProgramTestRpcConnection>::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: Some(ProverMode::Rpc),
circuits: vec![],
}),
)
.await;
let payer_pubkey = payer.pubkey();
let merkle_tree_pubkey = env.merkle_tree_pubkey;
let address_seed = [1u8; 32];
let derived_address = derive_address(&env.address_merkle_tree_pubkey, &address_seed).unwrap();
let output_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: payer_pubkey,
data: None,
address: Some(derived_address), // this should not be sent, only derived on-chain
}];
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&Vec::new(),
&output_compressed_accounts,
&Vec::new(),
&[merkle_tree_pubkey],
&Vec::new(),
&Vec::new(),
None,
None,
false,
None,
true,
);
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer_pubkey),
&[&payer],
context.get_latest_blockhash().await.unwrap(),
);
let res = context.process_transaction(transaction).await;
assert_custom_error_or_program_error(res, SystemProgramError::InvalidAddress.into()).unwrap();
println!("creating address -------------------------");
create_addresses_test(
&mut context,
&mut test_indexer,
&[env.address_merkle_tree_pubkey],
&[env.address_merkle_tree_queue_pubkey],
vec![env.merkle_tree_pubkey],
&[address_seed],
&Vec::new(),
false,
None,
)
.await
.unwrap();
// transfer with address
println!("transfer with address-------------------------");
let compressed_account_with_context = test_indexer.compressed_accounts[0].clone();
let recipient_pubkey = Keypair::new().pubkey();
transfer_compressed_sol_test(
&mut context,
&mut test_indexer,
&payer,
&[compressed_account_with_context.clone()],
&[recipient_pubkey],
&[compressed_account_with_context
.merkle_context
.merkle_tree_pubkey],
None,
)
.await
.unwrap();
assert_eq!(test_indexer.compressed_accounts.len(), 1);
assert_eq!(
test_indexer.compressed_accounts[0]
.compressed_account
.address
.unwrap(),
derived_address
);
assert_eq!(
test_indexer.compressed_accounts[0].compressed_account.owner,
recipient_pubkey
);
let address_seed_2 = [2u8; 32];
let event = create_addresses_test(
&mut context,
&mut test_indexer,
&[
env.address_merkle_tree_pubkey,
env.address_merkle_tree_pubkey,
],
&[
env.address_merkle_tree_queue_pubkey,
env.address_merkle_tree_queue_pubkey,
],
vec![env.merkle_tree_pubkey, env.merkle_tree_pubkey],
&[address_seed_2, address_seed_2],
&Vec::new(),
false,
None,
)
.await;
// Should fail to insert the same address twice in the same tx
assert!(matches!(
event,
Err(RpcError::TransactionError(
// ElementAlreadyExists
TransactionError::InstructionError(0, InstructionError::Custom(9002))
))
));
println!("test 2in -------------------------");
let address_seed_3 = [3u8; 32];
create_addresses_test(
&mut context,
&mut test_indexer,
&[
env.address_merkle_tree_pubkey,
env.address_merkle_tree_pubkey,
],
&[
env.address_merkle_tree_queue_pubkey,
env.address_merkle_tree_queue_pubkey,
],
vec![env.merkle_tree_pubkey, env.merkle_tree_pubkey],
&[address_seed_2, address_seed_3],
&Vec::new(),
false,
None,
)
.await
.unwrap();
// Test combination
// (num_input_compressed_accounts, num_new_addresses)
let test_inputs = vec![
(1, 1),
(1, 2),
(2, 1),
(2, 2),
(3, 1),
(3, 2),
(4, 1),
(4, 2),
];
for (n_input_compressed_accounts, n_new_addresses) in test_inputs {
let compressed_input_accounts = test_indexer
.get_compressed_accounts_by_owner(&payer_pubkey)[0..n_input_compressed_accounts]
.to_vec();
let mut address_vec = Vec::new();
// creates multiple seeds by taking the number of input accounts and zeroing out the jth byte
for j in 0..n_new_addresses {
let mut address_seed = [n_input_compressed_accounts as u8; 32];
address_seed[j + (n_new_addresses * 2)] = 0_u8;
address_vec.push(address_seed);
}
create_addresses_test(
&mut context,
&mut test_indexer,
&vec![env.address_merkle_tree_pubkey; n_new_addresses],
&vec![env.address_merkle_tree_queue_pubkey; n_new_addresses],
vec![env.merkle_tree_pubkey; n_new_addresses],
&address_vec,
&compressed_input_accounts,
true,
None,
)
.await
.unwrap();
}
}
#[tokio::test]
async fn test_with_compression() {
let (mut context, env) = setup_test_programs_with_accounts(None).await;
let payer = context.get_payer().insecure_clone();
let payer_pubkey = payer.pubkey();
let merkle_tree_pubkey = env.merkle_tree_pubkey;
let nullifier_queue_pubkey = env.nullifier_queue_pubkey;
let mut test_indexer = TestIndexer::<ProgramTestRpcConnection>::init_from_env(
&payer,
&env,
Some(ProverConfig {
run_mode: None,
circuits: vec![ProofType::Inclusion],
}),
)
.await;
let compress_amount = 1_000_000;
let output_compressed_accounts = vec![CompressedAccount {
lamports: compress_amount + 1,
owner: payer_pubkey,
data: None,
address: None,
}];
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&Vec::new(),
&output_compressed_accounts,
&Vec::new(),
&[merkle_tree_pubkey],
&Vec::new(),
&Vec::new(),
None,
Some(compress_amount),
false,
None,
true,
);
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer_pubkey),
&[&payer],
context.get_latest_blockhash().await.unwrap(),
);
let result = context.process_transaction(transaction).await;
// should fail because of insufficient input funds
assert_custom_error_or_program_error(result, SystemProgramError::ComputeOutputSumFailed.into())
.unwrap();
let output_compressed_accounts = vec![CompressedAccount {
lamports: compress_amount,
owner: payer_pubkey,
data: None,
address: None,
}];
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&Vec::new(),
&output_compressed_accounts,
&Vec::new(),
&[merkle_tree_pubkey],
&Vec::new(),
&Vec::new(),
None,
None,
true,
None,
true,
);
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer_pubkey),
&[&payer],
context.get_latest_blockhash().await.unwrap(),
);
let result = context.process_transaction(transaction).await;
// should fail because of insufficient decompress amount funds
assert_custom_error_or_program_error(result, SystemProgramError::ComputeOutputSumFailed.into())
.unwrap();
compress_sol_test(
&mut context,
&mut test_indexer,
&payer,
&Vec::new(),
false,
compress_amount,
&env.merkle_tree_pubkey,
None,
)
.await
.unwrap();
let compressed_account_with_context = test_indexer.compressed_accounts.last().unwrap().clone();
let proof_rpc_res = test_indexer
.create_proof_for_compressed_accounts(
Some(&[compressed_account_with_context
.compressed_account
.hash::<Poseidon>(
&merkle_tree_pubkey,
&compressed_account_with_context.merkle_context.leaf_index,
)
.unwrap()]),
Some(&[compressed_account_with_context
.merkle_context
.merkle_tree_pubkey]),
None,
None,
&mut context,
)
.await;
let input_compressed_accounts =
vec![compressed_account_with_context.clone().compressed_account];
let recipient_pubkey = Keypair::new().pubkey();
let output_compressed_accounts = vec![CompressedAccount {
lamports: 0,
owner: recipient_pubkey,
data: None,
address: None,
}];
let recipient = Keypair::new().pubkey();
let instruction = create_invoke_instruction(
&payer_pubkey,
&payer_pubkey,
&input_compressed_accounts,
&output_compressed_accounts,
&[MerkleContext {
merkle_tree_pubkey,
leaf_index: 0,
nullifier_queue_pubkey,
queue_index: None,
}],
&[merkle_tree_pubkey],
&proof_rpc_res.root_indices,
&Vec::new(),
Some(proof_rpc_res.proof.clone()),
Some(compress_amount),
true,
Some(recipient),
true,
);
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer_pubkey),
&[&payer],
context.get_latest_blockhash().await.unwrap(),
);
println!("Transaction with zkp -------------------------");
let result = context.process_transaction(transaction).await;
// should fail because of insufficient output funds
assert_custom_error_or_program_error(result, SystemProgramError::SumCheckFailed.into())
.unwrap();
let compressed_account_with_context =
test_indexer.get_compressed_accounts_by_owner(&payer_pubkey)[0].clone();
decompress_sol_test(
&mut context,
&mut test_indexer,
&payer,
&vec![compressed_account_with_context],
&recipient_pubkey,
compress_amount,
&env.merkle_tree_pubkey,
None,
)
.await
.unwrap();
}
#[ignore = "this is a helper function to regenerate accounts"]
#[tokio::test]
async fn regenerate_accounts() {
let output_dir = "../../cli/accounts/";
let protocol_config = ProtocolConfig {
genesis_slot: 0,
slot_length: 10,
registration_phase_length: 100,
active_phase_length: 200,
report_work_phase_length: 100,
..ProtocolConfig::default()
};
let context = setup_test_programs(None).await;
let mut context = ProgramTestRpcConnection { context };
let mut keypairs = EnvAccountKeypairs::from_target_folder();
keypairs.governance_authority = Keypair::from_bytes(&PAYER_KEYPAIR).unwrap();
keypairs.forester = Keypair::from_bytes(&FORESTER_TEST_KEYPAIR).unwrap();
airdrop_lamports(
&mut context,
&keypairs.governance_authority.pubkey(),
100_000_000_000,
)
.await
.unwrap();
// let forester = Keypair::from_bytes(&FORESTER_TEST_KEYPAIR).unwrap();
airdrop_lamports(&mut context, &keypairs.forester.pubkey(), 10_000_000_000)
.await
.unwrap();
// Note this will not regenerate the registered program accounts.
let skip_register_programs = true;
let env = initialize_accounts(
&mut context,
keypairs,
protocol_config,
true,
skip_register_programs,
)
.await;
// List of public keys to fetch and export
let pubkeys = vec![
("merkle_tree_pubkey", env.merkle_tree_pubkey),
("nullifier_queue_pubkey", env.nullifier_queue_pubkey),
("governance_authority_pda", env.governance_authority_pda),
("group_pda", env.group_pda),
("registered_program_pda", env.registered_program_pda),
("address_merkle_tree", env.address_merkle_tree_pubkey),
(
"address_merkle_tree_queue",
env.address_merkle_tree_queue_pubkey,
),
("cpi_context", env.cpi_context_account_pubkey),
(
"registered_registry_program_pda",
env.registered_registry_program_pda,
),
("registered_forester_pda", env.registered_forester_pda),
(
"forester_epoch_pda",
env.forester_epoch.as_ref().unwrap().forester_epoch_pda,
),
("epoch_pda", env.forester_epoch.as_ref().unwrap().epoch_pda),
];
let mut rust_file = String::new();
let code = quote::quote! {
use solana_sdk::account::Account;
use solana_sdk::pubkey::Pubkey;
use std::str::FromStr;
};
rust_file.push_str(&code.to_string());
for (name, pubkey) in pubkeys {
// Fetch account data. Adjust this part to match how you retrieve and structure your account data.
let account = context.get_account(pubkey).await.unwrap();
println!(
"{} DISCRIMINATOR {:?}",
name,
account.as_ref().unwrap().data[0..8].to_vec()
);
let unwrapped_account = account.unwrap();
let account = CliAccount::new(&pubkey, &unwrapped_account, true);
// Serialize the account data to JSON. Adjust according to your data structure.
let json_data = serde_json::to_vec(&account).unwrap();
// Construct the output file path
let file_name = format!("{}_{}.json", name, pubkey);
let file_path = format!("{}{}", output_dir, file_name);
println!("Writing account data to {}", file_path);
// Write the JSON data to a file in the specified directory
async_write(file_path.clone(), json_data).await.unwrap();
if name == "registered_program_pda" || name == "registered_registry_program_pda" {
let lamports = unwrapped_account.lamports;
let owner = unwrapped_account.owner.to_string();
let executable = unwrapped_account.executable;
let rent_epoch = unwrapped_account.rent_epoch;
let data = unwrapped_account.data.iter().map(|b| quote::quote! {#b});
let function_name = format_ident!("get_{}", name);
let code = quote::quote! {
pub fn #function_name()-> Account {
Account {
lamports: #lamports,
data: vec![#(#data),*],
owner: Pubkey::from_str(#owner).unwrap(),
executable: #executable,
rent_epoch: #rent_epoch,
}
}
};
rust_file.push_str(&code.to_string());
}
}
use light_utils::rustfmt;
use std::io::Write;
let output_path = "../../test-utils/src/env_accounts.rs";
let mut file = std::fs::File::create(&output_path).unwrap();
file.write_all(
b"// This file is generated by getAccountState.sh. Do not edit it manually.\n\n",
)
.unwrap();
file.write_all(&rustfmt(rust_file).unwrap()).unwrap();
}
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-test
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/system-test/src/lib.rs
|
// placeholder
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/account-compression-test/Cargo.toml
|
[package]
name = "account-compression-test"
version = "1.1.0"
description = "Created with Anchor"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "account_compression_test"
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
test-sbf = []
custom-heap = []
default = ["custom-heap"]
[dependencies]
[dev-dependencies]
ark-bn254 = "0.4.0"
ark-ff = "0.4.0"
solana-program-test = { workspace = true}
light-test-utils = { version = "1.2.0", path = "../../test-utils", features=["devenv"] }
light-program-test = { workspace = true, features = ["devenv"] }
reqwest = "0.11.26"
tokio = { workspace = true }
light-prover-client = {path = "../../circuit-lib/light-prover-client" }
num-bigint = "0.4.6"
num-traits = "0.2.19"
spl-token = { workspace = true }
anchor-spl = { workspace = true }
anchor-lang = { workspace = true }
light-compressed-token = { workspace = true }
light-system-program = { workspace = true }
account-compression = { workspace = true }
light-hasher = {path = "../../merkle-tree/hasher"}
light-hash-set = { workspace = true}
light-concurrent-merkle-tree = {path = "../../merkle-tree/concurrent"}
light-indexed-merkle-tree = {path = "../../merkle-tree/indexed"}
light-merkle-tree-reference = {path = "../../merkle-tree/reference"}
light-bounded-vec = {path = "../../merkle-tree/bounded-vec"}
light-utils = {path = "../../utils"}
light-verifier = {path = "../../circuit-lib/verifier"}
rand = "0.8"
solana-cli-output = { workspace = true }
serde_json = "1.0.114"
solana-sdk = { workspace = true }
thiserror = "1.0"
memoffset = "0.9.1"
| 0
|
solana_public_repos/Lightprotocol/light-protocol/test-programs
|
solana_public_repos/Lightprotocol/light-protocol/test-programs/account-compression-test/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.