18 min read

What are blockchains

1.0 Definitions

Termdefinition
Nodea computer storing blockchain data
P2P networkcomputer↔computer, no intermediary
Blockstransactions are grouped into blocks
chainblocks are chained in chronological order.
that creates the blockchain
block → block → block

1.1 Overview

traditional systems rely on intermediaries like banks, tech companies, govt/election committees
these control money, data, agreements

cons of this:
- bank freezes your money, fraud triggers/suspicious transfers
- central company bans your business/central authority controls your economic survival
- international sanctions/blocked regions
- currency collapse, central authority is a bank, government prints too much money, currency value crashes
- vote manipulation, central authority if removed, results can be verified properly
- escrow authority takes fees and gains power
- government records, central authority can alter ownership records
- monopoly marketplaces can change platform rules overnight (increasing fees, change rules)

blockchain introduces a new model, instead of trusting central authority you now trust maths, cryptography, code

blockchain is a decentralized shared ledger where instead of one private ledger, thousands of computers store identical copies

1.1.1 when to use blockchain

  1. can a single trusted operator maintain the state?
  2. are there multiple writers to the database because consensus on correct writing is important
  3. can one writer benefit by lying
  4. do participants need global agreement on even order
  5. can a trusted party cheaply solve consensus
  6. what is the cost if one actor blocks valid writes
  7. what is cost of corruption

1.1.2 History

people wanted digital money that worked just like cash i.e no double spending issue. to resolve double spending issue either have a central authority that maintains records or use some decentralized solution

double spending: same digital money gets spent more than once via copying, and resending the same value multiple times

1.2 Bitcoin (2008)

satoshi nakamoto publishes a bitcoin whitepaper launching a decentralized digital currency that has no double spending issue and also solves byzantine general problem
a total of 21Million BTC are there (limited supply)

in blockchain, instead of one ledger, everyone keeps a copy, process:
a. user sends transaction
b. network checks validity
c. transaction goes into block
d. block added to chain
e. everyone updates ledger

1.2.1 Byzantine general problem

A city is surrounded by 5 generals of byzantine army, they need to decide when to attack/retreat together. if they all attack → they win, if they all retreat → they survive. if some attack and some retreat → disaster, many killed. so they must agree on a single decision.

problem: they communicate by messengers, assume one general is a traitor, how do a general know that the sender is lying/messenger intercepted

1.3 Ethereum

after bitcoin, Vitalik expanded blockchain from money system to a programmable platform
uses a currency sytem: ETH (Ether)

1.4 Smart contracts

proposed by Nick szabo, smart contract is code on blockchain

1.5 Applications of Blockchain

  1. enables digital currencies (cryptocurrencies) with peer to peer transfer, global payments
  2. decentralized finance, financial services built on blockchain
  3. stablecoins - cypto assets designed to maintain stable value
  4. smart contracts - self executing agreements written in code
  5. digital ownership of assets
  6. DAO - Decentralized Autonomous Organization, members vote through blockchain voting
  7. DApp - decentralized applications/application whose backend runs on blockchain

1.6 Multi chain world

there are many blockchains (Bitcoin, ETH, solana, polygon, …)
there are soo many blockchains because popular blockchains can only process limited transactions (ETH can product 15-30 transactions/sec)

transaction/gas fees - pay network participants for processing transactions, when congestion rises, users compete and higher fees win priority.

solution → build more roads/blockchains, leads to Layer 1 and Layer 2 (L1, L2)

Layer 1 (L1): base blockchain, runs independently. provides consensus/security/ledger
Layer 2 (L2): layer 2 is built on top of a layer 1, improves speed/throughput/transaction cost
Mainnet: real live blockchain, involves real tokens/money
Testnet: practice blockchain used for testing/learning/experimentation/smart contract development
Faucet: to use testnet, you need test tokens which you can get from faucet from free.
Sepolia: is Ethereum major testnet, used by devs to practive eth safely
Chain ID: since many networks exist, wallets need unique identifiers (Chain IDs). Helps identify blockchain network.

