diff --git a/doc/2026-10-12T14-33-36Z_phase_5_tags_documents/2026-10-12T14-33-36Z_phase_5_tags_documents.md b/doc/2026-10-12T14-33-36Z_phase_5_tags_documents/2026-10-12T14-33-36Z_phase_5_tags_documents.md new file mode 100644 index 0000000000..e68d81997c --- /dev/null +++ b/doc/2026-10-12T14-33-36Z_phase_5_tags_documents/2026-10-12T14-33-36Z_phase_5_tags_documents.md @@ -0,0 +1,247 @@ +# Phase 5: tags, documents, and search + +- Plan: [phased plan](../../2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md), section 10. +- Start commit: `c12448c9` (origin/main after Phase 3). +- Base branch `phase-5`. Tracks: `p5-tags` (P5.1, P5.2), then `p5-compact` (P5.3), `p5-docs` (P5.4, P5.6), `p5-search` (P5.5), `p5-alias` (P5.7). +- Decisions in force: tags are claims on any event or document ID, anyone may tag anything, attributed to the signing key; observed-remove clears; user subject is the first identity event (owner); aliases are tags shown contested, with server primary, prefix disambiguation; compaction by snapshot at a causal cut; content on removal kept. + +## Steps + +| Step | Track | Status | Commits | Tests | Notes | +| ---------------------------- | ------- | ------ | ---------------------- | -------------------------------------------- | --------------------------------- | +| P5.1 Observed-remove tags | tags | done | `c999190e`, `79efff10` | `tests/tag_claims.rs` (12) | S8 model; fixed by `0f3b7eaa` | +| P5.2 Tag index on tuple keys | tags | done | `9a91339b` | `tests/tag_index.rs` (4) | | +| P5.3 Compaction | compact | done | `79efff10` | `tests/tag_claims.rs` (16-case property) | in memory; closes #184 | +| P5.4 Documents | docs | done | `b36e26dc`, `9bcd86fa` | `tests/documents.rs` (5) | live editing not built | +| P5.5 Search | search | done | `7563e10d`, `edcdaf7a` | `tests/search.rs` (9) | over `tag_claims()` and the index | +| P5.6 Content on removal | docs | done | `781ac3b8`, `b3b63f1f` | `tests/content_removal.rs` (7) | decision 4: content kept; #195 | +| P5.7 Aliases as tags | alias | done | `e92c72de`, `c2af7b90` | `tests/aliases.rs` (7), `src/aliases.rs` (3) | #185, #160 open | +| Step | Track | Status | Commits | Tests | Notes | +| ---------------------------- | ------- | ------ | ---------------------- | -------------------------------------------- | --------------- | + +## Decisions + +- See above and the index. + +## Open questions + +- User tag subject needs an identity event (issue). + +## Changes to the plan + +- None yet. + +## Review notes and regression tests + +- To be filled. + +## End + +- Pending. + +--- + +## 2026-10-12T16-45-04Z Progress: tags on the signed event, and compaction + +Base: `b6f1a1d5` (phase-5). Track: `p5-bodies`. Commits, in order: + +- `c999190e`, `9a91339b`, merged at `b6f1a1d5`: P5.1 observed-remove tags, P5.2 tag index (earlier). +- `2250f804` `feat(rust): tag body inside the signed tag event [P5.4 prep, #182]`. +- `79efff10` `feat(rust): compaction of tag claims and clears [P5.3, #184]`. + +### Steps + +| Step | Status | Commits | Tests | +| ------------------------- | --------------- | ---------------------- | -------------------------------------------------------------------------------- | +| P5.1 Observed-remove tags | done | `c999190e` | S8 tests in `tests/tag_claims.rs` | +| P5.2 Tag index | done | `9a91339b` | `tests/tag_index.rs` | +| #182 Body in the event | done | `2250f804` | `test_two_replicas_that_exchange_only_events_converge_on_the_tag_set` | +| P5.3 Compaction (#184) | done, in memory | `79efff10` | `test_the_compacted_fold_agrees_with_the_causal_walk` (16 cases, 2 to 3 writers) | +| P5.4 Documents | done | `b36e26dc`, `9bcd86fa` | `tests/documents.rs` (5) | +| P5.5 Search | done | `7563e10d`, `edcdaf7a` | `tests/search.rs` (9) | +| P5.6 Content on removal | todo | | | +| P5.7 Aliases as tags | done | `e92c72de`, `c2af7b90` | `tests/aliases.rs` (7) | + +### Red, then green + +- #182. Before `2250f804`, a replica that received only event bytes, as sync does, had an empty tag set: `left: {}`, with two claims expected. After it, the test passes. +- P5.3. With `compacted_claims` stubbed to remove nothing, the property failed at the minimal case `seed = 0, writers = 2, steps = 17`. The fold then passed all 16 cases. The failing seed is kept in `tests/tag_claims.proptest-regressions`. + +### Decisions + +- **#182: the tag body is in the signed header.** A tag's operation is the `tag` field of `ChainExt`. The header signs it, so an event carries its whole tag. Sync moves events alone, and no body is fetched. A tag event takes no payload body, and a payload beside one is refused. The `tag_ops` table, its write path, and the body codec (`encode_op`, `decode_op`, `MAX_TAG_BODY_BYTES`) are removed. The store format is now v8. A v7 store holds tag events whose operation is not in the header, so it is refused. +- **Value limit: 512 bytes, was 1024.** The header decoder (p2panda `AnyHeader::decode`) declares text and byte strings at most 512 bytes long. A value is text inside the header, so a 1024-byte value could never decode. A clear names at most 256 claims, which is within the 512-element array limit. **Owner to confirm** the 512-byte value limit. +- **Compaction is an in-memory fold.** `compacted_claims` makes one pass over the parent links. Each event gets the live claims in its past. A clear removes the claims it names that are in its parents' sets, and removed claims are dropped from later sets. So the per-clear walk over history is gone, and every set is bounded by the live claims. `live_claims` stays as the reference. Nothing is deleted from the store: all events are kept, and no snapshot is written. The fold runs on each `tag_claims()` call. +- **A clear from an author who had not seen a claim leaves it live.** This is unchanged. The property checks it against the writers' own record of what they had seen. + +### Open questions + +- **#185 (clear authority): untouched.** Owner decision. Anyone may clear a claim their author had seen. +- **#160 (user subject): untouched.** Owner decision. It needs the identity event. +- **N33 snapshot at a causal cut: not done.** The fold is in memory and nothing is persisted. A snapshot needs a decision on what a new device receives and how voiding interacts with it. Retention is P8.2. +- **Group bodies have the same sync gap.** Sync sends header bytes only (`store_traits.rs`, the operation the sync protocol sends). A group operation's body does not travel either. This branch leaves group bodies alone. +- **Lints.** The new code adds pedantic warnings of the same kinds the crate already has (a generic hasher on `HashMap` parameters, and a long first doc paragraph). These are deferred to P8.8. + +### Test results + +- `cargo test --lib tag`: 115 passed. +- `cargo test --test tag_claims`: 10 passed. `--test tag_index`: 4 passed. +- `cargo test --lib`: 1104 passed, 0 failed, 3 ignored. +- The other integration suites that build events: `chain_properties` 12, `production_ingest` 10, `voiding_scenarios` 12, `voiding_properties` 2, `event_store_properties` 11 (1 ignored), `regression_replay` 8. All pass. + +### Changes to the plan + +- P5.3 was "snapshot at a causal cut, then the tail (N33)". This track does the fold part, and the persisted snapshot is still open. +- P5.4 is no longer blocked on the body: a tag carries its body. Its "content events" are unaffected. + +### Next + +P5.4 to P5.7 are not started. P5.4 needs the document content events on the same header pattern, if it uses the same extension. #185 and #160 wait on the owner. + +--- + +## 2026-10-12T17-16-20Z Progress: documents (P5.4) + +Base: `37a8344b` (phase-5). Track: `p5-docs`. Commits, in order: + +- `b36e26dc` `feat(rust): documents as signed events with content hashes [P5.4]` +- `9bcd86fa` `test(rust): documents converge over events and blob fetch [P5.4]` + +### Steps + +| Step | Status | Commits | Tests | +| -------------- | ------ | ---------------------- | ------------------------ | +| P5.4 Documents | done | `b36e26dc`, `9bcd86fa` | `tests/documents.rs` (5) | + +### Red, then green + +- Red. `tests/documents.rs` was written first. Its first build failed, because `id::documents` did not exist. With the types in place and `EventStore::documents` returning no rows, three tests failed at the record check (`left: 0`, `right: 1`). The signing check and the body refusal passed, as they should. +- Green. With `documents()` reading applied `document.put` events, `tests/documents.rs` passes 5 of 5. + +### Decisions + +- A document is a `document.put` event. Its header names the content by BLAKE3 hash, its size, and its media type (`ChainExt.document`, carried the same way the tag operation is, #182). The event takes no payload body, and a body beside it is refused on receipt. +- The bytes are a blob. iroh-blobs verifies them as they arrive, and the blob gate decides who may fetch them. A replica that keeps fetched bytes calls `DocumentRef::verify_content` first, which checks the length, then the hash. `blob_hash()` is the content hash, since both are BLAKE3 over the same bytes. +- Tags on a document are `tag.set` and `tag.clear` events whose subject is the document event's ID. A clear removes a tag claim, never the document, which stays in `documents()`. +- Store format: unchanged. The `document` field is left out of the encoding when it is `None`, so existing events keep their bytes. No version bump. +- Tag value limit: `MAX_VALUE_BYTES` stays at 512 (owner to confirm). Clear authority (#185) and the user subject (#160) are not touched. + +### Changes to the plan + +- The P5.4 row also asks for snapshots from the collab server, and a save on explicit save and on idle close. Not built. Nothing produces a `document.put` from the ProseMirror collab server. The trigger is task 10, item 6. +- Design §9.3's inline `json` and `bytes` payloads are not built. Bodies do not travel with sync (`store_traits.rs`), and the header holds byte strings of at most 512 bytes, so every document is a blob. +- The blob gate still has no reference index producer. The test gives `WorldAccess` a fixed table, as `tests/blob_gate.rs` does. +- The test hands event bytes to `EventStore::ingest`, the path sync takes once it has the bytes. It does not run a live `/id-sync/1` session. + +### Open + +- Two property tests fail on random seeds. Resolved by the discovery section below (`0f3b7eaa`). Both fail the same way on `37a8344b`, checked in a scratch copy of HEAD with its own target directory. Neither is caused by this track. + - `tests/tag_claims.rs::test_the_compacted_fold_agrees_with_the_causal_walk` (P5.3). Seeds `12233682913237194312` (writers 3, steps 32) and `14490625886382135617` (writers 3, steps 23). + - `tests/tag_claims.rs::test_the_live_set_is_the_oracle_under_any_delivery_order` (P5.1). Seed `9408785462023634370` (steps 28). + - The seeds are not in `tests/tag_claims.proptest-regressions`, which stays at HEAD. The fix belongs to the tags track, and the seeds go in as regressions with it. +- Lib-only build (`--no-default-features`) fails on `src/log_sync.rs:49-50` and `src/groups/worlds.rs:30`: `crate::world` and `crate::world_net` are not gated. The same imports are at HEAD. +- `Staged::keeps` in `src/event_store/ingest.rs` has no call sites at HEAD (a dead-code warning, not from this track). + +### Test results + +- `cargo test --lib`: 1108 passed, 0 failed, 3 ignored. Before this track it was 1104; the 4 new are the unit tests in `src/documents.rs`. +- `cargo test --test documents`: 5 passed. Before the query existed, 2 passed and 3 failed. +- Also pass: `tag_index` 4, `voiding_scenarios` 12, `voiding_properties` 2, `chain_properties` 12, `production_ingest` 10, `regression_replay` 8, `blob_gate` 8, `event_store_properties` 11 (1 ignored). +- `tag_claims`: 8 passed, 2 failed. The two failures are the random properties under Open. +- Clippy on the lib and the tests: no new warnings from this track. The one from the new test file, a redundant clone, is removed. + +### Next + +- P5.5 search reads `tag_claims()`, and needs nothing from documents. A document is the subject of ordinary claims. +- P5.6 content on removal: no code yet. `documents()` keeps a document until its record says otherwise. The removal path is not tested here. +- P5.7 aliases are tags. The server primary alias needs a decision. +- Still open: the blob reference index producer, and the collab-server trigger for document events. + +## 2026-10-12T20-04-02Z Discovery: the tag property failures were in the test history generator + +Both properties failed at `37a8344b`, and the cause was in the oracle side, not the fold or the store. `history()` in `tests/tag_claims.rs` shadowed the writer count with a clear's claim count, so a clear's `after` named only the first 1 to 3 writers. A writer could have seen events its clear did not name. The oracle counts everything the author had seen, but the causal past read from the parent links did not include them. The fold and the causal walk agreed on every history, including the failing ones. + +- Sweep over 5000 histories: with the shadow, the walk and the fold agree on all, and the fold differs from the oracle on 148. With the rename, there are no mismatches. +- Red, then green: `a1304850` adds the regressions and fails on both properties and both named tests. `0f3b7eaa` renames the variable, and everything passes. +- The regression file keeps `cc 0759f56f…`. It replays under both properties. `test_the_regression_histories_reach_the_oracle_through_every_path` runs the two histories from the task in every test run. `test_each_event_names_every_event_its_author_had_seen` checks each event's causal past against its author's record. +- `PROPTEST_RNG_SEED` selects the runner's RNG, not the input. The `(seed, steps, writers)` triples in the task are the inputs to `history()`, and the named tests use them directly. +- Suites after the fix: `cargo test --lib tag` 115 passed, `--test tag_claims` 12 passed (the 10 existing plus 2), `--test tag_index` 4 passed, `cargo test --lib` 1104 passed, 3 ignored. The 256-case runs of both properties pass, using a scratch copy with the case count set to 256, since the explicit `cases` in the config overrides `PROPTEST_CASES`. + +## 2026-10-12T20-18-28Z Progress: search (P5.5) + +| P5.5 Search | done | `7563e10d`, `edcdaf7a` | `tests/search.rs` (9) | +| P5.7 Aliases as tags | done | `e92c72de`, `c2af7b90` | `tests/aliases.rs` (7) | +Base: `f42c549c` (phase-5). Track: `p5-search`. Commits, in order: + +- `7563e10d` `test(rust): search by tag name and value over live claims [P5.5]` +- `edcdaf7a` `feat(rust): search over the tag index [P5.5]` +- This record: `docs(id): phase 5 search [phase 5]` + +### Steps + +| Step | Status | Commits | Tests | +| ---- | ------ | ------- | ----- | + +### Red, then green + +- Red. `tests/search.rs` was written first. Its build failed with `unresolved import id::search`. +- Green. `src/search.rs` and `TagIndex::named` went in. Two of the nine failed on the first run, both from errors in the test expectations, not in the search. A bare tag's subject order is by digest bytes, not by the letters I used. The first hit is the lowest subject, which is not the subject I had picked. Both expectations were corrected in `edcdaf7a`, and the search code did not change. +- Planted bug. `TagIndex::named` was changed to `starts_with`, so the name `a` matches `a\0b`. The whole-field test and the property both failed. The change was reverted. + +### Decisions + +- **A search is a query over the live set.** `search` takes the claims from `tag_claims()`, builds the `TagIndex` over them, and reads it. `search_store` does the same from an `EventStore`. The index is rebuilt on each call (#183). Nothing is persisted. +- **"Prefix" is a tuple field prefix, matched as whole fields.** The design's prefix scans are over the leading fields of a key. Each field ends with `00 00`, so the value `a` does not match `a\0b`, and the name `a` does not match `a\0b`. A string prefix such as `ci` for `city` is not offered. Under the terminator rule, `a` would match `a\0b` as a string prefix, which the requirement forbids. **Open** for the owner, if a string prefix is wanted. +- **Matching.** `ValueMatch::Any` matches any value and the bare tag. `Bare` matches only the bare tag. `Exact(v)` matches only `v`. Multi-term AND is not built. The search takes one name. +- **Results.** Each `Hit` is a subject with the live claims that matched on it, so a contested tag returns both values. Hits are ordered by subject ID bytes, and each hit's claims by claim ID bytes. The subject can be an identity event or a document's `document.put` event ID. +- **Full-text search is out of scope.** Task 06 says so, and the plan does not schedule it. Nothing was added. + +### Test results + +- `cargo test --test search`: 9 passed, including `test_the_search_equals_a_filter_over_the_live_set` (16 cases). +- `cargo test --lib tag_index`: 1 passed (the new unit test). `cargo test --test tag_index`: 4 passed. +- `cargo test --lib`: 1109 passed, 0 failed, 3 ignored. The P5.4 record has 1108, so this step adds the one unit test. +- Clippy (`--lib --test search --test tag_index`): no warnings in `src/search.rs`, `src/tag_index.rs`, or `tests/search.rs`. The lib still reports its existing pedantic warnings, which were not counted against the base. + +### Open + +- Search by author and by kind (design §9.4) is not built. The index has no author key. +- Multi-term AND (task 06, item 3) is not built. +- The CLI `tag search` is not wired to `search`. +- The index is still rebuilt on each call (#183). +- Pre-existing, not from this step: `Staged::keeps` has no call sites (a dead-code warning). + +### Next + +P5.5 is complete, so P5.7 can use `search` for aliases. P5.6 content on removal is not started. + +## 2026-10-12T20-18-39Z Progress: aliases as tags (P5.7) + +Base: `f42c549c` (phase-5). Track: `p5-alias`. Commits, in order: + +- `e92c72de` `test(rust): aliases as tag claims, contested and prefix-shown [P5.7]` +- `c2af7b90` `feat(rust): alias display over tag claims and the server primary alias [P5.7]` +- this record: `docs(id): phase 5 aliases [phase 5]` + | Step | Status | Commits | Tests | + | -------------------- | ------ | ---------------------- | ------------------------------------------------------------------- | +- Red: `tests/aliases.rs` was committed with `src/aliases.rs` stubbed to the final API (no aliases, no rows). All 7 tests failed on their assertions (for example `left: 0`, `right: 1`). +- Green: `tests/aliases.rs` 7 of 7 passed. `cargo test --lib`: 1111 passed, 0 failed, 3 ignored (1108 before, plus the 3 unit tests). +- **An alias is a `tag.set` named `alias`, whose value is its text.** It is attributed to the signing key. Its subject is the object's ID. +- **A group's subject is its create event ID.** That is the group ID the server config computes, so a group's stored primary alias is read by that ID (`ServerConfig::primary_alias`). +- **Display order, per object:** a pet name first, then the stored server primary, then one alias claim shown alone, then, for two or more claims, contested. Nothing is picked from the claims. The full set is always in the row. +- **The pet name is an input to the view.** It is a map from subject to name, held by the caller. It is not an event and is not stored here. +- **Nothing is unique.** Two objects may claim one alias, and both are returned. +- **Prefix:** the shortest prefix of the hex ID that no other row in the view starts with, at least 7 digits, as git shows short IDs. The full ID is shown when no prefix is unique. The 7-digit minimum is my choice, not from the decisions. Owner to confirm. +- **Server alias fallback** is read as the stored primary, which sits below the pet name. When there is no primary, the claims are shown contested. The design's separate idea, that the server shows its own alias as a fallback, is "meaning to confirm" and is not built. + +### Not built (open) + +- **#185, who may clear an alias claim.** Untouched. An alias is cleared by the existing observed-remove rule. +- **#160, the user subject.** No identity event exists, so a user's subject is not defined. A user's primary alias is keyed by account key in the config and is not looked up. Only groups get a primary. +- **Creation date.** The design shows each alias's date. The signed header has no time field (p2panda-core 0.7.1), so the date is not shown. Adding one changes the signed format, so it needs an owner decision. +- **Where pet names are stored.** Not decided. This module takes them as input. + +### Changes to the plan + +- None to the phase. No store format change and no dependency change. +- #185 and #160 wait on the owner. The creation-date question is new and needs a decision. diff --git a/pkgs/id/src/aliases.rs b/pkgs/id/src/aliases.rs new file mode 100644 index 0000000000..7192847345 --- /dev/null +++ b/pkgs/id/src/aliases.rs @@ -0,0 +1,229 @@ +//! Alias display over tag claims (Phase 5, P5.7; owner decisions 2026-10-12). +//! +//! An alias is a tag claim named [`ALIAS_NAME`], whose value is the alias text. Its subject is the +//! object's ID: a group's create event, or a user's first identity event (#160, not yet built). +//! This module is the one place that decides what a view shows for an object's aliases. +//! +//! The rules, in order: +//! +//! - A pet name, which this client's owner set, is shown first. It is local and adds no claim. +//! - Otherwise the server's stored primary alias is shown, as one value. Only groups have one for +//! now, because a user's primary is keyed by account key and no user subject exists yet (#160). +//! - Otherwise, one alias claim is shown alone, and two or more are shown as contested. Nothing is +//! picked silently. The full set is always in [`Row::aliases`]. +//! +//! Nothing is unique. Two objects may claim the same alias, and both are returned. Each row shows a +//! prefix of its ID, the shortest one that no other row in the view shares, so the rows can be told +//! apart. The creation date is not shown, because the signed header has no time field (open). + +use std::collections::BTreeMap; + +use p2panda_core::Hash; + +use crate::server_config::{Object, ServerConfig}; +use crate::tag_claims::Claim; +use crate::waiting::AuthorKey; + +/// The tag name an alias claim carries. Its value is the alias text. +pub const ALIAS_NAME: &str = "alias"; + +/// The fewest hex digits a row's prefix has, as git shows short IDs. +const MIN_PREFIX: usize = 7; + +/// One alias claim on an object. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Alias { + /// The claim's ID: the `tag.set` event that made it. + pub claim: Hash, + /// The alias text. + pub text: String, + /// The key that made the claim. + pub author: AuthorKey, +} + +/// What a view shows as an object's alias. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Shown { + /// The owner's pet name for the object: a local name that only this client sees. + PetName(String), + /// The server's stored primary alias. + Primary(String), + /// The only alias claim on the object. + Only(Alias), + /// Two or more alias claims, none picked. The full set is in [`Row::aliases`]. + Contested, + /// No alias claim and no primary alias, so the name stands alone. + Unnamed, +} + +/// An object in a view: its ID and its official name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Named { + /// The object's subject: the ID its alias claims name. + pub subject: Hash, + /// The official name. + pub name: String, +} + +/// One object as a view shows it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + /// The object's subject. + pub subject: Hash, + /// The official name. + pub name: String, + /// The shortest prefix of the subject's hex ID that no other row in the view shares. When no + /// prefix is unique, which needs two rows with the same subject, it is the full ID. + pub prefix: String, + /// What the view shows as the object's alias. + pub shown: Shown, + /// Every alias claim on the object, in claim order. + pub aliases: Vec, +} + +/// The alias claims on `subject`, in claim order. A bare tag, or an alias with empty text, is not +/// an alias. +#[must_use] +pub fn aliases_of(claims: &[Claim], subject: &Hash) -> Vec { + claims + .iter() + .filter(|claim| claim.subject == *subject && claim.name == ALIAS_NAME) + .filter_map(|claim| { + let text = claim.value.as_deref().filter(|text| !text.is_empty())?; + Some(Alias { + claim: claim.id, + text: text.to_owned(), + author: claim.author, + }) + }) + .collect() +} + +/// The rows of a view over `named`, with the rules above. `server` is the server config, if this +/// server has one. `pet_names` maps a subject to the owner's pet name for it. +#[must_use] +pub fn rows( + named: &[Named], + claims: &[Claim], + server: Option<&ServerConfig>, + pet_names: &BTreeMap, +) -> Vec { + let hexes: Vec = named.iter().map(|object| object.subject.to_hex()).collect(); + named + .iter() + .enumerate() + .map(|(index, object)| { + let aliases = aliases_of(claims, &object.subject); + // A group's subject is its create event ID, which is the config's group ID. + let primary = + server.and_then(|config| config.primary_alias(&Object::Group(object.subject))); + let pet = pet_names.get(&object.subject).map(String::as_str); + Row { + subject: object.subject, + name: object.name.clone(), + prefix: shortest_prefix(index, &hexes), + shown: shown_for(pet, primary, &aliases), + aliases, + } + }) + .collect() +} + +/// What a view shows as one object's alias: the pet name, then the primary, then the claims. +fn shown_for(pet: Option<&str>, primary: Option<&str>, aliases: &[Alias]) -> Shown { + if let Some(name) = pet { + return Shown::PetName(name.to_owned()); + } + if let Some(text) = primary { + return Shown::Primary(text.to_owned()); + } + match aliases { + [] => Shown::Unnamed, + [only] => Shown::Only(only.clone()), + _ => Shown::Contested, + } +} + +/// The shortest prefix of `hexes[index]`, at least [`MIN_PREFIX`] digits, that no other entry +/// starts with. The full ID when no prefix is unique. +fn shortest_prefix(index: usize, hexes: &[String]) -> String { + let own = hexes[index].as_str(); + (MIN_PREFIX..=own.len()) + .map(|length| &own[..length]) + .find(|prefix| { + hexes + .iter() + .enumerate() + .all(|(other, hex)| other == index || !hex.starts_with(prefix)) + }) + .unwrap_or(own) + .to_owned() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn claim(n: u8, subject: Hash, name: &str, value: Option<&str>) -> Claim { + Claim { + id: Hash::digest([n]), + author: [n; 32], + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + } + } + + #[test] + fn test_a_bare_or_empty_alias_is_not_an_alias() { + let subject = Hash::digest(b"ann"); + let claims = [ + claim(1, subject, ALIAS_NAME, None), + claim(2, subject, ALIAS_NAME, Some("")), + claim(3, subject, "seen", Some("Ann")), + claim(4, Hash::digest(b"bo"), ALIAS_NAME, Some("Ann")), + ]; + assert!(aliases_of(&claims, &subject).is_empty()); + } + + #[test] + fn test_the_pet_name_wins_over_the_primary_and_the_primary_over_the_claims() { + let alias = Alias { + claim: Hash::digest(b"claim"), + text: "Ann".to_owned(), + author: [1; 32], + }; + let two = [alias.clone(), alias.clone()]; + assert_eq!( + shown_for(Some("Mine"), Some("team"), &two), + Shown::PetName("Mine".to_owned()) + ); + assert_eq!( + shown_for(None, Some("team"), &two), + Shown::Primary("team".to_owned()) + ); + assert_eq!(shown_for(None, None, &two), Shown::Contested); + assert_eq!( + shown_for(None, None, std::slice::from_ref(&alias)), + Shown::Only(alias) + ); + assert_eq!(shown_for(None, None, &[]), Shown::Unnamed); + } + + #[test] + fn test_a_lone_row_shows_the_minimum_prefix() { + let subject = Hash::digest(b"ann"); + let view = rows( + &[Named { + subject, + name: "ann".to_owned(), + }], + &[], + None, + &BTreeMap::new(), + ); + assert_eq!(view[0].prefix.len(), MIN_PREFIX); + assert!(subject.to_hex().starts_with(&view[0].prefix)); + } +} diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs index 7b8240dbcd..423b5f8b55 100644 --- a/pkgs/id/src/chain.rs +++ b/pkgs/id/src/chain.rs @@ -22,6 +22,9 @@ use p2panda_core::{AnyHeader, Hash, Header, HeaderError, SeqNum, SigningKey}; use serde::{Deserialize, Serialize}; use unicode_normalization::is_nfc; +use crate::documents::{DocumentRef, is_document_kind, is_removal_kind}; +use crate::tag_claims::{TagOp, check_op, is_tag_kind}; + /// The domain tag every `ChainExt` carries, so this header type cannot be /// confused with another protocol's. pub const DOMAIN_TAG: &str = "id.events.v1"; @@ -102,10 +105,21 @@ pub struct ChainExt { /// author had seen when writing this one. At most [`MAX_AFTER`] hashes, none /// repeated. pub after: Vec, + /// The tag operation of a `tag.set` or `tag.clear`, and `None` for every other + /// kind. It is the tag's body (#182): it is signed with the header, so an event + /// carries its tag, and sync needs no separate body. + pub tag: Option, + /// The document of a `document.put`, and `None` for every other kind. It names the content by + /// hash and size, and the bytes are a blob (P5.4). It is signed with the header. + pub document: Option, + /// The ID of the `document.put` a `document.remove` removes, and `None` for every other kind. + /// It is signed with the header (P5.6). + pub removes: Option, } /// The wire form of [`ChainExt`]: the same fields, plus the domain tag. Keys -/// this form does not name are refused. +/// this form does not name are refused. `tag`, `document` and `removes` are left +/// out when they are `None`, so events of other kinds keep their encoding. #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Wire { @@ -113,6 +127,12 @@ struct Wire { kind: String, group: Option, after: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + tag: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + document: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + removes: Option, } impl From for Wire { @@ -122,6 +142,9 @@ impl From for Wire { kind: ext.kind, group: ext.group, after: ext.after, + tag: ext.tag, + document: ext.document, + removes: ext.removes, } } } @@ -137,6 +160,9 @@ impl TryFrom for ChainExt { kind: wire.kind, group: wire.group, after: wire.after, + tag: wire.tag, + document: wire.document, + removes: wire.removes, }; ext.validate()?; Ok(ext) @@ -151,7 +177,12 @@ impl ChainExt { /// /// Refuses more than [`MAX_AFTER`] `after` hashes, a hash repeated in /// `after`, a `kind` that is empty or longer than [`MAX_KIND_BYTES`], and a - /// `kind` that is not NFC. + /// `kind` that is not NFC. A tag kind must carry a tag operation that fits + /// its kind, and any other kind must carry none. A document kind must carry + /// a document that passes [`DocumentRef::check`], and any other kind must + /// carry none. A removal kind must name the document it removes, and any + /// other kind must name none. A removal carries no tag and no document, as + /// any kind that is not a tag or a document kind must not. pub fn validate(&self) -> Result<(), ChainError> { if self.after.len() > MAX_AFTER { return Err(ChainError::TooManyAfter(self.after.len())); @@ -167,6 +198,60 @@ impl ChainExt { if !is_nfc(&self.kind) { return Err(ChainError::KindNotNfc); } + match (is_tag_kind(&self.kind), &self.tag) { + (false, None) => {} + (false, Some(_)) => { + return Err(ChainError::Extension(format!( + "kind {:?} carries a tag operation", + self.kind + ))); + } + (true, None) => { + return Err(ChainError::Extension(format!( + "kind {:?} needs its tag operation", + self.kind + ))); + } + (true, Some(op)) => { + check_op(&self.kind, op).map_err(|err| ChainError::Extension(err.to_string()))?; + } + } + match (is_document_kind(&self.kind), &self.document) { + (false, None) => {} + (false, Some(_)) => { + return Err(ChainError::Extension(format!( + "kind {:?} carries a document", + self.kind + ))); + } + (true, None) => { + return Err(ChainError::Extension(format!( + "kind {:?} needs its document", + self.kind + ))); + } + (true, Some(document)) => { + document + .check() + .map_err(|err| ChainError::Extension(err.to_string()))?; + } + } + match (is_removal_kind(&self.kind), &self.removes) { + (false, None) => {} + (false, Some(_)) => { + return Err(ChainError::Extension(format!( + "kind {:?} names a removed document", + self.kind + ))); + } + (true, None) => { + return Err(ChainError::Extension(format!( + "kind {:?} needs the document it removes", + self.kind + ))); + } + (true, Some(_)) => {} + } Ok(()) } } @@ -316,6 +401,9 @@ mod tests { kind: kind.to_owned(), group, after, + tag: None, + document: None, + removes: None, } } @@ -790,6 +878,9 @@ mod golden { kind: "group.policy".to_owned(), group: None, after: vec![Hash::digest(b"a"), Hash::digest(b"b")], + tag: None, + document: None, + removes: None, }, ) .unwrap(); @@ -803,6 +894,9 @@ mod golden { kind: "message".to_owned(), group: Some(Hash::digest(b"g")), after: vec![first.id], + tag: None, + document: None, + removes: None, }, ) .unwrap(); diff --git a/pkgs/id/src/documents.rs b/pkgs/id/src/documents.rs new file mode 100644 index 0000000000..49949b1fa6 --- /dev/null +++ b/pkgs/id/src/documents.rs @@ -0,0 +1,220 @@ +//! Documents as signed events over content hashes (Phase 5, P5.4; design §9.3). +//! +//! A document is a `document.put` event. Its header names the content by BLAKE3 hash and size, +//! and the media type, in a [`DocumentRef`]. The header carries it as the tag operation does +//! (#182), so the event is signed with its document and sync moves the event alone. The bytes +//! are not in the event. They are a blob, which iroh-blobs moves on request through the gate in +//! [`crate::blob_gate`]. +//! +//! A replica that stores fetched bytes checks them with [`DocumentRef::verify_content`] first. Bytes +//! whose length or hash differ from the document's are refused. +//! +//! Tags on a document are ordinary `tag.set` and `tag.clear` events whose subject is the document +//! event's ID, so they follow the tag model in [`crate::tag_claims`]. A clear removes a tag claim, +//! never the document. +//! +//! Inline content (design §9.3, `json` and `bytes`) is not built. A body does not travel with +//! sync, and a header holds byte strings of at most 512 bytes, so content is always a blob here. +//! +//! Removal (P5.6, design decision 4) is a `document.remove` event that names the document's event +//! ID in its header. Content is kept: the removal is an event like any other, and it changes +//! neither the document's bytes nor its tags. Only the document's author's removal marks the +//! document, in [`DocumentRecord::removal`]. A removal from anyone else is stored and has no +//! effect. + +use p2panda_core::Hash; +use serde::{Deserialize, Serialize}; +use unicode_normalization::is_nfc; + +use crate::waiting::AuthorKey; + +/// The kind of a `document.put` event, as the header's `kind` names it. +pub const DOCUMENT_KIND: &str = "document.put"; + +/// The kind of a `document.remove` event, which names the document it removes in its header. +pub const REMOVAL_KIND: &str = "document.remove"; + +/// The most bytes a media type may have. A media type is at least one byte. +pub const MAX_MEDIA_TYPE_BYTES: usize = 128; + +/// A document's content, as its `document.put` event names it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DocumentRef { + /// The media type of the content, for example `text/markdown`. NFC, 1 to 128 bytes. + pub media_type: String, + /// The BLAKE3 hash of the content. It is also the blob's hash. + pub content: Hash, + /// The content's length in bytes. + pub size: u64, +} + +/// Why a document was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum DocumentError { + /// The media type is empty, longer than [`MAX_MEDIA_TYPE_BYTES`], or not NFC. + #[error("{0}")] + MediaType(String), + /// The content is not the length the document names. + #[error("the content is {actual} bytes, the document names {named}")] + Size { + /// The length the document names. + named: u64, + /// The length of the content. + actual: u64, + }, + /// The content does not hash to the document's content hash. + #[error("the content does not hash to the document's content hash")] + Hash, +} + +/// Whether `kind` is the document kind, so its event carries a document. +#[must_use] +pub fn is_document_kind(kind: &str) -> bool { + kind == DOCUMENT_KIND +} + +/// Whether `kind` is the removal kind, so its event carries the ID of the document it removes. +#[must_use] +pub fn is_removal_kind(kind: &str) -> bool { + kind == REMOVAL_KIND +} + +impl DocumentRef { + /// The reference to `bytes`, as a document of `media_type`. + /// + /// # Errors + /// + /// Returns [`DocumentError::MediaType`] for a media type that [`DocumentRef::check`] refuses. + pub fn for_bytes(media_type: &str, bytes: &[u8]) -> Result { + let doc = Self { + media_type: media_type.to_owned(), + content: Hash::digest(bytes), + size: len_of(bytes), + }; + doc.check()?; + Ok(doc) + } + + /// Checks the rules every document reference meets. The builder and the decoder both apply + /// them, so a signed document always passes them on receipt. + /// + /// # Errors + /// + /// Returns [`DocumentError::MediaType`] for a media type that is empty, longer than + /// [`MAX_MEDIA_TYPE_BYTES`], or not NFC. + pub fn check(&self) -> Result<(), DocumentError> { + let length = self.media_type.len(); + if !(1..=MAX_MEDIA_TYPE_BYTES).contains(&length) { + return Err(DocumentError::MediaType(format!( + "the media type is {length} bytes, it must be 1 to {MAX_MEDIA_TYPE_BYTES}" + ))); + } + if !is_nfc(&self.media_type) { + return Err(DocumentError::MediaType( + "the media type is not NFC".to_owned(), + )); + } + Ok(()) + } + + /// Checks `bytes` against the reference: the length first, then the hash. + /// + /// # Errors + /// + /// Returns [`DocumentError::Size`] when the length differs, and [`DocumentError::Hash`] when + /// the bytes do not hash to the content hash. + pub fn verify_content(&self, bytes: &[u8]) -> Result<(), DocumentError> { + let actual = len_of(bytes); + if actual != self.size { + return Err(DocumentError::Size { + named: self.size, + actual, + }); + } + if Hash::digest(bytes) != self.content { + return Err(DocumentError::Hash); + } + Ok(()) + } + + /// The content hash as an iroh-blobs hash. It names the blob that holds the content. + #[must_use] + pub fn blob_hash(&self) -> iroh_blobs::Hash { + iroh_blobs::Hash::from_bytes(*self.content.as_bytes()) + } +} + +/// The length of `bytes`. A slice is never longer than `u64::MAX` bytes. +fn len_of(bytes: &[u8]) -> u64 { + u64::try_from(bytes.len()).unwrap_or(u64::MAX) +} + +/// A document in the store: its `document.put` event, the key that signed it, its content, and +/// the removal the author made of it, if any. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DocumentRecord { + /// The document's ID: the `document.put` event's ID. Tags name it as their subject. + pub id: Hash, + /// The key that signed the document event. + pub author: AuthorKey, + /// The content the event names. Removal keeps it (decision 4). + pub document: DocumentRef, + /// The ID of the `document.remove` event the author signed for this document, if the author + /// has removed it. When the author has signed more than one, this is the lowest ID. + pub removal: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn test_the_content_is_checked_by_its_length_and_its_hash() { + let body = b"quarterly figures"; + let doc = DocumentRef::for_bytes("text/plain", body).unwrap(); + assert!(doc.verify_content(body).is_ok()); + // Same length, one byte changed: the hash refuses it. + assert_eq!( + doc.verify_content(b"quarterly figurez"), + Err(DocumentError::Hash) + ); + // A prefix: the length refuses it before any hash is taken. + assert!(matches!( + doc.verify_content(&body[..body.len() - 1]), + Err(DocumentError::Size { .. }) + )); + } + + #[test] + fn test_a_reference_that_names_the_wrong_length_is_refused() { + let body = b"quarterly figures"; + let doc = DocumentRef { + size: 3, + ..DocumentRef::for_bytes("text/plain", body).unwrap() + }; + assert!(matches!( + doc.verify_content(body), + Err(DocumentError::Size { named: 3, .. }) + )); + } + + #[test] + fn test_the_media_type_is_one_to_128_bytes_in_nfc() { + assert!(DocumentRef::for_bytes("", b"x").is_err()); + let longest = "m".repeat(MAX_MEDIA_TYPE_BYTES); + assert!(DocumentRef::for_bytes(&longest, b"x").is_ok()); + let too_long = "m".repeat(MAX_MEDIA_TYPE_BYTES + 1); + assert!(DocumentRef::for_bytes(&too_long, b"x").is_err()); + // "e" and a combining acute accent is NFD, not NFC. + assert!(DocumentRef::for_bytes("e\u{301}", b"x").is_err()); + } + + #[test] + fn test_the_blob_hash_is_the_content_hash_of_the_bytes() { + let body = b"the same bytes, hashed two ways"; + let doc = DocumentRef::for_bytes("text/plain", body).unwrap(); + assert_eq!(doc.blob_hash(), iroh_blobs::Hash::new(body)); + } +} diff --git a/pkgs/id/src/event_store/claims.rs b/pkgs/id/src/event_store/claims.rs new file mode 100644 index 0000000000..f05a9f9a42 --- /dev/null +++ b/pkgs/id/src/event_store/claims.rs @@ -0,0 +1,87 @@ +//! Tag claims over the store (Phase 5, P5.1 and P5.2). +//! +//! A tag event is applied like any content event: the resolution decides whether it applies, and +//! the store keeps it either way. Its operation is in its header (#182), so the stored event +//! carries the claim or the clear. [`EventStore::tag_claims`] reads the applied tag events and +//! folds them with the parent links of every event the store holds. A clear's causal past is read +//! from those links, so it covers the events the clear's author had seen. + +use std::collections::HashMap; + +use p2panda_core::Hash; +use redb::{ReadableDatabase, ReadableTable}; + +use super::resolve::author_of; +use super::{APPLIED, EVENTS, EventStore, PROOF_HEADERS, StoreError, corrupt, decode_stored}; +use crate::chain::Event; +use crate::tag_claims::{Applied, Claim, compacted_claims, is_tag_kind}; +use crate::tag_index::TagIndex; + +/// The events an event names: its `after` hashes, and its backlink. +fn parents_of(event: &Event) -> Vec { + event + .header + .extensions + .after + .iter() + .copied() + .chain(event.header.backlink) + .collect() +} + +impl EventStore { + /// The live claims in the store: each applied `tag.set` that no applied `tag.clear` removes. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`] for a stored tag event + /// that carries no tag operation for its kind. + pub fn tag_claims(&self) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let events = txn.open_table(EVENTS)?; + let applied_table = txn.open_table(APPLIED)?; + + let mut parents: HashMap> = HashMap::new(); + let mut applied = Vec::new(); + for row in events.iter()? { + let (_position, bytes) = row?; + let event = decode_stored(bytes.value())?; + parents.insert(event.id, parents_of(&event)); + if !is_tag_kind(&event.header.extensions.kind) + || applied_table.get(event.id.as_bytes().as_slice())?.is_none() + { + continue; + } + let Some(op) = event.header.extensions.tag.clone() else { + return Err(corrupt( + "a stored tag event carries no tag operation".to_owned(), + )); + }; + applied.push(Applied { + id: event.id, + author: author_of(&event), + op, + }); + } + // A fork proof header is present, so a clear may name it, and it has parents. It never + // applies, so it only extends the parent links. + let headers = txn.open_table(PROOF_HEADERS)?; + for row in headers.iter()? { + let (_hash, bytes) = row?; + let header = decode_stored(bytes.value())?; + parents + .entry(header.id) + .or_insert_with(|| parents_of(&header)); + } + Ok(compacted_claims(&applied, &parents)) + } + + /// The tag index over the live claims, built from [`EventStore::tag_claims`]. + /// + /// # Errors + /// + /// Returns the errors of [`EventStore::tag_claims`]. + pub fn tag_index(&self) -> Result { + Ok(TagIndex::new(&self.tag_claims()?)) + } +} diff --git a/pkgs/id/src/event_store/documents.rs b/pkgs/id/src/event_store/documents.rs new file mode 100644 index 0000000000..f0a8a3571d --- /dev/null +++ b/pkgs/id/src/event_store/documents.rs @@ -0,0 +1,87 @@ +//! Documents over the event store (Phase 5, P5.4 and P5.6). +//! +//! A document is its `document.put` event. The event applies like any content event, and the store +//! keeps it either way. Its content is a blob that the store does not hold: the header names it by +//! hash, and the bytes come from iroh-blobs on request. Tags on a document are tag events in the +//! same store, read by [`EventStore::tag_claims`], so they need nothing here. +//! +//! A removal (P5.6) is a `document.remove` event in the same store. It is kept like any other event, +//! and it does not change the document or its tags. [`EventStore::documents`] marks the document +//! with it, when the document's own author signed it. + +use std::collections::BTreeMap; + +use p2panda_core::Hash; +use redb::{ReadableDatabase, ReadableTable}; + +use super::resolve::author_of; +use super::{APPLIED, EVENTS, EventStore, StoreError, corrupt, decode_stored}; +use crate::documents::{DOCUMENT_KIND, DocumentRecord, REMOVAL_KIND}; +use crate::waiting::AuthorKey; + +impl EventStore { + /// The documents in the store: each applied `document.put`, sorted by event ID. A document + /// carries the ID of its author's removal, if the author has signed one (P5.6). A removal by + /// anyone else has no effect on the record. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`] for a stored document + /// event that carries no document, or a stored removal that names no document. + pub fn documents(&self) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let events = txn.open_table(EVENTS)?; + let applied_table = txn.open_table(APPLIED)?; + + let mut records = Vec::new(); + // The lowest applied removal for each (document, author) pair. Its key is the document's + // event ID and the author who signed the removal. + let mut removals: BTreeMap<([u8; 32], AuthorKey), Hash> = BTreeMap::new(); + for row in events.iter()? { + let (_position, bytes) = row?; + let event = decode_stored(bytes.value())?; + if applied_table.get(event.id.as_bytes().as_slice())?.is_none() { + continue; + } + let kind = event.header.extensions.kind.as_str(); + if kind == REMOVAL_KIND { + let Some(target) = event.header.extensions.removes else { + return Err(corrupt( + "a stored removal event names no document".to_owned(), + )); + }; + let key = (*target.as_bytes(), author_of(&event)); + removals + .entry(key) + .and_modify(|lowest| { + if event.id.as_bytes() < lowest.as_bytes() { + *lowest = event.id; + } + }) + .or_insert(event.id); + continue; + } + if kind != DOCUMENT_KIND { + continue; + } + let Some(document) = event.header.extensions.document.clone() else { + return Err(corrupt( + "a stored document event carries no document".to_owned(), + )); + }; + records.push(DocumentRecord { + id: event.id, + author: author_of(&event), + document, + removal: None, + }); + } + for record in &mut records { + record.removal = removals + .get(&(*record.id.as_bytes(), record.author)) + .copied(); + } + records.sort_by_key(|record| *record.id.as_bytes()); + Ok(records) + } +} diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index da52179f2e..2a57171255 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -97,8 +97,10 @@ use super::{ store_event, store_fork, }; use crate::chain::{self, Event}; +use crate::documents::{is_document_kind, is_removal_kind}; use crate::membership::AuthId; use crate::membership::body::decode_body; +use crate::tag_claims::is_tag_kind; use crate::waiting::{AuthorKey, WaitingPool}; /// Why an event was refused. A refused event changes nothing. @@ -202,6 +204,13 @@ impl EventStore { /// - A body that is not a group operation, or no body at all, makes the event content. /// - A body that claims to be a group operation decodes to its action, or it is refused. /// - A body that is not the one the header commits to, by BLAKE3 hash and size, is refused. + /// - A tag event (kind `tag.set` or `tag.clear`) takes no body. Its operation is in its + /// header (#182), so a payload on a tag event is refused. Its tag takes no membership + /// action, and the fold reads it from the stored header (see `claims`). + /// - A document event (kind `document.put`) takes no body either. Its content is a blob that + /// the header names by hash, so a payload beside it is refused (P5.4). + /// - A removal event (kind `document.remove`) takes no body. It names its document in its + /// header, so a payload beside it is refused (P5.6). /// /// # Errors /// @@ -216,9 +225,20 @@ impl EventStore { Ok(event) => event, Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; - let action = match body_action(&event, body) { - Ok(action) => action, - Err(refusal) => return Ok(Ingest::Refused(refusal)), + let kind = &event.header.extensions.kind; + let action = if is_tag_kind(kind) || is_document_kind(kind) || is_removal_kind(kind) { + if body.is_some() { + return Ok(Ingest::Refused(Refusal::Malformed( + "a tag, document or removal event carries its content in its header, not in a body" + .to_owned(), + ))); + } + None + } else { + match body_action(&event, body) { + Ok(action) => action, + Err(refusal) => return Ok(Ingest::Refused(refusal)), + } }; self.ingest_event(event, action.as_ref(), now_ms) } @@ -380,14 +400,21 @@ fn body_action( let Some(body) = body else { return Ok(None); }; + committed(event, body)?; + decode_body(body).map_err(|err| Refusal::Malformed(err.to_string())) +} + +/// Refuses a body that is not the one the header commits to, by BLAKE3 hash and size. +fn committed(event: &Event, body: &[u8]) -> Result<(), Refusal> { let committed = event.header.payload_hash == Some(Hash::digest(body)) && u32::try_from(body.len()).is_ok_and(|len| len == event.header.payload_size); - if !committed { - return Err(Refusal::Malformed( + if committed { + Ok(()) + } else { + Err(Refusal::Malformed( "the body is not the one the header commits to, by hash and size".to_owned(), - )); + )) } - decode_body(body).map_err(|err| Refusal::Malformed(err.to_string())) } /// How a call labels the events it stores: applied, or voided. The label is the resolution's answer @@ -411,6 +438,20 @@ enum Staged { } impl Staged { + /// Whether the event is kept: stored, or held. A refused event and a fork are not. + fn keeps(&self) -> bool { + matches!( + self, + Self::Stored { .. } + | Self::Ready( + Ingest::Accepted { .. } + | Ingest::Voided { .. } + | Ingest::Duplicate { .. } + | Ingest::Waiting { .. }, + ) + ) + } + /// The outcome, with its labels read from the store as it is now. fn finish(self, txn: &WriteTransaction) -> Result { match self { @@ -1026,6 +1067,9 @@ mod tests { kind: kind.to_owned(), group: None, after, + tag: None, + document: None, + removes: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -1543,6 +1587,9 @@ mod tests { kind: "message".to_owned(), group: Some(group), after: Vec::new(), + tag: None, + document: None, + removes: None, }; sign(&signer, seq, backlink, None, ext).unwrap() }; diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index b5d23a7414..ea8b6476cc 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -59,6 +59,8 @@ use redb::{ use crate::chain::{self, Event}; +mod claims; +mod documents; mod ingest; pub mod range; mod resolve; @@ -78,7 +80,7 @@ pub const FILE_NAME: &str = "events.redb"; pub const TEMP_NAME: &str = "events.redb.tmp"; /// The format row in `meta`. A store with another format is refused. -const FORMAT: &[u8] = b"id.events.store.v6"; +const FORMAT: &[u8] = b"id.events.store.v8"; const FORMAT_KEY: &[u8] = b"format"; const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -1116,6 +1118,9 @@ mod tests { kind: kind.to_owned(), group, after: Vec::new(), + tag: None, + document: None, + removes: None, } } diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index baced14682..813928a678 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -536,6 +536,9 @@ mod tests { kind: "message".to_owned(), group: None, after: Vec::new(), + tag: None, + document: None, + removes: None, }; events.push(chain::sign(&key, seq, backlink, Some(body), ext).unwrap()); } @@ -654,6 +657,9 @@ mod tests { kind: "message".to_owned(), group: None, after: Vec::new(), + tag: None, + document: None, + removes: None, }, ) .unwrap(); @@ -693,6 +699,9 @@ mod tests { kind: "message".to_owned(), group: None, after: Vec::new(), + tag: None, + document: None, + removes: None, }, ) .unwrap(); diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 15f187e2e8..f57ffaa4bb 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -153,6 +153,7 @@ //! ``` pub mod access; +pub mod aliases; #[cfg(feature = "world")] pub mod artifact; pub mod blob_gate; @@ -171,6 +172,7 @@ pub mod directory_mail; #[cfg(feature = "world")] pub mod directory_view; pub mod discovery; +pub mod documents; #[cfg(feature = "world")] pub mod encryption; pub mod envelope_net; @@ -191,11 +193,14 @@ pub mod protocol; pub mod repl; #[cfg(feature = "sandbox")] pub mod sandbox; +pub mod search; #[cfg(feature = "world")] pub mod server_config; pub mod store; pub mod store_traits; pub mod sync_method; +pub mod tag_claims; +pub mod tag_index; pub mod tags; #[cfg(test)] mod test_forgeries; diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index fb059464a0..5d49ce2e2f 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -522,6 +522,9 @@ mod tests { kind: "message".to_owned(), group: Some(group), after: Vec::new(), + tag: None, + document: None, + removes: None, }; events.push(sign(signer, seq, backlink, None, ext).unwrap()); } @@ -745,6 +748,9 @@ mod tests { kind: "rival".to_owned(), group: Some(group(9)), after: Vec::new(), + tag: None, + document: None, + removes: None, }; let rival = sign(alice, 1, Some(honest[0].id), None, rival_ext).unwrap(); assert!(matches!( diff --git a/pkgs/id/src/search.rs b/pkgs/id/src/search.rs new file mode 100644 index 0000000000..a1faee823e --- /dev/null +++ b/pkgs/id/src/search.rs @@ -0,0 +1,90 @@ +//! Search by tag name and value over the live claims (Phase 5, P5.5; design §9.4). +//! +//! A search takes a name and a [`ValueMatch`], and returns each subject that has a live claim +//! matching them, as [`Hit`]s. It is a thin query: the live set comes from +//! [`EventStore::tag_claims`], and the answer from the [`TagIndex`] built over it. The index is +//! rebuilt on each call, as [`EventStore::tag_index`] rebuilds it (#183). Nothing is persisted here. +//! +//! A value matches as a whole field. The tuple encoding ends every field with `00 00`, so the value +//! `a` does not match `a\0b`, and the name `a` does not match `a\0b` either. The design's "prefix" +//! is a scan over the leading fields of a key, so a search has no string prefix such as `ci` for +//! `city`. Full-text search is out of scope for Phase 5 (task 06). +//! +//! Hits are ordered by subject ID bytes, and the claims of a hit by claim ID bytes. The answer does +//! not depend on the order the events arrived in. + +use std::collections::{BTreeMap, HashMap}; + +use p2panda_core::Hash; + +use crate::event_store::{EventStore, StoreError}; +use crate::tag_claims::Claim; +use crate::tag_index::TagIndex; + +/// Which values a search matches, for one tag name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ValueMatch<'a> { + /// Any value, and the bare tag. + Any, + /// Only the bare tag, which has no value. + Bare, + /// Only this value, matched as a whole field. + Exact(&'a str), +} + +/// A subject that a search matched, with the live claims that matched on it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Hit { + /// The subject: an event ID, such as an identity's or a document's. + pub subject: Hash, + /// The matching live claims, sorted by claim ID bytes. A contested tag gives more than one. + pub claims: Vec, +} + +/// The subjects with a live claim that matches `name` and `value`, among `claims`. +/// +/// `claims` is the live set, as [`EventStore::tag_claims`] returns it. The index over it answers the +/// query: an Ω scan on the value and the name for [`ValueMatch::Exact`] and [`ValueMatch::Bare`], +/// and a scan of the name for [`ValueMatch::Any`]. +#[must_use] +pub fn search(claims: &[Claim], name: &str, value: ValueMatch<'_>) -> Vec { + let index = TagIndex::new(claims); + let entries = match value { + ValueMatch::Any => index.named(name), + ValueMatch::Bare => index.value_name(None, name), + ValueMatch::Exact(text) => index.value_name(Some(text), name), + }; + let by_id: HashMap = claims.iter().map(|claim| (claim.id, claim)).collect(); + let mut hits: BTreeMap<[u8; 32], Hit> = BTreeMap::new(); + for entry in entries { + let Some(claim) = by_id.get(&entry.claim) else { + continue; + }; + hits.entry(*entry.subject.as_bytes()) + .or_insert_with(|| Hit { + subject: entry.subject, + claims: Vec::new(), + }) + .claims + .push((*claim).clone()); + } + hits.into_values() + .map(|mut hit| { + hit.claims.sort_by_key(|claim| *claim.id.as_bytes()); + hit + }) + .collect() +} + +/// The search over the store's live claims, read by [`EventStore::tag_claims`]. +/// +/// # Errors +/// +/// Returns the errors of [`EventStore::tag_claims`]. +pub fn search_store( + store: &EventStore, + name: &str, + value: ValueMatch<'_>, +) -> Result, StoreError> { + Ok(search(&store.tag_claims()?, name, value)) +} diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index 3ca790c91c..984246fea8 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -552,6 +552,9 @@ mod tests { kind: kind.to_owned(), group, after: Vec::new(), + tag: None, + document: None, + removes: None, }; sign(signer, seq, backlink, body, ext).unwrap() } diff --git a/pkgs/id/src/tag_claims.rs b/pkgs/id/src/tag_claims.rs new file mode 100644 index 0000000000..6b8126310c --- /dev/null +++ b/pkgs/id/src/tag_claims.rs @@ -0,0 +1,398 @@ +//! Tags as signed events: observed-remove claims (Phase 5, P5.1; design §9.1, spike S8). +//! +//! A tag is a claim. `tag.set` names a subject (any event ID), a name, and an optional value. It +//! is attributed to the key that signed it. `tag.clear` names the claims it removes. Both are +//! ordinary events: the kind is in the header's [`ChainExt`](crate::chain::ChainExt), and so is the +//! operation, in its `tag` field. The operation is the tag's body (#182). It is signed with the +//! header, so an event carries its whole tag, and sync moves events alone. +//! +//! A clear removes a claim only when the claim is named by the clear and lies in the clear's +//! causal past, which is the set of events its author had seen. A concurrent add the clear did not +//! see survives it. A clear that names a claim its author never saw does nothing to that claim. +//! The past is the transitive closure of each event's `after` hashes and backlink, so the clear's +//! frontier need not name a claim for the clear to remove it. +//! +//! The operation's limits are checked when a header is built and when it is decoded. A value is +//! text inside the header, and the header decoder declares text at most 512 bytes long, so a value +//! is at most [`MAX_VALUE_BYTES`]. +//! +//! Two folds give the live claims. [`live_claims`] walks the causal past of each clear. It is the +//! reference. [`compacted_claims`] makes one pass over the parent links and keeps, for each event, +//! only the live claims in its past. Both give the same result (P5.3, #184). +//! +//! The old iroh-docs tag store in [`crate::tags`] is a separate model and is not read here. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use p2panda_core::Hash; +use serde::{Deserialize, Serialize}; +use unicode_normalization::is_nfc; + +use crate::waiting::AuthorKey; + +/// The kind of a `tag.set` event, as the header's `kind` names it. +pub const SET_KIND: &str = "tag.set"; + +/// The kind of a `tag.clear` event, as the header's `kind` names it. +pub const CLEAR_KIND: &str = "tag.clear"; + +/// The most bytes a tag name may have. A name is at least one byte. +pub const MAX_NAME_BYTES: usize = 128; + +/// The most bytes a tag value may have. The header decoder declares text at most 512 bytes long. +pub const MAX_VALUE_BYTES: usize = 512; + +/// The most claims one `tag.clear` may name. The header decoder declares arrays at most 512 long. +pub const MAX_CLEAR_CLAIMS: usize = 256; + +/// What a tag event does. The kind of the event says which form the operation takes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TagOp { + /// Adds a claim: the subject carries `name` (and `value`), attributed to the signer. + Set { + /// The event the claim is about. Any event ID. + subject: Hash, + /// The tag name. + name: String, + /// The tag value. `None` for a bare tag. + value: Option, + }, + /// Removes the named claims, if the clear's author had seen them. + Clear { + /// The IDs of the `tag.set` events this clear removes. + claims: Vec, + }, +} + +/// An applied tag event, as the fold reads it: its ID, its signer, and its operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Applied { + /// The event's ID. For a `tag.set`, this is the claim's ID. + pub id: Hash, + /// The key that signed the event. + pub author: AuthorKey, + /// What the event does. + pub op: TagOp, +} + +/// A claim that is live: a `tag.set` that no applied clear removes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Claim { + /// The claim's ID: the `tag.set` event's ID. + pub id: Hash, + /// The key that signed the claim. + pub author: AuthorKey, + /// The subject the claim is about. + pub subject: Hash, + /// The tag name. + pub name: String, + /// The tag value, if any. + pub value: Option, +} + +/// Why a tag operation was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum TagError { + /// The operation is not the one the event's kind names. + #[error("a {kind:?} event carries the wrong tag operation")] + KindMismatch { + /// The kind of the event. + kind: String, + }, + /// A field breaks a limit or the NFC rule. + #[error("{0}")] + Field(String), +} + +/// Whether `kind` is a tag kind, so its event carries a tag operation. +#[must_use] +pub fn is_tag_kind(kind: &str) -> bool { + kind == SET_KIND || kind == CLEAR_KIND +} + +/// Checks a tag operation against the kind of the event that carries it. +/// +/// # Errors +/// +/// Returns [`TagError::KindMismatch`] when the operation is not the one `kind` names. Returns +/// [`TagError::Field`] for a name or value that breaks its limit or the NFC rule, and for a clear +/// that names more than [`MAX_CLEAR_CLAIMS`] claims. +pub fn check_op(kind: &str, op: &TagOp) -> Result<(), TagError> { + match (kind, op) { + (SET_KIND, TagOp::Set { name, value, .. }) => { + check_text("name", name, 1, MAX_NAME_BYTES)?; + if let Some(text) = value { + check_text("value", text, 0, MAX_VALUE_BYTES)?; + } + Ok(()) + } + (CLEAR_KIND, TagOp::Clear { claims }) => { + if claims.len() > MAX_CLEAR_CLAIMS { + return Err(TagError::Field(format!( + "{} claims, the most is {MAX_CLEAR_CLAIMS}", + claims.len() + ))); + } + Ok(()) + } + _ => Err(TagError::KindMismatch { + kind: kind.to_owned(), + }), + } +} + +/// Checks a text field: its byte length is in `min..=max`, and it is NFC. +fn check_text(field: &str, text: &str, min: usize, max: usize) -> Result<(), TagError> { + let length = text.len(); + if !(min..=max).contains(&length) { + return Err(TagError::Field(format!( + "the {field} is {length} bytes, it must be {min} to {max}" + ))); + } + if !is_nfc(text) { + return Err(TagError::Field(format!("the {field} is not NFC"))); + } + Ok(()) +} + +/// The events that `start` reaches by following parent links: its own causal past, transitively. +/// `parents` maps each event to the events it names, its `after` hashes and its backlink. The +/// starting events are included. +#[must_use] +pub fn causal_past(start: &[Hash], parents: &HashMap>) -> HashSet { + let mut past = HashSet::new(); + let mut queue: Vec = start.to_vec(); + while let Some(id) = queue.pop() { + if !past.insert(id) { + continue; + } + if let Some(named) = parents.get(&id) { + queue.extend(named.iter().copied()); + } + } + past +} + +/// The live claims, given the applied tag events and the parent links of every event the store +/// holds. A claim is live unless an applied clear names it and has it in its causal past. +/// +/// This walks the causal past of each clear, so it costs O(clears x history). It is the reference +/// for [`compacted_claims`]. The result is sorted by claim ID. +#[must_use] +pub fn live_claims(applied: &[Applied], parents: &HashMap>) -> Vec { + let mut sets: BTreeMap<[u8; 32], Claim> = BTreeMap::new(); + let mut removed: HashSet = HashSet::new(); + for event in applied { + if let TagOp::Set { + subject, + name, + value, + } = &event.op + { + sets.insert( + *event.id.as_bytes(), + Claim { + id: event.id, + author: event.author, + subject: *subject, + name: name.clone(), + value: value.clone(), + }, + ); + } + } + for event in applied { + let TagOp::Clear { claims } = &event.op else { + continue; + }; + // What the clear's author had seen: the causal past of the clear, not counting the clear. + let seen = parents + .get(&event.id) + .map(|named| causal_past(named, parents)) + .unwrap_or_default(); + removed.extend(claims.iter().filter(|claim| seen.contains(claim))); + } + sets.into_values() + .filter(|claim| !removed.contains(&claim.id)) + .collect() +} + +/// The live claims, folded in one pass over the parent links (P5.3, #184). +/// +/// Each event gets the set of live claims in its causal past, including itself. The set of an +/// event is built from its parents' sets, so each event is visited once. A clear removes each +/// claim it names that is in its parents' sets: those are the claims its author had seen. A +/// removed claim is dropped from every set built after it, so a set holds only claims that are +/// still live. Removal is final, so dropping it changes no later decision. +/// +/// The result is the same as [`live_claims`], and it is sorted by claim ID. The walk for a clear is +/// over the live claims in its parents' sets, not over its whole past. A clear from an author who +/// had not seen a claim leaves that claim live, as [`live_claims`] does. +#[must_use] +pub fn compacted_claims(applied: &[Applied], parents: &HashMap>) -> Vec { + let by_id: HashMap = applied.iter().map(|event| (event.id, event)).collect(); + // The live claims in each event's causal past, including the event if it is a live claim. + let mut live_past: HashMap> = HashMap::new(); + let mut removed: HashSet = HashSet::new(); + let mut open: HashSet = HashSet::new(); + for root in parents.keys().copied() { + // A depth-first walk in post-order: an event is folded after its parents. + let mut stack = vec![(root, false)]; + while let Some((id, folded)) = stack.pop() { + if live_past.contains_key(&id) { + continue; + } + let named: &[Hash] = match parents.get(&id) { + Some(named) => named, + None => &[], + }; + if !folded { + if !open.insert(id) { + continue; + } + stack.push((id, true)); + stack.extend( + named + .iter() + .filter(|parent| !live_past.contains_key(*parent)) + .map(|parent| (*parent, false)), + ); + continue; + } + open.remove(&id); + let mut past: HashSet = HashSet::new(); + for parent in named { + if let Some(claims) = live_past.get(parent) { + past.extend(claims.iter().filter(|claim| !removed.contains(*claim))); + } + } + match by_id.get(&id).map(|event| &event.op) { + Some(TagOp::Clear { claims }) => { + removed.extend(claims.iter().filter(|claim| past.contains(*claim))); + } + Some(TagOp::Set { .. }) if !removed.contains(&id) => { + past.insert(id); + } + _ => {} + } + live_past.insert(id, past); + } + } + let mut live: Vec = applied + .iter() + .filter(|event| !removed.contains(&event.id)) + .filter_map(|event| match &event.op { + TagOp::Set { + subject, + name, + value, + } => Some(Claim { + id: event.id, + author: event.author, + subject: *subject, + name: name.clone(), + value: value.clone(), + }), + TagOp::Clear { .. } => None, + }) + .collect(); + live.sort_by_key(|claim| *claim.id.as_bytes()); + live +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn hash(n: u8) -> Hash { + Hash::from_bytes([n; 32]) + } + + fn set(id: u8, subject: u8, name: &str) -> Applied { + Applied { + id: hash(id), + author: [id; 32], + op: TagOp::Set { + subject: hash(subject), + name: name.to_owned(), + value: None, + }, + } + } + + fn clear(id: u8, claims: &[u8]) -> Applied { + Applied { + id: hash(id), + author: [id; 32], + op: TagOp::Clear { + claims: claims.iter().map(|n| hash(*n)).collect(), + }, + } + } + + #[test] + fn test_a_tag_op_is_checked_against_its_kind() { + let set_op = TagOp::Set { + subject: hash(1), + name: "city".to_owned(), + value: Some(String::new()), + }; + let clear_op = TagOp::Clear { claims: vec![] }; + assert!(check_op(SET_KIND, &set_op).is_ok()); + assert!(check_op(CLEAR_KIND, &clear_op).is_ok()); + assert!(check_op(CLEAR_KIND, &set_op).is_err()); + assert!(check_op(SET_KIND, &clear_op).is_err()); + assert!(check_op("message", &set_op).is_err()); + } + + #[test] + fn test_a_name_or_value_outside_its_limits_is_refused() { + let check = |name: &str, value: Option| { + check_op( + SET_KIND, + &TagOp::Set { + subject: hash(1), + name: name.to_owned(), + value, + }, + ) + }; + assert!(check("", None).is_err()); + assert!(check(&"n".repeat(MAX_NAME_BYTES + 1), None).is_err()); + assert!(check("a", Some("v".repeat(MAX_VALUE_BYTES))).is_ok()); + assert!(check("a", Some("v".repeat(MAX_VALUE_BYTES + 1))).is_err()); + assert!(check("a", Some("e\u{301}".to_owned())).is_err()); + } + + #[test] + fn test_a_clear_naming_too_many_claims_is_refused() { + let op = TagOp::Clear { + claims: (0..=MAX_CLEAR_CLAIMS) + .map(|n| Hash::digest(n.to_be_bytes())) + .collect(), + }; + assert!(check_op(CLEAR_KIND, &op).is_err()); + } + + #[test] + fn test_the_compacted_fold_keeps_a_claim_a_clear_did_not_see() { + // `b` (event 3) names claim 1, but its past is only itself, so claim 1 stays live. + let applied = [set(1, 9, "city"), clear(3, &[1])]; + let parents: HashMap> = HashMap::from([(hash(3), vec![])]); + let live = compacted_claims(&applied, &parents); + assert_eq!(live.iter().map(|c| c.id).collect::>(), vec![hash(1)]); + assert_eq!(live, live_claims(&applied, &parents)); + } + + #[test] + fn test_the_compacted_fold_removes_a_claim_its_clear_saw_through_another_event() { + // Claim 1 is in the past of clear 4 through event 2, which names claim 1. + let applied = [set(1, 9, "city"), set(2, 9, "seen"), clear(4, &[1])]; + let parents: HashMap> = + HashMap::from([(hash(2), vec![hash(1)]), (hash(4), vec![hash(2)])]); + let live = compacted_claims(&applied, &parents); + assert_eq!(live.iter().map(|c| c.id).collect::>(), vec![hash(2)]); + assert_eq!(live, live_claims(&applied, &parents)); + } +} diff --git a/pkgs/id/src/tag_index.rs b/pkgs/id/src/tag_index.rs new file mode 100644 index 0000000000..b45e94a568 --- /dev/null +++ b/pkgs/id/src/tag_index.rs @@ -0,0 +1,215 @@ +//! The tag index on the tuple encoding (Phase 5, P5.2; design §9.2). +//! +//! Each live claim is indexed twice, as a key in [`crate::tuple`] order: +//! +//! - α: `(subject, name, value, claim)`, for "the tags of X", "the tags of X named N" and "the +//! tags of X named N with value V". +//! - Ω: `(value, name, subject, claim)`, for "the subjects with value V", "with value V and name N" +//! and "with value V and name N on subject X". +//! +//! A bare tag has no value, and its value field is tuple null. Every text and byte field is +//! terminated, so a prefix on a whole field matches that field exactly: the name `a` does not +//! match `a\0b`. The index is local and rebuilt from the store's live claims. It is not replicated. + +use std::collections::BTreeMap; + +use p2panda_core::Hash; + +use crate::tag_claims::Claim; +use crate::tuple::TupleEncoder; + +/// One indexed claim. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// The subject the claim is about. + pub subject: Hash, + /// The tag name. + pub name: String, + /// The tag value, or `None` for a bare tag. + pub value: Option, + /// The claim's ID. + pub claim: Hash, +} + +/// The tag index: the live claims, keyed by their tuple encodings in both directions. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TagIndex { + alpha: BTreeMap, Entry>, + omega: BTreeMap, Entry>, +} + +impl TagIndex { + /// Builds the index over `claims`. + #[must_use] + pub fn new(claims: &[Claim]) -> Self { + let mut alpha = BTreeMap::new(); + let mut omega = BTreeMap::new(); + for claim in claims { + let entry = Entry { + subject: claim.subject, + name: claim.name.clone(), + value: claim.value.clone(), + claim: claim.id, + }; + alpha.insert(alpha_key(&entry), entry.clone()); + omega.insert(omega_key(&entry), entry); + } + Self { alpha, omega } + } + + /// The number of claims indexed. + #[must_use] + pub fn len(&self) -> usize { + self.alpha.len() + } + + /// Whether no claim is indexed. + #[must_use] + pub fn is_empty(&self) -> bool { + self.alpha.is_empty() + } + + /// Every claim on `subject`, whatever its name and value. + #[must_use] + pub fn subject(&self, subject: &Hash) -> Vec { + let mut prefix = TupleEncoder::new(); + prefix.bytes(subject.as_bytes()); + scan(&self.alpha, &prefix.build()) + } + + /// Every claim on `subject` named `name`, whatever its value. + #[must_use] + pub fn subject_name(&self, subject: &Hash, name: &str) -> Vec { + let mut prefix = TupleEncoder::new(); + prefix.bytes(subject.as_bytes()).string(name); + scan(&self.alpha, &prefix.build()) + } + + /// Every claim on `subject` named `name` with `value`. `None` is the bare tag. + #[must_use] + pub fn subject_name_value( + &self, + subject: &Hash, + name: &str, + value: Option<&str>, + ) -> Vec { + let mut prefix = TupleEncoder::new(); + prefix.bytes(subject.as_bytes()).string(name); + value_field(&mut prefix, value); + scan(&self.alpha, &prefix.build()) + } + + /// Every claim named `name`, on any subject, with any value. The name is not a leading field of + /// either key, so this is a scan of the whole Ω index. + #[must_use] + pub fn named(&self, name: &str) -> Vec { + self.omega + .values() + .filter(|entry| entry.name == name) + .cloned() + .collect() + } + + /// Every claim with `value`, whatever its name and subject. `None` is the bare tag. + #[must_use] + pub fn value(&self, value: Option<&str>) -> Vec { + let mut prefix = TupleEncoder::new(); + value_field(&mut prefix, value); + scan(&self.omega, &prefix.build()) + } + + /// Every claim with `value` and `name`, on any subject. + #[must_use] + pub fn value_name(&self, value: Option<&str>, name: &str) -> Vec { + let mut prefix = TupleEncoder::new(); + value_field(&mut prefix, value); + prefix.string(name); + scan(&self.omega, &prefix.build()) + } + + /// Every claim with `value` and `name` on `subject`. + #[must_use] + pub fn value_name_subject( + &self, + value: Option<&str>, + name: &str, + subject: &Hash, + ) -> Vec { + let mut prefix = TupleEncoder::new(); + value_field(&mut prefix, value); + prefix.string(name).bytes(subject.as_bytes()); + scan(&self.omega, &prefix.build()) + } +} + +/// The α key of a claim: `(subject, name, value, claim)`. +fn alpha_key(entry: &Entry) -> Vec { + let mut key = TupleEncoder::new(); + key.bytes(entry.subject.as_bytes()).string(&entry.name); + value_field(&mut key, entry.value.as_deref()); + key.bytes(entry.claim.as_bytes()); + key.build() +} + +/// The Ω key of a claim: `(value, name, subject, claim)`. +fn omega_key(entry: &Entry) -> Vec { + let mut key = TupleEncoder::new(); + value_field(&mut key, entry.value.as_deref()); + key.string(&entry.name).bytes(entry.subject.as_bytes()); + key.bytes(entry.claim.as_bytes()); + key.build() +} + +/// The value field: a string, or null for a bare tag. +fn value_field(encoder: &mut TupleEncoder, value: Option<&str>) { + match value { + Some(text) => encoder.string(text), + None => encoder.null(), + }; +} + +/// The entries whose keys start with `prefix`, in key order. +fn scan(index: &BTreeMap, Entry>, prefix: &[u8]) -> Vec { + index + .range(prefix.to_vec()..) + .take_while(|(key, _)| key.starts_with(prefix)) + .map(|(_, entry)| entry.clone()) + .collect() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn claim(n: u8, subject: u8, name: &str, value: Option<&str>) -> Claim { + Claim { + id: Hash::from_bytes([n; 32]), + author: [n; 32], + subject: Hash::from_bytes([subject; 32]), + name: name.to_owned(), + value: value.map(str::to_owned), + } + } + + #[test] + fn test_named_returns_the_claims_with_that_name_on_every_subject() { + let claims = [ + claim(1, 9, "city", Some("Seattle")), + claim(2, 8, "city", None), + claim(3, 9, "name", None), + claim(4, 7, "cityx", None), + claim(5, 7, "a\0b", None), + ]; + let index = TagIndex::new(&claims); + let mut got: Vec<[u8; 32]> = index + .named("city") + .iter() + .map(|entry| *entry.claim.as_bytes()) + .collect(); + got.sort_unstable(); + assert_eq!(got, vec![[1; 32], [2; 32]]); + assert!(index.named("a").is_empty(), "a is not a\\0b"); + assert!(index.named("missing").is_empty()); + } +} diff --git a/pkgs/id/tests/aliases.rs b/pkgs/id/tests/aliases.rs new file mode 100644 index 0000000000..3e1d65dbdc --- /dev/null +++ b/pkgs/id/tests/aliases.rs @@ -0,0 +1,292 @@ +//! Alias display over tag claims (Phase 5, P5.7; owner decisions 2026-10-12). +//! +//! Aliases are tag claims, so they are read through [`EventStore::tag_claims`] and shown by +//! `aliases::rows`. The checks: +//! +//! 1. An identity's alias is a claim on its first identity event. Two aliases for one identity are +//! both shown as contested, and nothing picks one. +//! 2. A server's primary alias is stored and wins for display over the claims. A pet name, which +//! only this client sees, wins over the primary. +//! 3. A prefix of each subject ID is shown. It is the shortest one that no other row in the view +//! shares, and the full ID when no prefix is unique. +//! 4. Nothing is unique: two identities may claim the same alias, and both are returned. +//! +//! No identity event kind exists yet (#160), so the identity's first identity event here is the +//! first event of its writer's chain. The subject rule belongs to the caller, so the display does +//! not depend on the event's kind. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeMap; + +use id::aliases::{ALIAS_NAME, Named, Shown, aliases_of, rows}; +use id::chain::{ChainExt, Event, sign}; +use id::event_store::{EventStore, Ingest}; +use id::server_config::ServerConfig; +use id::tag_claims::{SET_KIND, TagOp}; +use id::waiting::{AuthorKey, WaitingLimits}; +use p2panda_core::{Hash, SeqNum, SigningKey}; + +/// A signer with its own chain. Each event names the one before it as its `after`. +struct Writer { + key: SigningKey, + seq: SeqNum, + last: Option, +} + +impl Writer { + fn new(n: u8) -> Self { + Self { + key: SigningKey::from_bytes(&[n; 32]), + seq: 0, + last: None, + } + } + + fn author(&self) -> AuthorKey { + *self.key.verifying_key().as_bytes() + } + + /// Signs a `tag.set` of `name`, with `value`, on `subject`. + fn tag(&mut self, subject: Hash, name: &str, value: Option<&str>) -> Event { + let ext = ChainExt { + kind: SET_KIND.to_owned(), + group: None, + after: self.last.into_iter().collect(), + tag: Some(TagOp::Set { + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + }), + document: None, + removes: None, + }; + let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); + self.seq += 1; + self.last = Some(event.id); + event + } +} + +fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) +} + +/// Delivers each event's bytes, as sync does, and checks that none was refused. +fn deliver(store: &mut EventStore, events: &[&Event]) { + for event in events { + let outcome = store.ingest(&event.bytes, 0).unwrap(); + assert!( + !matches!(outcome, Ingest::Refused(_)), + "refused: {outcome:?}" + ); + } +} + +fn named(subject: Hash, name: &str) -> Named { + Named { + subject, + name: name.to_owned(), + } +} + +/// A config with one user, `ann`, and a group `team` that she creates. The group's primary alias +/// is `team`. The group's ID is the subject its alias claims name. +fn team_config(ann: AuthorKey) -> ServerConfig { + let text = format!( + "[[users]]\nkey = \"ann\"\nid = \"{}\"\n\n[[groups]]\nkey = \"team\"\nname = \"Team\"\n\ + creator = \"ann\"\nalias = \"team\"\n", + Hash::from_bytes(ann).to_hex() + ); + ServerConfig::parse(&text).unwrap() +} + +/// An ID whose first five bytes are fixed, so two such IDs share their first eight hex digits. +fn id_ending_in(last: u8) -> Hash { + let mut bytes = [0u8; 32]; + bytes[..4].copy_from_slice(&[0xab, 0xcd, 0xef, 0x01]); + bytes[4] = last; + Hash::from_bytes(bytes) +} + +#[test] +fn test_an_alias_is_a_tag_claim_on_the_identitys_first_event() { + let mut ann = Writer::new(1); + let identity = ann.tag(Hash::digest(b"ann"), "identity", None); + let alias = ann.tag(identity.id, ALIAS_NAME, Some("Ann")); + // Other claims on the identity are not aliases, and an alias on another subject is not its. + let seen = ann.tag(identity.id, "seen", None); + let elsewhere = ann.tag(Hash::digest(b"elsewhere"), ALIAS_NAME, Some("Ann")); + + let (_dir, mut store) = open(); + deliver(&mut store, &[&identity, &alias, &seen, &elsewhere]); + let claims = store.tag_claims().unwrap(); + + let found = aliases_of(&claims, &identity.id); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].text, "Ann"); + assert_eq!(found[0].claim, alias.id); + assert_eq!(found[0].author, ann.author()); +} + +#[test] +fn test_two_aliases_for_one_identity_are_both_shown_as_contested() { + let mut ann = Writer::new(1); + let mut bo = Writer::new(2); + let identity = ann.tag(Hash::digest(b"ann"), "identity", None); + let by_ann = ann.tag(identity.id, ALIAS_NAME, Some("Ann")); + let by_bo = bo.tag(identity.id, ALIAS_NAME, Some("Annie")); + + let (_dir, mut store) = open(); + deliver(&mut store, &[&identity, &by_ann, &by_bo]); + let claims = store.tag_claims().unwrap(); + + let view = rows( + &[named(identity.id, "ann")], + &claims, + None, + &BTreeMap::new(), + ); + assert_eq!(view.len(), 1); + assert_eq!(view[0].shown, Shown::Contested); + let mut texts: Vec<&str> = view[0].aliases.iter().map(|a| a.text.as_str()).collect(); + texts.sort_unstable(); + assert_eq!(texts, ["Ann", "Annie"]); + let authors: Vec = view[0].aliases.iter().map(|a| a.author).collect(); + assert!(authors.contains(&ann.author()) && authors.contains(&bo.author())); +} + +#[test] +fn test_a_server_primary_alias_wins_over_the_claims_for_display() { + let mut ann = Writer::new(1); + let mut bo = Writer::new(2); + let config = team_config(ann.author()); + let team = config.groups()[0].id; + let by_bo = bo.tag(team, ALIAS_NAME, Some("Team Alpha")); + let by_ann = ann.tag(team, ALIAS_NAME, Some("alpha")); + + let (_dir, mut store) = open(); + deliver(&mut store, &[&by_bo, &by_ann]); + let claims = store.tag_claims().unwrap(); + + let view = rows( + &[named(team, "Team")], + &claims, + Some(&config), + &BTreeMap::new(), + ); + assert_eq!(view.len(), 1); + assert_eq!(view[0].shown, Shown::Primary("team".to_owned())); + // The claims are still there for anyone who looks at the full set. + assert_eq!(view[0].aliases.len(), 2); +} + +#[test] +fn test_a_pet_name_wins_over_the_primary_alias_and_adds_no_claim() { + let mut ann = Writer::new(1); + let config = team_config(ann.author()); + let team = config.groups()[0].id; + let by_ann = ann.tag(team, ALIAS_NAME, Some("alpha")); + + let (_dir, mut store) = open(); + deliver(&mut store, &[&by_ann]); + let claims = store.tag_claims().unwrap(); + let before = claims.len(); + + let pets = BTreeMap::from([(team, "Our crew".to_owned())]); + let view = rows(&[named(team, "Team")], &claims, Some(&config), &pets); + assert_eq!(view[0].shown, Shown::PetName("Our crew".to_owned())); + // A pet name is local. It is not an event, so the store holds the same claims. + assert_eq!(store.tag_claims().unwrap().len(), before); +} + +#[test] +fn test_two_identities_may_claim_the_same_alias_and_both_are_returned() { + let mut ann = Writer::new(1); + let mut bo = Writer::new(2); + let ann_identity = ann.tag(Hash::digest(b"ann"), "identity", None); + let bo_identity = bo.tag(Hash::digest(b"bo"), "identity", None); + let ann_alias = ann.tag(ann_identity.id, ALIAS_NAME, Some("Sam")); + let bo_alias = bo.tag(bo_identity.id, ALIAS_NAME, Some("Sam")); + + let (_dir, mut store) = open(); + deliver( + &mut store, + &[&ann_identity, &bo_identity, &ann_alias, &bo_alias], + ); + let claims = store.tag_claims().unwrap(); + + let ann_found = aliases_of(&claims, &ann_identity.id); + let bo_found = aliases_of(&claims, &bo_identity.id); + assert_eq!(ann_found.len(), 1, "{ann_found:?}"); + assert_eq!(bo_found.len(), 1, "{bo_found:?}"); + assert_eq!(ann_found[0].claim, ann_alias.id); + assert_eq!(bo_found[0].claim, bo_alias.id); + + let view = rows( + &[named(ann_identity.id, "ann"), named(bo_identity.id, "bo")], + &claims, + None, + &BTreeMap::new(), + ); + assert_eq!(view.len(), 2); + for row in &view { + assert!( + matches!(&row.shown, Shown::Only(alias) if alias.text == "Sam"), + "{:?}", + row.shown + ); + } +} + +#[test] +fn test_each_row_shows_a_prefix_of_its_subject_unique_among_the_rows() { + // Two identities named `ann` whose IDs share their first eight hex digits, and one that does + // not share them. + let (x, y, z) = (id_ending_in(0x10), id_ending_in(0x20), Hash::digest(b"zed")); + let view = rows( + &[named(x, "ann"), named(y, "ann"), named(z, "zed")], + &[], + None, + &BTreeMap::new(), + ); + assert_eq!(view.len(), 3); + // They differ at the ninth hex digit, so each prefix is nine digits. + assert_eq!(view[0].prefix, "abcdef011"); + assert_eq!(view[1].prefix, "abcdef012"); + for (i, row) in view.iter().enumerate() { + assert!( + row.subject.to_hex().starts_with(&row.prefix), + "{} is not a prefix of {}", + row.prefix, + row.subject.to_hex() + ); + for (j, other) in view.iter().enumerate() { + if i != j { + assert!( + !other.subject.to_hex().starts_with(&row.prefix), + "{} is shared with another row", + row.prefix + ); + } + } + } +} + +#[test] +fn test_the_full_id_is_shown_when_no_prefix_is_unique() { + // Two rows with the same subject share every prefix, so only the full ID is unique to neither. + let subject = Hash::digest(b"ann"); + let view = rows( + &[named(subject, "ann"), named(subject, "ann")], + &[], + None, + &BTreeMap::new(), + ); + assert_eq!(view.len(), 2); + for row in &view { + assert_eq!(row.prefix, subject.to_hex()); + } +} diff --git a/pkgs/id/tests/chain_properties.rs b/pkgs/id/tests/chain_properties.rs index e7e754869c..6c722cb399 100644 --- a/pkgs/id/tests/chain_properties.rs +++ b/pkgs/id/tests/chain_properties.rs @@ -53,8 +53,16 @@ fn oversized_frontier() -> impl Strategy> { /// Any extension the builder accepts. fn chain_ext() -> impl Strategy { - (kind(), prop::option::of(hash()), frontier(MAX_AFTER)) - .prop_map(|(kind, group, after)| ChainExt { kind, group, after }) + (kind(), prop::option::of(hash()), frontier(MAX_AFTER)).prop_map(|(kind, group, after)| { + ChainExt { + kind, + group, + after, + tag: None, + document: None, + removes: None, + } + }) } /// An extension the builder would never sign. `after` is not limited here, so @@ -112,7 +120,7 @@ proptest! { let ext = ChainExt { kind: "m".to_owned(), group: None, - after: after.clone(), + after: after.clone(), tag: None, document: None, removes: None, }; prop_assert!(sign(&key(), 0, None, None, ext.clone()).is_err()); prop_assert!(ext.validate().is_err()); @@ -179,7 +187,7 @@ proptest! { ChainExt { kind: "m".to_owned(), group: None, - after: Vec::new(), + after: Vec::new(), tag: None, document: None, removes: None, }, ) .encode(); diff --git a/pkgs/id/tests/content_removal.rs b/pkgs/id/tests/content_removal.rs new file mode 100644 index 0000000000..cda7b0d8ee --- /dev/null +++ b/pkgs/id/tests/content_removal.rs @@ -0,0 +1,409 @@ +//! Content on removal (Phase 5, P5.6; design decision 4: "Content is kept. Removal stops new +//! content"). The author of a document may remove it. The removal is a signed `document.remove` +//! event that names the document's event ID, and it does not delete anything: +//! +//! 1. Content is kept. The removal is an event like any other, and it stays in the store. The +//! document, its blob and its tags are unchanged, and a member of the world may still fetch the +//! bytes. +//! 2. Only the removal by the document's author marks the document. A removal from anyone else is +//! stored and has no effect. +//! 3. The record and the tags do not depend on the order events arrive in. +//! 4. A removal takes no body, and it carries no tag and no document. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::{future::IntoFuture, sync::Arc, time::Duration}; + +use id::{ + access::AccessPolicy, + blob_gate::{BlobPolicy, WorldAccess, blob_events}, + chain::{ChainExt, Event, sign}, + commands::put::add_raw, + documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND}, + event_store::{EventStore, Ingest, Refusal}, + tag_claims::{SET_KIND, TagOp}, + waiting::WaitingLimits, +}; +use iroh::{ + Endpoint, EndpointAddr, + endpoint::{RelayMode, presets}, + protocol::Router, +}; +use iroh_base::{EndpointId, SecretKey}; +use iroh_blobs::{ + BlobsProtocol, Hash as BlobHash, api::Store, get::request::get_blob, store::mem::MemStore, +}; +use p2panda_core::{Hash, SeqNum, SigningKey}; + +/// Every network step must finish within this, so a stuck request fails the test. +const TIMEOUT: Duration = Duration::from_secs(20); + +const BODY: &[u8] = b"# Minutes\n\nThe plan is agreed."; + +/// The world graph the blob gate reads: membership and references. +#[derive(Default)] +struct Graph { + members: Vec<(&'static str, EndpointId)>, + refs: Vec<(BlobHash, &'static str)>, +} + +impl WorldAccess for Graph { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.members + .iter() + .any(|(w, member)| *w == world && member == requester) + } + + fn worlds_referencing(&self, hash: &BlobHash) -> Vec { + self.refs + .iter() + .filter(|(h, _)| h == hash) + .map(|(_, w)| (*w).to_owned()) + .collect() + } +} + +/// A signer with its own chain. Each event names the one before it. +struct Writer { + key: SigningKey, + seq: SeqNum, + last: Option, +} + +impl Writer { + fn new(n: u8) -> Self { + Self { + key: SigningKey::from_bytes(&[n; 32]), + seq: 0, + last: None, + } + } + + /// Signs `ext` after the writer's last event. + fn send(&mut self, ext: ChainExt) -> Event { + let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); + self.seq += 1; + self.last = Some(event.id); + event + } +} + +fn document_ext(doc: &DocumentRef, after: Vec) -> ChainExt { + ChainExt { + kind: DOCUMENT_KIND.to_owned(), + group: None, + after, + tag: None, + document: Some(doc.clone()), + removes: None, + } +} + +fn tag_ext(subject: Hash, name: &str, value: &str, after: Vec) -> ChainExt { + ChainExt { + kind: SET_KIND.to_owned(), + group: None, + after, + tag: Some(TagOp::Set { + subject, + name: name.to_owned(), + value: Some(value.to_owned()), + }), + document: None, + removes: None, + } +} + +fn removal_ext(target: Hash, after: Vec) -> ChainExt { + ChainExt { + kind: REMOVAL_KIND.to_owned(), + group: None, + after, + tag: None, + document: None, + removes: Some(target), + } +} + +fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) +} + +/// Delivers one event's bytes, as sync does, and checks that it was not refused. +fn deliver(store: &mut EventStore, event: &Event) { + let outcome = store.ingest(&event.bytes, 0).unwrap(); + assert!( + !matches!(outcome, Ingest::Refused(_)), + "refused: {outcome:?}" + ); +} + +/// The author's events: the document, two tags on it, and then its removal. A second writer +/// tags the document too, so the tags come from both sides. +struct Story { + doc: DocumentRef, + other: Writer, + published: Event, + kind: Event, + project: Event, + removal: Event, +} + +fn story() -> Story { + let doc = DocumentRef::for_bytes("text/markdown", BODY).unwrap(); + let mut author = Writer::new(1); + let mut other = Writer::new(2); + let published = author.send(document_ext(&doc, vec![])); + let kind = author.send(tag_ext(published.id, "kind", "minutes", vec![published.id])); + let project = other.send(tag_ext(published.id, "project", "p5", vec![published.id])); + let removal = author.send(removal_ext(published.id, vec![kind.id])); + Story { + doc, + other, + published, + kind, + project, + removal, + } +} + +/// Everything the author wrote, before the removal. +fn before_removal(s: &Story) -> Vec<&Event> { + vec![&s.published, &s.kind, &s.project] +} + +/// A node that connects to the provider: an endpoint with a known identity. +struct Peer { + endpoint: Endpoint, + id: EndpointId, +} + +async fn peer(seed: u8) -> Peer { + let key = SecretKey::from_bytes(&[seed; 32]); + let id = key.public(); + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .secret_key(key) + .bind() + .await + .unwrap(); + Peer { endpoint, id } +} + +/// A provider that serves `store` through the gate. Pushes are refused for everyone. +async fn provider(store: &Store, graph: Graph) -> (Router, EndpointAddr) { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .secret_key(SecretKey::from_bytes(&[200; 32])) + .bind() + .await + .unwrap(); + let addr = endpoint.addr(); + let events = blob_events( + Arc::new(graph), + BlobPolicy::default(), + AccessPolicy::restricted([]), + ); + let router = Router::builder(endpoint) + .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) + .spawn(); + (router, addr) +} + +/// Waits for `fut`, failing the test if it takes longer than [`TIMEOUT`]. +async fn within(fut: impl IntoFuture) -> T { + tokio::time::timeout(TIMEOUT, fut.into_future()) + .await + .expect("the request must finish within the timeout") +} + +/// Fetches `hash` from `server`: the bytes, or the error text. +async fn fetch(client: &Peer, server: &EndpointAddr, hash: BlobHash) -> Result, String> { + let conn = within(client.endpoint.connect(server.clone(), iroh_blobs::ALPN)) + .await + .unwrap(); + let got = within(get_blob(conn.clone(), hash).bytes()).await; + conn.close(0u32.into(), b"done"); + got.map(|b| b.to_vec()).map_err(|e| e.to_string()) +} + +#[test] +fn test_a_removal_is_kept_as_an_event_and_marks_its_document() { + let s = story(); + let (_dir, mut store) = open(); + for event in before_removal(&s) { + deliver(&mut store, event); + } + deliver(&mut store, &s.removal); + + // The removal stays in the store, as an event like any other. + assert!(store.event_applied(&s.removal.id).unwrap()); + assert!(store.event_by_id(&s.removal.id).unwrap().is_some()); + + // The document stays in the record, with its content, and it names the removal. + let record = store.documents().unwrap(); + assert_eq!(record.len(), 1, "{record:?}"); + assert_eq!(record[0].id, s.published.id); + assert_eq!(record[0].document, s.doc); + assert_eq!(record[0].removal, Some(s.removal.id)); +} + +#[test] +fn test_the_removal_leaves_the_tags_and_their_fold_unchanged() { + let s = story(); + let (_without_dir, mut without) = open(); + for event in before_removal(&s) { + deliver(&mut without, event); + } + let (_with_dir, mut with) = open(); + for event in before_removal(&s) { + deliver(&mut with, event); + } + deliver(&mut with, &s.removal); + + let claims = without.tag_claims().unwrap(); + assert_eq!(claims.len(), 2, "{claims:?}"); + assert_eq!(with.tag_claims().unwrap(), claims); +} + +#[test] +fn test_replicas_agree_on_the_event_set_and_the_record_in_any_order() { + let s = story(); + let all = [&s.published, &s.kind, &s.project, &s.removal]; + + // One replica gets the events in order, the other in reverse, so the removal arrives first. + let (_forward_dir, mut forward) = open(); + for event in all { + deliver(&mut forward, event); + } + let (_reverse_dir, mut reverse) = open(); + for event in all.iter().rev() { + deliver(&mut reverse, event); + } + + for event in all { + assert!( + forward.event_applied(&event.id).unwrap(), + "forward: {event:?}" + ); + assert!( + reverse.event_applied(&event.id).unwrap(), + "reverse: {event:?}" + ); + } + assert_eq!(reverse.documents().unwrap(), forward.documents().unwrap()); + assert_eq!(reverse.tag_claims().unwrap(), forward.tag_claims().unwrap()); + assert_eq!( + reverse.documents().unwrap()[0].removal, + Some(s.removal.id), + "the removal marks the document in either order" + ); +} + +#[test] +fn test_only_the_documents_author_may_remove_it() { + let mut s = story(); + // The other writer names the document in a removal of their own. It is stored, and it has + // no effect, since the other writer did not publish the document. + let other_removal = s + .other + .send(removal_ext(s.published.id, vec![s.project.id])); + + let (_dir, mut store) = open(); + for event in before_removal(&s) { + deliver(&mut store, event); + } + deliver(&mut store, &other_removal); + + assert!(store.event_applied(&other_removal.id).unwrap()); + let record = store.documents().unwrap(); + assert_eq!(record.len(), 1, "{record:?}"); + assert_eq!(record[0].removal, None, "{record:?}"); + assert_eq!(record[0].document, s.doc); +} + +#[tokio::test] +async fn test_a_member_may_still_fetch_the_bytes_after_removal() { + // Decision 4 keeps the content. The blob gate is unchanged by a removal: the member who was + // entitled before it is entitled after it. + let s = story(); + let provider_store: Store = MemStore::new().into(); + let (blob, _keep) = add_raw(&provider_store, BODY.to_vec()).await.unwrap(); + assert_eq!(blob, s.doc.blob_hash()); + + let (_dir, mut store) = open(); + for event in before_removal(&s) { + deliver(&mut store, event); + } + deliver(&mut store, &s.removal); + + let replica = peer(7).await; + let graph = Graph { + members: vec![("docs", replica.id)], + refs: vec![(blob, "docs")], + }; + let (router, addr) = provider(&provider_store, graph).await; + + let record = store.documents().unwrap(); + let got = fetch(&replica, &addr, record[0].document.blob_hash()) + .await + .expect("a member keeps its access after the removal"); + record[0].document.verify_content(&got).unwrap(); + assert_eq!(got, BODY); + + drop(router); +} + +#[test] +fn test_a_removal_with_a_body_is_refused() { + let s = story(); + let (_dir, mut store) = open(); + let outcome = store + .ingest_with_body(&s.removal.bytes, Some(BODY), 0) + .unwrap(); + assert!( + matches!(outcome, Ingest::Refused(Refusal::Malformed(_))), + "{outcome:?}" + ); + assert!(store.event_by_id(&s.removal.id).unwrap().is_none()); +} + +#[test] +fn test_a_removal_names_its_target_and_carries_nothing_else() { + let key = SigningKey::from_bytes(&[1; 32]); + let target = Hash::digest(b"document"); + let doc = DocumentRef::for_bytes("text/plain", b"notes").unwrap(); + + // No target. + let missing = ChainExt { + removes: None, + ..removal_ext(target, vec![]) + }; + assert!(sign(&key, 0, None, None, missing).is_err()); + // A document or a tag beside the target. + let with_document = ChainExt { + document: Some(doc), + ..removal_ext(target, vec![]) + }; + assert!(sign(&key, 0, None, None, with_document).is_err()); + let with_tag = ChainExt { + tag: Some(TagOp::Set { + subject: target, + name: "kind".to_owned(), + value: Some("memo".to_owned()), + }), + ..removal_ext(target, vec![]) + }; + assert!(sign(&key, 0, None, None, with_tag).is_err()); + // A target on any other kind. + let stray = ChainExt { + kind: DOCUMENT_KIND.to_owned(), + document: Some(DocumentRef::for_bytes("text/plain", b"notes").unwrap()), + ..removal_ext(target, vec![]) + }; + assert!(sign(&key, 0, None, None, stray).is_err()); + // The well-formed removal is signed. + assert!(sign(&key, 0, None, None, removal_ext(target, vec![])).is_ok()); +} diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs index 36cfda2b22..14df899c2f 100644 --- a/pkgs/id/tests/crash/store.rs +++ b/pkgs/id/tests/crash/store.rs @@ -431,6 +431,9 @@ fn workload() -> Vec> { kind: kind.to_owned(), group: None, after, + tag: None, + document: None, + removes: None, }; let a0 = sign(&author, 0, None, None, ext("message", Vec::new())).unwrap(); let a1 = sign(&author, 1, Some(a0.id), None, ext("message", Vec::new())).unwrap(); diff --git a/pkgs/id/tests/documents.rs b/pkgs/id/tests/documents.rs new file mode 100644 index 0000000000..ff764f9caa --- /dev/null +++ b/pkgs/id/tests/documents.rs @@ -0,0 +1,387 @@ +//! Documents over the event store and blob fetch (Phase 5, P5.4; design §9.3). +//! +//! A document is a `document.put` event that names its content by BLAKE3 hash and size, and its +//! media type. The bytes are a blob. Two replicas exchange only event bytes, as sync does, and +//! fetch the blob from a provider on request, through the gate in [`id::blob_gate`]: +//! +//! 1. A replica that holds the events holds the same document record and the same tags as the +//! author, whatever order the events arrive in. +//! 2. The bytes come only to a member of a world that names the blob. A replica outside that world +//! holds the record and the tags, and is refused the bytes. +//! 3. A clear of a document's tag removes that claim and leaves the document in the record. +//! 4. A document event that does not fit its kind is not signed, and one that carries a payload +//! body is refused on receipt. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::{future::IntoFuture, sync::Arc, time::Duration}; + +use id::{ + access::AccessPolicy, + blob_gate::{BlobPolicy, WorldAccess, blob_events}, + chain::{ChainExt, Event, sign}, + commands::put::add_raw, + documents::{DOCUMENT_KIND, DocumentRef, MAX_MEDIA_TYPE_BYTES}, + event_store::{EventStore, Ingest, Refusal}, + tag_claims::{CLEAR_KIND, SET_KIND, TagOp}, + waiting::{AuthorKey, WaitingLimits}, +}; +use iroh::{ + Endpoint, EndpointAddr, + endpoint::{RelayMode, presets}, + protocol::Router, +}; +use iroh_base::{EndpointId, SecretKey}; +use iroh_blobs::{ + BlobsProtocol, Hash as BlobHash, api::Store, get::request::get_blob, store::mem::MemStore, +}; +use p2panda_core::{Hash, SeqNum, SigningKey}; + +/// Every network step must finish within this, so a stuck request fails the test. +const TIMEOUT: Duration = Duration::from_secs(20); + +/// iroh-blobs' reset code for a refused request (`AbortReason::Permission`). +const DENIED: u64 = 1; + +const BODY: &[u8] = b"# Minutes\n\nThe plan is agreed."; + +/// The world graph the blob gate reads: membership and references. +#[derive(Default)] +struct Graph { + members: Vec<(&'static str, EndpointId)>, + refs: Vec<(BlobHash, &'static str)>, +} + +impl WorldAccess for Graph { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.members + .iter() + .any(|(w, member)| *w == world && member == requester) + } + + fn worlds_referencing(&self, hash: &BlobHash) -> Vec { + self.refs + .iter() + .filter(|(h, _)| h == hash) + .map(|(_, w)| (*w).to_owned()) + .collect() + } +} + +/// A signer with its own chain. Each event names the one before it. +struct Writer { + key: SigningKey, + seq: SeqNum, + last: Option, +} + +impl Writer { + fn new(n: u8) -> Self { + Self { + key: SigningKey::from_bytes(&[n; 32]), + seq: 0, + last: None, + } + } + + fn author(&self) -> AuthorKey { + *self.key.verifying_key().as_bytes() + } + + /// Signs `ext` after the writer's last event. + fn send(&mut self, ext: ChainExt) -> Event { + let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); + self.seq += 1; + self.last = Some(event.id); + event + } +} + +fn document_ext(doc: &DocumentRef, after: Vec) -> ChainExt { + ChainExt { + kind: DOCUMENT_KIND.to_owned(), + group: None, + after, + tag: None, + document: Some(doc.clone()), + removes: None, + } +} + +fn tag_ext(op: TagOp, after: Vec) -> ChainExt { + let kind = match op { + TagOp::Set { .. } => SET_KIND, + TagOp::Clear { .. } => CLEAR_KIND, + }; + ChainExt { + kind: kind.to_owned(), + group: None, + after, + tag: Some(op), + document: None, + removes: None, + } +} + +fn set(subject: Hash, name: &str, value: &str) -> TagOp { + TagOp::Set { + subject, + name: name.to_owned(), + value: Some(value.to_owned()), + } +} + +fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) +} + +/// Delivers one event's bytes, as sync does, and checks that it was not refused. +fn deliver(store: &mut EventStore, event: &Event) { + let outcome = store.ingest(&event.bytes, 0).unwrap(); + assert!( + !matches!(outcome, Ingest::Refused(_)), + "refused: {outcome:?}" + ); +} + +/// A node that connects to the provider: an endpoint with a known identity. +struct Peer { + endpoint: Endpoint, + id: EndpointId, +} + +async fn peer(seed: u8) -> Peer { + let key = SecretKey::from_bytes(&[seed; 32]); + let id = key.public(); + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .secret_key(key) + .bind() + .await + .unwrap(); + Peer { endpoint, id } +} + +/// A provider that serves `store` through the gate. Pushes are refused for everyone. +async fn provider(store: &Store, graph: Graph) -> (Router, EndpointAddr) { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .secret_key(SecretKey::from_bytes(&[200; 32])) + .bind() + .await + .unwrap(); + let addr = endpoint.addr(); + let events = blob_events( + Arc::new(graph), + BlobPolicy::default(), + AccessPolicy::restricted([]), + ); + let router = Router::builder(endpoint) + .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) + .spawn(); + (router, addr) +} + +/// Waits for `fut`, failing the test if it takes longer than [`TIMEOUT`]. +async fn within(fut: impl IntoFuture) -> T { + tokio::time::timeout(TIMEOUT, fut.into_future()) + .await + .expect("the request must finish within the timeout") +} + +/// Fetches `hash` from `server`: the bytes, or the error text. +async fn fetch(client: &Peer, server: &EndpointAddr, hash: BlobHash) -> Result, String> { + let conn = within(client.endpoint.connect(server.clone(), iroh_blobs::ALPN)) + .await + .unwrap(); + let got = within(get_blob(conn.clone(), hash).bytes()).await; + conn.close(0u32.into(), b"done"); + got.map(|b| b.to_vec()).map_err(|e| e.to_string()) +} + +/// The reset code of a fetch the provider refused, or `None` if the fetch was not refused. +async fn fetch_refusal_code(client: &Peer, server: &EndpointAddr, hash: BlobHash) -> Option { + let conn = within(client.endpoint.connect(server.clone(), iroh_blobs::ALPN)) + .await + .unwrap(); + let got = within(get_blob(conn.clone(), hash).bytes()).await; + conn.close(0u32.into(), b"done"); + got.err() + .and_then(|e| e.iroh_error_code()) + .map(iroh::endpoint::VarInt::into_inner) +} + +/// The author's three events: the document, then two tags on it, one from each writer. +fn authored() -> (DocumentRef, Writer, Vec) { + let doc = DocumentRef::for_bytes("text/markdown", BODY).unwrap(); + let mut author = Writer::new(1); + let mut other = Writer::new(2); + let published = author.send(document_ext(&doc, vec![])); + let kind = author.send(tag_ext( + set(published.id, "kind", "minutes"), + vec![published.id], + )); + let project = other.send(tag_ext( + set(published.id, "project", "p5"), + vec![published.id], + )); + (doc, author, vec![published, kind, project]) +} + +#[tokio::test] +async fn test_two_replicas_that_exchange_events_and_blob_bytes_converge_on_the_document_and_its_tags() + { + let (doc, author, events) = authored(); + let provider_store: Store = MemStore::new().into(); + let (blob, _keep) = add_raw(&provider_store, BODY.to_vec()).await.unwrap(); + assert_eq!(blob, doc.blob_hash(), "the document names the blob's hash"); + + // The author's replica holds every event, in the order written. + let (_author_dir, mut author_store) = open(); + for event in &events { + deliver(&mut author_store, event); + } + + // The other replica gets only the event bytes, in reverse order, so its tags arrive first. + let (_replica_dir, mut replica) = open(); + for event in events.iter().rev() { + deliver(&mut replica, event); + } + + // It is a member of the world that names the blob, so it may fetch the bytes. + let replica_peer = peer(7).await; + let graph = Graph { + members: vec![("docs", replica_peer.id)], + refs: vec![(blob, "docs")], + }; + let (router, addr) = provider(&provider_store, graph).await; + + let record = replica.documents().unwrap(); + assert_eq!(record.len(), 1, "one document: {record:?}"); + assert_eq!(record[0].id, events[0].id); + assert_eq!(record[0].author, author.author()); + assert_eq!(record[0].document, doc); + + let got = fetch(&replica_peer, &addr, record[0].document.blob_hash()) + .await + .expect("a member may fetch"); + record[0].document.verify_content(&got).unwrap(); + assert_eq!(got, BODY); + + assert_eq!( + replica.documents().unwrap(), + author_store.documents().unwrap() + ); + assert_eq!( + replica.tag_claims().unwrap(), + author_store.tag_claims().unwrap() + ); + assert_eq!(replica.tag_claims().unwrap().len(), 2); + + drop(router); +} + +#[tokio::test] +async fn test_a_replica_outside_the_world_has_the_record_but_not_the_bytes() { + let (doc, _author, events) = authored(); + let provider_store: Store = MemStore::new().into(); + let (blob, _keep) = add_raw(&provider_store, BODY.to_vec()).await.unwrap(); + + let (_replica_dir, mut replica) = open(); + for event in &events { + deliver(&mut replica, event); + } + + // A member of some other world holds nothing that names this blob. + let outsider = peer(8).await; + let graph = Graph { + members: vec![("docs", peer(7).await.id)], + refs: vec![(blob, "docs")], + }; + let (router, addr) = provider(&provider_store, graph).await; + + assert_eq!(replica.documents().unwrap()[0].document, doc); + assert_eq!( + fetch_refusal_code(&outsider, &addr, doc.blob_hash()).await, + Some(DENIED) + ); + + drop(router); +} + +#[test] +fn test_a_clear_of_a_document_tag_leaves_the_document_in_the_record() { + let doc = DocumentRef::for_bytes("text/plain", b"notes").unwrap(); + let mut author = Writer::new(1); + let mut other = Writer::new(2); + let published = author.send(document_ext(&doc, vec![])); + let memo = author.send(tag_ext( + set(published.id, "kind", "memo"), + vec![published.id], + )); + // The other writer's claim is concurrent with the memo: the author's clear does not see it. + let draft = other.send(tag_ext( + set(published.id, "kind", "draft"), + vec![published.id], + )); + let cleared = author.send(tag_ext( + TagOp::Clear { + claims: vec![memo.id], + }, + vec![memo.id], + )); + + let (_dir, mut store) = open(); + for event in [&published, &memo, &draft, &cleared] { + deliver(&mut store, event); + } + + let record = store.documents().unwrap(); + assert_eq!(record.len(), 1, "the clear leaves the document: {record:?}"); + assert_eq!(record[0].document, doc); + let claims = store.tag_claims().unwrap(); + assert_eq!(claims.len(), 1); + assert_eq!(claims[0].id, draft.id); + assert_eq!(claims[0].value.as_deref(), Some("draft")); +} + +#[test] +fn test_a_document_event_with_a_payload_body_is_refused() { + let (_doc, _author, events) = authored(); + let (_dir, mut store) = open(); + let outcome = store + .ingest_with_body(&events[0].bytes, Some(BODY), 0) + .unwrap(); + assert!( + matches!(outcome, Ingest::Refused(Refusal::Malformed(_))), + "{outcome:?}" + ); + assert!(store.documents().unwrap().is_empty()); +} + +#[test] +fn test_a_document_event_that_does_not_fit_its_kind_is_not_signed() { + let key = SigningKey::from_bytes(&[1; 32]); + let doc = DocumentRef::for_bytes("text/plain", b"notes").unwrap(); + let too_long = DocumentRef { + media_type: "m".repeat(MAX_MEDIA_TYPE_BYTES + 1), + ..doc + }; + assert!(sign(&key, 0, None, None, document_ext(&too_long, vec![])).is_err()); + let missing = ChainExt { + kind: DOCUMENT_KIND.to_owned(), + group: None, + after: vec![], + tag: None, + document: None, + removes: None, + }; + assert!(sign(&key, 0, None, None, missing).is_err()); + let with_tag = ChainExt { + tag: Some(set(Hash::digest(b"doc"), "kind", "memo")), + ..document_ext(&doc, vec![]) + }; + assert!(sign(&key, 0, None, None, with_tag).is_err()); +} diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index 710d6cd8ea..e33e720c7d 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -145,6 +145,9 @@ fn signed( kind: kind.to_owned(), group, after: pick_after(rng, known), + tag: None, + document: None, + removes: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -329,6 +332,9 @@ fn present_event( kind: kind.to_owned(), group: None, after: pick_present(rng, good), + tag: None, + document: None, + removes: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -749,7 +755,7 @@ proptest! { ChainExt { kind: "m".to_owned(), group: None, - after: Vec::new(), + after: Vec::new(), tag: None, document: None, removes: None, }, ) .encode(); @@ -790,6 +796,9 @@ fn print_ingest_seeds() { kind: kind.to_owned(), group: None, after, + tag: None, + document: None, + removes: None, }; sign(key, seq, backlink, None, ext).unwrap() }; diff --git a/pkgs/id/tests/production_ingest.rs b/pkgs/id/tests/production_ingest.rs index 138332cbc0..a8899be2c7 100644 --- a/pkgs/id/tests/production_ingest.rs +++ b/pkgs/id/tests/production_ingest.rs @@ -74,6 +74,9 @@ impl Chains { kind: kind.to_owned(), group, after: after.to_vec(), + tag: None, + document: None, + removes: None, }; let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); self.last.insert(who, (seq, event.id)); @@ -271,6 +274,9 @@ fn test_a_body_that_does_not_match_its_payload_hash_is_refused() { kind: GROUP_OP.to_owned(), group: Some(group), after: vec![group], + tag: None, + document: None, + removes: None, }, ) .unwrap(); diff --git a/pkgs/id/tests/search.rs b/pkgs/id/tests/search.rs new file mode 100644 index 0000000000..96c63578d0 --- /dev/null +++ b/pkgs/id/tests/search.rs @@ -0,0 +1,456 @@ +//! Search by tag name and value over the live claims (Phase 5, P5.5; design §9.4). +//! +//! A search takes a name and a value match, and returns each subject with the live claims that +//! match. The subjects are event IDs: identities, and documents, whose `document.put` event ID is +//! the subject their tags name. The result is ordered by subject ID bytes, and each subject's +//! claims by claim ID bytes: +//! +//! 1. A contested tag, with two different values both live, returns both claims. +//! 2. A cleared claim is not returned, and a concurrent add the clear did not see is. +//! 3. A value matches as a whole field. The value `a` does not match `a\0b`, and the name `a` +//! does not match the name `a\0b`. The 00 00 terminator makes that so. +//! 4. A bare tag matches only the bare search, and the empty value matches only itself. +//! 5. For random histories, the search equals a filter over the live set from +//! [`EventStore::tag_claims`]. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeMap; + +use id::chain::{ChainExt, Event, sign}; +use id::documents::{DOCUMENT_KIND, DocumentRef}; +use id::event_store::{EventStore, Ingest}; +use id::search::{Hit, ValueMatch, search, search_store}; +use id::tag_claims::{CLEAR_KIND, Claim, SET_KIND, TagOp}; +use id::waiting::WaitingLimits; +use p2panda_core::{Hash, SeqNum, SigningKey}; +use proptest::prelude::*; + +const WRITERS: usize = 3; +const SUBJECTS: usize = 3; +const NAMES: [&str; 3] = ["a", "a\0b", "city"]; +const CLAIM_VALUES: [Option<&str>; 5] = [None, Some("a"), Some("a\0b"), Some("ab"), Some("")]; +const QUERY_VALUES: [ValueMatch<'static>; 6] = [ + ValueMatch::Any, + ValueMatch::Bare, + ValueMatch::Exact("a"), + ValueMatch::Exact("a\0b"), + ValueMatch::Exact("ab"), + ValueMatch::Exact(""), +]; + +/// A signer with its own chain, as the tag tests have it. +struct Writer { + key: SigningKey, + seq: SeqNum, + last: Option, +} + +impl Writer { + fn new(n: u8) -> Self { + Self { + key: SigningKey::from_bytes(&[n; 32]), + seq: 0, + last: None, + } + } + + fn send(&mut self, ext: ChainExt) -> Event { + let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); + self.seq += 1; + self.last = Some(event.id); + event + } + + fn set(&mut self, subject: Hash, name: &str, value: Option<&str>, after: Vec) -> Event { + let op = TagOp::Set { + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + }; + self.send(tag_ext(SET_KIND, op, after)) + } + + fn clear(&mut self, claims: &[Hash], after: Vec) -> Event { + let op = TagOp::Clear { + claims: claims.to_vec(), + }; + self.send(tag_ext(CLEAR_KIND, op, after)) + } + + /// A `document.put`. Its event ID is the document's subject. + fn document(&mut self, bytes: &[u8]) -> Event { + let document = DocumentRef::for_bytes("text/markdown", bytes).unwrap(); + self.send(ChainExt { + kind: DOCUMENT_KIND.to_owned(), + group: None, + after: vec![], + tag: None, + document: Some(document), + removes: None, + }) + } +} + +fn tag_ext(kind: &str, op: TagOp, after: Vec) -> ChainExt { + ChainExt { + kind: kind.to_owned(), + group: None, + after, + tag: Some(op), + document: None, + removes: None, + } +} + +fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) +} + +/// Delivers one event's bytes, as sync does, and checks that it was not refused. +fn deliver(store: &mut EventStore, event: &Event) { + let outcome = store.ingest(&event.bytes, 0).unwrap(); + assert!( + !matches!(outcome, Ingest::Refused(_)), + "refused: {outcome:?}" + ); +} + +/// The subjects of `hits` with their claims' IDs, in the order the search returns them. +fn shape(hits: &[Hit]) -> Vec<(Hash, Vec)> { + hits.iter() + .map(|hit| { + ( + hit.subject, + hit.claims.iter().map(|claim| claim.id).collect(), + ) + }) + .collect() +} + +fn fits(value: Option<&str>, query: ValueMatch<'_>) -> bool { + match query { + ValueMatch::Any => true, + ValueMatch::Bare => value.is_none(), + ValueMatch::Exact(text) => value == Some(text), + } +} + +/// The reference: a filter over the live set, grouped by subject, in the order the search +/// promises. +fn expected(live: &[Claim], name: &str, query: ValueMatch<'_>) -> Vec<(Hash, Vec)> { + let mut by_subject: BTreeMap<[u8; 32], (Hash, Vec)> = BTreeMap::new(); + for claim in live { + if claim.name == name && fits(claim.value.as_deref(), query) { + by_subject + .entry(*claim.subject.as_bytes()) + .or_insert_with(|| (claim.subject, Vec::new())) + .1 + .push(claim.id); + } + } + by_subject + .into_values() + .map(|(subject, mut ids)| { + ids.sort_by_key(|id| *id.as_bytes()); + (subject, ids) + }) + .collect() +} + +fn sorted_by_subject(mut subjects: Vec) -> Vec { + subjects.sort_by_key(|subject| *subject.as_bytes()); + subjects +} + +#[test] +fn test_a_search_returns_each_identity_and_document_with_its_matching_claim() { + let mut author = Writer::new(1); + let document = author.document(b"minutes"); + let identity = Hash::digest(b"identity"); + let on_document = author.set(document.id, "city", Some("Seattle"), vec![document.id]); + let on_identity = author.set(identity, "city", Some("Seattle"), vec![on_document.id]); + let elsewhere = author.set(identity, "name", None, vec![on_identity.id]); + + let (_dir, mut store) = open(); + for event in [&document, &on_document, &on_identity, &elsewhere] { + deliver(&mut store, event); + } + + let hits = search_store(&store, "city", ValueMatch::Exact("Seattle")).unwrap(); + let subjects: Vec = hits.iter().map(|hit| hit.subject).collect(); + assert_eq!(subjects, sorted_by_subject(vec![document.id, identity])); + assert_eq!( + shape(&hits), + expected( + &store.tag_claims().unwrap(), + "city", + ValueMatch::Exact("Seattle") + ), + ); + // The pure search over the same live claims gives the same answer. + let live = store.tag_claims().unwrap(); + assert_eq!( + shape(&search(&live, "city", ValueMatch::Exact("Seattle"))), + shape(&hits) + ); + assert_eq!( + hits[0].claims[0].author, + *author.key.verifying_key().as_bytes() + ); +} + +#[test] +fn test_a_contested_tag_returns_both_values() { + let subject = Hash::digest(b"identity"); + let mut a = Writer::new(1); + let seattle = a.set(subject, "city", Some("Seattle"), vec![]); + let mut b = Writer::new(2); + // `b` did not see `seattle`, so both claims are live. + let portland = b.set(subject, "city", Some("Portland"), vec![]); + + let (_dir, mut store) = open(); + deliver(&mut store, &seattle); + deliver(&mut store, &portland); + + let hits = search_store(&store, "city", ValueMatch::Any).unwrap(); + assert_eq!( + shape(&hits), + vec![(subject, sorted_ids(vec![seattle.id, portland.id]))] + ); + let only_seattle = search_store(&store, "city", ValueMatch::Exact("Seattle")).unwrap(); + assert_eq!(shape(&only_seattle), vec![(subject, vec![seattle.id])]); + let only_portland = search_store(&store, "city", ValueMatch::Exact("Portland")).unwrap(); + assert_eq!(shape(&only_portland), vec![(subject, vec![portland.id])]); +} + +#[test] +fn test_a_cleared_claim_is_not_returned() { + let subject = Hash::digest(b"identity"); + let mut a = Writer::new(1); + let seen = a.set(subject, "city", Some("Seattle"), vec![]); + let kept = a.set(subject, "name", None, vec![seen.id]); + let mut b = Writer::new(2); + let cleared = b.clear(&[seen.id], vec![kept.id]); + + let (_dir, mut store) = open(); + for event in [&seen, &kept, &cleared] { + deliver(&mut store, event); + } + + assert!( + search_store(&store, "city", ValueMatch::Any) + .unwrap() + .is_empty() + ); + assert!( + search_store(&store, "city", ValueMatch::Exact("Seattle")) + .unwrap() + .is_empty() + ); + // The clear removes only the claim it names. + let names = search_store(&store, "name", ValueMatch::Any).unwrap(); + assert_eq!(shape(&names), vec![(subject, vec![kept.id])]); +} + +#[test] +fn test_a_concurrent_add_survives_a_clear_that_did_not_see_it() { + let subject = Hash::digest(b"identity"); + let mut a = Writer::new(1); + let seen = a.set(subject, "city", Some("Seattle"), vec![]); + let mut b = Writer::new(2); + let unseen_clear = b.clear(&[seen.id], vec![]); + + let (_dir, mut store) = open(); + for event in [&seen, &unseen_clear] { + deliver(&mut store, event); + } + + let hits = search_store(&store, "city", ValueMatch::Any).unwrap(); + assert_eq!(shape(&hits), vec![(subject, vec![seen.id])]); +} + +#[test] +fn test_a_bare_tag_matches_only_the_bare_search_and_an_empty_value_only_itself() { + let (s, t) = (Hash::digest(b"s"), Hash::digest(b"t")); + let mut a = Writer::new(1); + let bare = a.set(s, "flag", None, vec![]); + let empty = a.set(t, "flag", Some(""), vec![bare.id]); + + let (_dir, mut store) = open(); + for event in [&bare, &empty] { + deliver(&mut store, event); + } + + let bare_hits = search_store(&store, "flag", ValueMatch::Bare).unwrap(); + assert_eq!(shape(&bare_hits), vec![(s, vec![bare.id])]); + let empty_hits = search_store(&store, "flag", ValueMatch::Exact("")).unwrap(); + assert_eq!(shape(&empty_hits), vec![(t, vec![empty.id])]); + let any = search_store(&store, "flag", ValueMatch::Any).unwrap(); + let mut both = vec![(s, vec![bare.id]), (t, vec![empty.id])]; + both.sort_by_key(|(subject, _)| *subject.as_bytes()); + assert_eq!( + shape(&any), + both, + "any value returns both subjects, in subject order" + ); +} + +#[test] +fn test_a_value_and_a_name_match_as_whole_fields_so_a_does_not_match_a_nul_b() { + let (one, two, three, four) = ( + Hash::digest(b"s"), + Hash::digest(b"t"), + Hash::digest(b"u"), + Hash::digest(b"v"), + ); + let mut a = Writer::new(1); + let short = a.set(one, "city", Some("a"), vec![]); + let nul = a.set(two, "city", Some("a\0b"), vec![short.id]); + let longer = a.set(three, "city", Some("ab"), vec![nul.id]); + let short_name = a.set(four, "a", None, vec![longer.id]); + let nul_name = a.set(four, "a\0b", None, vec![short_name.id]); + + let (_dir, mut store) = open(); + for event in [&short, &nul, &longer, &short_name, &nul_name] { + deliver(&mut store, event); + } + + let value_a = search_store(&store, "city", ValueMatch::Exact("a")).unwrap(); + assert_eq!(shape(&value_a), vec![(one, vec![short.id])]); + let value_nul = search_store(&store, "city", ValueMatch::Exact("a\0b")).unwrap(); + assert_eq!(shape(&value_nul), vec![(two, vec![nul.id])]); + let name_a = search_store(&store, "a", ValueMatch::Any).unwrap(); + assert_eq!(shape(&name_a), vec![(four, vec![short_name.id])]); + let name_nul = search_store(&store, "a\0b", ValueMatch::Any).unwrap(); + assert_eq!(shape(&name_nul), vec![(four, vec![nul_name.id])]); +} + +#[test] +fn test_hits_are_ordered_by_subject_then_claim_and_do_not_depend_on_delivery_order() { + let mut a = Writer::new(1); + let mut b = Writer::new(2); + let subjects: Vec = (0..5u8).map(|n| Hash::digest([n])).collect(); + let mut events: Vec = subjects + .iter() + .map(|subject| a.set(*subject, "city", Some("Seattle"), vec![])) + .collect(); + // A second, concurrent claim on the first subject. + events.push(b.set(subjects[0], "city", Some("Seattle"), vec![])); + + let (_dir, mut forward) = open(); + for event in &events { + deliver(&mut forward, event); + } + let (_dir2, mut reverse) = open(); + for event in events.iter().rev() { + deliver(&mut reverse, event); + } + + let got = shape(&search_store(&forward, "city", ValueMatch::Any).unwrap()); + assert_eq!( + got, + shape(&search_store(&reverse, "city", ValueMatch::Any).unwrap()) + ); + let order: Vec = got.iter().map(|(subject, _)| *subject).collect(); + assert_eq!(order, sorted_by_subject(subjects.clone())); + let on_first = got + .iter() + .find(|(subject, _)| *subject == subjects[0]) + .unwrap(); + assert_eq!(on_first.1.len(), 2, "both claims on the first subject"); + assert!( + on_first + .1 + .windows(2) + .all(|pair| pair[0].as_bytes() < pair[1].as_bytes()) + ); +} + +#[test] +fn test_a_search_matches_nothing_on_an_empty_store_or_an_unknown_name() { + let (_dir, store) = open(); + assert!( + search_store(&store, "city", ValueMatch::Any) + .unwrap() + .is_empty() + ); + + let mut a = Writer::new(1); + let claim = a.set(Hash::digest(b"s"), "city", Some("Seattle"), vec![]); + let (_dir2, mut store) = open(); + deliver(&mut store, &claim); + assert!( + search_store(&store, "state", ValueMatch::Any) + .unwrap() + .is_empty() + ); +} + +/// The live claims' IDs, sorted by ID bytes. +fn sorted_ids(mut ids: Vec) -> Vec { + ids.sort_by_key(|id| *id.as_bytes()); + ids +} + +/// One random step: a clear or a set, the writer, the subject, the name, the value, and how many +/// recent events the author names in `after`. +type Step = (bool, usize, usize, usize, usize, usize); + +fn step_strategy() -> impl Strategy { + ( + any::(), + 0..WRITERS, + 0..SUBJECTS, + 0..NAMES.len(), + 0..CLAIM_VALUES.len(), + 0..4usize, + ) +} + +/// Builds a store from random steps. Each event is delivered as it is written, so every `after` +/// names an event the store holds. +fn build(steps: &[Step]) -> (tempfile::TempDir, EventStore) { + let (dir, mut store) = open(); + let mut writers: Vec = (0..WRITERS) + .map(|n| Writer::new(u8::try_from(n).unwrap() + 1)) + .collect(); + let mut events: Vec = Vec::new(); + let mut claims: Vec = Vec::new(); + for &(clear, writer, subject, name, value, reach) in steps { + let after: Vec = events.iter().rev().take(reach).copied().collect(); + let event = if clear && !claims.is_empty() { + writers[writer].clear(&[claims[value % claims.len()]], after) + } else { + let subject = Hash::digest([u8::try_from(subject).unwrap()]); + let set = writers[writer].set(subject, NAMES[name], CLAIM_VALUES[value], after); + claims.push(set.id); + set + }; + events.push(event.id); + deliver(&mut store, &event); + } + (dir, store) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 16, ..ProptestConfig::default() })] + + /// For random tag histories, the search equals a filter over the live set. + #[test] + fn test_the_search_equals_a_filter_over_the_live_set( + steps in prop::collection::vec(step_strategy(), 0..24), + name in 0..NAMES.len(), + query in 0..QUERY_VALUES.len(), + ) { + let (_dir, store) = build(&steps); + let live = store.tag_claims().unwrap(); + let (name, query) = (NAMES[name], QUERY_VALUES[query]); + prop_assert_eq!( + shape(&search_store(&store, name, query).unwrap()), + expected(&live, name, query) + ); + } +} diff --git a/pkgs/id/tests/tag_claims.proptest-regressions b/pkgs/id/tests/tag_claims.proptest-regressions new file mode 100644 index 0000000000..764a1da97e --- /dev/null +++ b/pkgs/id/tests/tag_claims.proptest-regressions @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 94862a47b0dd4d85b774795316aa616064f9cb8f39c89e9d19eaf02f6d00c583 # shrinks to seed = 0, writers = 2, steps = 17 +cc 0759f56f65da0bed99ca734202f2c922a127de01d7db27ada77935f12603086e # shrinks to seed = 7936381655908521821, writers = 3, steps = 29 diff --git a/pkgs/id/tests/tag_claims.rs b/pkgs/id/tests/tag_claims.rs new file mode 100644 index 0000000000..96bfaff803 --- /dev/null +++ b/pkgs/id/tests/tag_claims.rs @@ -0,0 +1,538 @@ +//! Tags as observed-remove claims over the event store (Phase 5, P5.1; design §9.1, spike S8). +//! +//! The S8 properties, checked on [`EventStore`] through its production path. Each event carries +//! its tag operation in its header, and a receiver gets nothing else (#182): +//! +//! 1. A clear removes the claims it names that its author had seen, and no others. +//! 2. A concurrent add survives a clear that did not see it. +//! 3. A clear that names a claim its author never saw does nothing to that claim. +//! 4. The past is the whole causal past, so a clear whose frontier does not name a claim still +//! removes it when the frontier's events saw it. +//! 5. The live set is the same under any delivery order, with duplicates. +//! +//! The oracle for 5 is the author's own record. Each writer knows which events it had seen when it +//! wrote a clear, so the expected live set is computed from those records, not from the causal walk. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; + +use id::chain::{ChainExt, Event, sign}; +use id::event_store::{EventStore, Ingest, Refusal}; +use id::tag_claims::{ + Applied, CLEAR_KIND, Claim, SET_KIND, TagOp, causal_past, compacted_claims, live_claims, +}; +use id::waiting::{AuthorKey, WaitingLimits}; +use p2panda_core::{Hash, SeqNum, SigningKey}; +use proptest::prelude::*; + +/// A signer with its own chain. Each event names the one before it, and names its frontier in +/// `after`. +struct Writer { + key: SigningKey, + seq: SeqNum, + last: Option, +} + +/// One signed event. +#[derive(Clone)] +struct Sent { + event: Event, + /// The key that signed it. + author: AuthorKey, + /// Which writer signed it. + writer: usize, +} + +impl Sent { + fn id(&self) -> Hash { + self.event.id + } +} + +impl Writer { + fn new(n: u8) -> Self { + Self { + key: SigningKey::from_bytes(&[n; 32]), + seq: 0, + last: None, + } + } + + fn author(&self) -> AuthorKey { + *self.key.verifying_key().as_bytes() + } + + fn send(&mut self, op: &TagOp, after: Vec, writer: usize) -> Sent { + let kind = match op { + TagOp::Set { .. } => SET_KIND, + TagOp::Clear { .. } => CLEAR_KIND, + }; + let ext = ChainExt { + kind: kind.to_owned(), + group: None, + after, + tag: Some(op.clone()), + document: None, + removes: None, + }; + let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); + self.seq += 1; + self.last = Some(event.id); + Sent { + event, + author: self.author(), + writer, + } + } +} + +fn set(subject: Hash, name: &str, value: Option<&str>) -> TagOp { + TagOp::Set { + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + } +} + +fn clear(claims: &[Hash]) -> TagOp { + TagOp::Clear { + claims: claims.to_vec(), + } +} + +fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) +} + +/// Delivers one event's bytes, as sync does, and checks that it was not refused. +fn deliver(store: &mut EventStore, sent: &Sent) { + let outcome = store.ingest(&sent.event.bytes, 0).unwrap(); + assert!( + !matches!(outcome, Ingest::Refused(_)), + "refused: {outcome:?}" + ); +} + +/// The live claims of `store`, as their IDs. +fn live(store: &EventStore) -> BTreeSet<[u8; 32]> { + store + .tag_claims() + .unwrap() + .iter() + .map(|claim| *claim.id.as_bytes()) + .collect() +} + +fn ids(sent: &[&Sent]) -> BTreeSet<[u8; 32]> { + sent.iter().map(|item| *item.id().as_bytes()).collect() +} + +#[test] +fn test_a_clear_removes_the_claim_its_author_saw() { + let subject = Hash::digest(b"doc"); + let mut a = Writer::new(1); + let seen = a.send(&set(subject, "city", Some("Seattle")), vec![], 0); + let kept = a.send(&set(subject, "name", None), vec![seen.id()], 0); + let mut b = Writer::new(2); + let cleared = b.send(&clear(&[seen.id()]), vec![kept.id()], 1); + + let (_dir, mut store) = open(); + for sent in [&seen, &kept, &cleared] { + deliver(&mut store, sent); + } + assert_eq!(live(&store), ids(&[&kept])); +} + +#[test] +fn test_a_concurrent_add_survives_a_clear_that_did_not_see_it() { + let subject = Hash::digest(b"doc"); + let mut a = Writer::new(1); + let mut b = Writer::new(2); + let a_add = a.send(&set(subject, "city", Some("Seattle")), vec![], 0); + // Written without seeing `a_add`, so it is concurrent with it. + let b_add = b.send(&set(subject, "city", Some("Seattle")), vec![], 1); + let a_clear = a.send(&clear(&[a_add.id()]), vec![a_add.id()], 0); + + let (_dir, mut store) = open(); + for sent in [&a_add, &b_add, &a_clear] { + deliver(&mut store, sent); + } + assert_eq!(live(&store), ids(&[&b_add])); +} + +#[test] +fn test_a_clear_of_an_unseen_claim_does_nothing_to_it() { + let subject = Hash::digest(b"doc"); + let mut a = Writer::new(1); + let mut b = Writer::new(2); + let unseen = a.send(&set(subject, "city", Some("Seattle")), vec![], 0); + let own = b.send(&set(subject, "tag", None), vec![], 1); + // `b` never saw `unseen`, but names it. + let clears_unseen = b.send(&clear(&[unseen.id()]), vec![own.id()], 1); + + let (_dir, mut store) = open(); + for sent in [&unseen, &own, &clears_unseen] { + deliver(&mut store, sent); + } + assert_eq!(live(&store), ids(&[&unseen, &own])); +} + +#[test] +fn test_a_clear_removes_a_claim_its_frontier_reaches_only_through_another_author() { + // Regression for the whole-causal-past clock (S8). `c` saw `x` through `y`, and its frontier + // names only `y`. A frontier-only clock would leave `x` live. + let (s1, s2) = (Hash::digest(b"one"), Hash::digest(b"two")); + let mut a = Writer::new(1); + let mut b = Writer::new(2); + let mut c = Writer::new(3); + let x = a.send(&set(s1, "city", Some("Seattle")), vec![], 0); + let y = b.send(&set(s2, "seen", None), vec![x.id()], 1); + let removes_x = c.send(&clear(&[x.id()]), vec![y.id()], 2); + + let (_dir, mut store) = open(); + for sent in [&x, &y, &removes_x] { + deliver(&mut store, sent); + } + assert_eq!(live(&store), ids(&[&y])); +} + +#[test] +fn test_a_clear_delivered_before_the_claim_it_names_still_removes_it() { + let subject = Hash::digest(b"doc"); + let mut a = Writer::new(1); + let seen = a.send(&set(subject, "city", Some("Seattle")), vec![], 0); + let kept = a.send(&set(subject, "name", None), vec![seen.id()], 0); + let mut b = Writer::new(2); + let cleared = b.send(&clear(&[seen.id()]), vec![kept.id()], 1); + + let (_dir, mut store) = open(); + for sent in [&cleared, &kept, &seen] { + deliver(&mut store, sent); + } + assert_eq!(live(&store), ids(&[&kept])); +} + +#[test] +fn test_a_claim_is_attributed_to_the_key_that_signed_it() { + let subject = Hash::digest(b"doc"); + let mut a = Writer::new(1); + let claim = a.send(&set(subject, "city", Some("Seattle")), vec![], 0); + + let (_dir, mut store) = open(); + deliver(&mut store, &claim); + let claims = store.tag_claims().unwrap(); + assert_eq!(claims.len(), 1); + assert_eq!(claims[0].author, a.author()); + assert_eq!(claims[0].subject, subject); + assert_eq!(claims[0].name, "city"); + assert_eq!(claims[0].value.as_deref(), Some("Seattle")); +} + +#[test] +fn test_a_tag_event_with_a_payload_body_is_refused() { + // The operation is in the header, so a body beside a tag event is refused. + let subject = Hash::digest(b"doc"); + let mut a = Writer::new(1); + let claim = a.send(&set(subject, "city", Some("Seattle")), vec![], 0); + let body = b"a body".to_vec(); + + let (_dir, mut store) = open(); + let outcome = store + .ingest_with_body(&claim.event.bytes, Some(&body), 0) + .unwrap(); + assert!( + matches!(outcome, Ingest::Refused(Refusal::Malformed(_))), + "{outcome:?}" + ); + assert!(live(&store).is_empty()); +} + +#[test] +fn test_a_tag_event_whose_operation_does_not_fit_its_kind_is_not_signed() { + let subject = Hash::digest(b"doc"); + let a = Writer::new(1); + let mismatch = ChainExt { + kind: CLEAR_KIND.to_owned(), + group: None, + after: vec![], + tag: Some(set(subject, "city", None)), + document: None, + removes: None, + }; + assert!(sign(&a.key, 0, None, None, mismatch).is_err()); + let missing = ChainExt { + kind: SET_KIND.to_owned(), + group: None, + after: vec![], + tag: None, + document: None, + removes: None, + }; + assert!(sign(&a.key, 0, None, None, missing).is_err()); +} + +// --------------------------------------------------------------------------- +// Convergence against the writers' own record of what they had seen +// --------------------------------------------------------------------------- + +/// SplitMix64. A history is a pure function of its seed. +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: usize) -> usize { + usize::try_from(self.next_u64() % u64::try_from(n).unwrap()).unwrap() + } +} + +/// A generated history: its events in the order they were written, and the expected live set. +struct History { + events: Vec, + expected: BTreeSet<[u8; 32]>, + /// For each event, the events its author had seen when it wrote it. + written: Vec<(Hash, HashSet)>, +} + +/// Writes a history of three writers, with syncs between them, sets, and clears. A clear names +/// random claims, seen or not. The oracle records the claims each clear's author had seen. +fn history(seed: u64, steps: usize, count: usize) -> History { + let mut rng = Rng(seed); + let subjects = [ + Hash::digest(b"s0"), + Hash::digest(b"s1"), + Hash::digest(b"s2"), + ]; + let names = ["city", "name", "a"]; + let values = [None, Some("Seattle"), Some("a\0b"), Some("a"), Some("")]; + + let mut writers: Vec = (1..=count) + .map(|n| Writer::new(u8::try_from(n).unwrap())) + .collect(); + // What each writer has seen: its events by ID, which is causally closed. + let mut known: Vec> = vec![BTreeMap::new(); count]; + let mut events: Vec = Vec::new(); + let mut sets: Vec = Vec::new(); + // Each clear's named claims, and the claims its author had seen when it wrote it. + let mut clears: Vec<(Vec, HashSet)> = Vec::new(); + let mut written: Vec<(Hash, HashSet)> = Vec::new(); + + for _ in 0..steps { + let w = rng.below(count); + match rng.below(10) { + 0..=1 => { + let other = rng.below(count); + let theirs = known[other].clone(); + known[w].extend(theirs); + } + 2..=6 => { + let subject = subjects[rng.below(subjects.len())]; + let name = names[rng.below(names.len())]; + let value = values[rng.below(values.len())]; + let after = frontier(&known[w], count); + let seen: HashSet = known[w].values().map(Sent::id).collect(); + let sent = writers[w].send(&set(subject, name, value), after, w); + known[w].insert(*sent.id().as_bytes(), sent.clone()); + written.push((sent.id(), seen)); + sets.push(sent.clone()); + events.push(sent); + } + _ => { + if sets.is_empty() { + continue; + } + let named_count = 1 + rng.below(3); + let named: Vec = (0..named_count) + .map(|_| sets[rng.below(sets.len())].id()) + .collect(); + let seen: HashSet = known[w].values().map(Sent::id).collect(); + let after = frontier(&known[w], count); + let sent = writers[w].send(&clear(&named), after, w); + known[w].insert(*sent.id().as_bytes(), sent.clone()); + written.push((sent.id(), seen.clone())); + clears.push((named, seen)); + events.push(sent); + } + } + } + + // The oracle: a set is live unless a clear names it and its author had seen it. + let removed: HashSet = clears + .iter() + .flat_map(|(named, seen)| named.iter().filter(|id| seen.contains(id)).copied()) + .collect(); + let expected = sets + .iter() + .filter(|sent| !removed.contains(&sent.id())) + .map(|sent| *sent.id().as_bytes()) + .collect(); + History { + events, + expected, + written, + } +} + +/// The parent links of each event: its `after` hashes and its backlink. +fn parents_of(events: &[Sent]) -> HashMap> { + events + .iter() + .map(|sent| { + let header = &sent.event.header; + ( + sent.id(), + header + .extensions + .after + .iter() + .copied() + .chain(header.backlink) + .collect(), + ) + }) + .collect() +} + +/// The latest event of each writer that `seen` holds: the frontier an author names in `after`. +fn frontier(seen: &BTreeMap<[u8; 32], Sent>, writers: usize) -> Vec { + (0..writers) + .filter_map(|writer| { + seen.values() + .filter(|sent| sent.writer == writer) + .max_by_key(|sent| sent.event.header.seq_num) + .map(Sent::id) + }) + .collect() +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 12, ..ProptestConfig::default() })] + + /// Three stores receive the same history in three orders: as written, reversed (so every event + /// waits for its causal past), and shuffled with every event repeated. Each reaches the oracle. + #[test] + fn test_the_live_set_is_the_oracle_under_any_delivery_order(seed in any::(), steps in 8usize..32) { + let history = history(seed, steps, 3); + let mut rng = Rng(seed ^ 0xD1E5_0C0F_FEE0_0001); + + let mut shuffled: Vec<&Sent> = history.events.iter().flat_map(|sent| [sent, sent]).collect(); + for i in (1..shuffled.len()).rev() { + shuffled.swap(i, rng.below(i + 1)); + } + let orders: [Vec<&Sent>; 3] = [ + history.events.iter().collect(), + history.events.iter().rev().collect(), + shuffled, + ]; + for order in orders { + let (_dir, mut store) = open(); + for sent in order { + let outcome = store.ingest(&sent.event.bytes, 0).unwrap(); + prop_assert!(!matches!(outcome, Ingest::Refused(_)), "refused: {outcome:?}"); + } + prop_assert_eq!(live(&store), history.expected.clone()); + } + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 16, ..ProptestConfig::default() })] + + /// The compacted fold gives the causal walk's live claims, for histories of two or three + /// writers. Clears name claims their authors had seen and claims they had not, so a clear from + /// an author who had not seen a claim must leave it live (P5.3, #184). + #[test] + fn test_the_compacted_fold_agrees_with_the_causal_walk(seed in any::(), writers in 2usize..=3, steps in 8usize..40) { + let history = history(seed, steps, writers); + let applied: Vec = history + .events + .iter() + .map(|sent| Applied { + id: sent.id(), + author: sent.author, + op: sent.event.header.extensions.tag.clone().expect("a tag event carries its operation"), + }) + .collect(); + let parents: HashMap> = history + .events + .iter() + .map(|sent| { + let header = &sent.event.header; + (sent.id(), header.extensions.after.iter().copied().chain(header.backlink).collect()) + }) + .collect(); + let walked = live_claims(&applied, &parents); + let folded = compacted_claims(&applied, &parents); + prop_assert_eq!(&folded, &walked); + let folded_ids: BTreeSet<[u8; 32]> = folded.iter().map(|claim| *claim.id.as_bytes()).collect(); + prop_assert_eq!(folded_ids, history.expected.clone()); + } +} + +/// The histories that shrank the two property failures (P5.1, P5.3), as `(seed, steps, writers)`. +const REGRESSION_HISTORIES: [(u64, usize, usize); 2] = [ + (12_311_497_518_687_219_712, 23, 3), + (2_831_645_957_844_276_698, 30, 3), +]; + +#[test] +fn test_each_event_names_every_event_its_author_had_seen() { + // The causal past of an event, read from its parent links, is the set its author had seen when + // it wrote it. A frontier that names too few writers leaves part of that set out of the past. + for (seed, steps, writers) in REGRESSION_HISTORIES { + let history = history(seed, steps, writers); + let parents = parents_of(&history.events); + for (id, seen) in &history.written { + assert_eq!( + causal_past(&parents[id], &parents), + *seen, + "seed {seed}, event {id:?}" + ); + } + } +} + +#[test] +fn test_the_regression_histories_reach_the_oracle_through_every_path() { + for (seed, steps, writers) in REGRESSION_HISTORIES { + let history = history(seed, steps, writers); + let (_dir, mut store) = open(); + for sent in &history.events { + deliver(&mut store, sent); + } + assert_eq!(live(&store), history.expected, "seed {seed}: the store"); + + let applied: Vec = history + .events + .iter() + .map(|sent| Applied { + id: sent.id(), + author: sent.author, + op: sent.event.header.extensions.tag.clone().unwrap(), + }) + .collect(); + let parents = parents_of(&history.events); + let ids = |claims: Vec| -> BTreeSet<[u8; 32]> { + claims.iter().map(|claim| *claim.id.as_bytes()).collect() + }; + assert_eq!( + ids(live_claims(&applied, &parents)), + history.expected, + "seed {seed}: the causal walk" + ); + assert_eq!( + ids(compacted_claims(&applied, &parents)), + history.expected, + "seed {seed}: the compacted fold" + ); + } +} diff --git a/pkgs/id/tests/tag_index.rs b/pkgs/id/tests/tag_index.rs new file mode 100644 index 0000000000..8e2a1cad1e --- /dev/null +++ b/pkgs/id/tests/tag_index.rs @@ -0,0 +1,165 @@ +//! The tag index on the tuple encoding (Phase 5, P5.2; design §9.2). +//! +//! Every prefix scan returns exactly the claims that match its query, in both directions. The +//! property draws claims whose names and values include NUL bytes, so a prefix that is only a +//! prefix of a longer field would show up. The regressions pin the `"a"` versus `"a\0b"` case. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeSet; + +use id::tag_claims::Claim; +use id::tag_index::{Entry, TagIndex}; +use p2panda_core::Hash; +use proptest::prelude::*; + +const SUBJECTS: [&[u8]; 3] = [b"subject-0", b"subject-1", b"subject-2"]; +const NAMES: [&str; 6] = ["a", "a\0b", "ab", "b", "a\0", "\0"]; +const VALUES: [Option<&str>; 7] = [ + None, + Some("a"), + Some("a\0b"), + Some("ab"), + Some(""), + Some("\0"), + Some("a\0"), +]; + +fn subject(index: usize) -> Hash { + Hash::digest(SUBJECTS[index]) +} + +/// A claim with a distinct ID per `n`, so claims never share an ID. +fn claim(n: usize, subject: Hash, name: &str, value: Option<&str>) -> Claim { + Claim { + id: Hash::digest(n.to_be_bytes()), + author: [7; 32], + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + } +} + +/// The IDs of the entries, checked for duplicates and for agreement with their claims. +fn ids_of(entries: &[Entry], claims: &[Claim]) -> BTreeSet<[u8; 32]> { + let ids: BTreeSet<[u8; 32]> = entries + .iter() + .map(|entry| *entry.claim.as_bytes()) + .collect(); + assert_eq!(ids.len(), entries.len(), "a scan returned a claim twice"); + for entry in entries { + let found = claims + .iter() + .find(|claim| claim.id == entry.claim) + .expect("a scan returned a claim that is not indexed"); + assert_eq!(found.subject, entry.subject); + assert_eq!(found.name, entry.name); + assert_eq!(found.value, entry.value); + } + ids +} + +/// The IDs of the claims that satisfy `matches`. +fn expected(claims: &[Claim], matches: impl Fn(&Claim) -> bool) -> BTreeSet<[u8; 32]> { + claims + .iter() + .filter(|claim| matches(claim)) + .map(|claim| *claim.id.as_bytes()) + .collect() +} + +fn claim_strategy() -> impl Strategy { + (0..SUBJECTS.len(), 0..NAMES.len(), 0..VALUES.len()) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })] + + /// Each scan, over random claims and random queries, returns exactly the matching claims. + #[test] + fn test_every_scan_returns_exactly_the_matching_claims( + drawn in prop::collection::vec(claim_strategy(), 0..40), + query in claim_strategy(), + ) { + let claims: Vec = drawn + .iter() + .enumerate() + .map(|(n, &(s, name, value))| claim(n, subject(s), NAMES[name], VALUES[value])) + .collect(); + let index = TagIndex::new(&claims); + prop_assert_eq!(index.len(), claims.len()); + + let (qs, qn, qv) = query; + let (s, name, value) = (subject(qs), NAMES[qn], VALUES[qv]); + + let got = ids_of(&index.subject(&s), &claims); + prop_assert_eq!(got, expected(&claims, |c| c.subject == s)); + + let got = ids_of(&index.subject_name(&s, name), &claims); + prop_assert_eq!(got, expected(&claims, |c| c.subject == s && c.name == name)); + + let got = ids_of(&index.subject_name_value(&s, name, value), &claims); + prop_assert_eq!( + got, + expected(&claims, |c| c.subject == s && c.name == name && c.value.as_deref() == value) + ); + + let got = ids_of(&index.value(value), &claims); + prop_assert_eq!(got, expected(&claims, |c| c.value.as_deref() == value)); + + let got = ids_of(&index.value_name(value, name), &claims); + prop_assert_eq!( + got, + expected(&claims, |c| c.value.as_deref() == value && c.name == name) + ); + + let got = ids_of(&index.value_name_subject(value, name, &s), &claims); + prop_assert_eq!( + got, + expected(&claims, |c| c.value.as_deref() == value && c.name == name && c.subject == s) + ); + } +} + +#[test] +fn test_the_name_a_does_not_match_the_longer_name_a_nul_b() { + let s = subject(0); + let claims = [ + claim(0, s, "a", None), + claim(1, s, "a\0b", None), + claim(2, s, "a\0", None), + ]; + let index = TagIndex::new(&claims); + let got = ids_of(&index.subject_name(&s, "a"), &claims); + assert_eq!(got, BTreeSet::from([*claims[0].id.as_bytes()])); +} + +#[test] +fn test_the_value_a_does_not_match_the_longer_value_a_nul_b_in_either_direction() { + let (s, t) = (subject(0), subject(1)); + let claims = [ + claim(0, s, "city", Some("a")), + claim(1, t, "city", Some("a\0b")), + claim(2, t, "city", Some("a\0")), + ]; + let index = TagIndex::new(&claims); + // Alpha: a subject's name and value. + let got = ids_of(&index.subject_name_value(&t, "city", Some("a")), &claims); + assert!(got.is_empty(), "a exact value on t matched a longer one"); + // Omega: the subjects with a value. + let got = ids_of(&index.value(Some("a")), &claims); + assert_eq!(got, BTreeSet::from([*claims[0].id.as_bytes()])); + let got = ids_of(&index.value_name(Some("a"), "city"), &claims); + assert_eq!(got, BTreeSet::from([*claims[0].id.as_bytes()])); +} + +#[test] +fn test_a_bare_tag_and_an_empty_value_are_different_queries() { + let s = subject(0); + let claims = [claim(0, s, "flag", None), claim(1, s, "flag", Some(""))]; + let index = TagIndex::new(&claims); + let got = ids_of(&index.subject_name_value(&s, "flag", None), &claims); + assert_eq!(got, BTreeSet::from([*claims[0].id.as_bytes()])); + let got = ids_of(&index.subject_name_value(&s, "flag", Some("")), &claims); + assert_eq!(got, BTreeSet::from([*claims[1].id.as_bytes()])); +} diff --git a/pkgs/id/tests/voiding_properties.rs b/pkgs/id/tests/voiding_properties.rs index 6b00116017..e26b15b42e 100644 --- a/pkgs/id/tests/voiding_properties.rs +++ b/pkgs/id/tests/voiding_properties.rs @@ -143,6 +143,9 @@ fn scenario(seed: u64) -> Vec { .to_owned(), group: if index == 0 { None } else { group }, after, + tag: None, + document: None, + removes: None, }; let body = action.as_ref().map(|action| encode_body(action).unwrap()); let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); diff --git a/pkgs/id/tests/voiding_scenarios.rs b/pkgs/id/tests/voiding_scenarios.rs index 179dc62527..3678f2ac4f 100644 --- a/pkgs/id/tests/voiding_scenarios.rs +++ b/pkgs/id/tests/voiding_scenarios.rs @@ -93,6 +93,9 @@ impl Builder { self.group }, after: after.iter().map(|n| self.ids[n]).collect(), + tag: None, + document: None, + removes: None, }; let body = action.as_ref().map(|action| encode_body(action).unwrap()); let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap();