WORKINGPROJECTCHAPTER 18

Project: a wallet with funding, transfers, refunds and daily reconciliation

Build the wallet that survives lost responses, repeated webhooks and timed-out payouts, then prove it with a reconciliation that ends at zero unexplained breaks

210 MINPAYMENTSUPDATED 2026-11-14

You build a working wallet service on the ledger you wrote in the module 1 project. It takes funding by card (through the mock provider) and by bank transfer (through the mock switch, into virtual accounts). It moves money between wallets, pays out to other banks, refunds card fundings, and runs a daily reconciliation against the provider’s settlement report and the switch’s transfer report. Then you run 1,000 operations through it while both mocks lose responses, repeat messages, time out and reverse payouts, and read what the reconciliation says.

Everything is standard-library Python. Every limit, fee, bank code and response code in the lab is illustrative, set by the generator and the mocks. They are not the CBN’s, NIBSS’s or any scheme’s. The payment rules a real Owoleaf would need to follow (wallet limits, licence conditions, settlement timetables) are for the chapters on wallets and on settlement in this module to source and date. Nothing in this project depends on them.

What you are building

Four pieces, each small enough to read in one sitting.

Piece File Job
The ledger ledger.py Your module 1 file, unchanged. The posting function is still the only door to the tables
The wallet wallet.py Operations, their states, the provider and switch calls, the receiver for webhooks and callbacks, and the sweep
The reconciliation reconcile.py Ledger against provider, ledger against switch, and the double-payment audit
The drivers scenarios.py, load.py One case at a time with forced outcomes, then 1,000 operations with random faults

The wallet adds two things to the ledger’s tables. An ops table, one row per customer request, and a unique index on (kind, external_ref) in transactions. The ops row remembers what the customer asked for and how far it got. The index is a second lock on duplicates, behind the ledger’s own check on the transaction id: a ledger entry for the same kind of event and the same reference cannot be written twice, even if every other safeguard has a bug.

One request, one row, one state machine

The core idea is that a request is never “in the code”. It is a row. When a customer asks to fund by card, the wallet writes an ops row with the customer’s request key and the state charging before it calls the provider. If the process dies, if the answer is lost, or if two threads look at the same request, the row says what happened so far.

The request key is also the reference everywhere else: the provider charge’s reference and Idempotency-Key, the switch transfer’s payment_reference, and the narration OP <key>. One key means the wallet, the provider and the switch can be lined up afterwards, and a retry carries the same key, so the other side can recognise it. The chapter on idempotency and moving money exactly once teaches the mechanism; the lesson on idempotency lets you break it. Here you use it.

Every change of state happens inside BEGIN IMMEDIATE, in the same SQLite transaction as the ledger posting that goes with it. The state credited and the funding entries appear together or not at all. This is the same rule as the all-or-nothing posting in the module 1 ledger, one level up: the ledger protects the books, and the transaction protects the pairing between the operation and the books.

Operation States Ledger postings
Card funding charging, pending, credited or failed (mismatch if the provider disagrees) funding_card: debit card_clearing, credit the wallet and fee_revenue
Bank funding credited (or unapplied) funding_transfer: debit settlement_bank, credit the wallet
Wallet to wallet done or refused p2p_transfer
Payout held, sent, settled, failed, reversed or refused payout_hold, then payout_nip or payout_release, then maybe payout_reversal
Refund held, pending, processed or failed refund_hold, then refund_settle or refund_release

A message is a hint, the provider’s record is the fact

The provider tells the wallet about a charge in three ways: the response to the charge request, a webhook, and the answer to GET /charges/{reference}. The first two can be lost, repeated, forged or out of order. The third is the provider’s own record. So the wallet has one function, settle_charge, that every path ends in, and the function ignores what it was told. It asks the provider what it holds and acts on that.

That one choice removes three bugs at once. A forged webhook cannot credit a wallet, because the wallet does not read the body for the amount: it asks. A repeated webhook finds the operation already credited and does nothing. A response lost after the charge succeeded (the mock’s test card 0005, and 5% of charges when you set --lost-response-rate 0.05) is handled by retrying the same request with the same Idempotency-Key. The provider replays its stored answer, with no second charge. The signature check on the webhook still matters: it keeps the receiver from doing work for strangers. It is not what protects the money.

The receiver is a small http.server that checks the signature (HMAC-SHA512 for the provider, HMAC-SHA256 for the switch, over the raw body), hands the event to the wallet, and answers 200. If handling raises, it answers 500, so the sender tries again. Recording the event id in a seen table happens after the handling, and only to count repeats. If the id were recorded before and the handler then crashed, the redelivery would be ignored and the money lost. The state machine is what makes repeats safe. The seen table only counts them.

Money in flight: hold, send, settle or release

A payout is the dangerous operation, because the answer from the switch can be yes, no, or nothing. The wallet handles it in four steps.

  1. Hold. In one transaction, write the ops row and post a payout_hold: debit the wallet, credit a liability account called in_flight, for the amount plus the fee. The ledger refuses it if the wallet cannot cover that. The customer’s money is no longer spendable, and no fee income is recognised yet.
  2. Check the beneficiary. A name enquiry. If it says the account does not exist, nothing has been sent, so the hold is released.
  3. Send once. POST /transfers with the operation key as payment_reference, and a client timeout of three seconds. An approval (00) settles the hold: debit in_flight, credit settlement_bank for the amount and fee_revenue for the fee. A refusal that happens before money moves (07, 13, 57, 61, 91) releases the hold back to the wallet.
  4. In doubt. Anything else (09 in progress, 97 timeout, 96 malfunction, no answer at all) leaves the money held and the state sent. The wallet does not send again. The sweep, which runs every second, asks the switch by payment_reference (a requery) until the status is successful or failed, and then settles or releases.

Holding before sending is the order that cannot lose money. The other order (send, then debit) leaves a window where the switch has paid out and the wallet still shows the balance. A customer who is quick can spend it twice. The cost of the hold is the in_flight account, which must be zero whenever nothing is open: a check the reconciliation makes.

The fourth case is where the Friday incident came from. After a timeout the switch may have paid or not, and the wallet cannot know from the failed call. The only safe moves are to wait, or to ask. A retry under a new reference is a new payment as far as the switch is concerned. A retry under the same reference would get code 26 (duplicate) and the first attempt’s status, which is safe, but it still does not tell you more than a requery does. The wallet’s --naive flag, which you meet at the end, re-creates the Friday bug on purpose.

Late reversals

There is a fifth outcome that no requery during the payout can catch. The switch can approve a transfer, return 00, and some seconds later flip it to reversed: the beneficiary’s bank sent the money back. The mock does this with --reverse-rate. The wallet has already settled the payout, so a new posting is needed, and the lab’s ledger already has the shape for it from module 1: a payout_reversal that debits settlement_bank and fee_revenue and credits the wallet for the amount plus the fee, pointing at the original payout and carrying its reference, and the original marked reversed. The posted entries are never edited. The original’s status column changes, as in the lab’s generated data, and check.py invariant 5 holds it to the pairing.

The wallet does not requery settled payouts to look for reversals. The reconciliation finds them. That is a design choice, and it is the one that makes the reconciliation do real work: the report is where late changes arrive, and a wallet that depended on polling every old payout forever would be slower and still incomplete. The job classifies a payout that the switch says is reversed and the ledger says is settled as an explained break, and repairs it with the same apply_reversal function the sweep uses.

Refunds

A refund returns card money to the customer’s card, so it must take the money out of the wallet. The wallet does that first, as a hold into in_flight, because the customer may have spent the funding already. If the wallet cannot cover it, the ledger refuses the hold and no provider call is made. If it can, the wallet asks the provider for the refund, and on refund.processed (verified by GET /refunds/{id}) it settles the hold against card_clearing: the money that Owoleaf expects from the processor falls by the refund.

Two choices here are the lab’s, not the world’s. The wallet does not refund the fee it charged on funding, so refunding a whole funding takes more out of the wallet than the funding put in, by the fee. And the mock’s refund call has no idempotency key, so the wallet makes it once and never retries blind. If that one call gets no clear answer (no reply, or a 5xx), the refund may exist, so the hold stays and the state stays held. Only a definite refusal releases it. The reconciliation then shows the difference for a person to settle. A real provider’s API says what it supports, which you check at the source.

Reconciliation: three comparisons and a verdict

The daily job compares the wallet’s ledger with two outside records that the wallet did not write. Each comparison has the same three outcomes for a line.

  • Matched. Both sides agree on the reference, the amount and the state.
  • Explained. The sides differ for a reason the job can name from the data: a card captured and not yet credited, a payout still pending at the switch, a late reversal, an inward credit whose callback never arrived. The job repairs what it can, through the wallet’s own functions, so a repair is posted by the same code, with the same checks, as anything else.
  • Unexplained. Nothing fits. The job prints the line and exits with status 1, and a person decides.

The three comparisons are these.

Cards. The provider’s settlement report for the day after capture lists every captured charge, the day’s processed refunds, a gross, the processor fee (1% in the lab), and a net. The job matches the report’s lines to the ledger’s funding_card transactions by reference and amount, matches refunds, recomputes the fee and the net from the lines, and checks that card_clearing holds exactly captures minus refunds. Only then does it post the card_settlement: debit settlement_bank for the net, debit processing_expense for the fee, credit card_clearing for captures minus refunds. It is the same entry the generated ledger posts each morning. The job posts it under a reference that carries the settlement date, so running the job twice posts it once.

