repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/Lightprotocol/light-protocol/macros/aligned-sized
solana_public_repos/Lightprotocol/light-protocol/macros/aligned-sized/src/expand.rs
use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use syn::{ parse::{Parse, ParseStream}, punctuated::Punctuated, ConstParam, Error, Field, Fields, FieldsNamed, GenericParam, ItemStruct, LifetimeParam, Meta, Result, Token, TypeParam, }; pub(crate) struct AlignedSizedArgs { /// Include Anchor discriminator (8 bytes). anchor: bool, } impl Parse for AlignedSizedArgs { fn parse(input: ParseStream) -> Result<Self> { let mut anchor = false; while !input.is_empty() { let ident: Ident = input.parse()?; match ident.to_string().as_str() { "anchor" => anchor = true, _ => return Err(input.error("Unsupported attribute")), } // If there's a comma, consume it, otherwise break out of the loop if input.peek(syn::token::Comma) { let _ = input.parse::<syn::token::Comma>(); } else { break; } } Ok(Self { anchor }) } } /// Provides an impelentation of `LEN` constant for the givent struct. pub(crate) fn aligned_sized(args: AlignedSizedArgs, strct: ItemStruct) -> Result<TokenStream> { let name = strct.clone().ident; // Expressions which define the size of each field. They can be: // // * `core::mem::size_of<T>()` calls - that's what we pick for fields without // attributes. // * Integer literals - either provided via `size` field attribute or // defined by us (Anchor discriminator). let mut field_size_getters = if args.anchor { // Add Anchor discriminator. let mut v = Vec::with_capacity(strct.fields.len() + 1); v.push(quote! { 8 }); v } else { Vec::with_capacity(strct.fields.len()) }; let mut fields = Punctuated::new(); // Iterate over all fields. Try to find the `size` attribute in them. If // not found, construct a `core::mem::size_of::<T>()` expression for field in strct.fields.iter() { // Attributes to reassign to the field. // We want to exclude our `#[size]` attribure here, because it might // annoy the compiler. To be safe, we need to remove it right after // consuming it. let mut attrs = Vec::with_capacity(field.attrs.len()); let mut include_type_size = true; // Iterate over attributes. for attr in field.attrs.iter() { // Check the type of attribute. We look for meta name attribute // with `size` key, e.g. `#[size = 128]`. // // For all other types, return an error. match attr.clone().meta { Meta::NameValue(name_value) => { if name_value.path.is_ident("size") { let value = name_value.value; field_size_getters.push(quote! { #value }); include_type_size = false; // Go to the next attribute. Do not include this one. continue; } // Include all other attributes. attrs.push(attr.to_owned()); } // Include all other attributes. _ => attrs.push(attr.to_owned()), } } if include_type_size { let ty = field.clone().ty; field_size_getters.push(quote! { ::core::mem::size_of::<#ty>() }); } let field = Field { attrs, vis: field.vis.clone(), mutability: field.mutability.clone(), ident: field.ident.clone(), colon_token: field.colon_token, ty: field.ty.clone(), }; fields.push(field); } // Replace fields to make sure that the updated struct definition doesn't // have fields with `size` attribute. let brace_token = match strct.fields { Fields::Named(fields_named) => fields_named.brace_token, _ => { return Err(Error::new( Span::call_site(), "Only structs with named fields are supported", )) } }; let fields = Fields::Named(FieldsNamed { brace_token, named: fields, }); let strct = ItemStruct { attrs: strct.attrs.clone(), vis: strct.vis.clone(), struct_token: strct.struct_token, ident: strct.ident.clone(), generics: strct.generics.clone(), // Exactly here. fields, semi_token: strct.semi_token, }; #[allow(clippy::redundant_clone)] let impl_generics = strct.generics.clone(); // Generics listed after struct ident need to contain only idents, bounds // and const generic types are not expected anymore. Sadly, there seems to // be no quick way to do that cleanup in non-manual way. let strct_generics: Punctuated<GenericParam, Token![,]> = strct .generics .params .clone() .into_iter() .map(|param: GenericParam| match param { GenericParam::Const(ConstParam { ident, .. }) | GenericParam::Type(TypeParam { ident, .. }) => GenericParam::Type(TypeParam { attrs: vec![], ident, colon_token: None, bounds: Default::default(), eq_token: None, default: None, }), GenericParam::Lifetime(LifetimeParam { lifetime, .. }) => { GenericParam::Lifetime(LifetimeParam { attrs: vec![], lifetime, colon_token: None, bounds: Default::default(), }) } }) .collect(); // Define a constant with the size of the struct (sum of all fields). Ok(quote! { #strct impl #impl_generics #name <#strct_generics> { pub const LEN: usize = #(#field_size_getters)+*; } }) } #[cfg(test)] mod tests { use syn::parse_quote; use super::*; #[test] fn sized_struct() { let test_struct: ItemStruct = parse_quote! { struct TestStruct { foo: u32, bar: u32, ayy: u16, lmao: u16, #[size = 128] kaboom: Vec<u8>, } }; let res_no_args = aligned_sized(parse_quote! {}, test_struct.clone()) .unwrap() .to_string(); println!("{res_no_args}"); assert!(res_no_args.contains(":: core :: mem :: size_of :: < u32 > ()")); assert!(res_no_args.contains(":: core :: mem :: size_of :: < u16 > ()")); assert!(res_no_args.contains(" 128 ")); let res_anchor = aligned_sized(parse_quote! { anchor }, test_struct) .unwrap() .to_string(); assert!(res_anchor.contains(" 8 ")); assert!(res_anchor.contains(":: core :: mem :: size_of :: < u32 > ()")); assert!(res_anchor.contains(":: core :: mem :: size_of :: < u16 > ()")); assert!(res_anchor.contains(" 128 ")); } }
0
solana_public_repos/Lightprotocol/light-protocol
solana_public_repos/Lightprotocol/light-protocol/programs/package.json
{ "name": "@lightprotocol/programs", "version": "0.3.0", "license": "Apache-2.0", "scripts": { "push-idls": "../scripts/push-stateless-js-idls.sh && ../scripts/push-compressed-token-idl.sh", "build": "anchor build", "build-idls": "anchor build && pnpm build-system && pnpm build-compressed-token && pnpm push-idls", "build-system": "anchor build --program-name light_system_program -- --features idl-build custom-heap", "build-compressed-token": "anchor build --program-name light_compressed_token -- --features idl-build custom-heap", "test": "pnpm test-account-compression && pnpm test-system && pnpm test-compressed-token && pnpm test-registry", "test-account-compression": "cargo-test-sbf -p account-compression-test -- --test-threads=1", "test-system": "cargo test-sbf -p system-test -- --test-threads=1", "test-compressed-token": "cargo test-sbf -p compressed-token-test -- --test-threads=1", "test-registry": "cargo-test-sbf -p registry-test -- --test-threads=1", "token-escrow": "cargo-test-sbf -p token-escrow -- --test-threads=1 --features idl-build", "program-owned-account-test": "cargo-test-sbf -p program-owned-account-test -- --test-threads=1", "random-e2e-test": "RUST_MIN_STACK=8388608 cargo-test-sbf -p e2e-test -- --nocapture --test-threads=1" }, "nx": { "targets": { "build": { "outputs": [ "{workspaceRoot}/target/deploy", "{workspaceRoot}/target/idl", "{workspaceRoot}/target/types" ] } } } }
0
solana_public_repos/Lightprotocol/light-protocol/programs
solana_public_repos/Lightprotocol/light-protocol/programs/system/Cargo.toml
[package] name = "light-system-program" version = "1.2.0" description = "ZK Compression on Solana" repository = "https://github.com/Lightprotocol/light-protocol" license = "Apache-2.0" edition = "2021" [lib] crate-type = ["cdylib", "lib"] name = "light_system_program" [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 = [] idl-build = ["anchor-lang/idl-build"] [dependencies] aligned-sized = { version = "1.1.0", path = "../../macros/aligned-sized" } anchor-lang = { workspace = true } light-hasher = { version = "1.1.0", path = "../../merkle-tree/hasher" } light-heap = { version = "1.1.0", path = "../../heap", optional = true } light-macros = { path = "../../macros/light", version = "1.1.0" } light-concurrent-merkle-tree = { path = "../../merkle-tree/concurrent", version = "1.1.0" } light-indexed-merkle-tree = { path = "../../merkle-tree/indexed", version = "1.1.0" } account-compression = { workspace = true } light-utils = { version = "1.1.0", path = "../../utils" } groth16-solana = "0.0.3" light-verifier = { path = "../../circuit-lib/verifier", version = "1.1.0", features = ["solana"] } solana-security-txt = "1.1.0" [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/system/Xargo.toml
[target.bpfel-unknown-unknown.dependencies.std] features = []
0
solana_public_repos/Lightprotocol/light-protocol/programs/system
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/constants.rs
pub const CPI_AUTHORITY_PDA_BUMP: u8 = 255;
0
solana_public_repos/Lightprotocol/light-protocol/programs/system
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/lib.rs
use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey}; pub mod invoke; pub use invoke::instruction::*; pub mod invoke_cpi; pub use invoke_cpi::{initialize::*, instruction::*}; pub mod constants; pub mod errors; pub mod sdk; pub mod utils; use errors::SystemProgramError; use sdk::event::PublicTransactionEvent; declare_id!("SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7"); #[cfg(not(feature = "no-entrypoint"))] solana_security_txt::security_txt! { name: "light_system_program", 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_system_program { use light_heap::{bench_sbf_end, bench_sbf_start}; use self::{ invoke::{processor::process, verify_signer::input_compressed_accounts_signer_check}, invoke_cpi::processor::process_invoke_cpi, }; use super::*; pub fn init_cpi_context_account(ctx: Context<InitializeCpiContextAccount>) -> Result<()> { // Check that Merkle tree is initialized. ctx.accounts.associated_merkle_tree.load()?; ctx.accounts .cpi_context_account .init(ctx.accounts.associated_merkle_tree.key()); Ok(()) } pub fn invoke<'a, 'b, 'c: 'info, 'info>( ctx: Context<'a, 'b, 'c, 'info, InvokeInstruction<'info>>, inputs: Vec<u8>, ) -> Result<()> { let inputs: InstructionDataInvoke = InstructionDataInvoke::deserialize(&mut inputs.as_slice())?; input_compressed_accounts_signer_check( &inputs.input_compressed_accounts_with_merkle_context, &ctx.accounts.authority.key(), )?; process(inputs, None, ctx, 0) } pub fn invoke_cpi<'a, 'b, 'c: 'info, 'info>( ctx: Context<'a, 'b, 'c, 'info, InvokeCpiInstruction<'info>>, inputs: Vec<u8>, ) -> Result<()> { bench_sbf_start!("cpda_deserialize"); let inputs: InstructionDataInvokeCpi = InstructionDataInvokeCpi::deserialize(&mut inputs.as_slice())?; bench_sbf_end!("cpda_deserialize"); process_invoke_cpi(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, InvokeInstruction<'info>>, _inputs1: InstructionDataInvoke, _inputs2: InstructionDataInvokeCpi, _inputs3: PublicTransactionEvent, ) -> Result<()> { Err(SystemProgramError::InstructionNotCallable.into()) } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/errors.rs
use anchor_lang::prelude::*; #[error_code] pub enum SystemProgramError { #[msg("Sum check failed")] SumCheckFailed, #[msg("Signer check failed")] SignerCheckFailed, #[msg("Cpi signer check failed")] CpiSignerCheckFailed, #[msg("Computing input sum failed.")] ComputeInputSumFailed, #[msg("Computing output sum failed.")] ComputeOutputSumFailed, #[msg("Computing rpc sum failed.")] ComputeRpcSumFailed, #[msg("InvalidAddress")] InvalidAddress, #[msg("DeriveAddressError")] DeriveAddressError, #[msg("CompressedSolPdaUndefinedForCompressSol")] CompressedSolPdaUndefinedForCompressSol, #[msg("DeCompressLamportsUndefinedForCompressSol")] DeCompressLamportsUndefinedForCompressSol, #[msg("CompressedSolPdaUndefinedForDecompressSol")] CompressedSolPdaUndefinedForDecompressSol, #[msg("DeCompressLamportsUndefinedForDecompressSol")] DeCompressLamportsUndefinedForDecompressSol, #[msg("DecompressRecipientUndefinedForDecompressSol")] DecompressRecipientUndefinedForDecompressSol, #[msg("WriteAccessCheckFailed")] WriteAccessCheckFailed, #[msg("InvokingProgramNotProvided")] InvokingProgramNotProvided, #[msg("InvalidCapacity")] InvalidCapacity, #[msg("InvalidMerkleTreeOwner")] InvalidMerkleTreeOwner, #[msg("ProofIsNone")] ProofIsNone, #[msg("Proof is some but no input compressed accounts or new addresses provided.")] ProofIsSome, #[msg("EmptyInputs")] EmptyInputs, #[msg("CpiContextAccountUndefined")] CpiContextAccountUndefined, #[msg("CpiContextEmpty")] CpiContextEmpty, #[msg("CpiContextMissing")] CpiContextMissing, #[msg("DecompressionRecipientDefined")] DecompressionRecipientDefined, #[msg("SolPoolPdaDefined")] SolPoolPdaDefined, #[msg("AppendStateFailed")] AppendStateFailed, #[msg("The instruction is not callable")] InstructionNotCallable, #[msg("CpiContextFeePayerMismatch")] CpiContextFeePayerMismatch, #[msg("CpiContextAssociatedMerkleTreeMismatch")] CpiContextAssociatedMerkleTreeMismatch, #[msg("NoInputs")] NoInputs, #[msg("Input merkle tree indices are not in ascending order.")] InputMerkleTreeIndicesNotInOrder, #[msg("Output merkle tree indices are not in ascending order.")] OutputMerkleTreeIndicesNotInOrder, OutputMerkleTreeNotUnique, DataFieldUndefined, }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/utils.rs
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED; use anchor_lang::solana_program::pubkey::Pubkey; 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 fn get_cpi_authority_pda(program_id: &Pubkey) -> Pubkey { Pubkey::find_program_address(&[CPI_AUTHORITY_PDA_SEED], program_id).0 }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/processor.rs
use account_compression::utils::transfer_lamports::transfer_lamports_cpi; use anchor_lang::{prelude::*, Bumps}; use light_heap::{bench_sbf_end, bench_sbf_start}; use light_verifier::CompressedProof as CompressedVerifierProof; use crate::{ errors::SystemProgramError, invoke::{ address::{derive_new_addresses, insert_addresses_into_address_merkle_tree_queue}, append_state::insert_output_compressed_accounts_into_state_merkle_tree, emit_event::emit_state_transition_event, nullify_state::insert_nullifiers, sol_compression::compress_or_decompress_lamports, sum_check::sum_check, verify_state_proof::{ fetch_input_compressed_account_roots, fetch_roots_address_merkle_tree, hash_input_compressed_accounts, verify_state_proof, }, }, sdk::accounts::{InvokeAccounts, SignerAccounts}, InstructionDataInvoke, }; // TODO: remove once upgraded to anchor 0.30.0 (right now it's required for idl generation) #[derive(Debug, Clone, PartialEq, Eq, AnchorSerialize, AnchorDeserialize)] pub struct CompressedProof { pub a: [u8; 32], pub b: [u8; 64], pub c: [u8; 32], } impl Default for CompressedProof { fn default() -> Self { Self { a: [0; 32], b: [0; 64], c: [0; 32], } } } /// Steps: /// 1. Sum check /// 2. Compression lamports /// 3. Verify state inclusion & address non-inclusion proof /// 4. Insert nullifiers /// 5. Insert output compressed accounts into state Merkle tree /// 6. Emit state transition event pub fn process< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( mut inputs: InstructionDataInvoke, invoking_program: Option<Pubkey>, ctx: Context<'a, 'b, 'c, 'info, A>, cpi_context_inputs: usize, ) -> Result<()> { if inputs.relay_fee.is_some() { unimplemented!("Relay fee is not implemented yet."); } // Sum check --------------------------------------------------- bench_sbf_start!("cpda_sum_check"); sum_check( &inputs.input_compressed_accounts_with_merkle_context, &inputs.output_compressed_accounts, &inputs.relay_fee, &inputs.compress_or_decompress_lamports, &inputs.is_compress, )?; bench_sbf_end!("cpda_sum_check"); // Compress or decompress lamports --------------------------------------------------- bench_sbf_start!("cpda_process_compression"); if inputs.compress_or_decompress_lamports.is_some() { if inputs.is_compress && ctx.accounts.get_decompression_recipient().is_some() { return err!(SystemProgramError::DecompressionRecipientDefined); } compress_or_decompress_lamports(&inputs, &ctx)?; } else if ctx.accounts.get_decompression_recipient().is_some() { return err!(SystemProgramError::DecompressionRecipientDefined); } else if ctx.accounts.get_sol_pool_pda().is_some() { return err!(SystemProgramError::SolPoolPdaDefined); } bench_sbf_end!("cpda_process_compression"); // Allocate heap memory here so that we can free memory after function invocations. let num_input_compressed_accounts = inputs.input_compressed_accounts_with_merkle_context.len(); let num_new_addresses = inputs.new_address_params.len(); let num_output_compressed_accounts = inputs.output_compressed_accounts.len(); let mut input_compressed_account_hashes = vec![[0u8; 32]; num_input_compressed_accounts]; let mut compressed_account_addresses: Vec<Option<[u8; 32]>> = vec![None; num_input_compressed_accounts + num_new_addresses]; let mut output_leaf_indices = vec![0u32; num_output_compressed_accounts]; let mut output_compressed_account_hashes = vec![[0u8; 32]; num_output_compressed_accounts]; // hashed_pubkeys_capacity is the maximum of hashed pubkey the tx could have. // 1 owner pubkey inputs + every remaining account pubkey can be a tree + every output can be owned by a different pubkey // + number of times cpi context account was filled. let hashed_pubkeys_capacity = 1 + ctx.remaining_accounts.len() + num_output_compressed_accounts + cpi_context_inputs; let mut hashed_pubkeys = Vec::<(Pubkey, [u8; 32])>::with_capacity(hashed_pubkeys_capacity); // Verify state and or address proof --------------------------------------------------- if !inputs .input_compressed_accounts_with_merkle_context .is_empty() || !inputs.new_address_params.is_empty() { // Allocate heap memory here because roots are only used for proof verification. let mut new_address_roots = vec![[0u8; 32]; num_new_addresses]; let mut input_compressed_account_roots = vec![[0u8; 32]; num_input_compressed_accounts]; // hash input compressed accounts --------------------------------------------------- bench_sbf_start!("cpda_hash_input_compressed_accounts"); if !inputs .input_compressed_accounts_with_merkle_context .is_empty() { hash_input_compressed_accounts( ctx.remaining_accounts, &inputs.input_compressed_accounts_with_merkle_context, &mut input_compressed_account_hashes, &mut compressed_account_addresses, &mut hashed_pubkeys, )?; // # Safety this is a safeguard for memory safety. // This error should never be triggered. if hashed_pubkeys.capacity() != hashed_pubkeys_capacity { msg!( "hashed_pubkeys exceeded capacity. Used {}, allocated {}.", hashed_pubkeys.capacity(), hashed_pubkeys_capacity ); return err!(SystemProgramError::InvalidCapacity); } fetch_input_compressed_account_roots( &inputs.input_compressed_accounts_with_merkle_context, &ctx, &mut input_compressed_account_roots, )?; } bench_sbf_end!("cpda_hash_input_compressed_accounts"); let mut new_addresses = vec![[0u8; 32]; num_new_addresses]; // Insert addresses into address merkle tree queue --------------------------------------------------- if !new_addresses.is_empty() { derive_new_addresses( &inputs.new_address_params, num_input_compressed_accounts, ctx.remaining_accounts, &mut compressed_account_addresses, &mut new_addresses, )?; let network_fee_bundle = insert_addresses_into_address_merkle_tree_queue( &ctx, &new_addresses, &inputs.new_address_params, &invoking_program, )?; if let Some(network_fee_bundle) = network_fee_bundle { let (remaining_account_index, network_fee) = network_fee_bundle; transfer_lamports_cpi( ctx.accounts.get_fee_payer(), &ctx.remaining_accounts[remaining_account_index as usize], network_fee, )?; } fetch_roots_address_merkle_tree( &inputs.new_address_params, &ctx, &mut new_address_roots, )?; } bench_sbf_start!("cpda_verify_state_proof"); let proof = match &inputs.proof { Some(proof) => proof, None => return err!(SystemProgramError::ProofIsNone), }; let compressed_verifier_proof = CompressedVerifierProof { a: proof.a, b: proof.b, c: proof.c, }; match verify_state_proof( &input_compressed_account_roots, &input_compressed_account_hashes, &new_address_roots, &new_addresses, &compressed_verifier_proof, ) { Ok(_) => Ok(()), Err(e) => { msg!( "input_compressed_accounts_with_merkle_context: {:?}", inputs.input_compressed_accounts_with_merkle_context ); Err(e) } }?; bench_sbf_end!("cpda_verify_state_proof"); // insert nullifiers (input compressed account hashes)--------------------------------------------------- bench_sbf_start!("cpda_nullifiers"); if !inputs .input_compressed_accounts_with_merkle_context .is_empty() { let network_fee_bundle = insert_nullifiers( &inputs, &ctx, &input_compressed_account_hashes, &invoking_program, )?; if let Some(network_fee_bundle) = network_fee_bundle { let (remaining_account_index, network_fee) = network_fee_bundle; transfer_lamports_cpi( ctx.accounts.get_fee_payer(), &ctx.remaining_accounts[remaining_account_index as usize], network_fee, )?; } } bench_sbf_end!("cpda_nullifiers"); } else if inputs.proof.is_some() { return err!(SystemProgramError::ProofIsSome); } else if inputs .input_compressed_accounts_with_merkle_context .is_empty() && inputs.new_address_params.is_empty() && inputs.output_compressed_accounts.is_empty() { return err!(SystemProgramError::EmptyInputs); } bench_sbf_end!("cpda_nullifiers"); // Allocate space for sequence numbers with remaining account length as a // proxy. We cannot allocate heap memory in // insert_output_compressed_accounts_into_state_merkle_tree because it is // heap neutral. let mut sequence_numbers = Vec::with_capacity(ctx.remaining_accounts.len()); // Insert leaves (output compressed account hashes) --------------------------------------------------- if !inputs.output_compressed_accounts.is_empty() { bench_sbf_start!("cpda_append"); insert_output_compressed_accounts_into_state_merkle_tree( &mut inputs.output_compressed_accounts, &ctx, &mut output_leaf_indices, &mut output_compressed_account_hashes, &mut compressed_account_addresses, &invoking_program, &mut hashed_pubkeys, &mut sequence_numbers, )?; // # Safety this is a safeguard for memory safety. // This error should never be triggered. if hashed_pubkeys.capacity() != hashed_pubkeys_capacity { msg!( "hashed_pubkeys exceeded capacity. Used {}, allocated {}.", hashed_pubkeys.capacity(), hashed_pubkeys_capacity ); return err!(SystemProgramError::InvalidCapacity); } bench_sbf_end!("cpda_append"); } bench_sbf_start!("emit_state_transition_event"); // Reduce the capacity of the sequence numbers vector. sequence_numbers.shrink_to_fit(); // Emit state transition event --------------------------------------------------- bench_sbf_start!("emit_state_transition_event"); emit_state_transition_event( inputs, &ctx, input_compressed_account_hashes, output_compressed_account_hashes, output_leaf_indices, sequence_numbers, )?; bench_sbf_end!("emit_state_transition_event"); Ok(()) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/nullify_state.rs
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED; use anchor_lang::{prelude::*, solana_program::pubkey::Pubkey, Bumps, InstructionData}; use light_macros::heap_neutral; use crate::{ constants::CPI_AUTHORITY_PDA_BUMP, invoke::InstructionDataInvoke, invoke_cpi::verify_signer::check_program_owner_state_merkle_tree, sdk::accounts::{InvokeAccounts, SignerAccounts}, }; /// 1. Checks that if nullifier queue has program_owner it invoking_program is /// program_owner. /// 2. Inserts nullifiers into the queue. #[heap_neutral] pub fn insert_nullifiers< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( inputs: &'a InstructionDataInvoke, ctx: &'a Context<'a, 'b, 'c, 'info, A>, nullifiers: &'a [[u8; 32]], invoking_program: &Option<Pubkey>, ) -> Result<Option<(u8, u64)>> { light_heap::bench_sbf_start!("cpda_insert_nullifiers_prep_accs"); let mut account_infos = vec![ ctx.accounts.get_fee_payer().to_account_info(), ctx.accounts .get_account_compression_authority() .to_account_info(), ctx.accounts.get_registered_program_pda().to_account_info(), ctx.accounts.get_system_program().to_account_info(), ]; let mut accounts = vec![ AccountMeta { pubkey: account_infos[0].key(), is_signer: true, is_writable: true, }, AccountMeta::new_readonly(account_infos[1].key(), true), AccountMeta::new_readonly(account_infos[2].key(), false), AccountMeta::new_readonly(account_infos[3].key(), false), ]; // If the transaction contains at least one input compressed account a // network fee is paid. This network fee is paid in addition to the address // network fee. The network fee is paid once per transaction, defined in the // state Merkle tree and transferred to the nullifier queue because the // nullifier queue is mutable. The network fee field in the queue is not // used. let mut network_fee_bundle = None; for account in inputs.input_compressed_accounts_with_merkle_context.iter() { let account_info = &ctx.remaining_accounts[account.merkle_context.nullifier_queue_pubkey_index as usize]; accounts.push(AccountMeta { pubkey: account_info.key(), is_signer: false, is_writable: true, }); account_infos.push(account_info.clone()); let (_, network_fee, _) = check_program_owner_state_merkle_tree( &ctx.remaining_accounts[account.merkle_context.merkle_tree_pubkey_index as usize], invoking_program, )?; if network_fee_bundle.is_none() && network_fee.is_some() { network_fee_bundle = Some(( account.merkle_context.nullifier_queue_pubkey_index, network_fee.unwrap(), )); } let account_info = &ctx.remaining_accounts[account.merkle_context.merkle_tree_pubkey_index as usize]; accounts.push(AccountMeta { pubkey: account_info.key(), is_signer: false, is_writable: false, }); account_infos.push(account_info.clone()); } light_heap::bench_sbf_end!("cpda_insert_nullifiers_prep_accs"); light_heap::bench_sbf_start!("cpda_instruction_data"); let instruction_data = account_compression::instruction::InsertIntoNullifierQueues { nullifiers: nullifiers.to_vec(), }; let data = instruction_data.data(); light_heap::bench_sbf_end!("cpda_instruction_data"); let bump = &[CPI_AUTHORITY_PDA_BUMP]; let seeds = &[&[CPI_AUTHORITY_PDA_SEED, bump][..]]; let instruction = anchor_lang::solana_program::instruction::Instruction { program_id: account_compression::ID, accounts, data, }; anchor_lang::solana_program::program::invoke_signed( &instruction, account_infos.as_slice(), seeds, )?; Ok(network_fee_bundle) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/sol_compression.rs
use account_compression::utils::transfer_lamports::transfer_lamports_cpi; use aligned_sized::*; use anchor_lang::{ prelude::*, solana_program::{account_info::AccountInfo, pubkey::Pubkey}, Bumps, }; use crate::{ errors::SystemProgramError, sdk::accounts::{InvokeAccounts, SignerAccounts}, InstructionDataInvoke, }; #[account] #[aligned_sized(anchor)] pub struct CompressedSolPda {} #[constant] pub const SOL_POOL_PDA_SEED: &[u8] = b"sol_pool_pda"; pub fn compress_or_decompress_lamports< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( inputs: &'a InstructionDataInvoke, ctx: &'a Context<'a, 'b, 'c, 'info, A>, ) -> Result<()> { if inputs.is_compress { compress_lamports(inputs, ctx) } else { decompress_lamports(inputs, ctx) } } pub fn decompress_lamports< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( inputs: &'a InstructionDataInvoke, ctx: &'a Context<'a, 'b, 'c, 'info, A>, ) -> Result<()> { let recipient = match ctx.accounts.get_decompression_recipient().as_ref() { Some(decompression_recipient) => decompression_recipient.to_account_info(), None => return err!(SystemProgramError::DecompressRecipientUndefinedForDecompressSol), }; let sol_pool_pda = match ctx.accounts.get_sol_pool_pda().as_ref() { Some(sol_pool_pda) => sol_pool_pda.to_account_info(), None => return err!(SystemProgramError::CompressedSolPdaUndefinedForDecompressSol), }; let lamports = match inputs.compress_or_decompress_lamports { Some(lamports) => lamports, None => return err!(SystemProgramError::DeCompressLamportsUndefinedForDecompressSol), }; transfer_lamports(&sol_pool_pda, &recipient, lamports) } pub fn compress_lamports< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( inputs: &'a InstructionDataInvoke, ctx: &'a Context<'a, 'b, 'c, 'info, A>, ) -> Result<()> { let recipient = match ctx.accounts.get_sol_pool_pda().as_ref() { Some(sol_pool_pda) => sol_pool_pda.to_account_info(), None => return err!(SystemProgramError::CompressedSolPdaUndefinedForCompressSol), }; let lamports = match inputs.compress_or_decompress_lamports { Some(lamports) => lamports, None => return err!(SystemProgramError::DeCompressLamportsUndefinedForCompressSol), }; transfer_lamports_cpi( &ctx.accounts.get_fee_payer().to_account_info(), &recipient, lamports, ) } pub fn transfer_lamports<'info>( from: &AccountInfo<'info>, to: &AccountInfo<'info>, lamports: u64, ) -> Result<()> { let instruction = anchor_lang::solana_program::system_instruction::transfer(from.key, to.key, lamports); let (_, bump) = anchor_lang::prelude::Pubkey::find_program_address(&[SOL_POOL_PDA_SEED], &crate::ID); let bump = &[bump]; let seeds = &[&[SOL_POOL_PDA_SEED, bump][..]]; anchor_lang::solana_program::program::invoke_signed( &instruction, &[from.clone(), to.clone()], seeds, )?; Ok(()) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/verify_signer.rs
use anchor_lang::{ err, solana_program::{msg, pubkey::Pubkey}, Result, }; use crate::{ errors::SystemProgramError, sdk::compressed_account::PackedCompressedAccountWithMerkleContext, }; pub fn input_compressed_accounts_signer_check( input_compressed_accounts_with_merkle_context: &[PackedCompressedAccountWithMerkleContext], authority: &Pubkey, ) -> Result<()> { input_compressed_accounts_with_merkle_context .iter() .try_for_each( |compressed_account_with_context: &PackedCompressedAccountWithMerkleContext| { if compressed_account_with_context.compressed_account.owner == *authority && compressed_account_with_context .compressed_account .data .is_none() { Ok(()) } else { msg!( "signer check failed compressed account owner {} != authority {} or data is not none {} (only programs can own compressed accounts with data)", compressed_account_with_context.compressed_account.owner, authority, compressed_account_with_context.compressed_account.data.is_none() ); err!(SystemProgramError::SignerCheckFailed) } }, ) } #[cfg(test)] mod test { use super::*; use crate::sdk::compressed_account::CompressedAccount; #[test] fn test_input_compressed_accounts_signer_check() { let authority = Pubkey::new_unique(); let compressed_account_with_context = PackedCompressedAccountWithMerkleContext { compressed_account: CompressedAccount { owner: authority, ..CompressedAccount::default() }, ..PackedCompressedAccountWithMerkleContext::default() }; assert_eq!( input_compressed_accounts_signer_check( &vec![compressed_account_with_context.clone()], &authority ), Ok(()) ); let invalid_compressed_account_with_context = PackedCompressedAccountWithMerkleContext { compressed_account: CompressedAccount { owner: Pubkey::new_unique(), ..CompressedAccount::default() }, ..PackedCompressedAccountWithMerkleContext::default() }; assert_eq!( input_compressed_accounts_signer_check( &vec![ compressed_account_with_context, invalid_compressed_account_with_context ], &authority ), Err(SystemProgramError::SignerCheckFailed.into()) ); } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/address.rs
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED; use anchor_lang::{prelude::*, Bumps}; use crate::{ constants::CPI_AUTHORITY_PDA_BUMP, invoke_cpi::verify_signer::check_program_owner_address_merkle_tree, sdk::{ accounts::{InvokeAccounts, SignerAccounts}, address::derive_address, }, NewAddressParamsPacked, }; pub fn derive_new_addresses( new_address_params: &[NewAddressParamsPacked], num_input_compressed_accounts: usize, remaining_accounts: &[AccountInfo], compressed_account_addresses: &mut [Option<[u8; 32]>], new_addresses: &mut [[u8; 32]], ) -> Result<()> { new_address_params .iter() .enumerate() .try_for_each(|(i, new_address_params)| { let address = derive_address( &remaining_accounts[new_address_params.address_merkle_tree_account_index as usize] .key(), &new_address_params.seed, ) .map_err(ProgramError::from)?; // We are inserting addresses into two vectors to avoid unwrapping // the option in following functions. compressed_account_addresses[i + num_input_compressed_accounts] = Some(address); new_addresses[i] = address; Ok(()) }) } pub fn insert_addresses_into_address_merkle_tree_queue< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( ctx: &'a Context<'a, 'b, 'c, 'info, A>, addresses: &'a [[u8; 32]], new_address_params: &'a [NewAddressParamsPacked], invoking_program: &Option<Pubkey>, ) -> anchor_lang::Result<Option<(u8, u64)>> { let mut remaining_accounts = Vec::<AccountInfo>::with_capacity(new_address_params.len() * 2); let mut network_fee_bundle = None; new_address_params.iter().try_for_each(|params| { remaining_accounts .push(ctx.remaining_accounts[params.address_queue_account_index as usize].clone()); remaining_accounts.push( ctx.remaining_accounts[params.address_merkle_tree_account_index as usize].clone(), ); // If at least one new address is created an address network fee is // paid.The network fee is paid once per transaction, defined in the // state Merkle tree and transferred to the nullifier queue because the // nullifier queue is mutable. The network fee field in the queue is not // used. let network_fee = check_program_owner_address_merkle_tree( &ctx.remaining_accounts[params.address_merkle_tree_account_index as usize], invoking_program, )?; // We select the first network fee we find. All Merkle trees are // initialized with the same network fee. if network_fee_bundle.is_none() && network_fee.is_some() { network_fee_bundle = Some((params.address_queue_account_index, network_fee.unwrap())); } anchor_lang::Result::Ok(()) })?; insert_addresses_cpi( ctx.accounts.get_account_compression_program(), &ctx.accounts.get_fee_payer().to_account_info(), ctx.accounts.get_account_compression_authority(), &ctx.accounts.get_registered_program_pda().to_account_info(), &ctx.accounts.get_system_program().to_account_info(), remaining_accounts, addresses.to_vec(), )?; Ok(network_fee_bundle) } #[allow(clippy::too_many_arguments)] pub fn insert_addresses_cpi<'a, 'b>( account_compression_program_id: &'b AccountInfo<'a>, fee_payer: &'b AccountInfo<'a>, authority: &'b AccountInfo<'a>, registered_program_pda: &'b AccountInfo<'a>, system_program: &'b AccountInfo<'a>, remaining_accounts: Vec<AccountInfo<'a>>, addresses: Vec<[u8; 32]>, ) -> Result<()> { let bump = &[CPI_AUTHORITY_PDA_BUMP]; let seeds = &[&[CPI_AUTHORITY_PDA_SEED, bump][..]]; let accounts = account_compression::cpi::accounts::InsertIntoQueues { fee_payer: fee_payer.to_account_info(), authority: authority.to_account_info(), registered_program_pda: Some(registered_program_pda.to_account_info()), system_program: system_program.to_account_info(), }; let mut cpi_ctx = CpiContext::new_with_signer(account_compression_program_id.clone(), accounts, seeds); cpi_ctx.remaining_accounts.extend(remaining_accounts); account_compression::cpi::insert_addresses(cpi_ctx, addresses) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/verify_state_proof.rs
use crate::{ sdk::{accounts::InvokeAccounts, compressed_account::PackedCompressedAccountWithMerkleContext}, NewAddressParamsPacked, }; use account_compression::{ utils::check_discrimininator::check_discriminator, AddressMerkleTreeAccount, StateMerkleTreeAccount, }; use anchor_lang::{prelude::*, Bumps}; use light_concurrent_merkle_tree::zero_copy::ConcurrentMerkleTreeZeroCopy; use light_hasher::Poseidon; use light_indexed_merkle_tree::zero_copy::IndexedMerkleTreeZeroCopy; use light_macros::heap_neutral; use light_utils::hash_to_bn254_field_size_be; use light_verifier::{ verify_create_addresses_and_merkle_proof_zkp, verify_create_addresses_zkp, verify_merkle_proof_zkp, CompressedProof, }; use std::mem; #[inline(never)] #[heap_neutral] pub fn fetch_input_compressed_account_roots< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + Bumps, >( input_compressed_accounts_with_merkle_context: &'a [PackedCompressedAccountWithMerkleContext], ctx: &'a Context<'a, 'b, 'c, 'info, A>, roots: &'a mut [[u8; 32]], ) -> Result<()> { for (i, input_compressed_account_with_context) in input_compressed_accounts_with_merkle_context .iter() .enumerate() { let merkle_tree = &ctx.remaining_accounts[input_compressed_account_with_context .merkle_context .merkle_tree_pubkey_index as usize]; let merkle_tree = merkle_tree.try_borrow_data()?; check_discriminator::<StateMerkleTreeAccount>(&merkle_tree)?; let merkle_tree = ConcurrentMerkleTreeZeroCopy::<Poseidon, 26>::from_bytes_zero_copy( &merkle_tree[8 + mem::size_of::<StateMerkleTreeAccount>()..], ) .map_err(ProgramError::from)?; let fetched_roots = &merkle_tree.roots; roots[i] = fetched_roots[input_compressed_account_with_context.root_index as usize]; } Ok(()) } #[inline(never)] #[heap_neutral] pub fn fetch_roots_address_merkle_tree< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + Bumps, >( new_address_params: &'a [NewAddressParamsPacked], ctx: &'a Context<'a, 'b, 'c, 'info, A>, roots: &'a mut [[u8; 32]], ) -> Result<()> { for (i, new_address_param) in new_address_params.iter().enumerate() { let merkle_tree = ctx.remaining_accounts [new_address_param.address_merkle_tree_account_index as usize] .to_account_info(); let merkle_tree = merkle_tree.try_borrow_data()?; check_discriminator::<AddressMerkleTreeAccount>(&merkle_tree)?; let merkle_tree = IndexedMerkleTreeZeroCopy::<Poseidon, usize, 26, 16>::from_bytes_zero_copy( &merkle_tree[8 + mem::size_of::<AddressMerkleTreeAccount>()..], ) .map_err(ProgramError::from)?; let fetched_roots = &merkle_tree.roots; roots[i] = fetched_roots[new_address_param.address_merkle_tree_root_index as usize]; } Ok(()) } /// Hashes the input compressed accounts and stores the results in the leaves array. /// Merkle tree pubkeys are hashed and stored in the hashed_pubkeys array. /// Merkle tree pubkeys should be ordered for efficiency. #[inline(never)] #[heap_neutral] #[allow(unused_mut)] pub fn hash_input_compressed_accounts<'a, 'b, 'c: 'info, 'info>( remaining_accounts: &'a [AccountInfo<'info>], input_compressed_accounts_with_merkle_context: &'a [PackedCompressedAccountWithMerkleContext], leaves: &'a mut [[u8; 32]], addresses: &'a mut [Option<[u8; 32]>], hashed_pubkeys: &'a mut Vec<(Pubkey, [u8; 32])>, ) -> Result<()> { let mut owner_pubkey = input_compressed_accounts_with_merkle_context[0] .compressed_account .owner; let mut hashed_owner = hash_to_bn254_field_size_be(&owner_pubkey.to_bytes()) .unwrap() .0; hashed_pubkeys.push((owner_pubkey, hashed_owner)); #[allow(unused)] let mut current_hashed_mt = [0u8; 32]; let mut current_mt_index: i16 = -1; for (j, input_compressed_account_with_context) in input_compressed_accounts_with_merkle_context .iter() .enumerate() { // For heap neutrality we cannot allocate new heap memory in this function. match &input_compressed_account_with_context .compressed_account .address { Some(address) => addresses[j] = Some(*address), None => {} }; if input_compressed_account_with_context .merkle_context .queue_index .is_some() { unimplemented!("Queue index is not supported."); } #[allow(clippy::comparison_chain)] if current_mt_index != input_compressed_account_with_context .merkle_context .merkle_tree_pubkey_index as i16 { current_mt_index = input_compressed_account_with_context .merkle_context .merkle_tree_pubkey_index as i16; let merkle_tree_pubkey = remaining_accounts[input_compressed_account_with_context .merkle_context .merkle_tree_pubkey_index as usize] .key(); current_hashed_mt = match hashed_pubkeys.iter().find(|x| x.0 == merkle_tree_pubkey) { Some(hashed_merkle_tree_pubkey) => hashed_merkle_tree_pubkey.1, None => { let hashed_merkle_tree_pubkey = hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0; hashed_pubkeys.push((merkle_tree_pubkey, hashed_merkle_tree_pubkey)); hashed_merkle_tree_pubkey } }; } // Without cpi context all input compressed accounts have the same owner. // With cpi context the owners will be different. if owner_pubkey != input_compressed_account_with_context .compressed_account .owner { owner_pubkey = input_compressed_account_with_context .compressed_account .owner; hashed_owner = match hashed_pubkeys.iter().find(|x| { x.0 == input_compressed_account_with_context .compressed_account .owner }) { Some(hashed_owner) => hashed_owner.1, None => { let hashed_owner = hash_to_bn254_field_size_be( &input_compressed_account_with_context .compressed_account .owner .to_bytes(), ) .unwrap() .0; hashed_pubkeys.push(( input_compressed_account_with_context .compressed_account .owner, hashed_owner, )); hashed_owner } }; } leaves[j] = input_compressed_account_with_context .compressed_account .hash_with_hashed_values::<Poseidon>( &hashed_owner, &current_hashed_mt, &input_compressed_account_with_context .merkle_context .leaf_index, )?; } Ok(()) } #[heap_neutral] pub fn verify_state_proof( roots: &[[u8; 32]], leaves: &[[u8; 32]], address_roots: &[[u8; 32]], addresses: &[[u8; 32]], compressed_proof: &CompressedProof, ) -> anchor_lang::Result<()> { if !addresses.is_empty() && !leaves.is_empty() { verify_create_addresses_and_merkle_proof_zkp( roots, leaves, address_roots, addresses, compressed_proof, ) .map_err(ProgramError::from)?; } else if !addresses.is_empty() { verify_create_addresses_zkp(address_roots, addresses, compressed_proof) .map_err(ProgramError::from)?; } else { verify_merkle_proof_zkp(roots, leaves, compressed_proof).map_err(ProgramError::from)?; } Ok(()) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/mod.rs
pub mod instruction; pub use instruction::*; pub mod address; pub mod append_state; pub mod emit_event; pub mod nullify_state; pub mod processor; pub mod sol_compression; pub mod sum_check; pub mod verify_signer; pub mod verify_state_proof;
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/append_state.rs
use account_compression::utils::constants::CPI_AUTHORITY_PDA_SEED; use anchor_lang::{ prelude::*, solana_program::{program::invoke_signed, pubkey::Pubkey}, Bumps, }; use light_hasher::Poseidon; use light_heap::{bench_sbf_end, bench_sbf_start}; use light_macros::heap_neutral; use light_utils::hash_to_bn254_field_size_be; use crate::{ constants::CPI_AUTHORITY_PDA_BUMP, errors::SystemProgramError, invoke_cpi::verify_signer::check_program_owner_state_merkle_tree, sdk::{ accounts::{InvokeAccounts, SignerAccounts}, event::MerkleTreeSequenceNumber, }, OutputCompressedAccountWithPackedContext, }; #[allow(clippy::too_many_arguments)] #[heap_neutral] pub fn insert_output_compressed_accounts_into_state_merkle_tree< 'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + SignerAccounts<'info> + Bumps, >( output_compressed_accounts: &mut [OutputCompressedAccountWithPackedContext], ctx: &'a Context<'a, 'b, 'c, 'info, A>, output_compressed_account_indices: &'a mut [u32], output_compressed_account_hashes: &'a mut [[u8; 32]], compressed_account_addresses: &'a mut Vec<Option<[u8; 32]>>, invoking_program: &Option<Pubkey>, hashed_pubkeys: &'a mut Vec<(Pubkey, [u8; 32])>, sequence_numbers: &'a mut Vec<MerkleTreeSequenceNumber>, ) -> Result<()> { bench_sbf_start!("cpda_append_data_init"); let mut account_infos = vec![ ctx.accounts.get_fee_payer().to_account_info(), // fee payer ctx.accounts .get_account_compression_authority() // authority .to_account_info(), ctx.accounts.get_registered_program_pda().to_account_info(), ctx.accounts.get_system_program().to_account_info(), ]; let mut 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::new_readonly(account_infos[2].key(), false), AccountMeta::new_readonly(account_infos[3].key(), false), ]; let instruction_data = create_cpi_accounts_and_instruction_data( output_compressed_accounts, output_compressed_account_indices, output_compressed_account_hashes, compressed_account_addresses, invoking_program, hashed_pubkeys, sequence_numbers, ctx.remaining_accounts, &mut account_infos, &mut accounts, )?; let bump = &[CPI_AUTHORITY_PDA_BUMP]; let seeds = &[&[CPI_AUTHORITY_PDA_SEED, bump][..]]; let instruction = anchor_lang::solana_program::instruction::Instruction { program_id: account_compression::ID, accounts, data: instruction_data, }; invoke_signed(&instruction, account_infos.as_slice(), seeds)?; bench_sbf_end!("cpda_append_rest"); Ok(()) } /// Creates CPI accounts, instruction data, and performs checks. /// - Merkle tree indices must be in order. /// - Hashes output accounts for insertion and event. /// - Collects sequence numbers for event. /// /// Checks: /// 1. Checks whether a Merkle tree is program owned, if so checks write /// eligibility. /// 2. Checks ordering of Merkle tree indices. /// 3. Checks that addresses in output compressed accounts have been created or /// exist in input compressed accounts. An address may not be used in an /// output compressed accounts. This will close the account. #[allow(clippy::too_many_arguments)] pub fn create_cpi_accounts_and_instruction_data<'a>( output_compressed_accounts: &[OutputCompressedAccountWithPackedContext], output_compressed_account_indices: &mut [u32], output_compressed_account_hashes: &mut [[u8; 32]], compressed_account_addresses: &mut Vec<Option<[u8; 32]>>, invoking_program: &Option<Pubkey>, hashed_pubkeys: &mut Vec<(Pubkey, [u8; 32])>, sequence_numbers: &mut Vec<MerkleTreeSequenceNumber>, remaining_accounts: &'a [AccountInfo<'a>], account_infos: &mut Vec<AccountInfo<'a>>, accounts: &mut Vec<AccountMeta>, ) -> Result<Vec<u8>> { let mut current_index: i16 = -1; let mut num_leaves_in_tree: u32 = 0; let mut mt_next_index = 0; let num_leaves = output_compressed_account_hashes.len(); let mut instruction_data = Vec::<u8>::with_capacity(12 + 33 * num_leaves); let mut hashed_merkle_tree = [0u8; 32]; let mut index_merkle_tree_account = 0; let number_of_merkle_trees = output_compressed_accounts.last().unwrap().merkle_tree_index as usize + 1; let mut merkle_tree_pubkeys = Vec::<Pubkey>::with_capacity(number_of_merkle_trees); // Anchor instruction signature. instruction_data.extend_from_slice(&[199, 144, 10, 82, 247, 142, 143, 7]); // leaves vector length (for borsh compat) instruction_data.extend_from_slice(&(num_leaves as u32).to_le_bytes()); for (j, account) in output_compressed_accounts.iter().enumerate() { // if mt index == current index Merkle tree account info has already been added. // if mt index != current index, Merkle tree account info is new, add it. #[allow(clippy::comparison_chain)] if account.merkle_tree_index as i16 == current_index { // Do nothing, but it is the most common case. } else if account.merkle_tree_index as i16 > current_index { current_index = account.merkle_tree_index.into(); let seq; // Check 1. (mt_next_index, _, seq) = check_program_owner_state_merkle_tree( &remaining_accounts[account.merkle_tree_index as usize], invoking_program, )?; let account_info = remaining_accounts[account.merkle_tree_index as usize].to_account_info(); sequence_numbers.push(MerkleTreeSequenceNumber { pubkey: account_info.key(), seq, }); hashed_merkle_tree = match hashed_pubkeys.iter().find(|x| x.0 == account_info.key()) { Some(hashed_merkle_tree) => hashed_merkle_tree.1, None => { hash_to_bn254_field_size_be(&account_info.key().to_bytes()) .unwrap() .0 } }; // check Merkle tree uniqueness if merkle_tree_pubkeys.contains(&account_info.key()) { return err!(SystemProgramError::OutputMerkleTreeNotUnique); } else { merkle_tree_pubkeys.push(account_info.key()); } accounts.push(AccountMeta { pubkey: account_info.key(), is_signer: false, is_writable: true, }); account_infos.push(account_info); num_leaves_in_tree = 0; index_merkle_tree_account += 1; } else { // Check 2. // Output Merkle tree indices must be in order since we use the // number of leaves in a Merkle tree to determine the correct leaf // index. Since the leaf index is part of the hash this is security // critical. return err!(SystemProgramError::OutputMerkleTreeIndicesNotInOrder); } // Check 3. if let Some(address) = account.compressed_account.address { if let Some(position) = compressed_account_addresses .iter() .filter(|x| x.is_some()) .position(|&x| x.unwrap() == address) { compressed_account_addresses.remove(position); } else { msg!("Address {:?}, is no new address and does not exist in input compressed accounts.", address); msg!( "Remaining compressed_account_addresses: {:?}", compressed_account_addresses ); return Err(SystemProgramError::InvalidAddress.into()); } } output_compressed_account_indices[j] = mt_next_index + num_leaves_in_tree; num_leaves_in_tree += 1; if account.compressed_account.data.is_some() && invoking_program.is_none() { msg!("Invoking program is not provided."); msg!("Only program owned compressed accounts can have data."); return err!(SystemProgramError::InvokingProgramNotProvided); } let hashed_owner = match hashed_pubkeys .iter() .find(|x| x.0 == account.compressed_account.owner) { Some(hashed_owner) => hashed_owner.1, None => { let hashed_owner = hash_to_bn254_field_size_be(&account.compressed_account.owner.to_bytes()) .unwrap() .0; hashed_pubkeys.push((account.compressed_account.owner, hashed_owner)); hashed_owner } }; // Compute output compressed account hash. output_compressed_account_hashes[j] = account .compressed_account .hash_with_hashed_values::<Poseidon>( &hashed_owner, &hashed_merkle_tree, &output_compressed_account_indices[j], )?; // - 1 since we want the index of the next account index. instruction_data.extend_from_slice(&[index_merkle_tree_account - 1]); instruction_data.extend_from_slice(&output_compressed_account_hashes[j]); } Ok(instruction_data) } #[test] fn test_instruction_data_borsh_compat() { let mut vec = Vec::<u8>::new(); vec.extend_from_slice(&2u32.to_le_bytes()); vec.push(1); vec.extend_from_slice(&[2u8; 32]); vec.push(3); vec.extend_from_slice(&[4u8; 32]); let refe = vec![(1, [2u8; 32]), (3, [4u8; 32])]; let mut serialized = Vec::new(); Vec::<(u8, [u8; 32])>::serialize(&refe, &mut serialized).unwrap(); assert_eq!(serialized, vec); let res = Vec::<(u8, [u8; 32])>::deserialize(&mut vec.as_slice()).unwrap(); assert_eq!(res, vec![(1, [2u8; 32]), (3, [4u8; 32])]); }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/emit_event.rs
use account_compression::emit_indexer_event; use anchor_lang::{prelude::*, Bumps}; use crate::{ errors::SystemProgramError, sdk::{ accounts::InvokeAccounts, event::{MerkleTreeSequenceNumber, PublicTransactionEvent}, }, InstructionDataInvoke, }; pub fn emit_state_transition_event<'a, 'b, 'c: 'info, 'info, A: InvokeAccounts<'info> + Bumps>( inputs: InstructionDataInvoke, ctx: &'a Context<'a, 'b, 'c, 'info, A>, input_compressed_account_hashes: Vec<[u8; 32]>, output_compressed_account_hashes: Vec<[u8; 32]>, output_leaf_indices: Vec<u32>, sequence_numbers: Vec<MerkleTreeSequenceNumber>, ) -> Result<()> { // Note: message is unimplemented let event = PublicTransactionEvent { input_compressed_account_hashes, output_compressed_account_hashes, output_compressed_accounts: inputs.output_compressed_accounts, output_leaf_indices, sequence_numbers, relay_fee: inputs.relay_fee, pubkey_array: ctx.remaining_accounts.iter().map(|x| x.key()).collect(), compress_or_decompress_lamports: inputs.compress_or_decompress_lamports, message: None, is_compress: inputs.is_compress, }; // 10240 = 10 * 1024 the max instruction data of a cpi. let data_capacity = 10240; let mut data = Vec::with_capacity(data_capacity); event.man_serialize(&mut data)?; if data_capacity != data.capacity() { msg!( "Event serialization exceeded capacity. Used {}, allocated {}.", data.capacity(), data_capacity ); return err!(SystemProgramError::InvalidCapacity); } emit_indexer_event(data, ctx.accounts.get_noop_program()) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/sum_check.rs
use crate::{ errors::SystemProgramError, sdk::compressed_account::PackedCompressedAccountWithMerkleContext, OutputCompressedAccountWithPackedContext, }; use anchor_lang::solana_program::program_error::ProgramError; use anchor_lang::Result; use light_macros::heap_neutral; #[inline(never)] #[heap_neutral] pub fn sum_check( input_compressed_accounts_with_merkle_context: &[PackedCompressedAccountWithMerkleContext], output_compressed_accounts: &[OutputCompressedAccountWithPackedContext], relay_fee: &Option<u64>, compress_or_decompress_lamports: &Option<u64>, is_compress: &bool, ) -> Result<()> { let mut sum: u64 = 0; for compressed_account_with_context in input_compressed_accounts_with_merkle_context.iter() { if compressed_account_with_context.read_only { unimplemented!("read_only accounts are not supported. Set read_only to false."); } sum = sum .checked_add(compressed_account_with_context.compressed_account.lamports) .ok_or(ProgramError::ArithmeticOverflow) .map_err(|_| SystemProgramError::ComputeInputSumFailed)?; } match compress_or_decompress_lamports { Some(lamports) => { if *is_compress { sum = sum .checked_add(*lamports) .ok_or(ProgramError::ArithmeticOverflow) .map_err(|_| SystemProgramError::ComputeOutputSumFailed)?; } else { sum = sum .checked_sub(*lamports) .ok_or(ProgramError::ArithmeticOverflow) .map_err(|_| SystemProgramError::ComputeOutputSumFailed)?; } } None => (), } for compressed_account in output_compressed_accounts.iter() { sum = sum .checked_sub(compressed_account.compressed_account.lamports) .ok_or(ProgramError::ArithmeticOverflow) .map_err(|_| SystemProgramError::ComputeOutputSumFailed)?; } if let Some(relay_fee) = relay_fee { sum = sum .checked_sub(*relay_fee) .ok_or(ProgramError::ArithmeticOverflow) .map_err(|_| SystemProgramError::ComputeRpcSumFailed)?; } if sum == 0 { Ok(()) } else { Err(SystemProgramError::SumCheckFailed.into()) } } #[cfg(test)] mod test { use solana_sdk::{signature::Keypair, signer::Signer}; use super::*; use crate::sdk::compressed_account::{CompressedAccount, PackedMerkleContext}; #[test] fn test_sum_check() { // SUCCEED: no relay fee, compression sum_check_test(&[100, 50], &[150], None, None, false).unwrap(); sum_check_test(&[75, 25, 25], &[25, 25, 25, 25, 12, 13], None, None, false).unwrap(); // FAIL: no relay fee, compression sum_check_test(&[100, 50], &[150 + 1], None, None, false).unwrap_err(); sum_check_test(&[100, 50], &[150 - 1], None, None, false).unwrap_err(); sum_check_test(&[100, 50], &[], None, None, false).unwrap_err(); sum_check_test(&[], &[100, 50], None, None, false).unwrap_err(); sum_check_test(&[100, 50], &[0], None, None, false).unwrap_err(); sum_check_test(&[0], &[100, 50], None, None, false).unwrap_err(); // SUCCEED: empty sum_check_test(&[], &[], None, None, true).unwrap(); sum_check_test(&[], &[], None, None, false).unwrap(); sum_check_test(&[0], &[0], None, None, true).unwrap(); sum_check_test(&[0], &[0], None, None, false).unwrap(); // FAIL: empty sum_check_test(&[], &[], Some(1), None, false).unwrap_err(); sum_check_test(&[], &[], None, Some(1), false).unwrap_err(); sum_check_test(&[], &[], None, Some(1), true).unwrap_err(); // SUCCEED: with compress sum_check_test(&[100], &[123], None, Some(23), true).unwrap(); sum_check_test(&[], &[150], None, Some(150), true).unwrap(); // FAIL: compress sum_check_test(&[], &[150], None, Some(150 - 1), true).unwrap_err(); sum_check_test(&[], &[150], None, Some(150 + 1), true).unwrap_err(); // SUCCEED: with decompress sum_check_test(&[100, 50], &[100], None, Some(50), false).unwrap(); sum_check_test(&[100, 50], &[], None, Some(150), false).unwrap(); // FAIL: decompress sum_check_test(&[100, 50], &[], None, Some(150 - 1), false).unwrap_err(); sum_check_test(&[100, 50], &[], None, Some(150 + 1), false).unwrap_err(); // SUCCEED: with relay fee sum_check_test(&[100, 50], &[125], Some(25), None, false).unwrap(); sum_check_test(&[100, 50], &[150], Some(25), Some(25), true).unwrap(); sum_check_test(&[100, 50], &[100], Some(25), Some(25), false).unwrap(); // FAIL: relay fee sum_check_test(&[100, 50], &[2125], Some(25 - 1), None, false).unwrap_err(); sum_check_test(&[100, 50], &[2125], Some(25 + 1), None, false).unwrap_err(); } fn sum_check_test( input_amounts: &[u64], output_amounts: &[u64], relay_fee: Option<u64>, compress_or_decompress_lamports: Option<u64>, is_compress: bool, ) -> Result<()> { let mut inputs = Vec::new(); for i in input_amounts.iter() { inputs.push(PackedCompressedAccountWithMerkleContext { compressed_account: CompressedAccount { owner: Keypair::new().pubkey(), lamports: *i, address: None, data: None, }, merkle_context: PackedMerkleContext { merkle_tree_pubkey_index: 0, nullifier_queue_pubkey_index: 0, leaf_index: 0, queue_index: None, }, root_index: 1, read_only: false, }); } let mut outputs = Vec::new(); for amount in output_amounts.iter() { outputs.push(OutputCompressedAccountWithPackedContext { compressed_account: CompressedAccount { owner: Keypair::new().pubkey(), lamports: *amount, address: None, data: None, }, merkle_tree_index: 0, }); } sum_check( &inputs, &outputs, &relay_fee, &compress_or_decompress_lamports, &is_compress, ) } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke/instruction.rs
use account_compression::{program::AccountCompression, utils::constants::CPI_AUTHORITY_PDA_SEED}; use anchor_lang::prelude::*; use super::processor::CompressedProof; use crate::{ invoke::sol_compression::SOL_POOL_PDA_SEED, sdk::{ accounts::{InvokeAccounts, SignerAccounts}, compressed_account::{CompressedAccount, PackedCompressedAccountWithMerkleContext}, }, }; /// These are the base accounts additionally Merkle tree and queue accounts are required. /// These additional accounts are passed as remaining accounts. /// 1 Merkle tree for each input compressed account one queue and Merkle tree account each for each output compressed account. #[derive(Accounts)] pub struct InvokeInstruction<'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: this account #[account( seeds = [&crate::ID.to_bytes()], bump, seeds::program = &account_compression::ID, )] pub registered_program_pda: AccountInfo<'info>, /// CHECK: is checked when emitting the event. pub noop_program: UncheckedAccount<'info>, /// CHECK: this account in account compression program. /// This pda is used to invoke the account compression program. #[account(seeds = [CPI_AUTHORITY_PDA_SEED], bump)] pub account_compression_authority: UncheckedAccount<'info>, /// CHECK: Account compression program is used to update state and address /// Merkle trees. pub account_compression_program: Program<'info, AccountCompression>, /// Sol pool pda is used to store the native sol that has been compressed. /// It's only required when compressing or decompressing sol. #[account( mut, seeds = [SOL_POOL_PDA_SEED], bump )] pub sol_pool_pda: Option<AccountInfo<'info>>, /// Only needs to be provided for decompression as a recipient for the /// decompressed sol. /// Compressed sol originate from authority. #[account(mut)] pub decompression_recipient: Option<AccountInfo<'info>>, pub system_program: Program<'info, System>, } impl<'info> SignerAccounts<'info> for InvokeInstruction<'info> { fn get_fee_payer(&self) -> &Signer<'info> { &self.fee_payer } fn get_authority(&self) -> &Signer<'info> { &self.authority } } impl<'info> InvokeAccounts<'info> for InvokeInstruction<'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>> { self.sol_pool_pda.as_ref() } fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>> { self.decompression_recipient.as_ref() } } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct InstructionDataInvoke { pub proof: Option<CompressedProof>, pub input_compressed_accounts_with_merkle_context: Vec<PackedCompressedAccountWithMerkleContext>, pub output_compressed_accounts: Vec<OutputCompressedAccountWithPackedContext>, pub relay_fee: Option<u64>, pub new_address_params: Vec<NewAddressParamsPacked>, pub compress_or_decompress_lamports: Option<u64>, pub is_compress: bool, } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct OutputCompressedAccountWithContext { pub compressed_account: CompressedAccount, pub merkle_tree: Pubkey, } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct OutputCompressedAccountWithPackedContext { pub compressed_account: CompressedAccount, pub merkle_tree_index: u8, } #[derive(Debug, PartialEq, Default, Clone, Copy, AnchorSerialize, AnchorDeserialize)] pub struct NewAddressParamsPacked { pub seed: [u8; 32], pub address_queue_account_index: u8, pub address_merkle_tree_account_index: u8, pub address_merkle_tree_root_index: u16, } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct NewAddressParams { pub seed: [u8; 32], pub address_queue_pubkey: Pubkey, pub address_merkle_tree_pubkey: Pubkey, pub address_merkle_tree_root_index: u16, }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/sdk/accounts.rs
use account_compression::program::AccountCompression; use anchor_lang::prelude::*; pub trait InvokeAccounts<'info> { fn get_registered_program_pda(&self) -> &AccountInfo<'info>; fn get_noop_program(&self) -> &UncheckedAccount<'info>; fn get_account_compression_authority(&self) -> &UncheckedAccount<'info>; fn get_account_compression_program(&self) -> &Program<'info, AccountCompression>; fn get_system_program(&self) -> &Program<'info, System>; fn get_sol_pool_pda(&self) -> Option<&AccountInfo<'info>>; fn get_decompression_recipient(&self) -> Option<&AccountInfo<'info>>; } pub trait SignerAccounts<'info> { fn get_fee_payer(&self) -> &Signer<'info>; fn get_authority(&self) -> &Signer<'info>; }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/sdk/address.rs
use std::collections::HashMap; use anchor_lang::{err, solana_program::pubkey::Pubkey, Result}; use light_utils::hash_to_bn254_field_size_be; use crate::{errors::SystemProgramError, NewAddressParams, NewAddressParamsPacked}; pub fn derive_address(merkle_tree_pubkey: &Pubkey, seed: &[u8; 32]) -> Result<[u8; 32]> { let hash = match hash_to_bn254_field_size_be( [merkle_tree_pubkey.to_bytes(), *seed].concat().as_slice(), ) { Some(hash) => Ok::<[u8; 32], SystemProgramError>(hash.0), None => return err!(SystemProgramError::DeriveAddressError), }?; Ok(hash) } pub fn add_and_get_remaining_account_indices( pubkeys: &[Pubkey], remaining_accounts: &mut HashMap<Pubkey, usize>, ) -> Vec<u8> { let mut vec = Vec::new(); let mut next_index: usize = remaining_accounts.len(); for pubkey in pubkeys.iter() { match remaining_accounts.get(pubkey) { Some(_) => {} None => { remaining_accounts.insert(*pubkey, next_index); next_index += 1; } }; vec.push(*remaining_accounts.get(pubkey).unwrap() as u8); } vec } // Helper function to pack new address params for instruction data in rust clients pub fn pack_new_address_params( new_address_params: &[NewAddressParams], remaining_accounts: &mut HashMap<Pubkey, usize>, ) -> Vec<NewAddressParamsPacked> { let mut new_address_params_packed = new_address_params .iter() .map(|x| NewAddressParamsPacked { seed: x.seed, address_merkle_tree_root_index: x.address_merkle_tree_root_index, address_merkle_tree_account_index: 0, // will be assigned later address_queue_account_index: 0, // will be assigned later }) .collect::<Vec<NewAddressParamsPacked>>(); let mut next_index: usize = remaining_accounts.len(); for (i, params) in new_address_params.iter().enumerate() { match remaining_accounts.get(&params.address_merkle_tree_pubkey) { Some(_) => {} None => { remaining_accounts.insert(params.address_merkle_tree_pubkey, next_index); next_index += 1; } }; new_address_params_packed[i].address_merkle_tree_account_index = *remaining_accounts .get(&params.address_merkle_tree_pubkey) .unwrap() as u8; } for (i, params) in new_address_params.iter().enumerate() { match remaining_accounts.get(&params.address_queue_pubkey) { Some(_) => {} None => { remaining_accounts.insert(params.address_queue_pubkey, next_index); next_index += 1; } }; new_address_params_packed[i].address_queue_account_index = *remaining_accounts .get(&params.address_queue_pubkey) .unwrap() as u8; } new_address_params_packed } #[cfg(test)] mod tests { use solana_sdk::{signature::Keypair, signer::Signer}; use super::*; #[test] fn test_derive_address_with_valid_input() { let merkle_tree_pubkey = Keypair::new().pubkey(); let seeds = [1u8; 32]; let result = derive_address(&merkle_tree_pubkey, &seeds); let result_2 = derive_address(&merkle_tree_pubkey, &seeds); assert_eq!(result, result_2); } #[test] fn test_derive_address_no_collision_same_seeds_diff_pubkey() { let merkle_tree_pubkey = Keypair::new().pubkey(); let merkle_tree_pubkey_2 = Keypair::new().pubkey(); let seed = [2u8; 32]; let result = derive_address(&merkle_tree_pubkey, &seed); let result_2 = derive_address(&merkle_tree_pubkey_2, &seed); assert_ne!(result, result_2); } #[test] fn test_add_and_get_remaining_account_indices_empty() { let pubkeys = vec![]; let mut remaining_accounts = HashMap::new(); let result = add_and_get_remaining_account_indices(&pubkeys, &mut remaining_accounts); assert!(result.is_empty()); } #[test] fn test_add_and_get_remaining_account_indices_single() { let pubkey = Keypair::new().pubkey(); let pubkeys = vec![pubkey]; let mut remaining_accounts = HashMap::new(); let result = add_and_get_remaining_account_indices(&pubkeys, &mut remaining_accounts); assert_eq!(result, vec![0]); assert_eq!(remaining_accounts.get(&pubkey), Some(&0)); } #[test] fn test_add_and_get_remaining_account_indices_multiple() { let pubkey1 = Keypair::new().pubkey(); let pubkey2 = Keypair::new().pubkey(); let pubkeys = vec![pubkey1, pubkey2]; let mut remaining_accounts = HashMap::new(); let result = add_and_get_remaining_account_indices(&pubkeys, &mut remaining_accounts); assert_eq!(result, vec![0, 1]); assert_eq!(remaining_accounts.get(&pubkey1), Some(&0)); assert_eq!(remaining_accounts.get(&pubkey2), Some(&1)); } #[test] fn test_add_and_get_remaining_account_indices_duplicates() { let pubkey = Keypair::new().pubkey(); let pubkeys = vec![pubkey, pubkey]; let mut remaining_accounts = HashMap::new(); let result = add_and_get_remaining_account_indices(&pubkeys, &mut remaining_accounts); assert_eq!(result, vec![0, 0]); assert_eq!(remaining_accounts.get(&pubkey), Some(&0)); assert_eq!(remaining_accounts.len(), 1); } #[test] fn test_add_and_get_remaining_account_indices_multiple_duplicates() { let pubkey1 = Keypair::new().pubkey(); let pubkey2 = Keypair::new().pubkey(); let pubkey3 = Keypair::new().pubkey(); let pubkeys = vec![pubkey1, pubkey2, pubkey1, pubkey3, pubkey2, pubkey1]; let mut remaining_accounts = HashMap::new(); let result = add_and_get_remaining_account_indices(&pubkeys, &mut remaining_accounts); assert_eq!(result, vec![0, 1, 0, 2, 1, 0]); assert_eq!(remaining_accounts.get(&pubkey1), Some(&0)); assert_eq!(remaining_accounts.get(&pubkey2), Some(&1)); assert_eq!(remaining_accounts.get(&pubkey3), Some(&2)); assert_eq!(remaining_accounts.len(), 3); } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/sdk/event.rs
use std::io::Write; use anchor_lang::{ prelude::borsh, solana_program::pubkey::Pubkey, AnchorDeserialize, AnchorSerialize, }; use crate::OutputCompressedAccountWithPackedContext; #[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize, Default, PartialEq)] pub struct MerkleTreeSequenceNumber { pub pubkey: Pubkey, pub seq: u64, } #[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize, Default, PartialEq)] pub struct PublicTransactionEvent { pub input_compressed_account_hashes: Vec<[u8; 32]>, pub output_compressed_account_hashes: Vec<[u8; 32]>, pub output_compressed_accounts: Vec<OutputCompressedAccountWithPackedContext>, pub output_leaf_indices: Vec<u32>, pub sequence_numbers: Vec<MerkleTreeSequenceNumber>, pub relay_fee: Option<u64>, pub is_compress: bool, pub compress_or_decompress_lamports: Option<u64>, pub pubkey_array: Vec<Pubkey>, pub message: Option<Vec<u8>>, } impl PublicTransactionEvent { pub fn man_serialize<W: Write>(&self, writer: &mut W) -> std::io::Result<()> { writer.write_all(&(self.input_compressed_account_hashes.len() as u32).to_le_bytes())?; for hash in self.input_compressed_account_hashes.iter() { writer.write_all(hash)?; } writer.write_all(&(self.output_compressed_account_hashes.len() as u32).to_le_bytes())?; for hash in self.output_compressed_account_hashes.iter() { writer.write_all(hash)?; } #[cfg(target_os = "solana")] let pos = light_heap::GLOBAL_ALLOCATOR.get_heap_pos(); writer.write_all(&(self.output_compressed_accounts.len() as u32).to_le_bytes())?; for i in 0..self.output_compressed_accounts.len() { let account = self.output_compressed_accounts[i].clone(); account.serialize(writer)?; } #[cfg(target_os = "solana")] light_heap::GLOBAL_ALLOCATOR.free_heap(pos).unwrap(); writer.write_all(&(self.output_leaf_indices.len() as u32).to_le_bytes())?; for index in self.output_leaf_indices.iter() { writer.write_all(&index.to_le_bytes())?; } writer.write_all(&(self.sequence_numbers.len() as u32).to_le_bytes())?; for element in self.sequence_numbers.iter() { writer.write_all(&element.pubkey.to_bytes())?; writer.write_all(&element.seq.to_le_bytes())?; } match self.relay_fee { Some(relay_fee) => { writer.write_all(&[1])?; writer.write_all(&relay_fee.to_le_bytes()) } None => writer.write_all(&[0]), }?; writer.write_all(&[self.is_compress as u8])?; match self.compress_or_decompress_lamports { Some(compress_or_decompress_lamports) => { writer.write_all(&[1])?; writer.write_all(&compress_or_decompress_lamports.to_le_bytes()) } None => writer.write_all(&[0]), }?; writer.write_all(&(self.pubkey_array.len() as u32).to_le_bytes())?; for pubkey in self.pubkey_array.iter() { writer.write_all(&pubkey.to_bytes())?; } match &self.message { Some(message) => { writer.write_all(&[1])?; writer.write_all(&(message.len() as u32).to_le_bytes())?; writer.write_all(message) } None => writer.write_all(&[0]), }?; Ok(()) } } #[cfg(test)] pub mod test { use rand::Rng; use solana_sdk::{signature::Keypair, signer::Signer}; use super::*; use crate::sdk::compressed_account::{CompressedAccount, CompressedAccountData}; #[test] fn test_manual_vs_borsh_serialization() { // Create a sample `PublicTransactionEvent` instance let event = PublicTransactionEvent { input_compressed_account_hashes: vec![[0u8; 32], [1u8; 32]], output_compressed_account_hashes: vec![[2u8; 32], [3u8; 32]], output_compressed_accounts: vec![OutputCompressedAccountWithPackedContext { compressed_account: CompressedAccount { owner: Keypair::new().pubkey(), lamports: 100, address: Some([5u8; 32]), data: Some(CompressedAccountData { discriminator: [6u8; 8], data: vec![7u8; 32], data_hash: [8u8; 32], }), }, merkle_tree_index: 1, }], sequence_numbers: vec![ MerkleTreeSequenceNumber { pubkey: Keypair::new().pubkey(), seq: 10, }, MerkleTreeSequenceNumber { pubkey: Keypair::new().pubkey(), seq: 2, }, ], output_leaf_indices: vec![4, 5, 6], relay_fee: Some(1000), is_compress: true, compress_or_decompress_lamports: Some(5000), pubkey_array: vec![Keypair::new().pubkey(), Keypair::new().pubkey()], message: Some(vec![8, 9, 10]), }; // Serialize using Borsh let borsh_serialized = event.try_to_vec().unwrap(); // Serialize manually let mut manual_serialized = Vec::new(); event.man_serialize(&mut manual_serialized).unwrap(); // Compare the two byte arrays assert_eq!( borsh_serialized, manual_serialized, "Borsh and manual serialization results should match" ); } #[test] fn test_serialization_consistency() { let mut rng = rand::thread_rng(); for _ in 0..10_000 { let input_hashes: Vec<[u8; 32]> = (0..rng.gen_range(1..10)).map(|_| rng.gen()).collect(); let output_hashes: Vec<[u8; 32]> = (0..rng.gen_range(1..10)).map(|_| rng.gen()).collect(); let output_accounts: Vec<OutputCompressedAccountWithPackedContext> = (0..rng .gen_range(1..10)) .map(|_| OutputCompressedAccountWithPackedContext { compressed_account: CompressedAccount { owner: Keypair::new().pubkey(), lamports: rng.gen(), address: Some(rng.gen()), data: None, }, merkle_tree_index: rng.gen(), }) .collect(); let leaf_indices: Vec<u32> = (0..rng.gen_range(1..10)).map(|_| rng.gen()).collect(); let pubkeys: Vec<Pubkey> = (0..rng.gen_range(1..10)) .map(|_| Keypair::new().pubkey()) .collect(); let message: Option<Vec<u8>> = if rng.gen() { Some((0..rng.gen_range(1..100)).map(|_| rng.gen()).collect()) } else { None }; let event = PublicTransactionEvent { input_compressed_account_hashes: input_hashes, output_compressed_account_hashes: output_hashes, output_compressed_accounts: output_accounts, output_leaf_indices: leaf_indices, sequence_numbers: (0..rng.gen_range(1..10)) .map(|_| MerkleTreeSequenceNumber { pubkey: Keypair::new().pubkey(), seq: rng.gen(), }) .collect(), relay_fee: if rng.gen() { Some(rng.gen()) } else { None }, is_compress: rng.gen(), compress_or_decompress_lamports: if rng.gen() { Some(rng.gen()) } else { None }, pubkey_array: pubkeys, message, }; let borsh_serialized = event.try_to_vec().unwrap(); let mut manual_serialized = Vec::new(); event.man_serialize(&mut manual_serialized).unwrap(); assert_eq!( borsh_serialized, manual_serialized, "Borsh and manual serialization results should match" ); } } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/sdk/mod.rs
pub mod accounts; pub mod address; pub mod compressed_account; pub mod event; pub mod invoke; use anchor_lang::prelude::*; #[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct CompressedCpiContext { /// Is set by the program that is invoking the CPI to signal that is should /// set the cpi context. pub set_context: bool, /// Is set to wipe the cpi context since someone could have set it before /// with unrelated data. pub first_set_context: bool, /// Index of cpi context account in remaining accounts. pub cpi_context_account_index: u8, }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/sdk/invoke.rs
#![cfg(not(target_os = "solana"))] use std::collections::HashMap; use anchor_lang::{AnchorSerialize, InstructionData, ToAccountMetas}; use solana_sdk::{ instruction::{AccountMeta, Instruction}, pubkey::Pubkey, }; use super::compressed_account::{ CompressedAccount, MerkleContext, PackedCompressedAccountWithMerkleContext, PackedMerkleContext, }; use crate::{ invoke::{processor::CompressedProof, sol_compression::SOL_POOL_PDA_SEED}, utils::{get_cpi_authority_pda, get_registered_program_pda}, InstructionDataInvoke, NewAddressParams, NewAddressParamsPacked, OutputCompressedAccountWithPackedContext, }; pub fn get_sol_pool_pda() -> Pubkey { Pubkey::find_program_address(&[SOL_POOL_PDA_SEED], &crate::ID).0 } #[allow(clippy::too_many_arguments)] pub fn create_invoke_instruction( fee_payer: &Pubkey, payer: &Pubkey, input_compressed_accounts: &[CompressedAccount], output_compressed_accounts: &[CompressedAccount], merkle_context: &[MerkleContext], output_compressed_account_merkle_tree_pubkeys: &[Pubkey], input_root_indices: &[u16], new_address_params: &[NewAddressParams], proof: Option<CompressedProof>, compress_or_decompress_lamports: Option<u64>, is_compress: bool, decompression_recipient: Option<Pubkey>, sort: bool, ) -> Instruction { let (remaining_accounts, mut inputs_struct) = create_invoke_instruction_data_and_remaining_accounts( new_address_params, merkle_context, input_compressed_accounts, input_root_indices, output_compressed_account_merkle_tree_pubkeys, output_compressed_accounts, proof, compress_or_decompress_lamports, is_compress, ); if sort { inputs_struct .output_compressed_accounts .sort_by(|a, b| a.merkle_tree_index.cmp(&b.merkle_tree_index)); } let mut inputs = Vec::new(); InstructionDataInvoke::serialize(&inputs_struct, &mut inputs).unwrap(); let instruction_data = crate::instruction::Invoke { inputs }; let sol_pool_pda = compress_or_decompress_lamports.map(|_| get_sol_pool_pda()); let accounts = crate::accounts::InvokeInstruction { fee_payer: *fee_payer, authority: *payer, registered_program_pda: get_registered_program_pda(&crate::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(&crate::ID), sol_pool_pda, decompression_recipient, system_program: solana_sdk::system_program::ID, }; 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_invoke_instruction_data_and_remaining_accounts( new_address_params: &[NewAddressParams], merkle_context: &[MerkleContext], input_compressed_accounts: &[CompressedAccount], input_root_indices: &[u16], output_compressed_account_merkle_tree_pubkeys: &[Pubkey], output_compressed_accounts: &[CompressedAccount], proof: Option<CompressedProof>, compress_or_decompress_lamports: Option<u64>, is_compress: bool, ) -> (Vec<AccountMeta>, InstructionDataInvoke) { let mut remaining_accounts = HashMap::<Pubkey, usize>::new(); let mut _input_compressed_accounts: Vec<PackedCompressedAccountWithMerkleContext> = Vec::<PackedCompressedAccountWithMerkleContext>::new(); let mut index = 0; let mut new_address_params_packed = new_address_params .iter() .map(|x| NewAddressParamsPacked { seed: x.seed, address_merkle_tree_root_index: x.address_merkle_tree_root_index, address_merkle_tree_account_index: 0, // will be assigned later address_queue_account_index: 0, // will be assigned later }) .collect::<Vec<NewAddressParamsPacked>>(); for (i, context) in merkle_context.iter().enumerate() { match remaining_accounts.get(&context.merkle_tree_pubkey) { Some(_) => {} None => { remaining_accounts.insert(context.merkle_tree_pubkey, index); index += 1; } }; _input_compressed_accounts.push(PackedCompressedAccountWithMerkleContext { compressed_account: input_compressed_accounts[i].clone(), merkle_context: PackedMerkleContext { merkle_tree_pubkey_index: *remaining_accounts .get(&context.merkle_tree_pubkey) .unwrap() as u8, nullifier_queue_pubkey_index: 0, leaf_index: context.leaf_index, queue_index: None, }, read_only: false, root_index: input_root_indices[i], }); } for (i, context) in merkle_context.iter().enumerate() { match remaining_accounts.get(&context.nullifier_queue_pubkey) { Some(_) => {} None => { remaining_accounts.insert(context.nullifier_queue_pubkey, index); index += 1; } }; _input_compressed_accounts[i] .merkle_context .nullifier_queue_pubkey_index = *remaining_accounts .get(&context.nullifier_queue_pubkey) .unwrap() as u8; } let mut output_compressed_accounts_with_context: Vec<OutputCompressedAccountWithPackedContext> = Vec::<OutputCompressedAccountWithPackedContext>::new(); for (i, mt) in output_compressed_account_merkle_tree_pubkeys .iter() .enumerate() { match remaining_accounts.get(mt) { Some(_) => {} None => { remaining_accounts.insert(*mt, index); index += 1; } }; output_compressed_accounts_with_context.push(OutputCompressedAccountWithPackedContext { compressed_account: output_compressed_accounts[i].clone(), merkle_tree_index: *remaining_accounts.get(mt).unwrap() as u8, }); } for (i, params) in new_address_params.iter().enumerate() { match remaining_accounts.get(&params.address_merkle_tree_pubkey) { Some(_) => {} None => { remaining_accounts.insert(params.address_merkle_tree_pubkey, index); index += 1; } }; new_address_params_packed[i].address_merkle_tree_account_index = *remaining_accounts .get(&params.address_merkle_tree_pubkey) .unwrap() as u8; } for (i, params) in new_address_params.iter().enumerate() { match remaining_accounts.get(&params.address_queue_pubkey) { Some(_) => {} None => { remaining_accounts.insert(params.address_queue_pubkey, index); index += 1; } }; new_address_params_packed[i].address_queue_account_index = *remaining_accounts .get(&params.address_queue_pubkey) .unwrap() as u8; } let mut remaining_accounts = remaining_accounts .iter() .map(|(k, i)| (AccountMeta::new(*k, false), *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>>(); let inputs_struct = InstructionDataInvoke { relay_fee: None, input_compressed_accounts_with_merkle_context: _input_compressed_accounts, output_compressed_accounts: output_compressed_accounts_with_context, proof, new_address_params: new_address_params_packed, compress_or_decompress_lamports, is_compress, }; (remaining_accounts, inputs_struct) } #[cfg(test)] mod test { use anchor_lang::AnchorDeserialize; use solana_sdk::{signature::Keypair, signer::Signer}; use super::*; #[test] fn test_create_execute_compressed_transaction() { let payer = Keypair::new().pubkey(); let recipient = Keypair::new().pubkey(); let input_compressed_accounts = vec![ CompressedAccount { lamports: 100, owner: payer, address: None, data: None, }, CompressedAccount { lamports: 100, owner: payer, address: None, data: None, }, ]; let output_compressed_accounts = vec![ CompressedAccount { lamports: 50, owner: payer, address: None, data: None, }, CompressedAccount { lamports: 150, owner: recipient, address: None, data: None, }, ]; let merkle_tree_indices = vec![0, 2]; let merkle_tree_pubkey = Keypair::new().pubkey(); let merkle_tree_pubkey_1 = Keypair::new().pubkey(); let nullifier_array_pubkey = Keypair::new().pubkey(); let input_merkle_context = vec![ MerkleContext { merkle_tree_pubkey, nullifier_queue_pubkey: nullifier_array_pubkey, leaf_index: 0, queue_index: None, }, MerkleContext { merkle_tree_pubkey, nullifier_queue_pubkey: nullifier_array_pubkey, leaf_index: 1, queue_index: None, }, ]; let output_compressed_account_merkle_tree_pubkeys = vec![merkle_tree_pubkey, merkle_tree_pubkey_1]; let input_root_indices = vec![0, 1]; let proof = CompressedProof { a: [0u8; 32], b: [1u8; 64], c: [0u8; 32], }; let instruction = create_invoke_instruction( &payer, &payer, &input_compressed_accounts.clone(), &output_compressed_accounts.clone(), &input_merkle_context, &output_compressed_account_merkle_tree_pubkeys, &input_root_indices.clone(), Vec::<NewAddressParams>::new().as_slice(), Some(proof.clone()), Some(100), true, None, true, ); assert_eq!(instruction.program_id, crate::ID); let deserialized_instruction_data: InstructionDataInvoke = InstructionDataInvoke::deserialize(&mut instruction.data[12..].as_ref()).unwrap(); deserialized_instruction_data .input_compressed_accounts_with_merkle_context .iter() .enumerate() .for_each(|(i, compressed_account_with_context)| { assert_eq!( input_compressed_accounts[i], compressed_account_with_context.compressed_account ); }); deserialized_instruction_data .output_compressed_accounts .iter() .enumerate() .for_each(|(i, compressed_account)| { assert_eq!( OutputCompressedAccountWithPackedContext { compressed_account: output_compressed_accounts[i].clone(), merkle_tree_index: merkle_tree_indices[i] as u8 }, *compressed_account ); }); assert_eq!( deserialized_instruction_data .input_compressed_accounts_with_merkle_context .len(), 2 ); assert_eq!( deserialized_instruction_data .output_compressed_accounts .len(), 2 ); assert_eq!( deserialized_instruction_data.proof.clone().unwrap().a, proof.a ); assert_eq!( deserialized_instruction_data.proof.clone().unwrap().b, proof.b ); assert_eq!( deserialized_instruction_data.proof.clone().unwrap().c, proof.c ); assert_eq!( deserialized_instruction_data .compress_or_decompress_lamports .unwrap(), 100 ); assert_eq!(deserialized_instruction_data.is_compress, true); let ref_account_meta = AccountMeta::new(payer, true); assert_eq!(instruction.accounts[0], ref_account_meta); assert_eq!( deserialized_instruction_data.input_compressed_accounts_with_merkle_context[0] .merkle_context .nullifier_queue_pubkey_index, 1 ); assert_eq!( deserialized_instruction_data.input_compressed_accounts_with_merkle_context[1] .merkle_context .nullifier_queue_pubkey_index, 1 ); assert_eq!( instruction.accounts[9 + deserialized_instruction_data .input_compressed_accounts_with_merkle_context[0] .merkle_context .merkle_tree_pubkey_index as usize], AccountMeta::new(merkle_tree_pubkey, false) ); assert_eq!( instruction.accounts[9 + deserialized_instruction_data .input_compressed_accounts_with_merkle_context[1] .merkle_context .merkle_tree_pubkey_index as usize], AccountMeta::new(merkle_tree_pubkey, false) ); assert_eq!( instruction.accounts[9 + deserialized_instruction_data .input_compressed_accounts_with_merkle_context[0] .merkle_context .nullifier_queue_pubkey_index as usize], AccountMeta::new(nullifier_array_pubkey, false) ); assert_eq!( instruction.accounts[9 + deserialized_instruction_data .input_compressed_accounts_with_merkle_context[1] .merkle_context .nullifier_queue_pubkey_index as usize], AccountMeta::new(nullifier_array_pubkey, false) ); assert_eq!( instruction.accounts[9 + deserialized_instruction_data.output_compressed_accounts[0] .merkle_tree_index as usize], AccountMeta::new(merkle_tree_pubkey, false) ); assert_eq!( instruction.accounts[9 + deserialized_instruction_data.output_compressed_accounts[1] .merkle_tree_index as usize], AccountMeta::new(merkle_tree_pubkey_1, false) ); } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/sdk/compressed_account.rs
use std::collections::HashMap; use anchor_lang::prelude::*; use light_hasher::{Hasher, Poseidon}; use light_utils::hash_to_bn254_field_size_be; #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct PackedCompressedAccountWithMerkleContext { pub compressed_account: CompressedAccount, pub merkle_context: PackedMerkleContext, /// Index of root used in inclusion validity proof. pub root_index: u16, /// Placeholder to mark accounts read-only unimplemented set to false. pub read_only: bool, } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct CompressedAccountWithMerkleContext { pub compressed_account: CompressedAccount, pub merkle_context: MerkleContext, } impl CompressedAccountWithMerkleContext { pub fn hash(&self) -> Result<[u8; 32]> { self.compressed_account.hash::<Poseidon>( &self.merkle_context.merkle_tree_pubkey, &self.merkle_context.leaf_index, ) } } #[derive(Debug, Clone, Copy, AnchorSerialize, AnchorDeserialize, PartialEq, Default)] pub struct MerkleContext { pub merkle_tree_pubkey: Pubkey, pub nullifier_queue_pubkey: Pubkey, pub leaf_index: u32, /// Index of leaf in queue. Placeholder of batched Merkle tree updates /// currently unimplemented. pub queue_index: Option<QueueIndex>, } #[derive(Debug, Clone, Copy, AnchorSerialize, AnchorDeserialize, PartialEq, Default)] pub struct PackedMerkleContext { pub merkle_tree_pubkey_index: u8, pub nullifier_queue_pubkey_index: u8, pub leaf_index: u32, /// Index of leaf in queue. Placeholder of batched Merkle tree updates /// currently unimplemented. pub queue_index: Option<QueueIndex>, } #[derive(Debug, Clone, Copy, AnchorSerialize, AnchorDeserialize, PartialEq, Default)] pub struct QueueIndex { /// Id of queue in queue account. pub queue_id: u8, /// Index of compressed account hash in queue. pub index: u16, } pub fn pack_merkle_context( merkle_context: &[MerkleContext], remaining_accounts: &mut HashMap<Pubkey, usize>, ) -> Vec<PackedMerkleContext> { let mut merkle_context_packed = merkle_context .iter() .map(|x| PackedMerkleContext { leaf_index: x.leaf_index, merkle_tree_pubkey_index: 0, // will be assigned later nullifier_queue_pubkey_index: 0, // will be assigned later queue_index: None, }) .collect::<Vec<PackedMerkleContext>>(); let mut index: usize = remaining_accounts.len(); for (i, params) in merkle_context.iter().enumerate() { match remaining_accounts.get(&params.merkle_tree_pubkey) { Some(_) => {} None => { remaining_accounts.insert(params.merkle_tree_pubkey, index); index += 1; } }; merkle_context_packed[i].merkle_tree_pubkey_index = *remaining_accounts.get(&params.merkle_tree_pubkey).unwrap() as u8; } for (i, params) in merkle_context.iter().enumerate() { match remaining_accounts.get(&params.nullifier_queue_pubkey) { Some(_) => {} None => { remaining_accounts.insert(params.nullifier_queue_pubkey, index); index += 1; } }; merkle_context_packed[i].nullifier_queue_pubkey_index = *remaining_accounts .get(&params.nullifier_queue_pubkey) .unwrap() as u8; } merkle_context_packed } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct CompressedAccount { pub owner: Pubkey, pub lamports: u64, pub address: Option<[u8; 32]>, pub data: Option<CompressedAccountData>, } #[derive(Debug, PartialEq, Default, Clone, AnchorSerialize, AnchorDeserialize)] pub struct CompressedAccountData { pub discriminator: [u8; 8], pub data: Vec<u8>, pub data_hash: [u8; 32], } /// Hashing scheme: /// H(owner || leaf_index || merkle_tree_pubkey || lamports || address || data.discriminator || data.data_hash) impl CompressedAccount { pub fn hash_with_hashed_values<H: Hasher>( &self, &owner_hashed: &[u8; 32], &merkle_tree_hashed: &[u8; 32], leaf_index: &u32, ) -> Result<[u8; 32]> { let capacity = 3 + std::cmp::min(self.lamports, 1) as usize + self.address.is_some() as usize + self.data.is_some() as usize * 2; let mut vec: Vec<&[u8]> = Vec::with_capacity(capacity); vec.push(owner_hashed.as_slice()); // leaf index and merkle tree pubkey are used to make every compressed account hash unique let leaf_index = leaf_index.to_le_bytes(); vec.push(leaf_index.as_slice()); vec.push(merkle_tree_hashed.as_slice()); // Lamports are only hashed if non-zero to safe CU // For safety we prefix the lamports with 1 in 1 byte. // Thus even if the discriminator has the same value as the lamports, the hash will be different. let mut lamports_bytes = [1, 0, 0, 0, 0, 0, 0, 0, 0]; if self.lamports != 0 { lamports_bytes[1..].copy_from_slice(&self.lamports.to_le_bytes()); vec.push(lamports_bytes.as_slice()); } if self.address.is_some() { vec.push(self.address.as_ref().unwrap().as_slice()); } let mut discriminator_bytes = [2, 0, 0, 0, 0, 0, 0, 0, 0]; if let Some(data) = &self.data { discriminator_bytes[1..].copy_from_slice(&data.discriminator); vec.push(&discriminator_bytes); vec.push(&data.data_hash); } let hash = H::hashv(&vec).map_err(ProgramError::from)?; Ok(hash) } pub fn hash<H: Hasher>( &self, &merkle_tree_pubkey: &Pubkey, leaf_index: &u32, ) -> Result<[u8; 32]> { self.hash_with_hashed_values::<H>( &hash_to_bn254_field_size_be(&self.owner.to_bytes()) .unwrap() .0, &hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0, leaf_index, ) } } #[cfg(test)] mod tests { use light_hasher::Poseidon; use solana_sdk::signature::{Keypair, Signer}; use super::*; /// Tests: /// 1. functional with all inputs set /// 2. no data /// 3. no address /// 4. no address and no lamports /// 5. no address and no data /// 6. no address, no data, no lamports #[test] fn test_compressed_account_hash() { let owner = Keypair::new().pubkey(); let address = [1u8; 32]; let data = CompressedAccountData { discriminator: [1u8; 8], data: vec![2u8; 32], data_hash: [3u8; 32], }; let lamports = 100; let compressed_account = CompressedAccount { owner, lamports, address: Some(address), data: Some(data.clone()), }; let merkle_tree_pubkey = Keypair::new().pubkey(); let leaf_index = 1; let hash = compressed_account .hash::<Poseidon>(&merkle_tree_pubkey, &leaf_index) .unwrap(); let hash_manual = Poseidon::hashv(&[ hash_to_bn254_field_size_be(&owner.to_bytes()) .unwrap() .0 .as_slice(), leaf_index.to_le_bytes().as_slice(), hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0 .as_slice(), [&[1u8], lamports.to_le_bytes().as_slice()] .concat() .as_slice(), address.as_slice(), [&[2u8], data.discriminator.as_slice()].concat().as_slice(), &data.data_hash, ]) .unwrap(); assert_eq!(hash, hash_manual); assert_eq!(hash.len(), 32); // no data let compressed_account = CompressedAccount { owner, lamports, address: Some(address), data: None, }; let no_data_hash = compressed_account .hash::<Poseidon>(&merkle_tree_pubkey, &leaf_index) .unwrap(); let hash_manual = Poseidon::hashv(&[ hash_to_bn254_field_size_be(&owner.to_bytes()) .unwrap() .0 .as_slice(), leaf_index.to_le_bytes().as_slice(), hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0 .as_slice(), [&[1u8], lamports.to_le_bytes().as_slice()] .concat() .as_slice(), address.as_slice(), ]) .unwrap(); assert_eq!(no_data_hash, hash_manual); assert_ne!(hash, no_data_hash); // no address let compressed_account = CompressedAccount { owner, lamports, address: None, data: Some(data.clone()), }; let no_address_hash = compressed_account .hash::<Poseidon>(&merkle_tree_pubkey, &leaf_index) .unwrap(); let hash_manual = Poseidon::hashv(&[ hash_to_bn254_field_size_be(&owner.to_bytes()) .unwrap() .0 .as_slice(), leaf_index.to_le_bytes().as_slice(), hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0 .as_slice(), [&[1u8], lamports.to_le_bytes().as_slice()] .concat() .as_slice(), [&[2u8], data.discriminator.as_slice()].concat().as_slice(), &data.data_hash, ]) .unwrap(); assert_eq!(no_address_hash, hash_manual); assert_ne!(hash, no_address_hash); assert_ne!(no_data_hash, no_address_hash); // no address no lamports let compressed_account = CompressedAccount { owner, lamports: 0, address: None, data: Some(data.clone()), }; let no_address_no_lamports_hash = compressed_account .hash::<Poseidon>(&merkle_tree_pubkey, &leaf_index) .unwrap(); let hash_manual = Poseidon::hashv(&[ hash_to_bn254_field_size_be(&owner.to_bytes()) .unwrap() .0 .as_slice(), leaf_index.to_le_bytes().as_slice(), hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0 .as_slice(), [&[2u8], data.discriminator.as_slice()].concat().as_slice(), &data.data_hash, ]) .unwrap(); assert_eq!(no_address_no_lamports_hash, hash_manual); assert_ne!(hash, no_address_no_lamports_hash); assert_ne!(no_data_hash, no_address_no_lamports_hash); assert_ne!(no_address_hash, no_address_no_lamports_hash); // no address and no data let compressed_account = CompressedAccount { owner, lamports, address: None, data: None, }; let no_address_no_data_hash = compressed_account .hash::<Poseidon>(&merkle_tree_pubkey, &leaf_index) .unwrap(); let hash_manual = Poseidon::hashv(&[ hash_to_bn254_field_size_be(&owner.to_bytes()) .unwrap() .0 .as_slice(), leaf_index.to_le_bytes().as_slice(), hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0 .as_slice(), [&[1u8], lamports.to_le_bytes().as_slice()] .concat() .as_slice(), ]) .unwrap(); assert_eq!(no_address_no_data_hash, hash_manual); assert_ne!(hash, no_address_no_data_hash); assert_ne!(no_data_hash, no_address_no_data_hash); assert_ne!(no_address_hash, no_address_no_data_hash); assert_ne!(no_address_no_lamports_hash, no_address_no_data_hash); // no address, no data, no lamports let compressed_account = CompressedAccount { owner, lamports: 0, address: None, data: None, }; let no_address_no_data_no_lamports_hash = compressed_account .hash::<Poseidon>(&merkle_tree_pubkey, &leaf_index) .unwrap(); let hash_manual = Poseidon::hashv(&[ hash_to_bn254_field_size_be(&owner.to_bytes()) .unwrap() .0 .as_slice(), leaf_index.to_le_bytes().as_slice(), hash_to_bn254_field_size_be(&merkle_tree_pubkey.to_bytes()) .unwrap() .0 .as_slice(), ]) .unwrap(); assert_eq!(no_address_no_data_no_lamports_hash, hash_manual); assert_ne!(no_address_no_data_hash, no_address_no_data_no_lamports_hash); assert_ne!(hash, no_address_no_data_no_lamports_hash); assert_ne!(no_data_hash, no_address_no_data_no_lamports_hash); assert_ne!(no_address_hash, no_address_no_data_no_lamports_hash); assert_ne!( no_address_no_lamports_hash, no_address_no_data_no_lamports_hash ); } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/processor.rs
pub use anchor_lang::prelude::*; use light_heap::{bench_sbf_end, bench_sbf_start}; use super::verify_signer::cpi_signer_checks; use crate::{ invoke::processor::process, invoke_cpi::instruction::InvokeCpiInstruction, sdk::accounts::SignerAccounts, InstructionDataInvoke, InstructionDataInvokeCpi, }; /// Processes an `InvokeCpi` instruction. /// Checks: /// 1. signer checks (inputs), writeaccess (outputs) (cpi_signer_checks) /// 2. sets or gets cpi context (process_cpi_context) #[allow(unused_mut)] pub fn process_invoke_cpi<'a, 'b, 'c: 'info + 'b, 'info>( mut ctx: Context<'a, 'b, 'c, 'info, InvokeCpiInstruction<'info>>, inputs: InstructionDataInvokeCpi, ) -> Result<()> { bench_sbf_start!("cpda_cpi_signer_checks"); cpi_signer_checks( &ctx.accounts.invoking_program.key(), &ctx.accounts.get_authority().key(), &inputs.input_compressed_accounts_with_merkle_context, &inputs.output_compressed_accounts, )?; bench_sbf_end!("cpda_cpi_signer_checks"); bench_sbf_start!("cpda_process_cpi_context"); #[allow(unused)] let mut cpi_context_inputs_len = if let Some(value) = ctx.accounts.cpi_context_account.as_ref() { value.context.len() } else { 0 }; let inputs = match crate::invoke_cpi::process_cpi_context::process_cpi_context( inputs, &mut ctx.accounts.cpi_context_account, ctx.accounts.fee_payer.key(), ctx.remaining_accounts, ) { Ok(Some(inputs)) => inputs, Ok(None) => return Ok(()), Err(err) => return Err(err), }; bench_sbf_end!("cpda_process_cpi_context"); let data = InstructionDataInvoke { input_compressed_accounts_with_merkle_context: inputs .input_compressed_accounts_with_merkle_context, output_compressed_accounts: inputs.output_compressed_accounts, relay_fee: inputs.relay_fee, proof: inputs.proof, new_address_params: inputs.new_address_params, compress_or_decompress_lamports: inputs.compress_or_decompress_lamports, is_compress: inputs.is_compress, }; process( data, Some(ctx.accounts.invoking_program.key()), ctx, cpi_context_inputs_len, ) }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/process_cpi_context.rs
use super::{account::CpiContextAccount, InstructionDataInvokeCpi}; use crate::errors::SystemProgramError; use anchor_lang::prelude::*; /// Cpi context enables the use of input compressed accounts owned by different /// programs. /// /// Example: /// - a transaction calling a pda program needs to transfer tokens and modify a /// compressed pda /// - the pda is owned by pda program while the tokens are owned by the compressed /// token program /// /// without cpi context: /// - naively invoking each compressed token via cpi and modifying the pda /// requires two proofs 128 bytes and ~100,000 CU each /// /// with cpi context: /// - only one proof is required -> less instruction data and CU cost /// 1. first invocation (token program) performs signer checks of the compressed /// token accounts, caches these in the cpi context and returns. The state /// transition is not executed yet. /// 2. second invocation (pda program) performs signer checks of the pda /// compressed account, reads cpi context and combines the instruction inputs /// with verified inputs from the cpi context. The proof is verified and /// other state transition is executed with the combined inputs. pub fn process_cpi_context<'info>( mut inputs: InstructionDataInvokeCpi, cpi_context_account: &mut Option<Account<'info, CpiContextAccount>>, fee_payer: Pubkey, remaining_accounts: &[AccountInfo<'info>], ) -> Result<Option<InstructionDataInvokeCpi>> { let cpi_context = &inputs.cpi_context; if cpi_context_account.is_some() && cpi_context.is_none() { msg!("cpi context account is some but cpi context is none"); return err!(SystemProgramError::CpiContextMissing); } if let Some(cpi_context) = cpi_context { let cpi_context_account = match cpi_context_account { Some(cpi_context_account) => cpi_context_account, None => return err!(SystemProgramError::CpiContextAccountUndefined), }; let index = if !inputs .input_compressed_accounts_with_merkle_context .is_empty() { inputs.input_compressed_accounts_with_merkle_context[0] .merkle_context .merkle_tree_pubkey_index } else if !inputs.output_compressed_accounts.is_empty() { inputs.output_compressed_accounts[0].merkle_tree_index } else { return err!(SystemProgramError::NoInputs); }; let first_merkle_tree_pubkey = remaining_accounts[index as usize].key(); if first_merkle_tree_pubkey != cpi_context_account.associated_merkle_tree { msg!( "first_merkle_tree_pubkey {:?} != associated_merkle_tree {:?}", first_merkle_tree_pubkey, cpi_context_account.associated_merkle_tree ); return err!(SystemProgramError::CpiContextAssociatedMerkleTreeMismatch); } if cpi_context.set_context { set_cpi_context(fee_payer, cpi_context_account, inputs)?; return Ok(None); } else { if cpi_context_account.context.is_empty() { msg!("cpi context account : {:?}", cpi_context_account); msg!("fee payer : {:?}", fee_payer); msg!("cpi context : {:?}", cpi_context); return err!(SystemProgramError::CpiContextEmpty); } else if cpi_context_account.fee_payer != fee_payer || cpi_context.first_set_context { msg!("cpi context account : {:?}", cpi_context_account); msg!("fee payer : {:?}", fee_payer); msg!("cpi context : {:?}", cpi_context); return err!(SystemProgramError::CpiContextFeePayerMismatch); } inputs.combine(&cpi_context_account.context); // Reset cpi context account cpi_context_account.context = Vec::new(); cpi_context_account.fee_payer = Pubkey::default(); } } Ok(Some(inputs)) } pub fn set_cpi_context( fee_payer: Pubkey, cpi_context_account: &mut CpiContextAccount, mut inputs: InstructionDataInvokeCpi, ) -> Result<()> { // SAFETY Assumptions: // - previous data in cpi_context_account // -> we require the account to be wiped in the beginning of a // transaction // - leaf over data: There cannot be any leftover data in the // account since if the transaction fails the account doesn't change. // Expected usage: // 1. The first invocation is marked with // No need to store the proof (except in first invokation), // cpi context, compress_or_decompress_lamports, // relay_fee // 2. Subsequent invocations check the proof and fee payer if inputs.cpi_context.unwrap().first_set_context { clean_input_data(&mut inputs); cpi_context_account.context = vec![inputs]; cpi_context_account.fee_payer = fee_payer; } else if fee_payer == cpi_context_account.fee_payer && !cpi_context_account.context.is_empty() { clean_input_data(&mut inputs); cpi_context_account.context.push(inputs); } else { msg!(" {} != {}", fee_payer, cpi_context_account.fee_payer); return err!(SystemProgramError::CpiContextFeePayerMismatch); } Ok(()) } fn clean_input_data(inputs: &mut InstructionDataInvokeCpi) { inputs.cpi_context = None; inputs.compress_or_decompress_lamports = None; inputs.relay_fee = None; inputs.proof = None; } /// Set cpi context tests: /// 1. Functional: Set cpi context first invocation /// 2. Functional: Set cpi context subsequent invocation /// 3. Failing: Set cpi context fee payer mismatch /// 4. Failing: Set cpi context without first context /// /// process cpi context: /// 1. CpiContextMissing /// 2. CpiContextAccountUndefined /// 3. NoInputs /// 4. CpiContextAssociatedMerkleTreeMismatch /// 5. CpiContextEmpty /// 6. CpiContextFeePayerMismatch /// /// Functional process cpi context: /// 1. Set context /// 2. Combine (with malicious input in cpi context account) #[cfg(test)] mod tests { use std::cell::RefCell; use crate::{ sdk::{ compressed_account::{ CompressedAccount, PackedCompressedAccountWithMerkleContext, PackedMerkleContext, }, CompressedCpiContext, }, NewAddressParamsPacked, OutputCompressedAccountWithPackedContext, }; use super::*; use anchor_lang::solana_program::pubkey::Pubkey; fn create_test_cpi_context_account() -> CpiContextAccount { CpiContextAccount { fee_payer: Pubkey::new_unique(), associated_merkle_tree: Pubkey::new_unique(), context: vec![], } } fn create_test_instruction_data( first_set_context: bool, set_context: bool, iter: u8, ) -> InstructionDataInvokeCpi { InstructionDataInvokeCpi { proof: None, new_address_params: vec![NewAddressParamsPacked { seed: vec![iter; 32].try_into().unwrap(), address_merkle_tree_account_index: iter, address_merkle_tree_root_index: iter.into(), address_queue_account_index: iter, }], input_compressed_accounts_with_merkle_context: vec![ PackedCompressedAccountWithMerkleContext { compressed_account: CompressedAccount { owner: Pubkey::new_unique(), lamports: iter.into(), address: None, data: None, }, merkle_context: PackedMerkleContext { merkle_tree_pubkey_index: 0, nullifier_queue_pubkey_index: iter, leaf_index: 0, queue_index: None, }, root_index: iter.into(), read_only: false, }, ], output_compressed_accounts: vec![OutputCompressedAccountWithPackedContext { compressed_account: CompressedAccount { owner: Pubkey::new_unique(), lamports: iter.into(), address: None, data: None, }, merkle_tree_index: iter, }], relay_fee: None, compress_or_decompress_lamports: None, is_compress: false, cpi_context: Some(CompressedCpiContext { first_set_context, set_context, cpi_context_account_index: 0, }), } } #[test] fn test_set_cpi_context_first_invocation() { let fee_payer = Pubkey::new_unique(); let mut cpi_context_account = create_test_cpi_context_account(); let mut inputs = create_test_instruction_data(true, true, 1); let result = set_cpi_context(fee_payer, &mut cpi_context_account, inputs.clone()); assert!(result.is_ok()); assert_eq!(cpi_context_account.fee_payer, fee_payer); assert_eq!(cpi_context_account.context.len(), 1); assert_ne!(cpi_context_account.context[0], inputs); clean_input_data(&mut inputs); assert_eq!(cpi_context_account.context[0], inputs); } #[test] fn test_set_cpi_context_subsequent_invocation() { let fee_payer = Pubkey::new_unique(); let mut cpi_context_account = create_test_cpi_context_account(); let inputs_first = create_test_instruction_data(true, true, 1); set_cpi_context(fee_payer, &mut cpi_context_account, inputs_first.clone()).unwrap(); let mut inputs_subsequent = create_test_instruction_data(false, true, 2); let result = set_cpi_context( fee_payer, &mut cpi_context_account, inputs_subsequent.clone(), ); assert!(result.is_ok()); assert_eq!(cpi_context_account.context.len(), 2); clean_input_data(&mut inputs_subsequent); assert_eq!(cpi_context_account.context[1], inputs_subsequent); } #[test] fn test_set_cpi_context_fee_payer_mismatch() { let fee_payer = Pubkey::new_unique(); let mut cpi_context_account = create_test_cpi_context_account(); let inputs_first = create_test_instruction_data(true, true, 1); set_cpi_context(fee_payer, &mut cpi_context_account, inputs_first.clone()).unwrap(); let different_fee_payer = Pubkey::new_unique(); let inputs_subsequent = create_test_instruction_data(false, true, 2); let result = set_cpi_context( different_fee_payer, &mut cpi_context_account, inputs_subsequent, ); assert!(result.is_err()); } #[test] fn test_set_cpi_context_without_first_context() { let fee_payer = Pubkey::new_unique(); let mut cpi_context_account = create_test_cpi_context_account(); let inputs_first = create_test_instruction_data(false, true, 1); let result = set_cpi_context(fee_payer, &mut cpi_context_account, inputs_first.clone()); assert_eq!( result, Err(SystemProgramError::CpiContextFeePayerMismatch.into()) ); } /// Check: process cpi 1 #[test] fn test_process_cpi_context_both_none() { let fee_payer = Pubkey::new_unique(); let inputs = create_test_instruction_data(false, true, 1); let mut cpi_context_account: Option<Account<CpiContextAccount>> = None; let result = process_cpi_context(inputs.clone(), &mut cpi_context_account, fee_payer, &[]); assert_eq!( result, Err(SystemProgramError::CpiContextAccountUndefined.into()) ); } /// Check: process cpi 1 #[test] fn test_process_cpi_context_account_none_context_some() { let fee_payer = Pubkey::new_unique(); let inputs = create_test_instruction_data(false, true, 1); let mut cpi_context_account: Option<Account<CpiContextAccount>> = None; let result = process_cpi_context(inputs, &mut cpi_context_account, fee_payer, &[]); assert_eq!( result, Err(SystemProgramError::CpiContextAccountUndefined.into()) ); } /// Check: process cpi 2 #[test] fn test_process_cpi_context_account_some_context_none() { let fee_payer = Pubkey::new_unique(); let inputs = InstructionDataInvokeCpi { cpi_context: None, ..create_test_instruction_data(false, true, 1) }; let mut lamports = 0; let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: Pubkey::new_unique(), context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let result = process_cpi_context(inputs, &mut cpi_context_account, fee_payer, &[]); assert_eq!(result, Err(SystemProgramError::CpiContextMissing.into())); } /// Check: process cpi 3 #[test] fn test_process_cpi_no_inputs() { let fee_payer = Pubkey::new_unique(); let mut inputs = create_test_instruction_data(false, true, 1); inputs.input_compressed_accounts_with_merkle_context = vec![]; inputs.output_compressed_accounts = vec![]; let mut lamports = 0; let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: Pubkey::new_unique(), context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let result = process_cpi_context(inputs, &mut cpi_context_account, fee_payer, &[]); assert_eq!(result, Err(SystemProgramError::NoInputs.into())); } /// Check: process cpi 4 #[test] fn test_process_cpi_context_associated_tree_mismatch() { let fee_payer = Pubkey::new_unique(); let inputs = create_test_instruction_data(true, true, 1); let mut lamports = 0; let merkle_tree_pubkey = Pubkey::new_unique(); let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: merkle_tree_pubkey, context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let mut mt_lamports = 0; let mut data = vec![172, 43, 172, 186, 29, 73, 219, 84]; let invalid_merkle_tree_pubkey = Pubkey::new_unique(); let merkle_tree_account_info = AccountInfo { key: &invalid_merkle_tree_pubkey, is_signer: false, is_writable: false, lamports: RefCell::new(&mut mt_lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let remaining_accounts = &[merkle_tree_account_info]; let result = process_cpi_context( inputs, &mut cpi_context_account, fee_payer, remaining_accounts, ); assert_eq!( result, Err(SystemProgramError::CpiContextAssociatedMerkleTreeMismatch.into()) ); } /// Check: process cpi 5 #[test] fn test_process_cpi_context_no_set_context() { let fee_payer = Pubkey::new_unique(); let inputs = create_test_instruction_data(false, false, 1); let mut lamports = 0; let merkle_tree_pubkey = Pubkey::new_unique(); let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: merkle_tree_pubkey, context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let mut mt_lamports = 0; let mut data = vec![172, 43, 172, 186, 29, 73, 219, 84]; let merkle_tree_account_info = AccountInfo { key: &merkle_tree_pubkey, is_signer: false, is_writable: false, lamports: RefCell::new(&mut mt_lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let remaining_accounts = &[merkle_tree_account_info]; let result = process_cpi_context( inputs.clone(), &mut cpi_context_account, fee_payer, remaining_accounts, ); assert_eq!(result, Err(SystemProgramError::CpiContextEmpty.into())); } /// Check: process cpi 6 #[test] fn test_process_cpi_context_empty_context_error() { let fee_payer = Pubkey::default(); let inputs = create_test_instruction_data(false, true, 1); let mut lamports = 0; let merkle_tree_pubkey = Pubkey::new_unique(); let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: merkle_tree_pubkey, context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let mut mt_lamports = 0; let mut data = vec![172, 43, 172, 186, 29, 73, 219, 84]; let merkle_tree_account_info = AccountInfo { key: &merkle_tree_pubkey, is_signer: false, is_writable: false, lamports: RefCell::new(&mut mt_lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let remaining_accounts = &[merkle_tree_account_info]; let result = process_cpi_context( inputs, &mut cpi_context_account, fee_payer, remaining_accounts, ); assert_eq!( result, Err(SystemProgramError::CpiContextFeePayerMismatch.into()) ); } /// Check: process cpi 6 #[test] fn test_process_cpi_context_fee_payer_mismatch_error() { let fee_payer = Pubkey::new_unique(); let inputs = create_test_instruction_data(true, true, 1); let mut lamports = 0; let merkle_tree_pubkey = Pubkey::new_unique(); let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: merkle_tree_pubkey, context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let mut mt_lamports = 0; let mut data = vec![172, 43, 172, 186, 29, 73, 219, 84]; let merkle_tree_account_info = AccountInfo { key: &merkle_tree_pubkey, is_signer: false, is_writable: false, lamports: RefCell::new(&mut mt_lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let remaining_accounts = &[merkle_tree_account_info]; let result = process_cpi_context( inputs.clone(), &mut cpi_context_account, fee_payer, remaining_accounts, ); assert!(result.is_ok()); let invalid_fee_payer = Pubkey::new_unique(); let inputs = create_test_instruction_data(false, true, 1); let result = process_cpi_context( inputs, &mut cpi_context_account, invalid_fee_payer, remaining_accounts, ); assert_eq!( result, Err(SystemProgramError::CpiContextFeePayerMismatch.into()) ); } #[test] fn test_process_cpi_context_set_context() { let fee_payer = Pubkey::new_unique(); let mut inputs = create_test_instruction_data(true, true, 1); let mut lamports = 0; let merkle_tree_pubkey = Pubkey::new_unique(); let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: merkle_tree_pubkey, context: vec![], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let mut mt_lamports = 0; let mut data = vec![172, 43, 172, 186, 29, 73, 219, 84]; let merkle_tree_account_info = AccountInfo { key: &merkle_tree_pubkey, is_signer: false, is_writable: false, lamports: RefCell::new(&mut mt_lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let remaining_accounts = &[merkle_tree_account_info]; let result = process_cpi_context( inputs.clone(), &mut cpi_context_account, fee_payer, remaining_accounts, ); assert!(result.is_ok()); assert_eq!(cpi_context_account.as_ref().unwrap().context.len(), 1); assert_eq!(cpi_context_account.as_ref().unwrap().fee_payer, fee_payer); clean_input_data(&mut inputs); assert_eq!(cpi_context_account.as_ref().unwrap().context[0], inputs); assert_eq!(result.unwrap(), None); } #[test] fn test_process_cpi_context_combine() { let fee_payer = Pubkey::new_unique(); let mut inputs = create_test_instruction_data(true, true, 1); let malicious_inputs = create_test_instruction_data(true, true, 100); let mut lamports = 0; let merkle_tree_pubkey = Pubkey::new_unique(); let cpi_context_content = CpiContextAccount { fee_payer: Pubkey::default(), associated_merkle_tree: merkle_tree_pubkey, context: vec![malicious_inputs], }; let mut data = vec![22, 20, 149, 218, 74, 204, 128, 166]; data.extend_from_slice(&cpi_context_content.try_to_vec().unwrap()); let account_info = AccountInfo { key: &Pubkey::new_unique(), is_signer: false, is_writable: false, lamports: RefCell::new(&mut lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let mut cpi_context_account = Some(Account::try_from(account_info.as_ref()).unwrap()); let mut mt_lamports = 0; let mut data = vec![172, 43, 172, 186, 29, 73, 219, 84]; let merkle_tree_account_info = AccountInfo { key: &merkle_tree_pubkey, is_signer: false, is_writable: false, lamports: RefCell::new(&mut mt_lamports).into(), data: RefCell::new(data.as_mut_slice()).into(), owner: &crate::ID, rent_epoch: 0, executable: false, }; let remaining_accounts = &[merkle_tree_account_info]; let result = process_cpi_context( inputs.clone(), &mut cpi_context_account, fee_payer, remaining_accounts, ); assert!(result.is_ok()); assert_eq!(cpi_context_account.as_ref().unwrap().context.len(), 1); assert_eq!(cpi_context_account.as_ref().unwrap().fee_payer, fee_payer); clean_input_data(&mut inputs); assert_eq!(cpi_context_account.as_ref().unwrap().context[0], inputs); assert_eq!(result.unwrap(), None); for i in 2..10 { let mut inputs = create_test_instruction_data(false, true, i); let result = process_cpi_context( inputs.clone(), &mut cpi_context_account, fee_payer, remaining_accounts, ); assert!(result.is_ok()); assert_eq!( cpi_context_account.as_ref().unwrap().context.len(), i as usize ); assert_eq!(cpi_context_account.as_ref().unwrap().fee_payer, fee_payer); clean_input_data(&mut inputs); assert_eq!( cpi_context_account.as_ref().unwrap().context[(i - 1) as usize], inputs ); assert_eq!(result.unwrap(), None); } let inputs = create_test_instruction_data(false, false, 10); let result = process_cpi_context( inputs.clone(), &mut cpi_context_account, fee_payer, remaining_accounts, ); assert!(result.is_ok()); let result = result.unwrap().unwrap(); for i in 1..10 { assert_eq!( result.output_compressed_accounts[i] .compressed_account .lamports, i as u64 ); assert_eq!( result.input_compressed_accounts_with_merkle_context[i] .compressed_account .lamports, i as u64 ); assert_eq!( result.new_address_params[i].seed, <[u8; 32]>::try_from(vec![i as u8; 32]).unwrap() ); } assert_eq!( cpi_context_account.as_ref().unwrap().associated_merkle_tree, merkle_tree_pubkey ); assert_eq!( cpi_context_account.as_ref().unwrap().fee_payer, Pubkey::default() ); assert_eq!(cpi_context_account.as_ref().unwrap().context.len(), 0); } }
0
solana_public_repos/Lightprotocol/light-protocol/programs/system/src
solana_public_repos/Lightprotocol/light-protocol/programs/system/src/invoke_cpi/initialize.rs
use account_compression::StateMerkleTreeAccount; use anchor_lang::prelude::*; use super::account::CpiContextAccount; pub const CPI_SEED: &[u8] = b"cpi_signature_pda"; #[derive(Accounts)] pub struct InitializeCpiContextAccount<'info> { #[account(mut)] pub fee_payer: Signer<'info>, #[account(zero)] pub cpi_context_account: Account<'info, CpiContextAccount>, pub associated_merkle_tree: AccountLoader<'info, StateMerkleTreeAccount>, }
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(), &current_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/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], &registered_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