Skip to main content

zre — Pure Python ZRE (RFC 36) Implementation

PyPI Python versions License: MIT CI

ZRE implements the ZeroMQ Realtime Exchange Protocol (RFC 36) for peer-to-peer discovery and messaging. No brokers, no servers — peers find each other on the LAN with zero configuration, or dial each other directly across subnets by address.

Features

Feature Description
Zero-configuration No central servers, brokers, or admin
Peer discovery Automatic via UDP broadcast beacons (port 5670), direct dial via connect_peer(host, port) where broadcasts can't reach, or UDP-free gossip hub (gossip_bind / gossip_connect, python3 -m zre.gossip)
Group messaging Join/leave named groups, multicast via unicast; per-group leader elections with LEADER events
Transport security Optional CurveZMQ + ZAP (set_zcert, set_zap_domain) with v3 beacons
Direct messaging Whisper to individual peers
Stable peer ids Optional fixed UUID (set_uuid) so peer_hex survives restarts
Heartbeating Automatic detection of peers going evasive, silent, or dead
Language neutral Speaks RFC 36 on the wire — interoperates with any compliant peer
Pure Python Single asyncio event loop, no threads, no C extensions

Wire conformance details: docs/PROTOCOL.md. Interop with the C implementation: docs/LIBZYRE_INTEROP.md.

Installation

Requires Python 3.10+ on Linux or macOS.

pip install zre

With optional dependencies:

Extra Provides Install
secure cryptography, used by examples/secure_chat.py pip install "zre[secure]"
dev pytest, pytest-asyncio, ruff pip install "zre[dev]"

From a checkout of this repository:

git clone https://github.com/pitch-cardinal-coding/zre.git
cd zre
python3 -m venv .venv && source .venv/bin/activate
pip install -e .          # runtime
pip install -e .[dev]     # + development tools

requirements.txt carries pinned versions of the dependency stack for reproducible environments; it is not needed for a normal install.

Quick Start

import asyncio
from zre import ZreNode


async def main():
    node = ZreNode("my-app")
    node.set_port(5670)  # override beacon port to isolate clusters
    await node.start()
    await node.join("CHAT")

    # Must run beacon/ROUTER loop concurrently with events
    run_task = asyncio.create_task(node.run())

    async for event in node.events():
        print(event)
        if event["type"] == "ENTER":
            await node.shout("CHAT", b"Hello!")

    run_task.cancel()
    await node.stop()


asyncio.run(main())

API Overview

node = ZreNode("my-node")  # name optional (random otherwise)

# Headers shared with peers during discovery (HELLO)
node.set_header("X-ROLE", "worker")

# Configuration — all of it BEFORE start()
node.set_port(5670)  # UDP beacon port (cluster isolation)
node.set_interface("eth0")  # pin NIC (or an IP) on multi-homed hosts
node.set_interval(1000)  # beacon interval, ms
node.set_evasive_timeout(5000)  # peer quiet -> EVASIVE probes, ms
node.set_silent_timeout(5000)  # alias of the evasive timeout
node.set_expired_timeout(30000)  # peer silent -> removed, ms
node.set_beacon_peer_port(9999)  # fixed TCP ROUTER port (default ephemeral)
node.set_advertised_endpoint("tcp://203.0.113.50:9999")  # NAT setups
node.set_uuid("32-char-hex-or-16-bytes")  # stable peer id (default random)
node.set_ipv6(True)  # enable IPv6 on TCP sockets (beacon stays IPv4)
node.set_zcert(public_key, secret_key)  # CurveZMQ transport crypto (32 B / z85)
node.set_zap_domain("global")  # ZAP domain for Curve clients
node.set_contest_in_group("WORKERS")  # opt into group-leader elections
node.set_verbose()  # wire-level logging

# Duplicate-uuid guard: if another node with the same stable uuid is live
# on the network, run() raises zre.UUIDCollisionError and the node shuts
# itself down (stable uuids must be unique among concurrently running peers).

await node.start()  # bind ROUTER + beacon socket
run_task = asyncio.create_task(node.run())  # REQUIRED: drive the node

await node.join("CHAT")  # / leave(group)
await node.shout("CHAT", b"hi all")  # group message
await node.shouts("CHAT", "hi all")  # same, str convenience
await node.whisper(peer_hex, b"hi")  # direct message (peer id = UUID hex)
await node.whispers(peer_hex, "hi")  # same, str convenience
await node.connect_peer("10.0.0.7", 9999)  # direct dial, no beacons
await node.connect_peer("10.0.0.7", 9999, public_key=peer_key)  # Curve dial

node.gossip_bind("tcp://0.0.0.0:15671")  # host a discovery hub (no beacons)
node.gossip_connect("tcp://10.0.0.7:15671")  # join one (UDP-free mesh)
# or: python3 -m zre.gossip --port 15671  (standalone hub)

async for event in node.events():  # or: event = await node.recv(timeout=1.0)
    ...
node.peers()  # list of peer UUID hexes
node.own_groups()  # groups this node joined
node.peers_by_group("CHAT")  # peer ids in a group
node.peer_groups()  # all groups known through peers
node.peer_address(peer_hex)  # peer endpoint ("" when unknown)
node.peer_header_value(peer_hex, "X-ROLE")  # one peer header (None when missing)

run_task.cancel()
await node.stop()

Event types

