Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 41 ยท Practice and Review

Practice Exercises with Solutions

Ten graded blockchain exercises in Python on hashing, Merkle roots and proofs, mining, chain validation, UTXO checks, AMM math and supply: with runnable solutions.

Reading about a blockchain is one thing; writing the checks yourself is another. These ten exercises go from easy to hard and cover the tools you met in the tutorial: hashing, Merkle trees, mining, chain validation, the UTXO model, automated market makers and the supply schedule. Every exercise has a runnable solution with assert statements, so you can tell at once whether it is correct.

How to use this page

  1. Read the exercise and try it yourself first, ideally in a scratch file or in a TryIt editor of your own.
  2. Run the solution below it, then compare. A different but correct approach is fine, as long as the asserts pass.
  3. Change a number or break a rule on purpose and see which assert fires. That is the quickest way to learn what each check protects.
Level Exercises
Easy 1 to 3
Medium 4 to 7
Hard 8 to 10

Exercise 1 (easy): leading zeros

Write leading_zeros(digest) that counts the zero characters at the start of a hex digest. Then find the smallest number n such that the SHA-256 digest of "block-" + str(n) starts with at least three zeros. Reminder: each extra zero character multiplies the expected work by 16 (Proof of Work and Mining).

Python Solution 1: leading zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 2 (easy): count the avalanche

Write bits_different(a, b) that returns how many of the 256 bits differ between the SHA-256 digests of two strings. Check it for "hello" and "hellp", and for identical strings. Hint: XOR the digests as integers and count the ones.

Python Solution 2: bits that differ

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 3 (easy): canonical fingerprints

Two nodes must agree on the hash of a transaction even when their dictionaries list the keys in a different order, including inside nested dictionaries. Write fingerprint(obj) that returns a SHA-256 hex digest which does not depend on key order, but does change when any value changes. Use a compact JSON form with no spaces.

Python Solution 3: order-independent fingerprint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 4 (medium): Merkle root

Write merkle_root(items) for a list of strings. Hash each item to make the leaves, then combine neighbours as sha256(left + right) on the hex strings, level by level. When a level has an odd number of hashes, pair the last one with itself. A single item's root is the hash of that item. Check the three-leaf case against a manual calculation, and check that changing one item changes the root (Merkle Trees and Proofs of Inclusion).

Python Solution 4: Merkle root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 5 (medium): Merkle proofs

Extend exercise 4. Write make_proof(items, index) that returns a list of (sibling_hash, side) pairs, where side says whether the sibling sits on the "left" or the "right", and verify(item, proof, root) that recomputes the root from one item. Test every index for trees of 1 to 9 items, and make sure a wrong item fails.

Python Solution 5: proof of inclusion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 6 (medium): mine and measure

Write mine(data, difficulty) that returns the first nonce for which sha256(data + str(nonce)) starts with difficulty zero characters, together with the digest. Then mine 20 different blocks at difficulty 3 and compute the average number of attempts. Theory says the average should be near 16^3 = 4096; with only 20 samples expect it to be off by a lot (Proof of Work and Mining).

Python Solution 6: mining and its average cost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 7 (medium): find the broken block

Build a chain where each block stores index, data, prev and hash, with hash computed over the other three fields. Change the data in one block and write first_invalid(chain) that returns the index of the first block that fails verification, or None when the chain is fine. Then repair the chain by rehashing from the edited block onward, and check that the last hash still shows the change (Building and Validating the Chain).

Python Solution 7: first invalid block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 8 (hard): validate a UTXO transaction

A ledger is a dictionary that maps (txid, output_index) to (owner, amount). A transaction lists input references and new outputs. Write apply_tx(utxos, tx) that raises ValueError when an input does not exist (or was already spent), when the same input is listed twice, when an amount is not positive, or when outputs add up to more than inputs. Otherwise it spends the inputs, creates the outputs and returns the fee (inputs minus outputs). Do not change the ledger when a check fails (UTXO vs Account Model).

Python Solution 8: UTXO validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 9 (hard): constant-product swaps

A pool holds x units of token A and y units of token B and keeps x * y from falling. A swap of dx token A in pays out token B after a 0.3 percent fee on the input. Write swap_a_for_b(x, y, dx) that returns the pair (new_x, new_y) and the amount dy received, using integer arithmetic: dx_fee = dx * 997, dy = dx_fee * y // (x * 1000 + dx_fee). Check that x * y never decreases, that the price you get gets worse for bigger trades, and that swapping a tiny amount costs about the fee (DeFi, DAOs and Governance).

Python Solution 9: AMM swap math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 10 (hard): the halving supply

A Bitcoin-style chain starts with a reward of 50 coins per block, halved every 210,000 blocks, using integer satoshis (1 coin = 100,000,000 satoshis) and a right shift, so the reward rounds down. Compute the total supply when the reward reaches zero, and the supply after the first three eras (630,000 blocks). Then find the height at which the reward becomes zero (Bitcoin in Practice).

Python Solution 10: supply schedule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the Merkle proof for 9 items need more hashes than the proof for 8 items?

    Proof length is the number of levels above the leaves, about log2(n) rounded up. Eight leaves need 3 levels, nine need 4.
  2. 2. In exercise 8, why must the ledger stay unchanged when a transaction is rejected?

    State changes must be all or nothing. Validating first and mutating afterwards guarantees that.
  3. 3. In the AMM exercise, why does x times y grow slightly after each swap?

    The fee is taken from the input but not paid out, so reserves grow a little more than the constant-product rule alone requires.
  4. 4. Why do the halving calculations use integer satoshis and right shifts?

    Consensus rules must give identical results on every machine. Integer arithmetic is exact and deterministic, so it avoids rounding differences.

Summary

  • Hashing exercises showed leading zeros, the avalanche effect and canonical serialization.
  • Merkle roots and proofs use about log2(n) hashes, and odd levels pair the last hash with itself.
  • Mining cost is geometric: average attempts are about 16 to the power of the difficulty in hex zeros, with large variance.
  • Validation always checks first and changes state last, in chains and in UTXO ledgers.
  • Money rules, such as AMM swaps and supply schedules, use integer arithmetic so every node agrees.

Next: Blockchain Interview Questions, concise answers to the questions interviewers actually ask.