Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 25 min

Project: your blockchain node

By the end of this chapter, you'll be able to

  • Assemble signed transactions, the UTXO set, the Merkle root and proof of work into a node
  • Build a block with a reward transaction equal to the reward plus the fees
  • Fully validate a received block: header, proof of work, Merkle root, reward and transactions
  • Test the node with deliberately invalid blocks

The node's architecture

A block that fails a single check is rejected entirely.

Step 5 of 5
Text description of the animation
  1. Signed transactions travel around and wait to be included.
  2. The block's first transaction creates the miner's reward, with no input.
  3. The root summarises all the block's transactions.
  4. Only the header is mined: it is small, and the root commits it to all the transactions.
  5. A block that fails a single check is rejected entirely.

Here is the node, on the miner's side. Transactions are signed as in the wallets chapter (demonstration keys built from well-known primes).

import hashlib
import json

E, REWARD, DIFFICULTY = 65537, 5000, 3

def h(o): return hashlib.sha256(json.dumps(o, sort_keys=True).encode()).hexdigest()
def wallet(p, q): return {"pub": p * q, "priv": pow(E, -1, (p - 1) * (q - 1))}
def address(pub): return h(str(pub))[:16]
def to_sign(tx): return {"inputs": [i["output"] for i in tx["inputs"]], "outputs": tx["outputs"]}
def sign(tx, k, w):
    tx["inputs"][k].update(key=w["pub"], sig=pow(int(h(to_sign(tx)), 16), w["priv"], w["pub"]))

def merkle_root(txs):
    level = [h(tx) for tx in txs]
    while len(level) > 1:
        if len(level) % 2: level.append(level[-1])
        level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0]

class Node:
    def __init__(self):
        self.utxos, self.chain, self.pending = {}, [], []

    def validate_tx(self, tx, utxos):
        if len({i["output"] for i in tx["inputs"]}) != len(tx["inputs"]) or not tx["inputs"]:
            return None
        total = 0
        for i in tx["inputs"]:
            o = utxos.get(i["output"])
            if o is None or address(i.get("key")) != o["to"] or pow(i.get("sig", 0), E, i["key"]) != int(h(to_sign(tx)), 16):
                return None
            total += o["amount"]
        out = sum(o["amount"] for o in tx["outputs"])
        return total - out if all(o["amount"] > 0 for o in tx["outputs"]) and out <= total else None

    def apply(self, txs, utxos):
        for tx in txs:
            for i in tx["inputs"]:
                del utxos[i["output"]]
            for n, o in enumerate(tx["outputs"]):
                utxos[f"{h(tx)[:8]}:{n}"] = o

    def mine(self, miner_address):
        utxos, chosen, fees = dict(self.utxos), [], 0
        for tx in self.pending:                       # keep the valid transactions, in order
            f = self.validate_tx(tx, utxos)
            if f is not None:
                chosen.append(tx); fees += f
                self.apply([tx], utxos)
        number = len(self.chain)
        txs = [{"inputs": [], "outputs": [{"to": miner_address, "amount": REWARD + fees}], "block": number}] + chosen
        header = {"number": number, "previous": self.chain[-1]["hash"] if self.chain else "0" * 64,
                  "root": merkle_root(txs), "nonce": 0}
        while not h(header).startswith("0" * DIFFICULTY):
            header["nonce"] += 1
        block = {"header": header, "hash": h(header), "txs": txs}
        self.apply(txs, self.utxos)
        self.chain.append(block)
        self.pending = [tx for tx in self.pending if tx not in chosen]
        return block

    def balance(self, addr):
        return sum(o["amount"] for o in self.utxos.values() if o["to"] == addr)

awa, kofi = wallet(2**521 - 1, 2**607 - 1), wallet(2**127 - 1, 2**521 - 1)
A, K = address(awa["pub"]), address(kofi["pub"])
node = Node()
b0 = node.mine(A)                                     # Awa mines the first block and earns 5,000

awa_output = next(k for k, o in node.utxos.items() if o["to"] == A)
tx = {"inputs": [{"output": awa_output}], "outputs": [{"to": K, "amount": 3000}, {"to": A, "amount": 1900}]}
sign(tx, 0, awa)
node.pending.append(tx)
b1 = node.mine(K)                                     # Kofi mines the next block and collects the fees

