Tạo một Token Account

Cách tạo token account với tiện ích mở rộng Confidential Transfer

Tiện ích mở rộng Confidential Transfer cho phép chuyển token riêng tư bằng cách bổ sung trạng thái bổ sung vào token account. Phần này giải thích cách tạo một token account với tiện ích mở rộng này được kích hoạt.

Sơ đồ sau đây cho thấy các bước liên quan đến việc tạo token account với tiện ích mở rộng Confidential Transfer:

Create Token Account with Confidential Transfer Extension

Trạng thái Confidential Transfer Token Account

Tiện ích mở rộng này bổ sung trạng thái ConfidentialTransferAccount vào token account:

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,
}

ConfidentialTransferAccount chứa một số trường để quản lý các giao dịch chuyển token bảo mật:

  • approved: Trạng thái phê duyệt của tài khoản cho các giao dịch chuyển bảo mật. Nếu cấu hình auto_approve_new_accounts của mint account được đặt là true, tất cả token account sẽ tự động được phê duyệt cho các giao dịch chuyển bảo mật.

  • elgamal_pubkey: Khóa công khai ElGamal được sử dụng để mã hóa số dư và số lượng chuyển.

  • pending_balance_lo: 16 bit thấp đã được mã hóa của số dư đang chờ xử lý. Số dư được chia thành phần cao và thấp để giải mã hiệu quả.

  • pending_balance_hi: 48 bit cao đã được mã hóa của số dư đang chờ xử lý. Số dư được chia thành phần cao và thấp để giải mã hiệu quả.

  • available_balance: Số dư đã mã hóa có sẵn cho các giao dịch chuyển.

  • decryptable_available_balance: Số dư khả dụng được mã hóa bằng khóa Advanced Encryption Standard (AES) để chủ tài khoản giải mã hiệu quả.

  • allow_confidential_credits: Nếu là true, cho phép các giao dịch chuyển bảo mật đến.

  • allow_non_confidential_credits: Nếu là true, cho phép các giao dịch chuyển không bảo mật đến.

  • pending_balance_credit_counter: Đếm số lần ghi có vào số dư đang chờ xử lý từ các lệnh gửi tiền và chuyển tiền.

  • maximum_pending_balance_credit_counter: Giới hạn số lượng ghi có đang chờ xử lý trước khi yêu cầu lệnh ApplyPendingBalance để chuyển đổi số dư đang chờ xử lý thành số dư khả dụng.

  • expected_pending_balance_credit_counter: Giá trị pending_balance_credit_counter được cung cấp bởi client thông qua instruction data lần cuối cùng khi lệnh ApplyPendingBalance được xử lý.

  • actual_pending_balance_credit_counter: Giá trị pending_balance_credit_counter trên token account tại thời điểm lệnh ApplyPendingBalance cuối cùng được xử lý.

Số dư đang chờ xử lý và số dư khả dụng

Số dư bảo mật được phân tách thành số dư đang chờ xử lý và số dư khả dụng để ngăn chặn các cuộc tấn công DoS. Nếu không có sự phân tách này, kẻ tấn công có thể liên tục gửi token đến một token account, chặn khả năng chuyển token của chủ token account. Chủ token account sẽ không thể chuyển token vì số dư được mã hóa sẽ thay đổi giữa thời điểm giao dịch được gửi và khi nó được xử lý, dẫn đến giao dịch thất bại.

Tất cả các khoản tiền gửi và chuyển khoản ban đầu đều được thêm vào số dư đang chờ xử lý. Chủ token account phải sử dụng lệnh ApplyPendingBalance để chuyển đổi số dư đang chờ xử lý thành số dư khả dụng. Các giao dịch chuyển khoản hoặc tiền gửi đến không ảnh hưởng đến số dư khả dụng của token account.

Phân chia số dư đang chờ xử lý thành cao/thấp

