Skip to content

Mezgeb Specification (draft outline)

Status: DRAFT. Each section is an outline to be filled in before the code it governs is written. A section is “done” when it states rules precisely enough that two people would implement them the same way.


  • An open-source, double-entry financial ledger in Rust on PostgreSQL.
  • First-class offline sync: devices spend escrowed funds while disconnected and settle later, safely and deterministically.
  • In scope: accounts, journal entries, balances, holds, offline escrow and settlement, audit, history.
  • Out of scope: users, KYC, cards, QR, fees policy, FX rates, UI. Those belong to the client application.
  • Non-goals: being a general-purpose database; multi-region consensus (v1).

Account, chart of accounts, control account, sub-account, journal entry, line, side (debit/credit), posting, hold, capture, release, reversal, escrow, voucher, receipt, device, counter, sync, settlement, event time, recorded time, daily close, invariant, ledger receipt (signed proof that the ledger committed an entry; see §7.2).

2. Invariants (the contract — everything else serves these)

Section titled “2. Invariants (the contract — everything else serves these)”

The invariants are catalogued in invariants.md: 26 invariants (INV-1 to INV-26), each with where it is enforced and the tests that cover it. That file replaces the draft list that was here.

The pure types live in crates/core. Storage (step 1.08) follows them.

  • Accounts, entries, holds and clients have their own ID types: UUIDv7, generated by the ledger (ADR-0006).
  • Retries are matched by the client’s idempotency key, not by ID (ADR-0008).
  • Money: a signed 64-bit count of the currency’s minor units (santim for ETB) plus its ISO 4217 currency (ADR-0005).
  • Line amounts are PositiveAmount: greater than zero. The side gives the direction, never the sign.
  • No floats and no rounding in the core. Overflow is an error, never a wrap.
  • A chart is data: a TOML file such as charts/wallet-provider.toml, validated when loaded. See the accounting model.
  • Each chart account has a four-digit code, a type (asset, liability, equity, revenue, expense), a kind (control or system) and a status (active or reserved). Control accounts are posted to only through sub-accounts such as 2010:cust-abebe.
  • Opened from a chart reference, so its type, normal side and allow_negative always come from the chart.
  • Fields: id, code, sub-account, name, type, currency, status, allow_negative, debits_total, credits_total.
  • Status: open ⇄ frozen → closed. Only open accounts accept postings. Closing needs a zero balance; a closed account never reopens.
  • Balance on the normal side: debits − credits for assets and expenses, credits − debits for the rest.
  • An EntryDraft is a request: two or more lines (account, side, amount), optional metadata and an optional event_time.
  • A BalancedEntry is an entry that passed every posting rule (§4.1). It can only be created by validate (ADR-0003).
  • After posting (step 1.09), the stored entry also has an ID, the client’s idempotency key, recorded_time and its place in the hash chain (§7.1).
  • recorded_time: assigned by the ledger, strictly monotonic. Authoritative.
  • event_time: claimed by the client/device. Informational, bounded and validated, never used for ordering.
  • Both are microseconds since the Unix epoch, passed into the core, never read from a clock inside it.
  • 4.1 Validation. Rules are checked in a fixed order, each with a stable numeric code (crates/core/src/error.rs): too few lines (1001), too many lines (1002), metadata too large (1003), amount not positive (1004), account not found (1005), account not open (1006), currency mismatch (1007), duplicate line (1008), amount overflow (1009), unbalanced (1010), account total overflow (1011), insufficient funds (1012, INV-8). Codes are never renumbered.
  • 4.2 Posting. One entry posts in one database transaction, all lines or none (step 1.09).
  • 4.3 Holds. A hold is a posting into its own held sub-account, then exactly one of: a capture (full or partial, the remainder returned in the same entry), a release, or an expiry once expires_at has passed (ADR-0004, step 1.14, INV-16 to INV-18). Only the hold’s own entries may post to its held account. An expiry worker expires due holds, skipping any being captured or released, and can be stopped and restarted at any point (db-schema.md).
  • 4.4 Corrections. History is never edited (INV-9).
    • A reversal is a new entry that mirrors the original exactly, at most once, never itself reversed (INV-14). It carries a reversal reason (such as booking_error) and its requester. A reversal that would take an account below zero is refused (ADR-0013).
    • An adjustment is a manual correction or compensation, such as E14’s goodwill credit. It carries an adjustment reason (such as goodwill_credit), a requester and a different approver (INV-25).
    • Both rules are enforced by the engine and again by the database.
  • 4.5 Idempotency. Every write carries a client idempotency key. The same key with the same request (same SHA-256 fingerprint) returns the original entry; the same key with a different request is refused with IdempotencyKeyReused. A refused posting does not use up its key. A client that lost a response can look up the entry by its key (db-schema.md, INV-13).
  • 4.6 Posting templates. A business event is booked by a named, versioned template such as p2p_transfer.v1 (crates/ops, ADR-0002, step 2.01). A template books lines against roles such as payer_wallet, never account IDs; the request binds each role to an account, which must be opened under one of the chart codes the role allows (TM-07). The draft records its template in the reserved metadata key template, and then passes the posting rules like any other entry. A released version is never changed or removed. Refusals have stable codes: invalid template ID (2001), unknown template (2002), unknown version (2003), missing amount (2004), unexpected amount (2005), amount not positive (2006), missing account (2007), unexpected account (2008), account not found (2009), account not allowed for its role (2010), same account for two roles (2011), reserved metadata (2012), template books an undeclared role (2013), amount not the whole balance of an item that moves whole (2014), account not new for an item that opens its own sub-account (2015), fees more than the amount (2016), amounts in different currencies (2017), an amount too large (2018), required metadata missing (2019), metadata value not allowed (2020), refund template without the entry it refunds (2021), another template naming one (2022). A template may also have optional amounts (such as a fee), optional roles (such as fee revenue, needed only with a fee) and metadata keys it checks (such as channel).
  • 4.7 Clearing and suspense. Money in flight and money with no known owner sit in per-item sub-accounts (2020:wd-… pending withdrawals, 9030:wdt-… withdrawals in transit, 9010:sus-… suspense) that each return to zero. Every item moves whole and has exactly one outcome, which the posting rules enforce because none of these accounts may go below zero. Cash in 1010 moves only when the bank statement shows it (clearing and suspense, step 2.02). The ageing query lists open items with their age.
  • 4.8 Payments and fees. A merchant payment or a paid payment request is one entry: the payer, the payee and, if there is a fee, fee revenue (4010). A merchant-paid fee comes out of the price, a payer-paid fee is added to it, and the client computes both; the ledger never rounds. The channel (qr, card_tap, phone_tap, fingerprint) is metadata, never an account (ADR-0014, step 2.03).
  • 4.9 Refunds and disputes. A refund is an entry of kind refund that names the standard entry it refunds. It may credit only accounts the original debited, and all of an entry’s refunds together move each account of the original back by at most what the original moved on it (INV-15). The engine enforces this with the original’s refund tallies locked; the database checks it again at commit. A reversed entry cannot be refunded and a refunded entry cannot be reversed. A dispute holds the merchant’s money in its own 2060:dsp-… sub-account until it is decided wholly for one side; a decision for the payer is a refund of the payment (ADR-0015, policy, step 2.04).

