Arcium 백서

Arcium

원문

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

calars #[instruction] pub fn update_entity() -> Enc<Shared, Entity> { /* ... */ } ``` Result: `SharedEncryptedStruct<4>` because Entity contains 4 total scalar values. ## Migration from v0.1.x If you're upgrading from an older version, the new type generation system replaces manual byte parsing: **Old way (v0.1.x)**: ```rust theme={null} pub fn encrypted_ix_callback(output: ComputationOutputs) -> Result<()> { let bytes = if let ComputationOutputs::Bytes(bytes) = output { bytes } else { return Err(ErrorCode::AbortedComputation.into()); }; let sum = bytes[48..80].try_into().unwrap(); let nonce = bytes[32..48].try_into().unwrap(); // ... } ``` **New way (current)**: ```rust theme={null} pub fn encrypted_ix_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()), }; let sum = o.ciphertexts[0]; let nonce = o.nonce; // ... } ``` For version compatibility and required changes, see [Versioning and compatibility](/developers/versioning) and the [release notes](/developers/release-notes). ## Type generation limitations ### Supported return types The type generation system works with most common Rust types, but has some constraints: **✅ Supported:** * Primitive types: `u8`, `u16`, `u32`, `u64`, `u128`, `i8`, `i16`, `i32`, `i64`, `i128`, `bool` * Fixed-size arrays: `[T; N]` where N is a compile-time constant * Tuples: `(T, U, V)` with any number of elements * Custom structs with supported field types * Nested combinations of the above **❌ Not Supported:** * Dynamic types: `Vec<T>`, `String`, `HashMap<K, V>` * Reference types: `&T`, `&mut T` (except for input parameters) * Generic types with lifetime parameters * Recursive or self-referencing structs * `Option<T>` or `Result<T, E>` as return types ### Practical constraints **Size limitations:** * Very large structs (1000+ fields) may impact compilation time * Arrays with thousands of elements create correspondingly large LEN values * Deep nesting (10+ levels) may cause macro expansion issues **Naming conflicts:** ```rust theme={null} // This would create a conflict: #[instruction] pub fn test() -> u32 // → TestOutput #[instruction] pub fn TEST() -> u32 // → TestOutput (same name!) ``` Function names must be unique when converted to PascalCase + "Output". ### Working within constraints If you need unsupported types, consider these patterns: ```rust theme={null} // Instead of Vec<u32>, use fixed arrays: #[instruction] pub fn process() -> Enc<Shared, [u32; 10]> { /* ... */ } // Instead of Option<T>, use a flag + value: #[instruction] pub fn maybe_compute() -> (Enc<Shared, bool>, Enc<Shared, u32>) { // (has_value, value) } // Instead of String, use fixed-size byte arrays: #[instruction] pub fn get_name() -> Enc<Shared, [u8; 32]> { /* ... */ } ``` ## Common patterns and performance tips ### Choosing the right encryption type * **Use `Enc<Shared, T>`** when users need to decrypt and verify results (votes, game outcomes, personal data) * **Use `Enc<Mxe, T>`** for internal state that users shouldn't access (system secrets, aggregate statistics, protocol data) ### Performance considerations * **Large arrays**: `[u8; 1000]` becomes `SharedEncryptedStruct<1000>` - consider if you really need all elements encrypted * **Complex nesting**: Deep struct hierarchies increase LEN values - flatten when possible * **Mixed returns**: `(Enc<Shared, T>, Enc<Mxe, U>)` creates separate encrypted structs for optimal access patterns ### Testing your callbacks Test callbacks in two layers: 1. **Rust unit tests**: extract the post-`verify_output()` business logic into a pure function and test that directly. 2. **TypeScript integration tests**: queue a real computation with `arcium test`, wait for finalization with `awaitComputationFinalization(...)`, then assert the callback result via emitted events or updated account state. See [Building and testing](/developers/hello-world#building-and-testing) for the `arcium test` runner and [Tracking callbacks](/developers/js-client-library/callback) for `awaitComputationFinalization`. `verify_output()` performs real BLS signature verification against the cluster's BLS key, so a mocked `SignedComputationOutputs` with a dummy signature always fails verification in a unit test. That's why unit tests cover the pure logic only. Exercise the full verification wiring through the `arcium test` flow instead: queue a computation, `awaitComputationFinalization(...)`, then assert on the emitted event or updated account state. ```rust theme={null} #[cfg(test)] mod tests { use super::*; // Post-verify logic extracted as a pure function: test this, not verify_output(). // The callback relays the encrypted ciphertext + nonce to the client (typically via // an emitted event); the client decrypts offchain. fn extract_flip_event_payload(output: FlipOutput) -> ([u8; 32], u128) { (output.field_0.ciphertexts[0], output.field_0.nonce) } #[test] fn test_event_payload_extraction() { let output = FlipOutput { field_0: SharedEncryptedStruct { encryption_key: [0u8; 32], nonce: 42, ciphertexts: [[1u8; 32]], }, }; let (ciphertext, nonce) = extract_flip_event_payload(output); assert_eq!(nonce, 42); assert_eq!(ciphertext, [1u8; 32]); } } ``` Keep your callback thin: match on `verify_output()`, destructure the result, and delegate to the pure function that holds your business logic. The pure function is what you unit-test; the `arcium test` flow is what exercises the callback end-to-end. ## Quick reference | Return Type | Generated Struct | Access Pattern | | ---------------- | -------------------------- | --------------------------------------- | | `Enc<Shared, T>` | `SharedEncryptedStruct<1>` | `result.ciphertexts[0]`, `result.nonce` | | `Enc<Mxe, T>` | `MXEEncryptedStruct<1>` | `result.ciphertexts[0]`, `result.nonce` | | `(T, U, V)` | `{Circuit}OutputStruct0` | `result.field_0`, `result.field_1` | | Custom struct | `{Circuit}OutputStruct0` | `result.field_0`, `result.field_1` | **Callback pattern:** ```rust theme={null} #[arcium_callback(encrypted_ix = "your_function")] pub fn callback( ctx: Context<YourFunctionCallback>, output: SignedComputationOutputs<YourFunctionOutput>, ) -> Result<()> { let o = match output.verify_output( &ctx.accounts.cluster_account, &ctx.accounts.computation_account ) { Ok(YourFunctionOutput { field_0 }) => field_0, Err(_) => return Err(ErrorCode::AbortedComputation.into()), }; // Access o.ciphertexts[0], o.nonce.to_le_bytes(), etc. } ``` *** The callback type generation system automatically handles encrypted computation results, eliminating manual byte parsing and offset tracking. With properly typed structs, you can work directly with structured data and focus on building your applications rather than handling low-level data conversion. These generated types provide type safety and predictable patterns that make working with encrypted computation outputs straightforward and reliable. ## What's next? <CardGroup> <Card title="Callback accounts" icon="phone-arrow-up-right" href="/developers/program/callback-accs"> Pass additional accounts to your callback for storing results. </Card> <Card title="Deployment" icon="rocket" href="/developers/deployment"> Deploy your MXE program to devnet or mainnet. </Card> </CardGroup> # Computation definition accounts Source: https://docs.arcium.com/developers/program/computation-def-accs Onchain accounts that store compiled MPC circuits for execution ## Why computation definitions exist When you write an encrypted instruction with Arcis, it compiles into an MPC circuit: a program that MPC nodes can execute securely on encrypted data. Computation definitions tell the nodes which circuit to run when your Solana program queues a computation. Computation Definition Accounts bridge your Solana program and the MPC network. They store the circuit metadata and, for onchain circuit sources, the circuit bytecode needed for execution. ## Computation definition accounts When you define an encrypted instruction using [Arcis](/developers/arcis), the MPC cluster that executes it needs access to the instruction interface, metadata, and circuit source. A `ComputationDefinitionAccount` contains two parts: 1. The encrypted instruction metadata and interface. 2. The circuit source. For onchain sources, this references separate accounts that hold the raw MPC bytecode. The interface stores expected inputs, outputs, required accounts, and execution metadata. This data lives in an account with the seeds `b"ComputationDefinitionAccount", mxe_program_id, comp_def_offset`. The first seed is exported by the Arcium Anchor SDK, the second is your MXE program ID, and the third is an encrypted-instruction-specific offset. `comp_def_offset` is `sha256(<encrypted_instruction_name>).slice(0,4)` interpreted as a little-endian `u32`. The `derive_comp_def_pda!` macro computes the `ComputationDefinitionAccount` address for you. For onchain circuit sources, the MPC bytecode is stored in accounts with the seeds `b"ComputationDefinitionRaw", comp_def_acc, i`. The first seed is exported by the Arcium Anchor SDK, the second is the computation definition account, and the third is an index from `0` through the number of accounts needed to store the full bytecode. ## Usage When working locally, the Arcium CLI creates and manages MPC bytecode accounts for you. You still need to create the interface `ComputationDefinitionAccount`, which the Arcium Anchor tooling handles. For an encrypted instruction called `add_together`, define: ```rust theme={null} pub fn init_add_together_comp_def(ctx: Context<InitAddTogetherCompDef>) -> Result<()> { init_computation_def(ctx.accounts, None)?; Ok(()) } #[init_computation_definition_accounts("add_together", payer)] #[derive(Accounts)] pub struct InitAddTogetherCompDef<'info> { #[account(mut)] pub payer: Signer<'info>, #[account( mut, address = derive_mxe_pda!() )] pub mxe_account: Box<Account<'info, MXEAccount>>, #[account(mut)] /// CHECK: comp_def_account, checked by arcium program. pub comp_def_account: UncheckedAccount<'info>, #[account(mut, address = derive_mxe_lut_pda!(mxe_account.lut_offset_slot))] /// CHECK: address_lookup_table, checked by arcium program. pub address_lookup_table: UncheckedAccount<'info>, #[account(address = LUT_PROGRAM_ID)] /// CHECK: lut_program is the Address Lookup Table program. pub lut_program: UncheckedAccount<'info>, pub arcium_program: Program<'info, Arcium>, pub system_program: Program<'info, System>, } ``` Call this instruction once before using the encrypted instruction. When you no longer need the computation definition, follow the [account lifecycle](/developers/program/account-lifecycle) to deactivate and close it. ## Offchain circuit sources For larger circuits, you can store the compiled circuit offchain and pass an `OffChainCircuitSource` as the second argument to `init_computation_def`: ```rust theme={null} use arcium_client::idl::arcium::types::{CircuitSource, OffChainCircuitSource}; use arcium_macros::circuit_hash; pub fn init_add_together_comp_def(ctx: Context<InitAddTogetherCompDef>) -> Result<()> { init_computation_def( ctx.accounts, Some(CircuitSource::OffChain(OffChainCircuitSource { source: "https://your-storage.com/path/to/add_together.arcis".to_string(), hash: circuit_hash!("add_together"), })), )?; Ok(()) } ``` The `circuit_hash!` macro embeds the SHA-256 hash from `build/{circuit_name}.hash` at compile time; Arx nodes verify it when fetching the circuit. For the full offchain workflow, see [Deployment](/developers/deployment#handling-large-circuits-with-offchain-storage). # Release notes Source: https://docs.arcium.com/developers/release-notes Track compatibility, required actions, and developer-facing changes in coordinated Arcium releases from v0.11 onward. Arcium releases coordinate the CLI, Rust crates, TypeScript packages, and Arx node image. Start with [versioning and compatibility](/developers/versioning) to choose an upgrade path. For every upgrade, synchronize all Arcium components, then rebuild and test: each entry below lists additional release-specific actions. <Update label="v0.15.0" description="September 14, 2026"> **Upgrade impact** * **Existing applications:** No Arcis source changes from v0.14.1. Generated typed callbacks and Anchor programs require no source changes. Synchronize all Arcium dependencies, rebuild, and test. * **TypeScript applications:** No source changes from v0.14.1. * **Node Operators:** Update the Arx node image to `arcium/arx-node:v0.15.0`. Distributed preprocessing is opt-in: a `node_config.toml` written before this release parses unchanged and keeps the trusted dealer. **Changes** * **Preprocessing:** Adds distributed (Cerberus) preprocessing as an alternative to the trusted dealer, enabled with `distributed_preprocessing` in `node_config.toml`. Generate the per-node seed once with `arcium generate-cerberus-seed`. Every node in a cluster must use the same `parallel_preprocessing_bundlers`. See [node setup](/developers/node-setup). * **MXE authority:** Adds the `arcium set-mxe-authority` command, and the instruction behind it, for transferring an MXE to a new authority such as a multisig vault. See [deployment](/developers/deployment). * **Computation definitions:** Accepts a computation definition when `cu_amount >= circuit_weight` rather than only on exact equality, so a circuit can get cheaper without invalidating definitions already registered on chain. A value below the circuit weight is still rejected. * **Arcis:** Adds `sort_by_cached_key`, and fixes `..` patterns in slices, `div_ceil`, `each_mut`, and a family of empty-array and empty-iterator cases. See [supported operations](/developers/arcis/operations). * **Performance:** Reduces `mxe_keygen` by 24.5% and `add_together_test` by 11.5%, with smaller gains across most circuits. * **Reliability:** Adds a timeout to protocol initialization so a stuck peer no longer blocks the execution pool, makes a failure after the first MXE initialization transaction resumable, and snapshots per-peer stake so fee splits no longer drift after a membership change. </Update> <Update label="v0.14.1" description="July 29, 2026"> **Upgrade impact** * **Existing applications:** Generated typed callbacks require no source changes. Synchronize all Arcium dependencies, rebuild, and test. * **Callback integrations:** The first callback instruction must target the owning MXE, callback accounts cannot be signers, and custom accounts cannot reuse the node callback authority or Arx account. * **Raw callbacks:** Call `RawComputationOutputs::verify_output` before consuming raw output. See [Handle raw outputs](/developers/program/callback-type-generation#handle-raw-outputs). * **Program IDL:** `init_key_recovery_execution_part1` removes its two instruction arguments; the original and backup MXE program accounts remain required. `queue_key_recovery_init` removes the `mxe_program` account but retains the `mxe_program` argument for PDA derivation. * **Node Operators:** Update the Arx node image to `arcium/arx-node:v0.14.1`. **Changes** * **Local development:** Adds preview support for Surfpool through `arcium test --validator surfpool` and `arcium localnet --validator surfpool`. The legacy validator remains the default. * **Callbacks:** A `callback_cu_limit` of `0` derives the limit from simulation and retries compute-budget exhaustion with a higher limit. A non-zero value remains fixed. * **TypeScript reader:** `subscribeComputations` now resolves after the RPC server acknowledges the log subscription. The timeout defaults to 10 seconds and supports `{ ackTimeoutMs }`. * **Rust client:** Adds fallible `try_queue_key_recovery_init` and `try_reclaim_expired_computation_fee` helpers and uses confirmed commitment in `arcium_program_client`. * **Security and reliability:** Tightens callback, computation, migration, key-recovery, and raw-output validation; redacts shared Rescue keys from logs; and routes deterministic callback failures through failure claims. </Update> <Update label="v0.13.2" description="July 15, 2026"> **Upgrade impact** * **Existing applications:** No source changes from v0.13.1. Existing initialized MXEs are unaffected. * **New MXE deployments:** Sign initialization with the deployed program's upgrade authority. Immutable programs cannot initialize a new MXE. * **Node Operators:** Update the Arx node image. **Changes** * **Deployment:** Checks the program upgrade authority before queuing MXE initialization. See the [deployment guide](/developers/deployment). * **Arx node:** Reconnects stale subscriptions, applies the RPC slot buffer to computation-account fetches, tightens minimum-context checks, and supports local circuit loading. * **Node services:** Prevents the rewards server from persisting states that cannot be anchored. </Update> <Update label="v0.13.1" description="July 10, 2026"> **Upgrade impact** * **Existing applications:** No source changes from v0.12.x. **Changes** * **Arcis:** Adds all six range-slicing shapes, forward `RangeFrom` iteration, additional unary operations, and bitwise and shift operations on integer types. See [supported operations](/developers/arcis/operations). * **TypeScript:** Adds `@arcium-hq/staking` with staking account readers, PDA helpers, and instruction builders. * **Performance:** Caches Rescue cipher keys between operations. * **Circuit sources:** Reserves local circuit sources for internal MXE workflows. </Update> <Update label="v0.12.0" description="July 3, 2026"> **Upgrade impact** * **Existing applications:** No source changes from v0.11.x. **Changes** * **Arcis:** Adds the `Default` trait and qualified self paths such as `<T as Trait>::item`. See [supported operations](/developers/arcis/operations). </Update> <Update label="v0.11.2" description="June 25, 2026"> **Upgrade impact** * **Existing applications:** No source changes from v0.11.1. **Changes** * **Arcis:** Optimizes AES circuits with a Boyar-Peralta S-box implementation. * **MXE initialization:** Validates recovery peers before submission, rejects duplicate peers in the TypeScript client, and initializes recovery-stake state with `initMxePart2`. * **Program:** Corrects the program epoch duration. </Update> <Update label="v0.11.1" description="June 24, 2026"> **Upgrade impact** * **Protocol and accounts:** Existing state remains compatible. * **Existing applications:** Add `skip_init_mxe_part1` to direct calls to `arcium_client::transactions::init_mxe`. * **Staking CLI scripts:** Pass `--amount` and `--new-balance` values in whole ARX instead of base units. **Changes** * **Rust client:** Adds `skip_init_mxe_part1` to `init_mxe` so initialization can resume without repeating the first transaction. * **CLI:** Converts staking amount inputs from whole ARX to base units and corrects the ARX token mint. * **Staking:** Adds primary-stake modification and minimum-stake checks for execution pools. </Update> <Update label="v0.11.0" description="June 22, 2026"> **Upgrade impact** * **Baseline:** v0.11 is the oldest release covered by the maintained compatibility guidance. Existing MXE, Cluster, and computation-definition accounts remained compatible when upgrading from v0.10. Projects still on v0.10 or older should request a project-specific path in [Arcium Discord](https://discord.gg/arcium). * **Applications upgrading from v0.10:** Had to add `callback_cu_limit` to every `queue_computation` call, then rebuild and redeploy. * **Node Operators upgrading from v0.10:** Had to add fallback RPC and computation-limit
프로젝트로 돌아가기