SpriteandClaude Sonnet 5.5 7ed4bc8e51 mnix: Nix binary-cache client PoC in MoonBit
Store path model + nixbase32, narinfo parser, ed25519 signature
verification, NAR reader/writer, closure computation, xz/zstd NAR fetch
with hash verification, atomic store unpack, profile management, Hydra-based
name resolution, and the mnix CLI. README documents usage, the /nix/store
limitation, and what a fuller implementation needs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 22:09:44 +00:00

moon-nix (mnix)

A proof-of-concept implementation of the binary-cache side of Nix in MoonBit (native backend). It can install a package from nixpkgs — with its full runtime closure — from https://cache.nixos.org and run it:

$ mnix install hello
resolving 'hello' via https://hydra.nixos.org/job/nixpkgs/trunk/hello.x86_64-linux/latest-finished
target: /nix/store/sd779x86bjaqxj2lzh2jsir4h0zjz6d1-hello-2.12.3
closure: 5 paths (all signatures verified)
fetching r3hvhzl5fxhrgn0rfy5g7rda17702pj4-glibc-2.44-57 (10416204 bytes, zstd)
...
$ mnix run hello
Hello, world!

It is not a Nix evaluator: it never evaluates nixpkgs, never builds anything, and has no derivations/garbage collector/sandbox. See Limitations.

What was demonstrated (real run, not mocked)

On Linux x86_64, against the real cache.nixos.org / hydra.nixos.org:

  • mnix install hello → resolved hello to /nix/store/sd779x86…-hello-2.12.3, fetched and ed25519-verified 5 narinfos (hello, glibc, libidn2, libunistring, libgcc), downloaded 5 zstd NARs, verified FileHash + NarHash/NarSize, unpacked them, linked bin/hello into the profile.
  • mnix run hello → Hello, world! (both with the default user-writable store via a mount namespace, and with a native /nix/store).
  • mnix install ripgrep + mnix run rg … works too (closure shares paths with hello; already-present paths are skipped).

Build & usage

Requires the MoonBit toolchain (export PATH=$HOME/.moon/bin:$PATH), a C compiler, and OpenSSL 3 shared libs (loaded dynamically by moonbitlang/async for HTTPS).