Event Description Fields
ENTER New peer discovered peer_id, peer_name, address
EXIT Peer left network peer_id, peer_name
JOIN / LEAVE Peer joined/left group peer_id, peer_name, group
SHOUT Group message peer_id, peer_name, group, payload
WHISPER Direct message peer_id, peer_name, payload
EVASIVE Peer went quiet (probing started; emitted once per quiet episode, at most every 20 s — an idle-but-alive peer answers the probe and stays) peer_id, peer_name
LEADER Group election converged (lowest contestant id wins; lone contestant leads itself) peer_id, peer_name, group
COLLISION Another node with this node's stable uuid is live on the network; the node emits this, then stops itself detail

EXIT is the only reliable "peer is gone" signal. COLLISION is emitted before run() raises zre.UUIDCollisionError, and events() keeps draining until the queue is empty so late consumers still receive it.

Examples

The examples/ directory contains 16 runnable scenario demos — chat, encrypted chat, file transfer, media streaming, sensor networks, task queues, service discovery, distributed locks, game sync, benchmarks, and more.

Start with the examples testing guide — a step-by-step, zero-assumptions walkthrough: install, pick a free port, run each example in order with exact commands and the output you should see, plus two-machine and cross-subnet (WAN) recipes and a troubleshooting table.

Direct connection across subnets (beacons cannot cross routers):

await node.connect_peer("192.168.122.87", 19870)  # TCP + HELLO, no beacon

The far side pins a stable port with set_beacon_peer_port(19870); behind NAT, advertise your public address with set_advertised_endpoint("tcp://PUBLIC_IP:19870"). After the HELLO exchange the dialed peer is indistinguishable from a beacon-discovered one. See examples/wan_direct.py for a runnable both-directions demo and docs/PROTOCOL.md for the handshake rules (no phantom peers, duplicate-HELLO storm guard).

Testing

python3 -m pytest tests/ -v        # protocol + feature coverage (105 tests)
make test                          # same, via Makefile
make ci                            # format + lint + tests

On machines where another ZRE-speaking service already owns UDP 5670, isolate the suite:

ZRE_TEST_PORT=24190 python3 -m pytest tests/ -q

Cross-network smoke test

scripts/cross_smoke.py runs every example between two machines, in both role directions, verifying chat delivery, file/media sha256, and WAN dialing — the same matrix used to validate the examples:

# on machine A (local), against machine B over ssh:
python3 scripts/cross_smoke.py --peer user@B --password SECRET \
    --remote-dir '~/checkout' --host-iface virbr0 \
    --first-addr 192.168.122.1      # A's IP as seen by B (enables wan_direct)

Select subsets with --groups lan,coord,data,wan or -k name; use --base-port to pick free UDP ports (15 consecutive + 1 TCP at +200 are checked at preflight). Or via make:

make cross-smoke PEER=user@B PASSWORD=SECRET HOST_IFACE=virbr0 FIRST_ADDR=192.168.122.1

Documentation

Document Contents
examples/README.md Step-by-step guide to every example (start here)
docs/PROTOCOL.md RFC 36 wire format, beacon/message layouts, conformance notes
docs/LIBZYRE_INTEROP.md Building libzyre, C and Python peers, LAN/WAN/Curve how-to
docs/ARCHITECTURE.md Event-loop design and internal structure
docs/SCENARIOS.md Use-case catalog mapped to examples
docs/BENCHMARKS.md Performance results, receipts, methodology
docs/MONITORING.md py-spy/memray profiling, lint/CI, tmux demos
scripts/ndk/GETTING-STARTED.md Fresh-environment walkthrough: Android toolchain, Curve keys, app build/run/deploy, mesh trials, leak proof
docs/SESSION-VALIDATION.md Measured validation record: Python + C (JNI) zero-leak verdicts, release build, key-rotation evidence

License

MIT — see docs/LICENSE. For contributing, changelog, and security reporting, see docs/CONTRIBUTING.md, docs/CHANGELOG.md, and docs/SECURITY.md.

References


Status: Production-ready — 105 tests passing, all 18 examples verified live on two machines across subnets in both directions (scripts/cross_smoke.py, 36/36).

Metadata

Release files for zre 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for zre 0.3.0
File Size Uploaded Provenance Actions
zre-0.3.0.tar.gz 58.4 kB With provenance Details for zre-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for zre 0.3.0
File Interpreter ABI Platform Actions
zre-0.3.0-py3-none-any.whl Python 3 none any Details for zre-0.3.0-py3-none-any.whl

Total release size: 92.1 kB

Release files / zre-0.3.0.tar.gz

Download URL zre-0.3.0.tar.gz
Size 58.4 kB
Tags Source
SHA-256 checksum
How to use checksums
29addfa3de09440e4f3a91c27548947d9c4a1cf3f279fadcd92e56addc8af4fd
BLAKE2b-256 checksum
How to use checksums
58f7dd67a8b81d7ab865f7309f2fe1d166bdcf4c6a64b153383d1b450c411f0a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

Release files / zre-0.3.0-py3-none-any.whl

Download URL zre-0.3.0-py3-none-any.whl
Size 33.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7c95b59739844d2a1d62e7a90019364c37accbb0dcd75d1cf441d2f6296952d1
BLAKE2b-256 checksum
How to use checksums
98467e5210f6acafb4d64206c130c4fba958aeae26af0e819a95e4cd5b36ba5e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

Security for zre 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for zre-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page