The switch. The transfer report lists every outward and inward transfer with its status. Outward transfers are matched to payout operations by payment_reference, and a status table decides the class: successful with settled is a match, reversed with settled is a late reversal, pending with sent is in flight. Inward transfers are matched by session id to bank fundings. A transfer at the switch with no operation behind it is always unexplained. So is a settled payout the switch has never heard of. Finally the switch’s net position for the day (inward plus returned minus outward) must equal the net movement on settlement_bank for the same kinds of transaction.

Nobody paid twice. The net position can balance while a customer is paid twice, if another error offsets it. So the job also counts, for each intent (the narration OP <key>), the successful outward transfers at the switch, and for each card intent the successful captures at the provider. More than one is a double payment, and a break.

There is a limit to this. The lab has no bank statement for live operations, so the settlement account’s third leg, the partner bank’s own view, is not checked here. The reconciliation chapter in this module reconciles against the statement on the generated data, where nine breaks are planted. Here the switch report stands in for the bank’s side of the instant-payment flows and the provider’s report for the card flows.

What the design does not cover

State the gaps before you trust the result.

  • A crash between the hold and the send. The operation stays held, and the sweep does not look at held. A production wallet needs a rule for this, such as requerying by reference and releasing only when the switch has no record. The lab’s reconciliation does not list it either, because the load never crashes the process.
  • A payout the switch has no record of. If a request never arrived, the requery answers 25 (unable to locate record) and the operation stays sent, with the money held. The lab’s switch never loses a request outright, so this does not happen here. A production wallet needs a rule, such as a second requery after a stated wait and then a release that a person approves.
  • A refund in doubt. The held refund above has no way to resolve itself in the lab, because the mock offers no lookup by charge. A person checks the provider’s own record, and the reconciliation’s refund comparison and its in_flight check are what bring it to them.
  • Policy limits. The ledger refuses overdrafts. Balance caps, daily limits and KYC tiers belong to a layer in front, as module 1 argued. This wallet has none.
  • Several processes. One process holds one SQLite connection behind a lock. Several service instances would need the claim-then-act discipline on a shared database. The module 3 chapter on a ledger at scale starts from there.
  • Real rules. Settlement timetables, reversal windows, limits and licences are the regulator’s and the scheme’s. They go in the chapters that cite them.

One bug from building this is worth keeping, because the ledger caught it. The first version recorded an attempt count after the provider call with a plain state update. The once-a-second sweep, running in another thread, had already verified the charge and moved the operation to credited. The late update put it back to charging, and the next verification tried to credit it again. The ledger refused it as a duplicate, so no money moved twice, but the service crashed with an exception. The fix was a rule: a note on an operation never touches its state. Two locks, the state machine and the unique reference, are there so that the second catches what the first misses.

Lab

LAB Build the wallet, break it on purpose, and reconcile the day ~150 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated at seed 42 (python3 generate.py), and your ledger.py from the module 1 projectTwo terminals for the mocks, and about 10 minutes of run time in all

You work in labs/finance. You add four files: wallet.py, reconcile.py, scenarios.py and load.py. Your ledger.py from the module 1 project stays as it is. Ports are the defaults: the provider on 8101, the switch on 8102 and the wallet’s receiver on 9000. Timings are the mocks’ defaults, so the load run takes about 75 seconds. Your counts will differ a little from the ones below, because the mocks’ random choices interleave with timing. The lines that must not differ are marked in each step.

1. Start the two mocks with the faults on. Use two terminals. The flags set this chapter’s fault rates: 5% declines, 5% lost responses and 20% repeated webhooks at the provider; 5% timeouts, 10% pending answers and 2% late reversals at the switch. Both point their messages at the wallet’s receiver. --fresh clears their state.

cd labs/finance
python3 mock_provider.py --fresh --webhook-url http://127.0.0.1:9000/provider --decline-rate 0.05 --lost-response-rate 0.05 --webhook-dup-rate 0.2
cd labs/finance
python3 mock_switch.py --fresh --callback-url http://127.0.0.1:9000/switch --timeout-rate 0.05 --pending-rate 0.1 --reverse-rate 0.02
mock_provider on http://127.0.0.1:8101  secret sk_test_owoleaf_mock  webhooks -> http://127.0.0.1:9000/provider
mock_switch on http://127.0.0.1:8102  institution P01  key sw_test_owoleaf_mock  callbacks -> http://127.0.0.1:9000/switch

Leave both running. The scenario script resets them and turns the faults off for its forced cases, and the load script needs them on, so after the scenarios you restart both with the same commands.

2. Save the wallet. Save this as wallet.py. Read payout, settle_charge and apply_reversal before you run anything: they are the chapter’s argument in code.

"""Owoleaf's wallet service: funding by card and by bank transfer, wallet-to-wallet transfers,
payouts and refunds, on top of the module 1 ledger (ledger.py, unchanged). Money is integer kobo.

Every external call can be lost, repeated or answered late, so every operation is a row in `ops`
with a state, and every change of state happens in one SQLite transaction with its ledger posting.
"""
import datetime as dt
import hashlib
import hmac
import json
import sqlite3
import threading
import time
import urllib.error
import urllib.request
from collections import Counter
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from generate import CARD_FEE_CAP, CARD_FEE_RATE, NAIRA, WAT, payout_fee   # the lab's illustrative fees
from ledger import SCHEMA, Refused, post, record_failed

PROVIDER_KEY = "sk_test_owoleaf_mock"   # bearer token for the provider, and its webhook HMAC key
SWITCH_KEY = "sw_test_owoleaf_mock"     # bearer token for the switch, and its callback HMAC key

OPS = """
CREATE TABLE ops (
  op_key      TEXT PRIMARY KEY,        -- the customer's request: repeating it finds this row
  kind        TEXT NOT NULL,           -- fund_card, fund_bank, p2p, payout, refund
  customer_id INTEGER NOT NULL,
  amount_kobo INTEGER NOT NULL,
  fee_kobo    INTEGER NOT NULL DEFAULT 0,
  state       TEXT NOT NULL,
  ref         TEXT,                    -- a refund's provider id, an inward credit's session id
  detail      TEXT,
  parent      TEXT,                    -- a refund's funding operation
  updated_at  TEXT NOT NULL
);
CREATE TABLE seen (source TEXT NOT NULL, event_id TEXT NOT NULL, PRIMARY KEY (source, event_id));
CREATE TABLE virtual_accounts (account_number TEXT PRIMARY KEY, customer_id INTEGER NOT NULL);
CREATE UNIQUE INDEX txn_kind_ref ON transactions (kind, external_ref);   -- the second lock on duplicates
"""
OPEN_STATES = ("charging", "pending", "sent")   # the sweep looks at these again


def now_iso():
    return dt.datetime.now(WAT).isoformat(timespec="milliseconds")


def create(path, n_customers):
    """A new wallet database: the ledger's tables, ours, the company accounts, one wallet per customer."""
    import os
    if os.path.exists(path):
        os.remove(path)
    db = sqlite3.connect(path, isolation_level=None)
    db.executescript(SCHEMA)
    db.executescript(OPS)
    company = [("settlement_bank", "asset", 1), ("card_clearing", "asset", 1), ("share_capital", "equity", 1),
               ("fee_revenue", "income", 1), ("processing_expense", "expense", 1), ("in_flight", "liability", 0)]
    rows = [(i, code, code, typ, None, "NGN", now_iso(), ok) for i, (code, typ, ok) in enumerate(company, 1)]
    rows += [(len(company) + c, f"wallet:{c}", f"Wallet of C{c:07d}", "liability", c, "NGN", now_iso(), 0)
             for c in range(1, n_customers + 1)]
    db.executemany("INSERT INTO accounts VALUES (?, ?, ?, ?, ?, ?, ?, ?)", rows)
    capital = 50_000_000 * NAIRA        # the company's own money, so the settlement account starts positive
    post(db, dict(id=1, kind="capital_injection", status="succeeded", amount_kobo=capital, fee_kobo=0, rail="internal",
                  external_ref="CAPITAL-0001", created_at=now_iso()),
         [(1, "debit", capital), (3, "credit", capital)], now_iso())
    db.close()


class Api:
    """A JSON client that never raises: (status, body), or (None, why) when no answer arrived."""

    def __init__(self, base, key):
        self.base, self.key = base, key

    def call(self, method, path, body=None, headers=None, timeout=5):
        req = urllib.request.Request(
            self.base + path, method=method, data=None if body is None else json.dumps(body).encode(),
            headers=dict({"Authorization": f"Bearer {self.key}", "Content-Type": "application/json"}, **(headers or {})))
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return r.status, json.loads(r.read() or b"{}")
        except urllib.error.HTTPError as e:
            return e.code, json.loads(e.read() or b"{}")
        except Exception as e:              # a timeout or a refused connection: we do not know what happened
            return None, str(e)