moon build --target native --release
# binary: _build/native/release/build/cli/cli.exe  (alias it to `mnix`)
moon check && moon test && moon fmt --check   # 35+ unit tests
mnix [--root DIR] [--store DIR] [--channel C] [--system S] [--cache URL] <command>

  install [--no-profile] [--dry-run] <attr | /nix/store/<hash>-name | <hash>-name>
  resolve <attr>        print the store path an attribute maps to
  closure <attr>        print the verified transitive closure
  search  <term>        substring search of the channel's store-path names
  list                  list the profile
  remove  <name>        remove from the profile (store paths are kept; no GC)
  env                   print `export PATH=<profile>/bin:$PATH`
  run <cmd> [args…]     run a command with the profile on PATH
  • --root (default ~/.mnix): state dir holding store/, profile/, cache/.
  • --store (default <root>/store): where NARs are unpacked. Use --store /nix/store to install into the real store location.
  • --channel (default nixos-unstable): nixos-unstable, nixpkgs-unstable or nixos-YY.MM (e.g. nixos-25.05).
  • --system (default: from uname -m): e.g. x86_64-linux, aarch64-linux.
  • --cache (default https://cache.nixos.org; trusted key is always cache.nixos.org-1:6NCHdD59…).

The /nix/store problem (read this)

Binaries in cache.nixos.org have /nix/store/... hardcoded (ELF interpreter, RPATH, script shebangs, strings). They cannot be relocated to ~/.mnix/store by simply moving files (real Nix would have to rebuild, or rewrite hash-bearing paths — which changes the hash). mnix therefore supports two honest modes:

  1. Native /nix/store (--store /nix/store): needs /nix/store to be creatable/writable by the user (root-owned /nix created beforehand with sudo install -d -o $USER /nix /nix/store, as multi-user Nix does). Profile symlinks then just work: ~/.mnix/profile/bin/hello.
  2. User-writable store + mount namespace (default ~/.mnix/store): mnix run executes the command inside unshare -rm (unprivileged user namespace) in which a tmpfs root mirrors / via recursive bind mounts and <store> is bind-mounted at /nix/store, then chroots into it. No root required, but it needs unprivileged user namespaces (/proc/sys/kernel/unprivileged_userns_clone/user.max_user_namespaces) and unshare, mount, chroot from util-linux/coreutils. Running ~/.mnix/profile/bin/hello directly (outside mnix run) fails unless /nix/store happens to contain the same paths. (proot/bwrap would be alternatives; bwrap did not work in the development sandbox, which is why the raw unshare route was used.)

In the development sandbox both modes worked (the sandbox user could create /nix/store).

How name → store path resolution works (and why)

Nix attribute → store path normally requires evaluating nixpkgs (nix-instantiate + output hashing), which is out of scope. Two options were investigated:

  • https://channels.nixos.org/<channel>/store-paths.xz — a plain list of every store path of the channel (232k lines for nixos-unstable). It has no attribute names and, crucially, mixes all platforms: the same hello-… name appears with several hashes (x86_64-linux, aarch64-linux, darwin, …) and there is no way to tell which is which without downloading. Good for search (names), unreliable for install.
  • Hydra's JSON API — https://hydra.nixos.org/job/<project>/<jobset>/<attr>.<system>/latest-finished with Accept: application/json returns the exact out store path of the latest successful build of that attribute for that system. Everything Hydra built is in cache.nixos.org. Mapping used: nixos-unstable|nixpkgs-unstable → nixpkgs/trunk job <attr>.<system>; nixos-YY.MM → nixos/release-YY.MM job nixpkgs.<attr>.<system>.

So: install <attr> / resolve <attr> use Hydra (exact, per-platform, fails loudly if there is no successful build), search uses store-paths.xz (downloaded once, decompressed with the pure-MoonBit xz decoder, cached under <root>/cache), and install /nix/store/<hash>-name or <hash>-name bypasses resolution entirely. Caveat: Hydra's latest-finished is the newest build in the jobset, which can be newer than the current channel revision — it is not pinned to a channel commit. (A fuller implementation would pin to the channel's evaluation id.)

Architecture

 src/
  store      nixbase32, sha256 helpers, StorePath parse/validate, NixError
  narinfo    .narinfo parser (StorePath, URL, Compression, FileHash, FileSize,
             NarHash, NarSize, References, Deriver, Sig*, CA)
  sign       ed25519 verification of narinfo fingerprints
             "1;<path>;<narhash>;<narsize>;<comma-sep full ref paths>"
  nar        NAR reader/writer (regular, executable, symlink, directory)
  cache      HTTP(S) client, narinfo fetch+verify, NAR download, xz/zstd
             decompression, FileHash/NarHash/size verification
  closure    transitive closure over References (deps-first order)
  installer  atomic unpack of a NAR tree into the store (tmp dir + rename)
  resolve    channel→Hydra job URLs, Hydra JSON parsing, store-paths search
  profile    profile dir with bin/ symlinks + manifest (list/add/remove)
  cli        `mnix` (argparse, config, commands, `run` namespace wrapper)

Pure logic (store, narinfo, sign, nar, closure, resolve, manifest) is separated from I/O (cache, installer, profile, cli) and unit-tested.

Reused mooncakes packages (all checked for the native backend):

need package notes
HTTPS client, fs, process moonbitlang/async 0.22.10 TLS via dlopen'd OpenSSL; no redirect following (done manually), fs write_file fsyncs by default (disabled per file for NAR unpack)
sha256 moonbitlang/x (crypto) 0.5.9
ed25519 hustcer/ed25519 0.6.2 pure MoonBit, "not audited, not constant-time" per its README — fine for verification of public data, noted
xz / LZMA2 lin2077-zeming/moonxz 0.4.6 pure MoonBit; read-only use
zstd gaato/zstd 0.6.1 pure MoonBit decoder
base64, argparse, json, utf8, buffer moonbitlang/core

