Chapter 10 · Code Snippet 10.1
The Digital Notary
C2PA reality-handshake validator
A reference implementation of the 'reality handshake' described in Chapter 10. Loads the official C2PA Trust List, then verifies a file's C2PA manifest for identity and tamper status, returning VERIFIED, WARNING, TAMPERED, or UNSIGNED.
c2pa_validator.py142 lines · Python
# File: c2pa_validator.py# Dependency: c2pa-python (official Coalition for Content Provenance# and Authenticity bindings, contentauth/c2pa-python on GitHub)# Install: pip install c2pa-python (written against c2pa-python 0.38) import hashlibimport jsonimport urllib.requestfrom dataclasses import dataclass, fieldfrom typing import Optional import c2pa # The official C2PA Trust List, published under the C2PA Conformance Program.# The older Interim Trust List (contentcredentials.org/trust/anchors.pem) was# frozen on January 1, 2026: no new entries, kept only for legacy validation.# Source: https://opensource.contentauthenticity.org/docs/conformance/trust-listsTRUST_ANCHORS_URL = ( "https://raw.githubusercontent.com/c2pa-org/conformance-public/" "main/trust-list/C2PA-TRUST-LIST.pem") # Verification statuses.VERIFIED = "VERIFIED"WARNING = "WARNING"TAMPERED = "TAMPERED"UNSIGNED = "UNSIGNED" # Validation codes (C2PA specification) that mean the content no longer# matches what was signed.TAMPER_CODES = { "assertion.dataHash.mismatch", "assertion.bmffHash.mismatch", "assertion.boxesHash.mismatch", "assertion.collectionHash.mismatch", "assertion.hashedURI.mismatch", "claimSignature.mismatch",} @dataclassclass ValidationResult: status: str # VERIFIED, WARNING, TAMPERED, or UNSIGNED provenance_gap: float # 0.0 (complete chain) to 1.0 (no credentials) reason: str = "" issuer: Optional[str] = None claim_generator: Optional[str] = None ingredients: list = field(default_factory=list) # the chain of edits class RealityValidator: """ The Digital Notary: a logic gate for verifying Content Credentials. Simulates the 'reality handshake' performed by a browser, social platform, or newsroom verification pipeline. """ def __init__(self, trust_anchors_pem: Optional[str] = None): # Load the trust anchors and bind them to a c2pa.Settings object # that the Reader will consult during validation. Pass your own PEM # bundle to validate offline or against a private trust list. if trust_anchors_pem is None: with urllib.request.urlopen(TRUST_ANCHORS_URL) as response: trust_anchors_pem = response.read().decode("utf-8") self.settings = c2pa.Settings.from_dict({ "verify": {"verify_cert_anchors": True}, "trust": {"trust_anchors": trust_anchors_pem}, }) def validate_asset(self, file_path: str) -> ValidationResult: """ Input: Path to an image or video file. Output: ValidationResult with a status (VERIFIED, WARNING, TAMPERED, UNSIGNED) and the Provenance Gap (PG) the Circuit Breaker reads. """ # Step 1: Extract the 'Digital Nutrition Label' (Manifest). # The book prints the older c2pa.Reader.from_file() call; current # c2pa-python opens the file with c2pa.Reader(path). try: with c2pa.Context(self.settings) as context: with c2pa.Reader(str(file_path), context=context) as reader: manifest_json = json.loads(reader.json()) except Exception: # No manifest found. return ValidationResult(status=UNSIGNED, provenance_gap=1.0, reason="No credentials found (Gray Zone)") active_label = manifest_json.get("active_manifest") manifest = manifest_json.get("manifests", {}).get(active_label, {}) ingredients = manifest.get("ingredients", []) # Walk ingredients[]: chain_completeness is the share of ingredients # that carry Content Credentials of their own (1.0 if there are none). if ingredients: signed = sum(1 for i in ingredients if i.get("active_manifest")) chain_completeness = signed / len(ingredients) else: chain_completeness = 1.0 pg = round(1.0 - chain_completeness, 4) # The Reader reports its checks at the top level, in # validation_results['activeManifest']['failure']. failures = (manifest_json.get("validation_results") or {}) \ .get("activeManifest", {}).get("failure", []) codes = [f.get("code", "") for f in failures] # Step 2: Verify the integrity (has it been tampered with?). # The c2pa library validates hard-binding hashes during Reader # construction. A mismatch means the pixels changed after signing. if any(code in TAMPER_CODES for code in codes): return ValidationResult(status=TAMPERED, provenance_gap=pg, reason="Hash mismatch (deepfake injection)") # Step 3: Verify the identity (who signed this?). # The Reader has already checked the signing certificate against the # trust anchors loaded above. A trust failure is reported with a code # starting with 'signingCredential' (for example .untrusted). if any(code.startswith("signingCredential") for code in codes): return ValidationResult(status=WARNING, provenance_gap=pg, reason="Identity unknown or self-signed") # Step 4: The handshake is complete. return ValidationResult( status=VERIFIED, provenance_gap=pg, issuer=manifest.get("signature_info", {}).get("issuer"), claim_generator=manifest.get("claim_generator") or next( (g.get("name") for g in manifest.get("claim_generator_info", [])), None), ingredients=ingredients, ) @staticmethod def _calculate_sha256(file_path: str) -> str: """Standard cryptographic hash of the binary file (illustrative; the c2pa Reader performs hard-binding validation internally).""" sha = hashlib.sha256() with open(file_path, "rb") as f: for block in iter(lambda: f.read(4096), b""): sha.update(block) return sha.hexdigest()