class Wallet:
    def __init__(self, path, provider, switch, naive=False):
        # ledger.connect() ties a connection to one thread; the service has three, so we open our own.
        self.db = sqlite3.connect(path, isolation_level=None, check_same_thread=False)
        self.db.row_factory = sqlite3.Row
        self.db.execute("PRAGMA foreign_keys = ON")
        self.lock = threading.RLock()
        self.provider, self.switch, self.naive = provider, switch, naive
        self.acct = {code: i for i, code in self.db.execute("SELECT id, code FROM accounts")}
        self.stats = Counter()
        self.servers = []

    # --- plumbing ---------------------------------------------------------------------------
    @contextmanager
    def tx(self):
        """One writer at a time, and the state change commits together with its posting."""
        with self.lock:
            self.db.execute("BEGIN IMMEDIATE")
            try:
                yield
                self.db.execute("COMMIT")
            except BaseException:
                self.db.execute("ROLLBACK")
                raise

    def query(self, sql, *params):
        """Every read from outside the wallet goes through here: one connection, one thread at a time."""
        with self.lock:
            return self.db.execute(sql, params).fetchall()

    def w(self, customer_id):
        return self.acct[f"wallet:{customer_id}"]

    def balance(self, customer_id):
        with self.lock:
            return self.db.execute(
                """SELECT COALESCE(SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END), 0)
                   FROM entries WHERE account_id = ?""", (self.w(customer_id),)).fetchone()[0]

    def op(self, key):
        with self.lock:
            return self.db.execute("SELECT * FROM ops WHERE op_key = ?", (key,)).fetchone()

    def state(self, key):
        row = self.op(key)
        return row["state"] if row else None

    def _begin(self, key, kind, customer_id, amount, fee=0, state="new", ref=None, parent=None):
        """Insert the operation. False means this key was seen before: the request is a repeat."""
        try:
            self.db.execute("INSERT INTO ops VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)",
                            (key, kind, customer_id, amount, fee, state, ref, parent, now_iso()))
            return True
        except sqlite3.IntegrityError:
            return False

    def _set(self, key, state, detail=None, ref=None):
        self.db.execute("UPDATE ops SET state = ?, detail = COALESCE(?, detail), ref = COALESCE(?, ref), updated_at = ? "
                        "WHERE op_key = ?", (state, detail, ref, now_iso(), key))

    def _note(self, key, text):
        """A note on the operation. It never touches the state: the sweep may have moved it on already."""
        with self.tx():
            self.db.execute("UPDATE ops SET detail = ? WHERE op_key = ?", (text, key))

    def _txn(self, kind, ref, amount=0, fee=0, customer=None, counterparty=None, rail="internal", related=None,
             status="succeeded", reason=None):
        tid = self.db.execute("SELECT COALESCE(MAX(id), 0) + 1 FROM transactions").fetchone()[0]
        return dict(id=tid, kind=kind, status=status, failure_reason=reason, customer_id=customer,
                    counterparty_customer_id=counterparty, amount_kobo=amount, fee_kobo=fee, rail=rail,
                    external_ref=ref, related_transaction_id=related, created_at=now_iso())

    def _post(self, kind, ref, legs, **kw):
        """The only way in: refuse a repeated (kind, reference) first, then the module 1 posting function."""
        if self.db.execute("SELECT 1 FROM transactions WHERE kind = ? AND external_ref = ?", (kind, ref)).fetchone():
            raise Refused("duplicate", f"{kind} {ref} is already posted")
        txn = self._txn(kind, ref, **kw)
        post(self.db, txn, legs, txn["created_at"])
        return txn["id"]

    def _refuse(self, key, kind, ref, reason, **kw):
        record_failed(self.db, self._txn(kind, ref, status="failed", reason=reason, **kw))
        self._set(key, "refused", reason)

    # --- funding by card (the provider) -----------------------------------------------------------
    def fund_card(self, cid, amount, card, key):
        fee = min(CARD_FEE_CAP, round(amount * CARD_FEE_RATE))
        with self.tx():
            fresh = self._begin(key, "fund_card", cid, amount, fee, state="charging")
        if not fresh:
            return self.state(key)
        body = {"reference": key, "amount_kobo": amount, "customer_ref": f"C{cid:07d}", "card_number": card,
                "metadata": {"op": key}}
        for attempt in range(1, 4):
            status, out = self.provider.call("POST", "/charges", body, {"Idempotency-Key": key})
            if status == 200:
                break
            if status is not None and status < 500:
                with self.tx():
                    self._set(key, "failed", f"provider refused: {out}")
                return "failed"
            time.sleep(0.2 * attempt)       # a 500 or no answer: ask again, with the same reference and key
        else:
            self._note(key, "no answer; the sweep will ask the provider")
            return "charging"
        self._note(key, f"attempts={attempt}")
        return self.settle_charge(key)

    def settle_charge(self, key):
        """The one place a charge becomes money: ask the provider what it holds and act on that,
        never on the message or the response that told us to look."""
        status, out = self.provider.call("GET", f"/charges/{key}")
        if status != 200:
            return self.state(key)
        charge = out["charge"]
        with self.tx():
            row = self.op(key)
            if row is None or row["state"] not in ("charging", "pending"):
                self.stats["already settled"] += 1
                return row and row["state"]
            if charge["status"] == "success":
                if charge["amount_kobo"] != row["amount_kobo"] or charge["customer_ref"] != f"C{row['customer_id']:07d}":
                    self._set(key, "mismatch", f"provider holds {charge['amount_kobo']} for {charge['customer_ref']}")
                    return "mismatch"
                amount, fee, cid = row["amount_kobo"], row["fee_kobo"], row["customer_id"]
                self._post("funding_card", key, [(self.acct["card_clearing"], "debit", amount),
                                                 (self.w(cid), "credit", amount - fee),
                                                 (self.acct["fee_revenue"], "credit", fee)],
                           amount=amount, fee=fee, customer=cid, rail="card")
                self._set(key, "credited")
            elif charge["status"] == "failed":
                self._set(key, "failed", charge["gateway_response"])
            else:
                self._set(key, "pending")
            return self.state(key)

    # --- funding by bank transfer (the switch) ------------------------------------------------------
    def virtual_account(self, cid):
        with self.lock:
            row = self.db.execute("SELECT account_number FROM virtual_accounts WHERE customer_id = ?", (cid,)).fetchone()
        if row:
            return row[0]
        status, out = self.switch.call("POST", "/virtual-accounts", {"customer_ref": f"C{cid:07d}"})
        with self.tx():
            self.db.execute("INSERT OR IGNORE INTO virtual_accounts VALUES (?, ?)", (out["account_number"], cid))
        return out["account_number"]

    def on_inward(self, session_id, number, amount):
        """An inward credit, from a callback or from reconciliation. Once per session id, whoever tells us."""
        with self.tx():
            row = self.db.execute("SELECT customer_id FROM virtual_accounts WHERE account_number = ?", (number,)).fetchone()
            cid = row[0] if row else (int(number[1:]) if number.startswith("9") else None)
            if cid is None or f"wallet:{cid}" not in self.acct:
                self._begin(session_id, "fund_bank", 0, amount, state="unapplied", ref=session_id)
                return "unapplied"           # money with no owner is never dropped: reconciliation lists it
            if not self._begin(session_id, "fund_bank", cid, amount, state="credited", ref=session_id):
                self.stats["inward repeats"] += 1
                return "repeat"
            self._post("funding_transfer", session_id, [(self.acct["settlement_bank"], "debit", amount),
                                                        (self.w(cid), "credit", amount)],
                       amount=amount, customer=cid, rail="nip")
            return "credited"

    # --- wallet to wallet ---------------------------------------------------------------------------------
    def p2p(self, a, b, amount, key):
        with self.tx():
            if not self._begin(key, "p2p", a, amount, state="done"):
                return self.state(key)
            try:
                self._post("p2p_transfer", key, [(self.w(a), "debit", amount), (self.w(b), "credit", amount)],
                           amount=amount, customer=a, counterparty=b)
            except Refused as r:
                self._refuse(key, "p2p_transfer", key, r.reason, amount=amount, customer=a, counterparty=b)
            return self.state(key)

    # --- payouts (the switch) --------------------------------------------------------------------------------
    def payout(self, cid, amount, bank, account, key, force=None, timeout=3):
        """Hold the money first, send once, and follow the transfer to its end by requery."""
        fee = payout_fee(amount)
        total = amount + fee
        with self.tx():
            if not self._begin(key, "payout", cid, amount, fee, state="held"):
                return self.state(key)
            try:
                self._post("payout_hold", key, [(self.w(cid), "debit", total), (self.acct["in_flight"], "credit", total)],
                           amount=amount, fee=fee, customer=cid, rail="nip")
            except Refused as r:
                self._refuse(key, "payout_nip", key, r.reason, amount=amount, fee=fee, customer=cid, rail="nip")
                return "refused"
        status, ne = self.switch.call("POST", "/name-enquiry", {"bank_code": bank, "account_number": account})
        if status != 200 or ne.get("response_code") != "00":
            return self._release(key, f"name enquiry: {ne if status else 'no answer'}")   # nothing was sent
        body = {"payment_reference": key, "name_enquiry_ref": ne["name_enquiry_ref"], "sender_account": f"9{cid:09d}",
                "amount_kobo": amount, "narration": f"OP {key}"}
        status, out = self.switch.call("POST", "/transfers", body, {"X-Mock-Force": force} if force else None, timeout)
        if self.naive and status != 200:     # the bug this chapter warns about: a new reference on every retry
            body["payment_reference"] = f"{key}-retry"
            status, out = self.switch.call("POST", "/transfers", body, None, timeout)
        code = out.get("response_code") if status == 200 else None
        if code == "00":
            return self.settle_payout(key)
        if code in ("07", "13", "57", "61", "91"):          # refused before anything moved: safe to give back
            return self._release(key, f"switch said {code}")
        with self.tx():                                      # 09, 97, 96 or no answer: in doubt, never retried blind
            self._set(key, "sent", f"switch said {code or 'nothing'}")
        return "sent"

    def settle_payout(self, key):
        with self.tx():
            row = self.op(key)
            if row["state"] not in ("held", "sent"):
                return row["state"]
            amount, fee, total = row["amount_kobo"], row["fee_kobo"], row["amount_kobo"] + row["fee_kobo"]
            self._post("payout_nip", key, [(self.acct["in_flight"], "debit", total),
                                           (self.acct["settlement_bank"], "credit", amount),
                                           (self.acct["fee_revenue"], "credit", fee)],
                       amount=amount, fee=fee, customer=row["customer_id"], rail="nip")
            self._set(key, "settled")
            return "settled"

    def _release(self, key, why):
        with self.tx():
            row = self.op(key)
            if row["state"] not in ("held", "sent"):
                return row["state"]
            total = row["amount_kobo"] + row["fee_kobo"]
            self._post("payout_release", key, [(self.acct["in_flight"], "debit", total),
                                               (self.w(row["customer_id"]), "credit", total)],
                       amount=row["amount_kobo"], fee=row["fee_kobo"], customer=row["customer_id"], rail="nip")
            self._set(key, "failed", why)
            return "failed"

    def check_payout(self, key):
        """Requery by our own reference. 09 means wait; anything unclear means ask again later."""
        status, out = self.switch.call("POST", "/tsq", {"payment_reference": key})
        if status != 200 or out.get("response_code") in ("96", "25"):
            return self.state(key)
        if out["status"] == "successful":
            return self.settle_payout(key)
        if out["status"] == "failed":
            return self._release(key, "requery: failed")
        if out["status"] == "reversed":
            self.settle_payout(key)
            return self.apply_reversal(key)
        return self.state(key)

    def apply_reversal(self, key):
        """The switch returned a payout it had approved: money and fee go back to the wallet."""
        with self.tx():
            row = self.op(key)
            if row["state"] != "settled":
                return row["state"]
            tid = self.db.execute("SELECT id FROM transactions WHERE kind = 'payout_nip' AND external_ref = ?",
                                  (key,)).fetchone()[0]
            amount, fee = row["amount_kobo"], row["fee_kobo"]
            self._post("payout_reversal", key, [(self.acct["settlement_bank"], "debit", amount),
                                                (self.acct["fee_revenue"], "debit", fee),
                                                (self.w(row["customer_id"]), "credit", amount + fee)],
                       amount=amount, fee=fee, customer=row["customer_id"], rail="nip", related=tid)
            self.db.execute("UPDATE transactions SET status = 'reversed' WHERE id = ?", (tid,))
            self._set(key, "reversed")
            return "reversed"

    # --- refunds (the provider) ---------------------------------------------------------------------------------
    def refund(self, funding_key, amount, key):
        """Take the money out of the wallet first (it may have been spent), then ask the provider to return it."""
        with self.tx():
            f = self.op(funding_key)
            if f is None or f["state"] != "credited":
                return "refused"
            used = self.db.execute("SELECT COALESCE(SUM(amount_kobo), 0) FROM ops WHERE kind = 'refund' AND parent = ? "
                                   "AND state IN ('held', 'pending', 'processed')", (funding_key,)).fetchone()[0]
            if amount <= 0 or amount > f["amount_kobo"] - used:
                return "refused"
            if not self._begin(key, "refund", f["customer_id"], amount, state="held", parent=funding_key):
                return self.state(key)
            try:
                self._post("refund_hold", key, [(self.w(f["customer_id"]), "debit", amount),
                                                (self.acct["in_flight"], "credit", amount)],
                           amount=amount, customer=f["customer_id"], rail="card")
            except Refused as r:
                self._refuse(key, "refund_hold", key, r.reason, amount=amount, customer=f["customer_id"], rail="card")
                return "refused"
        status, out = self.provider.call("POST", "/refunds", {"reference": funding_key, "amount_kobo": amount})
        with self.tx():
            if status == 200:
                self._set(key, "pending", ref=out["refund"]["id"])
                return "pending"
            if status is None or status >= 500:      # in doubt: the provider may have made the refund, so keep the hold
                self._set(key, "held", f"no clear answer ({status or 'nothing'}): a person checks the provider")
                return "held"
            row = self.op(key)
            self._post("refund_release", key, [(self.acct["in_flight"], "debit", amount),
                                               (self.w(row["customer_id"]), "credit", amount)],
                       amount=amount, customer=row["customer_id"], rail="card")
            self._set(key, "failed", f"provider refused: {status}")
            return "failed"

    def settle_refund(self, key):
        row = self.op(key)
        status, out = self.provider.call("GET", f"/refunds/{row['ref']}")
        if status != 200 or out["refund"]["status"] != "processed":
            return row["state"]
        with self.tx():
            row = self.op(key)
            if row["state"] != "pending" or out["refund"]["amount_kobo"] != row["amount_kobo"]:
                return row["state"]
            self._post("refund_settle", key, [(self.acct["in_flight"], "debit", row["amount_kobo"]),
                                              (self.acct["card_clearing"], "credit", row["amount_kobo"])],
                       amount=row["amount_kobo"], customer=row["customer_id"], rail="card")
            self._set(key, "processed")
            return "processed"

    # --- looking again, and being told ------------------------------------------------------------------------------
    def sweep(self):
        """Everything not settled gets one more look. Messages are hints; this is the safety net."""
        with self.lock:
            rows = self.db.execute("SELECT op_key, kind, state FROM ops WHERE state IN ('charging', 'pending', 'sent')").fetchall()
        for key, kind, state in rows:
            if kind == "fund_card":
                self.settle_charge(key)
            elif kind == "payout":
                self.check_payout(key)
            elif kind == "refund":
                self.settle_refund(key)
        return len(rows)

    def open_ops(self):
        with self.lock:
            return self.db.execute("SELECT COUNT(*) FROM ops WHERE state IN ('charging', 'pending', 'sent')").fetchone()[0]

    def handle(self, source, event_id, event):
        """A provider webhook or a switch callback. Idempotent whatever arrives, however often."""
        if source == "provider":
            data = event["data"]
            if event["type"].startswith("charge."):
                self.settle_charge(data["reference"])
            elif event["type"] == "refund.processed":
                with self.lock:
                    row = self.db.execute("SELECT op_key FROM ops WHERE ref = ?", (data["id"],)).fetchone()
                if row:
                    self.settle_refund(row[0])
        elif event["type"] == "inward.credit":
            self.on_inward(event["session_id"], event["account_number"], event["amount_kobo"])
        with self.tx():
            first = self.db.execute("INSERT OR IGNORE INTO seen VALUES (?, ?)", (source, event_id)).rowcount
        self.stats["events"] += 1
        if not first:
            self.stats["event repeats"] += 1

    def start(self, hook_port):
        """The receiver for webhooks (/provider) and callbacks (/switch), and the sweep, as threads."""
        wallet = self

        class Hook(BaseHTTPRequestHandler):
            def log_message(self, *a):
                pass

            def do_POST(self):
                raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
                if self.path == "/provider":
                    key, algo, header, event_id = PROVIDER_KEY, hashlib.sha512, "X-Mock-Signature", self.headers.get("X-Mock-Event-Id")
                else:
                    key, algo, header, event_id = SWITCH_KEY, hashlib.sha256, "X-Switch-Signature", None
                good = hmac.new(key.encode(), raw, algo).hexdigest()
                if not hmac.compare_digest(good.encode(), self.headers.get(header, "").encode()):
                    wallet.stats["bad signatures"] += 1
                    return self._reply(401)
                event = json.loads(raw)
                try:
                    wallet.handle(self.path.strip("/"), event_id or event.get("session_id"), event)
                except Exception as e:                 # a 500 makes the sender try again, which is what we want
                    print("receiver:", repr(e))
                    return self._reply(500)
                self._reply(200)

            def _reply(self, status):
                self.send_response(status)
                self.send_header("Content-Length", "0")
                self.end_headers()

        server = ThreadingHTTPServer(("127.0.0.1", hook_port), Hook)
        self.servers.append(server)
        threading.Thread(target=server.serve_forever, daemon=True).start()

        def loop():
            while server in self.servers:
                time.sleep(1.0)
                try:
                    self.sweep()
                except Exception as e:
                    print("sweep:", repr(e))
        threading.Thread(target=loop, daemon=True).start()

    def stop(self):
        for s in self.servers:
            s.shutdown()
        self.servers.clear()

