Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

Wallets, addresses and signatures

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

  • Explain what a wallet is: a key pair and an address derived from the public key
  • Lock an output to an address and unlock it with a signature
  • Sign an entire transaction (inputs and outputs) and verify each signature
  • Explain why a signature that does not cover the outputs lets a payment be diverted

A wallet is a key pair

A wallet does not contain money: it contains keys. The private key is used to sign; the public key lets everyone verify; the address is a short fingerprint of the public key, which you share to get paid (like an account number).

To keep the code short, we reuse the RSA signatures from the "Public-key cryptography" course, with keys built from well-known primes (so not secret: for learning only). Bitcoin and Ethereum use signatures on the secp256k1 elliptic curve (ECDSA or Schnorr), with exactly the same logic.

Then that the signature is valid for this exact transaction. Otherwise: rejected.

Step 5 of 5
Text description of the animation
  1. The output does not say "Awa": it says "to whoever can prove they hold the key of 68fd7b…".
  2. Awa prepares the complete transaction.
  3. The signature covers the whole transaction, inputs AND outputs.
  4. The node checks that the public key provided really matches the output's address.
  5. Then that the signature is valid for this exact transaction. Otherwise: rejected.
import hashlib
import json

E = 65537

def new_wallet(p, q):
    """Demonstration RSA key pair (well-known primes: never for real!)."""
    n = p * q
    return {"public": n, "private": pow(E, -1, (p - 1) * (q - 1))}

def address(public_key):
    return hashlib.sha256(str(public_key).encode()).hexdigest()[:16]

def fingerprint(data):
    return int.from_bytes(hashlib.sha256(json.dumps(data, sort_keys=True).encode()).digest(), "big")

def sign(wallet, data):
    return pow(fingerprint(data), wallet["private"], wallet["public"])

def verify(public_key, data, signature):
    return pow(signature, E, public_key) == fingerprint(data)

awa = new_wallet(2**521 - 1, 2**607 - 1)
kofi = new_wallet(2**127 - 1, 2**521 - 1)
print("Awa's address :", address(awa["public"]))
print("Kofi's address:", address(kofi["public"]))

tx = {"inputs": ["tx1:0"], "outputs": [{"to": "addr-fatou", "amount": 6000}, {"to": address(awa["public"]), "amount": 3900}]}
sig = sign(awa, tx)
print("signed by Awa, checked with Awa's key :", verify(awa["public"], tx, sig))
print("signed by Awa, checked with Kofi's key:", verify(kofi["public"], tx, sig))
print("Kofi's signature presented for Awa    :", verify(awa["public"], tx, sign(kofi, tx)))
Awa's address : 68fd7b0a3e46d34e
Kofi's address: cd9aef6789d3631a
signed by Awa, checked with Awa's key : True
signed by Awa, checked with Kofi's key: False
Kofi's signature presented for Awa    : False

Spending a locked output

Each output now names an address instead of a name. To spend it, the input must provide the public key (whose fingerprint must be the address) and a signature of the transaction. We sign the transaction without the signatures (otherwise we would go round in circles).

import hashlib
import json

E = 65537
def wallet(p, q): return {"public": p * q, "private": pow(E, -1, (p - 1) * (q - 1))}
def address(key): return hashlib.sha256(str(key).encode()).hexdigest()[:16]
def h(d): return int.from_bytes(hashlib.sha256(json.dumps(d, sort_keys=True).encode()).digest(), "big")

def to_sign(tx):
    """What is signed: the inputs (without signatures) and all the outputs."""
    return {"inputs": [i["output"] for i in tx["inputs"]], "outputs": tx["outputs"]}

def sign_input(tx, index, w):
    tx["inputs"][index]["key"] = w["public"]
    tx["inputs"][index]["signature"] = pow(h(to_sign(tx)), w["private"], w["public"])

def check_tx(tx, utxos):
    for i in tx["inputs"]:
        output = utxos.get(i["output"])
        if output is None:
            return f"{i['output']}: unknown output"
        if address(i.get("key")) != output["to"]:
            return f"{i['output']}: the key does not match the address"
        if pow(i.get("signature", 0), E, i["key"]) != h(to_sign(tx)):
            return f"{i['output']}: invalid signature"
    return "valid signatures"

