Nitride.xyz
Receivers

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.

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.

receiver.go
1// receiver.go: go run receiver.go 9000 [source-ip]
2package main
3
4import (
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "net"
9 "net/netip"
10 "os"
11 "strconv"
12 "strings"
13 "time"
14)
15
16const (
17 maxDatagram = 1228
18 commonHeader = 83
19 wantRcvbuf = 8 << 20
20)
21
22type header struct {
23 slot uint64
24 kind string
25 index uint32
26 fec uint32
27 version uint16
28 length int
29}
30
31func isText(b []byte) bool {
32 if len(b) == 0 {
33 return false
34 }
35 for _, c := range b {
36 if c != '\t' && c != '\n' && c != '\r' && (c < 0x20 || c > 0x7e) {
37 return false
38 }
39 }
40 return true
41}
42
43func kind(variant byte) string {
44 switch variant {
45 case 0xa5:
46 return "data" // legacy data
47 case 0x5a:
48 return "code" // legacy coding
49 }
50 switch variant & 0xf0 {
51 case 0x80, 0x90, 0xb0:
52 return "data" // Merkle data
53 case 0x40, 0x60, 0x70:
54 return "code" // Merkle coding
55 }
56 return ""
57}
58
59func fail(err error) {
60 fmt.Fprintln(os.Stderr, err)
61 os.Exit(1)
62}
63
64func main() {
65 port := 9000
66 if len(os.Args) > 1 {
67 p, err := strconv.Atoi(os.Args[1])
68 if err != nil {
69 fail(err)
70 }
71 port = p
72 }
73 var source netip.Addr // zero value: accept every sender
74 if len(os.Args) > 2 {
75 a, err := netip.ParseAddr(os.Args[2])
76 if err != nil {
77 fail(err)
78 }
79 source = a
80 }
81
82 conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: port})
83 if err != nil {
84 fail(err)
85 }
86 defer conn.Close()
87 if err := conn.SetReadBuffer(wantRcvbuf); err != nil {
88 fail(err)
89 }
90 fmt.Printf("listening on udp://0.0.0.0:%d\n", port)
91
92 buf := make([]byte, maxDatagram)
93 var data, code, short, unknown int
94 var last *header
95 next := time.Now().Add(time.Second)
96 conn.SetReadDeadline(next)
97
98 for {
99 n, from, err := conn.ReadFromUDPAddrPort(buf)
100 if err != nil && !errors.Is(err, os.ErrDeadlineExceeded) {
101 fail(err)
102 }
103 ip := from.Addr().Unmap()
104 switch {
105 case err != nil, source.IsValid() && ip != source:
106 // deadline reached, or a sender we were told to ignore
107 case isText(buf[:n]):
108 fmt.Printf("text from %s: %s\n", ip, strings.TrimSpace(string(buf[:n])))
109 case n < commonHeader:
110 short++
111 default:
112 k := kind(buf[64])
113 if k == "" {
114 unknown++
115 break
116 }
117 if k == "data" {
118 data++
119 } else {
120 code++
121 }
122 last = &header{
123 slot: binary.LittleEndian.Uint64(buf[65:73]),
124 kind: k,
125 index: binary.LittleEndian.Uint32(buf[73:77]),
126 version: binary.LittleEndian.Uint16(buf[77:79]),
127 fec: binary.LittleEndian.Uint32(buf[79:83]),
128 length: n,
129 }
130 }
131
132 if now := time.Now(); !now.Before(next) {
133 line := fmt.Sprintf("data=%d code=%d short=%d unknown=%d", data, code, short, unknown)
134 if last != nil {
135 line += fmt.Sprintf(" last: slot=%d type=%s index=%d fec=%d version=%d len=%d",
136 last.slot, last.kind, last.index, last.fec, last.version, last.length)
137 }
138 fmt.Println(line)
139 data, code, short, unknown = 0, 0, 0, 0
140 next = now.Add(time.Second)
141 conn.SetReadDeadline(next)
142 }
143 }
144}

What does it print?#

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 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 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 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:

terminal
ss -ulmn 'sport = :9000'
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 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.

For the rest of the setup, start from the docs overview.

Sources#