Arcium 백서

Arcium

원문

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

gument. Use `SignedComputationOutputs<T>` with the generated `{encrypted_ix_name}Output` type by default. For custom raw decoding, use `RawComputationOutputs<T>` with `auto_serialize = false`; see [Handle raw outputs](/developers/program/callback-type-generation#handle-raw-outputs). For passing encrypted arguments, we use the `ArgBuilder` API. If the corresponding argument is `Enc<Shared, T>`, then we need to pass the `x25519_pubkey(pub_key)` and `plaintext_u128(nonce)`, before the ciphertext. If the corresponding argument is `Enc<Mxe, T>`, then we only need to pass the nonce as `plaintext_u128(nonce)` and the ciphertext. Ciphertexts are passed using methods like `encrypted_u8`, `encrypted_u16`, `encrypted_u32`, `encrypted_u64`, `encrypted_u128`, or `encrypted_bool`. ```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<()> { // 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, // Use callback_ix() helper to generate the callback instruction vec![AddTogetherCallback::callback_ix( computation_offset, &ctx.accounts.mxe_account, &[] // Empty array = no custom accounts )?], 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(()) } // 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(), }); Ok(()) } ``` A `callback_cu_limit` of `0` derives the limit from simulation and retries compute-budget exhaustion with a higher limit. Set a non-zero value to use a fixed limit. Let's also have a look at the `Accounts` structs for each of these instructions: ```rust theme={null} /// Accounts required to invoke the `add_together` encrypted instruction. /// `add_together` must be the name of the encrypted instruction we're invoking. #[queue_computation_accounts("add_together", payer)] #[derive(Accounts)] #[instruction(computation_offset: u64)] pub struct AddTogether<'info> { #[account(mut)] pub payer: Signer<'info>, #[account( init_if_needed, space = 9, payer = payer, seeds = [&SIGN_PDA_SEED], bump, address = derive_sign_pda!(), )] pub sign_pda_account: Account<'info, ArciumSignerAccount>, #[account( address = derive_mxe_pda!() )] pub mxe_account: Box<Account<'info, MXEAccount>>, #[account( mut, address = derive_mempool_pda!(mxe_account) )] /// CHECK: mempool_account, checked by the arcium program. pub mempool_account: UncheckedAccount<'info>, #[account( mut, address = derive_execpool_pda!(mxe_account) )] /// CHECK: executing_pool, checked by the arcium program. pub executing_pool: UncheckedAccount<'info>, #[account( mut, address = derive_comp_pda!(computation_offset, mxe_account) )] /// CHECK: computation_account, checked by the arcium program. pub computation_account: UncheckedAccount<'info>, #[account( address = derive_comp_def_pda!(COMP_DEF_OFFSET_ADD_TOGETHER) )] pub comp_def_account: Box<Account<'info, ComputationDefinitionAccount>>, #[account( mut, address = derive_cluster_pda!(mxe_account) )] pub cluster_account: Box<Account<'info, Cluster>>, #[account( mut, address = ARCIUM_FEE_POOL_ACCOUNT_ADDRESS, )] pub pool_account: Account<'info, FeePool>, #[account( mut, address = ARCIUM_CLOCK_ACCOUNT_ADDRESS )] pub clock_account: Account<'info, ClockAccount>, pub system_program: Program<'info, System>, pub arcium_program: Program<'info, Arcium>, } ``` That's a lot of accounts to remember! Here's what each one does: **Core MXE accounts:** * `mxe_account`: Your MXE's metadata and configuration * `mempool_account`: Queue where computations wait to be processed * `executing_pool`: Tracks computations currently being executed * `computation_account`: Stores individual computation data and results * `comp_def_account`: Definition of your encrypted instruction (circuit) **Arcium Network accounts:** * `cluster_account`: The MPC cluster that will process your computation * `pool_account`: Arcium's fee collection account * `clock_account`: Network timing information **System accounts:** * `payer`: Pays transaction fees and rent * `sign_pda_account`: PDA signer for the computation * `system_program`: Solana's system program for account creation * `arcium_program`: Arcium's core program that orchestrates MPC These accounts can be reused for any encrypted instruction. Change: 1. `COMP_DEF_OFFSET_ADD_TOGETHER` to match your instruction name 2. The instruction name in the `queue_computation_accounts` macro Callback accounts are smaller: ```rust theme={null} #[callback_accounts("add_together")] #[derive(Accounts)] pub struct AddTogetherCallback<'info> { pub arcium_program: Program<'info, Arcium>, /// COMP_DEF_OFFSET_ADD_TOGETHER is an encrypted instruction specific u32 /// offset which can be calculated with `comp_def_offset("add_together")`, where /// comp_def_offset is a function provided by the Arcium SDK and `add_together` /// is the name of the encrypted instruction we're invoking. #[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>, #[account(address = ::arcium_anchor::solana_instructions_sysvar::ID)] /// CHECK: instructions_sysvar, checked by the account constraint pub instructions_sysvar: UncheckedAccount<'info>, } ``` The callback requires fewer accounts. As with the `AddTogether` struct, change the `derive_comp_def_pda!` parameter and the instruction name in the `callback_accounts` macro for each encrypted instruction. The `callback_ix()` method is a convenient helper generated by the `#[callback_accounts]` macro that automatically creates the proper callback instruction with all required accounts. To return more than a raw value, check out [input/outputs](/developers/arcis/input-output) for how to handle encrypted data and [callback accounts](/developers/program/callback-accs) for returning additional accounts in the callback. ## What's next? <CardGroup> <Card title="Callback accounts" icon="reply" href="/developers/program/callback-accs"> Pass additional accounts to your callback for storing results. </Card> <Card title="JavaScript client" icon="js" href="/developers/js-client-library"> Encrypt inputs and invoke computations from TypeScript. </Card> <Card title="Deployment" icon="rocket" href="/developers/deployment"> Deploy your MXE to Solana devnet. </Card> <Card title="Account lifecycle" icon="trash" href="/developers/program/account-lifecycle"> Close computation definitions and MXEs when retiring them. </Card> <Card title="Design constraints" icon="triangle-exclamation" href="/developers/limitations"> Output size limits and language constraints to keep in mind. </Card> </CardGroup> # Account lifecycle and closing Source: https://docs.arcium.com/developers/program/account-lifecycle Close MXEs and computation definitions to reclaim rent: state machine, authority rules, errors, and common mistakes Computation definitions and MXEs are onchain accounts that hold rent. When you no longer need them, close them to reclaim that rent. This page covers the close lifecycle, authority rules, and common errors. For a shorter command list, see the [deployment guide](/developers/deployment#closing-an-mxe-or-computation-definition). <Note> This page covers long-lived MXE and computation-definition accounts. To close per-computation accounts after finalization, use [`claimComputationRent`](/developers/js-client-library#reclaiming-computation-rent). </Note> ## Computation-definition lifecycle A computation-definition account moves through the following states: ```mermaid theme={null} stateDiagram-v2 [*] --> IncompleteOnChain: init_computation_def<br/>(default OnChain) IncompleteOnChain --> Active: upload finalized<br/>(is_completed = true) [*] --> Active: init_computation_def<br/>(OffChain) Active --> Deactivated: deactivate-computation-definition<br/>(irreversible; blocks new queues) Deactivated --> Closed: close-computation-definition<br/>(after TTL + no in-flight comps) IncompleteOnChain --> Closed: close-computation-definition<br/>(skips deactivate + TTL) Closed --> [*] ``` A default `CircuitSource::OnChain` comp def starts as `IncompleteOnChain` (`is_completed = false`) and is not queueable until upload finalization marks it complete. `CircuitSource::OffChain` comp defs initialize directly as `Active`. `CircuitSource::Local` is reserved for internal MXE key-generation and recovery circuits; user initialization and queueing reject it. The two-step gate exists so computations queued before deactivation can drain safely. Calling `deactivate-computation-definition` blocks new `queue_computation` calls immediately; existing queued computations must finalize or expire before closing succeeds. ## Deactivation TTL `TTL_SLOTS = 180` (\~72s at 400 ms/slot). The TTL is identical to a Solana transaction's signature lifetime; the constant is shared on purpose. You can close the computation definition any time after `deactivation_slot + 180`. ## Authority | Circuit source | Who can deactivate / close | | ------------------------- | ------------------------------------------------------------- | | `CircuitSource::OnChain` | `upload_auth` (the keypair that uploaded the circuit buffers) | | `CircuitSource::OffChain` | `mxe.authority` | `close-mxe` always requires `mxe.authority`. Rent from every close goes back to the signer keypair (`-k`). ## Closing a computation definition ```bash theme={null} # 1. Mark the computation definition for closure (irreversible: blocks new queues immediately) arcium deactivate-computation-definition \ -o <computation-definition-offset> \ -p <mxe-program-id> \ -k <path-to-your-keypair> \ --rpc-url <your-rpc-url> # 2. After the TTL (180 slots, ~72s) has passed and no in-flight comps remain, close it arcium close-computation-definition \ -o <computation-definition-offset> \ -p <mxe-program-id> \ -c <cluster-offset> \ -k <path-to-your-keypair> \ --rpc-url <your-rpc-url> ``` `close-computation-definition` is the only close command that needs `--cluster-offset` (`-c`): the program enforces `mxe.cluster == cluster_offset`. ### Incomplete onchain comp defs skip the TTL If a `CircuitSource::OnChain` upload was aborted before finishing, the comp def remains `Incomplete` and can be closed immediately, without deactivating first. This is the only way out of the two-step gate. ### Raw circuit buffers (onchain circuits only) `CircuitSource::OnChain` comp defs also store circuit bytes in separate buffer accounts indexed by `raw_circuit_index`. Close each buffer separately with the MXE authority keypair: ```bash theme={null} arcium close-computation-definition-buffers \ -o <computation-definition-offset> \ -p <mxe-program-id> \ -i <raw-circuit-index> \ -k <path-to-your-keypair> \ --rpc-url <your-rpc-url> ``` Buffers can be closed when the parent comp def is `Deactivated` *or* still `Incomplete`. Unlike deactivating or closing the parent `OnChain` comp def, buffer close requires `mxe.authority`. Offchain comp defs store no buffers, so this step does not apply to them. Reserved internal `Local` comp defs close with the MXE. ### Reserved comp defs Each MXE has reserved internal computation definitions (e.g. `MxeKeygen`, `MxeKeyRecoveryInit`). You cannot close these directly with `close-computation-definition`: attempting it errors with `CannotCloseReservedComputationDefinition`. They are closed atomically by `close-mxe`. ### LUT entries persist across close Closing a comp def does **not** close its address-lookup-table entry. Re-initializing a comp def at the same offset reuses the existing LUT slot, so close + reinit cycles do not pay rent for a new LUT. ## Closing an MXE ```bash theme={null} arcium close-mxe \ -p <mxe-program-id> \ -k <path-to-your-keypair> \ --rpc-url <your-rpc-url> ``` `close-mxe` enforces several preconditions before closing: 1. MXE must not be in `Migration` state: abort or resume the migration first. 2. Keygen must be finalized (`MxeKeygenNotFinalized` otherwise). 3. Every user-defined computation definition must be closed first. Only reserved MXE computation definitions may remain (`MxeKeygen` and, if present, `MxeKeyRecoveryInit`). 4. Signer must be `mxe.authority`. When the preconditions pass, `close-mxe` closes the MXE account, the reserved keygen comp def, the keygen computation account, the recovery cluster account, and (if present) the key-recovery-init comp def and computation, all in one transaction. Rent for every closed account returns to the signer. ## Error reference Anchor program errors are reported as `Error Code: <number>` where the number is `6000 + <internal offset>`. Internal offsets and meanings: | Internal | Anchor surfaced | Name | Meaning | | -------- | --------------- | -------------------------------------------- | ------------------------------------------------- | | 0 | 6000 | `InvalidAuthority` | Signer is not the authority for this account | | 9 | 6009 | `MxeHasComputationDefinitions` | `close-mxe` blocked: user comp defs remain | | 10 | 6010 | `MxeKeygenNotFinalized` | `close-mxe` blocked: keygen not yet finalized | | 306 | 6306 | `ComputationDefinitionDeactivated` | Cannot deactivate twice | | 307 | 6307 | `ComputationDefinitionNotDeactivated` | Call `deactivate-computation-definition` first | | 308 | 6308 | `ComputationDefinitionHasActiveComputations` | A pre-deactivation computation is still in flight | | 309 | 6309 | `ComputationDefinitionTtlNotPassed` | Wait until `deactivation_slot + 180` | | 310 | 6310 | `CannotCloseReservedComputationDefinition` | Reserved offsets close atomically via `close-mxe` | | 725 | 6725 | `CannotCloseMxeDuringMigration` | Abort or resume the cluster migration first | ## Common mistakes * **"`ComputationDefinitionTtlNotPassed` (6309)"**: you're inside the 180-slot window after deactivation. Wait \~72 s and retry. * **"`ComputationDefinitionHasActiveComputations` (6308)"**: a computation queued before `deactivation_slot` is still in the execpool. Computations themselves expire after 180 slots; wait for it to finalize or expire and retry. * **"`ComputationDefinitionNotDeactivated` (6307)"**: you skipped `deactivate-computation-definition`. Active comp defs cannot be closed directly (the only exception is `Incomplete` `OnChain` comp defs). * **"`CannotCloseReservedComputationDefinition` (6310)"**: you targeted a reserved offset (`MxeKeygen`, `MxeKeyRecoveryInit`). Run `close-mxe` instead; reserved offsets close atomically as part of it. * **"`MxeHasComputationDefinitions` (6009)"**: `close-mxe` requires every user-defined comp def to be closed first. Only reserved MXE computation definitions may remain (`MxeKeygen` and, if present, `MxeKeyRecoveryInit`). * **"`CannotCloseMxeDuringMigration` (6725)"**: there's a `migrate-cluster` in flight. `--resume` or `--abort` it, then retry. * **"`InvalidAuthority` (6000)"**: for user-defined comp defs, `OnChain` accepts `upload_auth` while `OffChain` requires `mxe.authority`. `close-mxe` always requires `mxe.authority`. * **"`InvalidAuthority` (6000)" on buffer close**: `close-computation-definition-buffers` always requires `mxe.authority`, even for `OnChain` comp defs uploaded by a different `upload_auth`. * **"`close-computation-definition-buffers` did nothing"**: your comp def is `OffChain`. There are no buffer accounts to close; skip the step. * **"Forgot `--cluster-offset` on `close-computation-definition`"**: only that command needs `-c`; the program rejects mismatches against `mxe.cluster`. ## What's next? <CardGroup> <Card title="Deployment" icon="rocket" href="/developers/deployment"> Deploy, migrate, and close MXEs from the CLI. </Card> <Card title="Computation definition accounts" icon="file-lines" href="/developers/program/computation-def-accs"> How comp defs are created and initialized. </Card> </CardGroup> # Callback accounts Source: https://docs.arcium.com/developers/program/callback-accs Advanced patterns for callback accounts in Arcium programs Callback accounts define additional accounts used by a computation callback. Use them when a computation result needs to modify an onchain account. **Prerequisites**: Before diving into callback accounts, make sure you've read: * [Basic program invocation guide](/developers/program): fundamentals of queuing computations and defining callback instructions * [Callback type generation](/developers/program/callback-type-generation): how output types like `AddTogetherOutput` are automatically generated from encrypted instructions * [Arcis inputs/outputs](/developers/arcis/input-output): handling encrypted data types **When to use callback accounts:** * Storing computation results in persistent accounts * Updating game state, user balances, or protocol data * Writing results that exceed transaction size limits ## Complete example Expanding on our [basic example](/developers/program), let's say we want to save the result of our addition in an account for later use. We'll walk through the complete implementation step by step. ### Step 1: Define the account structure First, define an account to store our computation result: ```rust theme={null} #[account] #[derive(InitSpace)] pub struct SecretAdditionResult { pub sum: [u8; 32], // Store the encrypted result as ciphertext } pub fn init(ctx: Context<Initialize>) -> Result<()> { Ok(()) } #[derive(Accounts)] pub struct Initialize<'info> { #[account(mut)] pub signer: Signer<'info>, #[account( init, payer = signer, seeds = [b"AdditionResult"], space = 8 + SecretAdditionResult::INIT_SPACE, // 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>, pub system_program: Program<'info, System>, } ``` ### Step 2: Modify the queue function There are two ways to specify callback instructions in your `queue_computation` call: #### Recommended: using callback\_ix() helper The `callback_ix()` helper method is the **preferred approach** because it automatically handles all required standard accounts and is less error-prone. **What callback\_ix() does automatically:** * Creates a CallbackInstruction with the proper instruction data * Automatically includes standard accounts: `arcium_program`, `comp_def_account`, `mxe_account`, `computation_account`, `cluster_account`, `instruc
프로젝트로 돌아가기