Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 41 ยท Building a Toy Blockchain

Transactions and the Mempool

Build signed transactions, validate them against balances and nonces, hold them in a mempool and assemble a block by fee, with live Python.

So far your blocks have carried arbitrary text. A real blockchain carries transactions: signed instructions such as "move 30 coins from this account to that one". Every node must be able to check, on its own, that a transaction is genuine and affordable, without asking anybody.

This lesson covers the journey of a transaction from creation to block. You will define the fields, sign with a small public-key scheme, write the validation rules, keep valid transactions in a waiting area called the mempool ("memory pool") and let a miner pick the best ones for the next block. For the cryptographic ideas behind the signing step, see Public-Key Cryptography Basics and Digital Signatures with a Toy Scheme.

What a transaction contains

An account-style transaction usually carries these fields:

Field Meaning
sender Who pays (identified by a public key or an address derived from it)
recipient Who receives
amount How much to move
fee What the sender offers the miner for including it
nonce A counter: the sender's 0th, 1st, 2nd... transaction
signature Proof the holder of the sender's private key approved exactly these fields

The nonce here is not the mining nonce from Proof of Work and Mining. It is a per-account sequence number. It makes every transaction unique, puts a sender's transactions in order and stops anyone from replaying an old signed transaction a second time. The next lesson, UTXO vs Account Model, shows an alternative design that does not need it.

The transaction id is the hash of the transaction's canonical bytes, so two nodes always compute the same id. The signature covers the same bytes, so changing any field breaks it.

A small signature scheme to sign with

Real chains use elliptic-curve signatures, which you will meet in Elliptic Curves in Plain Language. To keep this lesson self-contained we use a tiny Schnorr signature over a modular group. It has real public verification (anyone with the public key can check a signature) but only 62-bit numbers, so it is a toy and not secure. Never use code like this to protect value.

The scheme in four lines:

  • Secret key x, public key y = g^x mod p.
  • To sign message m: pick a nonce k, compute r = g^k, e = H(r, m), s = k + e*x.
  • The signature is the pair (e, s).
  • To verify: recompute r' = g^s * y^(-e) and check H(r', m) == e.

The signing nonce k is derived from the secret key and the message, so signing the same message twice gives the same signature and no random generator is needed. Reusing one k for two different messages would leak the secret key, a famous real-world failure.

Python Sign, verify and catch a forgery

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.

The output is:

TEXT
address: 74cbf94c3ccd
valid signature: True
changed amount:  False
wrong key:       False

Changing one character of the message or checking against the wrong public key makes verification fail.

An address is just a hash of the public key, a shorter and more convenient name for an account. Keys, Addresses and Wallets covers real address formats.

Validation rules

Before a node accepts a transaction, whether into its mempool or into a block, it checks a fixed list of rules. Every honest node must apply exactly the same rules, because the whole network has to agree on which transactions are valid.

  1. The signature is valid for the sender's public key over the exact transaction body.
  2. Amounts make sense: the amount is positive and the fee is not negative.
  3. The nonce is the next one expected from this sender.
  4. The sender can afford it: balance is at least amount + fee.
flowchart TD
    T["Incoming transaction"] --> S{"Signature valid?"}
    S -- "no" --> X["Reject"]
    S -- "yes" --> A{"Amount and fee sane?"}
    A -- "no" --> X
    A -- "yes" --> N{"Nonce is the next one?"}
    N -- "no" --> X
    N -- "yes" --> B{"Balance covers<br/>amount + fee?"}
    B -- "no" --> X
    B -- "yes" --> OK["Accept"]

A transaction must pass every check; failing any one rejects it.

Python A transaction class and its checks

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.

You should see:

TEXT
txid e3dadf01fb -> valid
signed by Bob: bad signature
amount edited: bad signature
too big: insufficient balance
replay/skip: wrong nonce (expected 0)

