# moon-nix (`mnix`) A proof-of-concept implementation of the **binary-cache side of Nix** in [MoonBit](https://www.moonbitlang.com) (native backend). It can install a package from nixpkgs — with its full runtime closure — from and run it: ```console $ 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](#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). ```sh 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 ``` ```text mnix [--root DIR] [--store DIR] [--channel C] [--system S] [--cache URL] install [--no-profile] [--dry-run] -name | -name> resolve print the store path an attribute maps to closure print the verified transitive closure search substring search of the channel's store-path names list list the profile remove remove from the profile (store paths are kept; no GC) env print `export PATH=/bin:$PATH` run [args…] run a command with the profile on PATH ``` * `--root` (default `~/.mnix`): state dir holding `store/`, `profile/`, `cache/`. * `--store` (default `/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 `` is bind-mounted at `/nix/store`, then `chroot`s 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//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///./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 `.`; `nixos-YY.MM` → `nixos/release-YY.MM` job `nixpkgs..`. So: **`install ` / `resolve ` 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 `/cache`), and `install /nix/store/-name` or `-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 ```text 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;;;;" 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 ` 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). ## Inspiration: snix (and licensing) The layout is inspired by [snix](https://snix.dev/) ([source](https://git.snix.dev/snix/snix)), the Rust re-implementation of Nix, in particular its `nix-compat` crate, which splits Nix's wire/on-disk formats into small independent modules (`nixbase32`, `store_path`, `narinfo`, `nar`, `nixhash`, `derivation`, …) separate from the services that use them. Borrowed *ideas*: * format handling as pure, individually tested modules (our `store`, `narinfo`, `nar`, `sign`) kept apart from I/O (`cache`, `installer`, `profile`, `cli`); * the store / content-addressed-store split: snix's `castore` stores NAR *contents* (blobs/directories) separately from Nix's store-path metadata. `mnix` only has the first, simplest half of that idea: the NAR is parsed into an in-memory tree (`nar.Node`, comparable to castore's directory/file/symlink nodes) which the `installer` materialises into a store dir, so a content-addressed or chunked backend could replace `installer` without touching the NAR/narinfo/signature code; * "Nix-compatible surface, different internals" as the goal for a future evaluator (see below). **Licence:** snix's crates are licensed GPL-3.0 (only its protobuf service definitions are MIT). `mnix` is Apache-2.0, so **no snix code was copied or translated**; everything here was written from the public Nix formats (nixbase32, narinfo fingerprints, NAR) and from observing real cache.nixos.org/Hydra responses. If snix code were ever reused, the affected packages would have to be relicensed under GPL-3.0. ## Stretch goal: Nix expression evaluator Not implemented (the binary-cache path was prioritised). Design notes for a future `nixexpr` package, informed by snix's `eval` crate (parser → AST → bytecode compiler → VM with thunks/upvalues, builtins as a separate module, an I/O abstraction so evaluation is embeddable and testable): a lexer/parser for literals, attrsets, lists, `let`, lambdas, string interpolation; a *lazy* evaluator (thunks, since Nix is lazy and nixpkgs depends on it); a small `builtins` set behind an I/O trait; tests per language feature. A tree-walking lazy evaluator would be the realistic first step; a bytecode VM like snix's is the performance route. ## License Apache-2.0. Third-party mooncakes keep their own licenses.