Arcium 백서

Arcium

원문

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

romote computations from the mempool by leader choice, priority fee, and lock-conflict checks 3. **MPC execution** - When your computation's turn comes, MPC nodes execute it offchain 4. **Callback invocation** - Results are returned via your callback instruction This means you can't await a transaction completion like normal Solana programs. Instead, you need to wait for the entire computation lifecycle to finish. The Arcium client library provides utilities to handle this: ## Await computation completion with `awaitComputationFinalization` ```typescript theme={null} // Generate a random 8-byte computation offset const computationOffset = new anchor.BN(randomBytes(8), "hex"); // `program` is the anchor program client of the MXE we're invoking // the instruction `ourIx` on (which then invokes a computation under the hood by CPIing into the Arcium program). // `queueSig` is the signature of said transaction. const queueSig = await program.methods .ourIx( // Computation offset that you provide when invoking the instruction computationOffset /* other inputs */ ) .accounts(/* some accounts */) .rpc(); // Since this is an Arcium computation, we need to wait for it to be finalized // a little bit differently const finalizeSig = await awaitComputationFinalization( // Anchor provider provider as anchor.AnchorProvider, // Computation offset that you provide when invoking the instruction computationOffset, // Program ID of the MXE program.programId, // Solana commitment level, "confirmed" by default "confirmed" ); console.log("Computation was finalized with sig: ", finalizeSig); ``` The optional fifth argument, `timeoutMs`, sets the maximum wait time in milliseconds. It defaults to `120000`. <Note> Failed finalization reports a `CircuitFailureReason` such as `OffChainCircuitFetchFailed`, `OffChainCircuitHashMismatch`, `CircuitCUMismatch`, `LocalCircuitFetchFailed`, or `CircuitSerialization`. </Note> ## Subscribe to computation events Register the subscription before queuing a computation because log subscriptions do not backfill earlier events: ```typescript theme={null} import { subscribeComputations, unsubscribeComputations, } from "@arcium-hq/reader"; const computationOffset = new anchor.BN(randomBytes(8), "hex"); const subscriptionId = await subscribeComputations( connection, program.programId, (event, name) => { console.log(name, event); } ); try { await program.methods .ourIx(computationOffset /* other inputs */) .accounts(/* ... */) .rpc(); } finally { await unsubscribeComputations(connection, subscriptionId); } ``` `subscribeComputations` resolves after the RPC server acknowledges the log subscription. The acknowledgement timeout defaults to 10 seconds; pass `{ ackTimeoutMs }` as the fourth argument to override it. If acknowledgement times out, the helper attempts to remove the listener before throwing. ## Read and assert the callback result Finalization tells you the callback has run, but not what it produced. Consume the result the way you would in any Solana program: await an emitted event, or read updated account state. Events are the common path because Arcium callbacks typically relay encrypted payloads for the client to decrypt offchain. Event-based decryption requires the callback to emit both the ciphertext and the nonce. See the callback-side `emit!` pattern in the [Arcium program guide](/developers/program). On the client side, register the event listener **before** queuing the computation so it's attached by the time the callback fires. Helpers and imports are omitted for brevity: `awaitEvent` is a test-scaffold wrapper around `program.addEventListener`, `cipher` comes from the encryption setup in [Encrypting inputs](/developers/js-client-library/encryption), and `expect` / `expectedSum` are shown in a test context. ```typescript theme={null} // Register the listener first to avoid a race where the callback fires // before you've subscribed. const sumEventPromise = awaitEvent("sumEvent"); const computationOffset = new anchor.BN(randomBytes(8), "hex"); const queueSig = await program.methods .ourIx(computationOffset /* other inputs */) .accounts(/* ... */) .rpc({ commitment: "confirmed" }); await awaitComputationFinalization( provider as anchor.AnchorProvider, computationOffset, program.programId, "confirmed" ); // Callback has fired; resolve the event, decrypt offchain, and assert. const sumEvent = await sumEventPromise; const decrypted = cipher.decrypt([sumEvent.sum], new Uint8Array(sumEvent.nonce))[0]; expect(decrypted).to.equal(expectedSum); ``` The two valid orderings are: * **Event path**: `subscribe → queue → finalize → await event → decrypt → assert` * **Account path**: `queue → finalize → read account → assert` ## 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="Deployment" icon="rocket" href="/developers/deployment"> Deploy your MXE program to devnet or mainnet. </Card> </CardGroup> # Encrypting inputs Source: https://docs.arcium.com/developers/js-client-library/encryption Encrypt inputs with X25519 key exchange and Rescue, then decrypt encrypted computation outputs. Let's say we have the following encrypted instruction that adds 2 encrypted `u8`s and returns the result encrypted: ```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) } } ``` We want to input the values `x = 42` and `y = 101` into this instruction. To do this, we first have to build the parameters for the encrypted instruction correctly: ```typescript theme={null} import { RescueCipher, getArciumEnv, x25519 } from "@arcium-hq/client"; import { randomBytes } from "crypto"; // Our encrypted instruction takes two encrypted `u8` values as input, so we need to provide two ciphertext values which are represented as `[u8; 32]` in our Solana program. const val1 = BigInt(42); const val2 = BigInt(101); const plaintext = [val1, val2]; ``` Now that we have the inputs, we need to encrypt them. This is done using the `RescueCipher` class with some info about the MPC cluster we want to use: ```typescript theme={null} // Fetch the MXE x25519 public key // getMXEPublicKeyWithRetry is a helper that wraps getMXEPublicKey with retries // See the Hello World tutorial for the full implementation const mxePublicKey = await getMXEPublicKeyWithRetry( provider as anchor.AnchorProvider, program.programId ); // Generate a random private key for x25519 elliptic curve Diffie-Hellman key exchange. const privateKey = x25519.utils.randomSecretKey(); // Derive the public key from the private key. const publicKey = x25519.getPublicKey(privateKey); // Generate a random nonce for the encryption. const nonce = randomBytes(16); // Get the shared secret with the cluster. const sharedSecret = x25519.getSharedSecret(privateKey, mxePublicKey); // Initialize the cipher with the shared secret. const cipher = new RescueCipher(sharedSecret); // Encrypt the plaintext, and serialize it to a `[u8; 32]` array. const ciphertext = cipher.encrypt(plaintext, nonce); ``` To decrypt the data, again it follows a similar pattern: ```typescript theme={null} // Initialize the cipher with the shared secret. const cipher = new RescueCipher(sharedSecret); const plaintext = cipher.decrypt(ciphertext, nonce); ``` <Note> **Working with packed data?** If your Arcis structs use `Pack<T>`, you'll use generated packers on the client. See [Efficient data packing](/developers/arcis/input-output#efficient-data-packing). </Note> ## What's next? <CardGroup> <Card title="Handle callbacks" icon="phone" href="/developers/js-client-library/callback"> Learn how to await and process computation results. </Card> <Card title="Full API Reference" icon="book" href="https://ts.arcium.com/api"> Complete TypeScript SDK documentation. </Card> </CardGroup> # Current limitations Source: https://docs.arcium.com/developers/limitations Output size limits, Arcis language constraints, and common error codes when building encrypted applications on Arcium ## Keep callback transactions within the size limit Solana limits a serialized transaction to 1,232 bytes. Callback output shares this limit with signatures, account keys, instructions, and other callback data, so the usable output size depends on the callback. If Arx cannot build the callback as a single transaction, the computation fails with `OutputTooLarge`. Keep outputs compact and test the largest expected output with the callback accounts used by your application. Split larger results across separate computations when necessary. ## Arcis language constraints Arcis compiles Rust-like code into fixed MPC circuits. The circuit shape must be known at compile time, so several standard Rust patterns need different implementations: | Pattern | Status | Use instead | | --------------------------------------------------------------- | ------------- | ------------------------------------------------ | | `Vec`, `String`, `HashMap` | Not supported | Fixed-size arrays, byte arrays, or structs | | `while`, `loop` | Not supported | `for` loops with fixed bounds | | `break`, `continue`, early `return` | Not supported | A single exit path with conditional assignments | | `let ... else` | Not supported | `if let` or `match` | | `.reveal()` or `.from_arcis()` inside non-constant conditionals | Not supported | Move the reveal or conversion outside the branch | Arcis supports `if`, `else`, `else if`, `if let`, let chains, `match`, `matches!`, fixed-size arrays, structs, tuples, enums, `Option<T>`, and fixed-bound loops. Enums and `Option<T>` cannot be the input or output of an encrypted instruction, and enum discriminants cannot be set explicitly. See the [Operations guide](/developers/arcis/operations) for the complete support matrix. ## Common errors | Error or symptom | Likely cause | Fix | | ------------------------------------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `OutputTooLarge` | The complete callback transaction exceeds Solana's transaction size limit | Return less data or split the result across separate computations | | Computation never finalizes | Computation definition was not initialized, callback is missing, or cluster configuration is wrong | Initialize the computation definition, check callback registration, and verify the cluster offset | | Decryption fails | Nonce mismatch, nonce reuse, wrong MXE key, or incorrect ciphertext order | Use a fresh 16-byte nonce per encryption and match the circuit argument order exactly | | Shared input fails silently | Missing `x25519_pubkey` before the nonce and ciphertext | For `Enc<Shared, T>`, pass public key, nonce, then ciphertexts | | Callback runs but state is unchanged | Callback account was not writable or was omitted from callback accounts | Mark the account writable in both the callback account list and the Anchor account struct | | Circuit compile failure | Unsupported Rust construct or variable-size data | Replace dynamic constructs with fixed-size Arcis patterns | ## What's next? <CardGroup> <Card title="Best practices" icon="wand-magic-sparkles" href="/developers/arcis/best-practices"> Performance tips and common patterns </Card> <Card title="Operations guide" icon="grid-2" href="/developers/arcis/operations"> Complete operation support matrix </Card> <Card title="Types reference" icon="tags" href="/developers/arcis/types"> Supported and unsupported types </Card> <Card title="Deployment" icon="rocket" href="/developers/deployment"> Deploy your MXE to the network </Card> </CardGroup> # Node setup Source: https://docs.arcium.com/developers/node-setup Run an Arx node: hardware requirements and network registration ## Overview As a Node Operator, you'll set up your own Arx node to participate in the Arcium Network. This guide walks you through each step of the process. First, you'll prepare your environment by installing the necessary tools and generating security keys. Then, you'll get your node registered onchain and configure it to run. Finally, you'll connect to other nodes in a cluster and start doing computations. By the end, you will: * Install the Arcium tooling * Generate required keypairs * Fund accounts with SOL * Initialize onchain node accounts * Configure your node * Join or create a cluster * Deploy your node with Docker ## Prerequisites Before starting, ensure you have the following installed: * **Rust**: Install from [rustup.rs](https://rustup.rs/) * **Solana CLI 3.1.10**: Install from [Solana's documentation](https://docs.solana.com/cli/install-solana-cli-tools) * **Docker & Docker Compose**: Install from [Docker's documentation](https://docs.docker.com/get-docker/) * **OpenSSL**: Install from [OpenSSL's documentation](https://www.openssl.org/source/) (usually pre-installed on macOS/Linux) * **Git**: For cloning repositories and version control You'll also need: * A reliable internet connection * Basic familiarity with command-line tools **Recommended system requirements:** | Resource | Recommendation | | --------- | ------------------------------------ | | RAM | 32GB+ | | CPU | 12+ cores, 2.8GHz+ base | | Bandwidth | 1 Gbit/s minimum | | Disk | Minimal (node is not disk-intensive) | | GPU | Not required | **Network requirements - open these ports:** | Port | Protocol | Purpose | | ---- | --------- | -------------------------- | | 8001 | TCP & UDP | MPC protocol communication | | 8002 | TCP & UDP | BLS signature aggregation | | 8012 | TCP & UDP | TD preprocessing | | 8013 | TCP & UDP | TD registration | | 9091 | TCP | Prometheus metrics | <Warning>**Windows users:** Arcium doesn't run natively on Windows yet. Use Windows Subsystem for Linux (WSL2) with Ubuntu to follow this guide.</Warning> ## Step 1: Set up your workspace Create a dedicated folder for your node setup to keep everything organized: ```bash theme={null} mkdir arcium-node-setup cd arcium-node-setup ``` <Warning>Stay in this directory for all remaining steps. All file paths and Docker commands assume you're working from `arcium-node-setup/`.</Warning> You'll also need to know your public IP address for the next steps. Here's a quick way to find it: ```bash theme={null} curl https://ipecho.net/plain ; echo ``` ## Step 2: Install Arcium tooling The Arcium tooling suite includes the CLI and Arx node software. Install it using the automated installer: ```bash theme={null} curl --proto '=https' --tlsv1.2 -sSfL https://install.arcium.com/ | bash ``` This script will: * Check for all required dependencies * Install `arcup` (Arcium's version manager) * Install the latest Arcium CLI * Install the Arx node software Verify the installation: ```bash theme={null} arcium --version && arcup --version ``` If you prefer manual installation, see the [installation guide](/developers/installation) for detailed instructions. ## Step 3: Generate required keypairs Your Arx node needs five different keypairs for secure operation. Create these in your `arcium-node-setup` directory: ### 3.1 Node authority keypair This Solana keypair identifies your node and handles onchain operations: ```bash theme={null} solana-keygen new --outfile node-keypair.json --no-bip39-passphrase ``` <Note>The `--no-bip39-passphrase` flag creates a keypair without a passphrase for easier automation.</Note> ### 3.2 Callback authority keypair This Solana keypair signs callback computations and must be different from your node keypair for security separation: ```bash theme={null} solana-keygen new --outfile callback-kp.json --no-bip39-passphrase ``` ### 3.3 Identity keypair This keypair handles node-to-node communication and must be in PKCS#8 format: ```bash theme={null} openssl genpkey -algorithm Ed25519 -out identity.pem ``` ### 3.4 BLS keypair This keypair is used for BLS (Boneh-Lynn-Shacham) threshold signatures on MPC computation callbacks. Generate it using the Arcium CLI: ```bash theme={null} arcium gen-bls-key bls-keypair.json ``` This creates a 32-byte private key stored as a JSON array format. ### 3.5 X25519 keypair This keypair is used for encrypted communication between nodes: ```bash theme={null} arcium generate-x25519 -o x25519-keypair.json ``` This creates a 32-byte X25519 private key stored in JSON array format. ### 3.6 Cerberus global-keys seed Only needed if you run [distributed preprocessing](#preprocessing-backend). Skip this if you use a trusted dealer. ```bash theme={null} arcium generate-cerberus-seed -o cerberus-seed.json ``` This is secret, per-node key material. Generate it **once** per node and keep it stable across restarts. The file is created read-only to its owner (mode `0400`) and the command refuses to overwrite an existing file, so an accidental rerun cannot destroy a seed a node is already using. <Warning>Keep these keypairs safe and private. Back them up to a secure location outside your VPS - you'll need them to restore your node if something goes wrong. Never share them with anyone.</Warning> ## Step 4: Fund your accounts Your node and callback accounts need SOL for transaction fees. Transfer SOL to both accounts and verify balances: ```bash theme={null} # Check your account addresses solana address --keypair node-keypair.json solana address --keypair callback-kp.json # Verify balances solana balance "$(solana address --keypair node-keypair.json)" solana balance "$(solana address --keypair callback-kp.json)" ``` <Note>On devnet, you can use `solana airdrop 2 <address> -u devnet` or the [web faucet](https://faucet.solana.com/) to get free SOL for testing.</Note> <Warning>On mainnet, SOL has real economic value. Ensure you have sufficient funds before proceeding.</Warning> ## Step 5: Initialize node accounts Now we'll register your node with the Arcium Network by creating its onchain accounts. This step tells the blockchain about your node and its capabilities. <Warning> Always pass `--rpc-url <your-rpc-url>` to `arcium` commands. `solana config set --url ...` affects Solana CLI commands only; `arcium` defaults to mainnet when `--rpc-url` is omitted. `init-arx-accs` creates and activates the node's primary stake account unless you skip those steps. The default lockup is 100 epochs. Run the command with `--dry-run` first to inspect the planned transactions. </Warning> For guidance on choosing a reliable endpoint, see the [RPC Provider Recommendations](#rpc-provider-recommendations). Use the `init-arx-accs` command to initialize all required onchain accounts for your node: ```bash theme={null} arcium init-arx-accs \ --keypair-path node-keypair.json \ --callback-keypair-path callback-kp.json \ --peer-keypair-path identity.pem \ --bls-keypair-path bls-keypair.json \ --x25519-keypair-path x25519-keypair.json \ --amount <whole-arx-to-stake> \ --node-offset <your-node-offset> \ --ip-address <your-public-ip> \ --rpc-url <your-rpc-url> ``` ### Required parameters: * `--keypair-path`: Path to your node authority keypair * `--callback-keypair-path`: Path to your callback authority keypair * `--peer-keypair-path`: Path to your identity keypair (PEM format) * `--bls-keypair-path`: Path to your BLS keypair (JSON array format) * `--x25519-keypair-path`: Path to your X25519 keypair (JSON array format) * `--amount`: Amount to stake, in whole ARX tokens. For example, `1000` stakes 1,000 ARX. * `--node-offset`: Your node's unique ID number on the network. Choose a unique, non-zero number. If
프로젝트로 돌아가기