トークンアカウントの作成

ZK ElGamalプログラムは、セキュリティ監査中のため、メインネットとdevnetで一時的に無効化されています。これにより、機密転送拡張機能は現在利用できません。概念自体は有効ですが、コード例は実行できません。

Confidential Transfer拡張機能を使用したトークンアカウントの作成方法

Confidential Transfer拡張機能は、トークンアカウントに追加の状態を加えることで、プライベートなトークン転送を可能にします。このセクションでは、この拡張機能を有効にしたトークンアカウントの作成方法について説明します。

以下の図は、Confidential Transfer拡張機能を持つトークンアカウントを作成するための手順を示しています:

Create Token Account with Confidential Transfer Extension

Confidential Transferトークンアカウントの状態

この拡張機能は、トークンアカウントにConfidentialTransferAccount状態を追加します:

Confidential Token Account State
#[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 encryption
pub 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 balance
pub decryptable_available_balance: DecryptableBalance,
/// If `false`, the extended account rejects any incoming confidential
/// transfers
pub allow_confidential_credits: PodBool,
/// If `false`, the base account rejects any incoming transfers
pub 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 executed
pub maximum_pending_balance_credit_counter: PodU64,
/// The `expected_pending_balance_credit_counter` value that was included in
/// the last `ApplyPendingBalance` instruction
pub expected_pending_balance_credit_counter: PodU64,
/// The actual `pending_balance_credit_counter` when the last
/// `ApplyPendingBalance` instruction was executed
pub 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: アカウント所有者が効率的に復号化できるように、Advanced Encryption Standard(AES)キーで暗号化された利用可能な残高。

  • allow_confidential_credits: trueの場合、着信する機密転送を許可します。

  • allow_non_confidential_credits: trueの場合、着信する非機密転送を許可します。

  • pending_balance_credit_counter: 入金および送金instructionsからの保留中の残高クレジットをカウントします。

  • maximum_pending_balance_credit_counter: 保留中のクレジットの上限数で、この数を超えると ApplyPendingBalance instructionを使用して保留中の残高を利用可能な残高に変換する必要があります。

  • expected_pending_balance_credit_counter: クライアントが ApplyPendingBalance instructionを最後に処理した際に、instruction dataを通じて提供された pending_balance_credit_counter の値。

  • actual_pending_balance_credit_counter: 最後の ApplyPendingBalance instructionが処理された時点でのtoken accountの pending_balance_credit_counter の値。

保留中の残高と利用可能な残高の違い

機密残高は、DoS攻撃を防ぐために保留中の残高と利用可能な残高に分けられています。この分離がなければ、攻撃者はtoken accountに繰り返しトークンを送信し、token accountの所有者がトークンを送金する能力をブロックすることができます。トランザクションが送信されてから処理されるまでの間に暗号化された残高が変わるため、token accountの所有者はトークンを送金できなくなり、トランザクションが失敗することになります。

すべての入金と送金額は最初に保留中の残高に追加されます。token accountの所有者は ApplyPendingBalance instructionを使用して、保留中の残高を利用可能な残高に変換する必要があります。入金や送金はtoken accountの利用可能な残高に影響しません。

保留中の残高のHigh/Low分割

機密保留残高は pending_balance_lopending_balance_hi に分割されています。これはElGamal復号化が大きな数値に対してより多くの計算を必要とするためです。暗号文の算術実装はこちらで確認でき、これは ApplyPendingBalance instructionでこちらのように使用されています。

保留中の残高クレジットカウンター

ApplyPendingBalance instructionを呼び出して保留中の残高を利用可能な残高に変換する際:

  1. クライアントは現在の保留中および利用可能な残高を調べ、その合計を暗号化し、token accountの所有者のAESキーを使用して暗号化された decryptable_available_balance を提供します。

  2. 予想される保留中のクレジットカウンターと実際の保留中のクレジットカウンターは、ApplyPendingBalance instructionが作成されてから処理されるまでの間のカウンター値の変化を追跡します:

    • expected_pending_balance_credit_counter:クライアントがApplyPendingBalance instructionを作成する時点でのpending_balance_credit_counterの値
    • actual_pending_balance_credit_counterApplyPendingBalance instructionが処理される時点でのトークンアカウント上のpending_balance_credit_counterの値

予想カウンターと実際のカウンターが一致している場合、decryptable_available_balanceavailable_balanceと一致していることを示します。

トークンアカウントの状態を取得してdecryptable_available_balanceを読み取る際、予想カウンターと実際のカウンターの値が異なる場合、クライアントは正確な残高を計算するために、カウンターの差分に一致する最近の入金/送金instructionsを検索する必要があります。

残高照合プロセス

