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

# Go receiver

One file, standard library only. It binds your UDP port, prints the verification token, counts shreds and reads each shred's common header with encoding/binary.

## Build and run
Save the program as `receiver.go`, then build it and run it with the UDP port you sent us. It needs Go 1.18 or later, for `net/netip`, and no modules.

```sh file="terminal"
go build -o receiver receiver.go
./receiver 9000
```

A second argument, a source address, is optional. Add it only once delivery is active and support has given you the address the stream is sent from; datagrams from any other sender are then ignored. While your destination is being verified, leave it off, since support has not given you the address yet. A datagram that is all printable text, such as the verification token, is printed as a `text from` line and not parsed.

```go file="receiver.go"
// receiver.go: go run receiver.go 9000 [source-ip]
package main

import (
	"encoding/binary"
	"errors"
	"fmt"
	"net"
	"net/netip"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	maxDatagram  = 1228
	commonHeader = 83
	wantRcvbuf   = 8 << 20
)

type header struct {
	slot    uint64
	kind    string
	index   uint32
	fec     uint32
	version uint16
	length  int
}

func isText(b []byte) bool {
	if len(b) == 0 {
		return false
	}
	for _, c := range b {
		if c != '\t' && c != '\n' && c != '\r' && (c < 0x20 || c > 0x7e) {
			return false
		}
	}
	return true
}

func kind(variant byte) string {
	switch variant {
	case 0xa5:
		return "data" // legacy data
	case 0x5a:
		return "code" // legacy coding
	}
	switch variant & 0xf0 {
	case 0x80, 0x90, 0xb0:
		return "data" // Merkle data
	case 0x40, 0x60, 0x70:
		return "code" // Merkle coding
	}
	return ""
}

func fail(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

func main() {
	port := 9000
	if len(os.Args) > 1 {
		p, err := strconv.Atoi(os.Args[1])
		if err != nil {
			fail(err)
		}
		port = p
	}
	var source netip.Addr // zero value: accept every sender
	if len(os.Args) > 2 {
		a, err := netip.ParseAddr(os.Args[2])
		if err != nil {
			fail(err)
		}
		source = a
	}

	conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: port})
	if err != nil {
		fail(err)
	}
	defer conn.Close()
	if err := conn.SetReadBuffer(wantRcvbuf); err != nil {
		fail(err)
	}
	fmt.Printf("listening on udp://0.0.0.0:%d\n", port)

	buf := make([]byte, maxDatagram)
	var data, code, short, unknown int
	var last *header
	next := time.Now().Add(time.Second)
	conn.SetReadDeadline(next)

	for {
		n, from, err := conn.ReadFromUDPAddrPort(buf)
		if err != nil && !errors.Is(err, os.ErrDeadlineExceeded) {
			fail(err)
		}
		ip := from.Addr().Unmap()
		switch {
		case err != nil, source.IsValid() && ip != source:
			// deadline reached, or a sender we were told to ignore
		case isText(buf[:n]):
			fmt.Printf("text from %s: %s\n", ip, strings.TrimSpace(string(buf[:n])))
		case n < commonHeader:
			short++
		default:
			k := kind(buf[64])
			if k == "" {
				unknown++
				break
			}
			if k == "data" {
				data++
			} else {
				code++
			}
			last = &header{
				slot:    binary.LittleEndian.Uint64(buf[65:73]),
				kind:    k,
				index:   binary.LittleEndian.Uint32(buf[73:77]),
				version: binary.LittleEndian.Uint16(buf[77:79]),
				fec:     binary.LittleEndian.Uint32(buf[79:83]),
				length:  n,
			}
		}

		if now := time.Now(); !now.Before(next) {
			line := fmt.Sprintf("data=%d code=%d short=%d unknown=%d", data, code, short, unknown)
			if last != nil {
				line += fmt.Sprintf(" last: slot=%d type=%s index=%d fec=%d version=%d len=%d",
					last.slot, last.kind, last.index, last.fec, last.version, last.length)
			}
			fmt.Println(line)
			data, code, short, unknown = 0, 0, 0, 0
			next = now.Add(time.Second)
			conn.SetReadDeadline(next)
		}
	}
}
```

## What does it print?
```text file="output"
listening on udp://0.0.0.0:9000
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
```

The token line comes first: send the token back to support. After that, one line a second counts data shreds, coding shreds, datagrams too short for a header (`short`) and datagrams with a variant byte it does not recognise (`unknown`), then shows the most recent shred's slot, type, index, FEC set index, shred version and length. The output matches the [Python receiver](https://nitride.xyz/docs/receiver/python) line for line, so you can compare the two on one server.

## How does it read the header?
The first 64 bytes of a shred are the leader's signature. Byte 64 is the variant, and `kind` maps it to data or coding the same way the [Rust receiver](https://nitride.xyz/docs/rust) does. The next 18 bytes are read with `binary.LittleEndian`: slot from 65 to 72, index from 73 to 76, shred version from 77 to 78 and FEC set index from 79 to 82. The headers after these 83 bytes differ between data and coding shreds; [parsing the shred header](https://nitride.xyz/docs/shreds/parse-header) goes through them.

`ReadFromUDPAddrPort` returns the sender as a `netip.AddrPort`. Its address is a comparable value, so the source check is a plain `!=`. On a socket bound to an unspecified address, the Go docs say the address can come back IPv4-mapped, which is why the program calls `Unmap` before comparing.

## Why a read deadline?
The receive call blocks until a datagram arrives, so on an idle port the program would never print its summary. A deadline set to the next report time makes the read return `os.ErrDeadlineExceeded` instead, the summary prints, and the deadline moves on a second. The deadline is set once a second, not once per packet.

## Is SetReadBuffer enough?
`SetReadBuffer` sets `SO_RCVBUF` on the socket. Linux quietly caps the value at `net.core.rmem_max` and returns no error, so the call succeeding does not mean you got 8 MiB. Check what the kernel granted with `ss`; the `rb` field is the receive buffer in bytes:

```sh file="terminal"
ss -ulmn 'sport = :9000'
```

```text file="output"
UNCONN 0      0            0.0.0.0:9000      0.0.0.0:*
	 skmem:(r0,rb425984,t0,tb212992,f0,w0,o0,bl0,d0)
```

An `rb` of 425984 is a cap of 212992 bytes, doubled by the kernel. Raise `net.core.rmem_max`, restart the receiver and check again; [Linux sockets and buffers](https://nitride.xyz/docs/receiver/linux-sockets#raise-the-limit) has the commands. The `d` field in the same line counts datagrams the socket dropped.

## Towards production
- Keep the receive goroutine to receiving. Copy each datagram into a buffer from a pool and pass it on a buffered channel to workers, because the next read overwrites `buf`.
- Decide what happens when workers fall behind. If the channel is full, either drop and count in your own code, or let the kernel buffer fill and drop there. Either way, make the drops visible.
- The standard library reads one datagram per system call. For batches, `golang.org/x/net/ipv4` has `PacketConn.ReadBatch`, which its docs say is optimized on Linux. That module is outside the standard library, so this page does not use it.
- Watch for missing shreds by slot and index, as in [detecting gaps and duplicates](https://nitride.xyz/docs/receiver/gap-detection).

For the rest of the setup, start from the [docs overview](https://nitride.xyz/docs).