3. Save the reconciliation. Save this as reconcile.py.

"""The daily reconciliation job: the wallet's ledger against the provider's settlement report and
the switch's transfer report. It repairs what it can explain, lists what it cannot, and exits 1
if anything is left unexplained.

    python3 reconcile.py                   # today, against the services on the default ports
"""
import argparse
import datetime as dt
import sys
from collections import Counter, defaultdict

from generate import PROCESSOR_FEE_RATE, WAT
from wallet import PROVIDER_KEY, SWITCH_KEY, Api, Wallet

CLEARING_NET = """SELECT COALESCE(SUM(CASE e.direction WHEN 'debit' THEN e.amount_kobo ELSE -e.amount_kobo END), 0)
                  FROM entries e JOIN accounts a ON a.id = e.account_id WHERE a.code = ?"""
SWITCH_NET = """SELECT COALESCE(SUM(CASE e.direction WHEN 'debit' THEN e.amount_kobo ELSE -e.amount_kobo END), 0)
                FROM entries e JOIN transactions t ON t.id = e.transaction_id JOIN accounts a ON a.id = e.account_id
                WHERE a.code = 'settlement_bank' AND substr(t.created_at, 1, 10) = ?
                  AND t.kind IN ('funding_transfer', 'payout_nip', 'payout_reversal')"""


