Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 41 ยท Practice and Review

Blockchain Cheat Sheet

A one-page blockchain cheat sheet: glossary, formulas for mining, quorum, halving and constant-product swaps, Python hashing patterns and a when-to-use checklist.

This page is the quick reference for the whole Blockchain tutorial: the vocabulary you meet most often, the formulas worth remembering, a handful of code patterns for hashing and chains, and a checklist for deciding whether a project needs a blockchain at all. Each group points back to the lesson that explains it in full.

Bookmark it, and use it together with the practice exercises and the interview questions.

Glossary

Term Meaning
Block A batch of transactions plus a header (previous hash, Merkle root, timestamp, nonce).
Hash Fixed-size fingerprint of data from a one-way function such as SHA-256.
Digest The output of a hash function.
Nonce A number changed again and again in mining; in accounts, a counter that prevents replay.
Merkle root The single hash at the top of a tree that commits to every leaf.
Genesis block The first block, with no previous block.
Mempool Pending transactions a node has seen but not yet included in a block.
Mining Searching for a nonce that makes the block hash fall below the target (proof of work).
Difficulty / target How rare a valid block hash must be; the lower the target, the higher the difficulty.
Validator A participant who proposes and attests blocks in proof of stake.
Staking / slashing Locking funds as a guarantee / destroying part of them as a penalty for provable misbehavior.
Fork Two competing versions of the chain (accidental, or an intentional rule change).
Reorg A node switching to a different, heavier chain and discarding its own recent blocks.
Confirmation A block built on top of the block containing your transaction.
Finality The point after which a block will not be reverted (probabilistic or explicit).
UTXO Unspent transaction output, the "coin" in Bitcoin-style ledgers.
Account model Ledger of balances and nonces per address, used by Ethereum.
Public / private key The key pair used for signatures; the private key must stay secret.
Address An identifier derived by hashing a public key.
Wallet Software or hardware that stores keys and signs transactions.
Seed phrase Words encoding the entropy from which all wallet keys derive.
Smart contract Code and state stored on a chain, run by every node.
Gas The unit that meters work done by a transaction on Ethereum-style chains.
Oracle A service that brings off-chain data to contracts.
Token A balance kept inside a contract (ERC-20 is fungible, ERC-721 is non-fungible).
Layer 2 / rollup A system that runs transactions off the base layer and posts proof or data to it.
DeFi / DAO Financial apps built from contracts / an organization governed by token votes.
MEV Profit made by choosing, inserting or reordering transactions in a block.

Formulas to remember

Mining effort (Proof of Work and Mining)

  • Expected attempts for d leading hex zeros: 16^d. For b leading zero bits: 2^b.
  • General case: expected hashes = 2^256 / target.
  • Expected time = expected hashes divided by the network hash rate.

Difficulty retargeting (Difficulty Adjustment)

  • new_target = old_target * actual_time / expected_time, clamped by a maximum change per period.
  • Bitcoin: 2,016 blocks, 10 minutes per block, so 2 weeks per window.

