토큰 계정 생성하기
Confidential Transfer 확장 기능으로 토큰 계정 생성하는 방법
Confidential Transfer 확장 기능은 토큰 계정에 추가 상태를 더함으로써 비공개 토큰 전송을 가능하게 합니다. 이 섹션에서는 이 확장 기능이 활성화된 토큰 계정을 생성하는 방법을 설명합니다.
다음 다이어그램은 Confidential Transfer 확장 기능이 있는 토큰 계정을 생성하는 단계를 보여줍니다:
Confidential Transfer 토큰 계정 상태
이 확장 기능은 토큰 계정에 ConfidentialTransferAccount 상태를 추가합니다:
#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]pub struct ConfidentialTransferAccount {/// `true` if this account has been approved for use. All confidential/// transfer operations for the account will fail until approval is/// granted.pub approved: PodBool,/// The public key associated with ElGamal encryptionpub elgamal_pubkey: PodElGamalPubkey,/// The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`)pub pending_balance_lo: EncryptedBalance,/// The high 48 bits of the pending balance (encrypted by `elgamal_pubkey`)pub pending_balance_hi: EncryptedBalance,/// The available balance (encrypted by `encryption_pubkey`)pub available_balance: EncryptedBalance,/// The decryptable available balancepub decryptable_available_balance: DecryptableBalance,/// If `false`, the extended account rejects any incoming confidential/// transferspub allow_confidential_credits: PodBool,/// If `false`, the base account rejects any incoming transferspub allow_non_confidential_credits: PodBool,/// The total number of `Deposit` and `Transfer` instructions that have/// credited `pending_balance`pub pending_balance_credit_counter: PodU64,/// The maximum number of `Deposit` and `Transfer` instructions that can/// credit `pending_balance` before the `ApplyPendingBalance`/// instruction is executedpub maximum_pending_balance_credit_counter: PodU64,/// The `expected_pending_balance_credit_counter` value that was included in/// the last `ApplyPendingBalance` instructionpub expected_pending_balance_credit_counter: PodU64,/// The actual `pending_balance_credit_counter` when the last/// `ApplyPendingBalance` instruction was executedpub actual_pending_balance_credit_counter: PodU64,}
*rsConfidentialTransferAccount
*에는 비공개 전송을 관리하기 위한 여러 필드가
포함되어 있습니다:
-
approved: 비공개 전송에 대한 계정의 승인 상태입니다. mint account의
auto_approve_new_accounts
구성이true
로 설정된 경우, 모든 토큰 계정은 자동으로 비공개 전송이 승인됩니다. -
elgamal_pubkey: 잔액과 전송 금액을 암호화하는 데 사용되는 ElGamal 공개 키입니다.
-
pending_balance_lo: 대기 중인 잔액의 암호화된 하위 16비트입니다. 효율적인 복호화를 위해 잔액이 상위와 하위 부분으로 나뉩니다.
-
pending_balance_hi: 대기 중인 잔액의 암호화된 상위 48비트입니다. 효율적인 복호화를 위해 잔액이 상위와 하위 부분으로 나뉩니다.
-
available_balance: 전송에 사용 가능한 암호화된 잔액입니다.
-
decryptable_available_balance: 계정 소유자가 효율적으로 복호화할 수 있도록 고급 암호화 표준(AES) 키로 암호화된 사용 가능한 잔액입니다.
-
allow_confidential_credits: true인 경우, 들어오는 비공개 전송을 허용합니다.
-
allow_non_confidential_credits: true인 경우, 들어오는 비공개가 아닌 전송을 허용합니다.
-
pending_balance_credit_counter: 입금 및 전송 명령에서 들어오는 대기 중인 잔액 크레딧을 계산합니다.
-
maximum_pending_balance_credit_counter: 대기 중인 잔액을 사용 가능한 잔액으로 변환하기 위해
ApplyPendingBalance
명령이 필요하기 전의 대기 중인 크레딧 수 제한입니다. -
expected_pending_balance_credit_counter: 클라이언트가 마지막으로
ApplyPendingBalance
명령어가 처리될 때 instruction data를 통해 제공한pending_balance_credit_counter
값입니다. -
actual_pending_balance_credit_counter: 마지막
ApplyPendingBalance
명령어가 처리될 때 토큰 계정에 있는pending_balance_credit_counter
값입니다.
대기 잔액 vs 사용 가능 잔액
기밀 잔액은 DoS 공격을 방지하기 위해 대기 잔액과 사용 가능 잔액으로 분리됩니다. 이러한 분리가 없다면, 공격자는 반복적으로 토큰 계정에 토큰을 보내 토큰 계정 소유자의 토큰 전송 능력을 차단할 수 있습니다. 토큰 계정 소유자는 트랜잭션이 제출되고 처리되는 사이에 암호화된 잔액이 변경되어 트랜잭션이 실패하기 때문에 토큰을 전송할 수 없게 됩니다.
모든 입금 및 전송 금액은 처음에 대기 잔액에 추가됩니다. 토큰 계정 소유자는
ApplyPendingBalance
명령어를 사용하여 대기 잔액을 사용 가능 잔액으로
전환해야 합니다. 들어오는 전송이나 입금은 토큰 계정의 사용 가능 잔액에 영향을
미치지 않습니다.
대기 잔액 크레딧 카운터
ApplyPendingBalance
명령어를 호출하여 대기 잔액을 사용 가능 잔액으로
전환할 때:
-
클라이언트는 현재 대기 및 사용 가능 잔액을 조회하고, 합계를 암호화한 다음, 토큰 계정 소유자의 AES 키를 사용하여 암호화된
decryptable_available_balance
를 제공합니다. -
예상 및 실제 대기 크레딧 카운터는
ApplyPendingBalance
명령어가 생성되고 처리되는 사이의 카운터 값 변경을 추적합니다:expected_pending_balance_credit_counter
: 클라이언트가ApplyPendingBalance
명령어를 생성할 때의pending_balance_credit_counter
값actual_pending_balance_credit_counter
:ApplyPendingBalance
명령어가 처리될 때 토큰 계정에 있는pending_balance_credit_counter
값
일치하는 예상/실제 카운터는 decryptable_available_balance
가
available_balance
와 일치함을 나타냅니다.
토큰 계정의 상태를 가져와서 decryptable_available_balance
를 읽을 때, 예상/실제
카운터 값이 다르면 클라이언트는 카운터 차이와 일치하는 최근 입금/전송 명령어를
조회하여 정확한 잔액을 계산해야 합니다.
잔액 조정 프로세스
예상 및 실제 대기 중인 잔액 카운터가 다를 경우, 다음 단계에 따라
decryptable_available_balance
를 조정하세요:
- 토큰 계정에서
decryptable_available_balance
로 시작합니다 - 카운터 차이(실제 - 예상)까지 입금 및 전송 명령어를 포함한 가장 최근
트랜잭션을 가져옵니다:
- 입금 명령어의 공개 금액을 추가합니다
- 전송 명령어의 대상 암호화 금액을 복호화하고 추가합니다
필수 명령어
기밀 전송 확장 기능이 있는 토큰 계정을 생성하려면 세 가지 명령어가 필요합니다:
-
토큰 계정 생성: Associated Token Program의
AssociatedTokenAccountInstruction:Create
명령어를 호출하여 토큰 계정을 생성합니다. -
계정 공간 재할당: Token Extension Program의
TokenInstruction::Reallocate
명령어를 호출하여ConfidentialTransferAccount
상태를 위한 공간을 추가합니다. -
기밀 전송 구성: Token Extension Program의 ConfidentialTransferInstruction::ConfigureAccount 명령어를 호출하여
ConfidentialTransferAccount
상태를 초기화합니다.
토큰 계정 소유자만이 기밀 전송을 위한 토큰 계정을 구성할 수 있습니다.
ConfigureAccount
명령어는 토큰 계정 소유자만 생성할 수 있는 암호화 키와
증명 데이터를 클라이언트 측에서 생성해야 합니다.
*rsPubkeyValidityProofData
*는 ElGamal 키가 유효한지 확인하는 증명을
생성합니다. 구현 세부 정보는 다음을 참조하세요:
예제 코드
다음 코드는 기밀 전송 확장 기능이 있는 Associated Token Account를 생성하는 방법을 보여줍니다.
예제를 실행하려면 다음 명령어를 사용하여 메인넷에서 복제된 Token Extension Program으로 로컬 검증자를 시작하세요. 로컬 검증자를 시작하려면 Solana CLI가 설치되어 있어야 합니다.
$solana-test-validator --clone-upgradeable-program TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb --url https://api.mainnet-beta.solana.com -r
작성 시점에서는 기본 로컬 validator에서 기밀 전송(Confidential Transfers)이 활성화되어 있지 않습니다. 예제 코드를 실행하려면 메인넷 Token Extensions Program을 복제해야 합니다.
use anyhow::{Context, Result};use solana_client::nonblocking::rpc_client::RpcClient;use solana_sdk::{commitment_config::CommitmentConfig,signature::{Keypair, Signer},transaction::Transaction,};use spl_associated_token_account::{get_associated_token_address_with_program_id, instruction::create_associated_token_account,};use spl_token_client::{client::{ProgramRpcClient, ProgramRpcClientSendTransaction},spl_token_2022::{extension::{confidential_transfer::instruction::{configure_account, PubkeyValidityProofData},ExtensionType,},id as token_2022_program_id,instruction::reallocate,solana_zk_sdk::encryption::{auth_encryption::*, elgamal::*},},token::{ExtensionInitializationParams, Token},};use spl_token_confidential_transfer_proof_extraction::instruction::{ProofData, ProofLocation};use std::sync::Arc;#[tokio::main]async fn main() -> Result<()> {// Create connection to local test validatorlet rpc_client = Arc::new(RpcClient::new_with_commitment(String::from("http://localhost:8899"),CommitmentConfig::confirmed(),));// Load the default Solana CLI keypair to use as the fee payer// This will be the wallet paying for the transaction fees// Use Arc to prevent multiple clones of the keypairlet payer = Arc::new(load_keypair()?);println!("Using payer: {}", payer.pubkey());// Generate a new keypair to use as the address of the token mintlet mint = Keypair::new();println!("Mint keypair generated: {}", mint.pubkey());// Set up program client for Token clientlet program_client = ProgramRpcClient::new(rpc_client.clone(), ProgramRpcClientSendTransaction);// Number of decimals for the mintlet decimals = 9;// Create a token client for the Token-2022 program// This provides high-level methods for token operationslet token = Token::new(Arc::new(program_client),&token_2022_program_id(), // Use the Token-2022 program (newer version with extensions)&mint.pubkey(), // Address of the new token mintSome(decimals), // Number of decimal placespayer.clone(), // Fee payer for transactions (cloning Arc, not keypair));// Create extension initialization parameters for the mint// The ConfidentialTransferMint extension enables confidential (private) transfers of tokenslet extension_initialization_params =vec![ExtensionInitializationParams::ConfidentialTransferMint {authority: Some(payer.pubkey()), // Authority that can modify confidential transfer settingsauto_approve_new_accounts: true, // Automatically approve new confidential accountsauditor_elgamal_pubkey: None, // Optional auditor ElGamal public key}];// Create and initialize the mint with the ConfidentialTransferMint extension// This sends a transaction to create the new token mintlet transaction_signature = token.create_mint(&payer.pubkey(), // Mint authority - can mint new tokensSome(&payer.pubkey()), // Freeze authority - can freeze token accountsextension_initialization_params, // Add the ConfidentialTransferMint extension&[&mint], // Mint keypair needed as signer).await?;println!("Mint Address: {}", mint.pubkey());println!("Mint Creation Transaction Signature: {}",transaction_signature);// ===== Create and configure token account for confidential transfers =====println!("\nCreate and configure token account for confidential transfers");// Get the associated token account address for the ownerlet token_account_pubkey = get_associated_token_address_with_program_id(&payer.pubkey(), // Token account owner&mint.pubkey(), // Mint&token_2022_program_id(), // Token program ID);println!("Token Account Address: {}", token_account_pubkey);// Step 1: Create the associated token accountlet create_associated_token_account_instruction = create_associated_token_account(&payer.pubkey(), // Funding account&payer.pubkey(), // Token account owner&mint.pubkey(), // Mint&token_2022_program_id(), // Token program ID);// Step 2: Reallocate the token account to include space for the ConfidentialTransferAccount extensionlet reallocate_instruction = reallocate(&token_2022_program_id(), // Token program ID&token_account_pubkey, // Token account&payer.pubkey(), // Payer&payer.pubkey(), // Token account owner&[&payer.pubkey()], // Signers&[ExtensionType::ConfidentialTransferAccount], // Extension to reallocate space for)?;// Step 3: Generate the ElGamal keypair and AES key for token accountlet elgamal_keypair = ElGamalKeypair::new_from_signer(&payer, &token_account_pubkey.to_bytes()).expect("Failed to create ElGamal keypair");let aes_key = AeKey::new_from_signer(&payer, &token_account_pubkey.to_bytes()).expect("Failed to create AES key");// The maximum number of Deposit and Transfer instructions that can// credit pending_balance before the ApplyPendingBalance instruction is executedlet maximum_pending_balance_credit_counter = 65536;// Initial token balance is 0let decryptable_balance = aes_key.encrypt(0);// Generate the proof data client-sidelet proof_data = PubkeyValidityProofData::new(&elgamal_keypair).map_err(|_| anyhow::anyhow!("Failed to generate proof data"))?;// Indicate that proof is included in the same transactionlet proof_location =ProofLocation::InstructionOffset(1.try_into()?, ProofData::InstructionData(&proof_data));// Step 4: Create instructions to configure the account for confidential transferslet configure_account_instructions = configure_account(&token_2022_program_id(), // Program ID&token_account_pubkey, // Token account&mint.pubkey(), // Mint&decryptable_balance.into(), // Initial balancemaximum_pending_balance_credit_counter, // Maximum pending balance credit counter&payer.pubkey(), // Token Account Owner&[], // Additional signersproof_location, // Proof location)?;// Combine all instructionslet mut instructions = vec![create_associated_token_account_instruction,reallocate_instruction,];instructions.extend(configure_account_instructions);// Create and send the transactionlet recent_blockhash = rpc_client.get_latest_blockhash().await?;let transaction = Transaction::new_signed_with_payer(&instructions,Some(&payer.pubkey()),&[&payer],recent_blockhash,);let transaction_signature = rpc_client.send_and_confirm_transaction(&transaction).await?;println!("Create Token Account Transaction Signature: {}",transaction_signature);Ok(())}// Load the keypair from the default Solana CLI keypair path (~/.config/solana/id.json)// This enables using the same wallet as the Solana CLI toolsfn load_keypair() -> Result<Keypair> {// Get the default keypair pathlet keypair_path = dirs::home_dir().context("Could not find home directory")?.join(".config/solana/id.json");// Read the keypair file directly into bytes using serde_json// The keypair file is a JSON array of byteslet file = std::fs::File::open(&keypair_path)?;let keypair_bytes: Vec<u8> = serde_json::from_reader(file)?;// Create keypair from the loaded bytes// This converts the byte array into a keypairlet keypair = Keypair::from_bytes(&keypair_bytes)?;Ok(keypair)}
Is this page helpful?