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

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アカウントのauto_approve_new_accounts設定がtrueに設定されている場合、すべてのtoken accountは自動的に機密送金が承認されます。

  • 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: 入金と送金指示からの保留中の残高クレジットをカウントします。

  • maximum_pending_balance_credit_counter: 保留中の残高を利用可能な残高に変換するための*rsApplyPendingBalance*命令を必要とする前の、保留クレジットの制限数。

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

  • actual_pending_balance_credit_counter: 最後の ApplyPendingBalance 命令が処理された時点でのトークンアカウント上の pending_balance_credit_counter の値。

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

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

すべての入金と転送額は最初に保留残高に追加されます。トークンアカウント所有者は ApplyPendingBalance 命令を使用して、保留残高を利用可能残高に変換する必要があります。入金や転送はトークンアカウントの利用可能残高に影響しません。

保留残高のHigh/Low分割

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

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

ApplyPendingBalance 命令を呼び出して保留残高を利用可能残高に変換する際:

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

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

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

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

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

残高照合プロセス

期待値と実際の保留中残高カウンターが異なる場合、以下の手順に従って decryptable_available_balanceを照合します:

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

必要な指示

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

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

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

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

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

*rsConfigureAccount*指示には、トークンアカウント所有者のみが生成できる暗号化キーと証明データのクライアント側での生成が必要です。

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

サンプルコード

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

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

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

執筆時点では、機密転送はデフォルトのローカルvalidatorで有効になっていません。サンプルコードを実行するには、メインネットの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 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)
}
Click to execute the code.

Is this page helpful?

目次

ページを編集