Supply and halving (Bitcoin in Practice)

  • reward(height) = 50 * 10^8 satoshis >> (height // 210000).
  • Total supply: about 210000 * 50 * (1 + 1/2 + 1/4 + ...) = 21,000,000 coins, slightly less because of integer rounding.

Merkle trees (Merkle Trees)

  • Levels for n leaves: ceil(log2 n); a proof has the same number of sibling hashes.
  • One million leaves need a proof of 20 hashes.

Byzantine and crash fault tolerance (BFT and Other Consensus)

Model Nodes needed to tolerate f faults Quorum
Byzantine (malicious) n >= 3f + 1 2f + 1
Crash only (Raft) n >= 2f + 1 majority, floor(n/2) + 1

Constant-product AMM (DeFi, DAOs and Governance)

  • Invariant: x * y = k. Spot price of A in B: y / x.
  • Swap of dx with fee rate f (0.003): dy = y * dx * (1 - f) / (x + dx * (1 - f)).
  • Integer version used in contracts: dy = dx * 997 * y // (x * 1000 + dx * 997).
  • Price impact grows with trade size relative to the pool; k grows slightly with every fee.

Ethereum fees (Ethereum in Practice)

  • fee = gas_used * (base_fee_per_gas + priority_fee_per_gas).
  • A plain transfer uses 21,000 gas.

Attacks and security

  • A private fork attacker with a minority share has a probability of catching up that falls exponentially with the number of confirmations (Longest Chain Rule).
  • ECDSA: reusing a nonce for two signatures reveals the private key.

Code patterns

All of these are small, deterministic and use only the standard library.

Hash text, bytes and structured data

Python
import hashlib, json

def sha(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()

def fingerprint(obj) -> str:
    text = json.dumps(obj, sort_keys=True, separators=(",", ":"))
    return sha(text.encode("utf-8"))

Link blocks and verify a chain

Python
def make_block(index, data, prev_hash):
    body = {"index": index, "data": data, "prev": prev_hash}
    return {**body, "hash": fingerprint(body)}

def is_valid(chain):
    prev = "0" * 64
    for i, b in enumerate(chain):
        body = {"index": b["index"], "data": b["data"], "prev": b["prev"]}
        if b["index"] != i or b["prev"] != prev or b["hash"] != fingerprint(body):
            return False
        prev = b["hash"]
    return True

Proof of work

Python
def mine(data, zeros):
    nonce = 0
    while not sha(f"{data}{nonce}".encode()).startswith("0" * zeros):
        nonce += 1
    return nonce

Merkle root and proof check

Python
def merkle_root(hashes):
    level = list(hashes)
    while len(level) > 1:
        if len(level) % 2:
            level.append(level[-1])
        level = [sha((level[i] + level[i + 1]).encode()) for i in range(0, len(level), 2)]
    return level[0]

def check_proof(leaf, proof, root):          # proof = [(sibling, "left" or "right"), ...]
    cur = leaf
    for sibling, side in proof:
        pair = sibling + cur if side == "left" else cur + sibling
        cur = sha(pair.encode())
    return cur == root

Validate before you change state

Python
def apply(state, tx):
    if tx["amount"] <= 0:
        raise ValueError("amount must be positive")
    if state.get(tx["from"], 0) < tx["amount"]:
        raise ValueError("insufficient balance")
    state[tx["from"]] -= tx["amount"]        # only after every check passed
    state[tx["to"]] = state.get(tx["to"], 0) + tx["amount"]

Safe withdrawal order (checks, effects, interactions)

Python
def withdraw(self, user):
    amount = self.balances[user]
    require(amount > 0)
    self.balances[user] = 0                  # effect first
    self.send(user, amount)                  # external call last

Rules of thumb

  • Hash bytes in one fixed encoding, and sort keys when hashing dictionaries.
  • Never trust a single recomputed hash chain for security: remember or publish the head hash.
  • Use integers for money and voting rules, never floats.
  • Check every rule before changing any state; a rejected transaction must change nothing.
  • Never reuse a signature nonce, and never store a private key or seed phrase in code or on a server you do not control.
  • Treat all data coming from outside the chain (oracles, user input) as untrusted.

Do you need a blockchain? A checklist

Answer each question. Several "no" answers mean a normal database is the better tool.

  1. Do several parties write to the same data?
  2. Do those parties distrust each other, or lack a neutral operator everyone accepts?
  3. Does everyone need to verify the history independently?
  4. Is the data valuable enough to justify the cost of consensus?
  5. Is throughput modest, so a replicated, slow ledger is acceptable?
  6. Can the data be public, or reduced to hashes that are safe to share?
  7. Is it acceptable that records cannot easily be deleted or changed?
  8. Is there a clear plan for keys, recovery and governance (who upgrades the rules)?

More detail and examples are in Enterprise and Real-World Use Cases.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. About how many hash attempts does a miner need on average for 4 leading zero hex characters?

    Each hex character has 16 possibilities, so the expected work is 16 to the power 4, which is 65,536 attempts.
  2. 2. A BFT network must tolerate 3 malicious nodes. What is the minimum number of nodes?

    n must be at least 3f+1. With f = 3, that gives 10 nodes.
  3. 3. A pool holds 1,000 A and 2,000 B. What is the spot price of A in B?

    The spot price is y divided by x, which is 2,000 / 1,000 = 2 units of B per unit of A.
  4. 4. Which statement belongs in the checklist for choosing a blockchain?

    Blockchains add cost and complexity. They pay off when many writers, low trust and independent verification come together.

Summary

  • Know the vocabulary: block, hash, nonce, Merkle root, mempool, fork, finality, UTXO, gas, oracle, rollup.
  • Mining takes 16^d attempts for d hex zeros; Merkle proofs take ceil(log2 n) hashes; BFT needs 3f + 1 nodes.
  • AMMs keep x * y constant; Bitcoin halves its reward every 210,000 blocks, with integer arithmetic.
  • Canonical hashing, validate-then-change, and checks-effects-interactions are the patterns that prevent most toy-chain and contract bugs.
  • A blockchain is justified by several writers, low trust and a need for independent verification; otherwise use a database.

That completes the Blockchain tutorial. Revisit What Is a Blockchain? any time you want to see the big picture again.