1.7 Oracle problem

smart contracts are blind to outside world, they cannot access internet data e.g. weather, stock price, package delivery status.

Oracle problem: how can a blockchain securely know facts from outside world. smart contract cant call an API as is, because blockchain needs determinism. if external API breaks, that breaks consensus.

Oracle: messenger between blockchain and outside world, but if the oracle fails/returns invalid value → single point of failure

solution: Decentralized Oracle Network (DON), multiple oracle data nodes independently fetch data and updates the data on the chain
if values are 2001, 2000, 2002, 1999 then the aggregated value is sent on chain

1.8 Smart contracts

traditional contracts/promises/agreements are made on trust and centralized institutions are controlled by humans. Humans act selfishly, manipulate rules, seek profit and abuse power. (2008 financial crisis, mcdonalds monopoly scam, robinhood trading halt scam)

smart contract is an agreement written in code that executes automatically on a blockchain

considerations:
once deployed, code cannot be changed
runs on many blockchain nodes, noone can halt execution
smart contract code is public, anyone can inspect rules/logic

1.9 Ethereum Virtual Machine (EVM)

virtual computation environemnt taht exists on every Ethereum node, purpose is to run smart contracts/update blockchain state/process contract logic

written in languages like Solidity/vyper. these programs are compiled into bytecode which the evm understands
everyone can verify transaction history this way

1.9.1 51% attack

when a singel attacker/coordinated group controls more than 50% of a blockchain consensus power. it depends on blockchain, if attacker produces block faster than honest network they can dominate.


2.0 blockchain wallets

wallet: secure digital application used to manage blockchain assets and interact with blockchain networks. send/receive tokens

most blockchains have their own built in currency
Bitcoin blockchain = Bitcoin (BTC)
Ethereum blockchain = Ether (ETH)

native currency is used for transaction/gas fees, smart contract interaction, transfers

when you create a wallet, you get a unique wallet address:

javascript
public_key = 0x5392BD00571157Fa11103b0eE6D492c9563a6799

if someone wants to send you something, they need your address.
Note: Wallet does not store coins, coins are not stored inside wallet app, they actually live on the blockchain ledger. wallet mainly stores credentials needed to access assets

2.1 MetaMask

software wallet (hot wallet) that views balance, transaction history, send/receive tokens, connect to DApps. You control your wallet and private keys, no bank/company/support team. if you loose access → no one can recover funds for you.

Secret Recovery Phrase (SRP) is a 12 words key unique to wallet, acts as a ultimate backup and can restore wallets/funds

Wallet types:
a. hot wallet - connected to internet e.g MetaMask → easy to use/more hack risk
b. cold wallet - offline physical wallet → highest security/less convenient

2.1.1 Gas Fees

Gas = unit measuring computational work on Ethereum
payment to the network for doing computation, can get expensive when demand increases because capacity is fixed.

every blockchain action consumes gas (sending ETH, calling smart contracts, minting NFTs)

Gas exists because validators process transactions and secure network. Gas fees rewards them. Gas makes attacks expensive

Gas prices depends on demand too, since block space is limited it follows a supply and demand curve.

typical transaction contains: recipient address, amount/value, action/instructions, gas fees

older systems used auction model, higher bidder gets priority; issues = overpaying, stuck transactions, unpredictable fees

2.1.1.2 EIP-1559 (type 2 transactions)

introduced a better fee sytem with base fee + priority fee
base fee = minimum required gas price
block > 50% full → base fee increases
block < 50% full → base fee decreases

this makes ETH delationary

priority fee = optional extra payment to validator, helps transactions get processed faster
total cost = gas used * (base fee + priority fee)

ETH units:
a. Wei (smallest unit of ETH)
b. Gwei (common unit for gas prices)
1 Gwei = 1,000,000,000 Wei
1 ETH = 1,000,000,000 Gwei
 (one billion Gwei)
1 ETH = 10^18 Wei (one quintillion Wei)

