niobium/fhetch_encoding.h

Include: #include "niobium/fhetch_encoding.h"

Declarations

niobium::fhetch::fhex_byteswap

template <typename T>
constexpr T fhex_byteswap(T v)

Byte-swap an unsigned integer. C++23 has std::byteswap; until the project moves off C++17 this stands in for it.

niobium::fhetch::fhex_le

template <typename T>
constexpr T fhex_le(T v)

Whether the host is little-endian. C++20 has std::endian; until this library moves off C++17, the compiler's own byte-order macro stands in for it. GCC and Clang both define it, and needing no header is why it is preferred here over the <endian.h>/<machine/endian.h> split. Host value to/from the file's little-endian byte order. The conversion is its own inverse, so one helper serves both directions. On a little-endian host it folds away to nothing; the big-endian arm exists so the byte order is a property of the format rather than of whatever host happened to write the file.

niobium::fhetch::kFhexMagic

constexpr char kFhexMagic = {'N', 'B', 'F', 'H'}

Magic bytes at offset 0. Spelled out rather than a packed integer so the value reads the same in a hex dump on any host.

niobium::fhetch::kFhexVersion

constexpr uint16_t kFhexVersion = 1

Bumped whenever the record layout or prologue changes incompatibly. A reader refuses a version it does not know rather than mis-decoding it.

This versions the container. It is independent of the FHETCH IR version below, which versions the language the recorded program is written in — the two move for different reasons and a file carries both.

struct niobium::fhetch::FhetchVersion

struct niobium::fhetch::FhetchVersion

Version number of the FHETCH specification.

Deliberately not named major/minor: glibc's <sys/sysmacros.h> defines those as function-like macros, and a struct member of the same name is a standing trap for any translation unit that pulls it in.

Fields

NameDeclarationDescription
major_versionuint16_t major_version = 0
minor_versionuint16_t minor_version = 0
patch_versionuint16_t patch_version = 0

known

bool known() const

False when no version is known — which is the case for every file written today, because the current specification carries no version number. 0.0.0 is not a release any revision could bear, so it is a safe sentinel.

struct niobium::fhetch::FhetchSpecDate

struct niobium::fhetch::FhetchSpecDate

Date of the FHETCH specification document.

Stored as its three components rather than a day count so a hex dump and a diagnostic both read as the date on the document's cover.

Fields

NameDeclarationDescription
yearuint16_t year = 0
monthuint8_t month = 0
dayuint8_t day = 0

known

bool known() const

False when the file carried no spec-date tag — i.e. it predates this field. Year 0 is not a date any revision could bear.

struct niobium::fhetch::FhetchSpec

struct niobium::fhetch::FhetchSpec

Which revision of the FHETCH IR a program is written in.

FHETCH is specified by "Polynomial Intermediate Representation for Fully Homomorphic Encryption" (fhetch.org). That draft carries no version number, only a last-updated date, so today the date is all a writer has.

At least one of the two must be present — a file identifying itself by neither is rejected.

Exactly one of them is authoritative at a time, and which one depends on what is available:

Consumers should branch on authoritative_date() rather than re-deriving that rule, which is easy to invert by accident.

Fields

NameDeclarationDescription
versionFhetchVersion version
dateFhetchSpecDate date

valid

bool valid() const

Whether this names a revision at all. Enforced on both encode and decode, so a .fhex always says what it is written in.

authoritative_date

std::optional<FhetchSpecDate> authoritative_date() const

The date when it is the thing identifying the revision, nullopt when a version supersedes it. A caller that gets a value here should key its behaviour on the date; one that gets nullopt should use version.

niobium::fhetch::kFhetchSpec

constexpr FhetchSpec kFhetchSpec {FhetchVersion{}, FhetchSpecDate{2025, 5, 19}}

Revision of the FHETCH specification this implementation targets: 2025-05-19, per the draft at https://fhetch.org/wp-content/uploads/2025/05/COPY-FOR-SHARING-2025-05-19-Polynomial-Intermediate-Representation-for-Fully-Homomorphic-Encryption-DRAFT.pdf

The version is left unset because that draft has none; set it here once the specification carries one, and the date drops to advisory on its own. This is a claim about what this code implements, so it changes only when the code does, and deliberately is not derived from the submodule (whose CMake version tracks the library's releases, not the spec's revisions).

niobium::fhetch::fhex_pack_version

constexpr uint64_t fhex_pack_version(FhetchVersion version)

Pack a version into the u64 its metadata tag carries, and back.

niobium::fhetch::fhex_unpack_version

constexpr FhetchVersion fhex_unpack_version(uint64_t packed)

niobium::fhetch::fhex_pack_spec_date

constexpr uint64_t fhex_pack_spec_date(FhetchSpecDate date)

Pack a spec date as YYYYMMDD, the form its metadata tag carries. Chosen over a day count because it orders correctly as an integer and reads as the date itself in a dump.

niobium::fhetch::fhex_unpack_spec_date

constexpr FhetchSpecDate fhex_unpack_spec_date(uint64_t packed)

niobium::fhetch::kFhexPrologueBytes

constexpr size_t kFhexPrologueBytes = 24

