invoice-registration-reference 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """Public Python API for offline invoice-registration evidence verification."""
2
+
3
+ from .invoice_reference_verifier import VerifierConfig, verify
4
+
5
+ __all__ = ["VerifierConfig", "verify"]
@@ -0,0 +1,564 @@
1
+ #!/usr/bin/env python3
2
+ """Gate 2 verifier for the Invoice Registration Reference v0.1.
3
+
4
+ Computes the specification's three verdicts (section 8) from actual
5
+ inputs -- nothing is fixed or precomputed:
6
+
7
+ verify(checkout, order, bundle, config) -> {
8
+ "valid": bool, # structural rules 1, 2, 4, 6
9
+ "violations": [str, ...],
10
+ "verdicts": {
11
+ "registration_matches_invoice": {"verdict": ..., "reason": ...},
12
+ "registration_active_at_payment": {"verdict": ..., "reason": ...},
13
+ "signed_by_checkout_business": {"verdict": ..., "reason": ...},
14
+ },
15
+ }
16
+
17
+ Inputs
18
+ ------
19
+ checkout, order : the final checkout as accepted for completion, and
20
+ the order carrying the snapshot (parsed JSON dicts).
21
+ bundle : {
22
+ "artifact": compact JWS string of the scheme's signed artifact, or
23
+ None,
24
+ "status_evidence": the documented simulated status format (a dict
25
+ with a "jws" compact JWS) or None,
26
+ "payment_event": the documented simulated capture format or None,
27
+ "lookup_outcome": optional str -- "timeout" / "unavailable" /
28
+ "refused" records a failed lookup; it is never evidence.
29
+ }
30
+ config : VerifierConfig -- trust held independently of the bundle:
31
+ scheme_public_key (RSA), merchant_public_key (EC) or None,
32
+ expected_payment_id or None, scheme_timezone (IANA name) or None,
33
+ no_reinstatement_rule (documented for in_gst_einvoice_irp, spec
34
+ section 9; a verified status response's scheme_rule may also
35
+ supply it).
36
+
37
+ Verdicts follow specification section 8 exactly, including: digest
38
+ over the compact JWS ASCII bytes; only verified status claims are
39
+ evaluated; capture binding (checkout id, expected payment id, amount,
40
+ currency) gates the active-at-payment verdict; order.checkout_id is
41
+ checked alongside snapshot equality for the signature verdict;
42
+ offset-free scheme timestamps (IRP AckDt) order only under the
43
+ configured documented timezone; conflicting authenticated evidence is
44
+ not established; a timeout/refusal/"not available" is never
45
+ contradicted.
46
+
47
+ Scope is v0.1: scheme in_gst_einvoice_irp, simulated status/payment
48
+ formats. This module is the reference verifier, not a production
49
+ service.
50
+
51
+ Capture authentication: the field matching in this module (checkout
52
+ id, expected payment id, amount, currency) BINDS capture evidence to
53
+ the transaction; it does not AUTHENTICATE it. A live verdict requires
54
+ capture evidence authenticated by the caller's payment integration.
55
+ The simulated capture format is unauthenticated by construction.
56
+ """
57
+ import base64
58
+ import hashlib
59
+ import json
60
+ import pathlib
61
+ import re
62
+ from dataclasses import dataclass, replace
63
+ from datetime import datetime
64
+ from decimal import Decimal, InvalidOperation
65
+ from zoneinfo import ZoneInfo
66
+
67
+ import rfc8785
68
+ from cryptography.exceptions import InvalidSignature
69
+ from cryptography.hazmat.primitives import hashes, serialization
70
+ from cryptography.hazmat.primitives.asymmetric import ec, padding
71
+ from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
72
+
73
+ ESTABLISHED = "established"
74
+ NOT_ESTABLISHED = "not_established"
75
+ CONTRADICTED = "contradicted"
76
+
77
+
78
+ @dataclass
79
+ class VerifierConfig:
80
+ scheme_public_key: object = None # RSA public key
81
+ merchant_public_key: object = None # EC public key or None
82
+ expected_payment_id: str = None
83
+ scheme_timezone: str = None # e.g. "Asia/Kolkata"
84
+ no_reinstatement_rule: bool = True # spec section 9 (GSTN FAQ v1.4 Q91)
85
+
86
+
87
+ def b64u_decode(s: str) -> bytes:
88
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
89
+
90
+
91
+ def parse_time(value):
92
+ """Parse a timestamp. Returns (datetime, had_offset) or (None, False).
93
+
94
+ Accepted forms: RFC 3339 (the reference's own timestamps and the
95
+ simulated formats); the IRP's documented AckDt format
96
+ "yyyy-MM-dd HH:mm:ss" (e.g. "2026-11-20 10:15:23" -- NIC's
97
+ Generate IRN specification; ClearTax's published IRP response
98
+ example shows "2023-10-26 14:28:00"), which carries no offset; and
99
+ the IRP's dd/MM/yyyy date forms. A dd/MM/yyyy hh:mm:ss AM/PM
100
+ rendering is also tolerated by the strptime fallbacks below, but
101
+ it is NOT a documented IRP format and no claim in this repository
102
+ rests on it.
103
+ """
104
+ if not value or not isinstance(value, str):
105
+ return None, False
106
+ try:
107
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
108
+ return dt, dt.tzinfo is not None
109
+ except ValueError:
110
+ pass
111
+ for fmt in ("%d/%m/%Y %I:%M:%S %p", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y"):
112
+ try:
113
+ return datetime.strptime(value, fmt), False
114
+ except ValueError:
115
+ continue
116
+ return None, False
117
+
118
+
119
+ def aware_time(value, config: VerifierConfig):
120
+ """A timestamp usable for ordering: aware, applying the configured
121
+ documented scheme timezone to offset-free scheme times. Returns
122
+ None when the time cannot be ordered (spec section 8.4)."""
123
+ dt, had_offset = parse_time(value)
124
+ if dt is None:
125
+ return None
126
+ if had_offset:
127
+ return dt
128
+ if config.scheme_timezone:
129
+ return dt.replace(tzinfo=ZoneInfo(config.scheme_timezone))
130
+ return None
131
+
132
+
133
+ def verify_rs256(token: str, key) -> dict:
134
+ h, p, s = token.split(".")
135
+ key.verify(b64u_decode(s), f"{h}.{p}".encode(), padding.PKCS1v15(), hashes.SHA256())
136
+ return json.loads(b64u_decode(p))
137
+
138
+
139
+ def artifact_fields(payload: dict) -> dict:
140
+ """Flatten a signed artifact payload: fields may sit at the top
141
+ level (Example 2's simulation), inside a nested `data` object
142
+ (production IRP shape, Example 3), or inside a `data` JSON string
143
+ (the published signed QR code, Example 1).
144
+
145
+ The signed invoice's own structure nests the compared fields one
146
+ level deeper -- DocDtls (No/Typ/Dt), SellerDtls (Gstin), ValDtls
147
+ (TotInvVal); those are mapped onto the flat names the comparison
148
+ uses. (RC3 blocker 4: a DocDtls.No that differed from the
149
+ reference previously went unseen and matches was established.)"""
150
+ fields = dict(payload)
151
+ data = payload.get("data")
152
+ if isinstance(data, str):
153
+ try:
154
+ data = json.loads(data)
155
+ except (ValueError, TypeError):
156
+ data = None
157
+ if isinstance(data, dict):
158
+ merged = dict(data)
159
+ merged.update({k: v for k, v in payload.items() if k != "data" and v is not None})
160
+ fields = merged
161
+ doc_dtls = fields.get("DocDtls")
162
+ if isinstance(doc_dtls, dict):
163
+ fields.setdefault("DocNo", doc_dtls.get("No"))
164
+ fields.setdefault("DocTyp", doc_dtls.get("Typ"))
165
+ fields.setdefault("DocDt", doc_dtls.get("Dt"))
166
+ seller_dtls = fields.get("SellerDtls")
167
+ if isinstance(seller_dtls, dict):
168
+ fields.setdefault("SellerGstin", seller_dtls.get("Gstin"))
169
+ val_dtls = fields.get("ValDtls")
170
+ if isinstance(val_dtls, dict):
171
+ fields.setdefault("TotInvVal", val_dtls.get("TotInvVal"))
172
+ return fields
173
+
174
+
175
+ def structural_violations(checkout: dict, order: dict) -> list:
176
+ """Rules 1, 2, 4, 6 (spec section 6), decidable from the payloads."""
177
+ v = []
178
+ refs = checkout.get("invoice_reference") or []
179
+ li = {x["id"]: x for x in checkout.get("line_items", [])}
180
+ seen_lines, seen_irns, seen_docs = set(), set(), set()
181
+ for r in refs:
182
+ if r.get("line_item_id") in seen_lines or r.get("line_item_id") not in li:
183
+ v.append(f"rule 1: line item {r.get('line_item_id')!r} referred twice or unknown")
184
+ seen_lines.add(r.get("line_item_id"))
185
+ reg = r.get("registration")
186
+ if reg:
187
+ if reg["identifier"] in seen_irns:
188
+ v.append("rule 1: same registration identifier on two lines")
189
+ seen_irns.add(reg["identifier"])
190
+ if "status" not in r:
191
+ v.append("rule 6: registration present without a status")
192
+ doc_key = (r["document"]["number"], r["document"]["issuer_tax_identity"])
193
+ if doc_key in seen_docs:
194
+ v.append("rule 1: same document on two lines")
195
+ seen_docs.add(doc_key)
196
+ alloc = r.get("allocation")
197
+ if alloc and alloc["balance_after"] != alloc["balance_before"] - alloc["amount_applied"]:
198
+ v.append("rule 4: declared balance arithmetic does not hold")
199
+ def total_of(payload):
200
+ return [t["amount"] for t in payload.get("totals", []) if t["type"] == "total"][0]
201
+ li_total = {x["id"]: [t["amount"] for t in x["totals"] if t["type"] == "total"][0]
202
+ for x in checkout.get("line_items", [])}
203
+ applied = [(r.get("allocation", {}).get("amount_applied", li_total.get(r["line_item_id"])))
204
+ for r in refs]
205
+ if any(li_total.get(r["line_item_id"]) != a for r, a in zip(refs, applied)):
206
+ v.append("rule 2: an invoice line total does not equal the amount applied to it")
207
+ if refs and sum(applied) != total_of(checkout):
208
+ v.append("rule 2: invoice lines do not sum to the checkout total")
209
+ return v
210
+
211
+
212
+ def _verdict(verdict: str, reason: str) -> dict:
213
+ return {"verdict": verdict, "reason": reason}
214
+
215
+
216
+ def verify(checkout: dict, order: dict, bundle: dict, config: VerifierConfig) -> dict:
217
+ violations = structural_violations(checkout, order)
218
+ refs = checkout.get("invoice_reference") or []
219
+ if violations or not refs:
220
+ reason = "; ".join(violations) or "no invoice_reference present"
221
+ return {
222
+ "valid": False,
223
+ "violations": violations,
224
+ "verdicts": {
225
+ "registration_matches_invoice": _verdict(NOT_ESTABLISHED, f"input invalid: {reason}"),
226
+ "registration_active_at_payment": _verdict(NOT_ESTABLISHED, f"input invalid: {reason}"),
227
+ "signed_by_checkout_business": _verdict(NOT_ESTABLISHED, f"input invalid: {reason}"),
228
+ },
229
+ }
230
+
231
+ # ---- verified status claims (only the verified claims are read)
232
+ status_claims = None
233
+ status_note = None
234
+ sev = bundle.get("status_evidence")
235
+ if sev and sev.get("jws"):
236
+ try:
237
+ status_claims = verify_rs256(sev["jws"], config.scheme_public_key)
238
+ except (InvalidSignature, ValueError, KeyError):
239
+ status_note = "status evidence signature does not verify under the configured scheme key"
240
+ elif bundle.get("lookup_outcome"):
241
+ status_note = f"status lookup outcome: {bundle['lookup_outcome']} (not evidence)"
242
+ else:
243
+ status_note = "no authenticated status evidence supplied"
244
+
245
+ # ---- per-entry verdicts for matches and active-at-payment
246
+ matches_results, active_results = [], []
247
+ for ref in refs:
248
+ matches_results.append(_matches(ref, bundle, status_claims, config))
249
+ active_results.append(_active(ref, checkout, bundle, status_claims, status_note, config))
250
+
251
+ signed = _signed_by_business(checkout, order, config)
252
+ return {
253
+ "valid": True,
254
+ "violations": [],
255
+ "verdicts": {
256
+ "registration_matches_invoice": _aggregate(matches_results),
257
+ "registration_active_at_payment": _aggregate(active_results),
258
+ "signed_by_checkout_business": signed,
259
+ },
260
+ }
261
+
262
+
263
+ def _aggregate(results: list) -> dict:
264
+ for wanted in (CONTRADICTED, NOT_ESTABLISHED):
265
+ for r in results:
266
+ if r["verdict"] == wanted:
267
+ return r
268
+ return results[0]
269
+
270
+
271
+ def rupees_to_minor(value):
272
+ """Convert a rupee amount to minor units EXACTLY (RC4 check 1).
273
+
274
+ int() truncation dropped paise: Rs 118,000.25 became 11,800,000
275
+ instead of 11,800,025, contradicting the exact amount and
276
+ establishing the truncated one. Decimal over the value's string
277
+ form is exact; a value with sub-paise precision converts to None
278
+ (it cannot equal any minor-unit total)."""
279
+ try:
280
+ minor = Decimal(str(value)) * 100
281
+ except (InvalidOperation, ValueError):
282
+ return None
283
+ if minor != minor.to_integral_value():
284
+ return None
285
+ return int(minor)
286
+
287
+
288
+ _DATE_ONLY = re.compile(r"^(\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4})$")
289
+
290
+
291
+ def is_date_only(value) -> bool:
292
+ """True when a timestamp string states only a date (day precision)."""
293
+ return isinstance(value, str) and bool(_DATE_ONLY.match(value.strip()))
294
+
295
+
296
+ def _matches(ref: dict, bundle: dict, status_claims, config: VerifierConfig) -> dict:
297
+ reg = ref.get("registration")
298
+ if not reg:
299
+ return _verdict(NOT_ESTABLISHED, "no registration in this reference entry")
300
+ # Authoritative absence, evaluated WITH the artifact evidence
301
+ # rather than before it (RC4 check 4): absence alone contradicts,
302
+ # but absence alongside a verified matching invoice is a conflict
303
+ # of authenticated evidence -> not established, conflict reported.
304
+ absence = bool(status_claims) and status_claims.get("status") == "not_found" \
305
+ and status_claims.get("registration_identifier") == reg["identifier"]
306
+ artifact = bundle.get("artifact")
307
+ if not artifact:
308
+ if absence:
309
+ return _verdict(CONTRADICTED,
310
+ "authoritative negative response of known scope: the scheme "
311
+ "reports no such registration")
312
+ outcome = bundle.get("lookup_outcome")
313
+ if outcome:
314
+ return _verdict(NOT_ESTABLISHED,
315
+ f"lookup outcome '{outcome}' is not evidence; no artifact supplied")
316
+ return _verdict(NOT_ESTABLISHED, "no scheme artifact supplied")
317
+ digest = "sha256:" + hashlib.sha256(artifact.strip().encode()).hexdigest()
318
+ if digest != reg["artifact_digest"]:
319
+ return _verdict(NOT_ESTABLISHED,
320
+ "supplied artifact does not match the reference's artifact_digest")
321
+ try:
322
+ payload = verify_rs256(artifact.strip(), config.scheme_public_key)
323
+ except (InvalidSignature, ValueError, KeyError):
324
+ return _verdict(NOT_ESTABLISHED,
325
+ "artifact signature does not verify under the configured scheme key")
326
+ f = artifact_fields(payload)
327
+ # RC4 check 3: a match can only be established by an artifact that
328
+ # carries recognizable invoice or QR claims. A validly signed
329
+ # status response supplied in the artifact slot binds none of
330
+ # them, and previously established a match by default.
331
+ if not any(f.get(k) is not None
332
+ for k in ("DocNo", "DocTyp", "SellerGstin", "TotInvVal", "Irn")):
333
+ return _verdict(NOT_ESTABLISHED,
334
+ "supplied artifact carries no recognizable invoice or "
335
+ "QR claims; a match cannot be established from it")
336
+ doc = ref["document"]
337
+ mismatches = []
338
+ def cmp_field(name, artifact_value, ref_value):
339
+ if artifact_value is not None and str(artifact_value) != str(ref_value):
340
+ mismatches.append(f"{name}: artifact {artifact_value!r} != reference {ref_value!r}")
341
+ cmp_field("document number", f.get("DocNo"), doc["number"])
342
+ cmp_field("document type", f.get("DocTyp"), doc["type"])
343
+ cmp_field("issuer tax identity", f.get("SellerGstin"), doc["issuer_tax_identity"])
344
+ doc_dt, _ = parse_time(f.get("DocDt")) if f.get("DocDt") else (None, False)
345
+ if doc_dt is not None and doc_dt.date().isoformat() != doc["issue_date"]:
346
+ mismatches.append(f"issue date: artifact {f.get('DocDt')!r} != reference {doc['issue_date']!r}")
347
+ if f.get("TotInvVal") is not None and rupees_to_minor(f["TotInvVal"]) != doc["total"]:
348
+ mismatches.append(f"total: artifact {f['TotInvVal']!r} (rupees) != reference {doc['total']!r} (minor units)")
349
+ cmp_field("registration identifier", f.get("Irn"), reg["identifier"])
350
+ if mismatches:
351
+ return _verdict(CONTRADICTED, "verified mismatch -- " + "; ".join(mismatches))
352
+ if absence:
353
+ return _verdict(NOT_ESTABLISHED,
354
+ "conflicting authenticated evidence: the verified artifact "
355
+ "establishes this registration and an authoritative response "
356
+ "reports no such registration for the same identifier; the "
357
+ "conflict is reported and neither side is preferred")
358
+ return _verdict(ESTABLISHED,
359
+ "artifact signature verifies and every field the artifact binds matches")
360
+
361
+
362
+ def _active(ref: dict, checkout: dict, bundle: dict, status_claims, status_note,
363
+ config: VerifierConfig) -> dict:
364
+ reg = ref.get("registration")
365
+ if not reg:
366
+ return _verdict(NOT_ESTABLISHED, "no registration in this reference entry")
367
+ pay = bundle.get("payment_event")
368
+ if not pay:
369
+ return _verdict(NOT_ESTABLISHED, "no payment-event evidence supplied")
370
+ total = [t["amount"] for t in checkout["totals"] if t["type"] == "total"][0]
371
+ binding_failures = []
372
+ if pay.get("status") != "captured":
373
+ binding_failures.append("payment event is not a confirmed capture")
374
+ if pay.get("checkout_id") != checkout["id"]:
375
+ binding_failures.append("capture checkout_id does not equal the accepted checkout id")
376
+ if config.expected_payment_id is None:
377
+ # RC3 blocker 3: without an independently configured expected
378
+ # payment identifier the capture cannot be bound at all.
379
+ binding_failures.append("no expected payment identifier is configured; "
380
+ "the capture cannot be bound to the checkout's payment")
381
+ elif pay.get("payment_id") != config.expected_payment_id:
382
+ binding_failures.append("capture payment_id is not the expected payment identifier")
383
+ if pay.get("amount") != total:
384
+ binding_failures.append("capture amount does not equal the checkout total")
385
+ if pay.get("currency") != checkout["currency"]:
386
+ binding_failures.append("capture currency does not equal the checkout currency")
387
+ if binding_failures:
388
+ return _verdict(NOT_ESTABLISHED,
389
+ "payment event not bound to the accepted checkout -- "
390
+ + "; ".join(binding_failures))
391
+ pay_time = aware_time(pay.get("captured_at"), config)
392
+ if pay_time is None:
393
+ return _verdict(NOT_ESTABLISHED, "no trusted payment time supplied")
394
+
395
+ # Authenticated registration time: ONLY from an artifact that is
396
+ # bound to this reference (its digest is the reference's
397
+ # artifact_digest and its IRN is the reference's identifier) and
398
+ # whose signature verifies -- and only from that artifact's AckDt.
399
+ # RC3 blocker 1: the reference's own registered_at is the
400
+ # business's statement, never evidence; it supplied the time here
401
+ # before and established this verdict on a claim.
402
+ # RC3 blocker 2: an artifact failing digest or IRN binding
403
+ # previously supplied its AckDt on signature validity alone.
404
+ reg_time = None
405
+ artifact = bundle.get("artifact")
406
+ if artifact:
407
+ digest = "sha256:" + hashlib.sha256(artifact.strip().encode()).hexdigest()
408
+ if digest != reg["artifact_digest"]:
409
+ return _verdict(NOT_ESTABLISHED,
410
+ "supplied artifact does not match the reference's "
411
+ "artifact_digest; its timestamps are not evidence "
412
+ "for this reference")
413
+ try:
414
+ fields = artifact_fields(verify_rs256(artifact.strip(), config.scheme_public_key))
415
+ except (InvalidSignature, ValueError, KeyError):
416
+ return _verdict(NOT_ESTABLISHED, "artifact does not verify; no authenticated registration time")
417
+ if fields.get("Irn") != reg["identifier"]:
418
+ return _verdict(NOT_ESTABLISHED,
419
+ "supplied artifact binds a different registration "
420
+ "identifier; its timestamps are not evidence for "
421
+ "this reference")
422
+ if fields.get("AckDt"):
423
+ if is_date_only(fields["AckDt"]):
424
+ # RC4 check 2 / spec 8.4: a date-only registration
425
+ # time cannot be ordered against a payment event on
426
+ # that date; reading it as midnight invents precision
427
+ # the evidence does not state.
428
+ return _verdict(NOT_ESTABLISHED,
429
+ "registration time (AckDt) is stated only at day "
430
+ "precision, so its ordering against the payment "
431
+ "event is unresolved (spec section 8.4)")
432
+ reg_time = aware_time(fields["AckDt"], config)
433
+ if reg_time is None:
434
+ return _verdict(NOT_ESTABLISHED,
435
+ "registration time (AckDt) carries no offset and no "
436
+ "documented scheme timezone is configured, so it "
437
+ "cannot be ordered against the payment event")
438
+ if reg_time is None:
439
+ return _verdict(NOT_ESTABLISHED,
440
+ "no authenticated registration time at usable precision "
441
+ "(the reference's registered_at is a business claim, "
442
+ "not evidence)")
443
+
444
+ if status_claims is None:
445
+ return _verdict(NOT_ESTABLISHED, status_note or "no authenticated status evidence")
446
+ if status_claims.get("registration_identifier") != reg["identifier"]:
447
+ return _verdict(NOT_ESTABLISHED,
448
+ "status evidence binds a different registration identifier "
449
+ "than the reference (signature validity is separate)")
450
+ if status_claims.get("status") == "not_found":
451
+ return _verdict(NOT_ESTABLISHED,
452
+ "the scheme reports no such registration; activity cannot be established")
453
+
454
+ cancelled_at = aware_time(status_claims.get("cancelled_at"), config) \
455
+ if status_claims.get("cancelled_at") else None
456
+ observed_at = aware_time(status_claims.get("observed_at"), config) \
457
+ if status_claims.get("observed_at") else None
458
+ no_reinstatement = config.no_reinstatement_rule or \
459
+ "not reinstated" in (status_claims.get("scheme_rule") or "")
460
+
461
+ if cancelled_at is not None and cancelled_at <= pay_time \
462
+ and status_claims.get("status") == "active" \
463
+ and observed_at is not None and observed_at >= pay_time:
464
+ return _verdict(NOT_ESTABLISHED,
465
+ "conflicting authenticated evidence: a cancellation at or "
466
+ "before the payment event and an active observation at or "
467
+ "after it are both present")
468
+ if cancelled_at is not None and cancelled_at <= pay_time:
469
+ return _verdict(CONTRADICTED,
470
+ "authenticated cancellation took effect at or before the payment event")
471
+ if reg_time <= pay_time and cancelled_at is not None and cancelled_at > pay_time:
472
+ return _verdict(ESTABLISHED,
473
+ "registration time is at or before the payment event and the "
474
+ "authenticated cancellation falls after it")
475
+ if reg_time <= pay_time and status_claims.get("status") == "active" \
476
+ and observed_at is not None and observed_at >= pay_time and no_reinstatement:
477
+ return _verdict(ESTABLISHED,
478
+ "registration time is at or before the payment event, an "
479
+ "authenticated active observation at or after it is present, "
480
+ "and the scheme's documented rule is that a cancelled "
481
+ "registration cannot be reinstated")
482
+ return _verdict(NOT_ESTABLISHED,
483
+ "the authenticated evidence does not establish activity at the payment event")
484
+
485
+
486
+ def _signed_by_business(checkout: dict, order: dict, config: VerifierConfig) -> dict:
487
+ auth = (checkout.get("ap2") or {}).get("merchant_authorization")
488
+ if not auth:
489
+ return _verdict(NOT_ESTABLISHED, "the checkout carries no AP2 merchant authorization")
490
+ if config.merchant_public_key is None:
491
+ return _verdict(NOT_ESTABLISHED, "no merchant key is configured")
492
+ head_b64, _, sig_b64 = auth.partition("..")
493
+ if not sig_b64:
494
+ return _verdict(NOT_ESTABLISHED, "merchant authorization is not a detached JWS")
495
+ signed_checkout = {k: v for k, v in checkout.items() if k != "ap2"}
496
+ canonical = rfc8785.dumps(signed_checkout)
497
+ signing_input = (head_b64 + "." +
498
+ base64.urlsafe_b64encode(canonical).rstrip(b"=").decode()).encode()
499
+ raw = b64u_decode(sig_b64)
500
+ der = encode_dss_signature(int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big"))
501
+ try:
502
+ config.merchant_public_key.verify(der, signing_input, ec.ECDSA(hashes.SHA256()))
503
+ except InvalidSignature:
504
+ return _verdict(NOT_ESTABLISHED,
505
+ "merchant signature does not verify over the final checkout")
506
+ if order.get("invoice_reference") != checkout.get("invoice_reference"):
507
+ return _verdict(NOT_ESTABLISHED, "the order's snapshot differs from the signed checkout's reference")
508
+ if order.get("checkout_id") != checkout.get("id"):
509
+ return _verdict(NOT_ESTABLISHED, "the order's checkout_id is not the signed checkout's id")
510
+ return _verdict(ESTABLISHED,
511
+ "merchant signature verifies over the final checkout, the order's "
512
+ "snapshot equals its reference, and the order names that checkout")
513
+
514
+
515
+ # ------------------------------------------------------------------ config
516
+ def load_config(root: pathlib.Path, entry: str) -> VerifierConfig:
517
+ """Build a VerifierConfig from validation/trust_config.json + the
518
+ independently configured key files it names."""
519
+ cfg = json.loads((root / "validation" / "trust_config.json").read_text())[entry]
520
+ scheme_key = serialization.load_pem_public_key(
521
+ (root / "validation" / cfg["irp_public_key"]).read_bytes())
522
+ merchant_key = None
523
+ if cfg.get("merchant_public_key"):
524
+ jwk = json.loads((root / "validation" / cfg["merchant_public_key"]).read_text())
525
+ nums = ec.EllipticCurvePublicNumbers(
526
+ int.from_bytes(b64u_decode(jwk["x"]), "big"),
527
+ int.from_bytes(b64u_decode(jwk["y"]), "big"), ec.SECP256R1())
528
+ merchant_key = nums.public_key()
529
+ return VerifierConfig(
530
+ scheme_public_key=scheme_key,
531
+ merchant_public_key=merchant_key,
532
+ expected_payment_id=cfg.get("expected_payment_id"),
533
+ scheme_timezone=cfg.get("scheme_timezone"),
534
+ )
535
+
536
+
537
+ def load_bundle(example_dir: pathlib.Path) -> dict:
538
+ ev = example_dir / "evidence"
539
+ artifact = None
540
+ for name in ("signed_qr_code.jwt.txt", "scheme_artifact.jwt.txt"):
541
+ if (ev / name).exists():
542
+ artifact = (ev / name).read_text().strip()
543
+ status = json.loads((ev / "status_evidence.json").read_text()) \
544
+ if (ev / "status_evidence.json").exists() else None
545
+ pay = json.loads((ev / "payment_event.json").read_text()) \
546
+ if (ev / "payment_event.json").exists() else None
547
+ return {"artifact": artifact, "status_evidence": status, "payment_event": pay}
548
+
549
+
550
+ def verify_example(root: pathlib.Path, example: str, config_entry: str) -> dict:
551
+ d = root / "examples" / example
552
+ checkout = json.loads((d / "checkout.json").read_text())
553
+ order = json.loads((d / "order.json").read_text())
554
+ return verify(checkout, order, load_bundle(d), load_config(root, config_entry))
555
+
556
+
557
+ if __name__ == "__main__":
558
+ import sys
559
+ root = pathlib.Path(__file__).resolve().parent.parent
560
+ for example, entry in (("example-1-operator-sample", "example1"),
561
+ ("example-2-synthetic-full", "example2"),
562
+ ("example-3-production-shaped-irp", "example3")):
563
+ result = verify_example(root, example, entry)
564
+ print(example, json.dumps(result["verdicts"], indent=2))
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: invoice-registration-reference
3
+ Version: 0.1.0
4
+ Summary: Offline Python reference verifier for invoice-registration evidence in UCP checkout and order payloads
5
+ Author: Agorail Labs
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Source, https://github.com/agorail-labs/invoice-registration-reference
8
+ Project-URL: Specification, https://agorail-labs.github.io/invoice-registration-reference/spec/invoice-registration-reference-v0.1.md
9
+ Project-URL: Schema, https://agorail-labs.github.io/invoice-registration-reference/schema/invoice_reference.json
10
+ Project-URL: Issues, https://github.com/agorail-labs/invoice-registration-reference/issues
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: THIRD_PARTY_NOTICES.md
19
+ Requires-Dist: cryptography>=41
20
+ Requires-Dist: rfc8785>=0.1.4
21
+ Requires-Dist: tzdata>=2024.1
22
+ Dynamic: license-file
23
+
24
+ # Invoice Registration Reference
25
+
26
+ An offline Python reference verifier for invoice-registration evidence carried in UCP checkout and order payloads. Version 0.1 models a merchant collecting its own already-issued invoice in INR under India's GST e-invoice scheme.
27
+
28
+ ```python
29
+ from invoice_registration_reference import VerifierConfig, verify
30
+ ```
31
+
32
+ Call `verify(checkout, order, evidence_bundle, config)` with parsed, schema-validated payloads, the evidence bundle described in the specification, and an independently configured `VerifierConfig`. The result reports whether the invoice registration matches, whether it was active at payment, and whether the checkout business signed the reference.
33
+
34
+ Run the repository's fixtures and conformance suite for runnable examples. Status and capture fixtures are simulated. Matching capture fields binds a capture to a checkout; live capture evidence requires authentication by the caller's payment integration. The verifier operates offline and does not initiate payments or resolve invoice evidence from a live registry.
35
+
36
+ - [Source, examples, and conformance suite](https://github.com/agorail-labs/invoice-registration-reference)
37
+ - [Specification](https://agorail-labs.github.io/invoice-registration-reference/spec/invoice-registration-reference-v0.1.md)
38
+ - [Capability schema](https://agorail-labs.github.io/invoice-registration-reference/schema/invoice_reference.json)
@@ -0,0 +1,8 @@
1
+ invoice_registration_reference/__init__.py,sha256=zfLFWakEeS54Bi_w1kthLc19UJBS_N0wy9QAwK85hk4,184
2
+ invoice_registration_reference/invoice_reference_verifier.py,sha256=332PbUAYTtoMqJn-LTgqy3rTprkuAz4V9PcXPvS_yhc,27645
3
+ invoice_registration_reference-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
4
+ invoice_registration_reference-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=f068yFkLdNgmYH01R2JlVoOu6uxej6rouPVra6Zpj5g,1784
5
+ invoice_registration_reference-0.1.0.dist-info/METADATA,sha256=oWUNNDHh5q4yhRZMgw7RSWHRkRqS7F7o2nWLjOhVkk4,2500
6
+ invoice_registration_reference-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ invoice_registration_reference-0.1.0.dist-info/top_level.txt,sha256=cDa8SpzGqXQU6sZZPXHBjdrkNn5qmr8xryPteVtVLwE,31
8
+ invoice_registration_reference-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,38 @@
1
+ # Third-party notices
2
+
3
+ This repository is licensed under the Apache License 2.0 (see
4
+ `LICENSE`). It also contains or reproduces the following third-party
5
+ material, retained with its upstream licensing and provenance.
6
+
7
+ ## UCP published schemas (vendored cache)
8
+
9
+ `validation/schema_cache/` holds an unmodified copy of the published
10
+ JSON Schemas of the Universal Commerce Protocol (UCP), version
11
+ 2026-08-25 — 46 files fetched from https://ucp.dev/2026-08-25/schemas/
12
+ on 26 November 2026 and pinned so validation runs are reproducible
13
+ (the live fetch path intermittently truncates responses).
14
+
15
+ - Project: Universal Commerce Protocol — https://ucp.dev,
16
+ https://github.com/universal-commerce-protocol/ucp
17
+ - Licence: Apache License 2.0 (the UCP project's licence; the full
18
+ text is the same licence as this repository's `LICENSE`).
19
+ - These files are upstream material, not part of this extension's own
20
+ specification, and are used only as validation inputs (the base
21
+ schemas this extension composes over).
22
+
23
+ ## NIC published sample and public key (Example 1)
24
+
25
+ `examples/example-1-operator-sample/evidence/` reproduces the sample
26
+ Signed QR Code and the IRP public key printed in NIC's published QR
27
+ code procedure document for the Indian e-invoice system (portal:
28
+ einvoice1.gst.gov.in), which publishes the sample and the key for
29
+ anyone to verify with. The sample carries dummy particulars and is
30
+ used as a signed documentation vector, as its fixture notes record.
31
+ No real invoice is used anywhere in this repository.
32
+
33
+ ## Development dependencies (not vendored)
34
+
35
+ The verifier and harnesses run on `cryptography`, `rfc8785` and
36
+ `jsonschema` (see `verifier/requirements.txt`), installed by the user
37
+ from PyPI under their own licences; no dependency code is included in
38
+ this repository.
@@ -0,0 +1 @@
1
+ invoice_registration_reference