awa, thief = wallet(2**521 - 1, 2**607 - 1), wallet(2**89 - 1, 2**607 - 1)
utxos = {"tx1:0": {"to": address(awa["public"]), "amount": 10000}}

payment = {"inputs": [{"output": "tx1:0"}], "outputs": [{"to": "addr-fatou", "amount": 9900}]}
sign_input(payment, 0, awa)
print("Awa pays Fatou      :", check_tx(payment, utxos))

theft = {"inputs": [{"output": "tx1:0"}], "outputs": [{"to": address(thief["public"]), "amount": 9900}]}
sign_input(theft, 0, thief)
print("the thief helps out :", check_tx(theft, utxos))
Awa pays Fatou      : valid signatures
the thief helps out : tx1:0: the key does not match the address

The thief can sign anything with their own key, but the fingerprint of that public key is not the address that locks the output: rejected. Without Awa's private key, there is no way to produce an accepted signature.

Mini-lab: your walletPython 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

Worked exercise: a joint payment

Awa and Kofi buy a mill together for 15,000 F CFA. Awa brings output tx1:0 (10,000) and Kofi brings output tx2:0 (7,000). Build a transaction with two inputs, a payment of 15,000 to the seller and 1,900 of change to Kofi. Each one signs their own input. Check the transaction, then show that it is rejected if Kofi also signs Awa's input in Awa's place.

Hint 1
Use sign_input(tx, 0, awa) then sign_input(tx, 1, kofi): each input receives its owner's public key and signature, over the same to_sign(tx) form.
Hint 2
All the signatures cover the same content; it is the address of each spent output that says which key must sign which input.
Show the solution and common mistakes
import hashlib
import json

E = 65537
def wallet(p, q): return {"public": p * q, "private": pow(E, -1, (p - 1) * (q - 1))}
def address(key): return hashlib.sha256(str(key).encode()).hexdigest()[:16]
def h(d): return int.from_bytes(hashlib.sha256(json.dumps(d, sort_keys=True).encode()).digest(), "big")

def to_sign(tx):
    return {"inputs": [i["output"] for i in tx["inputs"]], "outputs": tx["outputs"]}

def sign_input(tx, index, w):
    tx["inputs"][index]["key"] = w["public"]
    tx["inputs"][index]["signature"] = pow(h(to_sign(tx)), w["private"], w["public"])

def check_tx(tx, utxos):
    for i in tx["inputs"]:
        output = utxos.get(i["output"])
        if output is None or address(i.get("key")) != output["to"]:
            return f"{i['output']}: key missing or not matching the address"
        if pow(i["signature"], E, i["key"]) != h(to_sign(tx)):
            return f"{i['output']}: invalid signature"
    return "valid transaction"

awa, kofi = wallet(2**521 - 1, 2**607 - 1), wallet(2**127 - 1, 2**521 - 1)
utxos = {"tx1:0": {"to": address(awa["public"]), "amount": 10000},
         "tx2:0": {"to": address(kofi["public"]), "amount": 7000}}

purchase = {"inputs": [{"output": "tx1:0"}, {"output": "tx2:0"}],
            "outputs": [{"to": "addr-seller", "amount": 15000}, {"to": address(kofi["public"]), "amount": 1900}]}
sign_input(purchase, 0, awa)
sign_input(purchase, 1, kofi)
print(check_tx(purchase, utxos))

sign_input(purchase, 0, kofi)          # Kofi signs in Awa's place
print(check_tx(purchase, utxos))
valid transaction
tx1:0: key missing or not matching the address

Both signatures cover the same complete transaction: neither can change the seller or the amount without invalidating the other's signature. And each can only unlock their own output.

Common mistakes:

  • Including the signatures in the signed content: the second signature would change the first one's content, which would become invalid.
  • Checking the signature without checking that the key provided matches the address: anyone could supply their own key.
  • Leaving the implicit fees too high: here 100 F CFA; a mistake in the change can make a large sum "disappear" as fees.

Summary

  1. 1A wallet contains keys, not money; the address is a fingerprint of the public key.
  2. 2An output is locked to an address; spending it requires the matching public key and a valid signature.
  3. 3The signature must cover the whole transaction, outputs included, otherwise a relay can divert the payment.
  4. 4Losing the private key means losing the funds; having it stolen too: nobody can cancel.

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