# Architecture of `Ridge-Lab/moonmls`

`moonmls` is organized as a strict acyclic DAG of 9 pure-MoonBit packages plus a foreign-library bridge (`bridge`) and 3 runnable examples (`examples/*`). Every protocol layer maps cleanly onto its corresponding section of IETF **RFC 9420**.

## Package Dependency DAG

```mermaid
flowchart TD
    root["Ridge-Lab/moonmls (Group, Welcome, KeyPackage, External Join)"]
    tree["tree (RatchetTree, Parent Hash, TreeKEM)"]
    framing["framing (PublicMessage, PrivateMessage)"]
    ks["key_schedule (EpochSecrets, PSK Chain, Transcript Hashes, Exporter)"]
    st["secret_tree (Secret Tree, Hash Ratchets, Replay Window)"]
    crypto["crypto (HKDF, ExpandWithLabel, HPKE, Ed25519/Ed448/ECDSA-P256, AEAD)"]
    codec["codec (TLS Presentation Language, Strict QUIC Varints)"]
    tm["treemath (RFC 9420 Appendix C LBBT Math)"]
    types["types (MlsError, CipherSuite, RFC 9420 Structs)"]
    mooncry["cc06b/mooncry (Apache-2.0 Primitives)"]
    bridge["bridge (Host JS/Wasm FFI: CLI, Browser Studio, IETF Verifier)"]

    root --> tree
    root --> framing
    root --> ks
    root --> st
    root --> crypto
    root --> codec
    root --> tm
    root --> types

    tree --> crypto
    tree --> codec
    tree --> tm
    tree --> types

    framing --> st
    framing --> crypto
    framing --> codec
    framing --> types

    ks --> crypto
    ks --> codec
    ks --> types

    st --> crypto
    st --> tm
    st --> types

    crypto --> codec
    crypto --> types
    crypto --> mooncry

    codec --> types
    bridge --> root
```

## Module Responsibilities & Design Choices

| Package | RFC 9420 Sections | Key Invariants Enforced |
| --- | --- | --- |
| `types` | §2, §5–§12 | Single typed `MlsError` error domain; explicit `CipherSuite` enum for CS1/CS2/CS3/CS4/CS6; exact wire-faithful enums (`Sender`, `ContentBody`, `Proposal`, `LeafNodeSource`, `MLSMessage`). |
| `treemath` | Appendix C | Left-Balanced Binary Tree arithmetic (`node_width`, `root`, `level`, `left`, `right`, `parent`, `sibling`, `direct_path`, `copath`, `common_ancestor`) using unsigned arithmetic with overflow/root guards. |
| `codec` | §2.1.2, Wire Formats | Strict canonical TLS wire codec. Rejects non-minimal 2-byte/4-byte QUIC varints, forbids 8-byte `0b11` prefix, rejects truncated frames and trailing garbage bytes. |
| `crypto` | §5, RFC 9180 | Bridges `cc06b/mooncry` to RFC 9420 labeled KDF/Sign/HPKE operations. Includes strict ASN.1 DER ECDSA P-256 encoder/decoder (`asn1_der.mbt`) and constant-time equality (`constant_time_eq`). |
| `secret_tree` | §9 | Lazy node expansion with **immediate parent secret erasure** on descent (Forward Secrecy); bounded out-of-order generation cache (`max_forward_distance`, `max_out_of_order`) rejecting duplicate/replayed generations. |
| `key_schedule` | §8 | `EpochSecrets::advance` & `from_joiner_secret`; iterative PSK secret extraction chain (§8.4); Confirmed & Interim Transcript Hashes (§8.2); `MLS-Exporter` (§8.5); `external_secret` -> external HPKE key pair derivation. |
| `framing` | §6 | `PublicMessage` enforces `membership_tag` and strictly rejects `Application` payloads; `PrivateMessage` applies 4-byte `reuse_guard` XOR on nonce, encrypts `MLSSenderData` with ciphertext-sample-derived AEAD key/nonce, and requires all padding bytes to be `0x00`. |
| `tree` | §7 | Power-of-2 LBBT normalization with right-half blank truncation on wire encode and `remove_leaf`; `resolution` with `unmerged_leaves`; `verify_parent_hashes` (§7.9.2); `verify_all_leaf_signatures`; `create_update_path` / `merge_update_path` / `process_update_path`. |
| Root (`moonmls`) | §10–§12 | Stateful `Group` engine with **atomic commit application**: `process_commit` computes the entire next-epoch tree, transcript hashes, key schedule, and `confirmation_tag` on cloned candidate state and only swaps fields after every cryptographic check succeeds. |
| `bridge` | Host FFI | Compiled as `pkgtype(kind: "foreign_library")` exporting both the 16-suite IETF vector verification entry points (`vectors.mbt`) and the interactive `SessionHandle` API (`session.mbt`) powering the CLI, fault-injection suite, benchmarks, and Browser TreeKEM Studio. |

## Cross-Target Strategy

- **Zero native/C FFI assumptions**: Pure MoonBit throughout; compiles cleanly with `--deny-warn` on `wasm-gc`, `wasm`, `js`, and `native`.
- **Deterministic entropy injection**: Core protocol operations (`Group::create`, `generate_key_package`, `Group::commit`, `Group::join_external`, `Group::encrypt_application`) take explicit seed / reuse-guard byte parameters so unit tests, IETF test-vector replays, and multi-target determinism checks produce bit-identical results across all four backends. Host applications supply CSPRNG bytes.