def run(w, day, say=print):
    """Returns the list of unexplained breaks. Everything it repairs goes through the wallet's own functions."""
    broken, repaired = [], Counter()
    q = w.query

    # 1. Cards: the provider's settlement report for the day after capture, against the ledger.
    nxt = (dt.date.fromisoformat(day) + dt.timedelta(days=1)).isoformat()
    _, rep = w.provider.call("GET", f"/settlements?date={nxt}")
    prov = {l["reference"]: l["amount_kobo"] for l in rep["lines"]}
    led = dict(q("SELECT external_ref, amount_kobo FROM transactions WHERE kind = 'funding_card' "
                 "AND substr(created_at, 1, 10) = ?", day))
    in_flight = Counter()
    for ref in sorted(set(prov) - set(led)):
        state = w.state(ref)
        if state in ("charging", "pending"):
            in_flight["card captured, not yet credited"] += 1
        else:
            broken.append(f"card: provider captured {ref} ({prov[ref]:,} kobo), the ledger never credited it (state {state})")
    for ref in sorted(set(led) - set(prov)):
        broken.append(f"card: ledger credited {ref} ({led[ref]:,} kobo), the provider's report has no such capture")
    for ref in sorted(r for r in set(prov) & set(led) if prov[r] != led[r]):
        broken.append(f"card: {ref} is {prov[ref]:,} kobo at the provider and {led[ref]:,} in the ledger")
    refunds_prov = Counter((r["reference"], r["amount_kobo"]) for r in rep["refunds"])
    refunds_led = Counter(tuple(r) for r in q("SELECT parent, amount_kobo FROM ops WHERE kind = 'refund' "
                                              "AND state = 'processed' AND substr(updated_at, 1, 10) = ?", day))
    if refunds_prov != refunds_led:
        broken.append(f"card: refunds differ: provider {sum(a * n for (_, a), n in refunds_prov.items()):,} kobo "
                      f"in {sum(refunds_prov.values())}, ledger {sum(a * n for (_, a), n in refunds_led.items()):,} "
                      f"in {sum(refunds_led.values())}")
    in_flight["refund asked, not yet processed"] += w.query(
        "SELECT COUNT(*) FROM ops WHERE kind = 'refund' AND state = 'pending'")[0][0]
    gross, refunded = sum(prov.values()), sum(a * n for (_, a), n in refunds_prov.items())
    fee = round(gross * PROCESSOR_FEE_RATE)
    if (rep["gross_kobo"], rep["fee_kobo"], rep["net_kobo"]) != (gross, fee, gross - fee - refunded):
        broken.append(f"card: the report's totals do not follow from its own lines: {rep['gross_kobo']}, {rep['fee_kobo']}, {rep['net_kobo']}")
    clearing = q(CLEARING_NET, "card_clearing")[0][0]
    settled = w.query("SELECT 1 FROM transactions WHERE kind = 'card_settlement' AND external_ref = ?",
                      f"CARD-SETTLE-{nxt}")
    say(f"cards    provider report for {nxt}: {len(prov)} captures, gross {gross:,} kobo, fee {fee:,}, refunds {refunded:,}, net {gross - fee - refunded:,}")
    say(f"         ledger: {len(led)} credited fundings; card_clearing holds {clearing:,} kobo before settlement")
    if not broken and not any(in_flight.values()) and not settled and clearing == gross - refunded:
        with w.tx():                       # the bank's credit, posted once the report is proved
            w._post("card_settlement", f"CARD-SETTLE-{nxt}", [(w.acct["settlement_bank"], "debit", gross - fee - refunded),
                                                              (w.acct["processing_expense"], "debit", fee),
                                                              (w.acct["card_clearing"], "credit", gross - refunded)],
                    amount=gross - refunded, fee=fee, rail="card")
        repaired["card settlement posted"] += 1
    elif clearing != gross - refunded and not settled:
        broken.append(f"card: card_clearing holds {clearing:,} kobo but captures minus refunds are {gross - refunded:,}")

    # 2. The switch: every transfer it reports for the day, against the operations behind them.
    _, rep = w.switch.call("GET", f"/transfers?date={day}")
    outward = {t["payment_reference"]: t for t in rep["transfers"] if t["direction"] == "outward"}
    inward = {t["session_id"]: t for t in rep["transfers"] if t["direction"] == "inward"}
    cls = Counter()
    for ref, t in sorted(outward.items()):
        op = w.op(ref)
        if op is None:
            broken.append(f"switch: transfer {ref} ({t['amount_kobo']:,} kobo, {t['status']}) has no operation in the ledger")
            continue
        before = op["state"]
        want = {"successful": ("settled",), "failed": ("failed",), "reversed": ("reversed",), "pending": ("sent",)}[t["status"]]
        if before in want:
            cls["pending at the switch, in flight here" if t["status"] == "pending" else "match"] += 1
        elif before == "settled" and t["status"] == "reversed":
            w.apply_reversal(ref)
            repaired["late reversal applied"] += 1
        elif before == "sent":
            after = w.check_payout(ref)
            repaired["in-doubt payout resolved by requery"] += 1
            if after not in want:
                broken.append(f"switch: {ref} is {t['status']} at the switch, {after} here after a requery")
        else:
            broken.append(f"switch: {ref} is {t['status']} at the switch and {before} in the ledger")
    for (key, kind, state) in q("SELECT op_key, kind, state FROM ops WHERE kind = 'payout' AND state IN ('settled', 'reversed')"):
        if key not in outward:
            broken.append(f"ledger: payout {key} is {state} but the switch has no such transfer today")
    for sid, t in sorted(inward.items()):
        op = w.op(sid)
        if op is None:
            w.on_inward(sid, t["beneficiary_account"], t["amount_kobo"])
            repaired["inward credit the callback never delivered"] += 1
        elif op["amount_kobo"] != t["amount_kobo"] or op["state"] != "credited":
            broken.append(f"switch: inward {sid} is {t['amount_kobo']:,} kobo at the switch, {op['amount_kobo']:,} {op['state']} here")
        else:
            cls["inward match"] += 1
    for (key,) in q("SELECT op_key FROM ops WHERE kind = 'fund_bank' AND state = 'credited' AND substr(updated_at, 1, 10) = ?", day):
        if key not in inward:
            broken.append(f"ledger: inward credit {key} is not in the switch's report")
    for (key,) in q("SELECT op_key FROM ops WHERE state IN ('unapplied', 'mismatch')"):
        broken.append(f"operation {key} is {w.state(key)}: a person must decide")
    _, pos = w.switch.call("GET", f"/settlement?date={day}")
    mine = q(SWITCH_NET, day)[0][0]
    say(f"switch   report for {day}: {len(outward)} outward, {len(inward)} inward transfers; "
        f"{', '.join(f'{n} {k}' for k, n in sorted(cls.items()))}")
    say(f"         net position: switch {pos['net_kobo']:,} kobo (pending {pos['pending_kobo']:,} listed apart), ledger {mine:,} kobo")
    if pos["net_kobo"] != mine:
        broken.append(f"switch: net position is {pos['net_kobo']:,} kobo at the switch and {mine:,} in the ledger (difference {pos['net_kobo'] - mine:,})")

    # 3. Nobody paid twice: one intent (our operation key) is one successful payout and one capture.
    paid, charged = defaultdict(int), defaultdict(int)
    for t in rep["transfers"]:
        if t["direction"] == "outward" and t["status"] == "successful":
            paid[t["narration"]] += 1
    _, ch = w.provider.call("GET", "/charges?status=success")
    for c in ch["charges"]:
        charged[c["metadata"].get("op")] += 1
    twice = {k: n for k, n in paid.items() if n > 1}
    say(f"audit    payout intents with more than one successful transfer: {len(twice)}; "
        f"card intents captured more than once: {sum(1 for n in charged.values() if n > 1)}")
    for k in sorted(twice):
        broken.append(f"paid twice: {k} went out {twice[k]} times")
    for k in sorted(k for k, n in charged.items() if n > 1):
        broken.append(f"charged twice: {k}")

    # 4. What must be true when nothing is in flight.
    open_ops = w.open_ops()
    held = q(CLEARING_NET, "in_flight")[0][0]
    say(f"balance  operations still open: {open_ops}; in_flight holds {-held:,} kobo; "
        f"card_clearing holds {q(CLEARING_NET, 'card_clearing')[0][0]:,} kobo")
    if open_ops == 0 and (held != 0 or q(CLEARING_NET, "card_clearing")[0][0] != 0):
        broken.append("in_flight or card_clearing is not zero with nothing open")
    for k, n in sorted(in_flight.items()):
        if n:
            say(f"         in flight at the cut-off, explained: {n} {k}")
    for k, n in sorted(repaired.items()):
        say(f"         repaired by this run: {n} {k}")
    say(f"unexplained breaks: {len(broken)}")
    for b in broken:
        say("  " + b)
    return broken


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--db", default="data/wallet.sqlite")
    ap.add_argument("--day", default=dt.datetime.now(WAT).date().isoformat())
    ap.add_argument("--provider", default="http://127.0.0.1:8101")
    ap.add_argument("--switch", default="http://127.0.0.1:8102")
    a = ap.parse_args()
    w = Wallet(a.db, Api(a.provider, PROVIDER_KEY), Api(a.switch, SWITCH_KEY))
    sys.exit(1 if run(w, a.day) else 0)


