Arcium 백서

Arcium

원문

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

ault test file. Some helper functions and imports are excluded for brevity, but you can find the complete examples in your generated project: ```typescript theme={null} describe("Hello World", () => { // Configure the client to use the local cluster. anchor.setProvider(anchor.AnchorProvider.env()); const program = anchor.workspace.HelloWorld as Program<HelloWorld>; const provider = anchor.getProvider(); const arciumEnv = getArciumEnv(); it("Is initialized!", async () => { const owner = readKpJson(`${os.homedir()}/.config/solana/id.json`); console.log("Initializing add together computation definition"); const initATSig = await initAddTogetherCompDef(program, owner); console.log( "Add together computation definition initialized with signature", initATSig ); const privateKey = x25519.utils.randomSecretKey(); const publicKey = x25519.getPublicKey(privateKey); const mxePublicKey = await getMXEPublicKeyWithRetry( provider as anchor.AnchorProvider, program.programId ); console.log("MXE x25519 pubkey is", mxePublicKey); const sharedSecret = x25519.getSharedSecret(privateKey, mxePublicKey); const cipher = new RescueCipher(sharedSecret); const val1 = BigInt(1); const val2 = BigInt(2); const plaintext = [val1, val2]; const nonce = randomBytes(16); const ciphertext = cipher.encrypt(plaintext, nonce); const sumEventPromise = awaitEvent("sumEvent"); const computationOffset = new anchor.BN(randomBytes(8), "hex"); const queueSig = await program.methods .addTogether( computationOffset, Array.from(ciphertext[0]), Array.from(ciphertext[1]), Array.from(publicKey), new anchor.BN(deserializeLE(nonce).toString()) ) .accountsPartial({ computationAccount: getComputationAccAddress( arciumEnv.arciumClusterOffset, computationOffset ), clusterAccount: getClusterAccAddress(arciumEnv.arciumClusterOffset), mxeAccount: getMXEAccAddress(program.programId), mempoolAccount: getMempoolAccAddress(arciumEnv.arciumClusterOffset), executingPool: getExecutingPoolAccAddress(arciumEnv.arciumClusterOffset), compDefAccount: getCompDefAccAddress( program.programId, Buffer.from(getCompDefAccOffset("add_together")).readUInt32LE() ), }) .rpc({ commitment: "confirmed" }); console.log("Queue sig is ", queueSig); const finalizeSig = await awaitComputationFinalization( provider as anchor.AnchorProvider, computationOffset, program.programId, "confirmed" ); console.log("Finalize sig is ", finalizeSig); const sumEvent = await sumEventPromise; const decrypted = cipher.decrypt([sumEvent.sum], new Uint8Array(sumEvent.nonce))[0]; expect(decrypted).to.equal(val1 + val2); }); }); ``` This test demonstrates the complete flow of encrypted computations in Arcium. Here's what each key step does: * `initAddTogetherCompDef`: Call the `init_add_together_comp_def` instruction to initialize the encrypted instruction definition. (only need to be called once after the program is deployed) * `getMXEPublicKeyWithRetry`: Fetch the MXE's x25519 public key. * `x25519.utils.randomSecretKey`: Generate a random private key for the x25519 key exchange. * `x25519.getPublicKey`: Generate the public key corresponding to the private key we generated above. * `x25519.getSharedSecret`: Generate the shared secret with the MXE cluster using a x25519 key exchange. * `cipher = new RescueCipher(sharedSecret)`: Initialize the Rescue cipher. The constructor derives a key from the Rescue-Prime hash function; see [Encryption overview](/developers/encryption). * `cipher.encrypt`: Encrypt the inputs for the encrypted instruction. * `awaitEvent`: Wait for the `sumEvent` event to be emitted by the program on finalization of the computation (in the callback instruction). * `addTogether`: Call the `add_together` instruction to invoke the encrypted instruction. * `awaitComputationFinalization`: Since waiting for an Arcium computation is not the same as waiting for one Solana transaction (because the MPC cluster must finish the computation and invoke the callback), this function is used, which is provided by the Arcium TypeScript library. ## Ready to Deploy? Now that you have built and tested your MXE locally, you are probably eager to see it running live! Head over to our [deployment guide](/developers/deployment) where we'll walk you through getting your MXE deployed on Solana. We'll cover everything from choosing the right RPC endpoint to initializing your computation definitions. ## What's next? <CardGroup> <Card title="Examples" icon="list" href="/developers/examples"> Continue with complete applications grouped by complexity. </Card> <Card title="Core concepts" icon="book" href="/developers/core-concepts"> Understand MXEs, Clusters, and encrypted instructions. </Card> <Card title="Learn Arcis" icon="code" href="/developers/arcis/mental-model"> Understand MPC constraints and build more complex circuits. </Card> </CardGroup> # Installation overview Source: https://docs.arcium.com/developers/installation Install the Arcium toolchain with arcup, including Rust, Solana CLI, and Anchor prerequisites ## Quick install (recommended) On Mac and Linux, run this single command to install Arcium: ```bash theme={null} curl --proto '=https' --tlsv1.2 -sSfL https://install.arcium.com/ | bash ``` `arcup` manages Arcium tooling versions, including the CLI and Arx node software. See the [Arcup version manager guide](/developers/installation/arcup) for version-management details. This script will: * Check for all required dependencies * Install Linux build dependencies automatically (if needed) * Download and install `arcup` for your platform * Install the latest Arcium CLI, which interacts with the Arcium Network and manages computations * Install the Arx node software, which performs encrypted computations in the network ### Prerequisites Before running the installation script, make sure you have these dependencies installed: * **Rust**: Install from the [Rust installation guide](https://www.rust-lang.org/tools/install) * **Solana CLI 3.1.10**: Install from the [Solana CLI installation guide](https://docs.solana.com/cli/install-solana-cli-tools), then run `solana-keygen new` * **Yarn**: Install from the [Yarn installation guide](https://yarnpkg.com/getting-started/install) * **Anchor 1.0.2**: Install from the [Anchor installation guide](https://www.anchor-lang.com/docs/installation) * **Docker & Docker Compose**: Install [Docker](https://docs.docker.com/engine/install/) and [Docker Compose](https://docs.docker.com/compose/install/) The installation script will check for all these dependencies and provide clear instructions if any are missing. Surfpool is optional and only required when using the preview `--validator surfpool` backend. Follow the [Surfpool installation guide](https://docs.surfpool.run/toolchain/getting-started) before selecting it. ## Manual installation If you prefer to install manually, use the target-specific binaries below. `arcup` still manages Arcium tooling versions after installation; see the [Arcup version manager guide](/developers/installation/arcup). Install `arcup`. We currently publish pre-built targets for x86 Linux and Apple Silicon. We do not support Windows at the moment. * `x86_64_linux` * `aarch64_macos` You can install it by replacing `<YOUR_TARGET>` with the target you want to install, and running the following command: <CodeGroup> ```bash x86 Linux theme={null} TARGET=x86_64_linux && curl "https://bin.arcium.com/download/arcup_${TARGET}_0.15.0" -o ~/.cargo/bin/arcup && chmod +x ~/.cargo/bin/arcup ``` ```bash Apple Silicon theme={null} TARGET=aarch64_macos && curl "https://bin.arcium.com/download/arcup_${TARGET}_0.15.0" -o ~/.cargo/bin/arcup && chmod +x ~/.cargo/bin/arcup ``` </CodeGroup> Install the latest version of the CLI using `arcup`: ```bash theme={null} arcup install ``` Verify the installation: ```bash theme={null} arcium --version ``` ## Shell completions Generate tab-completion scripts for your shell: <CodeGroup> ```bash Bash theme={null} arcium completions bash >> ~/.bashrc ``` ```bash Zsh theme={null} arcium completions zsh >> ~/.zshrc ``` ```bash Fish theme={null} arcium completions fish > ~/.config/fish/completions/arcium.fish ``` </CodeGroup> Restart your shell or source the config file to activate completions. ## Issues Installation might fail due to a variety of reasons. This section contains a list of the most common issues and their solutions, taken from Anchor's installation guide. ### Platform-specific issues **Windows users:** Arcium is not currently supported on Windows. We recommend using Windows Subsystem for Linux (WSL2) with Ubuntu for the best experience. **Linux systems:** You may need additional dependencies. On Ubuntu/Debian: ```bash theme={null} sudo apt-get update && sudo apt-get upgrade && sudo apt-get install -y pkg-config build-essential libudev-dev libssl-dev ``` ### Incorrect `$PATH` Rust binaries, including `arcup` and `arcium`, are installed to the `~/.cargo/bin` directory. Since this directory is required to be in the `PATH` environment variable, Rust installation tries to set it up automatically, but it might fail to do so on some platforms. To verify that the `PATH` environment variable was set up correctly, run: ```shell theme={null} which arcium ``` The output should look like (with your username): ```text theme={null} /home/user/.cargo/bin/arcium ``` **Shell-specific PATH issues:** If `which arcium` returns nothing, add the cargo bin directory to your PATH: * **Bash/Zsh:** Add to `~/.bashrc` or `~/.zshrc`: ```bash theme={null} export PATH="$HOME/.cargo/bin:$PATH" ``` * **Fish:** Add to `~/.config/fish/config.fish`: ```bash theme={null} set -gx PATH $HOME/.cargo/bin $PATH ``` After editing, restart your terminal or run `source ~/.bashrc` (or equivalent for your shell). ## 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="Core concepts" icon="book" href="/developers/core-concepts"> Understand the Arcium architecture before building. </Card> </CardGroup> # Arcup version manager Source: https://docs.arcium.com/developers/installation/arcup Install and manage Arcium toolchain versions with arcup The `arcup` version manager installs and manages the Arcium tooling suite, including the Arcium CLI binary and the Arx node Docker image. Use it to install the current release, switch between installed versions, and update components when new releases are available. The [Quick start](#quick-start) section below covers basic `arcup` onboarding. For the full toolchain setup, see the [installation overview](/developers/installation). For component compatibility rules, see [Inter-component versioning](#inter-component-versioning). ## Quick start First, check whether you already have a manually installed CLI or Arx node image: ```bash theme={null} command -v arcium || true docker image ls "arcium/*" ``` If you no longer need those old installs, remove the specific binary or Docker image before using `arcup`. Then verify the old CLI is gone or ready to be replaced: ```bash theme={null} arcium --version docker image ls "arcium/*" ``` Next, install `arcup` on your machine by following the [manual installation steps](/developers/installation#manual-installation). Then run the `arcup install` command: ```bash theme={null} arcup install # Installs the latest releases of the Arcium components ``` Now verify that everything is installed correctly: ```bash theme={null} arcium --version # Shows the latest CLI version arcup version # Shows the currently installed Arcium component versions docker images # Lists the image for the Arx node ``` You can also install older versions with `arcup install <version>`, remove installed versions with `arcup uninstall`, and switch between installed versions with `arcup use`. See [Available commands](#available-commands) for details. <Note> `arcium` and `arcup` may print a one-line update banner. Set `ARCIUM_NO_UPDATE_CHECK=1` to suppress it in scripts; CI and non-TTY runs are silent automatically. </Note> ## Inter-component versioning Arcium publishes the CLI and Arx node image as a coordinated release. `arcup install <version>` installs the matching CLI and image for that release, and `arcup update` updates both to the latest coordinated release. Use the same Arcium release across the CLI, Rust crates, TypeScript packages, and Arx node image. Mixed versions might work, but they are not tested or guaranteed. See [Versioning and compatibility](/developers/versioning) for compatibility across releases and the supported upgrade paths. ## Available commands ```bash theme={null} install Install the latest (or a specific) version of Arcium components (Arx node and CLI) update Update all Arcium components (Arx node and CLI) to the latest version list List all installed versions version Show currently active version use Switch to using a specific installed version uninstall Remove a specific version (alias: rm) self Manage arcup itself (update, uninstall) help Print this message or the help of the given subcommand(s) ``` ## Self management The `self` subcommand allows you to manage arcup itself: ```bash theme={null} # Update arcup to the latest version arcup self update # Uninstall arcup and all Arcium components arcup self uninstall # Uninstall but keep Docker images arcup self uninstall --keep-docker # Skip confirmation prompt arcup self uninstall --force # Preview what would be removed (dry run) arcup self uninstall --dry-run ``` # JavaScript client overview Source: https://docs.arcium.com/developers/js-client-library TypeScript SDKs for encrypted computations, network reads, and staking transactions ## Overview Arcium provides three TypeScript SDKs for interacting with Arcium, deployed MXEs (MPC eXecution Environments), and the staking program. Client library `@arcium-hq/client`: * Handles key exchange, encryption, and decryption * Derives Arcium PDAs and packs circuit data * Waits for computation finalization Reader library `@arcium-hq/reader`: * Reads MXE data * Views computations for a given MXE Staking SDK `@arcium-hq/staking`: * Derives staking program-derived addresses (PDAs) * Reads typed staking accounts and delegated positions * Builds staking instructions for a wallet to sign and send Use the client library to encrypt and pack data, derive PDAs, and wait for finalization. Use the reader library to inspect MXE and network state, and the staking SDK to interact with the staking program. For the full computation flow, see the [computation lifecycle](/developers/computation-lifecycle). ## Installation Client library: <CodeGroup> ```bash npm theme={null} npm install @arcium-hq/client ``` ```bash yarn theme={null} yarn add @arcium-hq/client ``` ```bash pnpm theme={null} pnpm add @arcium-hq/client ``` </CodeGroup> Reader library: <CodeGroup> ```bash npm theme={null} npm install @arcium-hq/reader ``` ```bash yarn theme={null} yarn add @arcium-hq/reader ``` ```bash pnpm theme={null} pnpm add @arcium-hq/reader ``` </CodeGroup> Staking SDK: <CodeGroup> ```bash npm theme={null} npm install @arcium-hq/staking @anchor-lang/core @solana/web3.js ``` ```bash yarn theme={null} yarn add @arcium-hq/staking @anchor-lang/core @solana/web3.js ``` ```bash pnpm theme={null} pnpm add @arcium-hq/staking @anchor-lang/core @solana/web3.js ``` </CodeGroup> ## Read staking accounts With an Anchor `AnchorProvider`, create a typed staking program client, then read a wallet's primary stake account and delegated positions: ```typescript theme={null} import { getPrimaryStakeAccInfo, getStakingProgram, getUserStakePositions, } from "@arcium-hq/staking"; const stakingProgram = getStakingProgram(provider); const owner = provider.wallet.publicKey; const primaryStake = await getPrimaryStakeAccInfo(stakingProgram, owner); const delegatedPositions = await getUserStakePositions(stakingProgram, owner); ``` Single-account readers return `null` when the account does not exist. Instruction builders return a `TransactionInstruction` for your wallet to sign and send. ## API reference For complete documentation for all three TypeScript SDKs, see the [API reference](https://ts.arcium.com/api). ## Reclaiming computation rent Every queued computation allocates a Solana account that holds rent. After the computation lifecycle completes, you should reclaim that rent. ### After successful finalization Once a computation reaches `Finalized` status (after the callback executes), use `claimComputationRent` to close the account and reclaim the rent: ```typescript theme={null} import { claimComputationRent } from '@arcium-hq/client'; const sig = await claimComputationRent( provider, // AnchorProvider clusterOffset, // cluster the computation was queued on computationOffset, // BN - the offset used when queueing ); ``` <Warning> The signer must be the original payer who queued the computation. Using a different signer will fail with `InvalidAuthority`. </Warning> <Note> Computations that remain in `Queued` status expire after 180 slots. Expired computations can be reclaimed using the `reclaimExpiredComputationFee` instruction, which also returns any fees from the fee pool. See the [API reference](https://ts.arcium.com/api) for details. </Note> <Note> `claimComputationRent` only closes per-computation accounts. To close long-lived MXE or computation-definition accounts, see [Account lifecycle and closing](/developers/program/account-lifecycle). </Note> ## Reading computation fees The reader library exposes two getters for inspecting a computation's fee, depending on whether its account is still open: ```typescript theme={null} import { getComputationFee, getComputationFeeFromQueueTx } from '@arcium-hq/reader'; // Live computation: reads the onchain fee from the open account. // Returns null once the account is closed (rent reclaimed). const fee = await getComputationFee( arciumProgram, mxeProgramId, computationOffset, ); // Closed computation: reconstructs the queue-time fee inputs by decoding // the original queue_computation instruction from its transaction signature. const queued = await getComputationFeeFromQueueTx( arciumProgram, queueTxSignature, mxeProgramId, computationOffset, ); ``` <Note> `getComputationFee` returns `{ source: 'account', ... }` with the live onchain fee, or `null` when the account has been closed. `getComputationFeeFromQueueTx` returns `{ source: 'queueTx', ... }` with the raw queue-time inputs (not lamport amounts) and requires an archive RPC that retains the original transaction and its inner instructions. See the [API reference](https://ts.arcium.com/api) for the full return shapes. </Note> ## Using the client Prefer a more step-by-step approach? Get started with learning [how to encrypt inputs for encrypted transactions](/developers/js-client-library/encryption). ## What's next? <CardGroup> <Card title="Encrypting inputs" icon="binary-lock" href="/developers/js-client-library/encryption"> Step-by-step guide to encrypting data for encrypted transactions. </Card> <Card title="Tracking callbacks" icon="mobile-retro" href="/developers/js-client-library/callback"> 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> # Tracking callbacks Source: https://docs.arcium.com/developers/js-client-library/callback Track computation progress and handle callback results Unlike regular transactions, encrypted computations involve additional steps after your Solana transaction completes: 1. **Your transaction completes** - Encrypted data is submitted and queued in the cluster's mempool 2. **Computation waits in queue** - MPC nodes p
프로젝트로 돌아가기