Số dư đang chờ xử lý bảo mật được chia thành pending_balance_lopending_balance_hi vì giải mã ElGamal đòi hỏi nhiều tính toán hơn cho các số lớn. Bạn có thể tìm thấy cách triển khai phép tính mã hóa tại đây, được sử dụng trong lệnh ApplyPendingBalance tại đây.

Bộ đếm tín dụng số dư đang chờ xử lý

Khi gọi lệnh ApplyPendingBalance để chuyển đổi số dư đang chờ xử lý thành số dư khả dụng:

  1. Client tra cứu số dư đang chờ xử lý và số dư khả dụng hiện tại, mã hóa tổng, và cung cấp một decryptable_available_balance được mã hóa bằng khóa AES của chủ token account.

  2. Bộ đếm tín dụng đang chờ xử lý dự kiến và thực tế theo dõi các thay đổi đối với giá trị bộ đếm giữa thời điểm lệnh ApplyPendingBalance được tạo và xử lý:

    • expected_pending_balance_credit_counter: Giá trị pending_balance_credit_counter khi client tạo lệnh ApplyPendingBalance
    • actual_pending_balance_credit_counter: Giá trị pending_balance_credit_counter trên token account tại thời điểm lệnh ApplyPendingBalance được xử lý

Các bộ đếm dự kiến/thực tế khớp nhau cho biết decryptable_available_balance khớp với available_balance.

Khi lấy trạng thái của token account để đọc decryptable_available_balance, các giá trị bộ đếm dự kiến/thực tế khác nhau yêu cầu client phải tra cứu các lệnh gửi/chuyển gần đây khớp với sự chênh lệch bộ đếm để tính toán số dư chính xác.

Quy trình đối chiếu số dư

Khi bộ đếm số dư đang chờ xử lý dự kiến và thực tế khác nhau, hãy làm theo các bước sau để đối chiếu decryptable_available_balance:

  1. Bắt đầu với decryptable_available_balance từ token account
  2. Lấy các giao dịch gần đây nhất bao gồm các lệnh gửi và chuyển tối đa bằng sự chênh lệch bộ đếm (thực tế - dự kiến):
    • Thêm số lượng công khai từ các lệnh gửi
    • Giải mã và thêm số lượng mã hóa đích từ các lệnh chuyển

Các lệnh bắt buộc

Việc tạo token account với phần mở rộng Confidential Transfer yêu cầu ba lệnh:

  1. Tạo Token Account: Gọi lệnh AssociatedTokenAccountInstruction:Create của Associated Token Program để tạo token account.

  2. Phân bổ lại không gian tài khoản: Gọi lệnh TokenInstruction::Reallocate của Token Extension Program để thêm không gian cho trạng thái ConfidentialTransferAccount.

  3. Cấu hình Confidential Transfers: Gọi lệnh ConfidentialTransferInstruction::ConfigureAccount của Token Extension Program để khởi tạo trạng thái ConfidentialTransferAccount.

Chỉ chủ sở hữu token account mới có thể cấu hình token account cho confidential transfers.

Lệnh ConfigureAccount yêu cầu tạo khóa mã hóa và dữ liệu chứng minh ở phía client mà chỉ có thể được tạo bởi chủ sở hữu token account.

Lệnh PubkeyValidityProofData tạo một bằng chứng xác minh rằng khóa ElGamal hợp lệ. Để biết chi tiết triển khai, xem:

Mã ví dụ

Đoạn mã sau đây minh họa cách tạo Associated Token Account với phần mở rộng Confidential Transfer,

Để chạy ví dụ, hãy khởi động validator cục bộ với Token Extension Program được sao chép từ mainnet bằng lệnh sau. Bạn phải cài đặt Solana CLI để khởi động validator cục bộ.

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

Tại thời điểm viết bài, Confidential Transfers chưa được kích hoạt trên validator cục bộ mặc định. Bạn phải sao chép Token Extension Program từ mainnet để chạy mã ví dụ.

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?

Mục lục

Chỉnh sửa trang