Ein Token-Konto erstellen

Wie man ein Token-Konto mit der Confidential Transfer-Erweiterung erstellt

Die Confidential Transfer-Erweiterung ermöglicht private Token-Transfers, indem sie dem Token-Konto zusätzliche Zustände hinzufügt. Dieser Abschnitt erklärt, wie man ein Token- Konto mit aktivierter Erweiterung erstellt.

Das folgende Diagramm zeigt die Schritte zur Erstellung eines Token-Kontos mit der Confidential Transfer-Erweiterung:

Create Token Account with Confidential Transfer Extension

Confidential Transfer Token Account Status

Die Erweiterung fügt dem Token-Konto den ConfidentialTransferAccount Status hinzu:

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

Der ConfidentialTransferAccount enthält mehrere Felder zur Verwaltung vertraulicher Transfers:

  • approved: Der Genehmigungsstatus des Kontos für vertrauliche Transfers. Wenn die auto_approve_new_accountsKonfiguration des mint account auf true gesetzt ist, sind alle token accounts automatisch für vertrauliche Transfers zugelassen.

  • elgamal_pubkey: Der ElGamal-Öffentliche Schlüssel, der zum Verschlüsseln von Guthaben und Transferbeträgen verwendet wird.

  • pending_balance_lo: Die verschlüsselten unteren 16 Bits des ausstehenden Guthabens. Das Guthaben wird für eine effiziente Entschlüsselung in hohe und niedrige Teile aufgeteilt.

  • pending_balance_hi: Die verschlüsselten oberen 48 Bits des ausstehenden Guthabens. Das Guthaben wird für eine effiziente Entschlüsselung in hohe und niedrige Teile aufgeteilt.

  • available_balance: Das verschlüsselte Guthaben, das für Transfers verfügbar ist.

  • decryptable_available_balance: Das verfügbare Guthaben, verschlüsselt mit einem Advanced Encryption Standard (AES)-Schlüssel für eine effiziente Entschlüsselung durch den Kontoinhaber.

  • allow_confidential_credits: Wenn wahr, erlaubt eingehende vertrauliche Transfers.

  • allow_non_confidential_credits: Wenn wahr, erlaubt eingehende nicht-vertrauliche Transfers.

  • pending_balance_credit_counter: Zählt eingehende ausstehende Guthabengutschriften aus Einzahlungs- und Überweisungsanweisungen.

  • maximum_pending_balance_credit_counter: Die Zählgrenze für ausstehende Gutschriften, bevor eine ApplyPendingBalance-Anweisung erforderlich ist, um das ausstehende Guthaben in das verfügbare Guthaben umzuwandeln.

  • expected_pending_balance_credit_counter: Der pending_balance_credit_counterWert, der vom Client über die instruction data das letzte Mal bereitgestellt wurde, als die ApplyPendingBalance-Anweisung verarbeitet wurde.

  • actual_pending_balance_credit_counter: Der pending_balance_credit_counterWert auf dem token account zum Zeitpunkt, als die letzte ApplyPendingBalance-Anweisung verarbeitet wurde.

Ausstehender vs. verfügbarer Kontostand

Vertrauliche Kontostände werden in ausstehende und verfügbare Guthaben aufgeteilt, um DoS-Angriffe zu verhindern. Ohne diese Trennung könnte ein Angreifer wiederholt Token an ein token account senden und damit die Möglichkeit des token account-Besitzers, Token zu übertragen, blockieren. Der token account-Besitzer wäre nicht in der Lage, Token zu übertragen, weil sich der verschlüsselte Kontostand zwischen dem Zeitpunkt der Transaktionsübermittlung und der Verarbeitung ändern würde, was zu einer fehlgeschlagenen Transaktion führen würde.

Alle Einzahlungen und Überweisungsbeträge werden zunächst dem ausstehenden Guthaben hinzugefügt. Token account-Besitzer müssen die ApplyPendingBalance-Anweisung verwenden, um das ausstehende Guthaben in verfügbares Guthaben umzuwandeln. Eingehende Überweisungen oder Einzahlungen haben keinen Einfluss auf das verfügbare Guthaben eines token account.

Aufteilung des ausstehenden Guthabens in Hoch/Niedrig

Das vertrauliche ausstehende Guthaben wird in pending_balance_lo und pending_balance_hi aufgeteilt, da die ElGamal-Entschlüsselung für größere Zahlen mehr Rechenleistung erfordert. Die Implementierung der Chiffretext-Arithmetik findest du hier, die in der ApplyPendingBalance-Anweisung verwendet wird hier.