予想される保留中の残高カウンターと実際のカウンターが異なる場合、decryptable_available_balanceを照合するには次の手順に従います:

  1. トークンアカウントからdecryptable_available_balanceを取得する
  2. カウンターの差分(実際 - 予想)までの入金および送金instructionsを含む最新のトランザクションを取得する:
    • 入金instructionsからの公開金額を追加する
    • 送金instructionsからの宛先暗号文金額を復号化して追加する

必要なInstructions

Confidential Transfer拡張機能を持つトークンアカウントを作成するには、3つのinstructionsが必要です:

  1. トークンアカウントの作成:Associated Token ProgramのAssociatedTokenAccountInstruction:Create instructionを呼び出してトークンアカウントを作成します。

  2. アカウントスペースの再割り当て:Token Extensions ProgramのTokenInstruction::Reallocate instructionを呼び出して、*rsConfidentialTransferAccount*状態のためのスペースを追加します。

  3. 機密転送の設定:Token Extensions ProgramのConfidentialTransferInstruction::ConfigureAccount instructionを呼び出して、*rsConfidentialTransferAccount*状態を初期化します。

トークンアカウントの所有者のみが機密転送用のトークンアカウントを設定できます

ConfigureAccount instructionは、トークンアカウントの所有者のみが生成できる暗号化キーと証明データのクライアント側での生成を必要とします。

PubkeyValidityProofData はElGamalキーが有効であることを検証する証明を作成します。実装の詳細については、以下を参照してください:

コード例

以下のコードは、機密転送拡張機能を持つAssociated Token Accountを作成する方法を示しています。

この例を実行するには、以下のコマンドを使用してメインネットからクローンしたToken Extension Programでローカルvalidatorを起動します。ローカルvalidatorを起動するにはSolana CLIがインストールされている必要があります。

Terminal
$
solana-test-validator --clone-upgradeable-program TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb --url https://api.mainnet-beta.solana.com -r

執筆時点では、機密転送はデフォルトのローカルvalidatorで有効になっていません。サンプルコードを実行するには、メインネットのToken Extension 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 validator
let 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 keypair
let payer = Arc::new(load_keypair()?);
println!("Using payer: {}", payer.pubkey());
// Generate a new keypair to use as the address of the token mint
let mint = Keypair::new();
println!("Mint keypair generated: {}", mint.pubkey());
// Set up program client for Token client
let program_client = ProgramRpcClient::new(rpc_client.clone(), ProgramRpcClientSendTransaction);
// Number of decimals for the mint
let decimals = 9;
// Create a token client for the Token-2022 program
// This provides high-level methods for token operations
let 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 mint
Some(decimals), // Number of decimal places
payer.clone(), // Fee payer for transactions (cloning Arc, not keypair)
);
// Create extension initialization parameters for the mint
// The ConfidentialTransferMint extension enables confidential (private) transfers of tokens
let extension_initialization_params =
vec![ExtensionInitializationParams::ConfidentialTransferMint {
authority: Some(payer.pubkey()), // Authority that can modify confidential transfer settings
auto_approve_new_accounts: true, // Automatically approve new confidential accounts
auditor_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 mint
let transaction_signature = token
.create_mint(
&payer.pubkey(), // Mint authority - can mint new tokens
Some(&payer.pubkey()), // Freeze authority - can freeze token accounts
extension_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 owner
let 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 account
let 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 extension
let 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 account
let 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 executed
let maximum_pending_balance_credit_counter = 65536;
// Initial token balance is 0
let decryptable_balance = aes_key.encrypt(0);
// Generate the proof data client-side
let proof_data = PubkeyValidityProofData::new(&elgamal_keypair)
.map_err(|_| anyhow::anyhow!("Failed to generate proof data"))?;
// Indicate that proof is included in the same transaction
let proof_location =
ProofLocation::InstructionOffset(1.try_into()?, ProofData::InstructionData(&proof_data));
// Step 4: Create instructions to configure the account for confidential transfers
let configure_account_instructions = configure_account(
&token_2022_program_id(), // Program ID
&token_account_pubkey, // Token account
&mint.pubkey(), // Mint
&decryptable_balance.into(), // Initial balance
maximum_pending_balance_credit_counter, // Maximum pending balance credit counter
&payer.pubkey(), // Token Account Owner
&[], // Additional signers
proof_location, // Proof location
)?;
// Combine all instructions
let mut instructions = vec![
create_associated_token_account_instruction,
reallocate_instruction,
];
instructions.extend(configure_account_instructions);
// Create and send the transaction
let 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 tools
fn load_keypair() -> Result<Keypair> {
// Get the default keypair path
let 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 bytes
let 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 keypair
let keypair = Keypair::from_bytes(&keypair_bytes)?;
Ok(keypair)
}

Is this page helpful?

目次

ページを編集