Size of the fixed prologue, in bytes.

niobium::fhetch::kFhexAlign

constexpr size_t kFhexAlign = 8

Alignment the fixed sections (metadata, modulus table) are padded to. The varint record stream that follows them is unaligned by nature.

niobium::fhetch::kFhexMaxFileBytes

constexpr size_t kFhexMaxFileBytes = 1ULL <<30

Sanity bound on a .fhex read into memory, not a format limit. A 200k-instruction trace is under 2 MB, so this is far above any real one.

niobium::fhetch::kFhexMaxVarintBytes

constexpr size_t kFhexMaxVarintBytes = 10

Largest number of bytes an unsigned LEB128 value can occupy: 64 bits at 7 payload bits per byte. Used to bound reads on a corrupt stream so a runaway continuation-bit chain terminates instead of walking off the end.

Instruction record

enum niobium::fhetch::FhRecordFlags

enum FhRecordFlags : uint8_t { FH_FLAG_HAS_MOD = 1u <<0, FH_FLAG_MOD_LITERAL = 1u <<1, FH_FLAG_HAS_IMM = 1u <<2, FH_FLAG_HAS_SRC2 = 1u <<3, FH_FLAG_HAS_AUX = 1u <<4, FH_FLAG_HAS_LOGN = 1u <<5 }

Per-record flag bits. Absent operands are not merely zero — zero is a legal address, immediate, and modulus index — so presence is explicit.

ValueDescription
FH_FLAG_HAS_MODmodulus field is meaningful
FH_FLAG_MOD_LITERALmodulus holds a prime, not a table index
FH_FLAG_HAS_IMMimm holds an immediate / k / offset
FH_FLAG_HAS_SRC2src2 is meaningful
FH_FLAG_HAS_AUXaux holds omega (NTT/INTT) or mask (automorph)
FH_FLAG_HAS_LOGNlogn is meaningful

struct niobium::fhetch::FhetchRecord

struct niobium::fhetch::FhetchRecord

One instruction, in memory. This is not the wire layout — records are varint-packed on disk, so this struct's size and field order are free to change without touching the format.

The wire form of a record is:

opcode    u8       always
flags     u8       always (FhRecordFlags)
logn      u8       iff FH_FLAG_HAS_LOGN
dst       varint   unless the opcode takes no operands (halt)
src1      varint   likewise
src2      varint   iff FH_FLAG_HAS_SRC2
modulus   varint   iff FH_FLAG_HAS_MOD
imm       varint   iff FH_FLAG_HAS_IMM
aux       varint   iff FH_FLAG_HAS_AUX

Operand presence is keyed on the flags rather than on the opcode so the decoder can skip a record it does not recognize; the one exception is dst/src1, which every opcode but halt has, and which are therefore keyed on the opcode itself.

modulus is a full 64 bits rather than a narrow table index because a writer falls back to the literal prime when a modulus is not in the chain, exactly as the text form does. Giving that case its own flag keeps it from colliding with aux, which sr_automorph_eval needs for mask at the same time. A varint charges for the width only when the literal case actually occurs.

aux carries omega for sr_ntt/sr_intt and mask for sr_automorph_eval — the two never co-occur on one instruction. imm carries the scalar immediate, k, or offset by opcode.

Fields

NameDeclarationDescription
opcodeuint8_t opcode = FH_ILLFhOpcode.
flagsuint8_t flags = 0FhRecordFlags.
lognuint8_t logn = 0sr_automorph_eval's logn (fits: logn <= 64)
dstuint32_t dst = 0
src1uint32_t src1 = 0
src2uint32_t src2 = 0
modulusuint64_t modulus = 0table index, or literal prime
immuint64_t imm = 0immediate | k | offset
auxuint64_t aux = 0omega | mask

Metadata section

enum niobium::fhetch::FhMetaTag

enum class FhMetaTag : uint16_t { ProgramName = 1, TraceFile = 2, Description = 3, SourceFile = 4, BuildTimestamp = 5, Scheme = 6, SecurityLevel = 7, SourceLine = 8, InstructionCount = 9, GeneratedTimestamp = 10, RingDimension = 11, MultiplicativeDepth = 12, ModulusChainLength = 13, FhetchSpecVersion = 14, FhetchSpecDateTag = 15, ProgramVersion = 16 }

TLV tags for the metadata section. Numbering is on the wire; a reader skips tags it does not recognize, so new fields can be added without a version bump as long as old readers can safely ignore them.

ValueDescription
ProgramNamestring
TraceFilestring
Descriptionstring
SourceFilestring
BuildTimestampstring
Schemestring
SecurityLevelstring
SourceLineu64
InstructionCountu64
GeneratedTimestampu64
RingDimensionu64
MultiplicativeDepthu64
ModulusChainLengthu64
FhetchSpecVersionu64, packed by fhex_pack_version()
FhetchSpecDateTagu64, YYYYMMDD per fhex_pack_spec_date()
ProgramVersionstring

struct niobium::fhetch::FhMetaEntry

struct niobium::fhetch::FhMetaEntry

One TLV entry header, followed by length payload bytes zero-padded to the next multiple of 8.

Fields