Zähler für ausstehende Guthabengutschriften

Beim Aufruf der ApplyPendingBalance-Anweisung zur Umwandlung des ausstehenden Guthabens in verfügbares Guthaben:

  1. Der Client schaut die aktuellen ausstehenden und verfügbaren Guthaben nach, verschlüsselt die Summe und stellt einen decryptable_available_balance bereit, der mit dem AES-Schlüssel des token account-Besitzers verschlüsselt ist.

  2. Die erwarteten und tatsächlichen Zähler für ausstehende Gutschriften verfolgen Änderungen am Zählerwert zwischen dem Zeitpunkt, zu dem die ApplyPendingBalance-Anweisung erstellt und verarbeitet wird:

    • expected_pending_balance_credit_counter: Der pending_balance_credit_counterWert, wenn der Client die ApplyPendingBalance-Anweisung erstellt
    • actual_pending_balance_credit_counter: Der pending_balance_credit_counterWert auf dem token account zum Zeitpunkt, zu dem die ApplyPendingBalance-Anweisung verarbeitet wird

Übereinstimmende erwartete/tatsächliche Zähler zeigen an, dass der decryptable_available_balance dem available_balance entspricht.

Wenn der Status eines Token-Accounts abgerufen wird, um den decryptable_available_balance zu lesen, erfordern unterschiedliche Werte für erwartete/tatsächliche Zähler, dass der Client kürzlich erfolgte Einzahlungs-/Überweisungsanweisungen sucht, die der Zählerdifferenz entsprechen, um den korrekten Kontostand zu berechnen.

Prozess zur Kontostandabstimmung

Wenn sich die erwarteten und tatsächlichen Zähler für ausstehende Kontostände unterscheiden, folgen Sie diesen Schritten zur Abstimmung des decryptable_available_balance:

  1. Beginnen Sie mit dem decryptable_available_balance aus dem Token-Account
  2. Rufen Sie die neuesten Transaktionen ab, einschließlich Einzahlungs- und Überweisungsanweisungen bis zur Zählerdifferenz (tatsächlich - erwartet):
    • Addieren Sie öffentliche Beträge aus Einzahlungsanweisungen
    • Entschlüsseln und addieren Sie Zieltext-Beträge aus Überweisungsanweisungen

Erforderliche Anweisungen

Das Erstellen eines Token-Accounts mit der Confidential Transfer-Erweiterung erfordert drei Anweisungen:

  1. Erstellen des Token-Accounts: Rufen Sie die AssociatedTokenAccountInstruction:Create-Anweisung des Associated Token Program auf, um den Token-Account zu erstellen.

  2. Neu-Allokieren des Account-Speicherplatzes: Rufen Sie die TokenInstruction::Reallocate-Anweisung des Token Extension Program auf, um Platz für den ConfidentialTransferAccount-Status hinzuzufügen.

  3. Konfigurieren von vertraulichen Überweisungen: Rufen Sie die ConfidentialTransferInstruction::ConfigureAccount Anweisung auf, um den ConfidentialTransferAccount-Status zu initialisieren.

Nur der Besitzer des Token-Accounts kann einen Token-Account für vertrauliche Überweisungen konfigurieren.

Die ConfigureAccount-Anweisung erfordert die clientseitige Generierung von Verschlüsselungsschlüsseln und Nachweisdaten, die nur vom Besitzer des Token-Accounts generiert werden können.

Der PubkeyValidityProofData erstellt einen Nachweis, der verifiziert, dass ein ElGamal-Schlüssel gültig ist. Für Implementierungsdetails siehe:

Beispielcode

Der folgende Code zeigt, wie man einen Associated Token Account mit der Confidential Transfer-Erweiterung erstellt.

Um das Beispiel auszuführen, starten Sie einen lokalen Validator mit dem Token Extension Program, das von Mainnet geklont wurde, mit dem folgenden Befehl. Sie müssen die Solana CLI installiert haben, um den lokalen Validator zu starten.

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

Zum Zeitpunkt der Erstellung sind die vertraulichen Überweisungen auf dem Standard-Local-validator nicht aktiviert. Sie müssen das Token Extensions Program des Mainnets klonen, um den Beispielcode auszuführen.

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?

Inhaltsverzeichnis

Seite bearbeiten