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 = 1Bumped 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::FhetchVersionVersion 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
| Name | Declaration | Description |
|---|---|---|
major_version | uint16_t major_version = 0 | |
minor_version | uint16_t minor_version = 0 | |
patch_version | uint16_t patch_version = 0 |
known
bool known() constFalse 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::FhetchSpecDateDate 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
| Name | Declaration | Description |
|---|---|---|
year | uint16_t year = 0 | |
month | uint8_t month = 0 | |
day | uint8_t day = 0 |
known
bool known() constFalse 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::FhetchSpecWhich 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:
- A version is present: the version is authoritative. It names the revision exactly, whereas a date only says which document was on the author's desk, so an accompanying date drops to informational.
- No version: the date is authoritative. This is the case for every file written today, and it is a real identifier in that situation, not a fallback hint.
Consumers should branch on authoritative_date() rather than re-deriving that rule, which is easy to invert by accident.
Fields
| Name | Declaration | Description |
|---|---|---|
version | FhetchVersion version | |
date | FhetchSpecDate date |
valid
bool valid() constWhether 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() constThe 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 = 24Size of the fixed prologue, in bytes.
niobium::fhetch::kFhexAlign
constexpr size_t kFhexAlign = 8Alignment 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 <<30Sanity 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 = 10Largest 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.
| Value | Description |
|---|---|
FH_FLAG_HAS_MOD | modulus field is meaningful |
FH_FLAG_MOD_LITERAL | modulus holds a prime, not a table index |
FH_FLAG_HAS_IMM | imm holds an immediate / k / offset |
FH_FLAG_HAS_SRC2 | src2 is meaningful |
FH_FLAG_HAS_AUX | aux holds omega (NTT/INTT) or mask (automorph) |
FH_FLAG_HAS_LOGN | logn is meaningful |
struct niobium::fhetch::FhetchRecord
struct niobium::fhetch::FhetchRecordOne 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_AUXOperand 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
| Name | Declaration | Description |
|---|---|---|
opcode | uint8_t opcode = FH_ILL | FhOpcode. |
flags | uint8_t flags = 0 | FhRecordFlags. |
logn | uint8_t logn = 0 | sr_automorph_eval's logn (fits: logn <= 64) |
dst | uint32_t dst = 0 | |
src1 | uint32_t src1 = 0 | |
src2 | uint32_t src2 = 0 | |
modulus | uint64_t modulus = 0 | table index, or literal prime |
imm | uint64_t imm = 0 | immediate | k | offset |
aux | uint64_t aux = 0 | omega | 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.
| Value | Description |
|---|---|
ProgramName | string |
TraceFile | string |
Description | string |
SourceFile | string |
BuildTimestamp | string |
Scheme | string |
SecurityLevel | string |
SourceLine | u64 |
InstructionCount | u64 |
GeneratedTimestamp | u64 |
RingDimension | u64 |
MultiplicativeDepth | u64 |
ModulusChainLength | u64 |
FhetchSpecVersion | u64, packed by fhex_pack_version() |
FhetchSpecDateTag | u64, YYYYMMDD per fhex_pack_spec_date() |
ProgramVersion | string |
struct niobium::fhetch::FhMetaEntry
struct niobium::fhetch::FhMetaEntryOne TLV entry header, followed by length payload bytes zero-padded to the next multiple of 8.
Fields
| Name | Declaration | Description |
|---|---|---|
tag | uint16_t tag | 0 FhMetaTag |
reserved | uint16_t reserved | 2 must be 0 |
length | uint32_t length | 4 payload bytes, excluding padding |
struct niobium::fhetch::FhexPrologue
struct niobium::fhetch::FhexPrologueFixed prologue, laid out to match the offsets documented at the top.
Fields
| Name | Declaration | Description |
|---|---|---|
magic | char magic | 0 |
version | uint16_t version | 4 |
flags | uint16_t flags | 6 |
metadata_bytes | uint32_t metadata_bytes | 8 |
modulus_count | uint32_t modulus_count | 12 |
instruction_count | uint64_t instruction_count | 16 |
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.
| Value | Description |
|---|---|
None | |
BadMagic | not a .fhex (or truncated before the prologue) |
UnsupportedVersion | written by a newer format version |
Truncated | a section runs past the end of the buffer |
Malformed | internally inconsistent (bad padding, overlong TLV) |
UnknownOpcode | opcode is one the consumer cannot represent |
MissingSpec | names neither a FHETCH spec version nor a date |
TooLarge | exceeds 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::FhexProgramEverything 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
| Name | Declaration | Description |
|---|---|---|
metadata | TraceMetadata metadata | |
format_version | uint16_t format_version = 0 | Version 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. |
spec | FhetchSpec spec | Revision of the FHETCH spec the program is written in. Always valid() — a file naming neither a version nor a date is refused. |
modulus_table | std::vector<uint64_t> modulus_table | |
records | std::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.