diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 291eda5..aec0602 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ }, "metadata": { "description": "BSV micropayment skill for Claude Code - BRC-31 auth + BRC-29 payment via a BRC-100 wallet", - "version": "1.1.2" + "version": "1.1.3" }, "plugins": [ { @@ -15,7 +15,7 @@ "skills": [ "./skills/x402" ], - "version": "1.1.2" + "version": "1.1.3" } ] } diff --git a/README.md b/README.md index daddffc..4641bd0 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,10 @@ Storage costs $0.05 per GB-month with a 1,000-sat minimum per upload. All payment is automatic - no confirmation prompts for typical micropayments (1–100,000 sats). +## Refunds + +If a paid response is lost, the helper retries the identical payment up to three times after 2, 5, and 10 seconds. Each send must start within the quote's five-minute window; a started request retains its full 300-second response timeout so slow work can finish. It never pays twice for that quote. Before sending, it saves the payment and request in `~/.x402/pending/.json`. Unresolved calls report the txid and an exact `retry-payment` command while the window remains open. A signed `ERR_PAYMENT_REPLAYED` refusal stops retries and removes the file because the payment was already claimed for service or refund. A signed `ERR_QUOTE_EXPIRED` refusal stops retries and keeps the file marked `expired-unclaimed` with the time, server code and message: the quote expired; the server may not have claimed this payment; the sats are yours if no service was delivered; keep this file and recover with the server operator using its saved payment details through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also retains and marks the file, without an unusable retry command. Other unconfirmed responses retain a terminal recovery record. A signed HTTP 200 for the same payment or successfully imported refund removes the file. If refund import fails, the response is returned and saved in the pending file, with an `import-refund` command to recover the refund without resending the payment. + ## Wallet selection and sessions Every wallet call goes to `X402_WALLET_URL` (default `http://localhost:3321`). Set it to use a second wallet daemon, e.g. `X402_WALLET_URL=http://localhost:3322`. @@ -195,6 +199,8 @@ Run checks with `python3 -m pytest -q`. Regenerate the Available Services table ## Changelog +- **1.1.3** - Retry identical payments after lost responses without paying twice. Save pending requests by txid and provide a `retry-payment` recovery command. Stop on signed replay or expired-quote codes; retain expired payments as `expired-unclaimed` with recovery instructions, time and server details, and remove records only for signed HTTP 200, claimed replay, or imported refunds. Report unsigned or signed paid 402 refusals with the txid. Bound send starts by the quote window while retaining the 300-second response timeout and one session refresh. Preserve delivered responses and refund bytes on import failure, with an `import-refund` command. Normalize the body once before quoting, tolerate stale server clocks beyond 60 seconds, suppress expired retry commands, and print payment JSON if the initial recovery-file write fails. + - **1.1.2** - Document the MetaNet Client and headless wallet paths, including gaps in the wallet README. Generate all service rows, exact registry tier ranges, and sync/async delivery from the public registry. - **1.1.1** - Sessions keyed by (server URL, client identity key); a session opened by one wallet is never reused by another (a wallet switch on the same server previously made the server derive the BRC-29 payee key from the wrong identity). Wallet URL configurable via `X402_WALLET_URL`. `createAction` accepts `tx` returned as an index-keyed object. Added `tests/` (`python3 -m pytest -q`). diff --git a/skills/x402/SKILL.md b/skills/x402/SKILL.md index 1892460..e65b72f 100644 --- a/skills/x402/SKILL.md +++ b/skills/x402/SKILL.md @@ -41,6 +41,8 @@ All operations use the helper script bundled with this skill. All commands outpu | `python3 ./scripts/brc31_helpers.py discover ` | Learn server endpoints, auth requirements, costs | | `python3 ./scripts/brc31_helpers.py auth [body]` | Authenticated request (no payment) | | `python3 ./scripts/brc31_helpers.py pay [body]` | Authenticated + paid request (auto-handles 402) | +| `python3 ./scripts/brc31_helpers.py retry-payment ` | Replay a saved payment with the original wallet | +| `python3 ./scripts/brc31_helpers.py import-refund ` | Import a saved refund without resending the payment | | `python3 ./scripts/brc31_helpers.py upload [retention_min] [--public-base URL]` | UHRP file upload: pays `/upload`, PUTs the bytes, returns the public URL | | `python3 ./scripts/brc31_helpers.py identity` | Get wallet's 66-char hex identity key | | `python3 ./scripts/brc31_helpers.py execute-action ` | Execute a pending action template (broadcasts inscription tx after user confirms) | @@ -148,6 +150,8 @@ Servers that support BRC-29 refunds will automatically return refund data when a The `discover` command shows which endpoints support refunds. The `pay` command output includes a `refund` block when a refund was received and internalized. +If a paid response is lost, the helper retries the identical payment after 2, 5, and 10 seconds. Sends must start within the quote's five-minute window; each started request retains its 300-second response timeout. It never creates another payment for that quote. Unresolved calls retain `~/.x402/pending/.json` and print the txid and an exact `retry-payment` command while the window remains open. Use that command with the original wallet instead of starting another `pay` call. Signed `ERR_PAYMENT_REPLAYED` stops retries and removes the already-claimed payment file. Signed `ERR_QUOTE_EXPIRED` stops retries and retains the file marked `expired-unclaimed`, with the time, server code and message: the server may not have claimed this payment; the sats are yours if no service was delivered. Keep the file and recover with the server operator through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also marks and retains the file without a retry command; other unconfirmed responses retain a terminal recovery record. Only signed HTTP 200 for the same payment, claimed replay, or an imported refund removes the pending file. Failed refund imports preserve and return the delivered response and print an `import-refund` command; use it with the original wallet to import the saved refund without resending the payment. + ## Payment Transport Payment is sent via `x-bsv-payment` header as JSON: `{"derivationPrefix":"...","derivationSuffix":"...","transaction":""}`. The client handles this automatically. diff --git a/skills/x402/cli.py b/skills/x402/cli.py index 1c43ef0..a353744 100755 --- a/skills/x402/cli.py +++ b/skills/x402/cli.py @@ -19,7 +19,7 @@ # payment.py may not exist yet (built in parallel); import conditionally. try: - from lib.payment import paid_request, PaymentError, PaymentRequired + from lib.payment import paid_request, retry_payment, PaymentError, PaymentRequired HAS_PAYMENT = True except ImportError: HAS_PAYMENT = False @@ -373,6 +373,17 @@ def cmd_pay(args): return 0 +def cmd_retry_payment(args): + """Replay a saved payment without creating a new transaction.""" + try: + response = retry_payment(args.file) + except (PaymentError, OSError, ValueError) as exc: + print_err(str(exc)) + return 1 + print_response(response) + return int(response.status_code >= 400 or response.signature_verdict != "signed") + + def cmd_upload(args): """End-to-end UHRP file upload: pay /upload, PUT bytes, print public URL.""" from lib.upload import do_upload, UploadError @@ -517,6 +528,9 @@ def build_parser() -> argparse.ArgumentParser: help="Request body (JSON string). Optional.", ) + p_retry = subparsers.add_parser("retry-payment", help="Replay a saved payment.") + p_retry.add_argument("file", help="Saved payment JSON file.") + # --- upload --- p_up = subparsers.add_parser( "upload", @@ -575,6 +589,7 @@ def main() -> int: "session": cmd_session, "auth": cmd_auth, "pay": cmd_pay, + "retry-payment": cmd_retry_payment, "upload": cmd_upload, } diff --git a/skills/x402/lib/CLAUDE.md b/skills/x402/lib/CLAUDE.md index d0a3c73..210f1ee 100644 --- a/skills/x402/lib/CLAUDE.md +++ b/skills/x402/lib/CLAUDE.md @@ -56,7 +56,8 @@ def paid_request( ) -> requests.Response ``` - **Purpose:** High-level entry point for paid endpoints. Makes an authenticated request, and if the server returns 402, automatically constructs and submits a BRC-29 payment, then retries. -- **Flow:** `authenticated_request()` → if 402: parse payment headers → `create_payment()` → retry with `x-bsv-payment` header → repeat up to `max_payment_attempts` +- **Flow:** `authenticated_request()` → if 402: parse payment headers → `create_payment()` → retry with `x-bsv-payment` header → retry identical payment up to `max_payment_attempts` times (2, 5, 10 seconds, within five minutes) +- **Recovery:** Save request and payment before sending in `~/.x402/pending/.json`; `retry-payment ` replays it with the original wallet and never creates a payment. Signed success or an imported refund removes the file. - **Payment transport:** If payment JSON exceeds 8KB (`MULTIPART_THRESHOLD`) **and** the server advertises multipart support (`x-bsv-payment-transports: multipart`), sends payment (+ any original body) as BRC-105 multipart/form-data; otherwise sends payment JSON in the `x-bsv-payment` header. Typical payments (~2KB) use the header. ### do_handshake (handshake.py) diff --git a/skills/x402/lib/auth_request.py b/skills/x402/lib/auth_request.py index d36dc58..f051cd2 100644 --- a/skills/x402/lib/auth_request.py +++ b/skills/x402/lib/auth_request.py @@ -24,6 +24,7 @@ import logging import base64 import sys +import time import requests as _requests from urllib.parse import urlparse @@ -92,6 +93,8 @@ def authenticated_request( body: bytes | str | None = None, session: Session | None = None, _allow_session_refresh: bool = True, + timeout: float = 300, + _deadline: float | None = None, ) -> _requests.Response: """Make an authenticated BRC-31 request. @@ -256,13 +259,17 @@ def authenticated_request( # ----------------------------------------------------------------------- # 10. Send the HTTP request # ----------------------------------------------------------------------- + if _deadline is not None: + remaining = _deadline - time.time() + if remaining <= 0: + raise AuthRequestError("Payment quote window expired before send.") try: response = _requests.request( method=method.upper(), url=url, headers=merged_headers, data=body_bytes, - timeout=300, + timeout=timeout, ) except _requests.RequestException as e: raise AuthRequestError(f"HTTP request failed: {e}") from e @@ -296,6 +303,8 @@ def authenticated_request( headers=headers, body=body, session=None, # force get_or_create_session -> handshake + timeout=timeout, + _deadline=_deadline, _allow_session_refresh=False, # only retry once; avoid loops ) diff --git a/skills/x402/lib/payment.py b/skills/x402/lib/payment.py index be84a27..785cdda 100644 --- a/skills/x402/lib/payment.py +++ b/skills/x402/lib/payment.py @@ -29,10 +29,15 @@ import hashlib import logging import requests +import time +import shlex +import sys +import tempfile +from pathlib import Path +from email.utils import parsedate_to_datetime from lib.metanet import get_public_key, create_action from lib.auth_request import authenticated_request -from lib.session import Session from lib.handshake import get_or_create_session log = logging.getLogger(__name__) @@ -48,8 +53,18 @@ # BRC-29 payment protocol version. Must match server expectation. PAYMENT_VERSION = "1.0" -# Maximum number of payment retry attempts before giving up. +# Maximum number of retries after the first paid send. MAX_PAYMENT_ATTEMPTS = 3 +PAYMENT_BACKOFF = (2, 5, 10) +QUOTE_WINDOW = 300 +PENDING_DIR = Path.home() / ".x402" / "pending" + + +class Payment(dict): + """Wire payment fields with local-only transaction metadata.""" + + txid: str + # Threshold for switching from header to multipart payment transport. # When payment JSON exceeds this, we send it as a multipart/form-data body @@ -455,11 +470,12 @@ def create_payment( # Step 6: Build the payment JSON (camelCase keys to match server expectation). # NOTE: no senderIdentityKey -- identity comes from BRC-31 auth context. - payment = { + payment = Payment({ "derivationPrefix": derivation_prefix, "derivationSuffix": derivation_suffix, "transaction": tx_b64, - } + }) + payment.txid = txid log.debug( "Payment JSON: prefix=%s..., suffix=%s, tx_b64_len=%d", @@ -526,216 +542,263 @@ def build_multipart_body( # --------------------------------------------------------------------------- -def paid_request( - method: str, - url: str, - headers: dict[str, str] | None = None, - body: bytes | str | None = None, - max_payment_attempts: int = MAX_PAYMENT_ATTEMPTS, -) -> requests.Response: - """Make a BRC-31 authenticated request, handling 402 payment automatically. - - This is the main entry point for interacting with paid endpoints. - It orchestrates the full flow: - - 1. Make an authenticated request via ``authenticated_request()``. - 2. If the server returns 402, parse the payment requirements. - 3. Create a payment transaction. - 4. Retry the original request with the ``x-bsv-payment`` header. - 5. Return the final response. - - The payment is only created on a 402 response. If the initial request - succeeds (or fails with a non-402 status), it is returned as-is. +def _recovery_command(path: Path, command: str) -> str: + helper = Path(__file__).resolve().parents[1] / "scripts" / "brc31_helpers.py" + return shlex.join([sys.executable, str(helper), command, str(path)]) - Args: - method: HTTP method (GET, POST, etc.). - url: Full URL to request. - headers: Optional headers (same restrictions as ``authenticated_request``). - body: Optional request body (str or bytes). - max_payment_attempts: Maximum times to attempt payment (default 3). - - Returns: - ``requests.Response`` from the final attempt. - Raises: - PaymentError: if payment construction/submission fails after all attempts. - lib.auth_request.AuthRequestError: if the authenticated request itself - fails at the protocol level. - """ - if headers is None: - headers = {} - - # Keep a copy of original headers so retries don't accumulate payment headers. - original_headers = dict(headers) - - # --- Step 1: Initial authenticated request --- - log.info("paid_request: %s %s", method, url) - response = authenticated_request( - method=method, - url=url, - headers=dict(original_headers), - body=body, - ) - - if response.status_code == 402 and response.signature_verdict != "signed": - return response # Never create a payment from an unverified challenge. - - if response.status_code != 402: - log.debug( - "paid_request: initial request returned %d (not 402), done.", - response.status_code, - ) - return response - - # --- Step 2: Handle 402 Payment Required --- - log.info( - "paid_request: got 402 Payment Required (attempt 0/%d)", - max_payment_attempts, +def _save_pending(record: dict, path: Path | None = None) -> Path: + """Persist payment bytes and request before sending, readable only by the payer.""" + path = path or PENDING_DIR / (record["txid"] + ".json") + fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".payment-") + try: + with os.fdopen(fd, "w") as stream: + json.dump(record, stream) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + return path + + +def _expired_unclaimed(record: dict, path: Path, code=None, server_message=None) -> PaymentError: + message = ( + "the quote expired; the server may not have claimed this payment; " + "the sats are yours if no service was delivered: keep this file; " + "recover with the server operator using this saved payment and the refund path " + "or a later receipt query; import returned refund data with import-refund." ) - - # We need the server identity key from the session for key derivation. - # Re-derive the server base URL to look up the session. - from urllib.parse import urlparse - parsed = urlparse(url) - server_base = f"{parsed.scheme}://{parsed.netloc}" - - session = get_or_create_session(server_base) - server_identity_key = session.server_identity_key - - # Also check if the 402 response has the identity key in headers - # (it should, since the 402 is a signed response from an authenticated session). - header_identity = response.headers.get("x-bsv-auth-identity-key") - if header_identity: - server_identity_key = header_identity - - for attempt in range(1, max_payment_attempts + 1): - log.info( - "paid_request: payment attempt %d/%d", - attempt, - max_payment_attempts, - ) - + record.update(state="expired-unclaimed", terminal_at=time.time(), + server_code=code, server_message=server_message, + recovery_message=message) + _save_pending(record, path) + error = PaymentError(f"Payment {record['txid']}: {message} Saved payment: {path}.") + log.error("%s", error) + return error + + +def _unresolved(record: dict, path: Path, reason: str) -> PaymentError: + message = f"Payment {record['txid']}: {reason}. Saved payment: {path}. " + if time.time() >= record["expires_at"]: + return _expired_unclaimed(record, path, record.get("server_code"), + record.get("server_message")) + elif record.get("state") == "terminal-unresolved": + message += record["recovery_message"] + else: + message += f"Retry the same payment by hand: {_recovery_command(path, 'retry-payment')}" + log.error(message) + return PaymentError(message) + + +def import_refund(path: str | Path) -> dict: + """Import a saved response's refund without sending another paid request.""" + from lib.metanet import get_identity_key + from lib.refund import parse_refund, process_refund + path = Path(path).expanduser() + record = json.loads(path.read_text()) + if record["identity_key"] != get_identity_key(): + raise PaymentError("Use the wallet identity that created this payment to import its refund.") + if record.get("refund_imported"): + return {"accepted": True, "already_imported": True} + refund = parse_refund(json.loads(base64.b64decode(record["response"]["body"]))) + if refund is None: + raise PaymentError("Saved response has no importable refund.") + result = process_refund(refund) + if not result.get("accepted", False): + raise PaymentError("Wallet did not accept refund; saved response retained.") + # Preserve the delivered response after import, but mark it as complete. + record["refund_imported"] = True + _save_pending(record, path) + return result + + +def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Response: + """Re-sign the same payment and body, without ever asking for another quote.""" + body = base64.b64decode(record["body"]) if record["body"] is not None else None + last_error = "quote window expired" + retry_after = None + for attempt in range(min(max(0, max_retries), len(PAYMENT_BACKOFF)) + 1): + if attempt: + delay = retry_after if retry_after is not None else PAYMENT_BACKOFF[attempt - 1] + retry_after = None + if time.time() + delay >= record["expires_at"]: + break + time.sleep(delay) + remaining = record["expires_at"] - time.time() + if remaining <= 0: + break try: - # Parse 402 requirements (re-parse each time in case server changes them) - payment_req = parse_402_response(response) - except PaymentError as e: - log.error("Failed to parse 402 response: %s", e) - raise - - try: - # Create payment - payment = create_payment( - derivation_prefix=payment_req.derivation_prefix, - server_identity_key=server_identity_key, - satoshis=payment_req.satoshis, - server_url=server_base, - ) - except PaymentError as e: - log.error( - "Payment creation failed (attempt %d/%d): %s", - attempt, max_payment_attempts, e, + response = authenticated_request( + method=record["method"], url=record["url"], + headers=dict(record["headers"]), body=body, + timeout=300, + _deadline=record["expires_at"], ) - if attempt >= max_payment_attempts: - raise + except Exception as exc: + # The wallet has already broadcast. Local signing failures must + # also retain the journal and can never restart payment creation. + last_error = f"paid request failed ({type(exc).__name__})" continue - - # Build the payment header value - payment_json = json.dumps(payment, separators=(",", ":")) - - # Determine transport: header (small) vs multipart (large). - # BRC-105 multipart transport wraps both the payment JSON and - # original body into multipart/form-data parts — works with or - # without an original body. - retry_headers = dict(original_headers) - - if len(payment_json) > MULTIPART_THRESHOLD and payment_req.supports_multipart(): - # BRC-105 multipart transport - log.info( - "Payment JSON %d bytes > %d threshold, using multipart transport", - len(payment_json), - MULTIPART_THRESHOLD, - ) - original_ct = original_headers.get("content-type") - multipart_body, multipart_ct = build_multipart_body( - payment_json, body, original_ct, - ) - retry_headers.pop("content-type", None) - retry_headers["content-type"] = multipart_ct - retry_body = multipart_body - else: - # Standard header transport - retry_headers["x-bsv-payment"] = payment_json - retry_body = body - - # Retry with payment + if not response.content or getattr(response, "signature_verdict", None) != "signed": + if response.status_code == 402: + raise _unresolved(record, path, "paid request returned HTTP 402; no new payment created") + last_error = "paid response missing a body or verified BRC-104 signature" + continue + # Only verified claim codes can establish a claimed payment outcome. try: - response = authenticated_request( - method=method, - url=url, - headers=retry_headers, - body=retry_body, - ) - except Exception as e: - log.error( - "Paid request failed (attempt %d/%d): %s", - attempt, max_payment_attempts, e, - ) - if attempt >= max_payment_attempts: - raise PaymentError( - f"Paid request to {url} failed after {attempt} attempts: {e}" - ) from e + parsed = response.json() + except ValueError: + parsed = None + code = parsed.get("code") if isinstance(parsed, dict) else None + if 400 <= response.status_code < 500 and code == "ERR_QUOTE_EXPIRED": + raise _expired_unclaimed(record, path, code, parsed.get("message", parsed.get("description"))) + if 400 <= response.status_code < 500 and code == "ERR_PAYMENT_REPLAYED": + path.unlink(missing_ok=True) + raise PaymentError( + f"Payment {record['txid']}: already claimed; the service was delivered " + "to the first request or will be refunded. No payment remains to retry.") + if response.status_code == 402: + raise _unresolved(record, path, "paid request returned HTTP 402; no new payment created") + if response.status_code == 202: + last_error = "payment outcome still pending" + try: + retry_after = max(0, int(response.headers.get("Retry-After", "5"))) + except ValueError: + retry_after = 5 continue + # Keep a journal when a refund cannot be imported, so it can be recovered. + from lib.refund import parse_refund, process_refund + refund = parse_refund(parsed) if isinstance(parsed, dict) else None + if refund: + try: + result = process_refund(refund) + if not result.get("accepted", False): + raise PaymentError("Wallet did not accept refund") + response.refund_result = { + "processed": True, "accepted": True, + "satoshis": refund.satoshis, "txid": refund.txid, + } + except Exception as exc: + record["response"] = { + "status": response.status_code, "headers": dict(response.headers), + "body": base64.b64encode(response.content).decode("ascii"), + } + command = _recovery_command(path, "import-refund") + error = f"refund internalization failed ({type(exc).__name__})" + try: + _save_pending(record, path) + except OSError: + # Return the response even if the disk has become unwritable. + print("Could not save refund response. Recovery JSON: " + + json.dumps(record), file=sys.stderr) + error += "; response save failed; recovery JSON printed to stderr" + response.refund_result = { + "processed": False, "error": error, + "path": str(path), "command": command, + } + log.error("Payment %s: %s. Saved response: %s. Import by hand: %s", + record["txid"], error, path, command) + return response + if response.status_code == 200 or refund: + path.unlink(missing_ok=True) + else: + record.update(state="terminal-unresolved", terminal_at=time.time(), + recovery_message="The server did not confirm delivery or refund; keep this file " + "and contact the server operator for recovery through the refund path or a later receipt query.", + server_code=code, + server_message=parsed.get("message", parsed.get("description")) + if isinstance(parsed, dict) else None) + _save_pending(record, path) + _unresolved(record, path, f"returned signed HTTP {response.status_code}") + return response + raise _unresolved(record, path, f"identical-payment retries exhausted: {last_error}") - if response.signature_verdict != "signed": - return response - if response.status_code == 402: - # Server still wants payment -- maybe requirements changed. - log.warning( - "Server returned 402 again after payment (attempt %d/%d). " - "Will retry if attempts remain.", - attempt, max_payment_attempts, - ) - if attempt >= max_payment_attempts: - raise PaymentError( - f"Paid request to {url} still getting 402 after " - f"{attempt} payment attempts. Last response: " - f"{response.text[:500]}" - ) - continue +def retry_payment(path: str | Path) -> requests.Response: + """Replay a saved request using the original wallet, without making a payment.""" + from lib.metanet import get_identity_key + path = Path(path).expanduser() + record = json.loads(path.read_text()) + if record["identity_key"] != get_identity_key(): + raise PaymentError("Use the wallet identity that created this payment to retry it.") + if record.get("state") in ("expired-unclaimed", "terminal-unresolved"): + raise PaymentError( + f"Payment {record['txid']}: {record['recovery_message']} Saved payment: {path}.") + if "response" in record: + raise PaymentError( + f"Payment {record['txid']}: response already saved at {path}; " + f"import its refund by hand: {_recovery_command(path, 'import-refund')}") + return _send_pending(record, path, MAX_PAYMENT_ATTEMPTS) - # Success (or at least not 402 anymore) - log.info( - "paid_request: payment accepted! status=%d (attempt %d/%d)", - response.status_code, attempt, max_payment_attempts, - ) - # Auto-detect and internalize refunds in any response. - # Async agents (banana, veo, kling) return 200 on /status polls - # with refund data for failed predictions — must check all responses. - try: - from lib.refund import parse_refund, process_refund - resp_body = response.json() - refund = parse_refund(resp_body) - if refund: - try: - refund_result = process_refund(refund) - log.info( - "Refund auto-internalized: %d sats, accepted=%s", - refund.satoshis, - refund_result.get("accepted", False), - ) - except Exception as re: - log.error("Failed to internalize refund: %s", re) - except Exception: - pass # Response not JSON or no refund — that's fine +def paid_request( + method: str, + url: str, + headers: dict[str, str] | None = None, + body: bytes | str | None = None, + max_payment_attempts: int = MAX_PAYMENT_ATTEMPTS, +) -> requests.Response: + """Pay a verified quote once; retry the identical payment at most three times. - return response + ``max_payment_attempts`` limits retries after the first paid send. All sends + must begin within five minutes of receiving the quote (or the server's + earlier Date within 60 seconds of local time). Responses may take 300 seconds + after a send starts. Failures before payment creation propagate without paid retries. + """ + from urllib.parse import urlparse - # Should not reach here, but just in case - raise PaymentError( - f"Paid request to {url} exhausted all {max_payment_attempts} attempts." - ) + headers = {k.lower(): v for k, v in (headers or {}).items()} + # Normalize once, then preserve exactly these bytes for every send and replay. + if isinstance(body, str): + try: + body = json.dumps(json.loads(body), separators=(",", ":")) + except ValueError: + pass + body = body.encode("utf-8") + if body is not None: + headers.setdefault("content-type", "application/json") + response = authenticated_request(method=method, url=url, headers=dict(headers), body=body) + quote_time = time.time() + if response.status_code != 402 or response.signature_verdict != "signed": + return response + payment_req = parse_402_response(response) + if response.headers.get("Date"): + try: + server_time = parsedate_to_datetime(response.headers["Date"]).timestamp() + if quote_time - 60 <= server_time <= quote_time: + quote_time = server_time + except (ValueError, TypeError, OverflowError): + pass + expires_at = quote_time + QUOTE_WINDOW + parsed_url = urlparse(url) + server_base = f"{parsed_url.scheme}://{parsed_url.netloc}" + session = get_or_create_session(server_base) + PENDING_DIR.mkdir(parents=True, exist_ok=True, mode=0o700) + if time.time() >= expires_at: + raise PaymentError("Quote expired before payment creation; no payment created.") + payment = create_payment(payment_req.derivation_prefix, session.server_identity_key, + payment_req.satoshis, server_base) + payment_json = json.dumps(payment, separators=(",", ":")) + original_body = body + if len(payment_json) > MULTIPART_THRESHOLD and payment_req.supports_multipart(): + body, headers["content-type"] = build_multipart_body( + payment_json, body, headers.get("content-type")) + else: + headers["x-bsv-payment"] = payment_json + record = { + "txid": payment.txid, "payment": payment, "url": url, "method": method, + "identity_key": session.client_identity_key, "expires_at": expires_at, + "headers": headers, "body": base64.b64encode(body).decode("ascii") if body is not None else None, + "body_sha256": hashlib.sha256(original_body or b"").hexdigest(), + } + try: + path = _save_pending(record) + except OSError as exc: + print(f"Payment {payment.txid} recovery JSON: {payment_json}", file=sys.stderr) + raise PaymentError(f"Payment {payment.txid}: could not save recovery file: {exc}") from exc + return _send_pending(record, path, max_payment_attempts) # --------------------------------------------------------------------------- diff --git a/skills/x402/scripts/brc31_helpers.py b/skills/x402/scripts/brc31_helpers.py index 25c3128..31a3a81 100755 --- a/skills/x402/scripts/brc31_helpers.py +++ b/skills/x402/scripts/brc31_helpers.py @@ -11,6 +11,8 @@ brc31_helpers.py session --clear-all List and clear all stored sessions brc31_helpers.py auth [body] Authenticated request brc31_helpers.py pay [body] Auth + payment request + brc31_helpers.py retry-payment Replay the identical saved payment + brc31_helpers.py import-refund Import a saved refund without resending brc31_helpers.py upload [server] [retention_min] [--public-base URL] UHRP file upload (pay /upload + PUT + public URL) brc31_helpers.py execute-action Execute a pending action template (broadcasts tx) @@ -25,7 +27,7 @@ from lib.handshake import do_handshake, get_or_create_session from lib.auth_request import authenticated_request -from lib.payment import paid_request +from lib.payment import paid_request, retry_payment, import_refund from lib.metanet import get_identity_key from lib.upload import do_upload, DEFAULT_RETENTION_MINUTES, DEFAULT_STORAGE_SERVER from lib import registry @@ -55,6 +57,13 @@ def discover(manifest_url): return {"error": str(e)} +def _pay_from_args(): + method = sys.argv[2].upper() + url = registry.resolve(sys.argv[3]) + body = sys.argv[4] if len(sys.argv) > 4 else None + return paid_request(method, url, body=body) + + def main(): if len(sys.argv) < 2: print(__doc__) @@ -100,11 +109,14 @@ def main(): if resp.signature_verdict != "signed": sys.exit(1) - elif cmd == "pay": - method = sys.argv[2].upper() - url = registry.resolve(sys.argv[3]) - body = sys.argv[4] if len(sys.argv) > 4 else None - resp = paid_request(method, url, body=body) + elif cmd == "import-refund": + print(json.dumps(import_refund(sys.argv[2]), indent=2)) + + elif cmd in ("pay", "retry-payment"): + if cmd == "retry-payment": + resp = retry_payment(sys.argv[2]) + else: + resp = _pay_from_args() result = { "status": resp.status_code, "verdict": resp.signature_verdict, @@ -114,32 +126,29 @@ def main(): if resp.signature_verdict != "signed": print(json.dumps(result, indent=2)) sys.exit(1) + if hasattr(resp, "refund_result"): + result["refund"] = resp.refund_result # Parse response body once for auto-detection body_parsed = None try: body_parsed = resp.json() except Exception: pass - # Auto-detect and process refund in response - try: - if isinstance(body_parsed, dict): - refund_data = body_parsed.get("refund") or body_parsed.get("excessRefund") - if refund_data and isinstance(refund_data, dict) and not refund_data.get("already_refunded"): - from lib.refund import parse_refund, process_refund - refund_info = parse_refund(body_parsed) - if refund_info: - try: - refund_result = process_refund(refund_info) - result["refund"] = { - "processed": True, - "accepted": refund_result.get("accepted", False), - "satoshis": refund_info.satoshis, - "txid": refund_info.txid, - } - except Exception as e: - result["refund"] = {"processed": False, "error": str(e)} - except Exception: - pass + # A no-payment status poll can also carry a deferred refund. + if not hasattr(resp, "refund_result") and isinstance(body_parsed, dict): + from lib.refund import parse_refund, process_refund + refund = parse_refund(body_parsed) + if refund: + try: + refund_result = process_refund(refund) + result["refund"] = { + "processed": True, + "accepted": refund_result.get("accepted", False), + "satoshis": refund.satoshis, + "txid": refund.txid, + } + except Exception as exc: + result["refund"] = {"processed": False, "error": str(exc)} # Detect action template — return for user confirmation, DON'T auto-execute try: if isinstance(body_parsed, dict): diff --git a/tests/test_payment_retry.py b/tests/test_payment_retry.py new file mode 100644 index 0000000..127b999 --- /dev/null +++ b/tests/test_payment_retry.py @@ -0,0 +1,484 @@ +"""Lost paid responses reuse one transaction and persist recoverable requests.""" +import base64 +import hashlib +import json +import shlex +import sys + +import pytest +import requests + +from conftest import SERVER_KEY +from lib import auth_request, payment +from lib.headers import filter_signable_headers +from lib.serialize import serialize_response +from test_helper_gaps import helper + +# Synthetic wallet transaction identifier, never a live payment. +TXID = "12" * 32 +URL = "https://service.example.test/paid" + + +@pytest.fixture +def server(net, monkeypatch, tmp_path): + monkeypatch.setattr(payment, "PENDING_DIR", tmp_path / "pending") + now = [1000.0] + sleeps = [] + monkeypatch.setattr(payment.time, "time", lambda: now[0]) + + def sleep(delay): + sleeps.append(delay) + now[0] += delay + + monkeypatch.setattr(payment.time, "sleep", sleep) + actions = [] + original_post = net.post + + def post(url, **kwargs): + if url.endswith("/createAction"): + actions.append(kwargs["json"]) + from conftest import FakeResponse + return FakeResponse(body={"txid": TXID, "tx": [1, 2, 3]}) + return original_post(url, **kwargs) + + monkeypatch.setattr(requests, "post", post) + + def verify(method, params): + assert method == "verifySignature" + return {"valid": hashlib.sha256(bytes(params["data"])).digest() == bytes(params["signature"])} + + monkeypatch.setattr(auth_request, "_call", verify) + calls = [] + outcomes = [] + quote_headers = { + "x-bsv-payment-version": "1.0", + "x-bsv-payment-satoshis-required": "5", + "x-bsv-payment-derivation-prefix": "test-quote", + "x-bsv-payment-transports": "header,multipart", + } + + def request(method, url, headers, data, timeout): + calls.append((dict(headers), data, timeout)) + if len(calls) == 1: + status, body, signed = 402, {"payment": "required"}, True + else: + # A journal must exist before any paid bytes leave the client. + assert (payment.PENDING_DIR / f"{TXID}.json").exists() + outcome = outcomes.pop(0) + if isinstance(outcome, Exception): + raise outcome + status, body, signed = outcome + response = requests.Response() + response.status_code = status + response._content = json.dumps(body).encode() if body is not None else b"" + response.headers.update({ + "x-bsv-auth-request-id": headers["x-bsv-auth-request-id"], + "x-bsv-auth-identity-key": SERVER_KEY, + "x-bsv-auth-your-nonce": headers["x-bsv-auth-nonce"], + "x-bsv-auth-nonce": base64.b64encode(b"n" * 32).decode(), + }) + # The verifier binds yourNonce to the session's client nonce. + from lib.session import load_session + response.headers["x-bsv-auth-your-nonce"] = load_session(URL.rsplit("/", 1)[0]).client_nonce_b64 + if status == 402: + response.headers.update(quote_headers) + if signed: + rid = base64.b64decode(headers["x-bsv-auth-request-id"]) + payload = serialize_response(rid, status, filter_signable_headers(response.headers), response.content or None) + response.headers["x-bsv-auth-signature"] = hashlib.sha256(payload).hexdigest() + return response + + monkeypatch.setattr(requests, "request", request) + return outcomes, actions, calls, sleeps, now, quote_headers + + +@pytest.mark.parametrize("multipart", [False, True]) +def test_lost_response_then_signed_success(server, monkeypatch, multipart): + outcomes, actions, calls, sleeps, _, _ = server + if multipart: + monkeypatch.setattr(payment, "MULTIPART_THRESHOLD", 1) + outcomes.extend([requests.ConnectionError("lost"), (200, {"ok": True}, True)]) + result = payment.paid_request("POST", URL, body='{"input": "hello"}') + assert result.signature_verdict == "signed" + assert len(actions) == 1 + assert actions[0]["options"]["acceptDelayedBroadcast"] is False + assert sleeps == [2] + first, retry = calls[1:] + assert first[1] == retry[1] + assert first[0].get("x-bsv-payment") == retry[0].get("x-bsv-payment") + assert first[0]["content-type"] == retry[0]["content-type"] + assert first[0]["x-bsv-auth-request-id"] != retry[0]["x-bsv-auth-request-id"] + assert list(payment.PENDING_DIR.iterdir()) == [] + + +def test_lost_then_already_claimed(server): + code = "ERR_PAYMENT_REPLAYED" + outcomes, actions, calls, sleeps, _, _ = server + outcomes.extend([requests.Timeout("lost"), (400, {"code": code}, True)]) + with pytest.raises(payment.PaymentError) as exc: + payment.paid_request("POST", URL) + assert TXID in str(exc.value) + assert "already claimed; the service was delivered to the first request or will be refunded" in str(exc.value) + assert len(actions) == 1 and len(calls) == 3 and sleeps == [2] + assert not (payment.PENDING_DIR / f"{TXID}.json").exists() + assert "retry-payment" not in str(exc.value) + + +def test_lost_then_quote_expired_unclaimed(server, caplog): + outcomes, actions, calls, sleeps, now, _ = server + outcomes.extend([requests.Timeout("lost"), + (400, {"code": "ERR_QUOTE_EXPIRED", "message": "quote gone"}, True)]) + with pytest.raises(payment.PaymentError) as exc: + payment.paid_request("POST", URL) + path = payment.PENDING_DIR / f"{TXID}.json" + saved = json.loads(path.read_text()) + assert saved["state"] == "expired-unclaimed" + assert saved["terminal_at"] == now[0] + assert saved["server_code"] == "ERR_QUOTE_EXPIRED" + assert saved["server_message"] == "quote gone" + for words in ("the quote expired", "the server may not have claimed this payment", + "the sats are yours if no service was delivered", "keep this file", + "refund path or a later receipt query", "import-refund"): + assert words in str(exc.value) and words in caplog.text + assert "retry-payment" not in str(exc.value) + assert len(actions) == 1 and len(calls) == 3 and sleeps == [2] + with pytest.raises(payment.PaymentError, match="keep this file"): + payment.retry_payment(path) + assert len(calls) == 3 + + +@pytest.mark.parametrize("outcome", [requests.ConnectionError("lost"), requests.Timeout("lost"), + (200, None, True), (200, {"ok": True}, False), (503, None, False)]) +def test_exhaustion_and_exact_hand_retry(server, monkeypatch, capsys, outcome): + outcomes, actions, calls, sleeps, _, _ = server + outcomes.extend([outcome] * 4) + with pytest.raises(payment.PaymentError) as exc: + payment.paid_request("POST", URL, body="test payload") + path = payment.PENDING_DIR / f"{TXID}.json" + saved = json.loads(path.read_text()) + assert saved["payment"]["transaction"] == base64.b64encode(bytes([1, 2, 3])).decode() + assert json.loads(saved["headers"]["x-bsv-payment"]) == saved["payment"] + assert saved["body_sha256"] == hashlib.sha256(b"test payload").hexdigest() + assert path.stat().st_mode & 0o777 == 0o600 + assert len(actions) == 1 and len(calls) == 5 and sleeps == [2, 5, 10] + command = str(exc.value).split("Retry the same payment by hand: ")[1] + argv = shlex.split(command) + assert argv[2:] == ["retry-payment", str(path)] + outcomes.append((200, {"ok": True}, True)) + monkeypatch.setattr(sys, "argv", argv[1:]) + helper().main() + assert '"status": 200' in capsys.readouterr().out + assert len(actions) == 1 + assert calls[-1][1] == calls[1][1] + assert calls[-1][0]["x-bsv-payment"] == calls[1][0]["x-bsv-payment"] + assert not path.exists() + + +def test_quote_window_includes_elapsed_request_time(server, monkeypatch): + outcomes, actions, calls, sleeps, now, _ = server + # One lost send leaves too little time for even the first backoff. + original = requests.request + def slow(**kwargs): + try: + return original(**kwargs) + finally: + if len(calls) == 2: + now[0] += 299 + monkeypatch.setattr(requests, "request", slow) + outcomes.append(requests.Timeout("lost")) + with pytest.raises(payment.PaymentError): + payment.paid_request("POST", URL) + assert len(calls) == 2 and len(actions) == 1 and sleeps == [] + with pytest.raises(payment.PaymentError): + now[0] += 2 + payment.retry_payment(payment.PENDING_DIR / f"{TXID}.json") + assert len(calls) == 2 + + +@pytest.mark.parametrize("failure", ["quote", "parse", "wallet"]) +def test_pre_payment_failure(server, monkeypatch, failure): + _, actions, calls, sleeps, _, quote_headers = server + if failure == "quote": + monkeypatch.setattr(requests, "request", lambda **kw: (_ for _ in ()).throw(requests.Timeout())) + elif failure == "parse": + quote_headers.pop("x-bsv-payment-satoshis-required") + else: + monkeypatch.setattr(payment, "get_public_key", lambda **kw: (_ for _ in ()).throw(RuntimeError("unavailable"))) + with pytest.raises(Exception): + payment.paid_request("POST", URL) + assert actions == [] and sleeps == [] + assert not payment.PENDING_DIR.exists() or list(payment.PENDING_DIR.iterdir()) == [] + + +def test_signed_refund_internalized_once(server, monkeypatch): + from lib import refund + outcomes, actions, calls, sleeps, _, _ = server + outcomes.extend([requests.Timeout("lost"), (500, {"refund": { + "transaction": "AQID", "derivationPrefix": "refund-prefix", "derivationSuffix": "refund-suffix", + "senderIdentityKey": SERVER_KEY, "satoshis": 5, "txid": "34" * 32}}, True)]) + imports = [] + monkeypatch.setattr(refund, "process_refund", lambda info: imports.append(info) or {"accepted": True}) + response = payment.paid_request("POST", URL) + assert response.status_code == 500 and len(imports) == 1 + assert not (payment.PENDING_DIR / f"{TXID}.json").exists() + + +@pytest.mark.parametrize("signed", [True, False]) +def test_paid_402_never_creates_second_payment(server, signed): + outcomes, actions, calls, sleeps, _, _ = server + outcomes.append((402, {"payment": "required"}, signed)) + with pytest.raises(payment.PaymentError, match=TXID): + payment.paid_request("POST", URL) + assert len(actions) == 1 and len(calls) == 2 and sleeps == [] + assert (payment.PENDING_DIR / f"{TXID}.json").exists() + + +def test_signing_delay_cannot_send_after_deadline(server, monkeypatch): + outcomes, actions, calls, _, now, _ = server + original = auth_request.create_signature + def slow_sign(**kwargs): + if calls: + now[0] += 301 + return original(**kwargs) + monkeypatch.setattr(auth_request, "create_signature", slow_sign) + with pytest.raises(payment.PaymentError): + payment.paid_request("POST", URL) + assert len(actions) == 1 and len(calls) == 1 + assert (payment.PENDING_DIR / f"{TXID}.json").exists() + + +def test_recovery_requires_original_wallet(server, monkeypatch): + from lib import metanet + outcomes, actions, calls, _, _, _ = server + outcomes.extend([requests.Timeout("lost")] * 4) + with pytest.raises(payment.PaymentError): + payment.paid_request("POST", URL) + monkeypatch.setattr(metanet, "get_identity_key", lambda: "different-wallet") + with pytest.raises(payment.PaymentError, match="wallet identity"): + payment.retry_payment(payment.PENDING_DIR / f"{TXID}.json") + assert len(actions) == 1 and len(calls) == 5 + + +@pytest.mark.parametrize("offset, expected", [(-1000, 1300), (-61, 1300), (-60, 1240), (-30, 1270), (0, 1300), (60, 1300)]) +def test_server_date_bounds_quote(server, offset, expected): + from email.utils import formatdate + outcomes, actions, calls, _, _, quote_headers = server + quote_headers["Date"] = formatdate(1000 + offset, usegmt=True) + outcomes.extend([requests.Timeout("lost")] * 4) + with pytest.raises(payment.PaymentError): + payment.paid_request("POST", URL) + record = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text()) + assert record["expires_at"] == expected + assert len(actions) == 1 + + +def test_helper_does_not_import_refund_twice(server, monkeypatch, capsys): + from lib import refund + outcomes, _, _, _, _, _ = server + outcomes.append((200, {"refund": { + "transaction": "AQID", "derivationPrefix": "refund-prefix", "derivationSuffix": "refund-suffix", + "senderIdentityKey": SERVER_KEY, "satoshis": 5, "txid": "34" * 32}}, True)) + imports = [] + monkeypatch.setattr(refund, "process_refund", lambda info: imports.append(info) or {"accepted": True}) + monkeypatch.setattr(sys, "argv", ["helper", "pay", "POST", URL]) + helper().main() + result = json.loads(capsys.readouterr().out) + assert result["refund"]["processed"] is True + assert len(imports) == 1 + + +@pytest.mark.parametrize("field", ["refund", "excessRefund"]) +@pytest.mark.parametrize("failure", ["rejected", "exception"]) +def test_failed_refund_preserves_response_and_manual_import(server, monkeypatch, capsys, field, failure): + from lib import refund + outcomes, actions, calls, _, _, _ = server + body = {"answer": "delivered result", field: { + "transaction": "AQID", "derivationPrefix": "refund-prefix", "derivationSuffix": "refund-suffix", + "senderIdentityKey": SERVER_KEY, "satoshis": 5, "txid": "34" * 32}} + outcomes.append((200, body, True)) + def fail(info): + if failure == "exception": + raise RuntimeError("wallet unavailable") + return {"accepted": False} + monkeypatch.setattr(refund, "process_refund", fail) + response = payment.paid_request("POST", URL) + assert response.json() == body + assert response.refund_result["processed"] is False + path = payment.PENDING_DIR / f"{TXID}.json" + saved = json.loads(path.read_text()) + assert base64.b64decode(saved["response"]["body"]) == response.content + assert path.stat().st_mode & 0o777 == 0o600 + with pytest.raises(payment.PaymentError, match="response already saved"): + payment.retry_payment(path) + imports = [] + monkeypatch.setattr(refund, "process_refund", lambda info: imports.append(info) or {"accepted": True}) + argv = shlex.split(response.refund_result["command"]) + assert argv[2:] == ["import-refund", str(path)] + monkeypatch.setattr(sys, "argv", argv[1:]) + helper().main() + assert json.loads(capsys.readouterr().out)["accepted"] is True + assert payment.import_refund(path)["already_imported"] is True + assert len(imports) == 1 and imports[0].transaction == body[field]["transaction"] + assert json.loads(path.read_text())["refund_imported"] is True + assert len(actions) == 1 and len(calls) == 2 + + +def test_pending_receipt_reuses_payment(server): + outcomes, actions, calls, sleeps, _, _ = server + outcomes.extend([(202, {"code": "RECEIPT_PENDING"}, True), (200, {"ok": True}, True)]) + assert payment.paid_request("POST", URL).status_code == 200 + assert sleeps == [5] and len(actions) == 1 + assert calls[1][0]["x-bsv-payment"] == calls[2][0]["x-bsv-payment"] + + +def test_wallet_action_failure_does_not_send_payment(server, monkeypatch): + _, actions, calls, sleeps, _, _ = server + def fail(**kwargs): + raise RuntimeError("wallet unavailable") + monkeypatch.setattr(payment, "create_action", fail) + with pytest.raises(payment.PaymentError, match="Failed to create payment transaction"): + payment.paid_request("POST", URL) + assert len(calls) == 1 and actions == [] and sleeps == [] + assert list(payment.PENDING_DIR.iterdir()) == [] + + +@pytest.mark.parametrize("hand_retry", [False, True]) +def test_first_send_or_hand_retry_quote_expired_is_terminal(server, hand_retry): + outcomes, actions, calls, _, _, _ = server + path = payment.PENDING_DIR / f"{TXID}.json" + if hand_retry: + outcomes.extend([requests.Timeout("lost")] * 4) + with pytest.raises(payment.PaymentError): + payment.paid_request("POST", URL) + outcomes.append((400, {"code": "ERR_QUOTE_EXPIRED", "message": "fresh quote"}, True)) + with pytest.raises(payment.PaymentError, match=TXID) as exc: + if hand_retry: + payment.retry_payment(path) + else: + payment.paid_request("POST", URL) + assert "the server may not have claimed this payment" in str(exc.value) + assert "retry-payment" not in str(exc.value) + assert len(actions) == 1 and path.exists() + saved = json.loads(path.read_text()) + assert saved["state"] == "expired-unclaimed" + assert saved["server_code"] == "ERR_QUOTE_EXPIRED" + assert saved["server_message"] == "fresh quote" + + +def test_error_message_text_does_not_establish_replay(server): + outcomes, actions, _, _, _, _ = server + outcomes.append((400, {"code": "OTHER", "message": "already claimed payment replayed ERR_QUOTE_EXPIRED"}, True)) + assert payment.paid_request("POST", URL).status_code == 400 + assert len(actions) == 1 + assert (payment.PENDING_DIR / f"{TXID}.json").exists() + + +def test_slow_paid_response_keeps_full_read_timeout(server, monkeypatch): + outcomes, actions, calls, _, now, _ = server + original_create = payment.create_payment + def slow_create(*args): + result = original_create(*args) + now[0] += 250 + return result + monkeypatch.setattr(payment, "create_payment", slow_create) + original_request = requests.request + def slow_response(**kwargs): + response = original_request(**kwargs) + if len(calls) == 2: + assert kwargs["timeout"] == 300 + now[0] += 240 + return response + monkeypatch.setattr(requests, "request", slow_response) + outcomes.append((200, {"answer": "slow result"}, True)) + assert payment.paid_request("POST", URL).json()["answer"] == "slow result" + assert len(actions) == 1 and len(calls) == 2 + assert now[0] > 1300 + + +@pytest.mark.parametrize("expired", [False, True]) +def test_paid_session_refresh_preserves_deadline(server, monkeypatch, expired): + outcomes, actions, calls, _, now, _ = server + outcomes.extend([(401, {"code": "SESSION_EXPIRED"}, True), (200, {"ok": True}, True)]) + original = auth_request.clear_session + def refresh(*args, **kwargs): + original(*args, **kwargs) + if expired: + now[0] += 301 + monkeypatch.setattr(auth_request, "clear_session", refresh) + if expired: + with pytest.raises(payment.PaymentError) as exc: + payment.paid_request("POST", URL) + assert "retry-payment" not in str(exc.value) + assert "the server may not have claimed this payment" in str(exc.value) + assert len(calls) == 2 + else: + assert payment.paid_request("POST", URL).status_code == 200 + assert calls[1][1] == calls[2][1] + assert calls[1][0]["x-bsv-payment"] == calls[2][0]["x-bsv-payment"] + assert len(actions) == 1 + + +@pytest.mark.parametrize("multipart", [False, True]) +def test_quoted_and_paid_body_bytes_match(server, monkeypatch, multipart): + outcomes, _, calls, _, _, _ = server + if multipart: + monkeypatch.setattr(payment, "MULTIPART_THRESHOLD", 1) + outcomes.append((200, {"ok": True}, True)) + payment.paid_request("POST", URL, body=' { "input": "hello" } ') + assert calls[0][1] == b'{"input":"hello"}' + assert calls[0][0]["content-type"] == "application/json" + if multipart: + assert b"Content-Type: application/json\r\n\r\n" + calls[0][1] + b"\r\n" in calls[1][1] + else: + assert calls[0][1] == calls[1][1] + assert calls[0][0]["content-type"] == calls[1][0]["content-type"] + + +def test_pending_write_failure_prints_payment_json(server, monkeypatch, capsys): + _, actions, calls, _, _, _ = server + def fail(record): + raise OSError("disk full") + monkeypatch.setattr(payment, "_save_pending", fail) + with pytest.raises(payment.PaymentError, match=TXID): + payment.paid_request("POST", URL) + payment_json = capsys.readouterr().err.split("recovery JSON: ")[1] + assert json.loads(payment_json)["transaction"] == "AQID" + assert len(actions) == 1 and len(calls) == 1 + + +def test_refund_save_failure_returns_response_and_prints_recovery(server, monkeypatch, capsys): + from lib import refund + outcomes, actions, calls, _, _, _ = server + body = {"answer": "delivered", "excessRefund": { + "transaction": "AQID", "derivationPrefix": "refund-prefix", "derivationSuffix": "refund-suffix", + "senderIdentityKey": SERVER_KEY, "satoshis": 5, "txid": "34" * 32}} + outcomes.append((200, body, True)) + monkeypatch.setattr(refund, "process_refund", lambda info: {"accepted": False}) + save = payment._save_pending + def fail_response_save(record, path=None): + if "response" in record: + raise OSError("disk full") + return save(record, path) + monkeypatch.setattr(payment, "_save_pending", fail_response_save) + response = payment.paid_request("POST", URL) + assert response.json() == body and response.refund_result["processed"] is False + saved = json.loads(capsys.readouterr().err.split("Recovery JSON: ")[1]) + assert json.loads(base64.b64decode(saved["response"]["body"])) == body + assert len(actions) == 1 and len(calls) == 2 + + +@pytest.mark.parametrize("status, code", [(201, None), (400, "ERR_INVALID_PAYMENT"), + (500, "ERR_PAYMENT_FAILED")]) +def test_unconfirmed_response_keeps_terminal_record(server, status, code): + outcomes, actions, calls, _, now, _ = server + outcomes.append((status, {"code": code, "message": "unconfirmed"}, True)) + assert payment.paid_request("POST", URL).status_code == status + path = payment.PENDING_DIR / f"{TXID}.json" + saved = json.loads(path.read_text()) + assert saved["state"] == "terminal-unresolved" + assert saved["terminal_at"] == now[0] + assert saved["server_code"] == code + assert saved["server_message"] == "unconfirmed" + with pytest.raises(payment.PaymentError, match="keep this file"): + payment.retry_payment(path) + assert len(actions) == 1 and len(calls) == 2