# BeeKEM Overview
BeeKEM is a Continuous Group Key Agreement (CGKA) protocol designed for local-first, peer-to-peer applications. It's an adaptation of TreeKEM (used by MLS) that drops the requirement for a central ordering server, relying only on causal ordering of operations and using only standard cryptographic primitives such as Diffie-Hellman key exchange (DH) and BLAKE3 hashing.
A dynamic group of peers needs to maintain shared encryption keys over time, supporting offline operation, concurrent membership changes, and no central coordinator. BeeKEM provides post-compromise security: after a rotation or removal, an adversary holding the old keys cannot read future updates. It does not provide forward secrecy. Members retain old path and root secrets so that [causal encryption](../design/causal_encryption.md) can reach document history, and a compromised replica yields them.
## Tree Structure
BeeKEM uses a binary tree:
* Each leaf holds a member's identity and DH public key or, after concurrent rotations by its instances, several keys
* The root holds the group's shared encryption key (encrypted)
* Each inner node holds a DH public key and encrypted secrets (which effectively function as the shared key for its subtree/subgroup)
Each leaf has an implicit secret known only to that member. Inner node secrets are encrypted via DH key exchange with sibling nodes, so any member can decrypt up the tree from their leaf to the root in O(log n) steps.
## Core Operations
1. **Update (key rotation)**: A member generates a fresh leaf keypair, then encrypts new secrets at each ancestor node using DH with the sibling's public key. This "path encryption" refreshes the root secret.
2. **Add**: Places a new member at the next available leaf and blanks the path from that leaf to root (invalidating the old root key, requiring a subsequent update to refresh it).
3. **Remove**: Blanks the removed member's leaf and its entire path to root.
4. **Decrypt**: Traverses from your leaf to the root. At each parent, performs DH with the sibling's public key to derive the symmetric key that decrypts their shared parent's secret. Continues until it reaches the root.
When a sibling is blank (from an add/remove), you can't do a single DH exchange. Instead, you must find the **sibling resolution**, i.e., the highest non-blank descendants of the blank subtree, and encrypt separately for each. This degrades to O(n) in the worst case but is typically O(log n).
## What Makes BeeKEM Novel: Handling Concurrency
BeeKEM's innovation is in how it handles concurrent operations without a central server to pick winners. When two members concurrently update overlapping path nodes, both DH public keys are retained as **conflict keys** at that node.
An inner node with conflict keys is treated similarly to a blank node during subsequent updates: you encrypt for its resolution rather than using a single key. This prevents an adversary who compromised one fork from decrypting the other fork's path to root. A later update whose path passes through the conflicted node, and whose causal past contains the origins of every conflicting version, replaces them with a single fresh key.
When applying a concurrent path change, BeeKEM merges keys at each affected node (combining into conflict keys where needed) and adds the update's secret store at each inner node as a new version (keeping all concurrent versions). Each version at a tree node is tagged with the operations that generated it. A path change removes the origins in its causal past from the versions at its nodes and removes a version once it has no origins left. So which versions an update removes depends only on which operations were applied, not on the order they arrived in. Remove operations are applied last, blanking paths after all other concurrent operations merge.
## Performance
In the common case (a balanced tree with few blanks or conflicts), operations are O(log n). The worst case would be a tree where every inner node is blank or has conflict keys, in which case operations degrade to O(n).
Space is O(n log n) worst case for conflict key storage.
## Security Properties
* **No forward secrecy**: Old root and path secrets are kept so that earlier content stays decryptable; compromising a member reveals them. Application secrets are derived from the root secret with BLAKE3 `derive_key`, so compromising one application secret reveals neither the root secret nor other application secrets.
* **Post-compromise security**: Leaf key rotation introduces fresh entropy and conflict key handling ensures an adversary with outdated leaf secrets can't decrypt new paths.
* **Standard crypto only**: Unlike Causal TreeKEM (which requires commutative/associative primitives like BLS), BeeKEM uses only X25519 Diffie-Hellman, BLAKE3, and XChaCha20-Poly1305.
# BeeKEM Deep Dive: The Algorithms
## Definitions
* **Encrypter child**: the child node that last encrypted its parent's secret.
* **Blank node**: a node set to empty. Either an inner node whose secret has been invalidated, an unoccupied leaf, or a removed member's leaf (functioning as a tombstone).
* **Resolution of a node**: if the node has a single public key, the resolution is just that node. If the node is blank or contains conflict keys, the resolution is the set of its highest descendants that are neither blank nor conflicted inner nodes. During encryption, resolution is taken on sibling nodes (not on the node being encrypted), so the worst case for a single resolution is n/2 (all leaves in one subtree).
* **Path**: the sequence of inner nodes from a leaf's parent up to and including the root.
* **Secret store**: what an update stores at an inner node on its path: a public key for the node, the encrypter child's public key, and a map of encrypted secrets keyed by tree node indices. An inner node has one or more secret stores, called its "versions".
* **Path node**: what an update sends for each inner node on its path (the node's public key and the map of encrypted secrets).
## The Tree
The tree is a complete binary tree sized to the next power of two. Leaves and inner nodes are stored in separate arrays. Leaves are 0-indexed from left to right. Inner nodes are also 0-indexed but mapped to positions within the tree via a standard implicit binary tree layout where leaf `i` sits at tree position `2i` and inner node `j` sits at tree position `2j + 1`.
The tree tracks a "next leaf index" pointer. New members are always placed at this position (the rightmost available slot), and the tree grows (doubling capacity) when needed. When members are removed, contiguous blank leaves at the right edge are trimmed back.
## Initialization
A new BeeKEM tree is created empty, with every leaf and inner node blank. Members are added one at a time, starting at leaf 0. There is no root secret until a member performs an update (path encryption).
## Path Encryption (Update/Key Rotation)
When a member rotates their leaf key, they encrypt a new secret at every ancestor up to the root.
1. **Generate a new leaf keypair.** Store the secret key in the member's local key map. The new public key is written to the leaf in step 5.
2. **Walk up the path from the leaf toward the root.** At each parent node:
a. **Sample a new parent secret** from the CSPRNG. Every ancestor's secret is sampled independently, so learning one secret on the path reveals nothing about the secrets above it. The encrypter keeps each sampled secret in its own key map so that it can derive the root secret later without decrypting its own path.
b. **Compute the new parent public key** from the new parent secret.
c. **Find the sibling's resolution.** Look at the sibling of the current child:
* If the sibling has a single public key (the common case), the resolution is just that one node.
* If the sibling is blank or has conflict keys, recursively descend into the sibling's subtree to find the highest descendants that are neither blank nor conflicted inner nodes.
d. **Encrypt the new parent secret for each node in the sibling resolution.** For each resolved node, derive a symmetric key via DH between the child's secret key and the resolved node's public key, then use that symmetric key to encrypt the new parent secret (using XChaCha20-Poly1305 with a synthetic IV derived by BLAKE3 from the key, plaintext, and tree ID; see [`design/ciphersuite.md`](../design/ciphersuite.md)). Each encrypted secret also records which public key it was paired with during DH. This is needed later during decryption so that non-encrypter members can identify the correct secret key to use. Store all encrypted secrets in a map keyed by tree node index, plus an additional entry for the encrypter child's own index (a copy of the first entry, enabling the encrypter to decrypt this node later using the same DH pair).
e. **Handle the empty resolution case.** If the sibling's entire subtree is blank (no members), generate a throwaway keypair and use it for the DH. The encrypted secret is stored keyed by the child's own index only (so the encrypter can still decrypt it later).
f. **Add the new path node** (parent's public key and encrypted secret map) to the path change. It is written to the parent, with its encrypter's key, in step 5.
3. **After reaching the root**, record which leaf performed this encryption.
4. **Emit a path change** containing the leaf's new public key and a path node for every inner node on the path.
5. **Sign the path change, then write it into the tree** as any received update is written, tagged with its digest. Its predecessors include every head so it replaces every version on its path. The tree then has a valid root secret that any member can decrypt.
## Decryption (Deriving the Root Secret)
Any group member can derive the current root secret by traversing from their leaf up to the root, decrypting at each step.
1. **Walk up your path from your leaf.** Keep track of every index you visit (a "seen indices" list). At each parent:
a. **Skip blank and conflict parents.** If a parent is blank or has conflict keys, skip it and move up to the next ancestor. You must hold onto the last secret you decrypted.
b. **Decrypt the parent's secret.** Look up the encrypted secret in the parent's secret store. The secret store maps tree node indices to encrypted secrets. Search your seen indices (most recent first) to find which index has a corresponding entry. This handles the case where the encrypter encrypted for a resolution that included a node on your path closer to your leaf rather than the child node immediately below this parent.
c. **Encrypter vs. non-encrypter decryption.** Each encrypted secret records which public key it was paired with during DH. If your public key matches the stored encrypter child public key (i.e., you are on the encrypter's side), derive the symmetric key via DH between your secret key and the paired public key, and decrypt. Otherwise (non-encrypter side), the paired public key corresponds to your node (or a node on your path to this point). Look up the secret key for it, derive the symmetric key via DH between that secret key and the encrypter child's public key, and decrypt.
d. **Store the decrypted secret** in your key map (mapping the parent's public key to the decrypted secret). This is reusable for future decryptions.
2. **Once you reach the root**, the last secret you decrypted is the root secret. Return it.
## Adding a Member
1. Place the new member's identity and public key at the next available leaf index.
2. If the tree capacity is exceeded, grow the tree (double it).
3. Blank the entire path from the new leaf to the root. This invalidates the root secret.
4. Record the operation with its causal predecessors.
After an add, there is no valid root key. Someone must perform an update (path encryption) to create a new one.
## Removing a Member
1. Verify the group has more than one member.
2. Find the leaf index for the member being removed.
3. Blank the leaf and its entire path to the root.
4. Trim contiguous blank leaves from the right edge of the tree.
Like add, remove invalidates the root key.
## Merging Concurrent Operations
BeeKEM assumes causal delivery of operations. Concurrent operations (those not causally ordered with respect to each other) require special merge handling.
### Merging a Concurrent Update (Path Change)
When applying a path change from another member that was created concurrently:
1. **Check if the path is still valid.** A path is valid if the originating member is still at the same leaf index and the path length matches. A mismatch (e.g., because a concurrent add reshuffled leaves or grew the tree) means the path is structurally incompatible and invalid.
2. **If the path is invalid**: update only the leaf and blank the path (no inner node updates are meaningful since the tree structure changed).
3. **If the path is valid**: Merge along the path:
a. **Find which versions it replaces.** Every version at a tree node is tagged with the operations that generated it. At the leaf and at each node on the path, this update drops the origins in its causal past from every version. A version left with no origins is replaced. So an update cannot remove a concurrent update's keys and a new key equal to an old one does not remove the old version unless its origin is in the past.
b. **At the leaf**: remove the replaced versions and add the new public key. Any version left from a concurrent write is kept as a **conflict key**. A leaf's conflict keys come from concurrent rotations by one member's instances. They remain until an update that has observed them replaces them. A conflicted leaf remains in its parent's resolution and encrypters encrypt to its lowest key.
c. **At each inner node on the path**: if the node is not blank, remove the replaced versions and add the update's path node, with its encrypter's key, as a new version, tagged with this update. If the node was blank, that becomes its only version. Two operations that generated identical versions leave one version with both as origins. It is removed once each origin has been in the causal past of some update at that node.
4. **Check the root.** If the root has a single version (no conflict), record the new encrypter. If the root now has multiple conflicting versions, clear the encrypter. The tree has no valid root key until someone does a fresh update.
### Merging Concurrent Membership Changes
Concurrent adds and removes require extra care. When a batch of more than one operation includes at least one add or remove:
1. Apply all operations in the batch (updates, adds, removes).
2. Then, as a cleanup step:
* **Re-blank removed members' paths.** Even though the remove itself blanked the path, concurrent updates from other members may have written new data along it. Re-blanking ensures the removed member's path is fully cleared.
* **Sort and re-add concurrently added leaves.** If multiple members concurrently added new members, those new leaves might have landed at the same position. Pull them all out, sort them deterministically by identity, and re-insert them in order (each getting the next available leaf, with paths blanked).
This sorting step is what ensures all peers converge to the same tree structure despite concurrent adds targeting the same leaf slot.
## Causal Ordering and Batches
Operations form a causal graph (a DAG). Each operation records its causal predecessors (the set of operation hashes it was aware of when created).
When a replay is required, the system sorts all operations and groups them into **batches**. Each operation's **depth** is the length of the longest chain of predecessors before it, recorded when the operation is added to the graph. Operations are ordered by depth (and by hash when depth is equal).
A batch is formed in two cases:
1. Boundary (singleton) batch: a single operation `x` is the only operation at its depth,
every shallower operation is its ancestor, and none of those ancestors has
a descendant deeper than `x` through a chain that excludes `x`.
2. Concurrency batch: all operations between consecutive boundary batches, before
the first, or after the last (or all operations, if there is no boundary batch).
A batch contains every operation concurrent with any operation in it (though two operations in one batch may be causally ordered).
Batches are applied in order:
* If a batch has one operation or contains only updates, apply its operations one by one (concurrent updates merge their paths).
* Otherwise, apply all the operations in the batch and then run membership change cleanup (re-blank, re-sort).
Concurrent updates are merged into the tree as they arrive. A concurrent add or remove is recorded but not applied. So is a concurrent update that a replay would put in the same batch as an add or remove. Once anything has been recorded this way, every later concurrent operation is recorded too, and the tree is **replayed from scratch** before the next local operation, before applying an operation whose predecessors include every head, and when listing members. Merging two replicas' states always replays. Replay starts from the initial state, sorts all known operations into batches, and re-applies them in order. This guarantees convergence regardless of the order in which operations were received.
## Inner Node Versions
Each inner node stores one or more **versions**, each a secret store. In the normal case, there is exactly one version. After concurrent updates that overlap at that node, there may be several.
A secret store contains the three components of an inner node described in an earlier section:
* **A public key** for the node corresponding to the encrypted secret.
* **The map from tree node indices to encrypted secrets.**
* **The encrypter child's public key.**
Each version also records the digests of the operations that generated it.
An inner node "has a conflict" when it has more than one version.
## Security Notes
**After a merge of concurrent updates, the tree has no root key.** The conflict keys at inner nodes mean that no single member can claim an uncontested root secret. A fresh update from any member will resolve the conflicts along its path and establish a new root.
**An adversary needs all historical leaf secrets from at least one leaf to exploit conflict merges.** Because conflict keys are retained (rather than picking a winner), an adversary who compromises one branch of a fork cannot read the other branch without also knowing its leaf secrets.
**A root secret always corresponds to a specific update at a specific leaf.** It is never a "merged" root secret. Instead, it is always the product of one member's path encryption. Other members decrypt it by traversing all the way from their leaf to the root.