Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
419 lines
14 KiB
Python
419 lines
14 KiB
Python
"""Real Mint hold/capture/release boundary for Prism success-only billing."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import Any, Protocol
|
|
|
|
import httpx
|
|
from app.domains.wallet.hold_settlement_attestation import (
|
|
HoldSettlementExpected,
|
|
verify_hold_settlement_attestation,
|
|
)
|
|
from app.domains.wallet.transfer_attestation import load_pinned_public_keys
|
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
|
|
from .models import SettlementReceipt
|
|
|
|
|
|
class MintSettlementError(RuntimeError):
|
|
"""Normalized Mint failure with explicit ambiguity semantics."""
|
|
|
|
def __init__(self, message: str, status_code: int, *, ambiguous: bool) -> None:
|
|
super().__init__(message)
|
|
self.status_code = status_code
|
|
self.ambiguous = ambiguous
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class HoldAuthorization:
|
|
hold_id: str
|
|
reserved_micros: int
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SettlementCommand:
|
|
hold_id: str
|
|
reserved_micros: int
|
|
status: str = "authorized"
|
|
charged_micros: int = 0
|
|
receipt_json: str = ""
|
|
submission_started: bool = False
|
|
last_error: str = ""
|
|
|
|
|
|
class SettlementPort(Protocol):
|
|
def authorize(
|
|
self, owner: str, correlation_id: str, amount_micros: int
|
|
) -> HoldAuthorization: ...
|
|
|
|
def capture(
|
|
self,
|
|
owner: str,
|
|
authorization: HoldAuthorization,
|
|
generation_id: str,
|
|
amount_micros: int,
|
|
) -> SettlementReceipt: ...
|
|
|
|
def release(
|
|
self, owner: str, authorization: HoldAuthorization, generation_id: str
|
|
) -> SettlementReceipt: ...
|
|
|
|
def readiness(self) -> dict[str, str]: ...
|
|
|
|
|
|
class UnconfiguredMintSettlement:
|
|
"""Fail-closed runtime boundary used when mandatory Mint config is absent."""
|
|
|
|
_MESSAGE = "Prism Mint settlement is not configured"
|
|
|
|
def authorize(
|
|
self, owner: str, correlation_id: str, amount_micros: int
|
|
) -> HoldAuthorization:
|
|
del owner, correlation_id, amount_micros
|
|
raise MintSettlementError(self._MESSAGE, 503, ambiguous=False)
|
|
|
|
def capture(
|
|
self,
|
|
owner: str,
|
|
authorization: HoldAuthorization,
|
|
generation_id: str,
|
|
amount_micros: int,
|
|
) -> SettlementReceipt:
|
|
del owner, authorization, generation_id, amount_micros
|
|
raise MintSettlementError(self._MESSAGE, 503, ambiguous=False)
|
|
|
|
def release(
|
|
self, owner: str, authorization: HoldAuthorization, generation_id: str
|
|
) -> SettlementReceipt:
|
|
del owner, authorization, generation_id
|
|
raise MintSettlementError(self._MESSAGE, 503, ambiguous=False)
|
|
|
|
def readiness(self) -> dict[str, str]:
|
|
return {"status": "unconfigured", "detail": self._MESSAGE}
|
|
|
|
|
|
class MintSettlementClient:
|
|
"""Authenticated HTTP client whose stable keys make every money op replayable."""
|
|
|
|
def __init__(
|
|
self,
|
|
base_url: str,
|
|
api_key: str,
|
|
payee_account: str,
|
|
payer_accounts: dict[str, str],
|
|
pinned_public_keys: dict[str, Ed25519PublicKey],
|
|
*,
|
|
client: httpx.Client | None = None,
|
|
timeout: float = 10.0,
|
|
) -> None:
|
|
self._api_key = api_key.strip()
|
|
self._payee = payee_account.strip()
|
|
self._payers = {
|
|
str(owner).strip().lower(): str(account).strip()
|
|
for owner, account in payer_accounts.items()
|
|
if str(owner).strip() and str(account).strip()
|
|
}
|
|
if not pinned_public_keys:
|
|
raise ValueError("at least one Mint attestation key must be pinned")
|
|
self._pinned_public_keys = dict(pinned_public_keys)
|
|
self._client = client or httpx.Client(
|
|
base_url=base_url.rstrip("/"),
|
|
headers={"x-api-key": self._api_key},
|
|
timeout=timeout,
|
|
)
|
|
|
|
@classmethod
|
|
def from_environment(cls) -> SettlementPort:
|
|
base_url = os.getenv("PRISM_MINT_SERVER_URL", "").strip()
|
|
api_key = os.getenv("PRISM_MINT_API_KEY", "").strip()
|
|
payee = os.getenv("PRISM_MINT_PAYEE_ACCOUNT", "").strip()
|
|
raw_map = os.getenv("PRISM_MINT_PAYER_ACCOUNTS_JSON", "").strip()
|
|
raw_keys = os.getenv("PRISM_MINT_ATTESTATION_PUBLIC_KEYS_JSON", "").strip()
|
|
if not all((base_url, api_key, payee, raw_map, raw_keys)):
|
|
return UnconfiguredMintSettlement()
|
|
try:
|
|
parsed = json.loads(raw_map)
|
|
except json.JSONDecodeError:
|
|
return UnconfiguredMintSettlement()
|
|
if not isinstance(parsed, dict):
|
|
return UnconfiguredMintSettlement()
|
|
try:
|
|
pinned_keys = load_pinned_public_keys(raw_keys)
|
|
except (TypeError, ValueError):
|
|
return UnconfiguredMintSettlement()
|
|
return cls(base_url, api_key, payee, parsed, pinned_keys)
|
|
|
|
@staticmethod
|
|
def _idempotency_key(operation: str, *parts: str) -> str:
|
|
digest = hashlib.sha256("\0".join((operation, *parts)).encode()).hexdigest()
|
|
return f"prism:{operation}:{digest}"
|
|
|
|
def _payer(self, owner: str) -> str:
|
|
account = self._payers.get(owner.strip().lower(), "")
|
|
if not account:
|
|
raise MintSettlementError(
|
|
"Prism API key has no funded Mint account", 402, ambiguous=False
|
|
)
|
|
return account
|
|
|
|
def _request(
|
|
self, method: str, path: str, body: dict[str, Any] | None = None
|
|
) -> tuple[Any, httpx.Headers]:
|
|
try:
|
|
response = self._client.request(
|
|
method,
|
|
path,
|
|
json=body,
|
|
headers={"x-api-key": self._api_key},
|
|
)
|
|
except httpx.RequestError as exc:
|
|
raise MintSettlementError(
|
|
f"Mint settlement transport failed: {exc}", 502, ambiguous=True
|
|
) from exc
|
|
try:
|
|
payload = response.json()
|
|
except ValueError:
|
|
payload = None
|
|
if (
|
|
200 <= response.status_code < 300
|
|
and isinstance(payload, dict)
|
|
and payload.get("success") is True
|
|
):
|
|
return payload.get("data"), response.headers
|
|
message = f"Mint settlement failed with status {response.status_code}"
|
|
if isinstance(payload, dict) and isinstance(payload.get("error"), dict):
|
|
message = str(payload["error"].get("message") or message)
|
|
raise MintSettlementError(
|
|
message,
|
|
response.status_code if response.status_code >= 400 else 502,
|
|
ambiguous=response.status_code >= 500,
|
|
)
|
|
|
|
@staticmethod
|
|
def _hold_id(data: Any, expected_amount: int) -> str:
|
|
if not isinstance(data, dict):
|
|
raise MintSettlementError(
|
|
"Mint returned an invalid hold", 502, ambiguous=True
|
|
)
|
|
hold_id = str(data.get("hold_id", "")).strip()
|
|
amount = data.get("amount_micros", expected_amount)
|
|
try:
|
|
amount_matches = (
|
|
not isinstance(amount, bool) and int(amount) == expected_amount
|
|
)
|
|
except (TypeError, ValueError, OverflowError):
|
|
amount_matches = False
|
|
if not hold_id or not amount_matches:
|
|
raise MintSettlementError(
|
|
"Mint hold does not match the requested authorization",
|
|
502,
|
|
ambiguous=True,
|
|
)
|
|
return hold_id
|
|
|
|
@staticmethod
|
|
def _receipt(
|
|
headers: httpx.Headers, operation: str, amount: int
|
|
) -> tuple[SettlementReceipt, dict[str, Any]]:
|
|
encoded = headers.get("aitp-receipt", "").strip()
|
|
try:
|
|
if not encoded or "=" in encoded:
|
|
raise ValueError("missing or padded receipt")
|
|
decoded = base64.b64decode(
|
|
encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True
|
|
)
|
|
if base64.urlsafe_b64encode(decoded).rstrip(b"=").decode() != encoded:
|
|
raise ValueError("non-canonical receipt")
|
|
value = json.loads(decoded)
|
|
except (binascii.Error, UnicodeDecodeError, ValueError, TypeError) as exc:
|
|
raise MintSettlementError(
|
|
f"Mint {operation} returned no valid signed receipt",
|
|
502,
|
|
ambiguous=True,
|
|
) from exc
|
|
if not isinstance(value, dict):
|
|
raise MintSettlementError(
|
|
f"Mint {operation} returned no valid signed receipt",
|
|
502,
|
|
ambiguous=True,
|
|
)
|
|
if value.get("op") != operation or value.get("amount_micros") != amount:
|
|
raise MintSettlementError(
|
|
f"Mint {operation} receipt does not match the request",
|
|
502,
|
|
ambiguous=True,
|
|
)
|
|
try:
|
|
return SettlementReceipt(
|
|
operation=operation,
|
|
sequence=value["seq"],
|
|
amount_micros=value["amount_micros"],
|
|
operation_hash=value["op_hash"],
|
|
receipt_hash=value["hash"],
|
|
signature=value["sig"],
|
|
signer="",
|
|
), value
|
|
except (KeyError, TypeError, ValueError) as exc:
|
|
raise MintSettlementError(
|
|
f"Mint {operation} returned an invalid signed receipt",
|
|
502,
|
|
ambiguous=True,
|
|
) from exc
|
|
|
|
@staticmethod
|
|
def _terminal_hold(data: Any, expected_hold_id: str, operation: str) -> None:
|
|
if (
|
|
not isinstance(data, dict)
|
|
or str(data.get("hold_id", "")) != expected_hold_id
|
|
):
|
|
raise MintSettlementError(
|
|
f"Mint {operation} response does not match the requested hold",
|
|
502,
|
|
ambiguous=True,
|
|
)
|
|
|
|
def authorize(
|
|
self, owner: str, correlation_id: str, amount_micros: int
|
|
) -> HoldAuthorization:
|
|
payer = self._payer(owner)
|
|
amount = int(amount_micros)
|
|
data, _ = self._request(
|
|
"POST",
|
|
"/v1/holds",
|
|
{
|
|
"from": payer,
|
|
"amount_micros": amount,
|
|
"idem_key": self._idempotency_key("hold", owner, correlation_id),
|
|
"ref": f"prism:{correlation_id}",
|
|
},
|
|
)
|
|
return HoldAuthorization(self._hold_id(data, amount), amount)
|
|
|
|
def capture(
|
|
self,
|
|
owner: str,
|
|
authorization: HoldAuthorization,
|
|
generation_id: str,
|
|
amount_micros: int,
|
|
) -> SettlementReceipt:
|
|
amount = int(amount_micros)
|
|
if amount < 0 or amount > authorization.reserved_micros:
|
|
raise MintSettlementError(
|
|
"capture amount exceeds Prism authorization", 500, ambiguous=False
|
|
)
|
|
idempotency_key = self._idempotency_key("capture", generation_id)
|
|
reference = f"prism:{generation_id}"
|
|
data, headers = self._request(
|
|
"POST",
|
|
f"/v1/holds/{authorization.hold_id}/capture",
|
|
{
|
|
"amount_micros": amount,
|
|
"to": self._payee,
|
|
"idem_key": idempotency_key,
|
|
"ref": reference,
|
|
},
|
|
)
|
|
self._terminal_hold(data, authorization.hold_id, "capture")
|
|
receipt, wire_receipt = self._receipt(headers, "hold.capture", amount)
|
|
return self._verify_attestation(
|
|
data,
|
|
receipt,
|
|
wire_receipt,
|
|
operation="hold.capture",
|
|
authorization=authorization,
|
|
payer_account=self._payer(owner),
|
|
amount_micros=amount,
|
|
idempotency_key=idempotency_key,
|
|
reference=reference,
|
|
)
|
|
|
|
def release(
|
|
self, owner: str, authorization: HoldAuthorization, generation_id: str
|
|
) -> SettlementReceipt:
|
|
idempotency_key = self._idempotency_key("release", generation_id)
|
|
reference = f"prism:{generation_id}"
|
|
data, headers = self._request(
|
|
"POST",
|
|
f"/v1/holds/{authorization.hold_id}/release",
|
|
{
|
|
"idem_key": idempotency_key,
|
|
"ref": reference,
|
|
},
|
|
)
|
|
self._terminal_hold(data, authorization.hold_id, "release")
|
|
receipt, wire_receipt = self._receipt(
|
|
headers, "hold.release", authorization.reserved_micros
|
|
)
|
|
return self._verify_attestation(
|
|
data,
|
|
receipt,
|
|
wire_receipt,
|
|
operation="hold.release",
|
|
authorization=authorization,
|
|
payer_account=self._payer(owner),
|
|
amount_micros=authorization.reserved_micros,
|
|
idempotency_key=idempotency_key,
|
|
reference=reference,
|
|
)
|
|
|
|
def _verify_attestation(
|
|
self,
|
|
data: Any,
|
|
receipt: SettlementReceipt,
|
|
wire_receipt: dict[str, Any],
|
|
*,
|
|
operation: str,
|
|
authorization: HoldAuthorization,
|
|
payer_account: str,
|
|
amount_micros: int,
|
|
idempotency_key: str,
|
|
reference: str,
|
|
) -> SettlementReceipt:
|
|
try:
|
|
verified = verify_hold_settlement_attestation(
|
|
data.get("attestation") if isinstance(data, dict) else None,
|
|
HoldSettlementExpected(
|
|
operation=operation,
|
|
hold_id=authorization.hold_id,
|
|
payer_account=payer_account,
|
|
payee_account=self._payee if operation == "hold.capture" else "",
|
|
amount_micros=amount_micros,
|
|
idempotency_key=idempotency_key,
|
|
reference=reference,
|
|
receipt=wire_receipt,
|
|
),
|
|
self._pinned_public_keys,
|
|
)
|
|
except (TypeError, ValueError) as exc:
|
|
raise MintSettlementError(
|
|
f"Mint {operation} attestation is invalid: {exc}",
|
|
502,
|
|
ambiguous=True,
|
|
) from exc
|
|
return receipt.model_copy(
|
|
update={"signer": str(verified.envelope["signer_key_id"])}
|
|
)
|
|
|
|
def readiness(self) -> dict[str, str]:
|
|
try:
|
|
self._request("GET", f"/v1/accounts/{self._payee}/balance")
|
|
except MintSettlementError as exc:
|
|
return {"status": "unavailable", "detail": str(exc)}
|
|
return {"status": "ready", "detail": "Mint payee is reachable"}
|
|
|
|
|
|
__all__ = [
|
|
"HoldAuthorization",
|
|
"MintSettlementClient",
|
|
"MintSettlementError",
|
|
"SettlementPort",
|
|
"SettlementCommand",
|
|
"UnconfiguredMintSettlement",
|
|
]
|