The full protocol is offline protocol v1 (step 2.10, ADR-0019). It covers the message formats and their encoding, the keys, device registration, the trust tiers, the state machines, gaps, conflicts, disputes and the loss policy. This section is the summary.

Cloned device, replayed receipt, forged receipt, device that never syncs, wrong/hostile clock, payer–merchant collusion, lost device, partial sync, merchant uploads receipt twice, payer and payee upload the same receipt.

  • Tier A: secure element (card). Tier B: hardware keystore (StrongBox/TEE). Tier C: software keys. Each tier has its own offline limit and expiry.
  • Issued online. Posts an entry from the user’s wallet to a per-voucher escrow sub-account (2050:vch-…, E16).
  • Contents: voucher_id, device_id, account_id, amount (with currency), counter_start, expires_at, issuer signature.
  • Contents: device_id, voucher_id, counter, prev_receipt_hash, payee account, amount, event_time, payer device signature, optional payee ack signature.
  • Hash chain per device: each receipt commits to the previous one.
  • Outcomes: SETTLED, SETTLED_LATE, DUPLICATE, WAITING_FOR_GAP, CONFLICT, FROZEN, OVER_LIMIT, EXPIRED, BAD_FORMAT, BAD_SIGNATURE, UNKNOWN_DEVICE, UNKNOWN_VOUCHER (protocol §9).
  • Either party may upload; the result is identical regardless of who or when.
  • Gap handling: receipts settle in counter order; a gap is skipped after 72 hours or at the voucher’s return (protocol §11).
  • Conflict handling: freeze device, settle nothing further, raise alert; the dispute path decides (protocol §10, §14).
  • Expiry, then 7 days’ grace, then return of unspent escrow; early close online; no top-up (one voucher per device). A late receipt after the return is paid from the payer’s wallet first, then the loss account 5030, until a 90-day deadline (protocol §7, §12).
  • Funds received offline are not spendable offline until synced (chain depth = 1).
  • Every entry belongs to the period that is open when it is posted. Exactly one period is open; a period is open, then closing, then closed, and a closed period’s balances never change (INV-10, ADR-0016).
  • A period holds a contiguous range of entry sequences. Closing it switches postings to the next period under a lock, verifies the period, writes each account’s totals as a snapshot, and marks it closed (runbook). Planned: sign a journal hash at each close (step 2.09).
  • Late events, such as offline receipts, post into the current open period and keep their original date in event_time.
  • Reports: the trial balance as of now, the end of a closed period (from its snapshot) or a point in time, and the general ledger of an account between two times. Every trial balance balances in every currency (INV-2).
  • Hash chain over the journal of entries, and over the audit events.
  • Signed checkpoints at each close, kept by clients and in files outside the database; mezgeb-cli verify --chain.
  • Database role permissions: no UPDATE/DELETE on journal tables.

