Chapter 4: Introduction to Mainstream Cryptocurrencies
Chapter 4: Introduction to Mainstream Cryptocurrencies
- Understand Ethereum and smart contracts
- Recognize other mainstream coins (Ripple, Litecoin, etc.)
- Understand the characteristics and use cases of different cryptocurrencies
- Master the differences between tokens and native coins
Ethereum
Basic Concepts and Features
Ethereum is a decentralized platform created by Vitalik Buterin in 2015 that supports smart contracts and decentralized applications (DApps).
- Turing Complete: Supports complex programming logic
- Smart Contracts: Self-executing code contracts
- Virtual Machine: Ethereum Virtual Machine (EVM) execution environment
- Gas Mechanism: Computational resource pricing system
- Account Model: Different state management from Bitcoin’s UTXO model
Smart Contract Implementation
import json
import hashlib
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
@dataclass
class Account:
"""Ethereum account"""
address: str
balance: float = 0.0
nonce: int = 0
code: str = "" # Contract code
storage: Dict[str, Any] = field(default_factory=dict) # Contract storage
class EthereumVirtualMachine:
"""Ethereum Virtual Machine (simplified)"""
def __init__(self):
self.accounts: Dict[str, Account] = {}
self.gas_price = 20 # Gwei
self.block_gas_limit = 30_000_000
def create_account(self, address: str, initial_balance: float = 0.0):
"""Create account"""
self.accounts[address] = Account(address, initial_balance)
def deploy_contract(self, deployer: str, contract_code: str,
constructor_args: List = None, gas_limit: int = 500_000):
"""Deploy smart contract"""
if deployer not in self.accounts:
raise ValueError("Deployer account does not exist")
# Generate contract address
deployer_account = self.accounts[deployer]
contract_address = self._generate_contract_address(deployer, deployer_account.nonce)
# Create contract account
contract_account = Account(
address=contract_address,
balance=0.0,
code=contract_code
)
# Execute constructor
if constructor_args:
gas_used = self._execute_constructor(contract_account, constructor_args)
else:
gas_used = 21000 # Base gas cost
# Calculate gas fee
gas_fee = (gas_used * self.gas_price) / 1e9 # Convert to ETH
if self.accounts[deployer].balance < gas_fee:
raise ValueError("Insufficient balance to pay gas fee")
# Deduct gas fee
self.accounts[deployer].balance -= gas_fee
self.accounts[deployer].nonce += 1
# Save contract
self.accounts[contract_address] = contract_account
print(f"Contract deployed successfully")
print(f"Contract address: {contract_address}")
print(f"Gas used: {gas_used:,}")
print(f"Gas fee: {gas_fee:.6f} ETH")
return contract_address
# (Smart contract demo code continues...)
Other Mainstream Cryptocurrencies
Ripple (XRP)
Ripple focuses on cross-border payment solutions:
import time
from typing import List
from dataclasses import dataclass
@dataclass
class RippleTransaction:
"""Ripple transaction"""
sender: str
receiver: str
amount: float
currency: str = "XRP"
timestamp: float = None
sequence: int = 0
fee: float = 0.00001 # Extremely low transaction fee
def __post_init__(self):
if self.timestamp is None:
self.timestamp = time.time()
class RippleLedger:
"""Ripple ledger"""
def __init__(self):
self.accounts: Dict[str, Dict] = {}
self.transaction_history: List[RippleTransaction] = []
self.validators = [
"ripple_validator_1",
"ripple_validator_2",
"ripple_validator_3"
]
def create_account(self, address: str, initial_balance: float = 0.0):
"""Create account (requires 20 XRP activation)"""
if initial_balance < 20:
raise ValueError("Ripple account requires at least 20 XRP activation")
self.accounts[address] = {
"balance": initial_balance,
"sequence": 0,
"trust_lines": {}, # Trust lines (for other currencies)
"reserve": 20 # Account reserve
}
# (Ripple payment demo code continues...)
Litecoin
Litecoin is an improved version of Bitcoin, known as “digital silver”:
class LitecoinBlock:
"""Litecoin block"""
def __init__(self, previous_hash: str, transactions: List[Dict]):
self.previous_hash = previous_hash
self.transactions = transactions
self.timestamp = time.time()
self.nonce = 0
self.target_time = 150 # 2.5-minute target block time
self.block_reward = 12.5 # Current block reward
def mine_with_scrypt(self, difficulty: int) -> bool:
"""Mining with Scrypt algorithm (simulated)"""
target = "0" * difficulty
start_time = time.time()
print(f"Starting Litecoin mining (Scrypt algorithm)...")
for nonce in range(100000): # Limit attempts
# Simulate Scrypt hash calculation
candidate_data = f"{self.previous_hash}{self.timestamp}{nonce}"
hash_result = hashlib.sha256(candidate_data.encode()).hexdigest()
if hash_result.startswith(target):
end_time = time.time()
print(f"Litecoin mining successful!")
print(f"Nonce: {nonce}")
print(f"Hash: {hash_result}")
print(f"Time elapsed: {end_time - start_time:.2f} seconds")
return True
print("Litecoin mining demo completed")
return False
Binance Coin (BNB)
Binance Coin is a platform token issued by Binance exchange:
class BNBToken:
"""Binance Coin smart contract (simplified)"""
def __init__(self):
self.name = "Binance Coin"
self.symbol = "BNB"
self.decimals = 18
self.total_supply = 200_000_000 # 200 million total supply
self.balances = {}
self.burn_events = [] # Burn records
def burn_tokens(self, amount: float) -> bool:
"""Burn tokens (Binance quarterly burn)"""
if self.total_supply < amount:
return False
self.total_supply -= amount
self.burn_events.append({
"amount": amount,
"timestamp": time.time(),
"remaining_supply": self.total_supply
})
print(f"BNB burned: {amount:,.0f} BNB")
print(f"Remaining supply: {self.total_supply:,.0f} BNB")
return True
Token Standards and Classification
ERC-20 Token Standard
from abc import ABC, abstractmethod
class IERC20(ABC):
"""ERC-20 token interface standard"""
@abstractmethod
def total_supply(self) -> int:
"""Return token total supply"""
pass
@abstractmethod
def balance_of(self, account: str) -> int:
"""Return account balance"""
pass
@abstractmethod
def transfer(self, to: str, amount: int) -> bool:
"""Transfer"""
pass
@abstractmethod
def allowance(self, owner: str, spender: str) -> int:
"""Return allowance"""
pass
@abstractmethod
def approve(self, spender: str, amount: int) -> bool:
"""Approve allowance"""
pass
@abstractmethod
def transfer_from(self, from_addr: str, to: str, amount: int) -> bool:
"""Delegated transfer"""
pass
NFT Standard (ERC-721)
class ERC721Token:
"""ERC-721 NFT token"""
def __init__(self, name: str, symbol: str):
self.name = name
self.symbol = symbol
self._owners: Dict[int, str] = {} # tokenId -> owner
self._token_approvals: Dict[int, str] = {}
self._operator_approvals: Dict[str, Dict[str, bool]] = {}
self._token_uris: Dict[int, str] = {}
self._token_counter = 0
def mint(self, to: str, token_uri: str) -> int:
"""Mint NFT"""
token_id = self._token_counter
self._owners[token_id] = to
self._token_uris[token_id] = token_uri
self._token_counter += 1
print(f"NFT minted: Token #{token_id} -> {to}")
print(f"Metadata URI: {token_uri}")
return token_id
Chapter Summary
This chapter comprehensively introduces the characteristics and applications of mainstream cryptocurrencies:
-
Ethereum Ecosystem:
- Smart contracts and EVM
- Gas mechanism and fee calculation
- Rich DApp ecosystem
-
Other Mainstream Coins:
- Ripple: Fast cross-border payments, 3-5 second confirmation
- Litecoin: Bitcoin improvement, 2.5-minute blocks
- Binance Coin: Platform token, trading fee discounts
-
Token Standards:
- ERC-20: Fungible token standard
- ERC-721: Non-fungible token (NFT) standard
- Different standard use cases
-
Technical Comparison:
- Performance metrics: TPS, confirmation time, fees
- Consensus mechanisms: PoW, PoS, consortium chains
- Use cases: payments, smart contracts, DeFi
Each cryptocurrency has its unique technical characteristics and use cases. Understanding these differences helps in selecting appropriate blockchain solutions. In the next chapter, we will learn about secure storage and wallet management of cryptocurrencies.