Metadata-Version: 2.4
Name: pyrak
Version: 0.1.0
Summary: An async implementation of the RakNet protocol
License-Expression: Apache-2.0
License-File: LICENSE
Author: loudblow
Author-email: 145815114+loudblow@users.noreply.github.com
Requires-Python: >=3.11
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Dist: anyio (>=4.12.1,<5.0.0)
Requires-Dist: rombob (>=1.1.0,<2.0.0)
Project-URL: Source, https://github.com/loudblow/pyrak/
Description-Content-Type: text/markdown

# pyrak

An async implementation of the [RakNet](https://github.com/facebookarchive/RakNet) protocol in pure Python.
Built on [anyio](https://anyio.readthedocs.io/) (works with both asyncio and trio). A single `RakPeer` can act
as a client, a server, or both at once.

> Status: MVP. Verified against a real MCPE client (see [TODO.md](TODO.md)).

## Features

- Offline handshake and connection: `OpenConnectionRequest1/2`, `ConnectionRequest`, `NewIncomingConnection`,
  MTU negotiation, protocol version check, IP bans
- All reliability modes: `UNRELIABLE`, `UNRELIABLE_SEQUENCED`, `RELIABLE`, `RELIABLE_ORDERED`, `RELIABLE_SEQUENCED`
- Ordering channels, send priorities, splitting of large messages, ACK/NAK and retransmission
- Connected/unconnected ping (RTT, and MOTD via `UnconnectedPong`), timeouts and graceful disconnect
- Declarative wire types on [rombob](https://pypi.org/project/rombob/); your own messages are carried as `UserMessage`
- `ReliabilityLayer` has no sockets and no clock (time is passed in), so it is easy to test

Not implemented yet: congestion control, security/cookie handshake, ack receipts, NAT punchthrough.

## Installation

Requires Python 3.11+.

```bash
pip install pyrak
```

Or install the latest unreleased code straight from Git:

```bash
pip install git+https://github.com/loudblow/rombob.git@main
```


The `rombob` dependency is pulled from a GitHub release.

## Server

```python
import anyio

from pyrak import (
    RELIABLE_ORDERED,
    ConnectionLost,
    DisconnectionNotification,
    NewIncomingConnection,
    RakPeer,
    UserMessage,
)


async def main() -> None:
    async with RakPeer(max_connections=10, max_incoming_connections=10) as server:
        server.payload = "MCPE;pyrak;122;;0;10;0;hello;Creative;1;19132;19133;"  # MOTD
        await server.listen(("0.0.0.0", 19132))

        async for packet in server:  # packet.address, packet.guid, packet.message
            match packet.message:
                case NewIncomingConnection():
                    print(f"{packet.address} connected")
                case UserMessage(id=0x86, payload=data):
                    # echo back to the same client
                    await server.send(
                        packet.guid, UserMessage(0x87, data), RELIABLE_ORDERED
                    )
                case DisconnectionNotification() | ConnectionLost():
                    print(f"{packet.address} left")


anyio.run(main)
```

[`examples/mcpe_server.py`](examples/mcpe_server.py) is a server that shows up in the server list of a real
Minecraft PE client and receives its first game packet (`0xFE`):

```bash
poetry run python examples/mcpe_server.py 19132
```

## Client

```python
import anyio

from pyrak import RELIABLE_ORDERED, RakPeer, UserMessage


async def main() -> None:
    async with RakPeer(max_connections=1) as client:
        server = ("127.0.0.1", 19132)

        # unconnected ping: fetch the server's MOTD
        pong = await client.ping(server)
        print("MOTD:", pong.payload if pong else "no answer")

        session = await client.connect(server)  # waits for the handshake
        print("RTT, ms:", await client.ping(server, connected=True))

        await client.send(server, UserMessage(0x86, b"hello"), RELIABLE_ORDERED)
        # or raw bytes: the first byte is the message id
        await client.send(server, b"\x86hello", RELIABLE_ORDERED, channel=1)

        packet = await client.receive()
        print(packet.message)

        await client.disconnect(session)


anyio.run(main)
```

Connection failures (`ConnectionBannedError`, `IncompatibleProtocolVersionError`,
`NoFreeIncomingConnectionsError`, `AlreadyConnectedError`, ...) are defined in `pyrak.errors`.

## Management

```python
server.ban("1.2.3.4", duration=60_000)   # ban for 60 seconds (0 = permanent)
server.unban("1.2.3.4")
server.sessions                          # active sessions
await server.disconnect(packet.guid)     # close a session gracefully
await server.shutdown(block_duration=500)
```

## Development

```bash
make install   # set up the environment
make test      # tests with coverage
make lint      # ruff via pre-commit
make build     # build the package
```

Single test: `poetry run pytest -v -s tests/test_peer.py::test_ban`

Layout:

| Path | Purpose |
| --- | --- |
| `src/pyrak/peer.py` | `RakPeer`: async client/server, sockets, offline handshake |
| `src/pyrak/session.py` | `Session`: connection state on top of `ReliabilityLayer` |
| `src/pyrak/reliability_layer.py` | reliability, ordering, split, ACK; no sockets, no clock |
| `src/pyrak/types/` | declarative wire types on rombob |
| `docs/raknet_protocol.md` | protocol documentation |

