Nitride.xyz
Receivers

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.

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.

receiver.py
1# receiver.py: python3 receiver.py 9000 [source-ip]
2import socket
3import struct
4import sys
5import time
6
7PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 9000
8SOURCE = sys.argv[2] if len(sys.argv) > 2 else None # optional: only accept this sender
9MAX_DATAGRAM = 1228
10COMMON_HEADER = 83
11WANT_RCVBUF = 8 * 1024 * 1024
12
13# variant (u8), slot (u64), index (u32), version (u16), fec set index (u32), from byte 64
14HEADER = struct.Struct("<BQIHI")
15TEXT = b"\t\n\r" + bytes(range(0x20, 0x7F))
16
17
18def is_text(data):
19 # True when every byte is printable ASCII, a tab or a line break
20 return len(data) > 0 and data[0] in TEXT and not data.translate(None, TEXT)
21
22
23def kind(variant):
24 if variant == 0xA5:
25 return "data" # legacy data
26 if variant == 0x5A:
27 return "code" # legacy coding
28 high = variant & 0xF0
29 if high in (0x80, 0x90, 0xB0):
30 return "data" # Merkle data
31 if high in (0x40, 0x60, 0x70):
32 return "code" # Merkle coding
33 return None
34
35
36sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
37sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, WANT_RCVBUF)
38sock.bind(("0.0.0.0", PORT))
39sock.settimeout(1.0)
40got = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
41print(f"listening on udp://0.0.0.0:{PORT} rcvbuf={got}", flush=True)
42
43buf = bytearray(MAX_DATAGRAM)
44counts = {"data": 0, "code": 0, "short": 0, "unknown": 0}
45last = None
46next_report = time.monotonic() + 1.0
47
48while True:
49 try:
50 n, (ip, _port) = sock.recvfrom_into(buf)
51 except socket.timeout:
52 n = -1
53 if n >= 0 and (SOURCE is None or ip == SOURCE):
54 if is_text(buf[:n]):
55 text = buf[:n].decode("ascii").strip()
56 print(f"text from {ip}: {text}", flush=True)
57 elif n < COMMON_HEADER:
58 counts["short"] += 1
59 else:
60 variant, slot, index, version, fec = HEADER.unpack_from(buf, 64)
61 k = kind(variant)
62 if k is None:
63 counts["unknown"] += 1
64 else:
65 counts[k] += 1
66 last = (slot, k, index, fec, version, n)
67 now = time.monotonic()
68 if now >= next_report:
69 line = " ".join(f"{name}={c}" for name, c in counts.items())
70 if last:
71 line += " last: slot={} type={} index={} fec={} version={} len={}".format(*last)
72 print(line, flush=True)
73 counts = dict.fromkeys(counts, 0)
74 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:

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, 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 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.

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:

send_test.py
1import os, socket, struct
2
3dst = ("127.0.0.1", 9000)
4s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
5s.sendto(b"verify token=abc123\n", dst)
6signature = b"\x00\xff" + os.urandom(62) # not text
7header = signature + bytes([0x96]) + struct.pack("<QIHI", 312345680, 18, 50093, 0)
8s.sendto(header + bytes(1200 - len(header)), dst)
9s.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.

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 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 uses only Go's standard library; the Node.js receiver has the same shape in JavaScript.

Next#

Sources#