Canonical: https://nitride.xyz/docs/receiver/python

# Python receiver

A receiver in one file that uses only the Python standard library. It shows the verification token, counts shreds and reads the common header, which is enough to confirm delivery and to prototype.

## Run it
Save the program below as `receiver.py` and run it with the UDP port you sent us. It needs nothing from pip; we tested it on Python 3.11.

```sh file="terminal"
python3 receiver.py 9000
```

The second argument is optional: a source address. Pass it only once delivery is active and support has told you the address the stream comes from; the program then drops datagrams from any other sender. Leave it off while your destination is being verified: you will not have the address yet. Any datagram made only of printable text, such as the verification token, is printed as a `text from` line instead of being parsed.

```python file="receiver.py"
# receiver.py: python3 receiver.py 9000 [source-ip]
import socket
import struct
import sys
import time

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 9000
SOURCE = sys.argv[2] if len(sys.argv) > 2 else None  # optional: only accept this sender
MAX_DATAGRAM = 1228
COMMON_HEADER = 83
WANT_RCVBUF = 8 * 1024 * 1024

# variant (u8), slot (u64), index (u32), version (u16), fec set index (u32), from byte 64
HEADER = struct.Struct("<BQIHI")
TEXT = b"\t\n\r" + bytes(range(0x20, 0x7F))


def is_text(data):
    # True when every byte is printable ASCII, a tab or a line break
    return len(data) > 0 and data[0] in TEXT and not data.translate(None, TEXT)


def kind(variant):
    if variant == 0xA5:
        return "data"   # legacy data
    if variant == 0x5A:
        return "code"   # legacy coding
    high = variant & 0xF0
    if high in (0x80, 0x90, 0xB0):
        return "data"   # Merkle data
    if high in (0x40, 0x60, 0x70):
        return "code"   # Merkle coding
    return None


sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, WANT_RCVBUF)
sock.bind(("0.0.0.0", PORT))
sock.settimeout(1.0)
got = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
print(f"listening on udp://0.0.0.0:{PORT} rcvbuf={got}", flush=True)

buf = bytearray(MAX_DATAGRAM)
counts = {"data": 0, "code": 0, "short": 0, "unknown": 0}
last = None
next_report = time.monotonic() + 1.0

while True:
    try:
        n, (ip, _port) = sock.recvfrom_into(buf)
    except socket.timeout:
        n = -1
    if n >= 0 and (SOURCE is None or ip == SOURCE):
        if is_text(buf[:n]):
            text = buf[:n].decode("ascii").strip()
            print(f"text from {ip}: {text}", flush=True)
        elif n < COMMON_HEADER:
            counts["short"] += 1
        else:
            variant, slot, index, version, fec = HEADER.unpack_from(buf, 64)
            k = kind(variant)
            if k is None:
                counts["unknown"] += 1
            else:
                counts[k] += 1
                last = (slot, k, index, fec, version, n)
    now = time.monotonic()
    if now >= next_report:
        line = " ".join(f"{name}={c}" for name, c in counts.items())
        if last:
            line += " last: slot={} type={} index={} fec={} version={} len={}".format(*last)
        print(line, flush=True)
        counts = dict.fromkeys(counts, 0)
        next_report = now + 1.0
```

Behind static NAT, the program binds `0.0.0.0`, which also covers the private address the public one is translated to.

## What does it print?
A start line, any text datagram as it arrives, then one summary line a second:

```text file="output"
listening on udp://0.0.0.0:9000 rcvbuf=425984
text from 203.0.113.10: verify token=abc123
data=3 code=1 short=1 unknown=1 last: slot=312345680 type=data index=18 fec=0 version=50093 len=1200
```

- `data` and `code` count the data shreds and coding shreds in the last second.
- `short` counts non-text datagrams under 83 bytes, too small to hold a common header.
- `unknown` counts datagrams whose variant byte matches no known shred type.
- `last` is the header of the most recent shred: slot, type, index within the slot, FEC set index, shred version and datagram length.

Reply to support with the token from the `text from` line. Once delivery starts, expect `data` and `code` to be non-zero every second and `len` never above 1228.

