Chapter 5: Cryptocurrency Wallets and Security
Haiyue
16min
Chapter 5: Cryptocurrency Wallets and Security
Learning Objectives
- Understand wallet working principles
- Master the differences between hot wallets and cold wallets
- Learn private key, public key, and mnemonic phrase management
- Understand common security threats and protective measures
Basic Wallet Principles
Key Pair Generation and Management
Cryptocurrency wallets are essentially tools for managing key pairs and addresses:
import hashlib
import secrets
import hmac
from typing import List, Tuple, Dict
from dataclasses import dataclass
@dataclass
class KeyPair:
"""Key pair"""
private_key: str
public_key: str
address: str
class CryptographicWallet:
"""Cryptocurrency wallet"""
def __init__(self, entropy_bits: int = 128):
"""
Initialize wallet
entropy_bits: Entropy bits (128, 256, etc.)
"""
self.entropy_bits = entropy_bits
self.master_seed = None
self.mnemonic = None
self.accounts: Dict[str, KeyPair] = {}
def generate_mnemonic(self, language: str = "english") -> List[str]:
"""Generate mnemonic phrase"""
# Generate random entropy
entropy = secrets.randbits(self.entropy_bits)
entropy_bytes = entropy.to_bytes(self.entropy_bits // 8, 'big')
# Calculate checksum
checksum_bits = self.entropy_bits // 32
hash_bytes = hashlib.sha256(entropy_bytes).digest()
checksum = int.from_bytes(hash_bytes, 'big') >> (256 - checksum_bits)
# Combine entropy and checksum
total_bits = self.entropy_bits + checksum_bits
combined = (entropy << checksum_bits) | checksum
# Convert to mnemonic words (simplified implementation)
word_count = total_bits // 11
mnemonic_words = []
# Simplified BIP39 word list
bip39_words = [
"abandon", "ability", "able", "about", "above", "absent", "absorb",
"abstract", "absurd", "abuse", "access", "accident", "account",
"accuse", "achieve", "acid", "acoustic", "acquire", "across", "act",
"action", "actor", "actress", "actual", "adapt", "add", "addict"
] * 80
for i in range(word_count):
word_index = (combined >> (total_bits - (i + 1) * 11)) & 0x7FF
word_index = word_index % len(bip39_words)
mnemonic_words.append(bip39_words[word_index])
self.mnemonic = mnemonic_words
return mnemonic_words
def create_seed_from_mnemonic(self, mnemonic: List[str],
passphrase: str = "") -> bytes:
"""Generate seed from mnemonic phrase"""
mnemonic_str = " ".join(mnemonic)
salt = "mnemonic" + passphrase
# Use PBKDF2 to generate 512-bit seed
seed = hashlib.pbkdf2_hmac(
'sha512',
mnemonic_str.encode('utf-8'),
salt.encode('utf-8'),
2048, # Iteration count
64 # Output length (512 bits)
)
self.master_seed = seed
return seed
def derive_key_pair(self, derivation_path: str = "m/44'/0'/0'/0/0") -> KeyPair:
"""Generate key pair based on derivation path (simplified)"""
if not self.master_seed:
raise ValueError("Must generate seed first")
# Simplified key derivation
path_hash = hashlib.sha256(
(derivation_path + str(len(self.accounts))).encode()
).digest()
# Generate private key
private_key_bytes = hmac.new(
self.master_seed,
path_hash,
hashlib.sha256
).digest()
private_key = private_key_bytes.hex()
# Generate public key (simplified: use private key hash)
public_key = hashlib.sha256(private_key_bytes).hexdigest()
# Generate address (simplified: use RIPEMD160 of public key)
address_bytes = hashlib.new(
'ripemd160',
bytes.fromhex(public_key)
).digest()
address = "1" + address_bytes.hex()
key_pair = KeyPair(private_key, public_key, address)
self.accounts[address] = key_pair
return key_pair
# Wallet demonstration
print("=== Cryptocurrency Wallet Demo ===")
# Create new wallet
wallet = CryptographicWallet(entropy_bits=128)
# Generate mnemonic phrase
mnemonic = wallet.generate_mnemonic()
print(f"Mnemonic phrase: {' '.join(mnemonic)}")
# Generate seed
seed = wallet.create_seed_from_mnemonic(mnemonic)
print(f"Seed (hex): {seed.hex()[:32]}...")
# Derive key pairs
key_pair1 = wallet.derive_key_pair("m/44'/0'/0'/0/0")
key_pair2 = wallet.derive_key_pair("m/44'/0'/0'/0/1")
print(f"\nAccount 1:")
print(f" Address: {key_pair1.address}")
print(f" Public key: {key_pair1.public_key[:16]}...")
print(f" Private key: {key_pair1.private_key[:16]}...")
Wallet Type Classification
Hot Wallets vs Cold Wallets
from enum import Enum
import time
from abc import ABC, abstractmethod
class WalletType(Enum):
"""Wallet types"""
HOT = "hot_wallet" # Hot wallet
COLD = "cold_wallet" # Cold wallet
HARDWARE = "hardware_wallet" # Hardware wallet
PAPER = "paper_wallet" # Paper wallet
class BaseWallet(ABC):
"""Wallet base class"""
def __init__(self, wallet_type: WalletType):
self.wallet_type = wallet_type
self.created_at = time.time()
self.last_backup = None
@abstractmethod
def create_transaction(self, to_address: str, amount: float) -> Dict:
pass
@abstractmethod
def sign_transaction(self, transaction: Dict) -> str:
pass
@abstractmethod
def get_security_level(self) -> int:
pass
class HotWallet(BaseWallet):
"""Hot wallet (online)"""
def __init__(self):
super().__init__(WalletType.HOT)
self.is_online = True
self.auto_sync = True
self.convenience_features = ["Quick transactions", "Real-time prices", "DApp connection"]
def create_transaction(self, to_address: str, amount: float) -> Dict:
"""Create transaction (hot wallet)"""
transaction = {
"from": "hot_wallet_address",
"to": to_address,
"amount": amount,
"timestamp": time.time(),
"gas_price": self._get_current_gas_price(),
"nonce": self._get_account_nonce()
}
print(f"Hot wallet transaction created: {amount} -> {to_address}")
print(f"Current gas price: {transaction['gas_price']} Gwei")
return transaction
def get_security_level(self) -> int:
"""Security level (1-10)"""
return 6 # Medium security
class ColdWallet(BaseWallet):
"""Cold wallet (offline)"""
def __init__(self):
super().__init__(WalletType.COLD)
self.is_online = False
self.air_gapped = True # Physically isolated
self.security_features = ["Offline storage", "Multisig", "Backup mechanism"]
def create_transaction(self, to_address: str, amount: float) -> Dict:
"""Create transaction (cold wallet)"""
transaction = {
"from": "cold_wallet_address",
"to": to_address,
"amount": amount,
"timestamp": time.time(),
"gas_price": self._get_manual_gas_price(),
"nonce": self._get_manual_nonce()
}
print(f"Cold wallet transaction created: {amount} -> {to_address}")
print("Warning: Network parameters must be set manually")
return transaction
def get_security_level(self) -> int:
"""Security level (1-10)"""
return 10 # Highest security
class HardwareWallet(BaseWallet):
"""Hardware wallet"""
def __init__(self, device_model: str):
super().__init__(WalletType.HARDWARE)
self.device_model = device_model
self.firmware_version = "1.0.0"
self.is_connected = False
self.pin_required = True
def connect_device(self, pin: str) -> bool:
"""Connect hardware device"""
if self._verify_pin(pin):
self.is_connected = True
print(f"Success: {self.device_model} connected")
return True
else:
print("Error: Incorrect PIN")
return False
def get_security_level(self) -> int:
"""Security level"""
return 9 # High security
Mnemonic Phrase and Seed Management
BIP39 Mnemonic Standard
import secrets
import hashlib
from typing import List, Optional
class BIP39:
"""BIP39 mnemonic standard implementation"""
# Simplified BIP39 word list (actual standard contains 2048 words)
WORDLIST = [
"abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract",
"absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid",
# ... should contain 2048 words
] * 64 # Extend to 2048
@classmethod
def generate_mnemonic(cls, strength: int = 128) -> List[str]:
"""
Generate mnemonic phrase
strength: Entropy strength (128, 160, 192, 224, 256)
"""
if strength not in [128, 160, 192, 224, 256]:
raise ValueError("Strength must be 128, 160, 192, 224, or 256")
# Generate random entropy
entropy_bytes = secrets.randbits(strength).to_bytes(strength // 8, 'big')
# Calculate checksum
checksum_length = strength // 32
hash_bytes = hashlib.sha256(entropy_bytes).digest()
checksum = int.from_bytes(hash_bytes, 'big') >> (256 - checksum_length)
# Combine entropy and checksum
entropy_with_checksum = (int.from_bytes(entropy_bytes, 'big') << checksum_length) | checksum
total_bits = strength + checksum_length
# Convert to mnemonic words
mnemonic_length = total_bits // 11
mnemonic = []
for i in range(mnemonic_length):
word_index = (entropy_with_checksum >> (total_bits - (i + 1) * 11)) & 0x7FF
word_index = word_index % len(cls.WORDLIST)
mnemonic.append(cls.WORDLIST[word_index])
return mnemonic
@classmethod
def mnemonic_to_seed(cls, mnemonic: List[str], passphrase: str = "") -> bytes:
"""Convert mnemonic phrase to seed"""
mnemonic_str = " ".join(mnemonic)
salt = "mnemonic" + passphrase
# Use PBKDF2-HMAC-SHA512
seed = hashlib.pbkdf2_hmac(
'sha512',
mnemonic_str.encode('utf-8'),
salt.encode('utf-8'),
2048, # Iteration count
64 # Output length (512 bits)
)
return seed
Common Security Threats and Protections
Security Threat Classification
from enum import Enum
from typing import Dict, List
import re
class ThreatLevel(Enum):
"""Threat level"""
LOW = 1
MEDIUM = 2
HIGH = 3
CRITICAL = 4
class ThreatType(Enum):
"""Threat types"""
PHISHING = "Phishing attacks"
MALWARE = "Malware"
SOCIAL_ENGINEERING = "Social engineering"
MAN_IN_THE_MIDDLE = "Man-in-the-middle attacks"
CLIPBOARD_HIJACKING = "Clipboard hijacking"
FAKE_WALLET = "Fake wallets"
PRIVATE_KEY_EXPOSURE = "Private key exposure"
WEAK_PASSWORD = "Weak passwords"
@dataclass
class SecurityThreat:
"""Security threat"""
threat_type: ThreatType
level: ThreatLevel
description: str
attack_vectors: List[str]
prevention_measures: List[str]
class SecurityAnalyzer:
"""Security analyzer"""
def analyze_url_safety(self, url: str) -> Dict:
"""Analyze URL security"""
risk_score = 0
warnings = []
# Check for suspicious domain
if not url.startswith("https://"):
risk_score += 20
warnings.append("Not using HTTPS encryption")
# Check for phishing patterns
phishing_patterns = [
"bin4nce", "coinb4se", "block-chain",
"meta-mask", "my-ether-wallet"
]
for pattern in phishing_patterns:
if pattern in url.lower():
risk_score += 50
warnings.append(f"Phishing pattern detected: {pattern}")
# Assess risk level
if risk_score >= 50:
risk_level = ThreatLevel.CRITICAL
elif risk_score >= 30:
risk_level = ThreatLevel.HIGH
elif risk_score >= 15:
risk_level = ThreatLevel.MEDIUM
else:
risk_level = ThreatLevel.LOW
return {
"url": url,
"risk_score": risk_score,
"risk_level": risk_level,
"warnings": warnings,
"safe": risk_score < 15
}
def check_password_strength(self, password: str) -> Dict:
"""Check password strength"""
score = 0
recommendations = []
# Length check
if len(password) >= 12:
score += 25
elif len(password) >= 8:
score += 15
else:
recommendations.append("Password should be at least 8 characters, 12+ recommended")
# Character complexity
if re.search(r"[a-z]", password):
score += 10
else:
recommendations.append("Include lowercase letters")
if re.search(r"[A-Z]", password):
score += 10
else:
recommendations.append("Include uppercase letters")
if re.search(r"[0-9]", password):
score += 10
else:
recommendations.append("Include numbers")
if re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
score += 15
else:
recommendations.append("Include special characters")
# Rating
if score >= 70:
strength = "Strong"
elif score >= 50:
strength = "Medium"
elif score >= 30:
strength = "Weak"
else:
strength = "Very weak"
return {
"score": max(0, score),
"strength": strength,
"recommendations": recommendations
}
Chapter Summary
This chapter comprehensively covers cryptocurrency wallet and security management:
-
Wallet Principles:
- Key pair generation and management
- Mnemonic phrase and seed mechanism
- Address derivation algorithm
-
Wallet Types:
- Hot wallets: Convenient but higher risk
- Cold wallets: Secure but less convenient
- Hardware wallets: Balance security and convenience
-
Mnemonic Management:
- BIP39 standard implementation
- Secure storage and recovery
- Passphrase protection
-
Security Threat Protection:
- Phishing attack recognition
- Malware protection
- Password security management
- Address verification mechanism
-
Best Practices:
- Multiple backup strategy
- Security checklist
- Tiered storage solution
- Regular security audits
Understanding and mastering these security concepts is crucial for the safe use of cryptocurrency. In the next chapter, we will learn the fundamentals of cryptocurrency trading.