Files
skills/docs/networking/drive/drive-plugin-chunks/src/codec/chunk.md
2026-05-29 08:20:56 +01:00

2.3 KiB

chunk

Purpose

Wraps the chunk wire format above the bare header: takes raw chunk bytes (header + signature + ciphertext) and parses them into the structured Chunk and EncodedChunk shapes that the rest of the plugin consumes. This is the inverse of encrypt-stream's output and the input to verify-chunk / decrypt-chunk.

Features

  • parseChunk(raw): Chunk — splits raw bytes into metadata, sig, and ciphertext slices using HEADER_SIZE as the boundary.
  • Length validation — rejects anything shorter than HEADER_SIZE + payloadLen.
  • Allocation-light — uses Uint8Array.subarray views where safe and slice only where ownership matters.
  • Round-trip stable when paired with encodeHeader and the encrypt-stream output.

Usage: Basic Example

import { parseChunk } from "@suaveplan/drive-plugin-chunks";

const raw: Uint8Array = await chunks.getChunk(fileId, 0).then((b) => b!);
const chunk = parseChunk(raw);
console.log(chunk.metadata.chunkId, chunk.ciphertext.length);

Usage: Advanced Example

import {
    decryptChunk,
    parseChunk,
    verifyChunkSig,
} from "@suaveplan/drive-plugin-chunks";

async function readVerifiedChunk(fileId: Uint8Array, idx: number) {
    const raw = await chunks.getChunk(fileId, idx);
    if (!raw) throw new Error("missing chunk");
    const chunk = parseChunk(raw);
    verifyChunkSig(raw, serverPubKey);
    const plaintext = decryptChunk(chunk.metadata, chunk.ciphertext, fileKey);
    return plaintext.slice(0, chunk.metadata.payloadLen);
}

API Reference

  • parseChunk(raw: Uint8Array): Chunk — returns { metadata, sig, ciphertext }. metadata flows through parseHeader; sig is the 64-byte Ed25519 signature slice; ciphertext is the trailing payloadLen bytes.
  • Throws ChunksError(CHUNKS.METADATA_INVALID) for under-length buffers (delegated to parseHeader).
  • Throws ChunksError(CHUNKS.PAYLOAD_LEN_INVALID) when the trailing payload is shorter than metadata.payloadLen.

Implementation Notes

parseChunk does not verify the signature or decrypt — those are independent stages so peers can short-circuit on metadata-only inspection (manifest checks, availability gossip). The ciphertext is sliced rather than viewed when its length differs from the underlying buffer to avoid pinning the larger raw allocation in caches.