if __name__ == "__main__":
    main()

4. Run the cases one at a time. Save this as scenarios.py. It uses a separate database, data/scenarios.sqlite, turns the random faults off, and forces each outcome with a test card or the switch’s X-Mock-Force header. It starts the two slow cases first (a timed-out payout and a payout the switch reverses later), so their waiting overlaps the quick cases.

"""The cases the load script only meets by luck, one at a time, with test cards and forced outcomes."""
import argparse
import time

import datetime as dt

import reconcile
from generate import BANKS, WAT
from wallet import PROVIDER_KEY, SWITCH_KEY, Api, Wallet, create

ap = argparse.ArgumentParser()
ap.add_argument("--db", default="data/scenarios.sqlite")
ap.add_argument("--provider", default="http://127.0.0.1:8101")
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--hook-port", type=int, default=9000)
a = ap.parse_args()
create(a.db, 6)
provider, switch = Api(a.provider, PROVIDER_KEY), Api(a.switch, SWITCH_KEY)
provider.call("POST", "/admin/reset")
provider.call("POST", "/admin/faults", {"decline_rate": 0, "lost_response_rate": 0, "webhook_dup_rate": 0})
switch.call("POST", "/admin/reset")
switch.call("POST", "/admin/faults", {"timeout_rate": 0, "pending_rate": 0, "reverse_rate": 0})
w = Wallet(a.db, provider, switch)
w.start(a.hook_port)


def show(label, *what):
    print(f"{label:34}", *what)


def wait(key, states, seconds=70):
    end = time.time() + seconds
    while time.time() < end and w.state(key) not in states:
        time.sleep(0.5)
    return w.state(key)


# slow ones first, so their waiting overlaps the quick ones
print(w.fund_card(1, 100_000_00, "4242424242420001", "S-FUND-1"), "(customer 1 funded to hold payouts)")
show("payout, switch times out", w.payout(1, 200_000, "B03", "1234567891", "S-TIMEOUT", force="timeout", timeout=2),
     "(client gave up after 2 s)")
show("payout, switch reverses later", w.payout(1, 300_000, "B05", "2234567891", "S-REVERSE", force="reverse"))
show("payout, normal", w.payout(1, 200_000, "B03", "1234567891", "S-PAYOUT"))
show("payout, account ends in 0", w.payout(1, 100_000, "B03", "1234567890", "S-BADACCT"), w.op("S-BADACCT")["detail"])
show("payout, more than held", w.payout(2, 100_000, "B03", "1234567891", "S-BROKE"))
show("card 0001, success", w.fund_card(2, 5_000_00, "4242424242420001", "S-CARD-OK"))
show("card 0002, declined", w.fund_card(3, 5_000_00, "4242424242420002", "S-CARD-DECLINE"), w.op("S-CARD-DECLINE")["detail"])
show("card 0005, response lost", w.fund_card(4, 5_000_00, "4242424242420005", "S-CARD-LOST"), w.op("S-CARD-LOST")["detail"])
show("card 0003, pending then success", w.fund_card(5, 5_000_00, "4242424242420003", "S-CARD-PEND"))
show("  ...after the webhook", wait("S-CARD-PEND", ("credited",)))
show("card 0004, pending then failed", w.fund_card(6, 5_000_00, "4242424242420004", "S-CARD-PFAIL"))
show("  ...after the webhook", wait("S-CARD-PFAIL", ("failed",)))
_, ev = provider.call("GET", "/events")
first = [e["id"] for e in ev["events"] if e["data"].get("reference") == "S-CARD-OK"][0]
before = w.balance(2)
for _ in range(3):
    provider.call("POST", f"/webhooks/replay/{first}")
time.sleep(2)
show("same webhook replayed 3 times", f"balance {before:,} -> {w.balance(2):,} kobo")
show("p2p, enough funds", w.p2p(2, 3, 100_000, "S-P2P-1"))
show("p2p, one kobo too many", w.p2p(2, 3, w.balance(2) + 1, "S-P2P-2"))
show("p2p, same key again", w.p2p(2, 3, 100_000, "S-P2P-1"), f"balance of 3: {w.balance(3):,} kobo")
show("refund of S-CARD-OK, 1,000 naira", w.refund("S-CARD-OK", 100_000, "S-REF-1"))
show("  ...after the webhook", wait("S-REF-1", ("processed",)))
show("refund of the rest and more", w.refund("S-CARD-OK", 500_000, "S-REF-2"))
va = w.virtual_account(4)
switch.call("POST", "/admin/inward", {"account_number": va, "amount_kobo": 700_000, "duplicate_callback": True})
time.sleep(3)
credits = w.query("SELECT COUNT(*) FROM ops WHERE kind = 'fund_bank'")[0][0]
show("inward credit, callback twice", f"{va}: {credits} credit, {w.stats['inward repeats']} repeat ignored")
import urllib.error
import urllib.request
forged = urllib.request.Request(f"http://127.0.0.1:{a.hook_port}/provider", method="POST", headers={"X-Mock-Signature": "00"},
                                data=b'{"type":"charge.success","data":{"reference":"S-CARD-PFAIL"}}')
try:
    urllib.request.urlopen(forged)
except urllib.error.HTTPError as e:
    show("forged webhook", f"HTTP {e.code}; bad signatures counted: {w.stats['bad signatures']}; S-CARD-PFAIL is still {w.state('S-CARD-PFAIL')}")
for k in ("S-TIMEOUT", "S-REVERSE"):
    show(f"waiting for {k}", wait(k, ("settled", "reversed", "failed")))
time.sleep(32)
print()
day = dt.datetime.now(WAT).date().isoformat()
broken = reconcile.run(w, day)
print("payout S-REVERSE is now", w.state("S-REVERSE"), "and S-TIMEOUT is", w.state("S-TIMEOUT"))
w.stop()
python3 scenarios.py
python3 check.py --db data/scenarios.sqlite
credited (customer 1 funded to hold payouts)
payout, switch times out           sent (client gave up after 2 s)
payout, switch reverses later      settled
payout, normal                     settled
payout, account ends in 0          failed name enquiry: {'response_code': '07', 'response_message': 'Invalid account'}
payout, more than held             refused
card 0001, success                 credited
card 0002, declined                failed Insufficient funds
card 0005, response lost           credited attempts=2
card 0003, pending then success    pending
  ...after the webhook             credited
card 0004, pending then failed     pending
  ...after the webhook             failed
same webhook replayed 3 times      balance 492,500 -> 492,500 kobo
p2p, enough funds                  done
p2p, one kobo too many             refused
p2p, same key again                done balance of 3: 100,000 kobo
refund of S-CARD-OK, 1,000 naira   pending
  ...after the webhook             processed
refund of the rest and more        refused
inward credit, callback twice      8954352970: 1 credit, 1 repeat ignored
forged webhook                     HTTP 401; bad signatures counted: 1; S-CARD-PFAIL is still failed
waiting for S-TIMEOUT              settled
waiting for S-REVERSE              settled

cards    provider report for 2026-11-15: 4 captures, gross 11,500,000 kobo, fee 115,000, refunds 100,000, net 11,285,000
         ledger: 4 credited fundings; card_clearing holds 11,400,000 kobo before settlement
switch   report for 2026-11-14: 3 outward, 1 inward transfers; 1 inward match, 2 match
         net position: switch 300,000 kobo (pending 0 listed apart), ledger 300,000 kobo
audit    payout intents with more than one successful transfer: 0; card intents captured more than once: 0
balance  operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
         repaired by this run: 1 card settlement posted
         repaired by this run: 1 late reversal applied
unexplained breaks: 0
payout S-REVERSE is now reversed and S-TIMEOUT is settled
accounts by type (debit-positive kobo): {'asset': 5011585000, 'equity': -5000000000, 'expense': 115000, 'income': -174500, 'liability': -11525500}
settlement_bank in ledger 5,011,585,000 kobo; on the statement (no statement)
6 skipped: no bank_statement table (or it is empty) in this database
OK: all invariants hold

