Arcium 백서

Arcium

원문

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

or computation definition When you no longer need an MXE or one of its computation definitions, close the accounts to reclaim rent. Comp defs close in two steps: deactivate, wait 180 slots, then close. MXEs can close only after all user-defined comp defs are closed. ```bash theme={null} # Comp def: deactivate, wait for TTL, then close arcium deactivate-computation-definition \ -o <comp-offset> \ -p <mxe-program-id> \ -k <keypair> \ --rpc-url <url> arcium close-computation-definition \ -o <comp-offset> \ -p <mxe-program-id> \ -c <cluster-offset> \ -k <keypair> \ --rpc-url <url> # OnChain circuits also need their raw buffers closed (one call per index) arcium close-computation-definition-buffers \ -o <comp-offset> \ -p <mxe-program-id> \ -i <raw-circuit-index> \ -k <keypair> \ --rpc-url <url> # MXE arcium close-mxe \ -p <mxe-program-id> \ -k <keypair> \ --rpc-url <url> ``` Pass an explicit `--rpc-url`: the CLI defaults to mainnet without it. For the full state machine, authority rules, error codes, and common mistakes, see [Account lifecycle and closing](/developers/program/account-lifecycle). ## What's next? After deployment, update your client code to use the correct cluster offset, initialize your computation definitions onchain, and run end-to-end tests on devnet. <CardGroup> <Card title="Arcis best practices" icon="lightbulb" href="/developers/arcis/best-practices"> Learn patterns and optimizations for efficient encrypted instructions. </Card> <Card title="Examples" icon="list" href="/developers/examples"> Browse runnable MXE projects mapped to the docs concept they demonstrate. </Card> </CardGroup> For questions or issues, reach out on [Discord](https://discord.gg/arcium). # Encryption overview Source: https://docs.arcium.com/developers/encryption How encryption works in Arcium: X25519 key exchange, Rescue cipher, and data protection Encrypted data is passed as an `Enc<Owner, T>` generic type. `Owner` specifies who can decrypt the data (`Shared` or `Mxe`), and `T` is the encrypted data type. With `Mxe`, the nodes can collectively decrypt the data under dishonest-majority assumptions. With `Shared`, the data is encrypted with a shared secret between the client and the MXE. The wrapper contains the ciphertext, the nonce, and, for `Shared` ownership, the public key used to encrypt the data. Encrypted data can be decrypted globally or selectively to a specific user. For global decryption, call the `reveal` method on any variable with a [supported data type](/developers/arcis/types). For selective decryption, use [sealing](/developers/encryption/sealing), which re-encrypts data for a chosen recipient. Private inputs are encrypted using the arithmetization-oriented symmetric [Rescue cipher](https://eprint.iacr.org/2019/426). Before the cipher runs, the client and cluster perform an [X25519](https://www.rfc-editor.org/rfc/rfc7748.html#page-7) elliptic curve Diffie-Hellman key exchange to derive a shared secret. The Rescue key is derived by hashing the shared secret with the [Rescue-Prime](https://eprint.iacr.org/2020/1143.pdf) hash function, as described in [Section 4](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Cr2.pdf), Option 1. This increases the min-entropy of the key.\ Note: 1. Since the X25519 key exchange natively returns shared secrets in the finite field with $p = 2^{255} - 19$ elements, we implemented Rescue over the field $\mathbb{F}_{p}$. States in the context of Rescue are elements of the $m$-dimensional vector space $\mathbb{F}_p^m$, i.e., the Rescue cipher transforms vectors of size $m$ to vectors of the same size. 2. The security level $s$ of the cipher is set to 128 bits. 3. We use the Rescue block cipher in [Counter (CTR) mode](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf) (see Section 6.5), with fixed $m = 5$. The choice $m = 5$ is motivated by the fact that it is the smallest value that attains the minimum of recommended rounds (10), given the fixed finite field and security level. The counters have the form `[nonce, i, 0, 0, 0]`, where `nonce` is a 16-byte random value provided by the user. 4. The hash function used for key derivation is Rescue-Prime over $\mathbb{F}_{2^{255}-19}$, with `rate = 7` and `capacity = 5` (i.e., $m = 12$) and output truncated to 5 field elements. The target security level $s$ is set to 256. According to [Section 2.2](https://eprint.iacr.org/2020/1143.pdf), this offers 256 bits of security against collision, preimage and second-preimage attacks for any field of size at least 102 bits. The decryption of `input_enc: Enc<Owner, T>` can conveniently be obtained by calling `input_enc.to_arcis()` (the nodes do not learn `input`; they convert the ciphertext to secret-shares of `input` by running the Rescue decryption circuit in MPC). If the owner is `Shared`, the MXE and the client perform a key exchange first. Similarly, `owner.from_arcis(output)` encrypts the secret-shared `output` by running the Rescue encryption circuit in MPC.\ Note: 1. After decrypting the user-provided inputs, the MXE increments the `nonce` by 1 and uses it for encrypting the outputs. For the forthcoming interaction with the MXE, a new `nonce` must be provided. 2. The performance will benefit from reducing the number of calls to `owner.from_arcis(..)` (per owner). Ideally, put all data encrypted to `owner` in one struct. <Note> [`EncData<T>`](/developers/arcis/types#advanced-encdata%3Ct%3E) contains only ciphertext, omitting pubkey and nonce. Use for multiple outputs to reduce callback payload size. </Note> ## What's next? <CardGroup> <Card title="Encrypting inputs" icon="binary-lock" href="/developers/js-client-library/encryption"> Implement encryption in your TypeScript client. </Card> <Card title="Sealing" icon="lock" href="/developers/encryption/sealing"> Re-encrypt data between different parties. </Card> </CardGroup> # Sealing (re-encryption) Source: https://docs.arcium.com/developers/encryption/sealing Re-encrypt data between parties using sealing patterns Suppose you're Alice and have secret data onchain that you want to share with Bob. You may also want to compute a function on sensitive data and share the result with Bob without revealing the data or result to anyone else. Arcium can re-encrypt any data to a given public key. This is known as "sealing" in cryptography: restricting data access to specific recipients. This is useful for a variety of reasons, such as compliance, end-to-end privacy, and more. ```rust theme={null} #[encrypted] mod circuits { use arcis::*; #[instruction] pub fn verify_loan_eligibility( alice_balance: Enc<Shared, u64>, min_balance_required: Enc<Mxe, u64>, loan_officer: Shared ) -> Enc<Shared, bool> { let balance = alice_balance.to_arcis(); let threshold = min_balance_required.to_arcis(); // Check if Alice meets minimum balance for loan without revealing her exact balance let is_eligible = balance >= threshold; // Re-encrypt the result for the loan officer loan_officer.from_arcis(is_eligible) } } ``` In this example, we have an encrypted function `verify_loan_eligibility` that takes Alice's encrypted balance (encrypted with a shared secret between Alice and the MXE), the minimum balance requirement (encrypted only for the MXE), and a `Shared` type parameter representing the loan officer who will receive the result. The function checks if Alice meets the minimum balance requirement for loan eligibility without revealing her actual balance to anyone. The boolean result is then re-encrypted specifically for the loan officer using their public key. This way, Alice's financial privacy is preserved: the loan officer only learns whether she's eligible, not her actual balance, and Arx nodes never see plaintext, only secret shares. ## What's next? <CardGroup> <Card title="Encrypting inputs" icon="binary-lock" href="/developers/js-client-library/encryption"> Learn how to encrypt data before sending to the MXE. </Card> <Card title="Invoke from Solana" icon="bullseye-arrow" href="/developers/program"> Call encrypted instructions from your Solana program. </Card> </CardGroup> # Examples Source: https://docs.arcium.com/developers/examples Browse runnable encrypted applications grouped by complexity and mapped to the Arcium concepts they demonstrate Browse complete MXE projects in the [Arcium examples repository](https://github.com/arcium-hq/examples). Each project includes its Arcis circuits, Solana program, tests, and setup instructions. <Note> The examples currently target Arcium `0.13.2`, while the latest toolchain is `0.15.0`. Check each project's manifests before copying code into a project on another release. </Note> ## Start with the fundamentals | Example | What it demonstrates | Maps to | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Coinflip](https://github.com/arcium-hq/examples/tree/main/coinflip) | Trustless randomness with `ArcisRNG`; stateless circuit | [Arcis primitives](/developers/arcis/primitives), [Callback type generation](/developers/program/callback-type-generation) | | Rock Paper Scissors: [player vs player](https://github.com/arcium-hq/examples/tree/main/rock_paper_scissors/against-player), [player vs house](https://github.com/arcium-hq/examples/tree/main/rock_paper_scissors/against-house) | Encrypted async gameplay with hidden moves or an MPC-generated opponent | [Input/output](/developers/arcis/input-output), [Callback accounts](/developers/program/callback-accs), [Arcis primitives](/developers/arcis/primitives) | ## Build stateful applications | Example | What it demonstrates | Maps to | | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | | [Voting](https://github.com/arcium-hq/examples/tree/main/voting) | Private ballots with public results via encrypted state accumulation | [Callback type generation](/developers/program/callback-type-generation) | | [Share medical records](https://github.com/arcium-hq/examples/tree/main/share_medical_records) | Patient-controlled re-encryption between parties | [Sealing](/developers/encryption/sealing) | | [Sealed-bid auction](https://github.com/arcium-hq/examples/tree/main/sealed_bid_auction) | Encrypted bid comparison supporting first-price and Vickrey mechanisms | [Operations](/developers/arcis/operations) | ## Explore advanced patterns | Example | What it demonstrates | Maps to | | ----------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | [Blackjack](https://github.com/arcium-hq/examples/tree/main/blackjack) | Hidden deck state with `Pack<T>` for compact encrypted storage | [Arcis primitives](/developers/arcis/primitives#data-packing), [Types](/developers/arcis/types) | | [Ed25519 signatures](https://github.com/arcium-hq/examples/tree/main/ed25519) | Threshold signing where the private key never exists in one place | [Arcis primitives](/developers/arcis/primitives#ed25519-signatures), [Input/output](/developers/arcis/input-output) | ## What's next? <CardGroup> <Card title="Hello World" icon="rocket" href="/developers/hello-world"> Build your first encrypted instruction end-to-end. </Card> <Card title="Arcis quick reference" icon="graduation-cap" href="/developers/arcis/quick-reference"> Syntax cheatsheet for the patterns these examples use. </Card> </CardGroup> # Hello World with Arcium Source: https://docs.arcium.com/developers/hello-world Build your first encrypted circuit with Arcis (Rust), a Solana program, and TypeScript tests ## Hello World The Arcium tooling suite for writing MXEs (MPC eXecution Environments) is built on top of [Anchor](https://www.anchor-lang.com/), so if you're familiar with Anchor, you should find Arcium to be a familiar experience, except that you're using the `arcium` CLI instead of `anchor`. To initialize a new MXE project, run: ```bash theme={null} arcium init <project-name> ``` This will create a new project with the given name and initialize it with a basic structure. The structure is the same as in an Anchor project with two differences, so it is not repeated here (for an explanation of the Anchor project structure, see the [Anchor documentation](https://www.anchor-lang.com/docs/quickstart/local)). The two differences are: * The `Arcium.toml` file, which contains the configuration for the Arcium tooling suite. * The `encrypted-ixs` directory. This is where we write all our code that is meant to operate on encrypted data and therefore runs in MPC. This code is written using our own Rust framework called [Arcis](/developers/arcis). This will already be populated with a simple example called `add_together.rs`. Let's take a closer look at it. ### Our first encrypted instruction ```rust theme={null} use arcis::*; #[encrypted] mod circuits { use arcis::*; pub struct InputValues { v1: u8, v2: u8, } #[instruction] pub fn add_together(input_ctxt: Enc<Shared, InputValues>) -> Enc<Shared, u16> { let input = input_ctxt.to_arcis(); let sum = input.v1 as u16 + input.v2 as u16; input_ctxt.owner.from_arcis(sum) } } ``` Let's go through it line by line. `use arcis::*;` imports all the necessary types and functions for writing encrypted instructions with Arcis. The `#[encrypted]` attribute marks a module that contains encrypted instructions. Inside this module, we define a struct `InputValues` that contains the two values we want to encrypt and pass to the encrypted instruction. The `#[instruction]` macro marks the function as an entry point for MPC execution. While you can write helper functions without this attribute, only functions marked with `#[instruction]` will be compiled into individual circuits that can be called onchain. The function `add_together` takes an encrypted input parameter of type `Enc<Shared, InputValues>`. Let's break this down: * `Enc<Owner, Data>` is Arcium's encrypted data type * `Shared` means the data is encrypted with a shared secret between the client and MXE (both can decrypt it) * `InputValues` is the actual data structure being encrypted (our struct with v1 and v2) * The alternative to `Shared` is `Mxe`, where only the MXE can decrypt the data Inside the function: 1. `input_ctxt.to_arcis()` converts the input into a form we can operate on within the MPC environment. 2. We perform the addition operation, casting the u8 values to u16 to prevent overflow. 3. `input_ctxt.owner.from_arcis(sum)` converts the encrypted sum into an encrypted format that can be stored onchain, while maintaining encryption with the shared secret between the client and the MXE. ### Calling it from Solana Now that we've written our first encrypted instruction, let's see how we can use it from within a Solana program. Our default project already contains a Solana program in the `programs/` directory. Let's take a closer look at it too: ```rust theme={null} use anchor_lang::prelude::*; use arcium_anchor::prelude::*; // This constant identifies our encrypted instruction for onchain operations // comp_def_offset() generates a unique identifier from the function name const COMP_DEF_OFFSET_ADD_TOGETHER: u32 = comp_def_offset("add_together"); declare_id!("YOUR_PROGRAM_ID_HERE"); #[arcium_program] pub mod hello_world { use super::*; pub fn init_add_together_comp_def(ctx: Context<InitAddTogetherCompDef>) -> Result<()> { init_computation_def(ctx.accounts, None)?; Ok(()) } 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<()> { let args = ArgBuilder::new() .x25519_pubkey(pub_key) .plaintext_u128(nonce) .encrypted_u8(ciphertext_0) .encrypted_u8(ciphertext_1) .build(); ctx.accounts.sign_pda_account.bump = ctx.bumps.sign_pda_account; queue_computation( ctx.accounts, computation_offset, args, vec![AddTogetherCallback::callback_ix( computation_offset, &ctx.accounts.mxe_account, &[] )?], 1, 0, // cu_price_micro: priority fee in microlamports 0, // callback_cu_limit: 0 derives the limit from simulation )?; Ok(()) } #[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(()) } } ``` For brevity, the `InitAddTogetherCompDef`, `AddTogether`, and `AddTogetherCallback` account structs are not included here, but they are automatically generated when you run `arcium init`. Here's a simplified version of what `AddTogether` looks like: ```rust theme={null} #[derive(Accounts)] #[instruction(computation_offset: u64)] pub struct AddTogether<'info> { #[account(mut)] pub payer: Signer<'info>, // ... other required Arcium accounts (see program/ section for full details) } ``` For the full Solana program flow, see [Invoking computations from your Solana program](/developers/program). The key things to note here are that every MXE program is identified by the `#[arcium_program]` macro (which replaces Anchor's `#[program]` macro) and that for every encrypted instruction, we generally have three instructions in the Solana program: * `init_add_together_comp_def`: Initializes the computation definition. This runs once before the first invocation of the encrypted instruction. See [Computation definition accounts](/developers/program/computation-def-accs). * `add_together`: Invokes the encrypted instruction, builds the arguments, and queues the computation through the Arcium program. See [Invoking computations](/developers/program). * `add_together_callback`: Runs after the MPC cluster finishes the encrypted instruction and returns the result. See [Invoking computations](/developers/program). These three instructions mirror the standard [computation lifecycle](/developers/computation-lifecycle). ## Building and testing Similar to Anchor, encrypted instructions and Solana programs are built with `arcium build`. Tests use the [`@arcium-hq/client` TypeScript library](/developers/js-client-library) by default and run with `arcium test`. Install npm dependencies first with `yarn` or `npm install` in your project directory. By default, tests run against a local cluster. To preview Surfpool locally, run `arcium test --validator surfpool`; see [Choose a local validator](/developers/arcium-toml#choose-a-local-validator). To test against devnet or mainnet, use `arcium test --cluster devnet` after adding the cluster offset to `Arcium.toml`, for example `[clusters.devnet] offset = 456`. For faster local loops, use `arcium test --test-name <name>` to run `tests/<name>.ts`. After a full localnet keygen, `arcium test --skip-keygen` or `arcium localnet --skip-keygen` reuses cached MXE keys; for detached runs, call `arcium snapshot-mxe-keygen --rpc-url l` before shutting down the validator. Let's take a quick look at the def
프로젝트로 돌아가기