Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 41 ยท Projects

Project: A Wallet with Signed Transactions

Build a wallet in Python on the secp256k1 curve: key generation, ECDSA signing, addresses, balance tracking and a ledger that rejects forged transactions.

A blockchain wallet does not hold coins. It holds keys. The coins live on the ledger, and the wallet's job is to prove, with a digital signature, that a payment was authorized by the person who controls an address. In this project you build exactly that: a wallet that creates keys, derives an address, signs payments and tracks its balance, and a small ledger that accepts good transactions and rejects forged ones.

This time the signatures are real ECDSA on secp256k1, the curve used by Bitcoin and Ethereum. The earlier project used a tiny stand-in scheme (Project: A Complete Mini Blockchain). Here you write the curve arithmetic yourself from the ideas in Elliptic Curves in Plain Language, with large integers from Python.

Everything in this lesson is for learning. The code is not constant-time, derives keys from a text seed instead of strong randomness, and has not been reviewed. Never use hand-written cryptography to protect real money.

The pieces

flowchart LR
  S["Secret seed"] --> D["Private key d<br/>(a number below N)"]
  D -->|"d times G"| Q["Public key Q<br/>(a curve point)"]
  Q -->|"hash"| A["Address"]
  D -->|"sign(hash of tx)"| SIG["Signature (r, s)"]
  Q -->|"verify(tx, signature)"| OK["Accept or reject"]
  SIG --> OK

One secret produces the public key, the address and every signature; the public key lets anyone verify without learning the secret.

secp256k1 is the curve y^2 = x^3 + 7 over the integers modulo a huge prime P. A fixed base point G generates a group of prime order N. A private key is a number d between 1 and N - 1. The public key is the point Q = d * G (G added to itself d times, computed quickly by doubling). Going from d to Q is easy; going from Q back to d is the hard discrete logarithm problem.

Step 1: curve arithmetic, keys and ECDSA

The first TryIt contains the curve, key generation, signing and verification. Notice the sanity checks first: the base point must lie on the curve, and N * G must be the point at infinity. If any constant were mistyped, these checks would fail immediately.

An ECDSA signature is a pair (r, s):

  • Choose a secret per-signature number k; let r be the x-coordinate of k * G (mod N).
  • Compute s = k^-1 * (z + r * d) mod N, where z is the hash of the message.
  • To verify, compute w = s^-1, then the point (z*w) * G + (r*w) * Q; the signature is valid if its x-coordinate equals r.

The number k must never repeat and must not be guessable. If two signatures use the same k, anyone can solve for the private key, and this has really happened to wallets. Here k is derived deterministically from the private key and the message (the idea of RFC 6979), so it is different for every message and never needs a random number generator.

Python Step 1: secp256k1 keys and ECDSA

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.

Only the owner of d can produce a signature that verifies against Q. A changed message or a different public key fails. And because k is derived from the message, signing the same message twice gives the same signature, but two different messages never share a k.

Step 2: the wallet and the ledger

Now build the two sides of the system.

The wallet keeps the private key, derives the public key and address, and builds signed payments. It also keeps a counter (nonce) so each payment has a unique number. The wallet does not store a balance of its own; it asks the ledger, because the ledger is the source of truth.

The ledger is the verifier. For every incoming transaction it checks, in order:

  1. the address matches the public key included in the transaction,
  2. the public key is a valid point on the curve,
  3. the signature is correct for exactly the fields of the transaction,
  4. the nonce is the sender's next one (this stops replays),
  5. the sender can afford the amount.

Public keys travel in compressed form: 33 bytes made of a prefix (02 for even y, 03 for odd) and the x-coordinate. The verifier recovers y with a modular square root, which for this prime is simply pow(v, (P + 1) // 4, P).

Python Step 2: a wallet, a ledger and forged transactions

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 two fragile spots are worth studying. An edited amount fails because the signature covers the exact text from>to:amount#nonce; change anything and verify returns false. Eve cannot claim Alice's address, because an address is the hash of a public key, so changing from breaks the address check, while swapping in Alice's public key breaks the signature check (the signature was made with Eve's key).

Remember what the ledger never needed: Alice's private key, her password or her name. Authorization is purely mathematical. This is also why losing the key means losing the coins, and why stealing the key means stealing them (Keys, Addresses and Wallets).

Design notes and improvements

  • Wallet state is only a cache. The wallet's next_nonce is a convenience. If the wallet restarts, it should ask the ledger for the sender's current nonce.
  • Seed phrases. Real wallets derive many keys from one seed (the HD wallet idea), so a single backup recovers everything.
  • Hardware wallets keep d inside a device that only exports signatures, so malware on your computer cannot read it.
  • Address checksums. Real addresses include a checksum so that a mistyped character is detected before money moves.
  • Chain ID in the payload. A signature should name the network it is meant for; otherwise a transaction signed for a test network could be replayed on the main one.
  • Fees. Add a fee field to the signed payload and let the ledger collect it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a wallet actually hold?

    Coins exist as entries on the ledger. The wallet holds the private key that can sign transactions spending them.
  2. 2. Why can the ledger verify a signature without knowing the private key?

    ECDSA verification needs the public key, the signed bytes and the signature. The private key never leaves the wallet.
  3. 3. Eve takes a valid transaction from Alice and changes the amount from 10 to 60. What happens?

    The signature covers the exact bytes of the transaction. Any change makes verification fail, even if the amount would be affordable.
  4. 4. Why is reusing the ECDSA per-signature number k dangerous?

    With the same k in two signatures, the equations can be combined to solve for the private key. Deterministic derivation of k from the key and the message avoids this.
  5. 5. What protects against replaying an old, valid transaction?

    The ledger only accepts the sender's next nonce. A transaction that was already applied carries an old nonce and is rejected.

Summary

  • A wallet holds keys; the ledger holds balances. Authorization is a signature over the exact transaction fields.
  • A private key is a number d, the public key is the point d * G on secp256k1, and the address is a hash of the public key.
  • ECDSA signs with a per-signature secret k that must be unique and unpredictable; deriving it from the key and message avoids repeats.
  • The ledger checks address, key validity, signature, nonce and balance, which rejects edits, impersonation, replays and overspending.
  • Real wallets add seed phrases, checksums, hardware protection and chain identifiers.

Next: Project: Simulating a Multi-Node Network, where several nodes mine, gossip and resolve forks.