2.1.2 Bitcoin miners

since bitcoin has no central bank, someone needs to verify all of the ledgers.
Miners do this stuff:
a. collect transactions - gather pending transactions from users
b. verify transactions - checks if sender has enough balance
c. add transactions to blockchain - valid transactions are grouped into a block

ASICs machines are generally used to mine BTC, they spend enormous compute to find a hash value that is rare to generate.

But how do miners make money?
a. people send BTC to each other
b. each transaction gets broadcasted to the bitcoin network
c. miner picks a bunch of pending transactions and makes a block
d. miner wants network to accept this block
e. Bitcoin doesnt allows anyone to append blocks freely, bad actors could spam fake blocks
f. Bitcoin requires a proof of work (how expensive the compute was)
g. miner must find a hash value below a target value, that is extremely hard/no shortcut
h. when a miner wins a block, bitcoin creates a new BTC (block subsidy) and awards it to the miner

2.2 Blockchain Consensus

consensus = how all nodes in a blockchain agree on one shared truth
all nodes must agree on transaction order, valid transactions, correct blockchain state

sybil attack/resistance = one attacker can create many fake identities/nodes to gain influence. if attacker nodes > honest nodes then attacker controls voting.

Finality = transaction becomes practically or mathematically irreversible
after finality, transactions cant be undone, blockchain history is fixed

transaction becomes safer as more blocks are added after it. In bitcoin after the chain gets appended by 6 blocks, its considered safe.

2.2.1 Sybil resistance

blockchain makes influence expensive, miners must show proof of work (more compute = more influence), and proof of stake (PoS) validators

Validators = just like crypto miners validators earn ETH for locking capital and behaving honestly. Validators lock cryptocurrency as stake, more stake = more influence. Dishonesty can cause slashing, loss of staked funds.

2.2.2 Proof of Work (PoW)

miners must perform real computational work to add new blocks. this work makes attacking blockchain expensive. hash is a fixed length output generated from input data using a hash function.

for hashes output length is always the same (256 bits/64 hex bits) and is deterministic

selected validator creates the block and signs it using their private key. if someone modifies the blockdata, hash changes and signature becomes invalid.

2.3 Block

a block stores blockchain data, typical block contains a block number, transaction data, previous block hash, nonce, block hash

miners must find a valid block hash

2.3.1 Forks

fork happens when two miners mine valid blocks simultaneously
resolution = whichever chain gets next block first becomes longer, shorter chain gets discarded

2.4 Cryptography

maths used for verifying if transaction is authentic/wasnt modified
public key = used by others to verify signatures
private key = secret cryptographic key
wallet addresses = shortened version derived from public key
seed phrase = 12 or 24 words, master backup of wallet
digital signature = data created when signing a message using private key
when sending crypto, wallet signs transaction data

2.5 PoS Consensus Process

protocol randomly selects one validator, that validator creates new block, proposes it to the network, other validators check/attest if transaction valid, rules followed.
once other validators vote/attest for validity, it becomes finality.

block needs approval from validators representing ≥ 2/3 total staked ETH then the block becomes justified.

if validators found cheating(proposing conflicting blocks, fake votes) then stake gets destroyed

to attack the network, attacker needs massive amount of ETH, more ETH → attack becomes expensive

2.6 Common vulnerabilities

  1. sybil attack - when attackers creates many fake identities to gain majority control
    can approve fake transactions, double spend, block valid transactions, reorder transactions, rewrite blockchain history.
    we have PoW and PoS to counter this stuff
  2. 51% attack - attacker gains majority consensus power
    if attacker controls >50% hash power (faster than honest network) can replace blockchain history, do double spend.
    if attacker has >50% staked tokens, can gain influence on chain selection/reorder transactions.
    this attack costs billions on dollars even then the community can reject malicious chain
  3. Blockchain reorganization (Re org) - blockchain history changes because chain switches to another valid chain.
  4. MEV (Maximal Extractable Value) - extra profit earned by manipulating transaction ordering inside a block. before confirmation transaction waits in mempool. bots can inspecct pending transactions
  5. Sandwich attack - bots profit by placing transactions before and after yours
    bot buys token before user → price rises, user buys at worse price → price rises more, bot sells immediately, bot profits.
  6. client software bugs - attacks caused by bugs in software implementation
  7. Replay attack - valid transaction from one chain gets replayed on another chain
    to prevent this:
    i. for protection, each blockchain has a unique ID, transaction valid only for intended chain
    ii. every transaction also contains a nonce, first try → nonce 0, second try → nonce 1

