### Bash Build and Run Commands for Solana Example
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
Provides bash commands to build and run the sol-safekey example bot. It includes building the release version of the example with the 'solana-ops' feature and launching it interactively or with a password piped from stdin.
```bash
# Build the example
cargo build --example bot_example --features solana-ops --release
# Launch interactive safekey commands
./build-cache/release/examples/bot_example safekey
# Run bot with password from stdin
echo "your-password" | ./build-cache/release/examples/bot_example
```
--------------------------------
### Rust Solana Operations Example
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
Demonstrates basic Solana operations using the SolanaClient from the sol-safekey library. It includes initializing the client, checking SOL balance, transferring SOL, and wrapping SOL to WSOL. Requires a Solana network endpoint and a Keypair.
```rust
use sol_safekey::solana_ops::SolanaClient;
fn bot_logic(keypair: &solana_sdk::signature::Keypair) -> Result<()> {
// Initialize Solana client
let client = SolanaClient::new("https://api.devnet.solana.com")?;
// Check balance
let balance = client.get_sol_balance(&keypair.pubkey())?;
println!("💰 Balance: {} SOL", balance);
// Transfer SOL
if balance > 0.01 {
let recipient = "RECIPIENT_ADDRESS_HERE".parse()?;
let signature = client.transfer_sol(keypair, &recipient, 0.01)?;
println!("✅ Transfer successful: {}", signature);
}
// Wrap SOL to WSOL
let signature = client.wrap_sol(keypair, 0.1)?;
println!("✅ Wrapped 0.1 SOL: {}", signature);
Ok(())
}
```
--------------------------------
### Build and Run Bot Example with Solana Operations (Bash)
Source: https://github.com/0xfnzero/sol-safekey/blob/main/README.md
This command builds a bot example that utilizes Solana operations and then runs it interactively. It requires the 'solana-ops' feature to be enabled during the build process. The output executable is placed in the 'build-cache/release/examples/' directory.
```bash
# Build the bot
cargo build --example bot_example --features solana-ops --release
# Run interactive safekey commands
./build-cache/release/examples/bot_example safekey
```
--------------------------------
### Create Multiple Wallets
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Demonstrates how to create separate keystore files for different purposes, such as a trading wallet and a holding wallet. It also shows how to unlock and use a specific wallet.
```bash
# Trading wallet
./bot safekey
# Create encrypted → keystore-trading.json
# Holding wallet
./bot safekey
# Create encrypted → keystore-holding.json
# Use specific wallet
./bot safekey
# Unlock → keystore-trading.json
```
--------------------------------
### Accessing Sol-SafeKey Interactive Menu
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Demonstrates how to launch the Sol-SafeKey interactive command-line interface. This can be done either through a bot integration or by directly executing the standalone binary.
```bash
./your-bot safekey
```
```bash
./build-cache/release/examples/bot_example safekey
```
--------------------------------
### Automate Password Input via Stdin
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Automates password input for bot deployment by piping the password to the sol-safekey executable. This should only be used in secure environments, and passwords should never be hardcoded.
```bash
# Create startup script
echo "your-password" | ./your-bot
```
--------------------------------
### Rust Robust Bot Logic with Error Handling
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
Illustrates a more robust approach to Solana bot logic in Rust, incorporating error handling using the `anyhow` crate. It shows how to load wallets securely, initialize clients with retry logic, and handle potential errors during balance queries.
```rust
use anyhow::{Context, Result};
fn robust_bot_logic() -> Result<()> {
// Load wallet with context
let keypair = load_wallet()
.context("Failed to load wallet from keystore.json")?;
// Initialize client with retry logic
let client = SolanaClient::new_with_retry("https://api.mainnet-beta.solana.com")
.context("Failed to connect to Solana network")?;
// Perform operations with error handling
match client.get_sol_balance(&keypair.pubkey()) {
Ok(balance) => println!("Balance: {}", balance),
Err(e) => eprintln!("Failed to get balance: {}", e),
}
Ok(())
}
```
--------------------------------
### Secure Startup Script for Bot with Password Input
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
This bash script securely builds the bot, prompts the user for a wallet password without echoing it, and then pipes the password to the bot's standard input during execution. It also handles clearing the password from memory immediately after use and checks the bot's exit code.
```bash
#!/bin/bash
# Build the bot
echo "🔧 Building bot..."
cargo build --features solana-ops --release
# Get password securely (no echo)
echo -n "🔐 Enter wallet password: "
read -s WALLET_PASSWORD
echo ""
# Start bot with password piped through stdin
echo "$WALLET_PASSWORD" | ./build-cache/release/your-bot > bot.log 2>&1
EXIT_CODE=$?
# Immediately clear password from memory
WALLET_PASSWORD=""
unset WALLET_PASSWORD
# Check execution result
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Bot completed successfully"
else
echo "❌ Bot failed with exit code: $EXIT_CODE"
echo "📝 Check bot.log for details"
fi
```
--------------------------------
### Create Encrypted Keypair (Keystore Output)
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Generates a new Solana keypair, encrypts it using AES-256 with PBKDF2 key derivation, and saves the encrypted key to a keystore JSON file. This is the recommended method for secure key management. A strong password is required.
```bash
🔐 Encrypted Keypair Options:
1. Generate new keypair and encrypt
2. Import existing private key and encrypt
Select [1/2]: 1
🔒 Set encryption password (min 10 characters):
New password: ************
Confirm password: ************
✅ Password accepted!
Output format:
1. Save as Keystore file (recommended)
2. Display encrypted string
Select [1/2]: 1
File path (default: wallet.json): keystore.json
✅ Keystore created successfully!
📍 Public Key: E7Rmd6piasPNs9jqRBUfS8nvNqDx6j5qPDE6Le7us5bp
📁 Location: keystore.json
⚠️ IMPORTANT: Remember your password! It cannot be recovered.
```
--------------------------------
### Create Plain Text Keypair (JSON Output)
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Generates a new, unencrypted Solana keypair and saves it to a JSON file. This method is intended for testing purposes only and is not recommended for production environments due to the plain text storage of private keys.
```bash
📝 Plain Text Keypair Options:
1. Generate new keypair
2. Import existing private key
Select [1/2]: 1
✅ Keypair generated successfully!
📍 Public Key: E7Rmd6piasPNs9jqRBUfS8nvNqDx6j5qPDE6Le7us5bp
Output format:
1. Save as JSON file
2. Display base58 private key
Select [1/2]: 1
File path (default: wallet.json): test-wallet.json
✅ Saved to test-wallet.json
```
--------------------------------
### Interactive Menu: Wallet Management and Solana Operations
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Showcases the interactive CLI menu provided by the sol-safekey library. This menu supports bilingual (English/Chinese) operations for creating, decrypting, and unlocking wallets, as well as performing various Solana operations if the corresponding features are enabled. It's a tool for manual setup and debugging.
```rust
use sol_safekey::interactive;
fn main() {
// Launch interactive menu
// Prompts for language selection, then provides options:
// 1. Create Plain Private Key
// 2. Create Encrypted Private Key
// 3. Decrypt Private Key
// U. Unlock Wallet (for Solana Operations)
// 4-18. Various Solana operations (if features enabled)
if let Err(e) = interactive::show_main_menu() {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
```
--------------------------------
### Airdrop Devnet SOL
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
A command to request SOL from the devnet faucet. This is useful for testing transactions and operations on the Solana devnet without using real SOL.
```bash
solana airdrop 2
--url devnet
```
--------------------------------
### Build Bot with Solana Operations Feature
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
This bash command builds your Solana bot project, enabling the 'solana-ops' feature for Sol-SafeKey's Solana functionalities. It compiles the project in release mode for optimization.
```bash
cargo build --features solana-ops --release
```
--------------------------------
### Add Sol-SafeKey Dependency to Cargo.toml
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
This snippet shows how to add the sol-safekey crate as a dependency in your project's Cargo.toml file. It includes the default 'solana-ops' feature for Solana operations.
```toml
[dependencies]
sol-safekey = { path = "../sol-safekey" }
[features]
default = ["solana-ops"]
solana-ops = ["sol-safekey/solana-ops"]
```
--------------------------------
### Unlock Wallet for Session
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Unlocks an encrypted Solana wallet using its keystore file and password for the current session. Once unlocked, subsequent Solana operations within the same session will not require re-entering the password.
```bash
🔓 Unlock Wallet
Keystore file path [keystore.json]: keystore.json
🔑 Enter wallet password: ************
✅ Wallet unlocked successfully!
📍 Address: E7Rmd6piasPNs9jqRBUfS8nvNqDx6j5qPDE6Le7us5bp
You can now use all Solana operations without re-entering password.
```
--------------------------------
### Load Encrypted Wallet in Rust
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
This Rust function demonstrates how to load an encrypted wallet keypair from a JSON keystore file. It reads the encrypted JSON, takes the password from standard input, and uses Sol-SafeKey's KeyManager to decrypt and return the keypair. It requires 'sol-safekey' and 'solana-sdk' crates.
```rust
use sol_safekey::KeyManager;
use std::io::{self, Read};
fn load_wallet() -> Result {
let wallet_path = "keystore.json";
// Read encrypted keystore
let json = std::fs::read_to_string(wallet_path)?;
// Read password from stdin
let mut password = String::new();
io::stdin().read_to_string(&mut password)?;
let password = password.trim();
// Decrypt and load keypair
let keypair = KeyManager::keypair_from_encrypted_json(&json, password)?;
Ok(keypair)
}
```
--------------------------------
### Create and Save New Encrypted Wallet in Rust
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
This Rust function shows how to generate a new Solana keypair, encrypt it using a provided password, and save it to a 'keystore.json' file. It utilizes Sol-SafeKey's KeyManager for key generation and encryption. The public address of the new wallet is printed to the console.
```rust
use sol_safekey::KeyManager;
fn create_wallet(password: &str) -> Result<()> {
// Generate new keypair
let keypair = KeyManager::generate_keypair();
println!("📍 Wallet Address: {}", keypair.pubkey());
// Encrypt and save
let json = KeyManager::keypair_to_encrypted_json(&keypair, password)?;
std::fs::write("keystore.json", json)?;
println!("✅ Encrypted wallet saved to keystore.json");
Ok(())
}
```
--------------------------------
### Integrate Sol-SafeKey Interactive Menu in Rust
Source: https://github.com/0xfnzero/sol-safekey/blob/main/BOT_INTEGRATION.md
This Rust code snippet demonstrates how to integrate the Sol-SafeKey interactive menu into your bot's main function. It checks for the 'safekey' argument and launches the interactive menu if present, otherwise proceeds with bot logic. This integration requires the 'anyhow' crate for error handling.
```rust
use anyhow::Result;
fn main() -> Result<()> {
// Check if running in safekey interactive mode
let args: Vec = std::env::args().skip(1).collect();
if args.first().map(|s| s.as_str()) == Some("safekey") {
// Launch sol-safekey interactive menu
if let Err(e) = sol_safekey::interactive::show_main_menu() {
eprintln!("❌ {}", e);
std::process::exit(1);
}
return Ok(());
}
// Your bot logic starts here...
println!("🤖 Starting bot...");
Ok(())
}
```
--------------------------------
### Decrypt Encrypted Keypair (Display Only)
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Decrypts an encrypted Solana keypair loaded from a keystore file. The decrypted private key is then displayed directly in the terminal. This operation requires the correct decryption password.
```bash
🔓 Decrypt Encrypted Keypair
Source:
1. Keystore file
2. Encrypted string
Select [1/2]: 1
Keystore file path: keystore.json
🔑 Enter decryption password: ************
✅ Decrypted successfully!
📍 Public Key: E7Rmd6piasPNs9jqRBUfS8nvNqDx6j5qPDE6Le7us5bp
Output:
1. Display only
2. Save as plain JSON
Select [1/2]: 1
Private Key (base58): 5JW8...
```
--------------------------------
### Pump.fun Sell Operation
Source: https://github.com/0xfnzero/sol-safekey/blob/main/USER_GUIDE.md
Sells all tokens on Pump.fun's bonding curve for native SOL. This is for tokens still on Pump.fun and not yet migrated. It requires an unlocked wallet with tokens in an ATA and sufficient SOL for fees. Supports Token-2022 and optional seed-optimized ATAs.
```bash
./your-bot safekey pumpfun-sell --mint
```
--------------------------------
### Rust: Bot Integration for Solana Wallet Management
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Shows the simplified bot integration using the `bot_helper` module in Rust. It demonstrates a single function call to ensure a wallet is ready (creating or unlocking it), checking for wallet file existence, and retrieving a wallet's public key without unlocking.
```rust
use sol_safekey::bot_helper;
use solana_sdk::signer::Signer;
// Single function call handles everything:
// - If wallet exists: prompts for password and unlocks
// - If wallet doesn't exist: launches interactive creation, then unlocks
let keypair = bot_helper::ensure_wallet_ready("wallet.json")
.expect("Failed to setup wallet");
println!("Wallet ready: {}", keypair.pubkey());
// Check if wallet file exists without prompting
let exists = bot_helper::wallet_exists("wallet.json");
// Get public key from wallet without unlocking (reads from JSON)
let pubkey = bot_helper::get_wallet_pubkey("wallet.json")
.expect("Failed to read wallet");
println!("Wallet address: {}", pubkey);
```
--------------------------------
### Sol-SafeKey CLI Commands for Wallet Management
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Provides essential command-line interface commands for building, setting up, generating, unlocking, and performing Solana operations with 2FA-protected wallets. Requires the 'cli' feature.
```bash
# Build CLI with all features
cargo build --release --features full
# Interactive mode (recommended for beginners)
sol-safekey start
# Setup 2FA authentication
sol-safekey setup-2fa
# Generate 2FA-protected wallet
sol-safekey gen-2fa-wallet -o secure-wallet.json
# Unlock 2FA wallet
sol-safekey unlock-2fa-wallet -f secure-wallet.json
# Solana operations with encrypted wallet
sol-safekey sol-ops -f wallet.json balance
sol-safekey sol-ops -f wallet.json transfer -t -a 0.1
# Build bot example
cargo build --example bot_example --features solana-ops --release
./target/release/examples/bot_example safekey
```
--------------------------------
### SolanaClient: Query Balances and Transfer SOL/Tokens
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Demonstrates synchronous Solana RPC operations using SolanaClient. This includes fetching SOL balances, transferring SOL between accounts, and transferring SPL tokens. Requires a Solana RPC endpoint and a loaded KeyManager.
```rust
use sol_safekey::solana_utils::{SolanaClient, lamports_to_sol};
use sol_safekey::KeyManager;
use solana_sdk::pubkey::Pubkey;
use std::str::FromStr;
let rpc_url = "https://api.mainnet-beta.solana.com";
let client = SolanaClient::new(rpc_url.to_string());
// Load wallet
let json = std::fs::read_to_string("wallet.json").unwrap();
let keypair = KeyManager::keypair_from_encrypted_json(&json, "password").unwrap();
// Check SOL balance
let balance_lamports = client.get_sol_balance(&keypair.pubkey())
.expect("Failed to get balance");
let balance_sol = lamports_to_sol(balance_lamports);
println!("Balance: {} SOL", balance_sol);
// Transfer SOL
let recipient = Pubkey::from_str("RecipientAddress111111111111111111111111111").unwrap();
let amount_lamports = 100_000_000; // 0.1 SOL
let signature = client.transfer_sol(&keypair, &recipient, amount_lamports)
.expect("Transfer failed");
println!("Transfer signature: {}", signature);
// Transfer SPL tokens
let token_mint = Pubkey::from_str("TokenMintAddress1111111111111111111111111111").unwrap();
let amount = 1000; // smallest units
let sig = client.transfer_token(&keypair, &recipient, &token_mint, amount)
.expect("Token transfer failed");
println!("Token transfer: {}", sig);
```
--------------------------------
### Keypair Generation, Encryption, and Decryption (Rust)
Source: https://github.com/0xfnzero/sol-safekey/blob/main/README.md
Demonstrates how to generate a new Solana keypair, encrypt it into a JSON format using a password, save it to a file, and then load and decrypt it back into a keypair. This snippet requires the 'sol-safekey' crate.
```rust
use sol_safekey::KeyManager;
// Generate keypair
let keypair = KeyManager::generate_keypair();
// Encrypt and save
let json = KeyManager::keypair_to_encrypted_json(&keypair, "password")?;
std::fs::write("keystore.json", json)?;
// Load and decrypt
let json = std::fs::read_to_string("keystore.json")?;
let keypair = KeyManager::keypair_from_encrypted_json(&json, "password")?;
```
--------------------------------
### SolanaClientSdk: Async WSOL Operations
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Provides asynchronous methods for Wrapped SOL (WSOL) operations using SolanaClientSdk. This includes creating WSOL Associated Token Accounts (ATAs), wrapping SOL to WSOL, and unwrapping WSOL back to SOL, including partial unwraps. Requires a Solana RPC endpoint and a loaded KeyManager.
```rust
use sol_safekey::solana_utils::SolanaClientSdk;
use sol_safekey::KeyManager;
#[tokio::main]
async fn main() {
let rpc_url = "https://api.mainnet-beta.solana.com";
let use_seed_optimize = false; // Use standard ATA for WSOL
let client = SolanaClientSdk::new(rpc_url.to_string(), use_seed_optimize);
// Load wallet
let json = std::fs::read_to_string("wallet.json").unwrap();
let keypair = KeyManager::keypair_from_encrypted_json(&json, "password").unwrap();
// Create WSOL ATA (Associated Token Account)
let sig = client.create_wsol_ata(&keypair).await
.expect("Failed to create WSOL ATA");
println!("WSOL ATA created: {}", sig);
// Check WSOL balance
let wsol_balance = client.get_wsol_balance(&keypair.pubkey())
.unwrap_or(0);
println!("WSOL balance: {} lamports", wsol_balance);
// Wrap SOL to WSOL
let amount = 50_000_000; // 0.05 SOL
let sig = client.wrap_sol(&keypair, amount).await
.expect("Wrap failed");
println!("Wrapped SOL: {}", sig);
// Unwrap all WSOL back to SOL (also closes ATA and reclaims rent)
let sig = client.unwrap_sol(&keypair).await
.expect("Unwrap failed");
println!("Unwrapped WSOL: {}", sig);
// Unwrap partial amount
let partial_amount = 10_000_000; // 0.01 SOL
let sig = client.unwrap_sol_partial(&keypair, partial_amount).await
.expect("Partial unwrap failed");
println!("Partially unwrapped: {}", sig);
}
```
--------------------------------
### Rust: Save and Load Encrypted JSON Keystores
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Illustrates how to use the `KeyManager` in Rust to create an encrypted JSON keystore from a Solana keypair and a password, save it to a file, and later load and decrypt it to restore the keypair. This enables secure persistence of wallet data.
```rust
use sol_safekey::KeyManager;
use std::fs;
// Generate keypair and save to encrypted JSON keystore
let keypair = KeyManager::generate_keypair();
let password = "secure_password_123";
let keystore_json = KeyManager::keypair_to_encrypted_json(&keypair, password)
.expect("Failed to create keystore");
// Save to file
fs::write("wallet.json", &keystore_json)
.expect("Failed to write file");
// Later: Load and decrypt from JSON keystore
let json = fs::read_to_string("wallet.json")
.expect("Failed to read file");
let restored_keypair = KeyManager::keypair_from_encrypted_json(&json, password)
.expect("Failed to decrypt keystore");
println!("Wallet restored: {}", restored_keypair.pubkey());
```
--------------------------------
### Cargo.toml Configuration for Sol-SafeKey Features
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Demonstrates how to configure the sol-safekey dependency in Cargo.toml, including specifying versions and enabling specific features like 'solana-ops' for blockchain operations.
```toml
[dependencies]
sol-safekey = "0.1.2"
# Or specify features explicitly
[dependencies.sol-safekey]
version = "0.1.2"
features = ["solana-ops"] # Enable Solana blockchain operations
# Available features:
# - cli: Command-line interface support
# - 2fa: Two-factor authentication with TOTP
# - solana-ops: Solana blockchain operations (transfers, tokens, etc.)
# - sol-trade-sdk: PumpSwap and Pump.fun DEX integration
# - full: All features enabled
[features]
solana-ops = ["sol-safekey/solana-ops"]
```
--------------------------------
### SolanaClient: Create Nonce Account for Durable Transactions
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Illustrates the creation of a nonce account using SolanaClient, enabling durable transaction signing. This is useful for offline or scheduled transactions that require a recent blockhash but may not be immediately broadcast. Requires a Solana RPC endpoint and a loaded KeyManager with sufficient SOL for rent exemption.
```rust
use sol_safekey::solana_utils::SolanaClient;
use sol_safekey::KeyManager;
let rpc_url = "https://api.devnet.solana.com";
let client = SolanaClient::new(rpc_url.to_string());
// Load wallet (needs ~0.00144 SOL for rent exemption)
let json = std::fs::read_to_string("wallet.json").unwrap();
let keypair = KeyManager::keypair_from_encrypted_json(&json, "password").unwrap();
// Create nonce account
let (nonce_pubkey, signature) = client.create_nonce_account(&keypair)
.expect("Failed to create nonce account");
println!("Nonce account: {}", nonce_pubkey);
println!("Creation signature: {}", signature);
println!("Explorer: https://explorer.solana.com/address/{}", nonce_pubkey);
```
--------------------------------
### Add Sol-SafeKey Dependency to Cargo.toml (TOML)
Source: https://github.com/0xfnzero/sol-safekey/blob/main/README.md
This TOML snippet shows how to add the 'sol-safekey' crate as a dependency in your project's Cargo.toml file. It also demonstrates how to enable specific features, such as 'solana-ops', and how to specify a local path for the dependency.
```toml
[dependencies]
sol-safekey = "0.1.2"
# or from local path: sol-safekey = { path = "path/to/sol-safekey" }
[features]
solana-ops = ["sol-safekey/solana-ops"]
```
--------------------------------
### Rust: Generate, Encrypt, Decrypt Solana Keypairs
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Demonstrates core `KeyManager` operations in Rust: generating a new Solana keypair, encrypting its private key using a password with AES-256 and PBKDF2, and then decrypting it back. It also shows how to derive a public key from a private key string.
```rust
use sol_safekey::KeyManager;
use solana_sdk::signer::Signer;
// Generate a new Solana keypair
let keypair = KeyManager::generate_keypair();
println!("Public key: {}", keypair.pubkey());
// Encrypt private key with password
let private_key = keypair.to_base58_string();
let encrypted = KeyManager::encrypt_with_password(&private_key, "my_strong_password_123")
.expect("Encryption failed");
// Decrypt private key with password
let decrypted = KeyManager::decrypt_with_password(&encrypted, "my_strong_password_123")
.expect("Decryption failed");
assert_eq!(private_key, decrypted);
// Get public key from private key
let pubkey = KeyManager::get_public_key(&private_key)
.expect("Invalid private key");
println!("Derived public key: {}", pubkey);
```
--------------------------------
### Triple-Factor 2FA Encryption and Decryption in Rust
Source: https://context7.com/0xfnzero/sol-safekey/llms.txt
Encrypts and decrypts private keys using a combination of hardware fingerprint, master password, and security question, along with a TOTP code for enhanced security. Requires the '2fa' feature to be enabled.
```rust
use sol_safekey::{
encrypt_with_triple_factor,
decrypt_with_triple_factor_and_2fa,
derive_totp_secret_from_hardware_and_password,
hardware_fingerprint::HardwareFingerprint,
};
// Requires feature: 2fa
// cargo build --features 2fa
// Step 1: Collect hardware fingerprint (device-bound)
let hardware_fp = HardwareFingerprint::collect()
.expect("Failed to collect hardware fingerprint");
// Step 2: Set master password and security answer
let master_password = "MyStrongPassword123!";
let security_answer = "fluffy"; // Answer to security question
let question_index = 0; // Index of selected security question
// Step 3: Derive deterministic 2FA secret
let twofa_secret = derive_totp_secret_from_hardware_and_password(
hardware_fp.as_str(),
master_password,
"wallet",
"Sol-SafeKey"
).expect("Failed to derive 2FA secret");
// Encrypt private key with triple-factor
let private_key = "YourBase58PrivateKey...";
let encrypted = encrypt_with_triple_factor(
private_key,
&twofa_secret,
hardware_fp.as_str(),
master_password,
question_index,
security_answer
).expect("Encryption failed");
// Later: Decrypt with all three factors + 2FA code
let twofa_code = "123456"; // Current TOTP code from authenticator
let (decrypted_key, _, _) = decrypt_with_triple_factor_and_2fa(
&encrypted,
hardware_fp.as_str(),
master_password,
security_answer,
twofa_code
).expect("Decryption failed");
```