⛓️ Blockchain
Blockchain & Web3 Cheatsheet
Cryptography, Bitcoin, Ethereum, smart contracts, DeFi, NFTs and Web3 development.
📖 10 sections
⏱ 24 min read
✅ Quizzes included
🌙 Dark mode
01 Blockchain Basics
Blockchain
Distributed ledger: chain of blocks containing transactions. Immutable, transparent, decentralised.
Block
Container: index, timestamp, data (transactions), nonce, hash, previous hash.
Hash
Unique fingerprint of block content. SHA-256: even 1 character change = completely different hash.
Decentralisation
No single authority. Copy on thousands of computers (nodes). No single point of failure.
Immutability
Once recorded, data cannot be altered. Changing one block breaks all subsequent hashes.
Transparency
All transactions public on public blockchains. Pseudonymous (addresses, not names).
Node
Computer that holds a copy of the blockchain and validates transactions.
Distributed ledger
Multiple copies of the same record across different locations — no central database.
CHAINBlock structure
Block n:
  index:     12345
  timestamp: 2026-04-19T10:00:00Z
  data:      [tx1: Alice→Bob 1BTC, tx2: Carol→Dave 0.5BTC]
  nonce:     48293
  prev_hash: 0000a8f3...
  hash:      0000c4d9...

Linked chain:
  Genesis Block → Block 1 → Block 2 → Block 3 → ...
  (each stores hash of previous block)
02 Cryptographic Foundations
SHA-256
Secure Hash Algorithm. 256-bit output. Bitcoin's main hash function. Deterministic, one-way.
Public key
Your blockchain address. Can share publicly. Like your bank account number.
Private key
Secret key to sign transactions. NEVER share. Like your PIN. Lose it = lose funds.
Digital signature
Transaction signed with private key. Proves ownership without revealing key.
Merkle tree
Hash tree of all transactions. Merkle root in block header = efficient verification.
Cryptographic proof
Mathematical proof you own funds without sharing private key.
Seed phrase
12-24 words that generate your private key. THE most important thing to protect.
Cold storage
Private keys stored offline (hardware wallet). Not connected to internet = more secure.
CHAINKey pair example
Private key: 5HueCGU8rMjxECyDialwujzT...  (KEEP SECRET)
Public key:  04bfcab8722991ae774db48f...  (share freely)
Address:     1PMycacnJaSqwwJqjawXBErnD...  (your 'account')

# Transaction signing
Tx = {from: address, to: bob, amount: 1 BTC}
signature = sign(private_key, hash(Tx))
# Network verifies: verify(public_key, signature, hash(Tx))
💡
Private key = full control. Seed phrase = regenerates private key. Anyone with either = owns your crypto. Never share, never store digitally.
03 Bitcoin
Bitcoin
First blockchain (2009). Creator: Satoshi Nakamoto. Limited supply: 21 million BTC.
UTXO
Unspent Transaction Output. Bitcoin model — like spending cash, getting change back.
Mining
Proof-of-Work: computers race to find nonce that makes block hash start with zeros.
Halving
Every 210,000 blocks (~4 years), mining reward halves. 50→25→12.5→6.25→3.125 BTC.
Mempool
Pending transactions waiting to be included in a block. Higher fee = faster confirmation.
Lightning Network
Layer 2: payment channels for fast, cheap Bitcoin transactions off-chain.
Full node
Downloads and validates entire blockchain. Most secure way to verify transactions.
Block time
~10 minutes per block. Difficulty adjusts every 2016 blocks to maintain this rate.
CHAINBitcoin mining
# Mining: find nonce where SHA256(block_data + nonce) < target
# Target: hash must start with many zeros (difficulty)

# Example: finding valid hash
for nonce in range(infinity):
    hash = SHA256(block_header + nonce)
    if hash.startswith('00000'):   # 5 zeros = simplified
        print(f'Valid block! nonce={nonce}')
        break  # broadcast to network

