Arcium 백서

Arcium

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 17쪽 중 13쪽

tions_sysvar` * Accepts custom accounts through the `&[CallbackAccount]` parameter * Eliminates boilerplate and prevents errors ```rust theme={null} pub fn add_together( ctx: Context<AddTogether>, computation_offset: u64, ciphertext_0: [u8; 32], ciphertext_1: [u8; 32], pub_key: [u8; 32], nonce: u128, ) -> Result<()> { // Note: Using `create_program_address` with the bump would be more efficient than `find_program_address`. // Since this PDA is constant, you could also derive it at compile time and save it as a constant. // We use find_program_address here for simplicity. let addition_result_pda = Pubkey::find_program_address(&[b"AdditionResult"], ctx.program_id).0; // Build the args the encrypted instruction expects using ArgBuilder let args = ArgBuilder::new() .x25519_pubkey(pub_key) .plaintext_u128(nonce) .encrypted_u8(ciphertext_0) .encrypted_u8(ciphertext_1) .build(); // Set the bump for the sign_pda_account ctx.accounts.sign_pda_account.bump = ctx.bumps.sign_pda_account; // Build & queue our computation (via CPI to the Arcium program) queue_computation( ctx.accounts, // Random offset for the computation computation_offset, // The one-time inputs our encrypted instruction expects args, // Using callback_ix() helper - automatically includes the 6 standard accounts // (arcium_program, comp_def_account, mxe_account, computation_account, cluster_account, instructions_sysvar) plus our custom account vec![AddTogetherCallback::callback_ix( computation_offset, &ctx.accounts.mxe_account, &[ CallbackAccount { pubkey: addition_result_pda, is_writable: true, // Tells nodes to mark this account as writable in the transaction } ] )?], 1, // Number of transactions needed for callback 0, // cu_price_micro: priority fee in microlamports (0 = no priority fee) 0, // callback_cu_limit: 0 derives the limit from simulation )?; Ok(()) } /* The AddTogether accounts struct stays exactly the same as shown in the basic guide */ ``` #### Understanding what happens: manual CallbackInstruction For educational purposes, here's what `callback_ix()` generates under the hood. This manual approach is functionally equivalent but more verbose and error-prone: ```rust theme={null} pub fn add_together( ctx: Context<AddTogether>, computation_offset: u64, ciphertext_0: [u8; 32], ciphertext_1: [u8; 32], pub_key: [u8; 32], nonce: u128, ) -> Result<()> { // Note: Using `create_program_address` with the bump would be more efficient than `find_program_address`. // Since this PDA is constant, you could also derive it at compile time and save it as a constant. // We use find_program_address here for simplicity. let addition_result_pda = Pubkey::find_program_address(&[b"AdditionResult"], ctx.program_id).0; // Build the args the encrypted instruction expects using ArgBuilder let args = ArgBuilder::new() .x25519_pubkey(pub_key) .plaintext_u128(nonce) .encrypted_u8(ciphertext_0) .encrypted_u8(ciphertext_1) .build(); // Set the bump for the sign_pda_account ctx.accounts.sign_pda_account.bump = ctx.bumps.sign_pda_account; // Build & queue our computation (via CPI to the Arcium program) queue_computation( ctx.accounts, // Random offset for the computation computation_offset, // The one-time inputs our encrypted instruction expects args, // Manual approach: Define which callback instruction to call when the computation is complete. // We specify the program ID, instruction discriminator, and all accounts needed // for the callback, including our result account which we want to be writable. vec![CallbackInstruction { program_id: ID_CONST, discriminator: instruction::AddTogetherCallback::DISCRIMINATOR.to_vec(), accounts: vec![ // Standard accounts (always required, in this order) CallbackAccount { pubkey: ::arcium_client::ARCIUM_PROGRAM_ID, is_writable: false, }, CallbackAccount { pubkey: derive_comp_def_pda!(COMP_DEF_OFFSET_ADD_TOGETHER), is_writable: false, }, CallbackAccount { pubkey: ctx.accounts.mxe_account.key(), is_writable: false, }, CallbackAccount { pubkey: ctx.accounts.computation_account.key(), is_writable: false, }, CallbackAccount { pubkey: derive_cluster_pda!(ctx.accounts.mxe_account), is_writable: false, }, CallbackAccount { pubkey: INSTRUCTIONS_SYSVAR_ID, is_writable: false, }, // Custom accounts (your callback-specific accounts) CallbackAccount { pubkey: addition_result_pda, is_writable: true, // Tells nodes to mark this account as writable in the transaction } ] }], 1, // Number of transactions needed for callback (1 for simple computations) 0, // cu_price_micro: priority fee in microlamports (0 = no priority fee) 0, // callback_cu_limit: 0 derives the limit from simulation )?; Ok(()) } /* The AddTogether accounts struct stays exactly the same as shown in the basic guide */ ``` **Key point**: Both approaches are functionally equivalent. The `callback_ix()` method automatically generates the exact same `CallbackInstruction` structure as the manual approach, but with less code and reduced chance for errors. **Important**: We added the account to the callback (either via `callback_ix()` parameter or `CallbackInstruction.accounts`) but didn't include it in the AddTogether accounts struct because we don't read or write to it during the queue function - only during the callback. ### Step 3: Implement the callback function The callback instruction receives the accounts in the exact order specified in the queue function: ```rust theme={null} // Macro provided by the Arcium SDK to define a callback instruction. #[arcium_callback(encrypted_ix = "add_together")] pub fn add_together_callback( ctx: Context<AddTogetherCallback>, output: SignedComputationOutputs<AddTogetherOutput>, ) -> Result<()> { let o = match output.verify_output( &ctx.accounts.cluster_account, &ctx.accounts.computation_account ) { Ok(AddTogetherOutput { field_0 }) => field_0, Err(e) => { msg!("Error: {}", e); return Err(ErrorCode::AbortedComputation.into()) }, }; emit!(SumEvent { sum: o.ciphertexts[0], nonce: o.nonce.to_le_bytes(), }); // Save the result in our callback account too ctx.accounts.add_result_account.sum = o.ciphertexts[0]; Ok(()) } #[callback_accounts("add_together")] #[derive(Accounts)] pub struct AddTogetherCallback<'info> { // Standard accounts required for all callbacks pub arcium_program: Program<'info, Arcium>, #[account( address = derive_comp_def_pda!(COMP_DEF_OFFSET_ADD_TOGETHER) )] pub comp_def_account: Account<'info, ComputationDefinitionAccount>, #[account( address = derive_mxe_pda!() )] pub mxe_account: Account<'info, MXEAccount>, /// CHECK: computation_account, checked by arcium program via constraints in the callback context. pub computation_account: UncheckedAccount<'info>, #[account( address = derive_cluster_pda!(mxe_account) )] pub cluster_account: Account<'info, Cluster>, /// CHECK: instructions_sysvar, checked by the account constraint #[account(address = ::arcium_anchor::solana_instructions_sysvar::ID)] pub instructions_sysvar: UncheckedAccount<'info>, // Custom accounts (match remaining accounts in CallbackInstruction.accounts) #[account( mut, seeds = [b"AdditionResult"], // Note: In a real implementation you should usually save the bump too, // but for the sake of simplicity in this example we skip that bump )] pub add_result_account: Account<'info, SecretAdditionResult>, } ``` ## Key requirements & constraints ### Follow callback instruction rules * The first callback instruction must target the MXE that owns the computation. Later instructions may target other programs because only the first receives the computation output. * Callback accounts cannot be signers. * Custom callback accounts cannot reuse the cluster node callback authority or Arx account. * Prefer the generated `callback_ix()` helper, which constructs the standard accounts and targets the owning MXE. Place that instruction first in the callback instruction list. ### Account ordering The accounts in your callback struct **must match exactly** the order in `CallbackInstruction.accounts`: 1. Standard accounts are always required first: `arcium_program`, `comp_def_account`, `mxe_account`, `computation_account`, `cluster_account`, `instructions_sysvar` 2. Custom accounts follow in the exact sequence you specified ### Account creation rules * **Can create** accounts in the queue computation function (user pays rent) * **Cannot create** accounts during callback execution (would require nodes to pay) * Accounts must exist before the callback executes * Account size cannot change during callback ### Writability requirements * Set `is_writable: true` in CallbackAccount to tell nodes to mark the account as writable * The account must have `#[account(mut)]` in the callback struct * Without proper writability flags, mutations will fail ## Troubleshooting **Account not found**: Ensure the account exists before callback execution. Initialize it in the queue function or a separate instruction. **Order mismatch errors**: Double-check that your callback struct accounts are in the exact same order as the CallbackInstruction.accounts vector. **Cannot modify account**: Verify both `is_writable: true` in CallbackAccount and `#[account(mut)]` in the callback struct are set. **Size errors**: Callback accounts cannot be resized. Allocate sufficient space when creating the account. ## Understanding callback\_ix() in detail The `callback_ix()` method you see throughout these examples is a convenient helper that's automatically generated by the `#[callback_accounts]` macro. ### How callback\_ix() works When you define a callback struct with `#[callback_accounts("instruction_name")]`, the macro automatically generates a `callback_ix()` method that: 1. **Takes required parameters**: `computation_offset` and `&mxe_account` for proper context 2. **Creates a CallbackInstruction** with the proper instruction data 3. **Automatically includes standard accounts** that every callback needs: * `arcium_program`: The Arcium program that will invoke your callback * `comp_def_account`: The computation definition account for your encrypted instruction * `mxe_account`: Your MXE's metadata and configuration * `computation_account`: The computation being processed * `cluster_account`: The MPC cluster processing the computation * `instructions_sysvar`: Solana's instructions sysvar for transaction validation 4. **Accepts custom accounts** through the `&[CallbackAccount]` parameter ### Usage patterns **Basic usage (no custom accounts):** ```rust theme={null} vec![AddTogetherCallback::callback_ix( computation_offset, &ctx.accounts.mxe_account, &[] )?] ``` The empty array indicates no custom accounts needed beyond the standard ones. **Advanced usage (with custom accounts):** ```rust theme={null} vec![AddTogetherCallback::callback_ix( computation_offset, &ctx.accounts.mxe_account, &[ CallbackAccount { pubkey: my_account.key(), is_writable: true, }, // ... more custom accounts ] )?] ``` ### Why use callback\_ix()? The `callback_ix()` helper is the **recommended approach** because it: * **Eliminates boilerplate**: No need to manually construct CallbackInstruction * **Prevents errors**: Automatically includes all required standard accounts * **Maintains consistency**: Ensures your callback instructions follow the correct format * **Simplifies maintenance**: Changes to callback requirements are handled by the macro ## Going further This guide covered the advanced patterns for working with callback accounts. To understand the fundamentals of callback instructions, see our [basic program invocation guide](/developers/program). For handling different types of encrypted data inputs and outputs, see [Arcis inputs/outputs](/developers/arcis/input-output). ## What's next? <CardGroup> <Card title="Type generation" icon="code-simple" href="/developers/program/callback-type-generation"> Understand how output types like `AddTogetherOutput` are automatically generated. </Card> <Card title="Client callbacks" icon="mobile-retro" href="/developers/js-client-library/callback"> Track computation completion from your TypeScript client. </Card> </CardGroup> # Callback type generation Source: https://docs.arcium.com/developers/program/callback-type-generation Automatic type generation for callback outputs in Arcium programs ## What this solves When you write encrypted instructions in Arcium, the results come back as structured data. Previously, developers had to manually parse raw bytes - tracking offsets, sizes, and converting back to the right types. This was error-prone and tedious. Arcium's type generation system analyzes your circuit's return type and automatically creates typed Rust structs. This means you can work directly with structured data instead of byte arrays. ## Mental model: from functions to structs Here's the transformation that happens automatically: ```rust theme={null} // You write this encrypted instruction: #[instruction] pub fn add_numbers() -> Enc<Shared, u64> { /* ... */ } // Arcium generates this for your callback: pub struct AddNumbersOutput { pub field_0: SharedEncryptedStruct<1>, // 1 = single u64 value } ``` The generated struct gives you typed access to encrypted results, with predictable naming and field patterns you can rely on. ## What you'll learn After reading this guide, you'll know how to: * Work with automatically generated Rust structs for encrypted computation outputs * Predict what struct names and fields Arcium will create * Handle different encryption types (Shared vs MXE) in callbacks * Debug type generation issues when they arise ## 30-second quick start 1. Write your circuit: ```rust theme={null} #[instruction] pub fn my_calc() -> Enc<Shared, u64> { /* ... */ } ``` 2. Generate types: `arcium build` 3. Use in callback: ```rust theme={null} #[arcium_callback(encrypted_ix = "my_calc")] pub fn my_calc_callback( ctx: Context<MyCalcCallback>, output: SignedComputationOutputs<MyCalcOutput>, ) -> Result<()> { let o = match output.verify_output( &ctx.accounts.cluster_account, &ctx.accounts.computation_account ) { Ok(MyCalcOutput { field_0 }) => field_0, Err(_) => return Err(ErrorCode::AbortedComputation.into()), }; let encrypted_value = o.ciphertexts[0]; // Your logic here Ok(()) } ``` ## Your first generated type: simple addition Here's a concrete example. Consider this encrypted instruction that adds two numbers: ```rust theme={null} #[encrypted] mod circuits { use arcis::*; #[instruction] pub fn add_together(input: Enc<Shared, (u8, u8)>) -> Enc<Shared, u16> { let (a, b) = input.to_arcis(); let sum = a as u16 + b as u16; input.owner.from_arcis(sum) } } ``` When Arcium sees that your function returns `Enc<Shared, u16>`, it automatically generates this output struct: ```rust theme={null} #[derive(AnchorSerialize, AnchorDeserialize)] pub struct AddTogetherOutput { pub field_0: SharedEncryptedStruct<1>, } ``` Notice the pattern: * **Name**: `add_together` becomes `AddTogetherOutput` * **Field**: Always `field_0` for single return values * **Type**: `SharedEncryptedStruct<1>` because it's shared-encrypted with 1 value (the u16) Now you can use this in your callback with full type safety: ```rust theme={null} #[arcium_callback(encrypted_ix = "add_together")] pub fn add_together_callback( ctx: Context<AddTogetherCallback>, output: SignedComputationOutputs<AddTogetherOutput>, ) -> Result<()> { let o = match output.verify_output( &ctx.accounts.cluster_account, &ctx.accounts.computation_account ) { Ok(AddTogetherOutput { field_0 }) => field_0, Err(_) => return Err(ErrorCode::AbortedComputation.into()), }; // Access the encrypted result and metadata emit!(SumEvent { sum: o.ciphertexts[0], // The encrypted u16 sum nonce: o.nonce.to_le_bytes(), // Nonce for decryption }); Ok(()) } ``` ## How type generation works Previously, decoding computation results required manual byte parsing. Now Arcium auto-generates typed structs, letting you focus on application logic. ### How output types are generated Type generation is a two-step process: 1. **`arcium build`** compiles your Arcis circuits and writes `.idarc` interface files describing each circuit's return type 2. **`#[callback_accounts]`** macro reads the `.idarc` file at compile time and generates the corresponding Rust struct in your program crate For example, given this encrypted instruction: ```rust theme={null} #[instruction] pub fn add_together(input: Enc<Shared, (u8, u8)>) -> Enc<Shared, u16> { // Your function code here } ``` After running `arcium build`, the `#[callback_accounts("add_together")]` macro reads `build/add_together.idarc` and generates: ```rust theme={null} // This struct is generated for you - you never write it yourself! pub struct AddTogetherOutput { pub field_0: SharedEncryptedStruct<1>, } ``` This is why you can reference `AddTogetherOutput` in your callback even though you never explicitly defined it. ### Build dependency You must run `arcium build` before compiling your program so the `.idarc` files exist for the macro to read. Run `arcium build` again whenever you change an encrypted instruction's return type. ```rust theme={null} // Available after running arcium build #[arcium_callback(encrypted_ix = "add_together")] pub fn callback( ctx: Context<AddTogetherCallback>, output: SignedComputationOutputs<AddTogetherOutput>, ) -> Result<()> { // AddTogetherOutput was generated by #[callback_accounts] from build/add_together.idarc } ``` ## Handle raw outputs Use raw outputs when a generated fixed-size type cannot represent the callback payload, such as when decoding only a prefix of a larger output. Set `auto_serialize = false`, then verify the cluster signature before consuming the decoded bytes: ```rust theme={null} #[arcium_callback(encrypted_ix = "add_order", auto_serialize = false)] pub fn add_order_callback( ctx: Context<AddOrderCallback>, output: RawComputationOutputs<[u8; 384]>, ) -> Result<()> { let _orderbook = output.verify_output( &ctx.accounts.instructions_sysvar, &ctx.accounts.cluster_account, &ctx.accounts.computation_account, )?; Ok(()) } ``` `verify_output` verifies the full signed payload from the current callback instruction, even when `T` decodes only a prefix. ## Behind the scenes: the two-step pipeline Understanding how types flow from your circuit to your Solana program helps explain why `arcium build` must run first. ### Step 1: `arcium build` produces `.idarc` files When you run `arcium build`, the compiler processes each `#[instruction]` function inside your `#[encrypted]` module: 1. **Parse the return type**: The compiler examines your function signature and extracts the return type 2. **Analyze the structure**: It breaks down complex types (tuples, structs, encryption wrappers) into components 3. **Write the interface file**: It serializes the type information to `build/{circuit_name}.idarc` ### Step 2: `#[callback_accounts]` generates Rust structs When you compile your Solana program, the `#[callback_accounts("circuit_name")]` macro: 1. **Reads the `.idarc` file**: Loads the circuit interface from `build/{circuit_name}.idarc` 2. **Generates struct definitions**: Creates typed Rust structs matching the circuit's return type 3. **Injects into scope**: The generated types become available in your program module ### What gets generated For different return types, the pipeline generates different struct patterns: ```rust theme={null} // Your function: #[instruction] pub fn simple() -> Enc<Shared, u32> // Macro generates: pub struct SimpleOutput { pub field_0: SharedEncryptedStruct<1>, } ``` ```rust theme={null} // Your function: #[instruction] pub fn complex() -> (Enc<Shared, u32>, Enc<Mxe, bool>) // Macro generates: pub struct ComplexOutput { pub field_0: ComplexOutputStruct0, } pub st
프로젝트로 돌아가기