NameDeclarationDescription
taguint16_t tag0 FhMetaTag
reserveduint16_t reserved2 must be 0
lengthuint32_t length4 payload bytes, excluding padding

struct niobium::fhetch::FhexPrologue

struct niobium::fhetch::FhexPrologue

Fixed prologue, laid out to match the offsets documented at the top.

Fields

NameDeclarationDescription
magicchar magic0
versionuint16_t version4
flagsuint16_t flags6
metadata_bytesuint32_t metadata_bytes8
modulus_countuint32_t modulus_count12
instruction_countuint64_t instruction_count16

niobium::fhetch::fhex_align_up

constexpr size_t fhex_align_up(size_t n)

Round n up to the next multiple of kFhexAlign.

Decoding

enum niobium::fhetch::FhexDecodeError

enum class FhexDecodeError : uint8_t { None, BadMagic, UnsupportedVersion, Truncated, Malformed, UnknownOpcode, MissingSpec, TooLarge }

Why a decode failed, including the two cases a self-describing container adds: a file that isn't a .fhex at all, and one written by a newer toolchain than this reader knows.

ValueDescription
None
BadMagicnot a .fhex (or truncated before the prologue)
UnsupportedVersionwritten by a newer format version
Truncateda section runs past the end of the buffer
Malformedinternally inconsistent (bad padding, overlong TLV)
UnknownOpcodeopcode is one the consumer cannot represent
MissingSpecnames neither a FHETCH spec version nor a date
TooLargeexceeds kFhexMaxFileBytes

niobium::fhetch::fhex_decode_error_string

const char * fhex_decode_error_string(FhexDecodeError err)

Human-readable form of a decode error, for the WARNING a caller logs before falling back to the text trace.

struct niobium::fhetch::FhexProgram

struct niobium::fhetch::FhexProgram

Everything a .fhex carries, decoded.

records are the program as the file holds it, which is strictly richer than what a consumer's own instruction type may be able to represent: omega, mask, and logn are all carried here whether or not the consumer has a home for them. Decoding to records first means the file stays faithful even when the form it is converted into cannot be.

Fields

NameDeclarationDescription
metadataTraceMetadata metadata
format_versionuint16_t format_version = 0Version of the .fhex container the file was written in, as read from the prologue. Always equals kFhexVersion for a file this build accepted — a mismatch is refused rather than decoded — but it is reported so a caller can log what it actually read.
specFhetchSpec specRevision of the FHETCH spec the program is written in. Always valid() — a file naming neither a version nor a date is refused.
modulus_tablestd::vector<uint64_t> modulus_table
recordsstd::vector<FhetchRecord> records

niobium::fhetch::to_record

FhetchRecord to_record(const Instruction &inst)

The wire record for an instruction. Absent operands are left out of the record's flags rather than written as zero, so the record and the instruction carry exactly the same information.

niobium::fhetch::from_record

Instruction from_record(const FhetchRecord &record)

The instruction a wire record stands for — the inverse of to_record().

modulus_table_size is needed for nothing here: the record's own FH_FLAG_MOD_LITERAL says whether its modulus is an index or a prime, which is the ambiguity the text form has and the binary form does not.

niobium::fhetch::encode_fhetch_program

std::vector<std::byte> encode_fhetch_program(const TraceMetadata &metadata, const std::vector<uint64_t> &modulus_table, const std::vector<FhetchRecord> &records, FhetchSpec spec=kFhetchSpec)

Serialize a program to the .fhex byte stream.

records is written verbatim — the caller has already chosen each record's opcode and flags, so this does not re-derive them from metadata. modulus_table is written as its own section and is what a reader will populate TraceMetadata::modulus_chain from. spec defaults to the revision this implementation targets, which is what a writer wants; pass it explicitly only when re-encoding a program written against a different revision, so the original is preserved rather than silently restamped with ours. An invalid spec (neither version nor date) is a programming error and throws — the invariant is enforced on the way out as well as the way in, so a malformed file is never produced.

niobium::fhetch::decode_fhetch_program

std::optional<FhexProgram> decode_fhetch_program(const std::byte *bytes, size_t size, FhexDecodeError *err=nullptr)

Decode a .fhex byte stream.

Returns nullopt on any error, setting *err to the reason, so a caller can log it and fall back to the text .fhetch — the same corrupt-sidecar posture a binary sidecar wants. Never throws and never reads outside bytes; a corrupt file is a fallback, not a crash.

niobium::fhetch::read_fhetch_program

std::optional<FhexProgram> read_fhetch_program(const std::string &path, FhexDecodeError *err=nullptr)

Read and decode a .fhex file. Convenience wrapper over decode_fhetch_program(); a missing or unreadable file reports BadMagic, which the caller treats the same way — fall back to text.

niobium::fhetch::write_fhetch_program

bool write_fhetch_program(const std::string &path, const TraceMetadata &metadata, const std::vector<uint64_t> &modulus_table, const std::vector<FhetchRecord> &records, FhetchSpec spec=kFhetchSpec)

Write a program to path. Returns false if the file could not be written; the caller keeps the text trace either way.

Something not looking right? Suggest a change on GitHub.