The virtual account number (8…) is different on every run. The run takes about 75 seconds, most of it the timed-out payout: the switch holds that request for 35 seconds and settles it 10 seconds later, and the reversal takes 30 seconds to arrive. Read the lines as checks.

  • Card 0005 shows attempts=2: the first response was a 500 although the charge had succeeded, the wallet asked again with the same key, and the provider replayed its answer. One capture, one credit.
  • Replaying a webhook three times leaves the balance at 492,500 kobo. The funding was 500,000 kobo and the lab’s fee on it is 1.5%, which is 7,500 kobo, so 500,000 - 7,500 = 492,500.
  • The timed-out payout returned sent and was later settled by requery, with one transfer at the switch. The reversed payout was settled at first and is reversed by the end: the reconciliation applied the reversal.
  • The forged webhook got a 401 and changed nothing.
  • Cards at the end. The provider’s report shows 4 captures. Customer 1’s funding was 10,000,000 kobo, and cards 0001, 0005 and 0003 each took 500,000, so gross is 10,000,000 + 3 × 500,000 = 11,500,000 kobo. The declined card and the one that failed after pending captured nothing. The fee is 1% of that, 115,000. The one refund of 100,000 kobo gives net 11,500,000 - 115,000 - 100,000 = 11,285,000, as printed.

check.py ends with OK: all invariants hold, and it prints 6 skipped: the wallet database has no bank statement, which is the gap the chapter named. Invariants 1 to 5 ran.

Now stop both mocks (Ctrl-C) and start them again with the commands from step 1, so the faults are on again and their state is clean.

5. Run the load. Save this as load.py. It creates a new wallet database, data/wallet.sqlite, starts the receiver, sends 1,000 operations (300 card fundings, 200 bank fundings, 200 transfers between wallets, 200 payouts and 100 refund attempts, in a seeded random order with 120 fundings first; a refund attempt that fails before any hold leaves no ops row, so about 90 appear in the table), waits for everything to settle, waits for the switch’s late reversals, and runs the reconciliation.

"""1,000 operations through the wallet while the mocks lose, repeat and delay things, then the
daily reconciliation. Run the mocks with the fault flags first (see the lab).

    python3 load.py                # the wallet's receiver listens on port 9000
    python3 load.py --naive        # the wallet that retries a timed-out payout under a new reference
"""
import argparse
import random
import sys
import time
import datetime as dt
from collections import Counter

import reconcile
from generate import BANKS, NAIRA, WAT
from wallet import PROVIDER_KEY, SWITCH_KEY, Api, Wallet, create

ap = argparse.ArgumentParser()
ap.add_argument("--db", default="data/wallet.sqlite")
ap.add_argument("--provider", default="http://127.0.0.1:8101")
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--hook-port", type=int, default=9000)
ap.add_argument("--ops", type=int, default=1000)
ap.add_argument("--customers", type=int, default=150)
ap.add_argument("--naive", action="store_true")
a = ap.parse_args()

create(a.db, a.customers)
provider, switch = Api(a.provider, PROVIDER_KEY), Api(a.switch, SWITCH_KEY)
w = Wallet(a.db, provider, switch, naive=a.naive)
w.start(a.hook_port)