Built in step 2.09 (ADR-0018): it makes tampering by someone with full database access detectable, not impossible.

7.2 Ledger receipts (signed proof for every entry)

Section titled “7.2 Ledger receipts (signed proof for every entry)”

Offline payments already carry device-signed receipts (§5.4). Ledger receipts extend signed proof to every committed entry, online or offline: the ledger signs what it recorded, and the client keeps a copy it can verify without trusting the database. Accounting stays double-entry; the receipt is evidence, not a third ledger column.

  • When issued: for every committed entry: payments, hold captures and releases, reversals, and settlement of an offline receipt. Failed postings get no receipt.
  • Contents: receipt format version, the entry’s canonical fields (§3.5), recorded_time, the entry’s journal hash and prev_hash (§7.1), the signing key ID, and the signature.
  • Signature: over a canonical, versioned byte encoding of the contents. Algorithm provisionally Ed25519; the algorithm and the encoding are decided in an ADR and are part of the public API once frozen.
  • Delivery: returned with each successfully posted entry, and retrievable later by entry ID.
  • Idempotency: the receipt is stored with the entry when the transaction commits. A retry with the same ID and body returns the stored receipt, never a newly signed one (INV-13).
  • Purity: mezgeb-core stays free of keys and I/O. It returns the canonical bytes to sign; signing happens in the server/storage layer inside the same database transaction.
  • What it proves: the ledger committed exactly this entry at this position in the journal. Combined with a signed checkpoint (§7.1), anyone holding receipts can detect a journal that was rewritten or had entries removed.
  • What it does not prove: that the account holder authorised the entry. That needs client-signed requests (see §14).
  • Verification: a standalone verifier (CLI and library) checks receipt signatures, key validity at recorded_time, and chain links against a checkpoint.
  • Schema v1, its constraints and roles: db-schema.md. The database enforces INV-1, 3, 4, 8, 9, 13, 14 and 24 on its own, as a second line of defence behind crates/core.
  • Isolation level and lock ordering; deadlock avoidance (ADR-0007, step 1.10).
  • Indexes and partitioning (journal lines by month): steps 3.02, 3.04.
  • Hot accounts: contention strategy (step 3.03).
  • Migrations policy: up and down files, tested up → down → up; once applied outside development, never edited (a change is a new migration).
  • REST over HTTPS with JSON, built with Axum (ADR-0009). Versioned in the path (/v1/...) and described by an OpenAPI document.
  • The contract is openapi/mezgeb.v1.yaml (OpenAPI 3.1, v1-draft, step 2.06); its conventions are in docs/api.
  • Resources: accounts (open, get, find, balance at a time, history, status), posting templates, one operation per template, entries (get, find by idempotency key), corrections (reversal; maker-checker adjustment requests), holds (place, capture, release), periods (list, close), reports (trial balance, ageing), and offline devices, vouchers and receipts (planned, 501).
  • Clients post only through posting templates. The only endpoint that takes arbitrary lines is the operator-only adjustment request, which a second person must approve (INV-25).
  • Every write that posts an entry or places a hold takes an Idempotency-Key header (ADR-0008).
  • Amounts are decimal strings with an explicit currency ({"amount": "39.20", "currency": "ETB"}), converted to minor units at the boundary (ADR-0005).
  • No batch writes in v1: each request posts one entry.
  • Every successfully posted entry includes its ledger receipt (§7.2), from step 2.09.
  • Errors: RFC 9457 Problem Details with stable codes (catalogue).
  • Compatibility: /v1 only grows; a breaking change is /v2 (policy).
  • Unit and property-based tests for every invariant.
  • Deterministic simulator (mezgeb-sim): seeded, reproducible; injects crashes, retries, reordering, duplicate and delayed sync, cloned devices, clock skew. Checks all invariants after every step.
    • v1 (step 1.15): random postings, reversals, adjustments and holds, in independent lanes, on the reference ledger and on PostgreSQL. A share of attempts fails at a fault point and is retried with the same key. Every answer, account, hold and entry count must match the reference ledger, and verify must be clean.
  • Fault points (step 1.15, test builds only): before lock, after lines, before commit, after commit (a lost response). A retry with the same idempotency key must leave exactly one entry.
  • Chaos run (scripts/chaos.sh): PostgreSQL killed with SIGKILL under load, restarted and checked. Every acknowledged request exists once, every unknown one exists once or not at all, and verify is clean.
  • Replay test: rebuild balances from journal and compare.
  • Shadow mode: run beside an existing ledger and compare nightly.
  • Entries per second (single node), p99 latency, hot-account throughput.
  • Benchmark harness and reference hardware.
  • Backups and point-in-time recovery, monitoring, alerts on invariant breaches, key management for voucher signing, disaster recovery.
  • Key hierarchy (issuer keys, receipt-signing keys, device keys), rotation, revocation list. Retired receipt keys stay published so old receipts remain verifiable.
  • Authentication between client apps and the ledger: OAuth 2.0 client credentials for short-lived opaque tokens, roles from a permission matrix, and each client limited to its own accounts (ADR-0017, step 2.08).
  • Regulator requirements for offline stored value (limits, expiry, reporting).
  • Who bears loss for late receipts after voucher return?
  • Partial settlement when a gap never fills?
  • Multi-currency in v1 or later?
  • Client-signed posting requests (proof of authorisation): v1 or later, and is the signature stored with the entry?
  • Receipt-signing keys in an HSM/KMS, or in process for v1?