2.7 Hard Forks

issa blockchain protocol upgrade that changes network rules in a non backward compatible way
which means old software cannot understand new blockchain rules, nodes must update to stay on main chain.
hard forks are used to upgrade blockchain features such as consensus changes, updated fee mechanism etc

Types of hard forks:
a. non contentious hard fork - most community agrees
b. Contentious hard fork - community disagrees on upgrade, as a result blockchain spilts into two chains

who decides hard forks?
a. core devs who write PRs
b. client teams who manage blockchain software
c. node operators, they choose to update or stay on old version
d. normal users and devs

2.7.1 Ethereum improvement proposal (EIP)

Formal proposal for changing Ethereum, anyone can propose a new rule

EIP stages:-
a. Initial proposal submitted
b. community + devs discuss it
c. final feedback stage
d. accepted and scheduled for upgrade

hard fork activation steps:-
a. proposal approved
b. client software updated
c. changes tested on testnets
d. activation block chosen
e. fork goes live

types of EIPs:
- core → changes Ethereum protocol
- networking → node communication improvements
- Interface - API/client standards
- ERC - Applevel standards
- Meta → Changes EIP process
- Informational → Documentation/guidelines

2.7.2 Ethereum Request for comment (ERC)

special subset of EIPs focused on application level standards
ERCs ensure wallets, exchanges, NFTs and dApps can all understand each other

2.8 Ethereum Transaction lifecycle

transaction = signed message sent to Ethereum requesting some action
goal of a transaction = change blockchain state
state = complete current record of account balances, smart contract storage/data

steps:
1. create transaction - crypto wallet builds transaction object(chain ID, nonce, gas params, transaction data)
2. sign transaction - hash transaction object, sign using private key
3. broadcast transaction - wallet sends signed transaction to Ethereum node via RPC
4. transaction enters mempool - if valid signature/enough balance/valid nonce then transaction enters mempool and propagates across the network [transaction pending]
5. block selection - Ethereum selects one validator to propose block, validator chooses transactions from mempool, priority is based on higher tips
6. validator - executes transactions, updates state, creates block, broadcast block
7. attestation - other validators attest if the transaction valid, signature correct, state changes correct
8. finalization - if enough validators approve, block added to blockchain [transaction confirmed] approx time: 12 seconds
9. if ≥ 2/3 validators agree permanently, block becomes irreversible, [transaction finalized] approx time: 12-13 minutes

2.8.1 Transaction states

  1. pending - waiting in mempool
  2. confirmed - included in valid block
  3. finalized - practically irreversible
  4. reverted/failed - smart contract condition failed (smart contract condition failed, insufficient token balance) state change is reversed but gas still lost
  5. dropped - transaction removed before block inclusion (due to low gas)

2.9 Account Abstraction (AA)

Goal of web3 was to make it as easy as web2

current problem in Ethereum account model:
a. Externally owned accounts (EOAs) - regular walletes like MetaMask are controlled by private key, can initiate transactions and arent programmable
b. smart contract accounts - controlled by smart contract code, highly programmable and can do custom logic. cannot initiate transactions by themselves
EOAs can transact but cannot program, smart contract programmable but cannot transact → Bad UX

Account abstraction removes the strict separation between EOAs and smart contract accounts
it creates smart wallets = can initiate transactions and is programmable

features enabled:
a. social recovery for seed phrase
b. gas sponsorship by game and apps for users
c. can batch multiple transactions into one