The forged transaction (claimed from Alice but signed with Bob's key) and the edited one both fail on the signature. The "too big" one is correctly signed but unaffordable. The last one fails the nonce rule; once Alice's first transaction is confirmed, her next valid nonce becomes 1.

Notice that the signature rule makes checks independent of trust. A node does not need to know Alice or ask her anything. The public key travels with the transaction, and the address is recomputed from it.

The mempool: where transactions wait

A new block arrives only every so often, but users send transactions all the time. Each node therefore keeps a waiting area for valid, not-yet-confirmed transactions, the mempool. A node that receives a transaction validates it, adds it to its own mempool and passes it on to its peers (see Peer-to-Peer Networking and Gossip).

Some things to know:

  • Each node has its own mempool. There is no single global one. Nodes see transactions at different moments and may apply different local policies, such as a minimum fee.
  • Transactions can be dropped or replaced. A full mempool evicts the lowest-fee transactions first. Some chains allow a sender to replace a waiting transaction by one with the same nonce and a higher fee.
  • Waiting is not confirmation. A transaction in the mempool is only a request. It becomes part of the ledger when a block containing it is accepted.
  • Conflicting transactions can wait together until one wins, which is why unconfirmed payments must not be trusted for valuable goods (The Double-Spend Problem and Byzantine Faults).

Choosing transactions for a block

Block space is limited, so a miner chooses. Since the miner keeps the fees, the natural strategy is to prefer the highest fees. Transactions from one sender have an internal order, though: nonce 1 cannot go in before nonce 0, no matter how high its fee. The assembler therefore walks the fee-sorted list repeatedly, taking only transactions that are valid right now given what it has already chosen.

Python A mempool and a greedy block builder

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.

The run prints:

TEXT
accepted | 74cb->52e9 amt=5 fee=1 n=0
accepted | 52e9->b567 amt=10 fee=4 n=0
accepted | 74cb->b567 amt=8 fee=9 n=1
accepted | b567->74cb amt=3 fee=6 n=0
accepted | 52e9->74cb amt=2 fee=2 n=1
accepted | b567->52e9 amt=100 fee=50 n=1
rejected: same sender and nonce already waiting | 74cb->b567 amt=1 fee=99 n=0

block of at most 4 transactions:
   b567->74cb amt=3 fee=6 n=0
   52e9->b567 amt=10 fee=4 n=0
   52e9->74cb amt=2 fee=2 n=1
   74cb->52e9 amt=5 fee=1 n=0
fees collected: 13
left in pool: 2

Follow the builder's choices. The transaction with the biggest fee (50) is skipped: Carol cannot afford 100 coins and its nonce is also not yet due. Alice's fee-9 transaction is skipped because her nonce 0 has not been included yet, and her nonce 0 has the lowest fee of the four winners, so it takes the last slot. The block is full, so Alice's fee-9 transaction stays in the pool for the next block. The duplicate (fee 99, same sender and nonce as an existing one) never entered the pool in the first place, because this simple mempool refuses a second transaction for the same sender and nonce. A real mempool would also check balances and nonces on arrival, as in the previous example. We left that to block assembly here to keep the code short.

Real miners solve a harder version of this problem, because transactions have different sizes and the block limit is measured in bytes or gas. They order by fee per unit of size, and the exact algorithm is a matter of policy rather than consensus: any selection of valid transactions makes a valid block.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the nonce inside an account-style transaction do?

    The transaction nonce is a per-account counter. Only the next expected value is valid, so a replayed transaction is rejected.
  2. 2. Why is a transaction in the mempool not yet final?

    The mempool is a local waiting area. Only inclusion in an accepted block changes the ledger.
  3. 3. Alice has nonce 0 and nonce 1 transactions waiting, and the nonce 1 transaction pays a much higher fee. What must a block builder do?

    Nonce 1 is only valid after nonce 0 has been applied, so the builder must respect the order.
  4. 4. Which of these checks needs the sender's public key?

    Signature verification uses the public key. The other checks use only the transaction fields and the ledger state.

Summary

  • A transaction names a sender, recipient, amount, fee and nonce, and carries a signature over exactly those fields.
  • Every node applies the same validation rules: valid signature, sane values, correct nonce, sufficient balance.
  • The mempool is each node's local waiting room for valid transactions, not a shared database and not a confirmation.
  • Miners pick transactions by fee but must respect each sender's nonce order and the balance at that point in the block.
  • The toy Schnorr scheme in this lesson shows the shape of real signatures but is far too small to be secure.

Next: UTXO vs Account Model, two different ways to record who owns what.