cache.nixos.org currently serves zstd NARs for new paths (xz for some older ones); both are supported. Other compressions (bzip2, …) fail loudly with unsupported.

Verification chain (no silent fallbacks)

  1. narinfo parsed strictly (malformed lines/duplicate keys → error); the StorePath hash must equal the requested hash.
  2. Signature must verify under a trusted key (fails if absent, from an unknown key, or invalid). Fingerprint covers path, NarHash, NarSize and references, so references/closure edges are authenticated.
  3. Compressed download: FileHash (sha256, nixbase32) and FileSize.
  4. Decompressed NAR: NarSize and NarHash.
  5. NAR parse is strict: names validated (no /, ., ..), entries must be strictly sorted, padding must be zero, no trailing bytes.
  6. Missing closure members, HTTP errors, unknown compression, unwritable store → hard error with a message; exit status 1.

Unit tests include a real cache.nixos.org narinfo whose signature verifies against the real public key (and fail when the path, size or references are tampered), real xz/zstd outputs produced by the reference xz/zstd tools, nixbase32 vectors (SHA-256 of the empty string, etc.), NAR round trips, and real symlink/exec-bit unpacking.

Limitations

  • No evaluator: attribute resolution is Hydra/store-paths.xz metadata only. Only attributes Hydra builds (nixpkgs release.nix jobs, i.e. mostly top-level packages) resolve. search is by store-path name and can't tell platforms apart. No nix-env -qaP-style description search.
  • Store path rewriting/relocation is impossible (hash-bearing paths); hence the /nix/store modes above. mnix run needs Linux user namespaces.
  • Linux only in practice (the namespace wrapper; the cache client itself is portable). --system can select e.g. aarch64-linux metadata but the result can only run on that architecture.
  • NARs are handled in memory; limited to < 2 GiB per NAR (the moonxz/zstd APIs use Int32 sizes). Large paths (e.g. big toolchains) need a streaming design.
  • Downloads are sequential, un-resumable, no retries, no progress bar, no Content-Length/proxy handling.
  • No store database (/nix/var/nix/db): no registration of valid paths, references, or deriver; no nix-store -q; no garbage collector (remove only deletes profile links); store files are chmod 0444/0555, directories 0755 (real Nix makes them read-only and normalizes mtime to 1).
  • The ed25519 implementation is not constant-time (irrelevant for verifying public signatures). Only the NAR hash/signature are trusted — there is no content-addressed (CA) path verification, no .narinfo CA: handling beyond parsing it.
  • Profile = a manifest + symlinks into bin/ only (no share/, no generations/rollback, no nix profile JSON format).
  • install <attr> can pick a build newer than the channel revision.
  • Only the out output of an attribute is installed (not man, dev).

What a fuller implementation would need

  • A Nix language parser + lazy evaluator + builtins (import, derivation, fetchurl, …) and nixpkgs' lib/stdenv to compute derivation paths (ATerm .drv serialization, hashDerivationModulo, output path hashing) — then substituting by computed path, as nix-build does.
  • Store DB (SQLite schema), path validity registration, closure queries, GC roots and garbage collection, locking, nix-store --verify.
  • Streaming NAR/decompression with parallel, resumable fetches and retries; .ls/nar listing and Range support; other compressions (bzip2, brotli); other binary caches/keys; file:///ssh:// stores.
  • Real profiles with generations (nix profile/nix-env), buildEnv-style merged share/lib, conflict resolution, multiple outputs, meta.
  • Building (sandboxed builders, namespaces, fixed-output derivations).
  • A pinned channel mechanism (channel eval id → exact package set).

Stretch goal: Nix expression evaluator

Not implemented. The binary-cache path was prioritised and an evaluator subset would not have contributed to the install flow.

License

Apache-2.0. Third-party mooncakes keep their own licenses.

S
Description
A basic Nix implementation in MoonBit: fetch and install nixpkgs packages from a binary cache (proof of concept)
Readme
93 KiB
0 Stars 1 Watchers 0 Forks
Languages
MoonBit 99.2%
AMPL 0.8%