Canonical: https://nitride.xyz/docs/shreds/recover-and-decode

# Recovering and decoding: FEC, entries, transactions

Raw shreds become transactions in six steps: group, recover, order, deshred, deserialize and extract. This page walks through each one and points to the Agave crates that do it in production.

Start with parsed shreds: each datagram's slot, index, FEC set index, type and, for data shreds, the flags byte and entry bytes. [Parsing the shred header](https://nitride.xyz/docs/shreds/parse-header) gives the offsets. From there, six steps turn shreds into transactions. The byte layouts below match the Agave source as read on 2026-11-17, and this page is part of the [Nitride.xyz docs](https://nitride.xyz/docs).

## Step 1: group by FEC set
Put each shred in a bucket keyed by `(slot, fec_set_index)`. Every shred of one erasure batch, data and coding alike, carries the same FEC set index: the index of the batch's first data shred. Agave calls this key `ErasureSetId`. In the current source each batch has 32 data shreds and 32 coding shreds, so a slot's batches start at data index 0, 32, 64 and so on. Background on how batches are built is in [FEC sets and erasure coding](https://nitride.xyz/learn/fec-sets).

## Step 2: recover missing data shreds
A batch can be rebuilt once any 32 of its 64 shreds are present. Agave uses the `reed-solomon-erasure` crate over GF(2^8), configured with 32 data shards and 32 parity shards. Each shred maps to one shard:

| Shred | Shard number | Shard bytes |
| --- | --- | --- |
| Data | `index - fec_set_index` (0 to 31) | from byte 64 to the end of the body |
| Coding | `num_data_shreds + position` (32 to 63) | from byte 89 to the end of the body |

Both ranges are the same length: 987 bytes, or 923 for a resigned batch. The data shard covers the data shred's headers as well as its body, so recovery rebuilds the headers too. It does not cover the signature or the Merkle trailer. A rebuilt data shred takes the leader signature shared by the whole batch; Agave then rebuilds the Merkle tree and checks the recovered shreds against the root before trusting them.

In Agave 4.4.1, the only public entry point for recovery in `solana-ledger` (`shred::filter::ShredRecoveryContext::recover`) needs a validator `Bank` and a retransmit channel, so outside a validator call `reed-solomon-erasure` yourself with the shard layout above. If a batch stays below 32 shreds, its missing data is gone for your receiver: a raw UDP feed has no retransmission. [Detecting gaps and duplicates](https://nitride.xyz/docs/receiver/gap-detection) shows how to count those batches.

## Step 3: order and find complete runs
Sort the slot's data shreds by index. Two flags in byte 85 mark the boundaries:

- `0x40`, `DATA_COMPLETE_SHRED`: the last shred of a run whose bytes deserialize on their own;
- `0xC0`, `LAST_SHRED_IN_SLOT`: the slot's last data shred. It sets the `0x40` bit as well.

A run starts at index 0, or just after the previous `DATA_COMPLETE_SHRED`, and ends at the next one. A run can span several FEC sets, so cut runs by these flags, after recovery, rather than by batch boundaries. You can decode a run as soon as every index in it is present, without waiting for the slot to finish.

## Step 4: deshred the payload
Concatenate the entry bytes of each shred in the run, in index order. A data shred's entry bytes are `payload[88:size]`, where `size` is the u16 at bytes 86 to 87. Agave's `Shredder::deshred` does exactly this and refuses the run if the indices are not consecutive or the last shred lacks `DATA_COMPLETE_SHRED`.

## Step 5: deserialize entries
Each run's bytes start with a u64 count. When the count is above zero, the bytes are an entry batch laid out as bincode lays out a `Vec<Entry>`: the count, then each entry. An entry is:

| Field | Encoding |
| --- | --- |
| `num_hashes` | u64 |
| `hash` | 32 bytes |
| `transactions` | u64 count, then each transaction |

When the count is zero, the current source reads the run as a block marker, a newer kind of block component, rather than entries. A deshredded Alpenglow block is therefore a sequence of block components: a header marker, entry batches and a footer marker, not a bare list of entries, and its last entry batch ends with a single tick. Skip those unless you need them. Agave reads both forms with the `wincode` crate, which reads bincode's layout. What an entry is, and why it sits between shreds and transactions, is covered in [Solana entries](https://nitride.xyz/learn/entries).

## Step 6: extract transactions
Transactions are packed back to back with no length prefix, so you must parse each one to find where the next begins. Three formats appear on mainnet:

- **Legacy**: a compact-u16 signature count, the signatures (64 bytes each), then the message: a 3-byte header, account keys, a recent blockhash and instructions.
- **v0**: the same, with a `0x80` byte before the message header and address table lookups after the instructions.
- **v1**: the message comes first, starting with `0x81`, and the signatures follow it.

The first signature is the transaction's ID. A block we fetched from public RPC on 2026-11-17 held all three formats.

## A decoder in Python
This covers steps 3 to 6 with the standard library. It assumes all shreds of a run are present (after recovery, if you need it) and does not verify signatures.

```python file="decode.py"
import struct

B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def b58(raw):
    n, out = int.from_bytes(raw, "big"), ""
    while n:
        n, r = divmod(n, 58)
        out = B58[r] + out
    return "1" * (len(raw) - len(raw.lstrip(b"\0"))) + out

def deshred(data_shreds, start=0):
    """data_shreds: {index: parsed data shred} for one slot. Yields each
    completed payload, from `start` up to a shred flagged DATA_COMPLETE."""
    chunk, i = [], start
    while i in data_shreds:
        shred = data_shreds[i]
        chunk.append(shred["data"])
        i += 1
        if shred["data_complete"]:
            yield b"".join(chunk)
            chunk = []
            if shred["last_in_slot"]:
                return

def cu16(b, p):                      # compact-u16 ("short_vec") length
    v = 0
    for k in range(3):
        v |= (b[p + k] & 0x7F) << (7 * k)
        if b[p + k] < 0x80:
            return v, p + k + 1
    raise ValueError("bad compact-u16")

def skip_vec(b, p):                  # compact-u16 length, then that many bytes
    n, p = cu16(b, p)
    return p + n

def read_transaction(b, p):
    """Returns (end offset, first signature) of the transaction at p."""
    if b[p] & 0x80:                  # v1: message first, signatures after it
        if b[p] != 0x81:
            raise ValueError(f"unknown transaction version {b[p]:#x}")
        n_sigs, (mask,) = b[p + 1], struct.unpack_from("<I", b, p + 4)
        n_ix, n_keys = b[p + 40], b[p + 41]
        q = p + 42 + 32 * n_keys + 4 * bin(mask).count("1")
        heads, q = q, q + 4 * n_ix
        for k in range(n_ix):        # header: program u8, accounts u8, data_len u16
            _, n_acc, n_data = struct.unpack_from("<BBH", b, heads + 4 * k)
            q += n_acc + n_data
        return q + 64 * n_sigs, b[q:q + 64]
    n_sigs, q = cu16(b, p)           # legacy and v0: signatures first
    first, q = b[q:q + 64], q + 64 * n_sigs
    v0 = b[q] & 0x80
    if v0 and b[q] != 0x80:
        raise ValueError(f"unknown message version {b[q]:#x}")
    q += 4 if v0 else 3              # version byte, then the 3-byte header
    n_keys, q = cu16(b, q)
    q += 32 * n_keys + 32            # account keys, recent blockhash
    n_ix, q = cu16(b, q)
    for _ in range(n_ix):
        q = skip_vec(b, skip_vec(b, q + 1))
    if v0:                           # address table lookups
        n_lookups, q = cu16(b, q)
        for _ in range(n_lookups):
            q = skip_vec(b, skip_vec(b, q + 32))
    return q, first

def decode_entries(payload):
    """One completed payload: u64 entry count, then the entries."""
    (count,), p = struct.unpack_from("<Q", payload), 8
    if count == 0:
        return None                  # a block marker, not an entry batch
    entries = []
    for _ in range(count):
        num_hashes, entry_hash, n_tx = struct.unpack_from("<Q32sQ", payload, p)
        p += 48
        txs = []
        for _ in range(n_tx):
            end, sig = read_transaction(payload, p)
            txs.append((b58(sig), payload[p:end]))
            p = end
        entries.append((num_hashes, b58(entry_hash), txs))
    return entries
```

`deshred` takes the dicts that the parser on [the header page](https://nitride.xyz/docs/shreds/parse-header) returns, keyed by index. It stops at the first missing index, so call it again from the next run's start once the hole is filled.

How we tested it: we took the 193 transactions of one mainnet block from public RPC (87 legacy, 54 v0 and 52 v1), packed them into entries and two entry batches, added a block marker, and cut the result into crafted data shreds. We sent those over a UDP socket on 127.0.0.1 in reverse order, then parsed, deshredded and decoded them. Every transaction's bytes and first signature matched what RPC returned for that block. That proves the decoder against real transaction bytes; the shreds themselves were crafted, and a real slot also fills the resigned last batch with smaller chunks.

## The Agave crates
For production, the practical route is Agave's own code, pinned to the release the cluster runs: `solana-ledger` for shreds (`Shred`, `Shredder::deshred`) and `solana-entry` for `Entry` and `BlockComponent`. Both put their API behind the `agave-unstable-api` feature, so pin an exact version.

```toml file="Cargo.toml"
[dependencies]
solana-ledger = { version = "=4.4.1", features = ["agave-unstable-api"] }
solana-entry = { version = "=4.4.1", features = ["agave-unstable-api"] }
wincode = "0.6"
```

The sketch below shows how the calls fit together. It is an outline, not a complete program: we did not compile it here, because version 4.4.1 needs a newer Rust toolchain than our test machine has.

```rust file="outline.rs"
// Outline: one complete run of data shreds, sorted by index.
use solana_entry::block_component::BlockComponent;
use solana_ledger::shred::{Shred, Shredder};

fn decode_run(run: &[Shred]) -> Result<(), Box<dyn std::error::Error>> {
    let bytes = Shredder::deshred(run.iter().map(|s| s.payload()))?;
    match wincode::deserialize::<BlockComponent>(&bytes)? {
        BlockComponent::EntryBatch(entries) => {
            for entry in entries {
                for tx in entry.transactions {
                    println!("{}", tx.signatures[0]);
                }
            }
        }
        BlockComponent::BlockMarker(_) => {}
    }
    Ok(())
}
```

For recovery, see step 2: Agave's public recovery entry point needs a validator `Bank` and a retransmit channel, so a standalone receiver calls `reed-solomon-erasure` directly.
