Metadata-Version: 2.5
Name: deadhop-client
Version: 0.1.0
Summary: Python client for deadhop: create on-chain bitcoin invoices over ContextVM (MCP over Nostr) and follow them until paid.
Project-URL: Homepage, https://deadhop.run
Project-URL: Documentation, https://deadhop.run/docs/integrate-backend.html
Project-URL: Repository, https://github.com/deadhop/client-py
Project-URL: Issues, https://github.com/deadhop/client-py/issues
Author: deadhop
License-Expression: MIT
License-File: LICENSE
Keywords: bitcoin,contextvm,invoice,mcp,nostr,payments
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: nostr-sdk<0.46,>=0.45.2
Requires-Dist: websockets>=14
Description-Content-Type: text/markdown

<div align="center">

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://deadhop.run/docs/mark-fog.svg">
  <img alt="deadhop mark" src="https://deadhop.run/docs/mark.svg" width="72">
</picture>

# deadhop-client for Python

Create bitcoin invoices on a [deadhop](https://deadhop.run) service and check that they are paid,
from your Python backend.

[![CI](https://img.shields.io/github/actions/workflow/status/deadhop/client-py/ci.yml?branch=main&style=for-the-badge&label=ci)](https://github.com/deadhop/client-py/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.11%2B-5fc6b9?style=for-the-badge)](pyproject.toml)
[![License](https://img.shields.io/github/license/deadhop/client-py?style=for-the-badge)](LICENSE)

</div>

A deadhop service has no web address. Your code reaches it through Nostr relays, with nothing
but the service's public key and a relay it listens on. This package handles that connection,
the proof of work a public invoice needs, and checking every answer before you see it. It is
the Python sibling of [`@deadhop/client`](https://github.com/deadhop/js/tree/main/packages/client)
and has no UI: show the invoice with the JavaScript components, or your own page.

```sh
pip install "git+https://github.com/deadhop/client-py@main"
```

Not on PyPI yet: until the first release (`pip install deadhop-client`), install from this
repository.

Python 3.11 or later, on Linux, macOS and Windows. The Nostr cryptography comes from
[`nostr-sdk`](https://pypi.org/project/nostr-sdk/) (prebuilt wheels, no compiler needed).

## Create an invoice and check it is paid

```python
import asyncio, os
from deadhop_client import Deadhop

deadhop = Deadhop(
    server_pubkey=os.environ["DEADHOP_SERVER_PUBKEY"],  # hex, npub or nprofile
    relays=os.environ["DEADHOP_RELAYS"].split(","),
    secret_key=os.environ["DEADHOP_BACKEND_NSEC"],  # an operator key: no proof of work
)


async def main() -> None:
    invoice = await deadhop.create_invoice(21_000, memo="Order 42")
    print(invoice.bip21)  # bitcoin:bcrt1q…?amount=0.00021000

    # …later, before you ship:
    paid = await deadhop.get_invoice(invoice.id)
    if paid.status == "confirmed" and paid.amount_sat == 21_000:
        print("ship it")
    await deadhop.close()


asyncio.run(main())
```

Create one `Deadhop` per process. It connects on first use, keeps one connection, and tries
again on the next call after a failure. It is also an async context manager.

**Who signs.** Leave out `secret_key` and each `Deadhop` makes a throwaway key: a guest. A guest can create
invoices only if the service allows public invoicing, and first mines the proof of work it asks
for (about 0.6 s on one core of a laptop at the service's default of 20 bits). Pass an `nsec` (or hex) whose
public key is in the service's operators (`DEADHOP_ADMINS`) to skip the work. **An operator key
can also manage the service:** keep it in your server's secrets. See
[Give your backend a key](https://deadhop.run/docs/integrate-backend.html#give-your-backend-a-key).

## Check before you fulfil

- `detected` means the payment was seen, not that it is final: an unconfirmed payment can still
  disappear. Wait for `confirmed`.
- An `expired` invoice can still become `confirmed`: the service keeps watching for late
  payments.
- Check the amount too, when someone else created the invoice.
- There are no webhooks. Poll `get_invoice`, or wait in a background task:

```python
invoice = await deadhop.wait_for_invoice(invoice_id, until=("confirmed",), interval=10, timeout=3600)
```

## Errors

Every failure is an `ApiError` with a stable `code`, and a message fit to show to people:

```python
from deadhop_client import ApiError

try:
    await deadhop.create_invoice(500)
except ApiError as e:
    if e.code == "invalid_params":
        print(e.message)  # The service rejected the request as invalid. (amount_sat must be between …)
```

| Code | Meaning |
| --- | --- |
| `unauthorized` | This key may not do that (is it in `DEADHOP_ADMINS`?) |
| `invalid_params` | The request was refused as invalid (amount out of range, bad id) |
| `not_found` | No such invoice |
| `rate_limited`, `capacity`, `paused` | Try again later, or the operator stopped invoicing |
| `pow_rejected`, `pow_failed` | The proof of work was refused (check the clock), or the service asks for more than `max_pow_bits` |
| `timeout`, `network` | The service did not answer on these relays |
| `bad_response` | The answer failed validation and was discarded |
| `internal` | The service had an internal error |

`await deadhop.info()` returns the service's limits (`min_amount_sat`, `max_amount_sat`,
`max_expiry_secs`, …) and the proof of work it asks of your key.

## API

| Name | What it is |
| --- | --- |
| `Deadhop(server_pubkey, relays, *, secret_key=None, connect_timeout=20, call_timeout=60, max_pow_bits=28)` | One service. Raises `ValueError` for an unusable key or relay list |
| `info()` | `ServiceInfo`: name, network, limits, `pow_bits`, `is_admin` |
| `create_invoice(amount_sat, memo=None, expiry_secs=None)` | A new `Invoice` |
| `get_invoice(invoice_id)` | The invoice now. Any key can read any invoice: the id is the capability |
| `wait_for_invoice(invoice_id, until=("confirmed", "expired"), *, interval=5, timeout=None)` | Polls until the status is in `until` |
| `call_tool(name, arguments)` | Any other tool, such as the operator tools, unvalidated |
| `close()` | Closes the relay connections; the next call opens them again |
| `Invoice`, `ServiceInfo` | Frozen dataclasses of what the service reported |
| `ApiError`, `ERROR_CODES` | Every failure, with its `code` |
| `parse_invoice`, `parse_info`, `parse_config`, `normalize_pubkey`, `uri_matches` | The checks behind the client, for your own use |

## What is checked

The client refuses an answer before you see it when it is not the service's or not what you
asked for:

- **Who answered.** Anyone can publish an event to your key on a relay. Replies arrive
  encrypted (NIP-44) in a gift wrap signed by a throwaway key, so the wrap proves nothing. The
  client reads a reply only when the event inside is signed by the service's key and names
  your request; it ignores everything else.
- **Who may read the replies.** When a relay asks for NIP-42 authentication, the client signs
  the relay's challenge with its own key, the one replies are addressed to. A relay that
  delivers replies only to their recipient, like deadhop's own, can then send them to you and
  to no one else. Relays that do not ask work as before.
- **What it says.** Invoices and service info must have exactly the expected fields, in range.
  The `bip21` URI must pay exactly the invoice's address and amount, and an answer must be about
  the invoice id or amount you asked for.

These are the same rules as the JavaScript client's: both are tested against one set of cases
(`tests/vectors.json`, generated from `@deadhop/client`).

## Develop

Requirements: Python 3.11+ and [`just`](https://github.com/casey/just).

```sh
python -m venv .venv && . .venv/bin/activate
pip install -e . --group dev       # pip 25.1 or later
just check      # ruff, mypy --strict, unit tests (an in-process relay and service)
just package    # build, twine check, install the wheel in a fresh venv
just e2e        # against a running service: see below
```

The end-to-end tests create, pay and confirm a real regtest invoice. They need the regtest stack
from [deadhop/stack](https://github.com/deadhop/stack) (`just up`, `just server` there), then:

```sh
export DEADHOP_E2E_SERVER=<the service's hex key> DEADHOP_E2E_RELAY=ws://127.0.0.1:7777
export DEADHOP_E2E_PAY=<path to deadhop/stack>/scripts/dev-pay.sh       # optional: pays and confirms
export DEADHOP_E2E_OPERATOR_NSEC=<an operator nsec>                     # optional: the operator path
just e2e
```

```
.
├── .github/workflows/    ci.yml (every push and pull request), publish.yml (tags)
├── scripts/              check-wheel.sh
├── src/deadhop_client/   the package
├── tests/                unit tests, the shared vectors, the e2e test
├── justfile
├── pyproject.toml
└── RELEASING.md          versions, tags, and the PyPI setup
```

Releases go to PyPI from a `vX.Y.Z` tag, with trusted publishing: see [RELEASING.md](RELEASING.md).

## Contributing

Issues and pull requests are welcome here. CI runs `just check` and the package check on every
pull request. Doc changes go to [deadhop/site](https://github.com/deadhop/site).

## License

[MIT](LICENSE).
