Payment messages: ISO 8583 and ISO 20022
Every card authorisation and bank transfer is a message two machines must read the same way. Build one of each from Owoleaf's books, decode it, and prove its amounts against the ledger
An authorisation request in the lab's ISO 8583-style format carries a purchase of ₦3,964.00 in naira, with currency code 566. Field 4, the amount, is a fixed twelve characters. What does it hold?
Module 1’s card payment named the parties: the cardholder’s bank (the issuer), the merchant’s bank or processor (the acquirer), and the card scheme between them. That chapter drew arrows. This one opens the envelope. Each arrow is a message: a string of characters with an agreed layout, sent by one firm’s software and parsed by another’s. Software from different firms can exchange money only because the layout is agreed. When it is misread, the error is silent. A shifted field is still a valid string.
The lab builds one message of each kind from Owoleaf’s generated books and reads it back. Its field choices are a small subset, labelled illustrative: the standards are paywalled and each network adds its own rules.
Two standards for two jobs
This chapter covers two families of message standards, one for cards and one for bank transfers and statements.
ISO 8583 is the message standard for card-originated transactions, used between acquirers and issuers. The ISO catalogue entry lists ISO 8583:2023 as the third edition, published in July 2023, replacing ISO 8583-1:2003, 8583-2:1998 and 8583-3:2003. Search results showed only the front matter. The text is sold, and most networks still run their own profile of earlier editionsas of 2026-11. It is built for one thing: a short question and a short answer in about a second. A message is compact, positional text or binary.
ISO 20022 is a catalogue of business messages for payments, cash management, securities and more. Its own FAQ says the messages are not themselves ISO standards, although the standard behind them is. The data dictionary and the message definitions in the catalogue are free to useas of 2026-11. Its messages are XML (the catalogue also defines other syntaxes), and every element has a name. A message is longer and carries more.
| ISO 8583 | ISO 20022 | |
|---|---|---|
| Typical job | Card authorisation, reversal, advice | Credit transfers, statements, status reports |
| Shape | Message type, bitmap, numbered data elements | Named, nested XML elements in a namespace |
| Size of the lab’s example | 124 characters | 1,150 characters as printed, indentation included |
| Read by | Position and field number | Element path |
| Where the amount sits | Field 4, digits, minor units | IntrBkSttlmAmt, a decimal string, currency in an attribute |
The two coexist. The card leg of a payment is 8583 end to end on many networks. The account-to-account leg and the statement are moving to 20022. A processor sits between them and has to map one into the other without changing an amount.
ISO 8583: a card authorisation as one line of text
A message has three parts, in order. The message type indicator (MTI) is four digits. Public descriptions say its digits give the version of the standard, the message class, the function and the origin. Function 0 is a request, 1 a response, 2 an advice and 3 an advice response, so 0110 answers a 0100. Search summaries of implementation guides agree; the standard’s own text is paywalledas of 2026-11. Then comes the bitmap: 64 bits, written as 16 hexadecimal characters. Bit n, counted from the left starting at 1, is set when data element n (also called a field, abbreviated DE) is present. When bit 1 is set, a second 64-bit bitmap follows and covers elements 65 to 128. Then come the data elements, in number order, each in its own layout: a fixed length, or a length prefix and then the value. A two-digit prefix is called LLVAR.
The lab’s request for one card funding looks like this, split into its parts:
Here is what the lab’s elements mean. The names and layouts come from public descriptions and from NIBSS’s published interface. The choice of subset, and every value, is the lab’s.
| DE | Name | Layout | In the lab |
|---|---|---|---|
| 2 | Primary account number (PAN) | LLVAR, up to 19 | A well-known test number, never a real card |
| 3 | Processing code | 6 digits | 000000, a purchase |
| 4 | Amount, transaction | 12 digits | Kobo, zero-padded |
| 7 | Transmission date and time | 10 digits, MMDDhhmmss | The attempt’s time in UTC |
| 11 | System trace audit number (STAN) | 6 digits | The transaction id, modulo 1,000,000 |
| 12 | Local transaction time | 6 digits, hhmmss | The attempt’s time in Lagos |
| 13 | Local transaction date | 4 digits, MMDD | The attempt’s date in Lagos |
| 14 | Expiry date | 4 digits, YYMM | From cards.exp_month |
| 37 | Retrieval reference number (RRN) | 12 characters | The first 12 digits of external_ref |
| 38 | Approval code | 6 characters | card_attempts.approval_code |
| 39 | Response code | 2 characters | 00 approved, 05 declined |
| 41 | Terminal id | 8 characters | OWOL0001 |
| 42 | Merchant id | 15 characters | OWOLEAF00000001 |
| 49 | Currency code | 3 digits | 566 |
| 90 | Original data elements | 42 digits | In the reversal |
NIBSS publishes a point-of-sale interface specification for the 1987 version of ISO 8583. Its DE 39 page says the field is two characters giving the disposition of the transaction, with 00 meaning approved, and its DE 41 entry is an 8-character terminal id. Search results did not show the meanings of 05 or 51 in that document, so the lab’s 05 is the lab’s own, and the generator records only card_declinedas of 2026-11. The same specification set also names DE 90, covered below. A processor reads the specification of each network it joins. Two networks that both say “ISO 8583” differ in encodings (ASCII, BCD or binary), required fields and response-code tables.
Three details decide whether money is right.
The amount has no decimal point. Field 4 is digits in the minor unit, and the currency in field 49 says what a minor unit is. The ISO 4217 currency list gives the naira the code NGN, the numeric code 566 and two minor-unit digits, the same two digits as module 1’s kobo. The amount is integer kobo from the books to the wire. Module 1’s minor units is the same rule at the edge of another system.
The response must be matched to its request. The reply is a separate message on a connection that carries thousands. The lab’s answers() function pairs them on the trace number (field 11), the retrieval reference (37) and the terminal id (41). The trace number alone is a trap: six digits hold a million values. A host that shares one counter across all its terminals at twelve authorisations a second repeats a number after 1,000,000 ÷ 12 = 83,333 seconds, or 23.1 hours. A late response can then match the wrong request. The RRN and terminal narrow it, and a timeout window keeps the pairing short.
The approval code and the response code are different fields. Field 39 says the outcome. Field 38 is six characters the issuer returns on approval: its own code for the approval. In the lab, the approval code in the books is the field 38 of the 0110, for every approved attempt.
When the answer does not arrive
The Why’s failure is the central case. An acquirer sends a 0100. The issuer approves it and places a hold. The response is lost, or late. The terminal times out and shows a decline. The cardholder has a hold and no purchase. This is the card version of a timeout means unknown, from idempotency: the sender cannot tell whether the other side acted.
The fix is a reversal, a message that asks the issuer to undo an authorisation. NIBSS’s published DE 90 definition lists original data elements as a numeric 42-digit field. Other public descriptions give it five parts: the original message type (4), the original trace number (6), the original transmission date and time (10), the acquirer id (11) and the forwarding institution id (11). Other search results showed the reversal pairs 0400 with 0410 and 0420 with 0430. The meaning of each pair, interactive or not, varies by networkas of 2026-11. The reversal carries no new question. It points at the old one. That pointer is its idempotency key: the issuer can find the authorisation it names, and a second reversal for the same original changes nothing.
Three rules follow, and the lab’s step 2 builds them.
- Send the reversal on every timeout, whether or not a decline comes later. The Why’s host sent it only after a decline.
- Retry it until it is answered. A reversal that is itself lost leaves the same hold. Repeating it is safe on a network that treats field 90 as naming one original, so check that rule in each network’s specification.
- Match the late response, then drop it. When the 0110 arrives after the reversal went out, it must not credit the merchant. The pairing keys decide which request it answers.
An advice (function digit 2) is the other direction of tell: it reports something that already happened, such as an approval a stand-in system gave on the issuer’s behalf while the issuer was unreachable. It asks for no permission. It belongs in the books and in reconciliation, because only one side may have seen it.
ISO 20022: named elements, namespaces and decimal strings
An ISO 20022 message is a tree. The ISO 20022 site publishes its message definitions by business area, and the messages fall into families named by a short prefix: pain for initiation (a customer to its bank, such as pain.001 for a credit transfer), pacs for clearing and settlement between institutions (pacs.008 for a customer credit transfer, pacs.002 for a status report, pacs.004 for a return) and camt for cash management (camt.053 for the bank-to-customer statement, with camt.052 and camt.054 as reports and notifications). A full identifier ends in a version, such as pacs.008.001.08. The archive page confirms that older versions such as pacs.008.001.08 are kept there. The family descriptions rest on search summaries of bank and industry guides, and each family holds more messages than listed hereas of 2026-11.
Owoleaf’s payout is a credit transfer between two institutions, which is a pacs.008. The lab maps its ledger fields to elements:
| Ledger or statement field | pacs.008 element | Note |
|---|---|---|
external_ref |
PmtId/TxId |
Also the reference on the bank statement |
amount_kobo |
IntrBkSttlmAmt, attribute Ccy="NGN" |
29869.11 for 2,986,911 kobo |
created_at |
GrpHdr/CreDtTm |
An ISO 8601 date and time |
counterparty_bank |
CdtrAgt/FinInstnId/ClrSysMmbId/MmbId |
The lab’s pseudo code B21. Real messages carry a real institution identifier |
| The statement narration | RmtInf/Ustrd |
Free text, which the beneficiary sees |
fee_kobo |
Not in the message | The ₦25 fee is Owoleaf’s charge to its customer, not part of the interbank amount |
In the lab’s switch, a payout that answers 09 (in progress) and later reverses is the story that pacs.002 (status) and pacs.004 (return) carry between institutions. The lab builds neither.
Two traps live in this table.
The amount is a decimal string, not a number you may parse as you like. 2440.95 multiplied by 100 as a float is 244094.99999999997, and int() cuts it to 244,094: one kobo short. That is the bug from money in floating point, arriving through a different door. The lab parses every payout both ways. The floating-point route is wrong for 1,078 of 20,897 payouts. The fix is to parse with Decimal, multiply by 100, require a whole number and refuse anything with a third decimal place.
The namespace is part of every element’s name. The elements live in a namespace named by a URN that includes the message identifier. A search written without it, find("FIToFICstmrCdtTrf/CdtTrfTxInf"), returns None. No error is raised, and the failure shows later, when something uses the answer. The lab shows it once so that you recognise it.
The identifiers in a message answer different questions. The message id identifies the file or envelope. The end-to-end id is meant to travel unchanged from the first sender to the last receiver, and the transaction id is assigned along the chain. Read the definitions for your version and your scheme’s usage guideline before you choose which one a reconciliation keys on. The lab keys on TxId because it equals the 30-digit reference on the statement.
The richer data is the point of the migration. Structured names and addresses, purpose codes and remittance details travel in named places, where an 8583 field would hold a short string. The CPMI’s report of 17 October 2023, developed with the Payments Market Practice Group, sets out 12 harmonised ISO 20022 data requirements to give cross-border payments a consistent minimum set of data. The CPMI says they are not regulatory requirements and encourages market participants to prepare to align by end-2027 at the latest. Search results show an updated report dated 26 February 2026, so check it for the current requirementsas of 2026-11. More data means more to validate. Each element is a field that can be missing, truncated or wrong.
The statement as a message: camt.053
The partner bank’s statement in the lab is a table. A real bank sends it as a file or feed, and the usual carrier is camt.053. Descriptions found by search agree on the shape. Balances sit in Bal blocks typed by a code, OPBD for the opening booked balance and CLBD for the closing one. Each Ntry carries a positive amount, a credit-or-debit indicator (CRDT or DBIT), a status (BOOK for booked), a booking date, a value date and an entry reference. One provider’s business rules require opening balance plus credits less debits to equal closing balance. Samples from banks use different versions (.02 and .08), so ask which your counterparty sendsas of 2026-11.
The booking date and value date are the pair that reconciliation used to separate timing from breaks. The lab’s statement for one booking day puts them in BookgDt and ValDt, and 3,114 of 56,008 entries have different ones. The feed makes it checkable. It also makes one mistake easy: treating a statement that foots as a statement that is right. A duplicate booking foots. A missing payout never appears and so cannot make it fail. Step 4 builds a statement for every day, confirms each foots, and then finds the nine days on which the feed and the ledger disagree.
The migration, and what it means in Nigeria
Messages change slowly because every counterparty has to change together. Swift’s press release of 25 November 2025 announces that the switch from the traditional MT format to ISO 20022 for cross-border payment instructions is complete. Search coverage of it dates the end of MT coexistence for those instructions to 22 November 2025 and says a conversion service remains for leftover MT instructions. Whether other message types have later dates was not confirmedas of 2026-11. The cross-border leg that a Nigerian bank or remittance firm reaches through Swift is therefore ISO 20022 for instructions. Cross-border payments, another chapter in this module, covers the route itself.
Inside Nigeria, two Central Bank of Nigeria circulars are relevant, and neither could be read at its source in this build. Search summaries report that a 2020 CBN circular, about Swift’s updated migration timelines, directed financial institutions to migrate to ISO 20022 for payments and reporting by November 2022. The PDF’s address came from search results, and its text was not readable hereas of 2026-11. Search summaries of a circular numbered PSS/DIR/PUB/CIR/001/001, dated 25 August 2025, say it requires payment service providers, super agents and other licensed operators to migrate their domestic and international payment transaction messaging to ISO 20022. Reports give 31 October 2025 as the migration deadline, and one report gives 20 October as the start of compliance validation, so the dates are not settled here. A later circular, PSS/DIR/PUB/CIR/001/003 of 29 May 2026, is reported to revise the terminal geo-fencing timeline; whether it touches the ISO 20022 date was not checked. The link is to a third-party mirror of the text, not the CBN’s own pageas of 2026-11. Read the CBN’s page for the circular and its later revisions before you rely on either date.
What the circulars mean for a processor’s card leg is a question for the circular and for each network’s specification. NIBSS’s published point-of-sale interface is the 1987 version of ISO 8583, as the titles above show. It is not confirmed from these sources which card messages the 2025 circular reaches and which it leaves alone. Do not assume either answer. A processor in Ekom’s position keeps two codecs and one mapping table, and tests each field of the table against the ledger.
Where it goes wrong
Each of these looks like a working system until money moves.
A bitmap read with bin(). bin(int(hexmap, 16)) drops leading zeros. A 0100 has bit 1 clear, so every field is read one place early. A 0400 with a second bitmap has bit 1 set, so the same code works on it. It passes the reversal test and fails every authorisation. The lab’s break runs it.
A float for an amount. In 8583 it is hard to do, because the field is digits. In 20022 the decimal string invites it.
A shared trace number. Six digits repeat in under a day at modest volume, as the arithmetic showed.
A PAN in a log line. The message holds the full number in field 2. The lab prints the masked form (the first six and last four digits) everywhere except the raw wire in step 1, where the test number is safe. Module 4’s PCI chapter covers what the rules say about storing it.
No reversal on timeout. The Why.
A statement that foots, so it must be right. It proves only that the file agrees with itself.
Mapping that drops data. A narration longer than a field, a name with a diacritic put into an ASCII field, or a structured address flattened to one line. A translation that works for the test file can truncate in production. Compare lengths and character sets field by field.
You work in labs/finance. You create nine small files there: iso8583.py, authorise.py, respond_reverse.py, pacs008.py, one_payout.py, all_payouts.py, camt053.py, statement_feed.py and break_bitmap.py. The data is generated at seed 42 and scale 0.1, so your numbers match the ones below. All queries run through Python’s sqlite3 module; no sqlite3 program is needed. Every field choice is illustrative: the standards are paywalled, and a real network’s layout differs. The card number is a well-known test number.
1. Write the codec and encode one authorisation. First check that the card tables exist and the books are sound:
cd labs/finance
ls data/finance.sqlite >/dev/null 2>&1 || python3 generate.py
ls data/card_attempts.csv >/dev/null 2>&1 || python3 cards.py
python3 check.pyloan book: 372 loans, 850,258,479 kobo of principal outstanding; checks 7-11 run
card book: 10,680 card attempts, 109 disputes for 91,728,900 kobo; checks 12-15 run
accounts by type (debit-positive kobo): {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
OK: all invariants holdInvariants 12 and 13 tie each card attempt to a card funding and, when the funding succeeded, to an approval code. Your messages draw on exactly those fields. The first line, about the loan book, appears only if loans.py ran in your data. The second line is the card book, which cards.py added.
Save iso8583.py, the codec:
"""A small ISO 8583-style codec for the lab. ILLUSTRATIVE.
The real standard is paywalled and each network adds its own rules: field encodings (ASCII,
BCD or binary), which fields a message must carry, extra codes. This subset follows the public
descriptions (message type indicator, bitmaps, fixed and LLVAR fields) and nothing more.
Every field here is ASCII text, and the bitmap is written as hexadecimal text.
"""
import datetime as dt
import sqlite3
# number: (name, layout, length). 'fixed' is exactly `length` characters; 'llvar' has a
# two-digit length prefix and then up to `length` characters.
SPEC = {
2: ("Primary account number", "llvar", 19),
3: ("Processing code", "fixed", 6),
4: ("Amount, transaction", "fixed", 12),
7: ("Transmission date and time", "fixed", 10),
11: ("System trace audit number", "fixed", 6),
12: ("Local time", "fixed", 6),
13: ("Local date", "fixed", 4),
14: ("Expiry date", "fixed", 4),
37: ("Retrieval reference number", "fixed", 12),
38: ("Approval code", "fixed", 6),
39: ("Response code", "fixed", 2),
41: ("Terminal id", "fixed", 8),
42: ("Merchant id", "fixed", 15),
49: ("Currency code, transaction", "fixed", 3),
90: ("Original data elements", "fixed", 42),
}
TEST_PAN = "4111111111111111" # a well-known test number, never a real card
RESPONSE_CODES = {"00": "approved", "05": "do not honour"} # the lab uses two; networks define many
def luhn_ok(pan):
total = 0
for i, ch in enumerate(reversed(pan)):
d = int(ch)
if i % 2:
d = d * 2 - (9 if d * 2 > 9 else 0)
total += d
return total % 10 == 0
def masked(pan):
return pan[:6] + "*" * (len(pan) - 10) + pan[-4:]
def bitmap_hex(numbers):
"""Bit n counts from the left; bit 1 says a second bitmap follows."""
width = 128 if any(n > 64 for n in numbers) else 64
value = 1 << (width - 1) if width == 128 else 0
for n in numbers:
value |= 1 << (width - n)
return format(value, "0%dX" % (width // 4))
def fields_in(bitmap):
width = len(bitmap) * 4
value = int(bitmap, 16)
return [n for n in range(2, width + 1) if value >> (width - n) & 1]
def pack(mti, fields):
out = [mti, bitmap_hex(sorted(fields))]
for n in sorted(fields):
name, layout, length = SPEC[n]
v = fields[n]
if layout == "fixed":
if len(v) != length:
raise ValueError("field %d (%s) must be %d characters, got %d" % (n, name, length, len(v)))
out.append(v)
else:
if not 0 < len(v) <= length:
raise ValueError("field %d (%s) is too long" % (n, name))
out.append("%02d%s" % (len(v), v))
return "".join(out)
def unpack(msg):
mti, rest = msg[:4], msg[4:]
size = 16
if int(rest[0], 16) & 8: # bit 1 set: a second bitmap follows the first
size = 32
bitmap, rest = rest[:size], rest[size:]
fields = {}
for n in fields_in(bitmap):
name, layout, length = SPEC[n]
if layout == "llvar":
length, rest = int(rest[:2]), rest[2:]
fields[n], rest = rest[:length], rest[length:]
if rest:
raise ValueError("%d characters left over" % len(rest))
return mti, fields
def attempt(db, txn):
cols = ("txn", "amount_kobo", "created_at", "ext_ref", "status", "approval", "exp_month", "three_ds")
row = db.execute("""SELECT t.id, t.amount_kobo, t.created_at, t.external_ref, t.status,
a.approval_code, c.exp_month, a.three_ds
FROM transactions t JOIN card_attempts a ON a.transaction_id = t.id
JOIN cards c ON c.id = a.card_id WHERE t.id = ?""", (txn,)).fetchone()
return dict(zip(cols, row))
def request_fields(a):
local = dt.datetime.fromisoformat(a["created_at"])
utc = local.astimezone(dt.timezone.utc)
return {2: TEST_PAN, 3: "000000", 4: "%012d" % a["amount_kobo"], 7: utc.strftime("%m%d%H%M%S"),
11: "%06d" % (a["txn"] % 1_000_000), 12: local.strftime("%H%M%S"), 13: local.strftime("%m%d"),
14: a["exp_month"][2:4] + a["exp_month"][5:7], 37: a["ext_ref"][:12], 41: "OWOL0001",
42: "OWOLEAF00000001", 49: "566"}
def response_fields(req, a):
keep = (3, 4, 7, 11, 12, 13, 37, 41, 42, 49) # echoed from the request; the PAN is not
out = {n: req[n] for n in keep}
if a["status"] == "succeeded":
out[38] = a["approval"]
out[39] = "00"
else:
out[39] = "05" # the generator records only card_declined, so the lab picks 05
return out
def reversal_fields(req, original_mti="0100", acquirer="00000000001", forwarding="00000000001"):
"""A 0400 for a request whose answer never arrived. Field 90 names the original."""
out = {n: req[n] for n in (2, 3, 4, 37, 41, 42, 49)}
out[7] = req[7] # the lab keeps the time; a real one sends a new one
out[11] = "%06d" % ((int(req[11]) + 1) % 1_000_000) # a new trace number for the new message
out[90] = original_mti + req[11] + req[7] + acquirer + forwarding
return out
def answers(req, resp):
"""Does this response belong to this request? Trace number, retrieval reference and terminal."""
return all(req[n] == resp[n] for n in (11, 37, 41))Save authorise.py and run it. It takes the first successful card funding and builds the 0100 request.
import sqlite3
import iso8583 as m
db = sqlite3.connect("data/finance.sqlite")
a = m.attempt(db, 8) # the first successful card funding
print("attempt:", {k: a[k] for k in ("txn", "amount_kobo", "created_at", "status", "approval", "three_ds")})
print("test PAN passes Luhn:", m.luhn_ok(m.TEST_PAN), "| in logs:", m.masked(m.TEST_PAN))
req = m.request_fields(a)
wire = m.pack("0100", req)
print()
print("field name value")
for n in sorted(req):
shown = m.masked(req[n]) if n == 2 else req[n]
print(f"{n:>5} {m.SPEC[n][0]:<30}{shown}")
print()
print("MTI :", wire[:4])
print("bitmap :", wire[4:20], "=", format(int(wire[4:20], 16), "064b"))
print("fields set in the bitmap:", m.fields_in(wire[4:20]))
print("message :", len(wire), "characters")
print(" ", wire)
mti, back = m.unpack(wire)
print()
print("decoded MTI", mti, "| fields back:", sorted(back))
print("round trip exact:", back == req)
print("amount in field 4:", back[4], "-> kobo", int(back[4]), "-> naira", f"{int(back[4]) // 100:,}.{int(back[4]) % 100:02d}")python3 authorise.pyattempt: {'txn': 8, 'amount_kobo': 396400, 'created_at': '2026-01-04T13:16:59+01:00', 'status': 'succeeded', 'approval': 'WMMNJ0', 'three_ds': 'frictionless'}
test PAN passes Luhn: True | in logs: 411111******1111
field name value
2 Primary account number 411111******1111
3 Processing code 000000
4 Amount, transaction 000000396400
7 Transmission date and time 0104121659
11 System trace audit number 000008
12 Local time 131659
13 Local date 0104
14 Expiry date 2705
37 Retrieval reference number 997777982287
41 Terminal id OWOL0001
42 Merchant id OWOLEAF00000001
49 Currency code, transaction 566
MTI : 0100
bitmap : 723C000008C08000 = 0111001000111100000000000000000000001000110000001000000000000000
fields set in the bitmap: [2, 3, 4, 7, 11, 12, 13, 14, 37, 41, 42, 49]
message : 124 characters
0100723C000008C08000164111111111111111000000000000396400010412165900000813165901042705997777982287OWOL0001OWOLEAF00000001566
decoded MTI 0100 | fields back: [2, 3, 4, 7, 11, 12, 13, 14, 37, 41, 42, 49]
round trip exact: True
amount in field 4: 000000396400 -> kobo 396400 -> naira 3,964.00The amount in field 4 is 000000396400, the Predict’s answer. The bitmap 723C000008C08000 starts 0111 0010: bit 1 clear (no second bitmap), then bits 2, 3, 4 and 7 set, and so on to 49. The bitmap has twelve bits set, and the decode returns the same twelve fields with the same values. The message is 124 characters long. Look at the OWOLEAF00000001 merchant id: a fixed field needs all fifteen characters, and a short value is padded, a place where trailing spaces get trimmed by a careless parser.
2. Answer it, then reverse it. Save respond_reverse.py. It builds a 0110 for one approved attempt and one declined attempt, a 0400 for an approved request whose answer “never arrived”, and then runs all 10,680 attempts through the codec.
import sqlite3
from collections import Counter
import iso8583 as m
db = sqlite3.connect("data/finance.sqlite")
# One approved and one declined attempt, request and response.
for txn in (8, 141):
a = m.attempt(db, txn)
req = m.request_fields(a)
resp = m.response_fields(req, a)
q, r = m.pack("0100", req), m.pack("0110", resp)
print(f"transaction {txn}: status={a['status']}, failure={'card_declined' if a['status'] == 'failed' else '-'}")
print(" response:", r)
_, got = m.unpack(r)
code = got[39]
print(f" field 39 = {code} ({m.RESPONSE_CODES[code]}); field 38 = {got.get(38, 'absent')}; "
f"approval_code in the books = {a['approval']}; belongs to the request: {m.answers(req, got)}")
# The response never arrives. The acquirer must undo what it cannot see: a 0400.
a = m.attempt(db, 8)
req = m.request_fields(a)
rev = m.pack("0400", m.reversal_fields(req))
print()
print("reversal:", rev)
print("bitmap:", rev[4:36], "| first bit set, so a second bitmap follows:", bool(int(rev[4], 16) & 8))
_, f = m.unpack(rev)
print("fields:", sorted(f))
print("field 90:", f[90], "->", {"mti": f[90][:4], "stan": f[90][4:10], "time": f[90][10:20],
"acquirer": f[90][20:31], "forwarding": f[90][31:]})
# Every card attempt in the books, built, packed, unpacked and answered.
codes, lengths, rrn, mismatch, total = Counter(), set(), Counter(), 0, 0
for (txn,) in db.execute("SELECT transaction_id FROM card_attempts ORDER BY transaction_id"):
a = m.attempt(db, txn)
req = m.request_fields(a)
wire = m.pack("0100", req)
lengths.add(len(wire))
assert m.unpack(wire)[1] == req
resp = m.unpack(m.pack("0110", m.response_fields(req, a)))[1]
codes[resp[39]] += 1
rrn[req[37]] += 1
total += int(req[4])
mismatch += (resp[39] == "00") != (a["status"] == "succeeded")
print()
print("attempts packed and unpacked:", sum(codes.values()), "| message lengths:", sorted(lengths))
print("response codes:", dict(codes), "| disagreements with the books:", mismatch)
print("sum of field 4 over all attempts:", f"{total:,} kobo; sum of amount_kobo:",
f"{db.execute('SELECT SUM(amount_kobo) FROM transactions t JOIN card_attempts a ON a.transaction_id = t.id').fetchone()[0]:,}")
print("retrieval reference numbers that repeat:", sum(1 for n in rrn.values() if n > 1))python3 respond_reverse.pytransaction 8: status=succeeded, failure=-
response: 0110323800000EC0800000000000000039640001041216590000081316590104997777982287WMMNJ000OWOL0001OWOLEAF00000001566
field 39 = 00 (approved); field 38 = WMMNJ0; approval_code in the books = WMMNJ0; belongs to the request: True
transaction 141: status=failed, failure=card_declined
response: 0110323800000AC080000000000000007272000113191532000141201532011376816667076905OWOL0001OWOLEAF00000001566
field 39 = 05 (do not honour); field 38 = absent; approval_code in the books = None; belongs to the request: True
reversal: 0400F220000008C0800000000040000000001641111111111111110000000000003964000104121659000009997777982287OWOL0001OWOLEAF00000001566010000000801041216590000000000100000000001
bitmap: F220000008C080000000004000000000 | first bit set, so a second bitmap follows: True
fields: [2, 3, 4, 7, 11, 37, 41, 42, 49, 90]
field 90: 010000000801041216590000000000100000000001 -> {'mti': '0100', 'stan': '000008', 'time': '0104121659', 'acquirer': '00000000001', 'forwarding': '00000000001'}
attempts packed and unpacked: 10680 | message lengths: [124]
response codes: {'00': 10280, '05': 400} | disagreements with the books: 0
sum of field 4 over all attempts: 11,614,027,900 kobo; sum of amount_kobo: 11,614,027,900
retrieval reference numbers that repeat: 0The approved response carries field 38 (WMMNJ0, the approval code in the books) and field 39 00. The declined one has no field 38 and field 39 05. In both, answers() pairs the response with its request. The reversal’s bitmap F220000008C08000... begins with F: bit 1 is set, so a second bitmap follows, and field 90 sits in it (it is element 90, bit 26 of the second half). Field 90 splits into the original message type 0100, trace 000008, time 0104121659 and two institution ids. Across all attempts, 10,280 get 00 and 400 get 05, which are the 10,280 succeeded and 400 card_declined rows with zero disagreements, the field 4 amounts sum to the same 11,614,027,900 kobo as the books, and no retrieval reference number repeats.
3. Build a pacs.008 for one payout and parse it back. Save pacs008.py, which builds and reads the message, and one_payout.py:
"""Build a pacs.008-style message for one payout and read it back. ILLUSTRATIVE subset."""
import sqlite3
import xml.etree.ElementTree as ET
from decimal import Decimal
NS = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08"
ET.register_namespace("", NS)
def q(tag):
return "{%s}%s" % (NS, tag)
def naira_text(kobo):
"""Integer kobo to the decimal string an ISO 20022 amount carries. No float on the way."""
return "%d.%02d" % divmod(kobo, 100)
def sub(parent, tag, text=None, **attrs):
e = ET.SubElement(parent, q(tag), attrs)
if text is not None:
e.text = text
return e
def build(txn):
kind, kobo, customer, bank, ref, at = txn
doc = ET.Element(q("Document"))
root = sub(doc, "FIToFICstmrCdtTrf")
hdr = sub(root, "GrpHdr")
sub(hdr, "MsgId", "OWL" + ref[:20])
sub(hdr, "CreDtTm", at)
sub(hdr, "NbOfTxs", "1")
sub(sub(hdr, "SttlmInf"), "SttlmMtd", "CLRG")
tx = sub(root, "CdtTrfTxInf")
pid = sub(tx, "PmtId")
sub(pid, "InstrId", "INSTR" + ref[:12])
sub(pid, "EndToEndId", "E2E" + ref[:12])
sub(pid, "TxId", ref)
sub(tx, "IntrBkSttlmAmt", naira_text(kobo), Ccy="NGN")
sub(tx, "ChrgBr", "SLEV")
sub(sub(tx, "Dbtr"), "Nm", "OWOLEAF/" + customer)
sub(sub(sub(sub(tx, "DbtrAgt"), "FinInstnId"), "ClrSysMmbId"), "MmbId", "P01")
sub(sub(sub(sub(tx, "CdtrAgt"), "FinInstnId"), "ClrSysMmbId"), "MmbId", bank)
sub(sub(tx, "Cdtr"), "Nm", "BENEFICIARY AT " + bank)
sub(sub(tx, "RmtInf"), "Ustrd", "NIP OUTWARD " + customer)
ET.indent(doc, space=" ")
return ET.tostring(doc, encoding="unicode")
def read(xml):
"""Parse the message and return what a receiving system needs, amounts as exact kobo."""
root = ET.fromstring(xml)
ns = {"p": NS}
tx = root.find("p:FIToFICstmrCdtTrf/p:CdtTrfTxInf", ns)
amt = tx.find("p:IntrBkSttlmAmt", ns)
exact = Decimal(amt.text) * 100
if exact != exact.to_integral_value():
raise ValueError("an amount with more than two decimals cannot be kobo: " + amt.text)
return {"tx_id": tx.find("p:PmtId/p:TxId", ns).text, "ccy": amt.get("Ccy"), "text": amt.text,
"kobo": int(exact), "to": tx.find("p:CdtrAgt/p:FinInstnId/p:ClrSysMmbId/p:MmbId", ns).text}import sqlite3
import xml.etree.ElementTree as ET
import pacs008 as p
db = sqlite3.connect("data/finance.sqlite")
row = db.execute("""SELECT kind, amount_kobo, (SELECT ref FROM customers WHERE id = customer_id),
counterparty_bank, external_ref, created_at
FROM transactions WHERE id = 4""").fetchone()
xml = p.build(row)
open("pacs008.xml", "w").write(xml)
print(xml)
got = p.read(xml)
print()
print("parsed:", got)
ledger = db.execute("""SELECT e.amount_kobo FROM entries e JOIN accounts a ON a.id = e.account_id
WHERE e.transaction_id = 4 AND a.code = 'settlement_bank'""").fetchone()[0]
stmt = db.execute("SELECT direction, amount_kobo, narration FROM bank_statement WHERE reference = ?",
(got["tx_id"],)).fetchone()
fee = db.execute("SELECT fee_kobo FROM transactions WHERE id = 4").fetchone()[0]
wallet = db.execute("""SELECT e.amount_kobo FROM entries e JOIN accounts a ON a.id = e.account_id
WHERE e.transaction_id = 4 AND a.code LIKE 'wallet:%'""").fetchone()[0]
print(f"message {got['kobo']:,} | settlement_bank credit {ledger:,} | statement {stmt[0]} {stmt[1]:,} ({stmt[2]})")
print(f"wallet debit {wallet:,} = message {got['kobo']:,} + fee {fee:,}: {wallet == got['kobo'] + fee}")
print("message, ledger and statement agree:", got["kobo"] == ledger == stmt[1])
# A parser that forgets the namespace finds nothing, and says so only when you use the answer.
root = ET.fromstring(xml)
print("find without the namespace:", root.find("FIToFICstmrCdtTrf/CdtTrfTxInf"))python3 one_payout.py<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08">
<FIToFICstmrCdtTrf>
<GrpHdr>
<MsgId>OWL37853954757595534613</MsgId>
<CreDtTm>2026-01-03T19:00:11+01:00</CreDtTm>
<NbOfTxs>1</NbOfTxs>
<SttlmInf>
<SttlmMtd>CLRG</SttlmMtd>
</SttlmInf>
</GrpHdr>
<CdtTrfTxInf>
<PmtId>
<InstrId>INSTR378539547575</InstrId>
<EndToEndId>E2E378539547575</EndToEndId>
<TxId>378539547575955346134255235804</TxId>
</PmtId>
<IntrBkSttlmAmt Ccy="NGN">29869.11</IntrBkSttlmAmt>
<ChrgBr>SLEV</ChrgBr>
<Dbtr>
<Nm>OWOLEAF/C0000764</Nm>
</Dbtr>
<DbtrAgt>
<FinInstnId>
<ClrSysMmbId>
<MmbId>P01</MmbId>
</ClrSysMmbId>
</FinInstnId>
</DbtrAgt>
<CdtrAgt>
<FinInstnId>
<ClrSysMmbId>
<MmbId>B21</MmbId>
</ClrSysMmbId>
</FinInstnId>
</CdtrAgt>
<Cdtr>
<Nm>BENEFICIARY AT B21</Nm>
</Cdtr>
<RmtInf>
<Ustrd>NIP OUTWARD C0000764</Ustrd>
</RmtInf>
</CdtTrfTxInf>
</FIToFICstmrCdtTrf>
</Document>
parsed: {'tx_id': '378539547575955346134255235804', 'ccy': 'NGN', 'text': '29869.11', 'kobo': 2986911, 'to': 'B21'}
message 2,986,911 | settlement_bank credit 2,986,911 | statement DR 2,986,911 (NIP OUTWARD C0000764)
wallet debit 2,989,411 = message 2,986,911 + fee 2,500: True
message, ledger and statement agree: True
find without the namespace: NoneThe message amount, the credit to settlement_bank and the statement’s NIP OUTWARD line are all 2,986,911 kobo. The wallet was debited 2,989,411: the message amount plus the ₦25 fee (2,500 kobo), and the fee is not in the interbank message. Without the namespace, find returns None.
Now do it for every payout. Save all_payouts.py. It builds and reads a message for each succeeded or reversed payout, parses each amount two ways, and looks up each TxId on the statement.
import sqlite3
import pacs008 as p
db = sqlite3.connect("data/finance.sqlite")
rows = db.execute("""SELECT t.kind, t.amount_kobo, c.ref, t.counterparty_bank, t.external_ref, t.created_at, t.status
FROM transactions t JOIN customers c ON c.id = t.customer_id
WHERE t.kind = 'payout_nip' AND t.status IN ('succeeded', 'reversed')
ORDER BY t.id""").fetchall()
stmt = {}
for ref, direction, kobo in db.execute("SELECT reference, direction, amount_kobo FROM bank_statement WHERE narration LIKE 'NIP OUTWARD%'"):
stmt.setdefault(ref, []).append(kobo)
exact = float_wrong = no_line = differ = 0
example = None
for kind, kobo, cust, bank, ref, at, status in rows:
got = p.read(p.build((kind, kobo, cust, bank, ref, at[:19] + "+01:00")))
exact += got["kobo"] == kobo
naive = int(float(got["text"]) * 100) # the tempting parse
if naive != kobo:
float_wrong += 1
example = example or (got["text"], naive, kobo)
if ref not in stmt:
no_line += 1
elif kobo not in stmt[ref]:
differ += 1
print(f"payouts built and parsed: {len(rows):,} (succeeded or reversed)")
print(f"parsed with Decimal to the same kobo: {exact:,}")
print(f"parsed with int(float(text) * 100) to a different kobo: {float_wrong:,}; first: text {example[0]} gives {example[1]:,}, ledger has {example[2]:,}")
print(f"message with no outward line on the statement: {no_line} | with a line of another amount: {differ}")
try:
p.read(p.build(("payout_nip", 2986911, "C0000764", "B21", "378539547575955346134255235804", "2026-01-03T19:00:11+01:00")).replace("29869.11", "29869.115"))
except ValueError as e:
print("a third decimal is refused:", e)python3 all_payouts.pypayouts built and parsed: 20,897 (succeeded or reversed)
parsed with Decimal to the same kobo: 20,897
parsed with int(float(text) * 100) to a different kobo: 1,078; first: text 2440.95 gives 244,094, ledger has 244,095
message with no outward line on the statement: 3 | with a line of another amount: 2
a third decimal is refused: an amount with more than two decimals cannot be kobo: 29869.115Decimal returns the ledger’s kobo for all 20,897. The floating-point parse is wrong on 1,078: 2440.95 gives 244,094 and the ledger holds 244,095. The last two checks are a reconciliation in disguise: 3 payouts have no outward line on the statement and 2 have a line of another amount. Those are the five payout breaks from the reconciliation chapter, found here from messages, without opening the answer key.
4. Build a camt.053 for every booking day and reconcile. Save camt053.py and statement_feed.py. The second builds a statement for each booking day, reads it back, foots it, and compares its entries with the ledger’s settlement_bank entries for the same day.
"""A camt.053-style statement for one booking day, and a reader for it. ILLUSTRATIVE subset."""
import xml.etree.ElementTree as ET
from collections import Counter
from decimal import Decimal
NS = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.08"
ET.register_namespace("", NS)
def q(tag):
return "{%s}%s" % (NS, tag)
def sub(parent, tag, text=None, **attrs):
e = ET.SubElement(parent, q(tag), attrs)
if text is not None:
e.text = text
return e
def naira_text(kobo):
return "%d.%02d" % divmod(kobo, 100)
def side_of(balance_kobo):
return "CRDT" if balance_kobo >= 0 else "DBIT"
def build(db, day):
lines = db.execute("""SELECT line, value_date, booked_at, direction, amount_kobo, reference, narration, balance_kobo
FROM bank_statement WHERE substr(booked_at, 1, 10) = ? ORDER BY line""", (day,)).fetchall()
first, last = lines[0], lines[-1]
opening = first[7] + (first[4] if first[3] == "DR" else -first[4]) # the balance before the first line
doc = ET.Element(q("Document"))
stmt = sub(sub(doc, "BkToCstmrStmt"), "Stmt")
sub(stmt, "Id", "STMT-" + day)
sub(stmt, "CreDtTm", day + "T23:59:59+01:00")
sub(sub(sub(sub(stmt, "Acct"), "Id"), "Othr"), "Id", "OWOLEAF-SETTLEMENT")
for code, kobo, dt_ in (("OPBD", opening, day), ("CLBD", last[7], day)):
bal = sub(stmt, "Bal")
sub(sub(sub(bal, "Tp"), "CdOrPrtry"), "Cd", code)
sub(bal, "Amt", naira_text(abs(kobo)), Ccy="NGN")
sub(bal, "CdtDbtInd", side_of(kobo))
sub(sub(bal, "Dt"), "Dt", dt_)
for line, value_date, booked_at, direction, kobo, ref, narration, _ in lines:
n = sub(stmt, "Ntry")
sub(n, "NtryRef", ref)
sub(n, "Amt", naira_text(kobo), Ccy="NGN")
sub(n, "CdtDbtInd", "CRDT" if direction == "CR" else "DBIT")
sub(sub(n, "Sts"), "Cd", "BOOK")
sub(sub(n, "BookgDt"), "Dt", booked_at[:10])
sub(sub(n, "ValDt"), "Dt", value_date)
sub(n, "AddtlNtryInf", narration)
ET.indent(doc, space=" ")
return ET.tostring(doc, encoding="unicode")
def kobo(text):
exact = Decimal(text) * 100
if exact != exact.to_integral_value():
raise ValueError("not a whole number of kobo: " + text)
return int(exact)
def read(xml):
ns = {"c": NS}
stmt = ET.fromstring(xml).find("c:BkToCstmrStmt/c:Stmt", ns)
bal = {}
for b in stmt.findall("c:Bal", ns):
v = kobo(b.find("c:Amt", ns).text)
bal[b.find("c:Tp/c:CdOrPrtry/c:Cd", ns).text] = v if b.find("c:CdtDbtInd", ns).text == "CRDT" else -v
entries = []
for n in stmt.findall("c:Ntry", ns):
v = kobo(n.find("c:Amt", ns).text)
side = "CR" if n.find("c:CdtDbtInd", ns).text == "CRDT" else "DR"
entries.append({"ref": n.find("c:NtryRef", ns).text, "side": side, "kobo": v,
"booked": n.find("c:BookgDt/c:Dt", ns).text, "value": n.find("c:ValDt/c:Dt", ns).text,
"text": n.find("c:AddtlNtryInf", ns).text})
return bal, entriesimport sqlite3
from collections import Counter
import camt053 as c
db = sqlite3.connect("data/finance.sqlite")
days = [d for (d,) in db.execute("SELECT DISTINCT substr(booked_at, 1, 10) FROM bank_statement ORDER BY 1")]
ledger = Counter()
for ref, side, kobo, at in db.execute("""
SELECT t.external_ref, CASE e.direction WHEN 'debit' THEN 'CR' ELSE 'DR' END, e.amount_kobo, e.posted_at
FROM entries e JOIN accounts a ON a.id = e.account_id AND a.code = 'settlement_bank'
JOIN transactions t ON t.id = e.transaction_id"""):
ledger[(at[:10], ref, side, kobo)] += 1
open("camt053-2026-04-15.xml", "w").write(c.build(db, "2026-04-15"))
lines = open("camt053-2026-04-15.xml").read().splitlines()
print("\n".join(lines[:lines.index(" </Ntry>") + 1]), "\n ...\n")
foots = entries = late = 0
off = []
for day in days:
bal, rows = c.read(c.build(db, day))
move = sum(r["kobo"] if r["side"] == "CR" else -r["kobo"] for r in rows)
foots += bal["OPBD"] + move == bal["CLBD"]
entries += len(rows)
late += sum(r["value"] != r["booked"] for r in rows)
feed = Counter((r["booked"], r["ref"], r["side"], r["kobo"]) for r in rows)
mine = Counter({k: v for k, v in ledger.items() if k[0] == day})
extra, missing = feed - mine, mine - feed
if extra or missing:
off.append((day, extra, missing))
print(f"statement days: {len(days)}; statements whose opening + movements = closing: {foots}")
print(f"entries read: {entries:,}; with a value date other than the booking date: {late:,}")
print(f"days where the feed and the ledger differ: {len(off)}")
for day, extra, missing in off:
for k, n in extra.items():
print(f" {day} on the statement only: {k[1][:8]}.. {k[2]} {k[3]:>9,}")
for k, n in missing.items():
print(f" {day} in the ledger only: {k[1][:8]}.. {k[2]} {k[3]:>9,}")python3 statement_feed.py<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08">
<BkToCstmrStmt>
<Stmt>
<Id>STMT-2026-04-15</Id>
<CreDtTm>2026-04-15T23:59:59+01:00</CreDtTm>
<Acct>
<Id>
<Othr>
<Id>OWOLEAF-SETTLEMENT</Id>
</Othr>
</Id>
</Acct>
<Bal>
<Tp>
<CdOrPrtry>
<Cd>OPBD</Cd>
</CdOrPrtry>
</Tp>
<Amt Ccy="NGN">100918962.97</Amt>
<CdtDbtInd>CRDT</CdtDbtInd>
<Dt>
<Dt>2026-04-15</Dt>
</Dt>
</Bal>
<Bal>
<Tp>
<CdOrPrtry>
<Cd>CLBD</Cd>
</CdOrPrtry>
</Tp>
<Amt Ccy="NGN">101580111.04</Amt>
<CdtDbtInd>CRDT</CdtDbtInd>
<Dt>
<Dt>2026-04-15</Dt>
</Dt>
</Bal>
<Ntry>
<NtryRef>120845208422911683418518703939</NtryRef>
<Amt Ccy="NGN">18762.22</Amt>
<CdtDbtInd>DBIT</CdtDbtInd>
<Sts>
<Cd>BOOK</Cd>
</Sts>
<BookgDt>
<Dt>2026-04-15</Dt>
</BookgDt>
<ValDt>
<Dt>2026-04-15</Dt>
</ValDt>
<AddtlNtryInf>NIP OUTWARD C0000127</AddtlNtryInf>
</Ntry>
...
statement days: 179; statements whose opening + movements = closing: 179
entries read: 56,008; with a value date other than the booking date: 3,114
days where the feed and the ledger differ: 9
2026-02-25 in the ledger only: 55981392.. DR 1,425,991
2026-03-15 on the statement only: 44945488.. DR 251,906
2026-04-15 on the statement only: 75551832.. CR 103,200
2026-04-22 in the ledger only: 66504728.. DR 857,489
2026-05-01 on the statement only: 28888239.. DR 106,059
2026-05-01 in the ledger only: 28888239.. DR 103,559
2026-05-09 on the statement only: 63702839.. DR 1,223,760
2026-05-09 in the ledger only: 63702839.. DR 1,221,260
2026-05-14 in the ledger only: 48860510.. DR 642,657
2026-06-02 on the statement only: 69506902.. DR 4,338,896
2026-06-21 on the statement only: 22035269.. CR 4,661,200All 179 statements foot. The feed still disagrees with the ledger on 9 days, 11 lines in all: the five payout breaks of step 3 (3 in the ledger only, 2 pairs of amounts), the two duplicate bookings and the two unapplied credits. 3,114 entries carry a value date that is not their booking date, and none of them is a break. A statement can foot, and be internally consistent, with every one of those errors in it.
Save break_bitmap.py and run python3 break_bitmap.py. It reads the bitmaps of the 0100 and the 0400 the tempting way, with bin().
import sqlite3
import iso8583 as m
db = sqlite3.connect("data/finance.sqlite")
a = m.attempt(db, 8)
auth = m.pack("0100", m.request_fields(a))
rev = m.pack("0400", m.reversal_fields(m.request_fields(a)))
for name, wire, size in (("0100 authorisation", auth, 16), ("0400 reversal", rev, 32)):
hexmap = wire[4:4 + size]
naive = bin(int(hexmap, 16))[2:] # looks right; drops leading zeros
right = format(int(hexmap, 16), "0%db" % (size * 4))
naive_fields = [i + 1 for i, b in enumerate(naive) if b == "1"]
right_fields = [i + 1 for i, b in enumerate(right) if b == "1" and i]
print(f"{name}: bitmap {hexmap}")
print(f" bits kept by bin(): {len(naive)} of {size * 4}; fields it reads: {naive_fields}")
print(f" fields with the width kept: {right_fields}")0100 authorisation: bitmap 723C000008C08000
bits kept by bin(): 63 of 64; fields it reads: [1, 2, 3, 6, 10, 11, 12, 13, 36, 40, 41, 48]
fields with the width kept: [2, 3, 4, 7, 11, 12, 13, 14, 37, 41, 42, 49]
0400 reversal: bitmap F220000008C080000000004000000000
bits kept by bin(): 128 of 128; fields it reads: [1, 2, 3, 4, 7, 11, 37, 41, 42, 49, 90]
fields with the width kept: [2, 3, 4, 7, 11, 37, 41, 42, 49, 90]The 0400 reads correctly: its first bit is 1, so nothing is lost. The 0100 loses its leading zero. bin() returns 63 characters, every field is read one place early (the real fields 2, 3, 4, 7 become 1, 2, 3, 6), and the first of them, field 1, tells a parser a second bitmap follows. A test on reversals alone would have passed. Fix it with a format that keeps the width, as the second line shows, and add a test of a message whose first bit is 0. Then change request_fields to send a four-digit amount in field 4 and see which line of pack() refuses it.
Template
# Field mapping: <flow> over <ISO 8583 | ISO 20022 message id>
Author · Reviewer (payments architect) · Confirmed by (partner's technical contact) · Date · Status
## Scope
Flow covered: <one flow>. Out of scope: <other messages, other flows>.
## Mapping
| Internal field | Type, length | Message field or element | Type, length | Transformation | Lost or truncated |
|---|---|---|---|---|---|
## Validation rules
| Rule | Applies to | On failure (reject, repair, alert) |
|---|---|---|
## Test cases
| Id | Input | Expected result | Source of the figure |
|---|---|---|---|
T1 happy path, T2 malformed message (exact refusal text), T3 volume check
## Assumptions and open questions
<What the lab or the spec does not show, who answers, by when>
## How this could be wrong
<One way, and what would show it>
## Sign-off
Author · Architect · Partner contact · Date WORKED EXAMPLE
Ekom, an integration engineer at the card processor, writes this specification for one flow: Owoleaf’s NIP payout sent as a pacs.008, using transaction 4 from the lab. The payments architect reviews and signs it, and the receiving bank’s technical contact confirms the elements they read. Out of scope: the card leg, pacs.002 and pacs.004.
| Internal | Message | Lost or truncated |
|---|---|---|
amount_kobo 2986911, integer |
IntrBkSttlmAmt 29869.11, Ccy="NGN" |
None. Built with divmod, read with Decimal |
fee_kobo 2500 |
Not sent | The fee stays with Owoleaf: wallet debit 2,989,411 = 2,986,911 + 2,500 |
external_ref, 30 digits |
TxId in full; MsgId OWL plus 20 digits; EndToEndId E2E plus 12 |
10 digits cut from MsgId, 18 from EndToEndId |
created_at |
CreDtTm 2026-01-03T19:00:11+01:00 |
None: the stored time already carries +01:00, Lagos time |
| Beneficiary name | Cdtr/Nm placeholder |
The books hold no name |
Validation: amount must parse as Decimal with at most two decimals; elements are found with the namespace; TxId must equal a statement reference.
Tests. T1: message, ledger and statement all say 2,986,911 kobo. T2, malformed: the same message with 29869.115 must be refused with “an amount with more than two decimals cannot be kobo: 29869.115”. T3: all 20,897 payouts parse to the ledger’s kobo; the float route is wrong for 1,078.
How this could be wrong: truncating to 12 digits may repeat an EndToEndId. The lab did not count; counting distinct values over the 20,897 payouts would show it.
Now you
You work at the same 120-person card processor. A month on, Owoleaf asks for the card leg to be specified too: the 0100 request and 0110 response, mapped to its card_attempts record. You write it, the payments architect reviews it, and Owoleaf’s technical contact confirms. Use the lab’s step 1 and 2 output: transaction 8 (₦3,964.00, field 4 000000396400, approval WMMNJ0, 124 characters), transaction 141 (declined, field 39 05), and the totals: 10,680 attempts, 10,280 with 00, 400 with 05, and 11,614,027,900 kobo in field 4 and in the books. Cover the trace number (the transaction id modulo 1,000,000), the 12-character reference taken from external_ref, the expiry and the missing field 38 on a decline. Include a malformed message: a field 4 that is eleven digits, with the exact refusal that the lab’s pack() gives for it. The architect decides whether the trace number alone may join a response to its request.
Self-check
Ekom's host team must add a new acquiring bank connection, and the bank's specification is a licensed ISO 8583 profile with its own field encodings. A second bank offers ISO 20022 messages for the transfer leg. The team has six weeks. What should the host's message layer look like?
- DOC ISO 8583:2023, Financial transaction card originated messages: interchange message specifications ISO, 2023
The standard's catalogue entry: scope, edition and the parts it replaces. Read it for what the standard covers and what it leaves to each network. The text itself is sold, so use it to check which edition a counterparty means.
- DOC NIBSS POS interface specification, ISO 8583 (1987 version): field definitions DE 39 to DE 48 NIBSS
A Nigerian network's own public layout for response code, approval and terminal fields. Read DE 39 and DE 41 against the lab's subset to see what a real profile fixes. Skip fields the lab does not use.
- DOC NIBSS POS interface specification, ISO 8583 (1987 version): field definitions DE 90 to DE 128 NIBSS
The definition of the original data elements field used in reversals: its five parts and their positions. Read it with step 2 of the lab, where you build the same field.
- DOC ISO 20022 messages archive (previous versions of the message definitions) ISO 20022 Registration Authority
The ISO 20022 site's archive of earlier message definitions and their documentation, by business area. Use it to find the pacs.008, pacs.002 and camt.053 definitions for the older version your counterparty names, such as pacs.008.001.08.
- DOC ISO 20022 Message Definition Report, Part 2: Payments Clearing and Settlement (2020/2021 edition) ISO 20022 Registration Authority, 2021
The definitions of the pacs messages, including the status report. Read the sections on pacs.008 and pacs.002 for each element's meaning and multiplicity. It is a December 2020 review draft for the standards evaluation group and an older edition than the current one, so check versions before building from it.
- DOC Implementation guidelines for cash management messages (SIX, Swiss Payment Standards 2021) SIX, 2021
One market's usage guideline for camt statements and reports: a worked example of how a community narrows a message to the fields it uses. Read the camt.053 part for balances and entries. It is Swiss practice, not Nigerian.
- DOC Harmonised ISO 20022 data requirements for enhancing cross-border payments (final report) BIS Committee on Payments and Market Infrastructures, 2023
The CPMI's list of the minimum data a cross-border payment message should carry. Read the summary and the list of requirements to see why richer data is the argument for migration. Skip the technical annex on a first pass.
- POST Global financial community completes switch to ISO 20022 (Swift press release) Swift, 2025
Swift's own account of the end of MT and MX coexistence for payment instructions, from the network that ran it. Read it for the date and scope. It is the operator's announcement, so treat adoption figures as its claim.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.