Is this document real? — verification for dispute evidence, refund claims and GST invoices, using cryptographic and arithmetic ground truth instead of pixel forensics.
Built for the Razorpay AI Buildathon, Track 02 — AI Risk Manager.
Tested against 9 corpora — every one either real, or written by someone else. A real government-signed QR, six real GSTN e-invoice payloads, two real IRP responses, a real Indian supplier invoice, 115 real PDFs, and 15 independently-authored layouts. 15 real GSTINs accepted, 4 placeholders rejected, 0 false positives anywhere. Fifteen false-positive defects were found and fixed along the way — twelve of them invisible to this project's own corpus.
In February 2026, AIForge-Doc tested the state of the art against AI-inpainted financial documents:
| detector | AUC on AI-inpainted | AUC on traditional forgery |
|---|---|---|
| TruFor — general SOTA | 0.751 | 0.96 |
| DocTamper — document-specific | 0.563 | 0.98 |
| GPT-4o — zero-shot | 0.509 ← coin flip | — |
The authors' word for the state of the art is "blind." Diffusion inpainting produces statistically consistent pixels — no compression seam, no cloning signature, nothing classical forensics was built to find.
Meanwhile AI-generated receipts went from 0% of detected fake receipts in March 2025 to 70.8% by May 2026 (AppZen), and India detected ₹74,782 crore of fake input tax credit in FY26 across 30,162 cases — more than double the prior year.
Every dispute, refund and claim is settled on documents nobody checks.
A real invoice states the same fact in several independent places. Ask whether they agree.
A ₹6,200 total exists in six independent encodings, each written by a different actor with a different tool at a different moment:
| # | Encoding | What can edit it |
|---|---|---|
| 1 | Rendered page pixels | image editor, diffusion inpainting |
| 2 | PDF text layer | PDF text editing — a different object entirely |
| 3 | Signed QR payload (JWS) | nothing — re-signing needs a government key |
| 4 | Line-item arithmetic | editing every line coherently |
| 5 | Amount in words | a second, natural-language copy of the number |
| 6 | PDF structure — xref, /Producer, ModDate |
rebuilding the file |
| move | what catches it |
|---|---|
| Inpaint the pixels | text layer still says ₹4,720 |
| Edit the text layer instead | OCR of the render disagrees |
| Edit both | amount-in-words still reads "Four Thousand Seven Hundred Twenty" |
| Edit all three | line items no longer sum |
| Edit all four | the signed QR carries the original, and cannot be re-signed |
| Rebuild the PDF to fix everything | xref chain, /Producer and ModDate all changed |
A document is a redundant encoding of a small set of facts, and forgery is a compression failure. The forger must stay consistent across representations no single tool shows at once.
DocForge-Bench (March 2026) lists this as an open problem, verbatim: "No existing method handles visual, textual, and structural forgery modalities simultaneously."
400 synthetic Indian GST invoices per mode, rendered to real PDF bytes, through the full cascade.
mode flagged insuff cleared
----------------------------------------------------------
AUTHENTIC (false positives) 0.0% 9.5% 90.5%
inpaint pixels only ← the 0.563 100.0% 0.0% 0.0%
PDF-editor edit (incremental) 100.0% 0.0% 0.0%
coherent edit (incremental) 100.0% 0.0% 0.0%
coherent edit, rebuilt clean 90.5% 9.5% 0.0%
coherent, rebuilt, QR removed 77.5% 22.5% 0.0%
print-and-rescan 77.5% 22.5% 0.0%
No tampered document was cleared, in any mode. 0.00% of authentic documents wrongly flagged.
The claim is deliberately narrow. Not "every forgery is detected" — a coherent rebuild with the QR stripped is genuinely indistinguishable from an authentic B2C invoice, because there is no evidence in either. It simply never gets cleared; it gets a human. The cost is 9.5% of genuine documents sent to review — the abstention rate, and the honest price of never guessing.
Random splits measure whether a model memorised one generator. Mode splits measure whether it learned tampering. The cross-dataset forgery literature reports 100%→47% collapses on this test.
| held-out mode | AUC |
|---|---|
| coherent edit, rebuilt clean | 0.9831 (worst) |
| coherent, rebuilt, QR removed | 0.9913 |
| print-and-rescan | 0.9938 |
| all others | 1.0000 |
No collapse — because the features are semantic facts, not learned pixel textures, so there is no generator fingerprint to overfit to.
Split-conformal calibration on held-out authentic documents. Distribution-free, finite-sample.
| promised FPR | threshold | recall on tampered |
|---|---|---|
| 0.1% | refused — n too small | — |
| 0.5% | 0.9333 | 89.5% |
| 2.0% | 0.9283 | 90.8% |
| 10.0% | 0.9171 | 95.7% |
At α=0.1% with n=200, no threshold can honour the bound, so the code refuses rather than returning a number it cannot stand behind. That refusal is tested.
A coverage matrix written by whoever wrote the checks is a design document, not an experiment. So the attacks are searched for — 14 mutation types composed up to four deep, across every field a forger could touch.
category count cleared escape
--------------------------------------------------
MATERIAL overclaim 2302 0 0.0%
identity edit 1593 308 19.3%
cosmetic only 1859 584 31.4%
Not one of 2,302 material overclaims was cleared — a document whose stated total exceeds the original by more than the rounding tolerance. These are attacks nobody designed.
The other rows are reported, not hidden. Cosmetic escapes move no money. Identity edits
found a real design flaw — a backdated invoice whose total matched its payment record was
being cleared, because anchoring was treated as per-document when a payment record corroborates
only the amount. Fixed, and every verdict now lists unverified_facts.
And the inpainting is performed, not modelled: eval/image_tamper.py repaints the total in
the page image — 6,630 pixels — then runs the real pipeline. OCR reads back the forged value;
the signed QR catches it.
One fact, six independent encodings, two of which the forger cannot author.
flowchart LR
F(["₹7,776.30<br/>one fact"])
F --- E1["① rendered pixels"]
F --- E2["② PDF text layer"]
F --- E3["③ signed QR payload"]
F --- E4["④ line arithmetic"]
F --- E5["⑤ amount in words"]
F --- E6["⑥ PDF structure"]
F --- X(["⑦ payment record<br/><i>outside the document</i>"])
E1 & E2 & E4 & E5 & E6 -.->|"forger can edit"| T1[/"internal consistency"/]
E3 ==>|"needs the IRP private key"| T2[/"EXTERNAL ANCHOR"/]
X ==>|"lives in Razorpay"| T2
style E3 stroke-width:3px
style X stroke-width:3px
style T2 stroke-width:3px
The pipeline: render and decode, then 21 deterministic checks, then a calibrated verdict.
flowchart TD
IN[["invoice PDF"]] --> R{{"render · decode · extract"}}
R --> P1["pixels → OCR"]
R --> P2["text layer → pdfplumber"]
R --> P3["QR → OpenCV"]
R --> P4["bytes → xref scan"]
PAY[["Razorpay payment record"]]
P1 & P2 & P3 & P4 & PAY --> C{{"21 deterministic checks<br/>no ML · no network · no training"}}
C --> L0["<b>L0</b> signed QR"]
C --> L1["<b>L1</b> GSTIN · IFSC"]
C --> L2["<b>L2</b> arithmetic · cess · words"]
C --> L3["<b>L3</b> xref · text-vs-render"]
C --> LX["<b>X</b> payment record"]
C --> LS["<b>SET</b> cross-document"]
L0 & L1 & L2 & L3 & LX & LS --> V["PASS / FAIL / N-A · HARD or SOFT"]
V --> M["glass-box additive model"] --> K["conformal threshold"] --> OUT{{"FLAGGED · INSUFFICIENT · CLEARED"}}
L4["<s>L4 pixel forensics</s><br/><i>demoted — AUC 0.563</i>"] -.->|"one weak feature"| M
style L0 stroke-width:3px
style LX stroke-width:3px
style L4 stroke-dasharray: 4 4
Why the verdict is three-valued: a forger who strips the QR and flattens the page does not
defeat the checks — he removes the evidence, and everything returns NOT-APPLICABLE. So
"clean" and "cleared" are kept as different claims, and clearing requires an external anchor.
Anchoring is per-fact: a payment record corroborates the amount and nothing else, so every
verdict also lists unverified_facts.
Full reference: ARCHITECTURE.md · DIAGRAM.md
python3 -m venv .venv && ./.venv/bin/pip install -r requirements-extract.txt
./.venv/bin/python demo.pySix forger moves against one invoice carrying NIC's own signed QR. Every failure line is real output. The failures peel off one at a time as the forger fixes each encoding — until only the government signature is left standing, and then he deletes it:
MOVE 1 inpaint the total qr_total · tax_reconciles · words · text_layer
MOVE 2 edit the text layer too qr_total · tax_reconciles · words
MOVE 3 rewrite amount-in-words qr_total · tax_reconciles
MOVE 4 make the arithmetic close qr_total
MOVE 5 rebuild the PDF clean qr_total ← the QR cannot be re-signed
MOVE 6 delete the QR nothing fails — and it is INSUFFICIENT, not CLEARED
"Clean" and "cleared" are different claims. He did not defeat the checks; he removed the evidence. He gets a human reviewer, not an approval. And for invoices with no QR, the Razorpay payment record is the anchor — you can inflate a receipt, you cannot inflate the payment it documents.
python3 -m venv .venv && ./.venv/bin/pip install pytest
./.venv/bin/python -m pytest tests/ -q # 96 passed
python3 eval/clean_fp_rate.py --n 2000 # false positives on authentic invoices
python3 eval/pdf_coverage.py --n 400 # coverage matrix, real PDF bytes
./.venv/bin/python eval/train_model.py --n 400 # held-out mode + conformal thresholdsThe shipped detector (verifier/) uses the Python standard library only — no ML, no
network, no training in the detection path. interpret-core and scikit-learn are optional and
used only by eval/cross_check_ebm.py.
Three-valued outcomes. A check that cannot run returns NOT_APPLICABLE, never FAIL.
Conflating absent with inconsistent is the fastest way to build a detector that fires on
genuine paperwork. Three false-positive bugs were caught this way and fixed before they could
reach a demo — 45.3% (exact amount-in-words comparison), 22.0% (the paise parser eating
rupee words, so the parser accused documents of its own error) and 7.75% (part payments read
as overclaims). Each is now a regression test.
"Clean" and "cleared" are different claims. A forger who strips the QR and flattens the page
does not defeat the checks — they remove the evidence, and every check returns N/A. So the
verdict is three-way: FLAGGED / INSUFFICIENT / CLEARED, where clearing requires an
external anchor: evidence the forger does not author — the signed QR, or the payment record.
Two other definitions were measured and rejected, including counting the PDF text layer, which
cleared a coherent rebuild 500/500.
A glass box, not SHAP over a black box. The inputs are already facts, so an additive model's contribution is the explanation:
shipping_proof_TXN8841.pdf 0.87
GSTIN check digit failed +0.41
3 incremental updates, /Producer changed between them +0.28
Line items sum ₹4,720; stated total ₹6,200 +0.18
Every line is a fact a reviewer can re-check in ten seconds.
Nine corpora. Every one either real, or written by someone else.
| corpus | n | what it is | flagged |
|---|---|---|---|
| NIC signed QR | 1 | The government's own signed e-invoice QR, from NIC's API sandbox docs. Authentic IRP wire format, RS256, iss: NIC |
passes |
| GSTN e-invoice payloads | 6 | Official GSTN schema v1.1 — the exact JSON an ERP submits to the IRP. Real GSTINs of registered entities. Credit note, debit note, export, discounts | 0 |
| IRP responses | 2 | Two independent real IRP responses from unrelated public repos, both iss: NIC, both dual-JWS (SignedInvoice + SignedQRCode) |
0 |
| Real Indian supplier invoice | 1 | A genuinely issued invoice — VMINFOTECH Mumbai, GSTIN 27AAEPM2067P1Z9, ₹93,392, scanned via Online2PDF |
0 |
| Real scanned Indian documents | 3 | E-way bills, purchase bundles. Badly degraded OCR — Dolivery, GHEMBUR, 4OOOTI, INFOVISIOH |
0 hard |
| Government PDFs | 5 | GSTN, GST Council, CGST zones. Real Word/Adobe producers | 0 hard |
| Personal PDFs | 107 | 183 MB, 20+ producers, real-world diversity | 0 hard |
| Third-party layouts | 15 | Synthetic but independently authored, with ground truth. UAE/Saudi/Kuwait, Arabic, multi-page, poor-scan | 0 |
| Synthetic invoices | 2,000 | Generated here | 0 |
Committed under eval/fixtures/. RESULTS.md is generated by
eval/run_all_fixtures.py — every row is this repo's code run against a file in this repo.
15 real GSTINs accepted, 4 developer placeholders rejected. No errors in either direction.
27AAEPM2067P1Z9 VMINFOTECH, Mumbai — a real issued invoice valid
29AAFCC9980M1ZR 29AADCG4992P1ZP 27AAEFP4570C1ZE 33AABCR0347P1ZA valid
06AAMCS8709B1ZA 29AAACK5675N1ZU 29AEEPL0813J1ZK 11AAACT3904F1ZZ valid
27AAATV2239C1ZP 27AAACO2048K1ZF 27AAATM1969L1Z4 valid
29AAFCD5862R000 developer placeholder — three trailing digits rejected
37BZNPM9430M1KL 03BZNPM9430M1KL 29AWGPV7107B1Z1 rejected
An e-invoice PDF carrying NIC's own signed QR as a real scannable image. Everything read back off the page with nothing supplied:
QR decoded : YES 900 bytes byte-exact through render → raster → decode
[PASS] qr_total_matches_printed signed 7776.3 matches printed 7776.30
[PASS] qr_seller_gstin_matches [PASS] qr_buyer_gstin_matches
[PASS] qr_docno_matches [PASS] qr_date_matches_printed
[PASS] irn_well_formed
Then inflate the printed total and leave the QR alone — the move a forger actually makes, because re-signing needs the IRP private key:
FAIL: signed total is 7776.3, document prints 9776.30 (off by 2000.00)
— the QR cannot be re-signed
Two Indian judgments show what invoice fraud looks like when it is litigated — NCLT CP (IB)-443/ND/2023 and Delhi HC CRL.A. 1142/2015. Both turn on the same thing, and neither is visible from a single document:
"the operational creditor had forged two invoices of same amount bearing same number" "the Invoice has unique number, which cannot be repeated in any other Bill given to any other Party"
In the NCLT case a claim of ₹1,88,66,181 rested on nine invoices totalling ₹1,17,26,178. The disputed ₹50,93,032 invoice existed to carry the claim over the ₹1 crore floor in Section 4 of the IBC. Reconstructed from the order, told nothing about which document was disputed:
[FAIL] set.claim_matches_documents unexplained gap of 7140003.00
[FAIL] set.not_threshold_dependent above ₹1 crore, but removing a single document
of 5093032 drops it to 6633146.00 — examine
that document first
It names the exact invoice the Tribunal found fabricated, for the reason the Tribunal gave.
One adjudicated case, not a benchmark — and no detection metric is computed on it.
See docs/22 and docs/23.
Track 02's bar is "honest metrics including false-positive cost". A rate is not a cost, so
eval/economics.py converts measured behaviour into review load and money — measured and
assumed inputs kept visibly separate.
10,000 disputes · 25,000 evidence documents · 2% forged
auto-cleared, no human time 22,172 (90.5% of genuine)
routed to a reviewer 2,828 (283 analyst-hours)
genuine documents wrongly accused 0 ← false-positive cost: ₹0
net ₹44.98 L
Below a 0.046% fraud rate it costs more in analyst time than it saves — solved by bisection. An earlier draft asserted "roughly 0.5%" and the table beneath it disagreed by an order of magnitude, which is why it is now computed.
Razorpay's official MCP server exposes ~45 tools and zero dispute tools. This composes with it — theirs fetches the dispute and the payment, these verify the document before it reaches a bank.
./.venv/bin/python -m mcp_server.serverSix tools: verify_document, verify_document_set, verify_invoice_payload, check_gstin,
verify_signed_qr, inspect_pdf_structure. Every verdict reports what it could not check.
See mcp_server/README.md.
Twenty of twenty-six were invisible to the corpus this project generated. Full register with what exposed each and the test pinning it: FAILURES.md.
| defect | rate | found by |
|---|---|---|
| Exact amount-in-words comparison | 45.3% | own corpus |
| Paise parser eating rupee words | 22.0% | own corpus |
| Part payments read as overclaims | 7.75% | own corpus |
| PDF-structure checks treated as hard failures | 12.5% | 107 real PDFs |
bytes(list) TypeError |
10.3% unscannable | 107 real PDFs |
| Quadratic regex — 61 s on one file | performance | 107 real PDFs |
| UTF-16 Producer mojibake | readability | government PDFs |
| Line discount ignored | 33% | 6 real GSTN e-invoices |
| Other charges ignored | (same) | 6 real GSTN e-invoices |
| Invoice discount applied at the wrong stage | (same) | 6 real GSTN e-invoices |
| Compensation cess missing entirely | ₹747 / ₹1,711 off | 2 real IRP responses |
| Field parsers 0/15, six confidently wrong | 40% wrong | 15 independent layouts |
| Discount semantics assumed one convention | — | 15 independent layouts |
| GST slab check had no jurisdiction gate | Saudi 15% VAT flagged | 15 independent layouts |
| Mixed tax rates — 28% + 18% blends to 25.53% | real invoice flagged | 1 real supplier invoice |
Fixing the invoice-discount bug made the synthetic false-positive rate jump from 0.00% to 19.75%.
The generator applied the discount to the subtotal; the checker expected it there. Generator and checker shared the same wrong assumption, agreed perfectly, and reported 0% while the model was wrong.
A self-generated corpus cannot find an error in the mental model that produced it.
Compensation cess. Two real IRP responses would not reconcile — off by ₹747.50 and
₹1,711.40. Cess is levied on top of GST on tobacco, coal, aerated drinks and vehicles, in
separate ValDtls fields. The model had no term for it. Six real GSTN payloads had not surfaced
it, because none of them carried cess.
OCR damage is not forgery. A real e-way bill's GSTIN failed its check digit — and
27AABCI5538B1ZU is valid. The OCR read Z as U, in a document that also produced
Dolivery and INFOVISIOH. Flagging that hard would accuse an honest merchant because their
invoice was scanned. The tempting fix — "if one edit makes it valid, call it damage" — was
measured first and is worthless: an invalid GSTIN has ~14.4 valid single-edit neighbours out
of 525. Position 13 is Z by convention, so that specific repair is 1-in-36 evidence, and only
that case is softened.
Full account in JOURNAL.md.
- Print-and-rescan destroys the text layer and the QR's machine readability.
- B2C receipts below the e-invoicing threshold carry no signed QR at all.
- A coherent rebuild with the QR removed cannot be distinguished from a genuine B2C invoice — there is no evidence in either. It is never cleared, but it is not detected.
- Text extraction: the dependency-free scanner yields usable text on 42.5% of 113 real
PDFs;
pdfplumberon 93.8%. The core verifier still runs on the standard library alone. - No real forgery has been tested. Every tampered document is generated by this project. This is the largest remaining gap and it is not closable from public sources — nobody publishes fraud corpora.
- No signature verified. Needs the IRP public certificate. The zero-key payload comparison carries the detection either way.
- RTL layouts are unparsed. The extractor returns
Noneon Arabic and bilingual invoices — declining rather than guessing, and recorded as a failure inRESULTS.mdrather than reclassified. - Shadow attacks — well-formed, standard-compliant incremental updates — leave a revision chain, but so do legitimate workflows. Revision count is evidence, not proof, and is weighted as one feature among many.
This is a detector. The tamper generators that build the evaluation corpus live in the
quarantined eval/ harness and are not part of the shipped package. Every document produced
is a synthetic invoice for a fictitious supplier, carrying a QR whose signature bytes are random
and could never verify against the IRP certificate.
Nothing here forges a government signature, and nothing here could — that needs a private key held by the Invoice Registration Portal, which is the entire reason the layer works.
| File | Contents |
|---|---|
ARCHITECTURE.md |
Fact-flow, layer table, integration surface |
DIAGRAM.md |
The idea, the pipeline, the verdict — as diagrams |
FAILURES.md |
All 26 defects, what exposed each, the test pinning it |
TESTS.md |
Test inventory by file and kind, generated from source |
RESULTS.md |
Generated pass/fail over every committed fixture |
JOURNAL.md |
The whole build, including what went wrong |
JOURNAL.md |
The whole build, honestly — every phase, all 15 false-positive defects, and what was got wrong and corrected |
RESULTS.md |
Generated pass/fail table over every committed fixture |
ARCHITECTURE.md |
Fact-flow diagram, layer table, integration surface |
docs/02-threat-model.md |
Attack A vs Attack B; the six-encoding trap; coverage matrix |
docs/03-verification-stack.md |
Layers L0–L4 in detail |
docs/04-metrics-and-calibration.md |
The calibration finding; conformal risk control |
docs/05-corpus.md |
Dataset licences; corpus design; the ethics boundary |
docs/09–12 |
Measured results, phase by phase, including every bug found |
docs/13-real-data-validation.md |
107 real PDFs — four defects found, one design decision invalidated |
research/sources.md |
Full bibliography with what each source established |