Metadata-Version: 2.4
Name: cowboy-sdk
Version: 0.2.0
Summary: Python SDK for Cowboy
Author-email: Cowboy <nathan@cowboy.inc>
License-Expression: MIT
Project-URL: Repository, https://github.com/cowboyinc/python-sdk
Project-URL: Issues, https://github.com/cowboyinc/python-sdk/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.0
Requires-Dist: eth-account<0.20,>=0.10
Requires-Dist: cbor2<6,>=5.4
Requires-Dist: blake3<2,>=0.3
Requires-Dist: cryptography<49,>=42
Requires-Dist: idna<4,>=3.4
Requires-Dist: cowboy-protocol-py==0.8.0
Provides-Extra: ras
Requires-Dist: cryptography<49,>=42; extra == "ras"
Provides-Extra: watchtower
Requires-Dist: cryptography<49,>=42; extra == "watchtower"
Requires-Dist: PyNaCl<2,>=1.5; extra == "watchtower"
Provides-Extra: dev
Requires-Dist: PyNaCl<2,>=1.5; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Requires-Dist: python-dotenv; extra == "dev"
Requires-Dist: responses; extra == "dev"
Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "dev"
Requires-Dist: ruff==0.15.8; extra == "dev"
Requires-Dist: mypy==2.3.1; extra == "dev"
Requires-Dist: pygments>=2.20.0; extra == "dev"
Requires-Dist: unasync<1,>=0.6; extra == "dev"
Requires-Dist: cryptography<49,>=42; extra == "dev"
Requires-Dist: PyYAML<7,>=6; extra == "dev"
Dynamic: license-file

# cowboy-sdk