2.9.1 EIP-4337

enables account abstraction without eth core protocol. instead of normal transaction, user creates UserOperation which goes into a Alt Mempool.

special nodes called bundlers collect multiple UserOperations convert AA requests to standard Ethereum transactions and submits them to Ethereum.

2.10 EIP-7702

smart wallets are powerful, but adoption was hard because EOA users had to migrate (new wallet address, transfer all funds, learn new wallet UI)

EIP7702 allows an EOA to temporarily behave like a smart contract wallet during transaction

2.11 Transaction types in Ethereum

type 0: legacy transaction
type 1: added access lists
type 2: added base fee + priority fee
type 3: cheaper layer 2 data storage
type 4: delegation to smart contract logic

3.0 Applications of blockchain

  1. Decentralized Finance (DeFi)
    financial services built on blockchain without traditional intermediaries
    allows users to:
    a. lend money
    b. borrow money
    c. trade assets
    d. earn yield/interest
  2. Tokens
    digital assets created on blockchain
    used for:
    a. transferring value
    b. rewards
    c. governance voting
    d. utility inside apps
  3. NFTs (Non-fungible Tokens)
    Non fungible → every asset unique
    used for digital art, gaming items, collectibles
  4. stablecoins
    cryptocurrencies designed to maintain stable value
    usually pegged to flat currency like USD
  5. Real world assets (RWA)
    tokenization of physical/off chain assets (real estate, stocks, bonds, gold) onto blockchain
  6. Governance & DOAs
    organization governed by smart contracts and community voting instead of central authority. members use tokens to vote on upgrades, treasurey spending, protocol decisions

3.1 Decentralized Finance (DeFi)

financial services built on blockchain using smart contracts
DeFi allows users to lend/borrow/trade/earn money
TradFi includes banks, insurance companies, brokers, stock exchanges

smart contract rules are hardcoded, same input → same output everytime
DeFi protocols are modular and interoperable

DeFi applications:
a. Decentralized Exchanges (DEXs) - trade tokens without centralized exchange
b. Lending & Borrowing - users lend assets for yield or borrow against collateral
c. Derivtatives - advanced financial products like leveraged trading
d. yield farming - users provide liquidity

3.2 Blockchain Tokens

  1. token = digital representation of value/utility on blockchain
  2. native tokens = built into the blockchain protocol itself. uses pay gas fees, default currency of chain, staking for PoS security, governance in some protocols.
  3. Fungible tokens = interchangeable + divisible, 1 token = same as another token of same type
    a. stable coins - pegged to external asset for price stability
    b. utility tokens - provide access to protocol/service
    c. governance tokens - give voting rights in DAO
    d. reward tokens - earned by participating in protocols
  4. Non fungible tokens - unique digital asset
    is unique, non interchangeable, indivisable, contains metadata
  5. semi fungible tokens - hybrid between fungible and NFTs
    same class tokens are interchangeable, different classes are not
  6. Real world assets (RWAs) - real world assets tokenized onto blockchain
    eg real estate, treasury bonds, gold, private equity
  7. stable coins - maintains stable price

3.3 Centralized Exchanges (CEX)

exchange = marketplace to buy/sell/swap crypto tokens

CEX = private company acting as intermediary for crypto trading e.g coinbase, binance
create account → complete verification → deposit flat money → buy/sell
exchange holds your crypto, controls private keys. easy to use but its a centralized exchange (centralized ke apny masly)

3.4 Decentralized Exchanges (DEX)

DEX = smart contract protocol enabling peer to peer crypto trading without an intermediary. eg. uniswap, curve, balancer.
connect wallet → select tokens to swap → sign transaction → trade directly from wallet
decentralized tou issues nae but smart contract bugs, gas fees

3.5 Automated Market Maker (AMM)

pricing determined automatically by smart contract using liquidity pools
liquid pool = smart contract holding token reserves
liquidity providers = users deposit token pairs into pool
earn trading fees

