Source code for fleetmesh_core.accounting.paidfetch

"""Paid fetch (profile `paid-fetch-402`): the shape of the refusal that names a price.

A Blossom GET, a sidecar session, or any other metered face answers
`402 Payment Required` with

    X-Price-Msat: <total>
    X-Cashu: <NUT-24 payment request>[, <request>]     (one per item, when a cashu rail is offered)

and a JSON body `{sha256, size, price_msat, items[{to, payee, msat}], offers[], expires}`,
optionally `error` when the 402 follows a payment that did not settle. `items`
is who the money is for: `to` is `operator` or `account`, `payee` a hex pubkey.
`price_msat` is always the sum of the items. `offers` is one entry per rail per
item, `{rail, request, item}`; its `request` is rail-specific and opaque here.

The client pays by resending the request with `X-Cashu: <token>[, <token>]`,
one cashuB token per item in item order. Settlement, trust and the free tier
are a node's business and are not pinned.
"""
from __future__ import annotations

import math
from dataclasses import dataclass, field
from typing import Any, Mapping, TypedDict


[docs]class ItemBody(TypedDict): to: str payee: str msat: int
[docs]class OfferBody(TypedDict, total=False): method: str mint: str amount: int unit: str rail: str request: str item: int
[docs]class QuoteBody(TypedDict, total=False): sha256: str size: int price_msat: int items: list[ItemBody] offers: list[OfferBody | Mapping[str, Any]] expires: int error: str
[docs]def msat_to_sat_ceil(msat: int) -> int: """Cashu quotes in sat; the edge rounds up, so 1 msat costs 1 sat.""" return max(1, math.ceil(int(msat) / 1000)) if msat > 0 else 0
[docs]@dataclass class Item: to: str # 'operator' | 'account' payee: str # hex pubkey the money is for msat: int
[docs]@dataclass class Quote: sha256: str size: int items: list[Item] expires: int offers: list[OfferBody | Mapping[str, Any]] = field(default_factory=list) @property def price_msat(self) -> int: return sum(i.msat for i in self.items)
[docs] def body(self, error: str = '') -> QuoteBody: b: QuoteBody = { 'sha256': self.sha256, 'size': self.size, 'price_msat': self.price_msat, 'items': [{'to': i.to, 'payee': i.payee, 'msat': i.msat} for i in self.items], 'offers': self.offers, 'expires': self.expires, } if error: b['error'] = error return b
[docs] def headers(self) -> dict[str, str]: h = {'X-Price-Msat': str(self.price_msat)} creq = [str(o['request']) for o in self.offers if o.get('rail') == 'cashu' and o.get('request')] if creq: h['X-Cashu'] = ', '.join(creq) return h
[docs]def tokens_of(header_value: str) -> list[str]: """Every token in an X-Cashu header, in order: comma-separated, or the caller joins repeated headers with commas before asking.""" return [t.strip() for t in header_value.split(',') if t.strip()]