for b in node.chain:
    print(f"block {b['header']['number']} | nonce {b['header']['nonce']:>5} | {b['hash'][:12]}… | {len(b['txs'])} tx")
print("Awa's balance:", node.balance(A), "| Kofi's balance:", node.balance(K))
block 0 | nonce  2096 | 000f115abbb9… | 1 tx
block 1 | nonce  4941 | 0009a156ed47… | 2 tx
Awa's balance: 1900 | Kofi's balance: 8100

Kofi collects 5,000 in reward, 100 in fees and the 3,000 sent by Awa: 8,100. Awa keeps 1,900 in change. The header does not contain the transactions themselves, only their Merkle root: that is what makes it possible to mine a header of a few dozen bytes, whatever the number of transactions.

Mini-lab: difficulty and block sizePython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Project: the node that trusts nobody

Add to the Node class a method receive(block) that fully validates a block mined by another node, and only applies it if it passes every check. It returns "accepted" or the first reason for rejection. Checks, in order:

  1. number and link with the last block;
  2. proof of work of the header (and exact announced hash);
  3. Merkle root recomputed from the transactions;
  4. ordinary transactions valid, in order, on a copy of the UTXO set;
  5. the miner's reward less than or equal to REWARD + fees.

Test with an honest block, then with four booby-trapped blocks: replaced transactions, inflated reward, double spend, and a link to the wrong block.

Hint 1
To build the booby-trapped blocks, create a second "miner" Node that starts from the same state (same first block), mines a block, then modifies a copy (copy.deepcopy) of that block before sending it. For the inflated reward, re-mine the header after changing the amount, otherwise the root check fails first.
Hint 2
In receive, validate the transactions on utxos = dict(self.utxos) and add up the fees returned by validate_tx. Only call self.apply(block["txs"], self.utxos) at the very end.
Show the solution and common mistakes
import copy
import hashlib
import json

E, REWARD, DIFFICULTY = 65537, 5000, 3

def h(o): return hashlib.sha256(json.dumps(o, sort_keys=True).encode()).hexdigest()
def wallet(p, q): return {"pub": p * q, "priv": pow(E, -1, (p - 1) * (q - 1))}
def address(pub): return h(str(pub))[:16]
def to_sign(tx): return {"inputs": [i["output"] for i in tx["inputs"]], "outputs": tx["outputs"]}
def sign(tx, k, w):
    tx["inputs"][k].update(key=w["pub"], sig=pow(int(h(to_sign(tx)), 16), w["priv"], w["pub"]))
def merkle_root(txs):
    level = [h(tx) for tx in txs]
    while len(level) > 1:
        if len(level) % 2: level.append(level[-1])
        level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0]
def mine_header(header):
    header["nonce"] = 0
    while not h(header).startswith("0" * DIFFICULTY):
        header["nonce"] += 1

class Node:
    def __init__(self):
        self.utxos, self.chain, self.pending = {}, [], []

    def validate_tx(self, tx, utxos):
        if not tx["inputs"] or len({i["output"] for i in tx["inputs"]}) != len(tx["inputs"]):
            return None
        total = 0
        for i in tx["inputs"]:
            o = utxos.get(i["output"])
            if o is None or address(i.get("key")) != o["to"] or pow(i.get("sig", 0), E, i["key"]) != int(h(to_sign(tx)), 16):
                return None
            total += o["amount"]
        out = sum(o["amount"] for o in tx["outputs"])
        return total - out if all(o["amount"] > 0 for o in tx["outputs"]) and out <= total else None

    def apply(self, txs, utxos):
        for tx in txs:
            for i in tx["inputs"]:
                del utxos[i["output"]]
            for n, o in enumerate(tx["outputs"]):
                utxos[f"{h(tx)[:8]}:{n}"] = o

    def mine(self, addr):
        utxos, chosen, fees = dict(self.utxos), [], 0
        for tx in self.pending:
            f = self.validate_tx(tx, utxos)
            if f is not None:
                chosen.append(tx); fees += f; self.apply([tx], utxos)
        n = len(self.chain)
        txs = [{"inputs": [], "outputs": [{"to": addr, "amount": REWARD + fees}], "block": n}] + chosen
        header = {"number": n, "previous": self.chain[-1]["hash"] if self.chain else "0" * 64, "root": merkle_root(txs)}
        mine_header(header)
        return {"header": header, "hash": h(header), "txs": txs}

    def receive(self, block):
        hd = block["header"]
        expected = self.chain[-1]["hash"] if self.chain else "0" * 64
        if hd["number"] != len(self.chain) or hd["previous"] != expected:
            return "rejected: wrong number or link"
        if h(hd) != block["hash"] or not block["hash"].startswith("0" * DIFFICULTY):
            return "rejected: invalid proof of work"
        if merkle_root(block["txs"]) != hd["root"]:
            return "rejected: wrong Merkle root"
        utxos, fees = dict(self.utxos), 0
        for tx in block["txs"][1:]:
            f = self.validate_tx(tx, utxos)
            if f is None:
                return "rejected: invalid transaction or double spend"
            fees += f
            self.apply([tx], utxos)
        reward = block["txs"][0]
        if reward["inputs"] or sum(o["amount"] for o in reward["outputs"]) > REWARD + fees:
            return "rejected: reward too high"
        self.apply(block["txs"], self.utxos)
        self.chain.append(block)
        return "accepted"