# Difficulty adjusts so block found every ~10 min
# Network hash rate now: ~600 EH/s (600 × 10^18 hashes/sec)
💡
Mining consumes massive energy. One Bitcoin transaction ≈ 1000+ kWh. This is why alternatives (Proof of Stake) emerged.
04 Ethereum & Smart Contracts
Ethereum
Programmable blockchain (2015). Ether (ETH) is native currency. Smart contracts run on EVM.
Smart contract
Self-executing code on blockchain. 'If X then Y' — no intermediary needed.
EVM
Ethereum Virtual Machine. Runs smart contract bytecode. Same result on every node.
Gas
Fee for computation on Ethereum. Gas price (Gwei) × Gas used = transaction cost.
ERC-20
Token standard. Most DeFi tokens follow this. Transfer, approve, allowance functions.
ERC-721
NFT standard. Each token unique. Used for digital art, collectibles.
Solidity
Main smart contract language. JavaScript-like. Compiles to EVM bytecode.
The Merge
2022: Ethereum switched from Proof-of-Work to Proof-of-Stake. 99.95% less energy.
CHAINSimple Solidity smart contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract SimpleBank {
    mapping(address => uint256) private balances;

    event Deposit(address indexed user, uint256 amount);
    event Withdrawal(address indexed user, uint256 amount);

    function deposit() external payable {
        require(msg.value > 0, 'Amount must be > 0');
        balances[msg.sender] += msg.value;
        emit Deposit(msg.sender, msg.value);
    }

    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount, 'Insufficient balance');
        balances[msg.sender] -= amount;
        payable(msg.sender).transfer(amount);
        emit Withdrawal(msg.sender, amount);
    }

    function getBalance() external view returns (uint256) {
        return balances[msg.sender];
    }
}
05 DeFi
DeFi
Decentralised Finance. Financial services on blockchain — no banks, no middlemen.
DEX
Decentralised Exchange. Trade tokens via smart contracts. Uniswap, Curve, dYdX.
AMM
Automated Market Maker. Uses liquidity pools instead of order books. x×y=k formula.
Liquidity pool
Users deposit token pairs → earn fees. Impermanent loss risk.
Lending protocol
Borrow against crypto collateral. Aave, Compound. Over-collateralised.
Yield farming
Earn rewards by providing liquidity. High risk — smart contract bugs, rug pulls.
Stablecoin
Price pegged to USD. USDC/USDT (centralised), DAI (decentralised/algorithmic).
TVL
Total Value Locked. Measures how much crypto is in DeFi protocols.
06 NFTs
NFT
Non-Fungible Token. Unique digital token. Proves ownership of digital asset on blockchain.
Fungible vs Non-fungible
BTC: fungible (1 BTC = 1 BTC). NFT: unique — cannot substitute for another.
ERC-721
Ethereum NFT standard. Each tokenId unique. Stores metadata URI.
Minting
Creating an NFT. Smart contract records your ownership on blockchain.
OpenSea
Largest NFT marketplace. Buy, sell, mint NFTs.
Royalties
Creator earns % of secondary sales. Enforced by smart contract.
Use cases
Digital art, game items, tickets, music rights, real-world asset ownership.
Speculation vs utility
Most 2021-22 NFTs speculative. Real utility: tickets, memberships, game assets.
⚠️
Most NFTs lost 90%+ of value since 2021 peak. Research carefully. 'Right-click save' doesn't give blockchain ownership — but ownership without utility may have limited value.
07 Consensus Mechanisms
Proof of Work
Miners compete to solve puzzle. Energy-intensive. Bitcoin, Litecoin.
Proof of Stake
Validators stake (lock) crypto as collateral. Random selection to validate. Ethereum, Cardano.
Delegated PoS
Token holders vote for delegates who validate. EOS, Tron.
Proof of Authority
Approved validators (known identities). Private/enterprise blockchains.
Byzantine fault tolerance
System works even if some nodes fail or are malicious.
51% attack
Control 51% of mining/stake → rewrite recent history. Expensive on large networks.
Finality
When transaction is truly irreversible. Probabilistic (PoW) vs deterministic (PoS).
Nakamoto consensus
PoW: longest valid chain wins. Simple but energy-intensive.
PoW energy
~1200 kWh per Bitcoin transaction
Major criticism
PoS energy
~0.01 kWh per transaction
99.95% more efficient (Ethereum post-merge)
51% cost
Billions of dollars for major networks
Economically impractical to attack Bitcoin/Ethereum
08 Web3 Development
CHAINWeb3 development tools
# Libraries
ethers.js  — interact with Ethereum from JavaScript
web3.py    — Python Ethereum library
wagmi      — React hooks for Ethereum
Viem       — TypeScript Ethereum library

# Development environment
Hardhat    — smart contract development framework
Foundry    — fast Rust-based framework (Forge)
Remix IDE  — browser-based Solidity IDE (beginner)
Ganache    — local blockchain for testing

# ethers.js example
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider(ALCHEMY_URL);
const signer = new ethers.Wallet(PRIVATE_KEY, provider);

// Read contract
const contract = new ethers.Contract(ADDRESS, ABI, provider);
const balance = await contract.getBalance();

// Write transaction
const tx = await contract.connect(signer).deposit({ value: ethers.parseEther('0.1') });
await tx.wait();

# Testing with Hardhat
const [owner, addr1] = await ethers.getSigners();
const contract = await (await ethers.deployContract('MyContract')).waitForDeployment();
await expect(contract.connect(addr1).withdraw(100)).to.changeEtherBalance(addr1, 100);
💡
Always audit smart contracts before deploying with real funds. Bugs are irreversible on-chain. Use Slither, MythX, or professional auditors.
09 Risks & Regulation
Rug pull
Dev team abandons project and takes funds. Often in DeFi/NFT projects.
Smart contract bug
Immutable code — bugs can't be patched. The DAO hack: $60M stolen 2016.
Private key loss
Lose key = lose crypto forever. ~3-4 million BTC permanently lost.
Regulatory risk
Governments may ban or heavily regulate crypto. Uncertainty remains high.
Volatility
Bitcoin: -80% crashes common. High risk speculative asset class.
CBDC
Central Bank Digital Currency. Governments creating their own digital currencies.
MiCA (EU)
Markets in Crypto-Assets regulation. EU regulatory framework from 2024.
Tax treatment
Most countries: crypto profits taxable as capital gains. Track every transaction.
⚠️
Never invest more than you can afford to lose completely. This is a highly speculative, volatile asset class with significant regulatory and security risks.
💡
Due diligence: Who are the developers? Is code open source? Is it audited? Does it have real-world utility? Avoid anonymous teams with no audit.
10 Mini Quizzes
❓ Quiz 1
What makes blockchain immutable?
Blockchain immutability comes from cryptographic chaining. Each block contains the hash of the previous block. If you alter any block, its hash changes, breaking the link to the next block — and all subsequent blocks. This makes undetected tampering computationally impossible.
❓ Quiz 2
What is the key difference between Proof of Work and Proof of Stake?
PoW: miners compete using massive energy to solve puzzles. PoS: validators lock up (stake) crypto as collateral — selected pseudo-randomly to validate. Ethereum's switch to PoS reduced energy usage by 99.95% with no significant security loss.