# Processing

Verify signatures, deduplicate shreds, recover missing data and replay and confirm transactions

Source: https://zerocopy.sh/docs/shredstream/processing

A shred arrives before the block is replayed, and its slot can still be skipped. Before
acting on a transaction you saw in the stream, replay the reconstructed block and confirm the
transaction at the commitment you need ([Terms 6.1](https://zerocopy.sh/terms#network-1)).

## Verify the leader signature [#verify-the-leader-signature]

ZeroCopy forwards shreds without verifying them. Use a Solana Merkle shred verifier
to check the Ed25519 signature over each shred's Merkle root against the slot leader's
identity. Drop any shred that fails. The [source allowlist](/docs/shredstream/receivers#firewall)
restricts traffic to your port; it doesn't verify the signature.

## Deduplicate valid shreds [#deduplicate-valid-shreds]

Deduplicate by `(slot, index, shred type)`, where the type is data or coding, and keep the
first copy with a valid signature. An invalid copy must not block a later valid one.

Each receiver gets its own copy, so deduplicate again when you combine receivers. Keep keys
only for slots still inside your processing window.

## Recover data shreds [#recover-data-shreds]

Group data and coding shreds by `slot` and `fec_set_index`, and use the coding header's
`num_data_shreds`, `num_coding_shreds` and `position` to rebuild missing data shreds in each
FEC set. Then decode entries and transactions.

UDP does not retransmit lost packets. If you can't recover an FEC set, the
block is still incomplete.

## Replay and confirm [#replay-and-confirm]

Replay the reconstructed data and confirm transactions at the commitment your application
needs before acting. A slot number and the flag for its final shred say nothing about
commitment. Your consumer has to handle skipped slots and incomplete data.

## Receiver example [#receiver-example]

Bind a UDP socket, read the [common header](/docs/shredstream/format#common-header) and drop
repeated `(slot, index, variant)` keys while they remain in a bounded cache.

Set up the [firewall allowlist](/docs/shredstream/receivers#firewall) first. Set
`SHREDSTREAM_UDP_PORT` to the receiver's UDP port and `DEDUPE_ENTRIES` to the number of keys
to keep. A full cache evicts its oldest key, so a duplicate can appear again after eviction.

Use the [example project](/docs/reference/json-rpc#example-project) for Rust and Go. Run
`cargo run --bin shred_receiver`, `go run ./shredstream_receiver` or `bun receiver.ts`
for the version you choose.

```rust title="src/bin/shred_receiver.rs" tab="Rust" tab-group="language"
use std::{
    collections::{HashSet, VecDeque},
    env,
    io::ErrorKind,
    net::{Ipv4Addr, UdpSocket},
};

#[derive(Clone, Copy, Eq, Hash, PartialEq)]
struct Key {
    slot: u64,
    index: u32,
    variant: u8,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let port: u16 = env::var("SHREDSTREAM_UDP_PORT")?.parse()?;
    if port == 0 {
        return Err("Set SHREDSTREAM_UDP_PORT to the assigned UDP port".into());
    }
    let capacity: usize = env::var("DEDUPE_ENTRIES")?.parse()?;
    if capacity == 0 {
        return Err("Set DEDUPE_ENTRIES to a positive integer".into());
    }

    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, port))?;
    let mut seen = HashSet::with_capacity(capacity);
    let mut order = VecDeque::with_capacity(capacity);
    let mut message = [0_u8; 1229];
    loop {
        let length = match socket.recv_from(&mut message) {
            Ok((length, _)) => length,
            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
            Err(error) => return Err(error.into()),
        };
        if !(83..=1228).contains(&length) {
            continue;
        }
        let key = Key {
            slot: u64::from_le_bytes(message[65..73].try_into()?),
            index: u32::from_le_bytes(message[73..77].try_into()?),
            variant: message[64],
        };
        if seen.contains(&key) {
            continue;
        }
        if order.len() == capacity {
            if let Some(oldest) = order.pop_front() {
                seen.remove(&oldest);
            }
        }
        seen.insert(key);
        order.push_back(key);
        let version = u16::from_le_bytes(message[77..79].try_into()?);
        let fec_set_index = u32::from_le_bytes(message[79..83].try_into()?);
        println!(
            "{{\"slot\":\"{}\",\"index\":{},\"variant\":{},\"version\":{},\"fecSetIndex\":{}}}",
            key.slot, key.index, key.variant, version, fec_set_index
        );
    }
}
```

```go title="shredstream_receiver/main.go" tab="Go" tab-group="language"
package main

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

type shredKey struct {
	slot    uint64
	index   uint32
	variant byte
}

func run() error {
	port, err := strconv.ParseUint(os.Getenv("SHREDSTREAM_UDP_PORT"), 10, 16)
	if err != nil || port == 0 {
		return errors.New("Set SHREDSTREAM_UDP_PORT to the assigned UDP port")
	}
	capacity, err := strconv.Atoi(os.Getenv("DEDUPE_ENTRIES"))
	if err != nil || capacity < 1 {
		return errors.New("Set DEDUPE_ENTRIES to a positive integer")
	}
	socket, err := net.ListenUDP("udp4", &net.UDPAddr{Port: int(port)})
	if err != nil {
		return err
	}
	defer socket.Close()

	seen := make(map[shredKey]struct{}, capacity)
	order := make([]shredKey, capacity)
	head, size := 0, 0
	message := make([]byte, 1229)
	for {
		length, _, err := socket.ReadFromUDP(message)
		if err != nil {
			return err
		}
		if length < 83 || length > 1228 {
			continue
		}
		key := shredKey{
			slot:    binary.LittleEndian.Uint64(message[65:73]),
			index:   binary.LittleEndian.Uint32(message[73:77]),
			variant: message[64],
		}
		if _, exists := seen[key]; exists {
			continue
		}
		if size == capacity {
			delete(seen, order[head])
			order[head] = key
			head = (head + 1) % capacity
		} else {
			order[(head+size)%capacity] = key
			size++
		}
		seen[key] = struct{}{}
		fmt.Printf("{\"slot\":\"%d\",\"index\":%d,\"variant\":%d,\"version\":%d,\"fecSetIndex\":%d}\n",
			key.slot, key.index, key.variant,
			binary.LittleEndian.Uint16(message[77:79]),
			binary.LittleEndian.Uint32(message[79:83]))
	}
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```ts title="receiver.ts" tab="TypeScript" tab-group="language"
import { createSocket } from 'node:dgram'

const port = Number(process.env.SHREDSTREAM_UDP_PORT)
const capacity = Number(process.env.DEDUPE_ENTRIES)
if (!Number.isInteger(port) || port < 1 || port > 65535) {
  throw new Error('Set SHREDSTREAM_UDP_PORT to the assigned UDP port')
}
if (!Number.isSafeInteger(capacity) || capacity < 1) {
  throw new Error('Set DEDUPE_ENTRIES to a positive integer')
}

const seen = new Set<string>()
const socket = createSocket('udp4')
socket.on('error', (error) => {
  console.error(error)
  socket.close()
  process.exitCode = 1
})
socket.on('message', (message) => {
  if (message.length < 83 || message.length > 1228) return
  const header = {
    signature: message.subarray(0, 64),
    variant: message[64],
    slot: message.readBigUInt64LE(65),
    index: message.readUInt32LE(73),
    version: message.readUInt16LE(77),
    fecSetIndex: message.readUInt32LE(79),
  }
  const key = `${header.slot}:${header.index}:${header.variant}`
  if (seen.has(key)) return
  if (seen.size === capacity) {
    const oldest = seen.values().next().value
    if (oldest !== undefined) seen.delete(oldest)
  }
  seen.add(key)
  console.log({
    slot: header.slot.toString(),
    index: header.index,
    variant: header.variant,
    version: header.version,
    fecSetIndex: header.fecSetIndex,
  })
})
socket.bind(port)
```

The example only inspects headers. It does not verify signatures, check the Merkle body or the
shred version, recover FEC sets, replay blocks or confirm transactions. Its cache holds
unverified headers, so do not use it to pick a trusted copy. A production consumer verifies
first, derives the shred type from the variant and keeps the first valid
`(slot, index, type)` copy.