awa, kofi = wallet(2**521 - 1, 2**607 - 1), wallet(2**127 - 1, 2**521 - 1)
A, K = address(awa["pub"]), address(kofi["pub"])

us, miner = Node(), Node()
b0 = miner.mine(A)
print("block 0:", us.receive(b0), "/", miner.receive(b0))

output = next(k for k, o in miner.utxos.items() if o["to"] == A)
payment = {"inputs": [{"output": output}], "outputs": [{"to": K, "amount": 3000}, {"to": A, "amount": 1900}]}
sign(payment, 0, awa)
double = {"inputs": [{"output": output}], "outputs": [{"to": K, "amount": 4900}]}
sign(double, 0, awa)

miner.pending = [payment]
honest = miner.mine(K)

replaced = copy.deepcopy(honest)
replaced["txs"][1]["outputs"][0]["to"] = "pirate-address"

inflated = copy.deepcopy(honest)
inflated["txs"][0]["outputs"][0]["amount"] = 50000
inflated["header"]["root"] = merkle_root(inflated["txs"])
mine_header(inflated["header"]); inflated["hash"] = h(inflated["header"])

double_block = copy.deepcopy(honest)
double_block["txs"].append(double)
double_block["header"]["root"] = merkle_root(double_block["txs"])
mine_header(double_block["header"]); double_block["hash"] = h(double_block["header"])

wrong_link = copy.deepcopy(honest)
wrong_link["header"]["previous"] = "f" * 64
mine_header(wrong_link["header"]); wrong_link["hash"] = h(wrong_link["header"])

for name, b in [("replaced transactions", replaced), ("inflated reward", inflated),
                ("double spend", double_block), ("wrong link", wrong_link), ("honest block", honest)]:
    print(f"{name:<22} → {us.receive(b)}")
print("Kofi's balance on our node:", sum(o["amount"] for o in us.utxos.values() if o["to"] == K))
block 0: accepted / accepted
replaced transactions  → rejected: wrong Merkle root
inflated reward        → rejected: reward too high
double spend           → rejected: invalid transaction or double spend
wrong link             → rejected: wrong number or link
honest block           → accepted
Kofi's balance on our node: 8100

Each booby-trapped block hits a different check, and our node only applies the honest block. Notice that the fraudster must re-mine the header for every change: proof of work costs computation, and the block is rejected anyway.

Common mistakes:

  • Applying the transactions one by one directly on self.utxos: if the third fails, the node's state is corrupted.
  • Validating the reward before adding up the fees: an honest block with fees would be rejected.
  • Forgetting to check that the reward transaction has no input: it could spend outputs without a signature.

Summary

  1. 1A node keeps the UTXO set, collects pending transactions, builds and mines blocks.
  2. 2The reward transaction creates at most the reward plus the fees; it has no input.
  3. 3The header is mined; the Merkle root in it commits to all the block's transactions.
  4. 4A received block is fully validated (link, work, root, transactions, reward) before being applied, all or nothing.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.