rng = random.Random(42)
plan = (["card"] * 3 + ["bank"] * 2 + ["p2p"] * 2 + ["payout"] * 2 + ["refund"] * 1) * (a.ops // 10)
rng.shuffle(plan)
funders = [k for k in plan if k in ("card", "bank")][:120]            # fund first, so there is money to spend
for k in funders:
    plan.remove(k)
plan = funders + plan
customers = range(1, a.customers + 1)
DAY = dt.datetime.now(WAT).date().isoformat()
inward_sent, last_payout = 0, 0.0


def spender():
    """A customer with at least ₦500, and how much they ask for: most look at their balance first, a few do not."""
    rows = w.query("""SELECT a.customer_id, COALESCE(SUM(CASE e.direction WHEN 'credit' THEN e.amount_kobo
                                                                    ELSE -e.amount_kobo END), 0) AS held
                           FROM accounts a LEFT JOIN entries e ON e.account_id = a.id
                           WHERE a.customer_id IS NOT NULL GROUP BY a.id HAVING held >= ? ORDER BY a.id""",
                   500 * NAIRA)
    cid, held = rng.choice(rows) if rows else (rng.choice(customers), 0)
    return cid, (held * 2 if rng.random() < 0.08 else held * rng.randrange(10, 91) // 100) or 100 * NAIRA


t0 = time.time()
for n, kind in enumerate(plan, 1):
    key, cid = f"OP-{n:05d}", rng.choice(customers)
    if kind == "card":
        w.fund_card(cid, rng.randrange(1_000, 50_000) * NAIRA, "4000000000001111", key)
    elif kind == "bank":
        number = w.virtual_account(cid)
        switch.call("POST", "/admin/inward", {"account_number": number, "amount_kobo": rng.randrange(2_000, 100_000) * NAIRA,
                                              "sender_bank": rng.choice(BANKS), "duplicate_callback": rng.random() < 0.2})
        inward_sent += 1
    elif kind == "p2p":
        cid, amount = spender()
        w.p2p(cid, rng.choice([c for c in customers if c != cid]), amount, key)
    elif kind == "payout":
        cid, amount = spender()
        w.payout(cid, amount, rng.choice(BANKS), str(rng.randrange(10**9, 10**10)), key)
        last_payout = time.time()
    else:
        rows = w.query("SELECT op_key, amount_kobo FROM ops WHERE kind = 'fund_card' AND state = 'credited'")
        if rows:
            funding = rng.choice(rows)
            w.refund(funding["op_key"], funding["amount_kobo"] * rng.randrange(20, 101) // 100, key)
    if n % 250 == 0:
        print(f"  {n} operations sent after {time.time() - t0:.0f} s; {w.open_ops()} still open")
ops_s = time.time() - t0

deadline = time.time() + 180
while time.time() < deadline:      # wait for webhooks, callbacks and the sweep to settle everything
    credited = w.query("SELECT COUNT(*) FROM ops WHERE kind = 'fund_bank'")[0][0]
    if w.open_ops() == 0 and credited >= inward_sent:
        break
    time.sleep(1)
time.sleep(max(0, last_payout + 33 - time.time()))   # the switch's late reversals arrive about 30 s after approval
total_s = time.time() - t0

print(f"{len(plan):,} operations in {ops_s:.0f} s; everything settled or explained after {total_s:.0f} s")
print(f"{'kind':10} {'state':10} {'count':>6}")
for kind, state, n in w.query("SELECT kind, state, COUNT(*) FROM ops GROUP BY kind, state ORDER BY kind, state"):
    print(f"{kind:10} {state:10} {n:>6}")
print(f"messages: {w.stats['events']} handled, {w.stats['event repeats']} repeats of an event already seen, "
      f"{w.stats['already settled']} that found the operation already settled, {w.stats['bad signatures']} bad signatures")
print()
print(f"daily reconciliation, {DAY}")
broken = reconcile.run(w, DAY)
w.stop()
sys.exit(1 if broken else 0)
python3 load.py
python3 check.py --db data/wallet.sqlite
  250 operations sent after 10 s; 29 still open
  500 operations sent after 16 s; 20 still open
  750 operations sent after 22 s; 23 still open
  1000 operations sent after 31 s; 17 still open
1,000 operations in 31 s; everything settled or explained after 64 s
kind       state       count
fund_bank  credited      200
fund_card  credited      281
fund_card  failed         19
p2p        done          182
p2p        refused        18
payout     failed         19
payout     refused        18
payout     settled       163
refund     processed      73
refund     refused        12
messages: 697 handled, 124 repeats of an event already seen, 378 that found the operation already settled, 0 bad signatures

daily reconciliation, 2026-11-19
cards    provider report for 2026-11-20: 281 captures, gross 695,240,400 kobo, fee 6,952,404, refunds 99,245,215, net 589,042,781
         ledger: 281 credited fundings; card_clearing holds 595,995,185 kobo before settlement
switch   report for 2026-11-19: 167 outward, 200 inward transfers; 200 inward match, 164 match
         net position: switch 613,605,156 kobo (pending 0 listed apart), ledger 613,605,156 kobo
audit    payout intents with more than one successful transfer: 0; card intents captured more than once: 0
balance  operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
         repaired by this run: 1 card settlement posted
         repaired by this run: 3 late reversal applied
unexplained breaks: 0
accounts by type (debit-positive kobo): {'asset': 6202647937, 'equity': -5000000000, 'expense': 6952404, 'income': -10824113, 'liability': -1198776228}
settlement_bank in ledger 6,202,647,937 kobo; on the statement (no statement)
6 skipped: no bank_statement table (or it is empty) in this database
OK: all invariants hold

Your counts will differ, and so will the time. Card fundings credited, payouts settled, late reversals applied and repeated events all move from run to run. These lines are the same on every run: 1,000 operations; 200 bank fundings credited; every provider capture credited once (281 captures against 281 credited fundings); the net positions equal; payout intents with more than one successful transfer: 0; operations still open: 0; unexplained breaks: 0; and OK: all invariants hold from check.py. The dates in the report are the day you run it.

Check the cards by hand from the printed numbers: gross 695,240,400 kobo; the 1% fee is 6,952,404; refunds are 99,245,215; so card_clearing must hold 695,240,400 - 99,245,215 = 595,995,185 kobo before settlement, and it does. The net is 695,240,400 - 6,952,404 - 99,245,215 = 589,042,781 kobo, which is the figure on the report. After the settlement posts, card_clearing is zero.

A few more things to read. The 378 messages that “found the operation already settled” are the webhooks and sweeps that arrived after the response path had already settled the operation. For a success, each is a place where acting on the message would have credited twice. The failed payouts are mostly name enquiries that found no account (about one number in ten ends in 0, which the mock treats as not existing), plus a few transfers the switch left pending and then failed on requery; each one released its hold, which is why in_flight ends at zero. The refused transfers, payouts and refunds are the customers who asked for more than they held, which the ledger refused as insufficient_funds, and they too vary from run to run.

6. Run the reconciliation again. The job must be safe to repeat. With the mocks still running and the wallet database as the load left it:

python3 reconcile.py
cards    provider report for 2026-11-20: 281 captures, gross 695,240,400 kobo, fee 6,952,404, refunds 99,245,215, net 589,042,781
         ledger: 281 credited fundings; card_clearing holds 0 kobo before settlement
switch   report for 2026-11-19: 167 outward, 200 inward transfers; 200 inward match, 167 match
         net position: switch 613,605,156 kobo (pending 0 listed apart), ledger 613,605,156 kobo
audit    payout intents with more than one successful transfer: 0; card intents captured more than once: 0
balance  operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
unexplained breaks: 0

Nothing is repaired the second time: the card settlement was posted once, under a reference that carries its date, and no payout is still settled while the switch says reversed. card_clearing holds 0 kobo before settlement because the first run already cleared it. The totals are the same as in step 5, because this is the same run. The one change is 167 match where step 5 printed 164 match: the first run found three late reversals and repaired them, so on the second run every outward transfer matches its operation.

Run the wallet that retries a timed-out payout under a new reference, which is the Friday bug. Restart both mocks with the commands from step 1, then:

python3 load.py --naive
switch   report for 2026-11-14: 172 outward, 200 inward transfers; 200 inward match, 160 match
         net position: switch 714,481,838 kobo (pending 3,912,976 listed apart), ledger 717,996,703 kobo
audit    payout intents with more than one successful transfer: 5; card intents captured more than once: 0
balance  operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
         repaired by this run: 1 card settlement posted
         repaired by this run: 3 late reversal applied
unexplained breaks: 15
  switch: transfer OP-00310-retry (205,422 kobo, successful) has no operation in the ledger
  switch: transfer OP-00375-retry (163,107 kobo, successful) has no operation in the ledger
  switch: transfer OP-00460-retry (324,349 kobo, successful) has no operation in the ledger
  switch: transfer OP-00468-retry (1,452,290 kobo, successful) has no operation in the ledger
  switch: transfer OP-00479-retry (1,369,697 kobo, successful) has no operation in the ledger
  switch: OP-00738 is pending at the switch and settled in the ledger
  switch: transfer OP-00738-retry (3,462,082 kobo, successful) has no operation in the ledger
  switch: OP-00787 is pending at the switch and settled in the ledger
  switch: transfer OP-00787-retry (450,894 kobo, successful) has no operation in the ledger
  switch: net position is 714,481,838 kobo at the switch and 717,996,703 in the ledger (difference -3,514,865)
  paid twice: OP OP-00310 went out 2 times
  paid twice: OP OP-00375 went out 2 times
  paid twice: OP OP-00460 went out 2 times
  paid twice: OP OP-00468 went out 2 times
  paid twice: OP OP-00479 went out 2 times
accounts by type (debit-positive kobo): {'asset': 6345211277, 'equity': -5000000000, 'expense': 7631731, 'income': -11850103, 'liability': -1340992905}
settlement_bank in ledger 6,345,211,277 kobo; on the statement (no statement)
6 skipped: no bank_statement table (or it is empty) in this database
OK: all invariants hold

--naive changes one thing: when the transfer request gets no usable answer, payout sends it again under the reference <key>-retry. Nothing raised an error and the ledger is internally sound, so check.py still ends with OK: all invariants hold. The reconciliation finds it three ways. Five intents were paid twice, found by counting successful transfers per intent. Each retry is a transfer at the switch with no operation behind it. And the net positions differ by 3,514,865 kobo, which is exactly the five second payments (the gap is always the retries that paid out on top of a payment the ledger holds once): 205,422 + 163,107 + 324,349 + 1,452,290 + 1,369,697 = 3,514,865. That is ₦35,148.65 that left the partner bank twice. Two more payouts (OP-00738, OP-00787) were still pending at the switch when the retry’s approval made the wallet settle them: their originals may yet succeed too, and the 3,912,976 kobo listed as pending is those two, 3,462,082 + 450,894.

Which retries happen, and so every count and amount above, differs from run to run, but at a 5% timeout rate a run with no double payment at all is very unlikely. Then answer three questions. Which comparison would still have caught the double payments if the net positions had happened to balance? Why does the wallet’s own database show nothing wrong? And what single rule in payout is the fix? Clean up with rm data/wallet.sqlite data/scenarios.sqlite, and stop both mocks.

Check your answers to the three questions

Which comparison would still have caught the double payments if the net positions had balanced? The audit count, payout intents with more than one successful transfer: 5. It counts successful transfers per payout intent, so it does not depend on any total. The per-transfer match of the switch’s report against the ledger’s operations also catches them: each of the five -retry transfers is listed as has no operation in the ledger, and the report prints paid twice for each original. Two double payments of opposite sign would cancel in a net. A count of lines per intent cannot cancel.

Why does the wallet’s own database show nothing wrong? The retry went out under a new reference, <key>-retry, that the wallet never wrote into its ledger. The ledger holds one hold and one settlement for each intent, every transaction balances, and check.py tests exactly those internal rules, so it ends with OK: all invariants hold. The second payment exists only at the switch, outside the books, and only a comparison with the switch’s report can show it.

What single rule in payout is the fix? One intent, one reference. When a transfer request gets no usable answer, the wallet must ask about, or resend under, the same payment_reference, never a new one. With the same reference the switch recognises the repeat and returns the first result, so a timeout can never turn into a second transfer.

ARTEFACT Write the incident post-mortem ~50 MIN
YOU PRODUCEIncident post-mortem (blameless)

Template

# Post-mortem: <what failed, in plain words>
Written by <engineer on call> · Reviewed by <head of engineering>, <finance operations lead> · <date>
Status: <draft | reviewed | signed by head of engineering>
Decision needed: <what the readers must decide, and by when>
Scope: <what this covers and what it leaves out>

## Summary
<Three sentences: what broke, who was affected, what it cost, how it was found.>

## Impact
- Customers: <number paid twice, number at risk>
- Money: <₦ that left the bank twice; ₦ still unresolved>
- Not yet known: <what we cannot see, and who will find out>

## Timeline
| When | What happened | Noticed by |
|---|---|---|

## How it was detected
<Which check or person found it, and which checks should have and did not.>

## Contributing factors
- <A gap in the design, the tests, the alerts or the process. No names.>

## What the design does now
<The rule or mechanism that makes a repeat impossible, in one paragraph.>

## Actions
| Action | Owner | Date | Signal that proves it worked |
|---|---|---|---|

## How this write-up could be wrong
<One way, and what would show it.>
WORKED EXAMPLE

The engineer on call writes the post-mortem; the head of engineering signs it and Abdullahi, who runs finance operations, reviews the money. The figures are from the lab’s reproduction of the Friday bug (python3 load.py --naive); a real one uses the production report.

Monday 23 November · Status: reviewed · Decision needed from the head of engineering by Friday 27 November: how the money is recovered. Scope: instant-transfer payouts; the audit printed card intents captured more than once: 0.

Owoleaf: customers paid twice after switch timeouts. On a Friday evening the switch timed out on some payouts and the wallet resent each under a new reference. Five payout intents went out twice. ₦35,148.65 left the partner bank twice.

Impact. Customers: 5 paid twice; 2 more (OP-00738, OP-00787) were pending at the switch when the retry’s approval settled them, so 3,912,976 kobo, ₦39,129.76, may also be paid twice. Money: 205,422 + 163,107 + 324,349 + 1,452,290 + 1,369,697 = 3,514,865 kobo.

Detected. Monday, by Abdullahi comparing the wallet with the switch’s report: 15 unexplained breaks, 5 lines reading paid twice. No alert fired; check.py printed OK: all invariants hold.

Contributing factors. The wallet kept no record of the retry’s reference, so its books could not see the second transfer. The reconciliation ran only when someone ran it. Assumed: no test forced a timeout.

Design now. One intent, one reference: after no usable answer the wallet requeries or resends under the same payment_reference.

Action Owner Date Signal
Remove the -retry path from payout Titilayo Friday 4 December Load run at 5% timeouts prints payout intents with more than one successful transfer: 0
Run the reconciliation daily and page on exit status 1 Abdullahi Friday 4 December A planted break pages the on-call within the hour
Decide recovery of ₦35,148.65 Head of engineering Friday 27 November Each of five intents has a recorded outcome

Wrong if: the 2 pending originals did not succeed; the next switch report shows it.

Now you

Ojaline pays its marketplace sellers every night by instant transfer from a seller wallet built the way this chapter builds Owoleaf’s. After a weekend of slow answers from the switch, the finance team finds on Tuesday that some sellers received a payout twice. You are the engineer on call. Reproduce it: restart both mocks with the step 1 commands and run python3 load.py --naive on your own copy. Your counts will differ from the chapter’s, so use only what your run prints: the audit line, the net-position gap, the paid twice lines and the pending total. State the date and time you assume for each stage of the timeline. The head of engineering and the finance lead will read it to decide how the recovery of the money is handled and whether payouts pause until the fix is verified.

Self-check

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Disputes, chargebacks and refund abuse →