Python SDK for the [Cowboy](https://cowboy.xyz) decentralized compute network.

See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for a contributor-oriented overview of the codebase internals.

## Requirements

- Python 3.10+

## Installation

```bash
pip install 'cowboy-sdk>=0.2.0'
```

**`0.2.0` is the first release of this client on PyPI**, and it is not
published yet: until it is, install from source (below). Keep the `>=0.2.0`
bound. The same PyPI name once carried a different package, so an unbounded
`pip install cowboy-sdk` can resolve to it.

### Distributions and versions

| Distribution | Import | What it is |
| --- | --- | --- |
| `cowboy-sdk` 0.2.0 and later | `cowboy` | This client SDK, published from `cowboyinc/python-sdk`. |
| `cowboy-sdk` 0.1.0, 0.1.1 | `cowboy_sdk` | **Historical actor SDK releases** (March 2026). They are not this client and are never re-published. |
| `cowboy-actor-sdk` | `cowboy_sdk` | The actor SDK for writing on-chain actors, now published under its own name from `cowboyinc/core`. |

The two current distributions install different top-level packages, so a
project can depend on both: an actor project depends on `cowboy-actor-sdk` and,
if it also drives the chain from Python, on `cowboy-sdk>=0.2.0`. An actor project
that still requires `cowboy-sdk` for its actor code (for example
`cowboy-sdk>=0.1.2`, which older CLI scaffolds wrote; current ones write
`cowboy-actor-sdk>=0.1.2`) must switch that requirement to `cowboy-actor-sdk`: from 0.2.0 the `cowboy-sdk` name resolves to
this client. Its `import cowboy_sdk` lines stay as they are.

The protocol codec comes in through `cowboy-protocol-py`, pinned to one release;
`protocol-pin.json` records which commit and WASM that release is. See
[docs/RELEASING.md](docs/RELEASING.md).

### Migrating from `cowboy-sdk` 0.1.x

`cowboy-sdk` 0.1.x was the actor SDK, which is now distributed as
`cowboy-actor-sdk`. Actor code continues to use `import cowboy_sdk`. Starting
with 0.2.0, `cowboy-sdk` is the client SDK and uses `import cowboy`. See the
[migration guide](https://docs.cowboy.inc/developers/migrating-from-cowboy-sdk-0-1)
for migration and repair steps.

### From source

With dev dependencies:

```bash
git clone <repo>
cd python-sdk
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
```

### `set_secret` / CBSS

`ChainClient.set_secret` and `encrypt_secret_for_account` need the native
`cowboy-crypto` extension (the BLS12-381 IBE wrap). The core SDK stays
pure-Python; methods that need the extension raise a clear `ImportError` if it is
missing.

**There is no `[crypto]` extra yet.** `cowboy-crypto` is not published to any
package index, so `0.2.0` does not declare it. The extra returns once
`cowboy-crypto` is published from `cowboyinc/core`. Until then the supported
installation is the native wheel, installed directly, then the SDK:

```bash
# 1. Get the cowboy-crypto wheel for your platform — from a cowboyinc/core
#    `core-extras` GitHub Actions run (Artifacts → crypto-wheels-*), or build
#    it locally:
#      maturin build --release -m path/to/core/protocol/bindings/cowboy-crypto/Cargo.toml
pip install ./cowboy_crypto-*.whl

# 2. Install the SDK (the manually-installed extension satisfies the import)
pip install 'cowboy-sdk>=0.2.0'
```

**Which wheel is canonical.** The wheel must be built from the **cowboy-protocol**
tree (`protocol/bindings/cowboy-crypto` in cowboyinc/core, revision `45eefb95` or
later) — it owns the canonical CBSS crypto (AAD layout, IBE identity, wrap-key
HKDF), so any wheel built from it matches what the chain enforces. The revision CI builds and
verifies is pinned as `COWBOY_PROTOCOL_CRYPTO_REV` in
`.github/workflows/ci.yml` (COW-2846; `MATURIN_VERSION` beside it is the
second bump point). The enforcement is the byte-parity vectors in
`tests/unit/test_set_secret.py`, which catch a wrong wheel. They `skip` when
no wheel is installed, except in CI's `native-crypto` job, which builds the
wheel from the pinned rev and runs them with `COWBOY_REQUIRE_NATIVE=1`
(missing wheel ⇒ fail, not skip; `0`/unset ⇒ skip; any other non-empty value
gates on, fail-loud by design). Still run them locally against the exact
wheel you intend to deploy.

### CBSS reshare events (schema v2)

The node-authored `cbss.reshare.requested` event is compact JSON, not actor
CBOR. Decode it with the strict, version-pinned helper:

```python
from cowboy import CBSS_RESHARE_REQUESTED_TOPIC, decode_cbss_reshare_requested_event

for event in receipt.events:
    if event.topic == CBSS_RESHARE_REQUESTED_TOPIC:
        requested = decode_cbss_reshare_requested_event(event.data)
        for member in requested.new_committee_metadata:
            connect_to = member.network_addr
```

Schema v2 carries complete connection metadata only for the five new committee
members. `old_committee_proxy_ids` and `old_signer_proxies` are proxy-ID
references and are the event-authoritative membership. Resolve their connection
metadata from the current `/cbss/proxies` registry because the node exposes no
exact-height registry read and registry snapshots are only every 100,000 blocks.
A missing ID must produce an explicit per-member resolution error rather than
being silently omitted; current registry membership must never replace the IDs
carried by the event.

The strict decoder rejects every schema version other than `2`, non-canonical
binary fields, and data over 512 KiB before JSON parsing. The largest legal
corpus is 130,974 data bytes (131,008 bytes as its `SystemBytes` page). The
durable FIFO is bounded to eight pages, 256 events, and 1 MiB. The CBSS actor log
is separately bounded and may trim old entries, so consumers should checkpoint
event height/order and must not assume indefinite log retention.

## Configuration

Copy `.env.example` to `.env` and fill in your values:

```bash
cp .env.example .env
```

| Variable | Description |
|---|---|
| `COWBOY_RPC_URL` | Node RPC URL (e.g. `http://localhost:4000`) |
| `COWBOY_KEY_FILE` | Path to PEM private key file |
| `COWBOY_BASE_URL` | Validator URL (alias for `COWBOY_RPC_URL`) |

---

## Usage

### Client

```python
from cowboy import CowboyClient

# Read-only
client = CowboyClient("http://localhost:4000")

# With signing key (required for write operations)
client = CowboyClient(
    "http://localhost:4000", private_key=open("key.pem").read(),
    expected_chain_id=42, expected_network="local",  # use your configured values
)

# Context manager — closes the HTTP connection on exit
with CowboyClient(
    "http://localhost:4000", private_key=key, expected_chain_id=42, expected_network="local"
) as client:
    height = client.get_height()
```

Signing on a custom endpoint requires both the configured `expected_chain_id`
and `expected_network`. Discovery checks those values and obtains the genesis
instance from the endpoint; applications must never compile in an instance ID.
Transaction and signed-object helpers take the validated `ChainIdentity`.
A client refuses an observed identity change; create a new client after genesis.

#### Network presets

```python
from cowboy import CowboyClient, Network

client = CowboyClient(network=Network.MESA, private_key=key)
client = CowboyClient(network=Network.LOCAL)   # http://localhost:4000

# Summit (mainnet) requires an explicit rpc_url — bare Network.SUMMIT is rejected
client = CowboyClient(network=Network.SUMMIT, rpc_url="https://rpc.summit.example.com")
```

### Async client

```python
from cowboy import AsyncCowboyClient

async with AsyncCowboyClient(
    "http://localhost:4000", private_key=key, expected_chain_id=42, expected_network="local"
) as client:
    height = await client.get_height()
    account = await client.get_account("0xABCD...")
```

All methods on `CowboyClient` have async equivalents on `AsyncCowboyClient` — just `await` them.

---

### Chain queries

```python
# Block and chain state
height = client.get_height()
block  = client.get_block("latest")       # by "latest", block hash, or height int
fee    = client.get_basefee()             # BaseFee: cycle/cell fee oracle values
ok     = client.health()                  # True if node reports healthy

# Closed v3 discovery: chain id, genesis instance, network, activation digest,
# transaction version, and supported signature modes.
info = client.get_chain_info()
identity = info.identity()               # pass this to transaction/object signing
parameters = client.get_chain_parameters()  # storage clock, activation, deployers

# Accounts
account = client.get_account("0xABCD...")  # raises AccountNotFound if absent

# Transactions
tx      = client.get_transaction("0xhash...")
receipt = client.get_transaction_receipt("0xhash...")  # raises TransactionFailed on failure
pending = client.get_mempool_transaction("0xhash...")

# Actors
info    = client.get_actor("0xABCD...")        # raises ActorNotFound if absent
code    = client.get_actor_code("0xABCD...")
logs    = client.get_actor_logs("0xABCD...")   # list[ActorEvent]
value   = client.get_actor_storage("0xABCD...", key="my_key")   # bytes | None
storage = client.get_actor_storage_all("0xABCD...")             # dict[str | bytes, bytes]

# Upgrade preflight: committed code hash + whether account libraries are pinned.
# Context only — it neither authorizes nor guards a later upgrade.
ctx     = client.get_actor_upgrade_context("0xABCD...")         # ActorUpgradeContext
```

---

### Standing workload mount policies

CIP-10 standing consent uses the canonical CN-19 workload policy exports. The
caller supplies one trusted `ChainIdentity` and the current volume owner proven
at the same finalized root as the workload, volume, pool and owner account-auth
claims. Read the
planned policy before signing it:

```python
import json
from cowboy import (
    WorkloadMountPolicyV1,
    workload_mount_policy_plan,
    workload_mount_policy_instruction,
)

# record_json is the canonical workload record as UTF-8 bytes.
# owner_auth is authenticated at that same root. For trusted-RPC workflows,
# client.get_account_auth(current_owner) reads the current endpoint form.
owner_auth_json = json.dumps(owner_auth)
policy_revision = "0" if owner_auth["kind"] == "AddressDerived" else str(owner_auth["policy_revision"])
# Epoch/revision arguments are canonical decimal u64 strings.
plan_json = workload_mount_policy_plan(
    record_json, volume_id, current_owner, "99", "4", policy_revision, trusted_identity
)
plan = json.loads(plan_json)
policy = WorkloadMountPolicyV1(json.dumps(plan["policy"]))
# After inspecting/approving the policy:
signed = policy.sign(
    owner_private_key, trusted_identity,
    current_owner=current_owner, owner_auth_json=owner_auth_json,
)
publish_json = workload_mount_policy_instruction(
    record_json, volume_id, current_owner, "99", "4",
    json.dumps(signed.signature), owner_auth_json, trusted_identity,
)
```

`workload_mount_policy_plan` and `workload_mount_policy_instruction` return the
codec's exact JSON **text**, without re-serialization. Parse `publish_json` when
passing the instruction to the transaction signer. Object preimage/hash exports
return `bytes`; `workload_mount_policy_verify` returns `{"address": ...}`. The
policy classes require the independently proven current owner and current
owner account-auth policy for signing and verification. The policy key may be
a rotated key; the account address stays the owner. Publication and release still require the node's current revision,
expiry, ownership, pool and attempt checks. Revocation uses only the outer v3
transaction signature.

The former credential-offer/owner-certificate flow and the three workload
delegation classes are removed. Ordinary CBFS delegations retain only
`MOUNT_CAPABLE_V1` and `NON_MOUNT_SERVICE_V1`.

### Native token transfers

```python
tx_hash = client.transfer(to="0xABCD...", amount=1_000_000)
```

SDK-built writes use estimate-then-sign by default: the client signs a
provisional transaction, sends that exact transaction to `POST /estimate_gas`,
re-signs the same nonce with the node's cycle/cell/access suggestions, and only
then submits. A dry run that reports `accesses_exceed_admission_ceiling` raises
`AccessLimitExceeded` before `/submit`; the SDK never clamps the estimate.
All three fee suggestions come from `GET /basefee`.

`estimate(signed_tx)` exposes the same dry run as a first-class `GasEstimate`,
including resource usage, suggested limits, status/success, per-meter fee
suggestions, and worst-case cost properties:

```python
estimate = client.estimate(signed_tx)
print(estimate.accesses_used, estimate.access_limit_suggested)
print(estimate.suggested_max_fee_per_access, estimate.total_max_cost)
```

Every typed write helper accepts `options`; explicit values override the
matching suggestions. Supplying all three limits skips `/estimate_gas`, and
supplying all three fees skips `/basefee`. The node already adds its standard
headroom; state-dependent transactions can request more without silent
clamping. Before both the provisional and final signature, the SDK fetches the
signer's current balance and rejects when the exact three-meter declared
maximum spend exceeds it. Set `max_total_cost` for a stricter caller-selected
bound:

```python
from cowboy import TransactionOptions

tx_hash = client.transfer(
    to="0xABCD...",
    amount=1_000_000,
    options=TransactionOptions(
        additional_access_headroom=8,
        max_total_cost=50_000_000,
    ),
)

# Deliberate fully explicit override: neither estimator nor fee oracle is used.
tx_hash = client.transfer(
    to="0xABCD...",
    amount=1_000_000,
    options=TransactionOptions(
        cycles_limit=200_000,
        cells_limit=20_000,
        access_limit=13,
        max_fee_per_cycle=10,
        max_fee_per_cell=10,
        max_fee_per_access=10,
    ),
)
```

`submit_raw(signed_tx)` remains an explicit low-level bypass because an already
signed transaction cannot have its limits replaced safely. Use
`submit_raw_instruction(..., options=...)` when the SDK should own
the estimate and final signature.

---

### Actors

#### Deploy

```python
from cowboy import CowboyClient

with open("actor.py", "rb") as f:
    code = f.read()

result = client.deploy_actor(
    code=code,
    salt=b"my-salt",          # optional — affects the deterministic address
    init_handler="init",       # optional — called immediately after deploy
    init_payload=b"",          # optional — passed to init_handler
)

print(result.actor_address)    # deterministic on-chain address
print(result.deploy_tx_hash)
print(result.init_tx_hash)     # None if no init_handler
```

`deploy_actor` defaults to `owner_draw=OwnerDraw.default()` (import `OwnerDraw`
from `cowboy`). This creates a revocable `FallbackToOwnerBalance` entitlement
with **NO total cap** for the new actor. Set `owner_draw=OwnerDraw.off()` to
disable that automatic entitlement, or `OwnerDraw.capped(amount)` to limit its
total draw in nano-CBY. Native route installation remains a follow-up for this
helper; it does not expose `routes` yet.

#### Execute

```python
from cowboy.serialization import encode

tx_hash = client.execute_actor(
    actor="0xABCD...",
    handler="increment",
    payload=encode({"amount": 1}),
)
```

---

### Token operations (CIP-20)

#### Create

```python
tx_hash, token_id = client.create_token(
    name="My Token",
    symbol="MTK",
    decimals=18,
    initial_supply=1_000_000,
    max_supply=10_000_000,     # optional hard cap
)
# token_id is derived locally and available immediately, but the token
# doesn't exist on-chain until the transaction is confirmed
client.wait_for_receipt(tx_hash)
```

If you'd rather skip the two-step pattern, `create_token_and_wait` does both atomically and returns the same `(tx_hash, token_id)` tuple.

#### Query

```python
# Call after wait_for_receipt(tx_hash) so the token exists on-chain
info      = client.get_token(token_id)
balance   = client.get_token_balance(token_id, "0xABCD...")
allowance = client.get_token_allowance(token_id, owner="0xOwner...", spender="0xSpender...")
tokens     = client.list_tokens()            # paginated: .items, .total, .limit, .offset
for t in tokens.items:
    print(t.symbol, t.total_supply)
print(f"{len(tokens.items)} of {tokens.total} tokens")

# Page through the registry with explicit offset/limit
page2 = client.list_tokens(offset=50, limit=50)
```

#### Transfer / approve

```python
# Direct transfer
tx_hash = client.transfer_token(token_id, to="0xABCD...", amount=500)

# Transfer on behalf of owner (requires prior approval)
tx_hash = client.transfer_token_from(token_id, owner="0xOwner...", to="0xABCD...", amount=500)

# Approve a spender
tx_hash = client.approve_token(token_id, spender="0xSpender...", amount=1000)

# Atomic batch transfer — all-or-nothing: every leg applies or the whole
# batch reverts with no writes. Supply 1..64 legs, in execution order.
# Each leg follows ordinary TokenTransfer rules, including transfer hooks.
tx_hash = client.batch_transfer_tokens([
    (token_id_a, "0xAlice...", 100),
    (token_id_b, "0xBob...",   200),
])
```

#### Mint / burn

```python
tx_hash = client.mint_token(token_id, to="0xABCD...", amount=1000)
tx_hash = client.burn_token(token_id, amount=500)
```

`burn_token_from` (CIP-36 third-party burn) is **encode/submission support for a
system-only operation** — it is not callable from an external key today. The node
authorizes it solely against a token's immutable `burn_from_authority`, and
`token_create` always stores `None`, so no SDK-created token can ever grant it. The
only production token with an authority is genesis CUSD, whose authority is the
BankActor system address — an address with no keypair. Any externally signed call
therefore fails `Unauthorized` on devnet; on node main, which pins a codec predating
the opcode, the submission fails to decode instead.

#### Admin operations

```python
tx_hash = client.freeze_token(token_id, account="0xABCD...")
tx_hash = client.unfreeze_token(token_id, account="0xABCD...")
tx_hash = client.set_token_hook(token_id, hook_address="0xHook...")  # pass None to clear
tx_hash = client.transfer_token_ownership(token_id, new_owner="0xNewOwner...")
```

---

### Jobs

#### Submit

```python
from cowboy import CowboyClient, JobSpec

spec = (
    JobSpec.llm(
        model="my-model",
        prompt="What is 2+2?",
        max_tokens=256,
    )
    .with_bounds(max_wall_time=60, max_retries=1)
    .with_verification(mode="majorityvote", runners=3, threshold=2)
    .with_callback(actor="0xMyActor...", handler="on_result")
    .with_budget(max_price=1_000_000, tip=10_000, timeout_blocks=50)
)

tx_hash = client.submit_job(spec)
```

JobSpec v6 uses core's default callback budget of 1,000,000 cycles and 150,000
cells. To set a different budget, pass
`resume_budget=ResumeBudget(cycles=6_000_000, cells=5_000_000)` to
`with_callback` (`ResumeBudget` is exported from `cowboy`). Core validates the
budget when the job is built. Container jobs now accept registered resource
class names through `resource_tier` and CBSS key names through `secret_env`.
Class names contain 3–63 lowercase ASCII letters, digits or hyphens, with
alphanumeric ends and no consecutive hyphens. The base-image keys are
`"cby-runner-base"` and `"cby-runner-python"`.
On v6, `"small"` and `"medium"` are not built-in tiers: they are literal resource
class names and work only if registered on the target chain. Omit
`resource_tier` to use core's default class (`"small-ephemeral"` at this pin).

RAS storage epochs also depend on the target chain. Use
`client.get_storage_epoch(height)` (or omit `height` for the current height)
when constructing authorization windows. It reads `/chain-info` for the chain
instance's epoch length and refuses missing or invalid values. The low-level
`storage_epoch_from_height(height, storage_epoch_blocks)` requires that length
explicitly; the old `STORAGE_EPOCH_BLOCKS` export has been removed.

Other job types:

```python
# HTTP fetch
spec = JobSpec.http_request(url="https://api.example.com/data", method="GET")

# Custom executor — `data` is JSON (dict / list / any JSON-serializable value), not raw bytes
spec = JobSpec.custom(job_type="my-executor", data={"seed": 42})

# Agent — open-ended LLM with tool-calling. `query` becomes the agent mode's
# single InteractiveQuery input, which is what the default Interactive profile
# takes; richer transient jobs pass profile=/inputs=/invocation=/secret_bindings=.
spec = (
    JobSpec.agent(
        model="kimi-k2",
        query="Explain the key design decisions in this codebase.",
        max_iterations=12,
        timeout_seconds=180,
    )
    .with_budget(max_price=2_000_000, timeout_blocks=100)
)
tx_hash = client.submit_job(spec)
```

The `JobSpec` builder is the recommended high-level path: it runs the shared
`cowboy-protocol` codec (compiled to WASM) **client-side** to produce the
canonical `JobSpec` bytes the node accepts — applying defaults and hashing
model/executor names into ids — so the bytes you submit are byte-identical to
what every node and runner independently derives.

#### Advanced / low-level submission (⚠️ unstable)

For tests, protocol debugging, and advanced users, you can bypass intent
normalization and submit raw bytes or instructions directly. These APIs are
**unstable** and may change without notice — prefer the `JobSpec` builder above.

```python
# Submit raw *canonical* JobSpec bytes verbatim (no client-side normalization;
# the node still applies protocol/security validation). Use blake3_id() to
# derive the canonical model_id/executor_hash a canonical spec expects.
tx_hash = client.submit_canonical_job_spec(raw_job_spec_bytes)

# Submit any pre-built low-level instruction dict verbatim.
tx_hash = client.submit_raw_instruction({"System": {"JobSubmit": {"job_spec": [...]}}})
```

#### Query / cancel

```python
job     = client.get_job(job_id)
status  = client.get_job_status(job_id)     # "pending" | "executing" | "completed" | "failed"
results = client.get_job_results(job_id)
best    = client.get_job_verified_result(job_id)

tx_hash = client.cancel_job(job_id)
```

---

### Runners

```python
runner  = client.get_runner("0xRunner...")
active  = client.get_active_runners()       # list[RunnerInfo]

# Move where the gateway proxies this runner's Target::Runner routes, without a
# deregister/re-register cycle. The node enforces sender == runner, and validates
# the URL: http is loopback-only, and private/link-local hosts are refused.
client.update_runner_endpoint(my_runner_address, "https://runner-01.example.net:8080")
client.update_runner_endpoint(my_runner_address, None)   # clear the advertisement
```

> The pinned `cowboy-protocol` binding encodes `RunnerUpdateEndpoint` (opcode 219).
> The method still probes the binding before taking a nonce and raises
> `ProtocolBindingTooOld` against an older one. See
> [docs/AUDIT_LOG.md](docs/AUDIT_LOG.md).

---

### Storage volumes (CIP-9 RAS)

RAS requests are authenticated twice: a wallet-signed `DelegationCert` binding a
`cbfs` Ed25519 key, and a per-request envelope that key signs.

```python
from cowboy import (
    EncryptionPublicKey, SigningPublicKey, MountGrant, MountPrincipal,
    generate_cbfs_keypair, mint_delegation_cert,
)

seed, cbfs_pub = generate_cbfs_keypair()
identity = client.get_chain_info().identity()
cert = mint_delegation_cert(private_key, SigningPublicKey.ed25519(cbfs_pub), identity, expires_at_ms)

# Owner: grant another wallet direct access. grantee_signing_key is the grantee's
# registered delegated key; a private volume also needs its X25519 key and the
# volume DEK sealed to it (GrantDekPackage, AAD from grant_dek_aad_bytes).
grant = MountGrant(
    MountPrincipal.account(grantee), "ReadOnly",
    grantee_signing_key=SigningPublicKey.ed25519(grantee_cbfs_pub),
    grantee_encryption_key=EncryptionPublicKey.x25519(grantee_x25519_pub),
    grantee_wrapped_dek=sealed_package,
)
grant.check_for_volume(visibility="PRIVATE", dek_version=dek_version)  # from the volume commitment
client.update_mount_allowlist(volume_id, cbfs_private_key=seed, delegation_cert=cert, add_grants=[grant])

# Grantee: open the owner's volume with its own delegated key. Any unusable grant
# is a plain 404; an unregistered or revoked delegation is a 401.
opened = grantee_client.open_volume("dataset", cbfs_private_key=grantee_seed,
                                    delegation_cert=grantee_cert, owner=owner_address)
opened.grantee_wrapped_dek   # this grantee's sealed DEK package (private volumes)
```

`EncryptionPublicKey` uses algorithm 1 and a contributory 32-byte X25519 key.
Its JSON form is a single `"0x0120…"` string containing the commonware codec bytes.
`GrantDekPackage` validates the tagged 124-byte package (version 1, algorithm 1,
DEK version, then u16-BE lengths for the recipient key, encapsulated key and
ciphertext). The HPKE info stays `cbfs/grant-volume-dek/v1`; `grant_dek_aad_bytes`
binds the version and algorithm tags plus the length-prefixed recipient key.
`OwnerWrappedDek` encodes the 62-byte owner envelope; transfers and volume reads
validate present envelopes. These helpers reject the old untagged formats.

The SDK does not perform the HPKE sealing, and does not build the
`RegisterDelegation` instruction `open_volume` depends on — see
[docs/UPSTREAM_GAPS.md](docs/UPSTREAM_GAPS.md).

---

### Faucet

```python
# Testnet only — funds the given address
result = await client.faucet("0xABCD...")
```

---

### Writing actors

Use the `@actor` decorator to write an on-chain actor in plain Python. Declare a
codec on ordinary handlers so local and deployed behavior agree before and after
gate retirement: `decode="raw"` receives bytes, `decode="cbor"` decodes CBOR and
encodes non-bytes returns, and `decode="json"` handles JSON payloads. The frozen SDK
default becomes CBOR after retirement; this SDK keeps its local raw default and
requires explicit codecs when generating source. Host-invoked `init`, `on_fork`, `handle_timer`
and `@on_stream` handlers retain their raw exemption.

```python
from cowboy import actor, public, callable_by, pure, deferred, OWNER, runtime

@actor
class CounterActor:
    @callable_by(OWNER)
    def init(self, payload: bytes) -> None:
        """Called atomically by the deployer as part of the DeployActor
        transaction. sender == deployer is enforced by the protocol."""
        # Deployment has already installed the protocol owner.
        self.storage["count"] = 0

    @pure
    @public(decode="cbor")
    def get_count(self, payload) -> int:
        """Pure read exposed to any caller."""
        return self.storage.get("count") or 0

    @deferred
    @public(decode="raw")
    def increment(self, payload: bytes) -> None:
        """Deferred — may emit events or send messages."""
        count = (self.storage.get("count") or 0) + 1
        self.storage["count"] = count
        runtime.emit_event("incremented", str(count).encode())

    @callable_by(OWNER, decode="raw")
    def reset_count(self, payload: bytes) -> None:
        """Only the actor owner may call this."""
        self.storage["count"] = 0
```

Deploy it:

```python
actor_instance = CounterActor()
code = actor_instance.to_source().encode()

result = client.deploy_actor(code=code, init_handler="init")
print(result.actor_address)
```

#### Handler modes

| Decorator | Description |
|---|---|
| `@pure` | Synchronous read — no async side effects |
| `@deferred` | May call `runtime.send_message()` or produce async effects |

#### Call permissions

By default, handlers are **deny-by-default** — external callers are rejected unless a permission decorator is present. Intra-actor calls (sender == actor's own address) always bypass this check. The sender is the actor itself only for work it caused: its own timer, deferred child, runner callback or self-send. A message from another actor, including one sent from a nested call, carries that actor's address; an in-handler `self.method()` call keeps the outer sender.

| Decorator | Who can call |
|---|---|
| `@public` | Any caller |
| `@callable_by(addr, ...)` | Listed addresses only (20-byte bytes or hex string) |
| `@callable_by(OWNER)` | The actor's registered owner |
| `@callable_by(SELF)` | The actor itself (intra-actor only) |
| *(none)* | Intra-actor calls only |

The `init` handler is called atomically by the protocol as part of the `DeployActor` transaction, with `sender` set to the deployer. The entire deploy reverts if `init` raises. `init` requires an explicit permission decorator before initialization too; use `@callable_by(OWNER)` for an owner-only initializer.

#### One-shot initializers

Use `@init_handler` to guarantee a handler runs exactly once at deploy time:

```python
from cowboy import actor, init_handler, callable_by, OWNER, runtime

DEPLOYER = b"\xaa" * 20

@actor
class MyActor:
    @callable_by(OWNER)
    @init_handler(deployer=DEPLOYER)
    def init(self, payload: bytes) -> None:
        self.storage["owner"] = runtime.get_sender()
```

`@init_handler` adds a one-shot guard; declare permissions separately. Without `deployer=`, this guard does not add a sender check.

#### Local testing with `runtime`

```python
from cowboy import runtime

DEPLOYER = b"\xaa" * 20
runtime.configure(sender=DEPLOYER, actor_address=b"\xbb" * 20)
a = CounterActor()
a.init(b"")   # sender == DEPLOYER, matching production behavior
a.increment(b"")
assert a.get_count(b"") == 1

events = runtime.get_captured_events()
runtime.reset()
```

#### Test assertions

```python
from cowboy.testing import assert_event_emitted, assert_message_sent

a.increment(b"")
assert_event_emitted("incremented", b"1")
assert_message_sent(to=b"\xcc" * 20)   # payload optional
```

> **The local harness is not a PVM sandbox emulator.** `cowboy.runtime` and
> `cowboy.testing` model the host API — storage, events, messages, ownership,
> intents — and none of the PVM's determinism or sandbox restrictions. Actor code
> that passes locally can still fail on-chain: the consensus path enforces a
> stdlib whitelist plus a deny-rooted blacklist (`os`, `posix`, `time`, `random`,
> `pickle`, `datetime`, `ctypes`, `_posixsubprocess`, …), an integer-width cap,
> gas metering, static non-determinism validation, and a per-transaction
> interpreter reset. Further OS-level restrictions (network/DNS, subprocess, host
> filesystem reads, `select`/`poll`, signals, descriptor control) are staged
> behind dormant activation heights and become committed `SandboxViolation`
> failures once enabled. Check actor code with the node's own `simulate --strict`
> before deploying (a static determinism check, not the enforcing interpreter); see
> [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#design-decisions) for the
> active-vs-dormant breakdown.

---

### Key management

```python
from cowboy import Wallet, CowboyClient

# Generate a new key and persist it
wallet = Wallet.create()
print(wallet.address)
wallet.export_keyfile("key.pem")           # written with mode 0600; raises if file exists
wallet.export_keyfile("key.pem", overwrite=True)  # replace an existing key file

# CowboyClient takes key file contents as a string: COWBOY PEM or raw hex
with open("key.pem") as f:
    key = f.read()

client = CowboyClient(rpc_url, private_key=key, expected_chain_id=chain_id, expected_network=network)

# Or pass a raw hex private key string directly
client = CowboyClient(rpc_url, private_key="0xdeadbeef...", expected_chain_id=chain_id, expected_network=network)

# Wallet is for direct payload signing, not required for CowboyClient
with Wallet.from_keyfile("key.pem") as wallet:
    sig = wallet.sign(some_payload)
```

---

### Error handling

```python
from cowboy import (
    CowboyError,            # base — catch all SDK errors
    APIError,               # HTTP error from the node
    RpcError,               # non-retryable transport error
    RateLimitError,         # 429 — retries exhausted
    AccountNotFound,
    ActorNotFound,
    TokenNotFound,
    JobNotFound,
    RunnerNotFound,
    NonceTooLow,            # nonce desync — surfaced, NOT auto-retried (resubmit could double-spend)
    NonceTooHigh,           # nonce desync — client invalidates cache and auto-retries once
    TransactionFailed,      # receipt.status != "Success"
    TransactionTimeout,     # receipt not mined within timeout
    InsufficientFunds,
    PermissionDeniedError,  # caller not authorised for this handler (E1230)
)

try:
    receipt = client.get_transaction_receipt(tx_hash)
except TransactionFailed as e:
    print(e.receipt.status)
    if e.error_guidance:
        print(e.error_guidance.why)
        print(e.error_guidance.suggestion)
```

---

## Development

```bash
python -m pip install -e ".[dev]"

# Lint and format
ruff check --fix .
ruff format .

# Type check
mypy cowboy/

# Regenerate the sync client after editing the async client (see below)
python scripts/gen_sync_client.py

# Run unit tests
pytest tests/unit/

# Build the sdist, its wheel and a direct wheel from the tracked files, and check
# that each ships only cowboy/ (see docs/RELEASING.md)
python -m pip install -r .github/requirements-publish.txt
python scripts/check_dist.py --build --out /tmp/cowboy-sdk-build

# Install them into fresh environments outside the checkout and run the unit
# suite against the installed package
python scripts/check_install.py --tests /tmp/cowboy-sdk-build/dist/*

# The protocol dependency is the pinned release (needs a token with read access
# to cowboyinc/core to check devnet); --installed checks the binding in this environment
python scripts/check_protocol_pin_durable.py
python scripts/check_protocol_pin_durable.py --installed

# Run integration tests (requires a running node and .env)
pytest tests/integration/
```

### Sync client is generated

`cowboy/async_client.py` (`AsyncCowboyClient`) is the single source of truth. The
sync `cowboy/chain_client.py` (`CowboyClient`) is generated from it with
[unasync](https://github.com/python-trio/unasync) — `async`/`await` are stripped
and a few async-only identifiers are rewritten (`asyncio.sleep` → `time.sleep`,
`httpx.AsyncClient` → `httpx.Client`, `asyncio.Lock` → `threading.Lock`).

Edit the **async** client, then regenerate:

```bash
python scripts/gen_sync_client.py          # rewrite cowboy/chain_client.py
python scripts/gen_sync_client.py --check   # verify it is up to date (CI runs this)
```

Do not edit `cowboy/chain_client.py` by hand — it carries a generated-file banner
and CI fails if it has drifted from the async source.

### Git hooks

```bash
cp scripts/pre-push.sh .git/hooks/pre-push
chmod +x .git/hooks/pre-push
```

### CIP-7 Watchtower cutover

The disposable-devnet cutover removes `cowboy.stream`, the legacy
`CbssCip7*` response models, and the sync/async `get_cbss_cip7_seal_requests`
and `get_cbss_cip7_delivery` methods. Use the Watchtower clients and
`cowboy.watchtower_codec` for CIP-7. CIP-9 volume polling and its signed proxy
authentication remain available. Deploy the coordinated node and service
revisions; this change does not provide a legacy SKM migration path.

Actor authoring uses the same explicit subscription terms as the PVM:

```python
@on_stream(feed, guard={"field": "kind", "op": "eq", "value": "price"},
           max_cycles=100_000, max_cells=20_000, wake_allowance_wei=1_000_000)
def on_price(self, payload: bytes):
    ...
```

The callback receives canonical signed-envelope bytes by default. Local authoring
freezes these terms and records them during init; the exported actor subscribes
on-chain using the PVM SDK. There is no implicit spending allowance.