pricing depends on token ratio inside pool
if ETH bought heavily, ETH become scarcer, price rises

modern DEXs use AMMs instead of order books

DEX aggregators search across many DEXs for best swap route/lowest slippage

3.6 Swapping tokens on a DEX (Uniswap)

token swap = exchanging one token for another directly on DEX
before swapping check:
a. amounts
b. protocol fee - uniswap trading fee
c. network cost - gas fee
d. max slippage - maximum allowed price change before transaction fails

3.7 Governance and DAOs

traditional organizations are centralized → small group makes decisions
in Web3, governance can be decentralized → community/token participate in decision making
DAO (Decentralized Autonomous Organization) → organization governed by smart contracts on blockchain instead of centralized management
over here; rules are written in code, decision are transparent, no single authority can override results

typical lifecycle:
a. proposal submission - community member submits proposal
b. proposal encoded in smart contract/code
c. when voting period starts, they get to vote
d. vote tallying in end
e. if majority reacched, proposal executes automatically

voting power = proportional to governance tokens held, more tokens → more voting influence
DAO voting works because voters are financially invested, if bad proposal passes; protocol becomes weaker and token value may drop. if good proposal; protocol improves, token value may rise

Challenges of DAOs
a. voter apathy - many token holders dont vote
b. whale dominance - large holders can heavily influence outcomes
c. technical complexity - proposals may require economics, smart contract knowledge
d. gas costs - voting cost transaction fees
e. token lockups - some systems temporarily lock tokens during voting

3.8 Layer 1 (L1)

base blockchain network, responsible for consensus, security, final settlement of transactions
L1 is the source of truth for blockchain state. also called settlement layer because transactions ultimately settle here.

blockchain can optimize only 2 or 3 properties
1. decentralization - many participants control network
2. security - hard to attack or manipulate
3. scalability - can process many transactions quickly

L1 limited throughput (tens of tx/s) gas becomes expensive

3.9 Layer 2 (L2)

separate blockchain built on top of L1 to improve scalability.
what it does:
a. processes transactions off L1
b. periodically settles back on L1
c. inherits L1 security

instead of processing lots of transactions in Ethereum, it processes compressed transaction summaries on Ethereum mainnet

rollups = most common L2 scaling solution
a. execute many transactions on L2
b. bundle them into batch
c. submit compressed batch to L1
benefit → one L1 gas fee shared across many transactions

Optimistic rollups = all submitted transactions are valid by default
batch posted to L1
challenge period begins (7 days)
if fraud detected, invalid batch reverted

ZK(Zero Knowledge) rollups = instead of assuming validity, ZK rollups prove validity cryptographically
operator submits transaction batch, validity proof
L1 verifier contract checks proof

if proof valid, batch accepted immediately
instant finality
advantages: faster finality, faster withdrawls, stronger mathematical guarantees

3.9.1 Sequencers

sequencer = special operator in rollups that handlers incoming L2 transactions
main job:
a. receive user transactions
b. decide transaction order
c. bundle transactions into batches
d. submit batch to L1

3.9.1.1 centralized sequencer

single sequencer controlled by one company
single entity has too much power

risks:
a. censorship risk - sequencer can refuse certain transactions
b. MEV (maximal extractable value) - sequencer can reorder transactions to profit
c. single point of failure - entire L2 depends on one sequencer

3.9.1.2 decentralized sequencers

multiple independent sequencers instead of one

benefits:
a. no single party controls ordering
b. censorship becomes harder
c. better fault tolerance
d. network remains live if one sequencer fails

3.10 Rollup stages

how much do users still need to trust the rollup team?
you deposit 10 ETH now your funds live in rollup contracts, if rollup team disappears, can you still recover your money?

framework to measure maturity/decentralization of L2 rollups:
a. stage 0 (full training wheels)
for rollups at this stage, users trust the core team, security council and everything
b. stage 1 (partial decentralization)
security shifts from humans to smart contracts and proof systems
c. stage 2 (no training wheels)
rollup becomes independent of the rollup team