`rcvbuf` is the receive buffer the kernel actually granted. The program asks for 8 MiB; Linux caps the request at `net.core.rmem_max` and then doubles it for bookkeeping, so 425984 means the limit on that machine was 212992 bytes and the request was cut down. Raise the limit as shown in [socket buffer tuning on Linux](https://nitride.xyz/docs/receiver/linux-sockets), then run the program again and check the number.

## How does it read the header?
`struct.Struct("<BQIHI")` describes 19 bytes in little-endian order with no padding: the variant (1 byte), slot (8), index (4), shred version (2) and FEC set index (4). `unpack_from(buf, 64)` reads them in place, starting right after the 64-byte signature, so bytes 64 to 82 give the 83-byte common header the [Rust receiver](https://nitride.xyz/docs/rust#the-header) also parses. The variant decides whether a shred is data or coding, legacy or Merkle. The other headers that follow, and what the variant's low bits mean, are covered in [parsing the shred header](https://nitride.xyz/docs/shreds/parse-header).

The program reads into one preallocated `bytearray` with `recvfrom_into`, so it does not create a new buffer object per datagram. The text check uses `bytes.translate`, which runs in C, and skips the full scan for most shreds because their first byte is already non-printable.

## Test it on one machine
You can check the program before any feed arrives. With the receiver running, this sender writes a token, a fake Merkle data shred (variant `0x96`, the chained data variant in use today) and a datagram too short to parse to `127.0.0.1`:

```python file="send_test.py"
import os, socket, struct

dst = ("127.0.0.1", 9000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b"verify token=abc123\n", dst)
signature = b"\x00\xff" + os.urandom(62)  # not text
header = signature + bytes([0x96]) + struct.pack("<QIHI", 312345680, 18, 50093, 0)
s.sendto(header + bytes(1200 - len(header)), dst)
s.sendto(b"\xff" * 40, dst)
```

The receiver should print the token on a `text from 127.0.0.1` line, then `data=1 short=1` with `slot=312345680 index=18 version=50093 len=1200`. If the real feed shows nothing at all, check the wire first with tcpdump, as described in the [command-line checks](https://nitride.xyz/docs/cli).

## How many packets can Python keep up with?
We have not measured a ceiling, and it depends on your CPU and Python version, so treat this program as a way to confirm delivery and prototype, then watch the drop counters before you rely on it. The costs are easy to see. Each datagram takes one `recvfrom_into` system call, and every line in the loop runs in the interpreter. Threads do not spread that work over cores, because the global interpreter lock lets one thread run Python code at a time. The kernel keeps queueing datagrams in the socket buffer while your loop catches up; once the buffer is full, new ones are dropped and counted, and with UDP they are gone. The [Linux socket and buffer guide](https://nitride.xyz/docs/receiver/linux-sockets#drops) shows how to see those drops.

Ideas that can help, in rough order of effort:

- Do less per packet. Count and copy in the receive loop, and move parsing, logging and decoding to a batch step that runs every few thousand packets or on another process.
- Raise the receive buffer, so short stalls are absorbed instead of dropped. A bigger buffer does not help if the loop is slower on average than the feed.
- Batch the system calls. Linux's `recvmmsg` reads many datagrams per call, but the standard `socket` module does not expose it, so reaching it from Python means `ctypes` or a C extension.
- Do not count on several processes with `SO_REUSEPORT` to share the load. The kernel picks the socket by hashing the sender's and receiver's addresses and ports, so a stream from one source address and port lands on one socket.
- Receive in a compiled language and give Python the parsed results. The [Go receiver](https://nitride.xyz/docs/receiver/go) uses only Go's standard library; the [Node.js receiver](https://nitride.xyz/docs/typescript) has the same shape in JavaScript.

## Next
- Track slots and indexes to find missing shreds: [detecting gaps and duplicates](https://nitride.xyz/docs/receiver/gap-detection).
- Read every field after the common header: [parsing the shred header](https://nitride.xyz/docs/shreds/parse-header).
- Back to the [docs overview](https://nitride.xyz/docs).
