"""Borrou Partner API: collateral-address verification. v0.1 DRAFT. Needs the ``cryptography`` package (``pip install cryptography``) for Ed25519; the rest is the standard library. Every deposit and top-up address comes with ``address_attestation``: Borrou's Ed25519 signature over a short statement of the address. Verify it before your app shows the address, and show the verification code beside it; the borrower's loan page shows the same code with the same address. 1. Find the key: ``GET /v1/address-keys`` lists the public keys by ``key_id`` (no credential needed). Cache the list; fetch it again when an attestation names a key id you do not hold. 2. Verify the signature over the statement's UTF-8 bytes exactly as received. 3. Read the statement: eight ``name=value`` lines in a fixed order, LF-separated, no trailing newline, for purpose ``BORROU_COLLATERAL_ADDRESS_V1``, asset ``BTC``, network ``bitcoin``, and the same key id as the attestation. 4. Check its address and loan reference against what you are about to show. 5. Work out the verification code from the signature and check it is the one you were given. Anything else: show no address, and contact TFG. """ from __future__ import annotations import base64 import hashlib import re from typing import Dict, Mapping, Optional, Sequence, Tuple from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey FIELDS = ("purpose", "asset", "network", "address", "loan_reference", "wallet", "key_id", "signed_at") _VALUE = re.compile(r"[\x21-\x7e]+") def _b64url(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) def read_statement(statement: str) -> Optional[Dict[str, str]]: """The statement's fields, or None for anything Borrou would not sign.""" lines = statement.split("\n") if len(lines) != len(FIELDS): return None fields: Dict[str, str] = {} for name, line in zip(FIELDS, lines): key, sep, value = line.partition("=") # Every value is printable ASCII with no spaces: a CR, a space or anything else is not Borrou's. if not sep or key != name or not _VALUE.fullmatch(value): return None fields[name] = value if fields["purpose"] != "BORROU_COLLATERAL_ADDRESS_V1" or fields["asset"] != "BTC" or fields["network"] != "bitcoin": return None return fields def verification_code(signature: str) -> str: """The first eight base32 characters of SHA-256(signature bytes), as XXXX-XXXX.""" code = base64.b32encode(hashlib.sha256(_b64url(signature)).digest()).decode("ascii")[:8] return f"{code[:4]}-{code[4:]}" def verify_address_attestation( shown: Mapping[str, str], attestation: Mapping[str, str], keys: Sequence[Mapping[str, str]], ) -> Tuple[bool, str]: """Returns (True, verification code), or (False, "unknown_key" | "bad_signature" | "malformed_statement" | "address_mismatch" | "loan_mismatch" | "code_mismatch").""" key = next((k for k in keys if k["key_id"] == attestation["key_id"]), None) if key is None: return False, "unknown_key" signature = _b64url(attestation["signature"]) try: if len(signature) != 64: raise InvalidSignature() Ed25519PublicKey.from_public_bytes(_b64url(key["public_key"])).verify(signature, attestation["statement"].encode("utf-8")) except InvalidSignature: return False, "bad_signature" fields = read_statement(attestation["statement"]) if fields is None or fields["key_id"] != attestation["key_id"]: return False, "malformed_statement" if fields["address"] != shown["address"]: return False, "address_mismatch" if fields["loan_reference"] != shown["loan_reference"]: return False, "loan_mismatch" code = verification_code(attestation["signature"]) if code != attestation["verification_code"]: return False, "code_mismatch" return True, code # With the API (borrou_client.py): # # keys = client.get("/v1/address-keys").body["keys"] # deposit = client.get(f"/v1/loans/{reference}/collateral/deposit-address").body # if deposit["address_attestation"] is None: # raise RuntimeError("Unsigned address: sandbox only; never show it as verified.") # ok, code = verify_address_attestation({"address": deposit["address"], "loan_reference": reference}, deposit["address_attestation"], keys) # if not ok: # raise RuntimeError(f"Do not show this address ({code}); contact TFG.") # show(deposit["address"], code)