Arcium 백서

Arcium

원문

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

execution fee and the full callback reserve to rewards. It does not refund the unallocated half of the execution fee to the payer. See [Fee allocation](/staking/overview#fee-allocation). After a recorded failure, the application decides whether to retry, choose another path, or initiate [Cluster migration](/clusters/cluster-migration). # Intro to Arcium Source: https://docs.arcium.com/developers What Arcium enables, common use cases, and a guided path from setup to deployment Arcium is a decentralized private computation network that processes encrypted data with Multi-Party Computation (MPC). It lets Solana applications run computations without revealing sensitive inputs to any single node. ## What Arcium enables As a Solana developer, you can use Arcium to: 1. **Build privacy-preserving applications**: Add privacy without adopting a new blockchain or abandoning Anchor-style workflows. 2. **Use familiar tooling**: Write encrypted instructions in Rust with Arcis and integrate them with Solana programs. 3. **Process sensitive data**: Run computations over data such as balances, trade orders, game state, or personal information without exposing plaintext inputs. ## How it works Your application uses an MXE to work with encrypted data in three steps: 1. The client encrypts data and sends it to your MXE program. 2. Your program submits the computation to Arcium's network of MPC nodes. 3. Nodes process the data while keeping it encrypted and return the result. The entire process happens onchain through Solana, with each step verified and coordinated by Arcium's programs. ## Common use cases 1. **Confidential DeFi**: Build dark pools or private order books where trade sizes and prices remain hidden. 2. **Secure AI**: Enable AI model inference and training on sensitive data while keeping the data encrypted. 3. **Confidential gaming**: Build hidden information games where player moves and state remain private until revealed (e.g., card games, strategy games, auctions). ## Getting started Arcium provides a familiar development experience for Solana developers: * Use the `arcium` CLI (a wrapper over `anchor` CLI) to build Solana programs with Arcium * Write encrypted instructions in Rust using the Arcis framework * Integrate with your Solana programs using the TypeScript client library Follow these steps to get started: 1. [Install Arcium](/developers/installation): Set up the development environment and tools. 2. [Hello World](/developers/hello-world): Create your first encrypted instruction. 3. [Core concepts](/developers/core-concepts): Learn how MXEs, Clusters, and encrypted instructions connect. 4. [Computation lifecycle](/developers/computation-lifecycle): Understand how encrypted computations work. 5. [Examples](/developers/examples): Explore complete applications and the concepts they demonstrate. 6. [Continuous integration](/developers/continuous-integration): Build and test each change in GitHub Actions. 7. [Deployment](/developers/deployment): Deploy your MXE to devnet or mainnet. 8. [TypeScript SDK reference](https://ts.arcium.com/api): Use the API reference for TypeScript client libraries. The Arcium Network is live on Solana mainnet. Join [Discord](https://discord.com/invite/arcium) for developer support and community discussion. # Arcis overview Source: https://docs.arcium.com/developers/arcis Introduction to Arcis, a Rust-based framework for writing secure MPC circuits on the Arcium Network Arcis is a Rust-based framework for writing secure multi-party computation (MPC) circuits that run on the Arcium Network. Create privacy-preserving applications that compute over encrypted data using familiar Rust syntax. ## What Arcis code looks like Arcis code is standard Rust with special annotations for MPC execution: ```rust theme={null} use arcis::*; #[encrypted] mod my_circuit { use arcis::*; #[instruction] pub fn add_private(a: Enc<Shared, u64>, b: Enc<Shared, u64>) -> Enc<Shared, u64> { let x = a.to_arcis(); // Encrypted → secret shares let y = b.to_arcis(); a.owner.from_arcis(x + y) // Secret shares → encrypted } } ``` This computes `a + b` where both inputs remain encrypted throughout. No node ever sees the plaintext values. <CardGroup> <Card title="Thinking in MPC" icon="brain" href="/developers/arcis/mental-model"> Understand why MPC circuits work differently and the mental model behind Arcis. </Card> <Card title="Hello World" icon="rocket" href="/developers/hello-world"> Build your first Arcis circuit with a hands-on tutorial. </Card> <Card title="Examples" icon="list" href="/developers/examples"> Real-world circuits: voting, games, DeFi applications. </Card> <Card title="Quick reference" icon="graduation-cap" href="/developers/arcis/quick-reference"> Quick reference cheatsheet for Arcis syntax and patterns. </Card> </CardGroup> ## Key features * **Rust-based**: Use Rust's type safety and performance for MPC development. * **Circuit-oriented**: Write MPC circuits using familiar Rust syntax with constraints for fixed circuit structure. * **Privacy-focused**: Compute over encrypted data without revealing the underlying information. ## What's next? <CardGroup> <Card title="Best practices" icon="shield-check" href="/developers/arcis/best-practices"> Security patterns, optimization tips, and common pitfalls to avoid. </Card> <Card title="Types" icon="brackets-curly" href="/developers/arcis/types"> Learn `Enc<Owner, T>`, `EncData<T>`, and supported data patterns. </Card> <Card title="Input/Output" icon="arrow-right-arrow-left" href="/developers/arcis/input-output"> Pass encrypted inputs and design callback-friendly outputs. </Card> <Card title="Operations" icon="bolt" href="/developers/arcis/operations"> Check what Rust operations are supported in Arcis circuits. </Card> </CardGroup> # Best practices Source: https://docs.arcium.com/developers/arcis/best-practices Performance tips, debugging techniques, and testing strategies for Arcis circuits This guide covers practical tips for writing efficient, debuggable, and testable Arcis circuits. <Tip> **Use this page when** you are optimizing circuit performance, debugging an issue, or setting up tests. </Tip> ## Understanding execution flow For conceptual background on why MPC circuits work differently (e.g., why both if/else branches execute), see [Thinking in MPC](/developers/arcis/mental-model). ## Performance optimization ### Operation costs See [Thinking in MPC - Cost Model](/developers/arcis/mental-model#cost-model) for the full cost breakdown. | Operation | Cost | Notes | | ------------------------------------- | --------- | ------------------------------------------- | | Addition, subtraction, multiplication | Cheap | Multiplications optimized via preprocessing | | Comparisons | Expensive | Bit decomposition required | | Division, modulo | Expensive | Multiple internal operations | | Dynamic indexing | O(n) | Checks all positions | ### Optimization tips **Batch encrypted outputs when possible**: ```rust theme={null} // Multiple separate encryptions have overhead let enc_a = owner.from_arcis(x); let enc_b = owner.from_arcis(y); // If you need both values encrypted together, use a tuple type let enc_tuple: Enc<Shared, (u64, u64)> = owner.from_arcis((x, y)); // ✗ Won't compile - Enc<T> wraps the entire value, // so destructuring patterns don't work on Enc types // let (enc_a, enc_b) = owner.from_arcis((x, y)); ``` **Reuse comparison results**: ```rust theme={null} // ✗ Redundant - same comparison computed twice if x > 1000 { do_something(); } if x > 1000 { // Expensive comparison done AGAIN do_another_thing(); } // ✓ Compute once, reuse the result let is_large = x > 1000; if is_large { do_something(); } if is_large { // Reuses the boolean, no recomputation do_another_thing(); } ``` **Prefer public constants over secret-dependent values**: ```rust theme={null} // ✓ Constant multiplier - compiler can optimize fn double(x: u64) -> u64 { x * 2 // Multiplication by constant is efficient } // ✓ Pass known values as public inputs fn apply_rate(amount: u64, rate_percent: u64) -> u64 { // If rate is known ahead of time, pass it as a public input // rather than computing it inside the secure computation amount * rate_percent / 100 } ``` In MPC, values known before the computation (public inputs and constants) can be handled more efficiently than values computed during secure execution. ## Debugging Arcis provides familiar debugging macros that work during circuit development. ### Print debugging ```rust theme={null} #[instruction] fn debug_example(a: u32, b: u32) -> u32 { println!("Inputs: a = {}, b = {}", a, b); let result = a + b; println!("Result: {}", result); // Also available: print!, eprint!, eprintln! eprintln!("Debug: computation complete"); result } ``` <Note> Print macros do not change circuit behavior. They are for development only. Output appears during circuit execution on Arx nodes. </Note> ### Debug assertions Use assertions to verify invariants during development: ```rust theme={null} #[instruction] fn with_assertions(x: u32, y: u32) -> u32 { debug_assert!(x > 0, "x must be positive"); debug_assert_eq!(x, x, "sanity check"); debug_assert_ne!(x, y, "x and y should differ"); x + y } ``` <Warning> `debug_assert` macros are for development verification only. They do not enforce constraints in production: use explicit conditionals for actual validation logic. </Warning> ### Common debugging patterns **Trace loop iterations**: ```rust theme={null} for i in 0..10 { println!("Iteration {}: value = {}", i, arr[i]); // ... processing } ``` **Check intermediate values**: ```rust theme={null} let step1 = compute_step1(input); println!("After step1: {}", step1); let step2 = compute_step2(step1); println!("After step2: {}", step2); ``` ## Testing ### What can be unit tested You can test: * **Helper functions** (non-`#[instruction]` functions) * **`#[arcis_circuit]` functions** (builtin circuits) * **Pure logic** extracted into testable units You **cannot** directly unit test: * **`#[instruction]` functions** (require MPC runtime) ### Testing strategy Extract testable logic into helper functions: ```rust theme={null} #[encrypted] mod circuits { use arcis::*; // Testable: regular function pub fn calculate_fee(amount: u64, rate: u64) -> u64 { amount * rate / 10000 // basis points } // Testable: builtin circuit #[arcis_circuit = "min"] pub fn min(a: u128, b: u128) -> u128 {} // NOT directly testable: requires MPC #[instruction] fn transfer_with_fee(amount: u64, rate: u64) -> u64 { let fee = calculate_fee(amount, rate); amount - fee } } #[cfg(test)] mod tests { use super::*; #[test] fn test_fee_calculation() { // 2.5% fee on 10000 assert_eq!(circuits::calculate_fee(10000, 250), 250); // 1% fee on 5000 assert_eq!(circuits::calculate_fee(5000, 100), 50); } #[test] fn test_builtin_circuit() { assert_eq!(circuits::min(10, 20), 10); assert_eq!(circuits::min(1, 0), 0); assert_eq!(circuits::min(4, 4), 4); } } ``` ### Integration testing `#[instruction]` functions cannot be unit-tested in isolation: they require the full MPC runtime. For end-to-end testing, use the TypeScript SDK to invoke deployed circuits on a test cluster. See the [JavaScript Client documentation](/developers/js-client-library) and the [Hello World tutorial](/developers/hello-world) for integration testing setup. ## Common pitfalls ### Conditionals don't guard execution When a condition is not a compile-time constant, both branches execute. The condition selects which result to keep, but Arx nodes perform work for both paths. See [Thinking in MPC](/developers/arcis/mental-model#both-branches-always-execute) for the full explanation. ```rust theme={null} // Problematic: assumes the indexing won't happen when found_match is false if found_match { data[secret_idx] = new_value; // Executes regardless of found_match } // Safe: constant-index loop with conditional assignment for i in 0..DATA_SIZE { let should_update = found_match && (i == secret_idx); if should_update { data[i] = new_value; } } ``` ### Reveal and encryption placement `.reveal()` and `.from_arcis()` cannot appear inside conditional blocks. See [Thinking in MPC](/developers/arcis/mental-model#reveal-and-encryption-placement) for the correct pattern. ## Error handling ### Compile-time vs runtime | Condition | Compile-Time | Runtime | | ------------------------- | ---------------------------- | ----------------------- | | Division by zero | Error if divisor is constant | Undefined behavior | | Array index out of bounds | Error if index is constant | Error during evaluation | | Float out of range | Error for literals | Silently clamped | <Warning> **Division by secret values:** If your divisor could be zero based on secret inputs, add explicit validation: ```rust theme={null} let is_valid = divisor != 0; let safe_divisor = if is_valid { divisor } else { 1 }; let result = if is_valid { numerator / safe_divisor } else { 0 }; ``` </Warning> **Best practices:** 1. Use constant array sizes where possible 2. Validate divisors before division when they depend on secret inputs 3. Keep floats within the supported range `[-2^75, 2^75)` ## What's next? For the operation cost breakdown, see [Thinking in MPC - Cost Model](/developers/arcis/mental-model#cost-model). <CardGroup> <Card title="Quick reference" icon="graduation-cap" href="/developers/arcis/quick-reference"> Keep this open while coding for fast syntax lookup. </Card> <Card title="Thinking in MPC" icon="brain" href="/developers/arcis/mental-model"> Understand MPC constraints and the cost model. </Card> </CardGroup> # Input/output Source: https://docs.arcium.com/developers/arcis/input-output Working with Enc types for encrypted inputs and outputs in Arcis circuits Inputs and outputs in encrypted instructions are handled the same way. The Arcium Network does not mutate any state itself. Both can be encrypted or plaintext. Encrypted data is passed as an `Enc<Owner, T>` generic type. See [Types](/developers/arcis/types#encryption-types) for the full reference on `Enc<Shared, T>` vs `Enc<Mxe, T>`. ## Data visibility Parameters and return values have different visibility levels during MPC execution: | Type | Who Sees Plaintext | | ------------------------------- | ------------------------------- | | Plaintext (`u64`, `bool`, etc.) | All Arx nodes | | `Enc<Shared, T>` | Client + MXE (after decryption) | | `Enc<Mxe, T>` | MXE only | <Warning> Plaintext parameters are visible to all Arx nodes during computation. Use `Enc<Shared, T>` for sensitive user data. </Warning> ### Return value requirements Values returned from an `#[instruction]` must be in a form that can leave the MPC circuit: * **Encrypted:** Call `.from_arcis()` to produce `Enc<Owner, T>`. The ciphertext is public bytes; the plaintext remains protected. * **Revealed:** Call `.reveal()` to produce plaintext. The value becomes visible to everyone. Secret-shared values (intermediate results from `.to_arcis()`) cannot be returned directly: they exist only within the MPC computation. ## Example ```rust theme={null} use arcis::*; #[encrypted] mod order_book { use arcis::*; const ORDER_BOOK_SIZE: usize = 8; #[derive(Copy, Clone)] pub struct Order { size: u64, bid: bool, owner: u128, } #[derive(Copy, Clone)] pub struct OrderBook { orders: [Order; ORDER_BOOK_SIZE], } #[instruction] pub fn add_order( order_ctxt: Enc<Shared, Order>, ob_ctxt: Enc<Mxe, OrderBook>, ) -> Enc<Mxe, OrderBook> { let order = order_ctxt.to_arcis(); let mut ob = ob_ctxt.to_arcis(); let mut found = false; for i in 0..ORDER_BOOK_SIZE { let overwrite = ob.orders[i].size == 0 && !found; if overwrite { ob.orders[i] = order; } found = overwrite || found; } ob_ctxt.owner.from_arcis(ob) } } ``` This example demonstrates how to pass inputs into encrypted instructions, compute on them, and return outputs. The goal is to add an order to an existing order book. In this example, `order_ctxt: Enc<Shared, Order>` contains data encrypted with a shared secret between the client and MXE: both can decrypt it. In contrast, `ob_ctxt: Enc<Mxe, OrderBook>` is encrypted exclusively for the MXE, so only the MXE nodes (acting together) can decrypt it. This pattern is useful for storing protocol state that users shouldn't access directly. <Note> **Why use Mxe?** If `ob_ctxt` were `Enc<Shared, OrderBook>`, any user could decrypt the entire order book and see everyone else's orders. By using `Enc<Mxe, OrderBook>`, only the MXE cluster can access the aggregate state. Individual users can only see their own inputs and the revealed outputs. </Note> To use the parameters `order_ctxt` and `ob_ctxt` for computation, we need to convert them to corresponding secret shares for the nodes to compute in MPC. This is done by calling the `to_arcis` function on any `Enc` generic parameter. This does not reveal the plaintext data underneath to the nodes during the process. The order parameter is consumed after the encrypted instruction has been processed. To output the new order book, convert it back using `from_arcis` on the `ob_ctxt.owner` field (the party that encrypted the data) to get the new `Enc<Owner, T>` type, and return it. For more details on how to invoke these encrypted instructions from your Solana program, see [Invoking a computation](/developers/program). ## Efficient data packing MPC operations work on field elements. For large arrays of small integers, `Pack<T>` provides significant compression. See [Data packing](/developers/arcis/primitives#data-packing) for when to use it. ### Usage <CodeGroup> ```rust Arcis theme={null} pub struct GameState { // Pack large arrays for ~26x storage reduction board: Pack<[u8; 256]>, } #[instruction] pub fn sum_board(input: Enc<Shared, Pack<[u8; 64]>>) -> u64 { let data: [u8; 64] = input.to_arcis().unpack(); let mut sum: u64 = 0; for i in 0..64 { sum += data[i] as u64; } sum.reveal() } ``` ```typescript Client theme={null} import { randomBytes } from 'crypto'; import { circuits } from './build/circuits'; // Generated by Arcium compiler import { RescueCipher } from '@arcium-hq/client'; // Your game board data const board = new Uint8Array(256).fill(0); // Pack using generated packer (matches Arcis struct) const packed = circuits.GameState.pack({ board: Array.from(board) }); // Encrypt for MPC (sharedSecret from x25519 key exchange - see Encryption docs) const cipher = new RescueCipher(sharedSecret); const nonce = randomBytes(16); const ciphertext = cipher.encrypt(packed, nonce); ``` </CodeGroup> <Note> The `sharedSecret` comes from x25519 key exchange with the MXE cluster. See [Encrypting inputs](/developers/js-client-library/encryption) for the full setup. </Note> <Warning> Field names and order in TypeScript must exactly match your Arcis struct definition. Mismatches cause silent data corruption. </Warning> The generated packers provide: * Type-safe interfaces matching your Arcis struct * Correct field ordering (must match Arcis definition) * Compile-time validation with TypeScript See [Primitives: Data Packing](/developers/arcis/primitives#data-packing) for full `Pack<T>` API. <Card title="Example: Ed25519 Signatures" icon="github" href="https://github.com/arcium-hq/examples/tree/main/ed25519"> Complete example with client-side packing via circuits.VerifyingKey.pack(). </Card> ## What's next? <CardGroup> <Card title="Primitives" icon="cube" href="/developers/arcis/primitives"> RNG, cryptography, and data packing operations. </Card> <Card title="Invoke from Solana" icon="link" href="/developers/program"> Queue computations from your Solana program. </Card> </CardGroup> # Thinking in MPC Source: https://docs.arcium.com/developers/arcis/mental-model Understand the
프로젝트로 돌아가기