Canonical: https://nitride.xyz/docs/rust

# Rust receiver

A minimal receiver that uses only the Rust standard library. It binds your UDP port, accepts the stream and prints each shred's common header. Use it to commission delivery before you build a production receiver.

## Build and run
Save the program as `receiver.rs`. It takes the bind address and, optionally, a source address: once delivery is active, you can pass the one support gives you, and it then ignores datagrams from anywhere else. Leave it off while you verify your destination, because support only gives you that address once delivery is active. A datagram that is plain text, such as the verification token, is printed as a `text from` line instead of being parsed.

```rust file="receiver.rs"
use std::{env, io::{self, Write}, net::{Ipv4Addr, SocketAddr, UdpSocket}};

const MAX_DATAGRAM: usize = 1228;
const COMMON_HEADER: usize = 83;

fn u16le(b: &[u8]) -> u16 { u16::from_le_bytes(b.try_into().unwrap()) }
fn u32le(b: &[u8]) -> u32 { u32::from_le_bytes(b.try_into().unwrap()) }
fn u64le(b: &[u8]) -> u64 { u64::from_le_bytes(b.try_into().unwrap()) }

fn is_text(b: &[u8]) -> bool {
    !b.is_empty() && b.iter().all(|&c| c == b'\t' || c == b'\n' || c == b'\r' || (0x20..0x7f).contains(&c))
}

fn shred_kind(variant: u8) -> Option<&'static str> {
    match variant {
        0xa5 => Some("legacy-data"),
        0x5a => Some("legacy-code"),
        v => match v & 0xf0 {
            0x80 | 0x90 | 0xb0 => Some("merkle-data"),
            0x40 | 0x60 | 0x70 => Some("merkle-code"),
            _ => None,
        },
    }
}

fn main() -> io::Result<()> {
    // usage: ./receiver 0.0.0.0:9000 <source-ip>
    let bind = env::args().nth(1).unwrap_or_else(|| "0.0.0.0:9000".into());
    let source: Option<Ipv4Addr> = env::args().nth(2).and_then(|s| s.parse().ok());
    let socket = UdpSocket::bind(&bind)?;
    eprintln!("listening on {bind}");

    let mut packet = [0u8; MAX_DATAGRAM];
    let mut out = io::stdout().lock();
    loop {
        let (len, peer) = socket.recv_from(&mut packet)?;
        if let (Some(want), SocketAddr::V4(v4)) = (source, peer) {
            if *v4.ip() != want { continue; }
        }
        if is_text(&packet[..len]) {
            writeln!(out, "text from {}: {}", peer.ip(), String::from_utf8_lossy(&packet[..len]).trim())?;
            continue;
        }
        if len < COMMON_HEADER {
            eprintln!("short datagram: len={len}");
            continue;
        }
        let variant = packet[64];
        let Some(kind) = shred_kind(variant) else {
            eprintln!("unknown variant: {variant:#04x}");
            continue;
        };
        let slot = u64le(&packet[65..73]);
        let index = u32le(&packet[73..77]);
        let version = u16le(&packet[77..79]);
        let fec = u32le(&packet[79..83]);
        writeln!(out, "slot={slot} type={kind} index={index} fec={fec} version={version} len={len}")?;
    }
}
```

```sh file="terminal"
rustc --edition 2021 -O receiver.rs
./receiver 0.0.0.0:9000
```

Use the UDP port you sent us. Behind static NAT, bind the private address or `0.0.0.0`, not the public translated address.

## The common header
| Bytes | Field |
| --- | --- |
| 0 to 63 | Leader’s signature |
| 64 | Variant: data or coding, legacy or Merkle |
| 65 to 72 | Slot (u64, little-endian) |
| 73 to 76 | Index within the slot (u32) |
| 77 to 78 | Shred version (u16) |
| 79 to 82 | FEC set index (u32) |

## Check the output
Expect slot numbers to climb most of the time. They can step back now and then: UDP delivers out of order, and a fork can put two blocks in play for one slot. Data shreds and coding shreds keep separate index counters. The `fec` value repeats across many lines because it names the erasure set each shred belongs to. Nothing should arrive longer than 1,228 bytes.

If every line says `unknown variant`, write the values down and check them against the Agave release running on the network, rather than guessing a mask.

## What it does not do
The program does not verify the leader signature or the Merkle proof, recover missing shreds, or detect kernel receive-buffer overflow. It also writes a line per packet inside the receive loop, which can itself cause drops when the terminal is slow.

> [!TIP]
> Use it to confirm delivery, then stop it. Don’t run it in production.

## Towards production
- Parse shreds with the ledger crate from the Agave release the network runs, rather than fixed offsets.
- Verify each shred’s signature against the scheduled leader for its slot.
- Group by `(slot, fec_set_index)`, recover missing data shreds, order them and deserialise entries.
- Keep the receive thread doing nothing but receiving: raise `SO_RCVBUF`, read in batches with `recvmmsg`, and hand packets to other threads through a bounded queue.

Socket tuning is covered in [the UDP wire contract](https://nitride.xyz/docs/udp#tuning). If you have not received a packet yet, start with the [quickstart](https://nitride.xyz/docs).
