diff --git a/.changeset/nip43-membership-list.md b/.changeset/nip43-membership-list.md new file mode 100644 index 000000000..b694b95ad --- /dev/null +++ b/.changeset/nip43-membership-list.md @@ -0,0 +1,11 @@ +--- +--- + +nip43: publish the relay-signed kind-13534 membership list (#1366) + +The rewrite now has v3's membership list: `nip43.publishMembershipList` gates a +relay-signed kind-13534 replaceable event listing every admitted, not-vanished member, +republished after every successful join, leave or vanish. The list carries the NIP-70 `-` +tag and one `member` tag per pubkey in ascending order, is capped at 10,000 entries, and is +stored and broadcast only when the upsert wrote a row. Default off, because publishing it +makes every member's pubkey public. diff --git a/CLI.md b/CLI.md index 687f62fad..7981b807e 100644 --- a/CLI.md +++ b/CLI.md @@ -113,7 +113,7 @@ docker compose exec nostream node src/cli/index.js invite create `--uses` defaults to `nip43.defaultMaxUses` (1). `--expires-in` defaults to `nip43.inviteCodeExpirySeconds` (600 = 10 minutes). `--expires-in` must be a positive integer; never-expiring codes are a yaml policy (`nip43.inviteCodeExpirySeconds: 0`), not a CLI flag. The printed code is the first line of human output so scripts can capture it. If `info.self` is a hex pubkey or `npub1…`, it is stored as `created_by`. -The relay also answers `REQ`s for kind 28935 by minting a code on the fly and returning it as a relay-signed ephemeral event, so users can obtain a claim string without an operator handing one out. It is off by default and requires `nip43.enabled`, `nip43.allowInviteRequests` and a NIP-42 authenticated client — see [CONFIGURATION.md](CONFIGURATION.md). Membership list events (kind 13534) are not published yet. +The relay also answers `REQ`s for kind 28935 by minting a code on the fly and returning it as a relay-signed ephemeral event, so users can obtain a claim string without an operator handing one out. It is off by default and requires `nip43.enabled`, `nip43.allowInviteRequests` and a NIP-42 authenticated client — see [CONFIGURATION.md](CONFIGURATION.md). With `nip43.publishMembershipList` on, the relay publishes a relay-signed kind-13534 membership list after every successful join, leave or vanish. Invites minted over `REQ` record the requesting pubkey as `created_by`; `nostream invite create` records `info.self`. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 4d555d713..ba73450be 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -269,6 +269,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta | nip43.defaultMaxUses | How many times a newly minted invite code can be claimed. Defaults to 1. | | nip43.allowInviteRequests | Answer REQs for kind 28935 by minting an invite code on the fly and returning it as a relay-signed ephemeral event on that subscription. NIP-43 requires relays to opt in to this explicitly. Requesters must be authenticated via NIP-42, and `info.self` must match the relay's signing pubkey. Defaults to false. | | nip43.inviteRequestWhitelist | Public keys allowed to request kind 28935 invite codes. Empty (the default) means any authenticated pubkey may request one; a non-empty list restricts minting to those pubkeys. | +| nip43.publishMembershipList | Publish the relay-signed kind-13534 membership list after every successful join, leave or vanish. Defaults to false because it makes every member's pubkey public. The event is signed by the relay, and its size can exceed `network.maxPayloadSize`, which bounds inbound frames only. | | nip45.enabled | Enable or disable NIP-45 COUNT handling. Defaults to true. | | nip50.enabled | Enable or disable NIP-50 full-text search. Defaults to false. When enabled, clients can include a `search` field in REQ filters to perform text queries against event content. Requires the GIN full-text index migration. | | nip50.language | PostgreSQL text-search configuration name. Defaults to `simple` (language-agnostic tokenization). Set to `english`, `spanish`, etc. for stemming support. See [PostgreSQL text search configurations](https://www.postgresql.org/docs/current/textsearch-configuration.html). **Note:** The GIN index migration is built with the `simple` configuration. If you change this value, you must manually rebuild the index: `DROP INDEX CONCURRENTLY events_content_fts_idx; CREATE INDEX CONCURRENTLY events_content_fts_idx ON events USING gin (to_tsvector('', event_content));` — otherwise the planner cannot use the index and queries fall back to sequential scans. | diff --git a/Cargo.lock b/Cargo.lock index 0125d5570..591967b4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1562,6 +1562,7 @@ dependencies = [ "serde_json", "serde_yaml", "sha2 0.11.1", + "tempfile", "thiserror", "tokio", "tokio-tungstenite", diff --git a/crates/nostream-admin/tests/common/mod.rs b/crates/nostream-admin/tests/common/mod.rs index d00e55d47..7d42d4701 100644 --- a/crates/nostream-admin/tests/common/mod.rs +++ b/crates/nostream-admin/tests/common/mod.rs @@ -544,6 +544,17 @@ impl EventRepository for SlowEventRepository { Box::pin(async { Err(not_implemented()) }) } + fn find_stored_replaceable<'a>( + &'a self, + _pubkey: &'a nostream_core::Pubkey, + _kind: nostream_core::Kind, + ) -> nostream_storage::repositories::StorageFuture< + 'a, + Option, + > { + Box::pin(async { Err(not_implemented()) }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a nostream_core::Pubkey, diff --git a/crates/nostream-config/src/settings.rs b/crates/nostream-config/src/settings.rs index 58077fca2..c7e3773c7 100644 --- a/crates/nostream-config/src/settings.rs +++ b/crates/nostream-config/src/settings.rs @@ -782,6 +782,10 @@ pub struct Nip43Settings { pub allow_invite_requests: Option, #[serde(skip_serializing_if = "Option::is_none")] pub invite_request_whitelist: Option>, + /// Publish the relay-signed kind-13534 membership list after every membership change. + /// Off by default because the list makes every member's pubkey public. + #[serde(skip_serializing_if = "Option::is_none")] + pub publish_membership_list: Option, } /// `nip77` (`src/@types/settings.ts` `Nip77Settings`). diff --git a/crates/nostream-config/tests/defaults_parity.rs b/crates/nostream-config/tests/defaults_parity.rs index 7cece411b..c167223a7 100644 --- a/crates/nostream-config/tests/defaults_parity.rs +++ b/crates/nostream-config/tests/defaults_parity.rs @@ -52,6 +52,7 @@ fn nip43_defaults_are_the_capture_mint_defaults() { "nip43.inviteRequestWhitelist", Value::Sequence(vec![]), ); + assert_value(&defaults, "nip43.publishMembershipList", boolean(false)); } #[test] diff --git a/crates/nostream-config/tests/defaults_roundtrip.rs b/crates/nostream-config/tests/defaults_roundtrip.rs index 176e5c776..b69125503 100644 --- a/crates/nostream-config/tests/defaults_roundtrip.rs +++ b/crates/nostream-config/tests/defaults_roundtrip.rs @@ -23,6 +23,30 @@ fn defaults() -> Value { serde_yaml::from_str(&raw).expect("the shipped defaults are valid YAML") } +/// The membership-list gate is shipped off, and the typed field round-trips it. +#[test] +fn the_typed_schema_carries_publish_membership_list() { + let defaults = defaults(); + let settings: Settings = + serde_yaml::from_value(defaults.clone()).expect("the defaults fit the typed schema"); + + assert_eq!( + settings + .nip43 + .as_ref() + .and_then(|nip43| nip43.publish_membership_list), + Some(false), + "the shipped default publishes no membership list" + ); + + let again = serde_yaml::to_value(&settings).expect("the typed settings serialize"); + assert_eq!( + again["nip43"]["publishMembershipList"], + Value::Bool(false), + "the typed field serializes under its camelCase name" + ); +} + #[test] fn the_shipped_defaults_validate_with_no_issues() { let defaults = defaults(); diff --git a/crates/nostream-core/src/nip19.rs b/crates/nostream-core/src/nip19.rs index 57469864d..515efa44f 100644 --- a/crates/nostream-core/src/nip19.rs +++ b/crates/nostream-core/src/nip19.rs @@ -38,6 +38,26 @@ pub fn decode_npub_hex(value: &str) -> Result { Ok(hex::encode(decode_npub(value)?)) } +/// Encodes one lowercase hex pubkey as its `npub1…` form, the inverse of [`decode_npub_hex`]. +pub fn encode_npub(pubkey_hex: &str) -> Result { + let bytes: [u8; 32] = hex::decode(pubkey_hex) + .map_err(|error| { + CoreError::InvalidMessage(format!("nip19: `{pubkey_hex}` is not hexadecimal: {error}")) + })? + .try_into() + .map_err(|bytes: Vec| { + CoreError::InvalidMessage(format!( + "nip19: `{pubkey_hex}` decoded to {} bytes, not 32", + bytes.len() + )) + })?; + let hrp = bech32::Hrp::parse("npub") + .map_err(|error| CoreError::InvalidMessage(format!("nip19: npub prefix: {error}")))?; + + bech32::encode::(hrp, &bytes) + .map_err(|error| CoreError::InvalidMessage(format!("nip19: npub encode: {error}"))) +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -62,6 +82,18 @@ mod tests { assert_eq!(encoded, NPUB); } + #[test] + fn an_npub_encodes_and_decodes() { + let npub = encode_npub(HEX).expect("the fixture encodes"); + assert_eq!(npub, NPUB); + assert_eq!( + decode_npub_hex(&npub).expect("the npub decodes"), + HEX, + "the encoded form decodes back to the original hex" + ); + assert!(encode_npub("not-hex").is_err()); + } + #[test] fn a_malformed_npub_is_refused() { assert!(decode_npub("npub1invalid").is_err()); diff --git a/crates/nostream-core/src/nip43.rs b/crates/nostream-core/src/nip43.rs index a5f93a3c7..d285a0800 100644 --- a/crates/nostream-core/src/nip43.rs +++ b/crates/nostream-core/src/nip43.rs @@ -2,8 +2,9 @@ //! `src/utils/nip43-invites.ts`. //! //! The pure half is implemented: the invite code's entropy, the limits the settings -//! resolve, and the relay-signed kind-28935 event that answers a REQ. Persisting the code is -//! the REQ handler's call into `InviteCodeRepository`; [`InviteCode`] is the row shape. +//! resolve, the relay-signed kind-28935 event that answers a REQ, and the relay-signed +//! kind-13534 membership list. Persisting the code is the REQ handler's call into +//! `InviteCodeRepository`; [`InviteCode`] is the row shape. use crate::error::CoreError; use crate::event::{Event, Kind, Pubkey}; @@ -25,6 +26,10 @@ pub const DEFAULT_INVITE_MAX_USES: u32 = 1; /// `src/utils/nip43-invites.ts:11`). pub const DEFAULT_INVITE_CODE_EXPIRY_SECONDS: u64 = 600; +/// The most members one published kind-13534 membership list carries +/// (`MAX_MEMBERSHIP_LIST_ENTRIES`, `src/utils/nip43-membership.ts:17`). +pub const MAX_MEMBERSHIP_LIST_ENTRIES: usize = 10_000; + /// The limits one minted code carries (`resolveInviteCodeLimits`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct InviteCodeLimits { @@ -106,6 +111,38 @@ pub fn build_invite_code_event( Ok(event) } +/// Builds the relay-signed kind-13534 membership list (`buildMembershipListEvent`, +/// `src/utils/nip43-membership.ts:23-44`). +/// +/// The NIP-70 `-` tag comes first, then one `member` tag per pubkey in the order given: the +/// query's ascending order, never sorted here. A list with no members is exactly `[["-"]]`. +pub fn build_membership_list_event( + secret_key: &[u8; 32], + members: &[Pubkey], + created_at: i64, +) -> Result { + let mut tags = vec![vec!["-".to_owned()]]; + tags.extend( + members + .iter() + .map(|member| vec!["member".to_owned(), member.to_string()]), + ); + + let mut event = Event { + id: crate::event::EventId::from_byte_array([0; 32]), + pubkey: crate::event::Pubkey::from_byte_array([0; 32]), + created_at, + kind: Kind(13_534), + tags, + content: String::new(), + sig: crate::event::Signature::from_byte_array([0; 64]), + }; + + crate::crypto::sign_event(secret_key, &mut event)?; + + Ok(event) +} + /// Whether a kind is the membership join request (`src/utils/nip43.ts`). pub fn is_join_request(kind: Kind) -> bool { kind == Kind(28_934) @@ -174,4 +211,52 @@ mod tests { assert!(!is_request_timestamp_valid(now - 601, now)); assert!(!is_request_timestamp_valid(now + 3600, now)); } + + fn member(byte: u8) -> Pubkey { + Pubkey::from_byte_array([byte; 32]) + } + + #[test] + fn membership_list_event_has_the_captures_kind_tags_and_signature() { + let secret = [1u8; 32]; + let first = member(0xaa); + let second = member(0xbb); + + let event = build_membership_list_event(&secret, &[first, second], 1_700_000_000).unwrap(); + + assert_eq!(event.kind, Kind(13_534)); + assert_eq!(event.pubkey, crate::crypto::public_key(&secret).unwrap()); + assert_eq!(event.created_at, 1_700_000_000); + assert_eq!(event.content, ""); + assert_eq!( + event.tags, + vec![ + vec!["-".to_owned()], + vec!["member".to_owned(), first.to_string()], + vec!["member".to_owned(), second.to_string()], + ] + ); + assert!(event.is_protected()); + crate::crypto::verify_event_signature(&event).expect("the relay-signed event verifies"); + } + + #[test] + fn an_empty_membership_list_has_only_the_protected_tag() { + let event = build_membership_list_event(&[1u8; 32], &[], 1_700_000_000).unwrap(); + + assert_eq!(event.tags, vec![vec!["-".to_owned()]]); + assert!(event.is_protected()); + } + + #[test] + fn the_membership_list_builder_keeps_the_member_order_it_is_given() { + let first = member(0xaa); + let second = member(0xbb); + + let event = + build_membership_list_event(&[1u8; 32], &[second, first], 1_700_000_000).unwrap(); + + assert_eq!(event.tags[1][1], second.to_string()); + assert_eq!(event.tags[2][1], first.to_string()); + } } diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 590da271a..6a5b8003b 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -635,6 +635,14 @@ impl EventRepository for VanishingRepository { EventRepository::find_stored(&*self.inner, id) } + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option> { + self.inner.find_stored_replaceable(pubkey, kind) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -772,6 +780,14 @@ impl EventRepository for ZeroCountDeleter { EventRepository::find_stored(&*self.inner, id) } + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option> { + self.inner.find_stored_replaceable(pubkey, kind) + } + /// The real soft delete, and a count that says nothing happened. fn delete_by_pubkey_and_ids<'a>( &'a self, @@ -905,4 +921,8 @@ impl nostream_storage::repositories::UserRepository for NoBalanceRead { fn revoke_admission<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, u64> { nostream_storage::repositories::UserRepository::revoke_admission(&*self.inner, pubkey) } + + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + nostream_storage::repositories::UserRepository::find_admitted_pubkeys(&*self.inner, limit) + } } diff --git a/crates/nostream-relay/Cargo.toml b/crates/nostream-relay/Cargo.toml index 6f96c49b0..b8a8dccc1 100644 --- a/crates/nostream-relay/Cargo.toml +++ b/crates/nostream-relay/Cargo.toml @@ -25,6 +25,7 @@ tracing.workspace = true [dev-dependencies] base64.workspace = true +tempfile.workspace = true serde_yaml.workspace = true [lints] diff --git a/crates/nostream-relay/src/lib.rs b/crates/nostream-relay/src/lib.rs index 531fa8d92..dc7147ce8 100644 --- a/crates/nostream-relay/src/lib.rs +++ b/crates/nostream-relay/src/lib.rs @@ -11,6 +11,7 @@ //! - `src/controllers/admission/get-admission-check-controller.ts`, //! `src/routes/admissions/index.ts` //! - `src/utils/{sliding-window-rate-limiter,ewma-rate-limiter,hidden-content-cache}.ts` +//! - `src/utils/nip43-membership.ts` (the relay-signed membership list) //! - `src/@types/{message-handlers,subscription,clients}.ts` //! - `src/factories/{event-strategy-factory,message-handler-factory, //! websocket-adapter-factory,rate-limiter-factory}.ts` @@ -54,6 +55,7 @@ pub mod hidden_content; pub mod limits; pub mod metrics; pub mod nip11; +pub mod nip43_membership; pub mod relay; pub mod relay_key; pub mod sink; diff --git a/crates/nostream-relay/src/nip43_membership.rs b/crates/nostream-relay/src/nip43_membership.rs new file mode 100644 index 000000000..c1f05fc81 --- /dev/null +++ b/crates/nostream-relay/src/nip43_membership.rs @@ -0,0 +1,212 @@ +//! The relay-signed kind-13534 membership list (`src/utils/nip43-membership.ts`). +//! +//! One replaceable event lists every admitted, not-vanished member and is signed with the +//! relay's own key. A successful join, leave or vanish publishes it after the membership write +//! and before that request's `OK`, so a refresh never fails the request. There is no timer and +//! no boot publish: v3 has neither, and the stored event is served by an ordinary REQ until the +//! next membership change replaces it. + +use std::sync::Arc; + +use nostream_core::Kind; +use nostream_core::nip19; +use nostream_core::nip43::{MAX_MEMBERSHIP_LIST_ENTRIES, build_membership_list_event}; +use nostream_storage::repositories::EventRecord; + +use crate::handlers::HandlerContext; +use tracing::{info, warn}; + +/// The kind of the membership list (`NIP43_MEMBERSHIP_LIST`, `src/constants/base.ts:64`). +const MEMBERSHIP_LIST_KIND: Kind = Kind(13_534); + +/// How many rows one publish asks for: the cap plus one, so a truncated list is detectable. +const QUERY_LIMIT: u64 = MAX_MEMBERSHIP_LIST_ENTRIES as u64 + 1; + +/// v3's module-level promise queue (`src/utils/nip43-membership.ts:46-49`) as a mutex: one +/// publish's read-modify-write at a time, so two cannot both read the same stored `created_at`. +static PUBLISH_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// What a configured `info.self` says about the derived key (`isRelaySelfConsistent`, +/// `src/utils/nip43.ts:59-71`, over `parseRelayPubkey`, `src/utils/nip43-invites.ts:26-47`). +#[derive(Debug, PartialEq, Eq)] +enum RelaySelf { + /// Absent, empty, or a string v3's parser does not recognise: nothing to compare. + Unset, + Matches, + Differs, + /// An `npub1…` value that does not decode. + Unparsable(String), +} + +/// Publishes the membership list when the settings ask for it, and does nothing otherwise. +pub async fn publish_membership_list(context: &HandlerContext) { + let Some(nip43) = context.settings.nip43.as_ref() else { + return; + }; + + if !nip43.enabled || nip43.publish_membership_list != Some(true) { + return; + } + + let keys = match context.keys.resolve(context.relay_url()) { + Ok(keys) => keys, + Err(error) => { + warn!("unable to derive the relay signing pubkey: {error}"); + + return; + } + }; + + match relay_self(context.settings.info.self_.as_deref(), &keys.public_key) { + RelaySelf::Unset | RelaySelf::Matches => {} + RelaySelf::Differs => { + warn!( + "info.self does not match the relay signing pubkey, not publishing the membership list" + ); + + return; + } + RelaySelf::Unparsable(error) => { + warn!("info.self is not a valid pubkey, not publishing the membership list: {error}"); + + return; + } + } + + // Acquired after the gate so a disabled publish never waits, and held across the whole + // read-modify-write so the later of two publishes sees the earlier one's row. + let _guard = PUBLISH_LOCK.lock().await; + + let members = match context + .stores + .users + .find_admitted_pubkeys(QUERY_LIMIT) + .await + { + Ok(members) => members, + Err(error) => { + warn!("unable to publish the membership list: {error}"); + + return; + } + }; + + let members = if members.len() > MAX_MEMBERSHIP_LIST_ENTRIES { + warn!("more than 10000 members, the membership list is cut to the first ones"); + + &members[..MAX_MEMBERSHIP_LIST_ENTRIES] + } else { + &members[..] + }; + + let stored = match context + .stores + .events + .find_stored_replaceable(&keys.public_key, MEMBERSHIP_LIST_KIND) + .await + { + Ok(stored) => stored, + Err(error) => { + warn!("unable to publish the membership list: {error}"); + + return; + } + }; + + let now = context.now_secs(); + let created_at = stored.map_or(now, |item| now.max(item.created_at.saturating_add(1))); + + let event = match build_membership_list_event(&keys.secret_key, members, created_at) { + Ok(event) => event, + Err(error) => { + warn!("unable to publish the membership list: {error}"); + + return; + } + }; + + let record = EventRecord::from_event(&event); + + match context.stores.events.upsert(&record).await { + Ok(count) => { + info!("published a membership list with {} members", members.len()); + + if count > 0 { + let _ = context.broadcast.send(Arc::new(event)); + } + } + Err(error) => warn!("unable to publish the membership list: {error}"), + } +} + +/// v3's `info.self` rule: a 64-hex value compares case-insensitively, an `npub1…` value is +/// decoded (a failure is [`RelaySelf::Unparsable`]), and any other string is treated as unset. +fn relay_self(configured: Option<&str>, derived: &nostream_core::Pubkey) -> RelaySelf { + let Some(configured) = configured.filter(|value| !value.is_empty()) else { + return RelaySelf::Unset; + }; + let derived_hex = derived.to_string(); + + if configured.len() == 64 && configured.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return if configured.eq_ignore_ascii_case(&derived_hex) { + RelaySelf::Matches + } else { + RelaySelf::Differs + }; + } + + if configured.to_ascii_lowercase().starts_with("npub1") { + return match nip19::decode_npub_hex(configured) { + Ok(hex) if hex == derived_hex => RelaySelf::Matches, + Ok(_) => RelaySelf::Differs, + Err(error) => RelaySelf::Unparsable(error.to_string()), + }; + } + + RelaySelf::Unset +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used)] + + use super::*; + + const DERIVED: &str = "22e804d26ed16b68db5259e78449e96dab5d464c8f470bda3eb1a70467f2c793"; + const OTHER: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + + fn derived() -> nostream_core::Pubkey { + serde_json::from_value(serde_json::Value::String(DERIVED.to_owned())).expect("a pubkey") + } + + #[test] + fn info_self_is_read_as_v3_reads_it() { + assert_eq!(relay_self(None, &derived()), RelaySelf::Unset); + assert_eq!(relay_self(Some(""), &derived()), RelaySelf::Unset); + assert_eq!( + relay_self(Some("not-a-pubkey"), &derived()), + RelaySelf::Unset + ); + assert_eq!(relay_self(Some(DERIVED), &derived()), RelaySelf::Matches); + assert_eq!( + relay_self(Some(&DERIVED.to_ascii_uppercase()), &derived()), + RelaySelf::Matches + ); + assert_eq!(relay_self(Some(OTHER), &derived()), RelaySelf::Differs); + + let matching_npub = nip19::encode_npub(DERIVED).expect("the npub"); + assert_eq!( + relay_self(Some(&matching_npub), &derived()), + RelaySelf::Matches + ); + let other_npub = nip19::encode_npub(OTHER).expect("the npub"); + assert_eq!( + relay_self(Some(&other_npub), &derived()), + RelaySelf::Differs + ); + assert!(matches!( + relay_self(Some("npub1invalid"), &derived()), + RelaySelf::Unparsable(_) + )); + } +} diff --git a/crates/nostream-relay/src/strategies/join_request.rs b/crates/nostream-relay/src/strategies/join_request.rs index d746bf52e..ba8637446 100644 --- a/crates/nostream-relay/src/strategies/join_request.rs +++ b/crates/nostream-relay/src/strategies/join_request.rs @@ -118,6 +118,8 @@ impl EventStrategy for JoinRequestStrategy { .admit_user(&event.pubkey, admitted_at(context)) .await?; + crate::nip43_membership::publish_membership_list(context).await; + context.send_ok( event.id, true, diff --git a/crates/nostream-relay/src/strategies/leave_request.rs b/crates/nostream-relay/src/strategies/leave_request.rs index fc9f0ed43..6faa4108e 100644 --- a/crates/nostream-relay/src/strategies/leave_request.rs +++ b/crates/nostream-relay/src/strategies/leave_request.rs @@ -90,6 +90,8 @@ impl EventStrategy for LeaveRequestStrategy { context.stores.users.revoke_admission(&event.pubkey).await?; + crate::nip43_membership::publish_membership_list(context).await; + context.send_ok(event.id, true, "", None); Ok(()) diff --git a/crates/nostream-relay/src/strategies/vanish.rs b/crates/nostream-relay/src/strategies/vanish.rs index 649c489a2..c0dd9ff4b 100644 --- a/crates/nostream-relay/src/strategies/vanish.rs +++ b/crates/nostream-relay/src/strategies/vanish.rs @@ -42,6 +42,8 @@ impl EventStrategy for VanishStrategy { .set_vanished(&event.pubkey, true) .await?; + crate::nip43_membership::publish_membership_list(context).await; + context.send_ok( event.id, true, diff --git a/crates/nostream-relay/src/testing.rs b/crates/nostream-relay/src/testing.rs index 7561320ec..2c9530d5f 100644 --- a/crates/nostream-relay/src/testing.rs +++ b/crates/nostream-relay/src/testing.rs @@ -117,6 +117,7 @@ pub fn nip43_settings() -> Nip43Settings { default_max_uses: None, allow_invite_requests: Some(true), invite_request_whitelist: None, + publish_membership_list: None, } } @@ -175,6 +176,9 @@ pub struct InMemoryEventRepository { /// leaves behind in LMDB. vanishing: Mutex>, upsert_failure: Mutex>, + /// When set, `upsert` answers 0 without writing, so a caller's no-broadcast branch can be + /// reached against a store that never wrote. + upsert_answers_zero: AtomicBool, upserts: Mutex>>, deletes: Mutex)>>, address_deletes: Mutex>, @@ -368,6 +372,11 @@ impl InMemoryEventRepository { .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(failure); } + /// Makes every `upsert` answer 0 without writing a row. + pub fn upsert_answers_zero(&self, zero: bool) { + self.upsert_answers_zero.store(zero, Ordering::SeqCst); + } + /// Makes both soft deletes fail. pub fn fail_delete(&self) { self.fail_delete.store(true, Ordering::SeqCst); @@ -483,6 +492,10 @@ impl EventRepository for InMemoryEventRepository { }); } + if self.upsert_answers_zero.load(Ordering::SeqCst) { + return Ok(0); + } + let mut records = self .records .lock() @@ -751,6 +764,32 @@ impl EventRepository for InMemoryEventRepository { }) } + /// The slot read: the newest row of `(pubkey, kind)`, smallest id on a tie, deleted or not. + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option> { + Box::pin(async move { + Ok(self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|record| record.event.pubkey == *pubkey && record.event.kind == kind) + .max_by(|left, right| { + left.event + .created_at + .cmp(&right.event.created_at) + .then_with(|| right.event.id.cmp(&left.event.id)) + }) + .map(|record| ReconciliationItem { + created_at: record.event.created_at, + event_id: record.event.id, + })) + }) + } + /// `UPDATE … SET deleted_at = now()` for the given ids of one author, skipping kind 62. fn delete_by_pubkey_and_ids<'a>( &'a self, @@ -924,6 +963,7 @@ impl EventRepository for InMemoryEventRepository { pub struct InMemoryUserRepository { users: Mutex>, vanish_calls: Mutex>, + admitted_queries: Mutex>, fail_reads: AtomicBool, } @@ -953,6 +993,14 @@ impl InMemoryUserRepository { .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } + + /// The `limit` each `find_admitted_pubkeys` was asked for, in call order. + pub fn admitted_queries(&self) -> Vec { + self.admitted_queries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } } impl UserRepository for InMemoryUserRepository { @@ -975,6 +1023,25 @@ impl UserRepository for InMemoryUserRepository { }) } + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async move { + self.admitted_queries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(limit); + + Ok(self + .users + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .values() + .filter(|user| user.is_admitted && !user.is_vanished) + .take(usize::try_from(limit).unwrap_or(usize::MAX)) + .map(|user| user.pubkey) + .collect()) + }) + } + fn upsert<'a>(&'a self, patch: &'a UserPatch) -> StorageFuture<'a, u64> { Box::pin(async move { let now = chrono::Utc::now(); diff --git a/crates/nostream-relay/src/unavailable.rs b/crates/nostream-relay/src/unavailable.rs index fbe9019a7..832bb5bb3 100644 --- a/crates/nostream-relay/src/unavailable.rs +++ b/crates/nostream-relay/src/unavailable.rs @@ -109,6 +109,14 @@ impl EventRepository for UnavailableEventRepository { Box::pin(async { Err(unavailable()) }) } + fn find_stored_replaceable<'a>( + &'a self, + _pubkey: &'a Pubkey, + _kind: Kind, + ) -> StorageFuture<'a, Option> { + Box::pin(async { Err(unavailable()) }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a Pubkey, @@ -208,6 +216,10 @@ impl UserRepository for UnavailableUserRepository { fn revoke_admission<'a>(&'a self, _pubkey: &'a Pubkey) -> StorageFuture<'a, u64> { Box::pin(async { Err(unavailable()) }) } + + fn find_admitted_pubkeys<'a>(&'a self, _limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async { Err(unavailable()) }) + } } /// The NIP-05 store. diff --git a/crates/nostream-relay/tests/nip43_membership.rs b/crates/nostream-relay/tests/nip43_membership.rs new file mode 100644 index 000000000..e1f74c611 --- /dev/null +++ b/crates/nostream-relay/tests/nip43_membership.rs @@ -0,0 +1,782 @@ +//! The relay-signed kind-13534 membership list (`src/utils/nip43-membership.ts`). +//! +//! These drive the public publisher and the three strategies that call it: the gate, the +//! `info.self` refusals, the cap, the `created_at` rule, the serialisation, a real LMDB slot +//! and one full-size frame over a socket. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use nostream_config::settings::Settings; +use nostream_core::clock::TestClock; +use nostream_core::crypto::public_key; +use nostream_core::event::{EventId, Signature}; +use nostream_core::messages::{CommandResult, RelayMessage}; +use nostream_core::nip19; +use nostream_core::nip42::Nip42Session; +use nostream_core::{Event, Filter, Kind, Pubkey}; +use nostream_relay::connection::Connection; +use nostream_relay::handlers::{HandlerContext, Stores}; +use nostream_relay::nip43_membership::publish_membership_list; +use nostream_relay::sink::FrameSink; +use nostream_relay::strategies::EventStrategy; +use nostream_relay::strategies::join_request::JoinRequestStrategy; +use nostream_relay::testing::{Fixture, UpsertFailure, hub_receiver, nip43_settings, settings}; +use nostream_storage::repositories::{ + CreateInviteCodeOptions, EventRepository, FieldUpdate, InviteCodeRepository, StorageFuture, + User, UserPatch, UserRepository, +}; +use nostream_storage::{LmdbBackend, Repositories}; +use serde_json::Value; +use tokio::sync::{mpsc, oneshot}; + +use common::{ + CLIENT_SECRET, NOW_MS, NOW_SECS, RELAY_SECRET, Server, fast_config, relay_keys, signed_event, +}; + +/// Settings with NIP-43 on and the membership list gated by `publish`. +fn publish_settings(publish: Option, enabled: bool) -> Settings { + let mut settings = settings(); + let mut nip43 = nip43_settings(); + nip43.enabled = enabled; + nip43.publish_membership_list = publish; + settings.nip43 = Some(nip43); + + settings +} + +fn publishing_context(fixture: &Fixture) -> HandlerContext { + fixture.anonymous_context(Arc::new(TestClock::new(NOW_MS)), relay_keys()) +} + +fn membership_filter() -> Filter { + Filter { + kinds: Some(vec![Kind(13_534)]), + ..Filter::default() + } +} + +fn membership_event(fixture: &Fixture) -> Event { + fixture + .events + .events() + .into_iter() + .find(|event| event.kind == Kind(13_534)) + .expect("a published membership list") +} + +fn user(pubkey: Pubkey) -> User { + User { + pubkey, + is_admitted: true, + is_vanished: false, + balance: 0, + created_at: Utc::now(), + updated_at: Utc::now(), + } +} + +/// A pubkey whose ascending order is its index: the first 28 bytes are zero. +fn counter_member(index: u32) -> Pubkey { + let mut bytes = [0u8; 32]; + bytes[28..].copy_from_slice(&index.to_be_bytes()); + Pubkey::from_byte_array(bytes) +} + +fn member_tag(pubkey: &Pubkey) -> Vec { + vec!["member".to_owned(), pubkey.to_string()] +} + +fn protected_tag() -> Vec { + vec!["-".to_owned()] +} + +fn options(remaining_uses: i32) -> CreateInviteCodeOptions { + CreateInviteCodeOptions { + expires_at: None, + remaining_uses: FieldUpdate::Set(remaining_uses), + created_by: None, + } +} + +fn event(kind: u64, tags: Vec>) -> Event { + Event { + id: EventId::from_byte_array([0x11; 32]), + pubkey: author(), + created_at: NOW_SECS, + kind: Kind(kind), + tags, + content: String::new(), + sig: Signature::from_byte_array([0x33; 64]), + } +} + +fn author() -> Pubkey { + Pubkey::from_byte_array([0x22; 32]) +} + +fn join_event() -> Event { + event( + 28_934, + vec![vec!["claim".to_owned(), "valid-code".to_owned()]], + ) +} + +/// A context whose sink a test can read, with its frames. +fn socket(fixture: &Fixture) -> (HandlerContext, mpsc::UnboundedReceiver) { + let (sink, frames) = FrameSink::channel(64 * 1024, None); + let connection = Arc::new(Connection::new( + "127.0.0.1".to_owned(), + Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), + )); + + ( + fixture.context( + Arc::new(TestClock::new(NOW_MS)), + relay_keys(), + connection, + sink, + ), + frames, + ) +} + +fn authenticated_socket( + fixture: &Fixture, + pubkey: Pubkey, +) -> (HandlerContext, mpsc::UnboundedReceiver) { + let (context, frames) = socket(fixture); + + context.connection.authenticate( + pubkey, + EventId::from_byte_array([0x09; 32]), + context.now_secs(), + ); + + (context, frames) +} + +fn frames(receiver: &mut mpsc::UnboundedReceiver) -> Vec { + let mut queued = Vec::new(); + + while let Ok(frame) = receiver.try_recv() { + queued.push(frame); + } + + queued +} + +fn ok_frame(event: &Event, accepted: bool, message: &str) -> String { + RelayMessage::Ok(CommandResult { + event_id: event.id, + accepted, + message: message.to_owned(), + params: None, + }) + .to_text() +} + +#[tokio::test] +async fn two_publishes_in_one_second_leave_one_row_and_two_frames() { + let directory = tempfile::tempdir().expect("tempdir"); + let backend = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let repositories = Repositories::over(backend); + let fixture = Fixture::new(publish_settings(Some(true), true)); + let mut context = publishing_context(&fixture); + context.stores = Arc::new(Stores::from(&repositories)); + let relay_pubkey = public_key(&RELAY_SECRET).expect("the relay pubkey"); + + let admitted_at = DateTime::from_timestamp(NOW_SECS, 0).expect("a timestamp"); + let first = counter_member(0x11); + let second = counter_member(0x22); + let vanished = counter_member(0x33); + for pubkey in [first, second, vanished] { + repositories + .users + .admit_user(&pubkey, admitted_at) + .await + .expect("the admission"); + } + repositories + .users + .set_vanished(&vanished, true) + .await + .expect("the vanish write"); + + let mut hub = hub_receiver(&fixture.hub); + publish_membership_list(&context).await; + publish_membership_list(&context).await; + + let filter = Filter { + kinds: Some(vec![Kind(13_534)]), + authors: Some(vec![relay_pubkey.to_string()]), + ..Filter::default() + }; + assert_eq!( + repositories + .events + .count_by_filters(std::slice::from_ref(&filter)) + .await + .expect("the count"), + 1 + ); + + let slot = repositories + .events + .find_stored_replaceable(&relay_pubkey, Kind(13_534)) + .await + .expect("the slot") + .expect("a stored list"); + assert_eq!( + slot.created_at, + NOW_SECS + 1, + "the second publish is stored + 1" + ); + + let expected = vec![protected_tag(), member_tag(&first), member_tag(&second)]; + let stored = repositories + .events + .find_stored(&slot.event_id) + .await + .expect("the row") + .expect("a row"); + assert_eq!(stored.event.created_at, NOW_SECS + 1); + assert_eq!(stored.event.tags, expected); + + let first_frame = hub.try_recv().expect("the first frame"); + let second_frame = hub.try_recv().expect("the second frame"); + assert_eq!(first_frame.created_at, NOW_SECS); + assert_eq!(second_frame.created_at, NOW_SECS + 1); + assert_ne!(first_frame.id, second_frame.id); + assert_eq!(first_frame.tags, expected); + assert_eq!(second_frame.tags, expected); + assert!(hub.try_recv().is_err(), "exactly two frames"); +} + +#[tokio::test] +async fn the_created_at_is_the_later_of_the_clock_and_the_stored_second() { + let fixture = Fixture::new(publish_settings(Some(true), true)); + let clock = Arc::new(TestClock::new(NOW_MS)); + let context = fixture.anonymous_context(clock.clone(), relay_keys()); + fixture.users.insert(user(counter_member(0x11))); + let mut hub = hub_receiver(&fixture.hub); + + publish_membership_list(&context).await; + let first = hub.try_recv().expect("the first frame"); + assert_eq!(first.created_at, NOW_SECS); + + publish_membership_list(&context).await; + let second = hub.try_recv().expect("the second frame"); + assert_eq!(second.created_at, NOW_SECS + 1, "the stored + 1 branch"); + assert_eq!( + membership_event(&fixture).created_at, + NOW_SECS + 1, + "the stored row follows the frame" + ); + + clock.advance(500_000); + publish_membership_list(&context).await; + let third = hub.try_recv().expect("the third frame"); + assert_eq!(third.created_at, NOW_SECS + 500, "the clock branch"); + assert_eq!(membership_event(&fixture).created_at, NOW_SECS + 500); +} + +#[tokio::test] +async fn the_gate_setting_off_publishes_nothing() { + for publish in [None, Some(false)] { + let fixture = Fixture::new(publish_settings(publish, true)); + let context = publishing_context(&fixture); + let mut hub = hub_receiver(&fixture.hub); + + publish_membership_list(&context).await; + + assert_eq!( + fixture + .events + .count_by_filters(&[membership_filter()]) + .await + .expect("the count"), + 0 + ); + assert!(hub.try_recv().is_err()); + assert!(fixture.users.admitted_queries().is_empty()); + } +} + +#[tokio::test] +async fn the_gate_nip43_disabled_publishes_nothing() { + let fixture = Fixture::new(publish_settings(Some(true), false)); + let context = publishing_context(&fixture); + let mut hub = hub_receiver(&fixture.hub); + + publish_membership_list(&context).await; + + assert_eq!( + fixture + .events + .count_by_filters(&[membership_filter()]) + .await + .expect("the count"), + 0 + ); + assert!(hub.try_recv().is_err()); + assert!(fixture.users.admitted_queries().is_empty()); +} + +async fn publish_with_self(value: Option<&str>) -> (Fixture, u64, bool) { + let mut settings = publish_settings(Some(true), true); + settings.info.self_ = value.map(str::to_owned); + let fixture = Fixture::new(settings); + fixture.users.insert(user(counter_member(0x11))); + let context = publishing_context(&fixture); + let mut hub = hub_receiver(&fixture.hub); + + publish_membership_list(&context).await; + + let rows = fixture + .events + .count_by_filters(&[membership_filter()]) + .await + .expect("the count"); + let broadcast = hub.try_recv().is_ok(); + + (fixture, rows, broadcast) +} + +#[tokio::test] +async fn info_self_matching_hex_publishes() { + let relay_hex = public_key(&RELAY_SECRET) + .expect("the relay pubkey") + .to_string(); + let (fixture, rows, broadcast) = publish_with_self(Some(&relay_hex)).await; + + assert_eq!(rows, 1); + assert!(broadcast); + assert_eq!(fixture.users.admitted_queries(), vec![10_001]); +} + +#[tokio::test] +async fn info_self_matching_npub_publishes() { + let relay_hex = public_key(&RELAY_SECRET) + .expect("the relay pubkey") + .to_string(); + let npub = nip19::encode_npub(&relay_hex).expect("the npub"); + let (fixture, rows, broadcast) = publish_with_self(Some(&npub)).await; + + assert_eq!(rows, 1); + assert!(broadcast); + assert_eq!(fixture.users.admitted_queries(), vec![10_001]); +} + +#[tokio::test] +async fn info_self_mismatched_hex_publishes_nothing() { + let other = public_key(&[2u8; 32]).expect("a pubkey").to_string(); + let (fixture, rows, broadcast) = publish_with_self(Some(&other)).await; + + assert_eq!(rows, 0); + assert!(!broadcast); + assert!(fixture.users.admitted_queries().is_empty()); +} + +#[tokio::test] +async fn info_self_mismatched_npub_publishes_nothing() { + let other = public_key(&[2u8; 32]).expect("a pubkey").to_string(); + let npub = nip19::encode_npub(&other).expect("the npub"); + let (fixture, rows, broadcast) = publish_with_self(Some(&npub)).await; + + assert_eq!(rows, 0); + assert!(!broadcast); + assert!(fixture.users.admitted_queries().is_empty()); +} + +#[tokio::test] +async fn info_self_malformed_npub_publishes_nothing() { + let (fixture, rows, broadcast) = publish_with_self(Some("npub1invalid")).await; + + assert_eq!(rows, 0); + assert!(!broadcast); + assert!(fixture.users.admitted_queries().is_empty()); +} + +#[tokio::test] +async fn info_self_non_pubkey_is_treated_as_unset() { + let (fixture, rows, broadcast) = publish_with_self(Some("relay.example.com")).await; + + assert_eq!(rows, 1); + assert!(broadcast); + assert_eq!(fixture.users.admitted_queries(), vec![10_001]); +} + +#[tokio::test] +async fn the_list_is_cut_to_the_cap() { + let fixture = Fixture::new(publish_settings(Some(true), true)); + for index in 0..10_001u32 { + fixture.users.insert(user(counter_member(index))); + } + let context = publishing_context(&fixture); + + publish_membership_list(&context).await; + + let event = membership_event(&fixture); + assert_eq!( + event.tags.len(), + 10_001, + "the protected tag plus 10,000 members" + ); + assert_eq!(event.tags[0], protected_tag()); + for (index, tag) in event.tags[1..].iter().enumerate() { + assert_eq!( + tag, + &member_tag(&counter_member(index as u32)), + "the lowest pubkeys survive" + ); + } + assert_eq!(fixture.users.admitted_queries(), vec![10_001]); +} + +struct LatchingUsers { + inner: Arc, + first_members: Vec, + entries: mpsc::UnboundedSender<()>, + release: Mutex>>, + calls: AtomicUsize, + answered: Mutex>, +} + +impl LatchingUsers { + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } + + fn answered(&self) -> Vec { + self.answered + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } +} + +impl UserRepository for LatchingUsers { + fn find_by_pubkey<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, Option> { + self.inner.find_by_pubkey(pubkey) + } + + fn upsert<'a>(&'a self, user: &'a UserPatch) -> StorageFuture<'a, u64> { + self.inner.upsert(user) + } + + fn get_balance_by_pubkey<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, i64> { + self.inner.get_balance_by_pubkey(pubkey) + } + + fn is_vanished<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, bool> { + self.inner.is_vanished(pubkey) + } + + fn set_vanished<'a>(&'a self, pubkey: &'a Pubkey, vanished: bool) -> StorageFuture<'a, u64> { + self.inner.set_vanished(pubkey, vanished) + } + + fn admit_user<'a>( + &'a self, + pubkey: &'a Pubkey, + admitted_at: DateTime, + ) -> StorageFuture<'a, ()> { + self.inner.admit_user(pubkey, admitted_at) + } + + fn revoke_admission<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, u64> { + self.inner.revoke_admission(pubkey) + } + + /// The first call latches and answers a fixed set; later calls delegate. + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async move { + let call = self.calls.fetch_add(1, Ordering::SeqCst); + let _ = self.entries.send(()); + + if call == 0 { + let receiver = self + .release + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + .expect("the release is armed"); + let _ = receiver.await; + + self.answered + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(self.first_members.len()); + + Ok(self.first_members.clone()) + } else { + let members = self.inner.find_admitted_pubkeys(limit).await?; + + self.answered + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(members.len()); + + Ok(members) + } + }) + } +} + +#[tokio::test] +async fn concurrent_publishes_are_serialised() { + let fixture = Fixture::new(publish_settings(Some(true), true)); + let second_set = counter_member(0x22); + fixture.users.insert(user(second_set)); + + let (entry_tx, mut entry_rx) = mpsc::unbounded_channel(); + let (release_tx, release_rx) = oneshot::channel(); + let stub = Arc::new(LatchingUsers { + inner: Arc::clone(&fixture.users), + first_members: vec![counter_member(0x10), counter_member(0x11)], + entries: entry_tx, + release: Mutex::new(Some(release_rx)), + calls: AtomicUsize::new(0), + answered: Mutex::new(Vec::new()), + }); + + let users: Arc = stub.clone(); + let stores = Stores { + events: Arc::clone(&fixture.stores.events), + users, + nip05: Arc::clone(&fixture.stores.nip05), + invites: Arc::clone(&fixture.stores.invites), + dvm_jobs: Arc::clone(&fixture.stores.dvm_jobs), + reports: Arc::clone(&fixture.stores.reports), + }; + let mut context = publishing_context(&fixture); + context.stores = Arc::new(stores); + + let mut hub = hub_receiver(&fixture.hub); + let first = tokio::spawn({ + let context = context.clone(); + async move { publish_membership_list(&context).await } + }); + tokio::time::timeout(Duration::from_secs(5), entry_rx.recv()) + .await + .expect("the first publish reaches its query") + .expect("one entry"); + + let second = tokio::spawn({ + let context = context.clone(); + async move { publish_membership_list(&context).await } + }); + assert!( + tokio::time::timeout(Duration::from_millis(100), entry_rx.recv()) + .await + .is_err(), + "the second publish cannot reach the query while the first holds the lock" + ); + + release_tx.send(()).expect("the release"); + first.await.expect("the first publish"); + second.await.expect("the second publish"); + + assert_eq!(stub.calls(), 2); + assert_eq!(stub.answered(), vec![2, 1], "A's set, then B's"); + assert_eq!( + membership_event(&fixture).tags, + vec![protected_tag(), member_tag(&second_set)], + "the newest member set is what the slot holds" + ); + + assert_eq!( + membership_event(&fixture).created_at, + NOW_SECS + 1, + "the later publish writes the stored second plus one" + ); + assert!(hub.try_recv().is_ok(), "the first frame"); + assert!(hub.try_recv().is_ok(), "the second frame"); + assert!(hub.try_recv().is_err(), "exactly two frames"); +} + +#[tokio::test] +async fn a_connected_client_receives_the_full_list() { + let server = Server::start_with( + Fixture::new(publish_settings(Some(true), true)), + relay_keys(), + fast_config(), + ) + .await; + + // The seeds sort below the joiner: 30 zero bytes then the index. + let joiner = public_key(&CLIENT_SECRET).expect("the joiner pubkey"); + let mut seeds = Vec::new(); + for index in 0..9_999u16 { + let mut bytes = [0u8; 32]; + bytes[30..].copy_from_slice(&index.to_be_bytes()); + let seed = Pubkey::from_byte_array(bytes); + assert!(seed < joiner, "every seed sorts below the joiner"); + seeds.push(seed); + server.fixture.users.insert(user(seed)); + } + server + .fixture + .invites + .create("valid-code", &options(1)) + .await + .expect("the invite code"); + + let (mut client, challenge) = server.connect().await; + let auth = signed_event( + &CLIENT_SECRET, + 22_242, + vec![ + vec!["relay", "wss://relay.example.com"], + vec!["challenge", challenge.as_str()], + ], + "", + NOW_SECS, + ); + client + .send(&format!( + r#"["AUTH",{}]"#, + serde_json::to_string(&auth).expect("the auth json") + )) + .await; + assert!(client.expect_frame().await.ends_with(r#"true,""]"#)); + + client.send(r#"["REQ","members",{"kinds":[13534]}]"#).await; + client.read_until_eose().await; + + let join = signed_event( + &CLIENT_SECRET, + 28_934, + vec![vec!["claim", "valid-code"]], + "", + NOW_SECS, + ); + client + .send(&format!( + r#"["EVENT",{}]"#, + serde_json::to_string(&join).expect("the join json") + )) + .await; + + let frame = loop { + let frame = client.expect_frame().await; + if frame.starts_with(r#"["EVENT","members","#) { + break frame; + } + }; + let document: Value = serde_json::from_str( + frame + .strip_prefix(r#"["EVENT","members","#) + .and_then(|rest| rest.strip_suffix(']')) + .expect("an EVENT frame"), + ) + .expect("the event json"); + + assert_eq!(document["kind"], 13_534); + assert_eq!( + document["pubkey"], + Value::String( + public_key(&RELAY_SECRET) + .expect("the relay pubkey") + .to_string() + ) + ); + assert_eq!(document["content"], ""); + let tags = document["tags"].as_array().expect("tags"); + assert_eq!(tags.len(), 10_001); + assert_eq!(tags[0], serde_json::json!(["-"])); + + let mut expected: Vec = seeds.iter().map(ToString::to_string).collect(); + expected.push(joiner.to_string()); + for (index, pubkey) in expected.iter().enumerate() { + assert_eq!( + tags[index + 1], + serde_json::json!(["member", pubkey]), + "the admitted set ascending" + ); + } + assert_eq!( + tags[10_000], + serde_json::json!(["member", joiner.to_string()]), + "the joiner is last" + ); + + let event: Event = serde_json::from_value(document).expect("a wire event"); + nostream_core::crypto::verify_event_signature(&event).expect("the relay's signature verifies"); + assert_eq!( + server + .fixture + .events + .events() + .iter() + .filter(|event| event.kind == Kind(13_534)) + .count(), + 1 + ); +} + +#[tokio::test] +async fn an_unwritable_store_does_not_fail_the_membership_change() { + let fixture = Fixture::new(publish_settings(Some(true), true)); + fixture + .invites + .create("valid-code", &options(1)) + .await + .expect("the invite code"); + fixture.events.fail_upsert(UpsertFailure::Unavailable); + + let (context, mut sink) = authenticated_socket(&fixture, author()); + let mut hub = hub_receiver(&fixture.hub); + let event = join_event(); + + JoinRequestStrategy + .execute(&event, &context) + .await + .expect("the join answers"); + + assert_eq!( + frames(&mut sink), + vec![ok_frame( + &event, + true, + "info: welcome to wss://relay.example.com!" + )] + ); + assert!( + fixture + .events + .events() + .iter() + .all(|event| event.kind != Kind(13_534)) + ); + assert!(hub.try_recv().is_err()); +} + +#[tokio::test] +async fn a_store_that_did_not_write_is_not_broadcast() { + let fixture = Fixture::new(publish_settings(Some(true), true)); + fixture.users.insert(user(counter_member(0x11))); + fixture.events.upsert_answers_zero(true); + let context = publishing_context(&fixture); + let mut hub = hub_receiver(&fixture.hub); + + publish_membership_list(&context).await; + + assert!(fixture.events.events().is_empty()); + assert_eq!( + fixture.events.upserts().len(), + 1, + "one upsert was attempted" + ); + assert!(hub.try_recv().is_err()); +} diff --git a/crates/nostream-relay/tests/strategies.rs b/crates/nostream-relay/tests/strategies.rs index d4838999a..2966426de 100644 --- a/crates/nostream-relay/tests/strategies.rs +++ b/crates/nostream-relay/tests/strategies.rs @@ -98,6 +98,40 @@ fn keys() -> RelayKeySource { RelayKeySource::from_values(None, None) } +/// A key source that can sign the published membership list. +fn publishing_keys() -> RelayKeySource { + RelayKeySource::from_values(Some("01".repeat(32)), None) +} + +fn publishing_socket(fixture: &Fixture) -> (HandlerContext, mpsc::UnboundedReceiver) { + let (sink, frames) = FrameSink::channel(64 * 1024, None); + let connection = Arc::new(Connection::new( + "127.0.0.1".to_owned(), + Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), + )); + + ( + fixture.context(clock(), publishing_keys(), connection, sink), + frames, + ) +} + +fn publishing_authenticated_socket( + fixture: &Fixture, + pubkey: Pubkey, +) -> (HandlerContext, mpsc::UnboundedReceiver) { + let (context, frames) = publishing_socket(fixture); + + context.connection.authenticate( + pubkey, + EventId::from_byte_array([0x09; 32]), + context.now_secs(), + ); + + (context, frames) +} + /// A context whose sink a test can read, with its frames. fn socket(fixture: &Fixture) -> (HandlerContext, mpsc::UnboundedReceiver) { let (sink, frames) = FrameSink::channel(64 * 1024, None); @@ -161,6 +195,18 @@ fn nip43_on() -> Settings { settings } +/// Settings with NIP-43 on and the membership list published after a change. +fn nip43_publishing() -> Settings { + let mut settings = nip43_on(); + settings + .nip43 + .as_mut() + .expect("nip43_on sets the block") + .publish_membership_list = Some(true); + + settings +} + /// Settings with NIP-56 on and the given trusted moderators. fn nip56_on(trusted_moderators: Vec, hide_actionable_reports: bool) -> Settings { let mut settings = settings(); @@ -2634,3 +2680,102 @@ async fn vanish_answers_duplicate_when_the_request_exists() { vec![ok_frame(&event, true, "duplicate:")] ); } + +#[tokio::test] +async fn join_publishes_the_membership_list() { + let fixture = Fixture::new(nip43_publishing()); + fixture + .invites + .create( + "valid-code", + &CreateInviteCodeOptions { + expires_at: None, + remaining_uses: FieldUpdate::Set(1), + created_by: None, + }, + ) + .await + .unwrap(); + let (context, mut sink) = publishing_authenticated_socket(&fixture, author()); + let mut hub = hub_receiver(&fixture.hub); + let event = join_request_event(); + + JoinRequestStrategy.execute(&event, &context).await.unwrap(); + + assert_eq!( + frames(&mut sink), + vec![ok_frame( + &event, + true, + "info: welcome to wss://relay.example.com!" + )] + ); + let lists: Vec = fixture + .events + .events() + .into_iter() + .filter(|event| event.kind == Kind(13_534)) + .collect(); + assert_eq!(lists.len(), 1); + let author_hex = author().to_string(); + assert_eq!( + lists[0].tags, + vec![tag(&["-"]), tag(&["member", &author_hex])] + ); + assert_eq!( + broadcast(&mut hub).map(|event| event.kind), + Some(Kind(13_534)) + ); +} + +#[tokio::test] +async fn leave_publishes_the_membership_list() { + let fixture = Fixture::new(nip43_publishing()); + fixture.users.insert(admitted_user()); + let (context, mut sink) = publishing_authenticated_socket(&fixture, author()); + let mut hub = hub_receiver(&fixture.hub); + let event = leave_request_event(); + + LeaveRequestStrategy + .execute(&event, &context) + .await + .unwrap(); + + assert_eq!(frames(&mut sink), vec![ok_frame(&event, true, "")]); + let lists: Vec = fixture + .events + .events() + .into_iter() + .filter(|event| event.kind == Kind(13_534)) + .collect(); + assert_eq!(lists.len(), 1); + assert_eq!(lists[0].tags, vec![tag(&["-"])]); + assert_eq!( + broadcast(&mut hub).map(|event| event.kind), + Some(Kind(13_534)) + ); +} + +#[tokio::test] +async fn vanish_publishes_the_membership_list() { + let fixture = Fixture::new(nip43_publishing()); + let (context, mut sink) = publishing_socket(&fixture); + let mut hub = hub_receiver(&fixture.hub); + let event = vanish_event(); + + VanishStrategy.execute(&event, &context).await.unwrap(); + + assert_eq!(frames(&mut sink), vec![ok_frame(&event, true, "")]); + let lists: Vec = fixture + .events + .events() + .into_iter() + .filter(|event| event.kind == Kind(13_534)) + .collect(); + assert_eq!(lists.len(), 1); + assert_eq!(lists[0].tags, vec![tag(&["-"])]); + assert_eq!( + broadcast(&mut hub).map(|event| event.kind), + Some(Kind(13_534)) + ); +} diff --git a/crates/nostream-services/src/testing.rs b/crates/nostream-services/src/testing.rs index 13fd3f2f9..f6d9302a3 100644 --- a/crates/nostream-services/src/testing.rs +++ b/crates/nostream-services/src/testing.rs @@ -611,6 +611,32 @@ impl EventRepository for InMemoryEventRepository { }) } + /// The slot read: the newest row of `(pubkey, kind)`, smallest id on a tie, deleted or not. + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option> { + Box::pin(async move { + Ok(self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|record| record.event.pubkey == *pubkey && record.event.kind == kind) + .max_by(|left, right| { + left.event + .created_at + .cmp(&right.event.created_at) + .then_with(|| right.event.id.cmp(&left.event.id)) + }) + .map(|record| ReconciliationItem { + created_at: record.event.created_at, + event_id: record.event.id, + })) + }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -954,6 +980,11 @@ impl UserRepository for InMemoryUserRepository { Box::pin(async { Ok(None) }) } + /// This double answers no users, like its other reads. + fn find_admitted_pubkeys<'a>(&'a self, _limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async { Ok(Vec::new()) }) + } + fn upsert<'a>(&'a self, user: &'a UserPatch) -> StorageFuture<'a, u64> { Box::pin(async move { if let Some(trace) = self diff --git a/crates/nostream-services/src/unavailable.rs b/crates/nostream-services/src/unavailable.rs index 78e7380d7..0f43a2d8a 100644 --- a/crates/nostream-services/src/unavailable.rs +++ b/crates/nostream-services/src/unavailable.rs @@ -119,6 +119,14 @@ impl EventRepository for UnavailableEventRepository { Box::pin(async { Err(unavailable()) }) } + fn find_stored_replaceable<'a>( + &'a self, + _pubkey: &'a nostream_core::Pubkey, + _kind: nostream_core::Kind, + ) -> StoreFuture<'a, Option> { + Box::pin(async { Err(unavailable()) }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a nostream_core::Pubkey, @@ -231,6 +239,13 @@ impl UserRepository for UnavailableUserRepository { fn revoke_admission<'a>(&'a self, _pubkey: &'a nostream_core::Pubkey) -> StoreFuture<'a, u64> { Box::pin(async { Err(unavailable()) }) } + + fn find_admitted_pubkeys<'a>( + &'a self, + _limit: u64, + ) -> StoreFuture<'a, Vec> { + Box::pin(async { Err(unavailable()) }) + } } /// The invoice store. diff --git a/crates/nostream-storage/src/lmdb/events.rs b/crates/nostream-storage/src/lmdb/events.rs index bb55b69e1..9578942fb 100644 --- a/crates/nostream-storage/src/lmdb/events.rs +++ b/crates/nostream-storage/src/lmdb/events.rs @@ -374,6 +374,36 @@ pub(crate) fn find_stored( rows::decode_event(value).map(Some) } +/// `findStoredReplaceable`: the pointer the writer left for `(author, kind)`'s slot, then that +/// row's header. Soft deletion, expiry and the NIP-56 gate are not predicates here: the slot +/// is occupied whether or not a read would answer the row. +pub(crate) fn find_stored_replaceable( + txn: &RoTxn<'_>, + databases: &Databases, + pubkey: &Pubkey, + kind: Kind, +) -> Result, StorageError> { + let deduplication = crate::records::default_deduplication_for(pubkey, kind); + let kind_number = i32::try_from(kind.0).map_err(|_| StorageError::ValueOutOfRange { + column: "event_kind", + value: kind.0.to_string(), + })?; + let pointer = encoding::replaceable_key(pubkey, kind_number, &deduplication)?; + let Some(stored) = databases.replaceable.get(txn, &pointer)? else { + return Ok(None); + }; + let event_id = encoding::event_id_from(stored)?; + let Some(value) = databases.events.get(txn, event_id.as_bytes())? else { + return Ok(None); + }; + let header = rows::event_header(value)?; + + Ok(Some(ReconciliationItem { + created_at: header.created_at, + event_id, + })) +} + /// `delete_by_pubkey_and_ids`: a soft delete that never touches kind 62 or a deleted row. pub(crate) fn delete_by_pubkey_and_ids( txn: &mut RwTxn<'_>, @@ -4428,4 +4458,68 @@ mod tests { ); } } + #[tokio::test] + async fn the_stored_replaceable_is_read_from_the_primary_slot() { + use crate::lmdb::LmdbBackend; + use crate::repositories::EventRepository; + + let directory = tempfile::tempdir().expect("tempdir"); + let backend = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let secret = [1u8; 32]; + let first = nostream_core::nip43::build_membership_list_event(&secret, &[], 1_700_000_000) + .expect("the builder"); + + assert_eq!( + backend + .upsert(&EventRecord::from_event(&first)) + .await + .expect("the upsert"), + 1 + ); + assert_eq!( + backend + .find_stored_replaceable(&first.pubkey, first.kind) + .await + .expect("the slot"), + Some(ReconciliationItem { + created_at: 1_700_000_000, + event_id: first.id, + }) + ); + + backend + .delete_by_pubkey_and_ids(&first.pubkey, &[first.id]) + .await + .expect("the soft delete"); + assert_eq!( + backend + .find_stored_replaceable(&first.pubkey, first.kind) + .await + .expect("the slot"), + Some(ReconciliationItem { + created_at: 1_700_000_000, + event_id: first.id, + }), + "a soft-deleted row still occupies the slot" + ); + + let newer = nostream_core::nip43::build_membership_list_event(&secret, &[], 1_700_000_001) + .expect("the builder"); + backend + .upsert(&EventRecord::from_event(&newer)) + .await + .expect("the upsert"); + assert_eq!( + backend + .find_stored_replaceable(&newer.pubkey, newer.kind) + .await + .expect("the slot"), + Some(ReconciliationItem { + created_at: 1_700_000_001, + event_id: newer.id, + }) + ); + } } diff --git a/crates/nostream-storage/src/lmdb/mod.rs b/crates/nostream-storage/src/lmdb/mod.rs index d7e96b2bb..d24491f92 100644 --- a/crates/nostream-storage/src/lmdb/mod.rs +++ b/crates/nostream-storage/src/lmdb/mod.rs @@ -636,6 +636,20 @@ impl EventRepository for LmdbBackend { }) } + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option> { + Box::pin(async move { + let pubkey = *pubkey; + self.read(move |txn, databases| { + events::find_stored_replaceable(txn, databases, &pubkey, kind) + }) + .await + }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -866,6 +880,13 @@ impl UserRepository for LmdbBackend { }) } + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async move { + self.read(move |txn, databases| users::find_admitted_pubkeys(txn, databases, limit)) + .await + }) + } + fn upsert<'a>(&'a self, user: &'a UserPatch) -> StorageFuture<'a, u64> { Box::pin(async move { let user = user.clone(); diff --git a/crates/nostream-storage/src/lmdb/users.rs b/crates/nostream-storage/src/lmdb/users.rs index e44c1c5fc..5e7adc2e6 100644 --- a/crates/nostream-storage/src/lmdb/users.rs +++ b/crates/nostream-storage/src/lmdb/users.rs @@ -47,6 +47,27 @@ pub(crate) fn find_by_pubkey( Ok(load(txn, databases, pubkey)?.map(StoredUser::user)) } +/// `findAdmittedPubkeys`: the admitted, not-vanished pubkeys in ascending key order, which the +/// `users` database gives by construction (`src/repositories/user-repository.ts:126-137`). +pub(crate) fn find_admitted_pubkeys( + txn: &RoTxn<'_>, + databases: &Databases, + limit: u64, +) -> Result, StorageError> { + let mut pubkeys = Vec::new(); + for entry in databases.users.iter(txn)? { + if pubkeys.len() as u64 >= limit { + break; + } + let (_, value) = entry?; + let stored: StoredUser = rows::decode("users", value)?; + if stored.is_admitted && !stored.is_vanished { + pubkeys.push(stored.pubkey); + } + } + Ok(pubkeys) +} + /// `upsert`: the flags the patch carries and `updated_at`, plus `tos_accepted_at` only when the /// patch carries it. A flag the patch leaves `Absent` is `false` on a new row and left alone on /// an existing one, as the Postgres merge does. `balance` and `created_at` are never touched. @@ -436,4 +457,38 @@ mod tests { "the write half committed nothing" ); } + + #[tokio::test] + async fn admitted_pubkeys_are_ascending_and_skip_vanished() { + let directory = tempfile::tempdir().expect("tempdir"); + let backend = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let admitted_low = Pubkey::from_byte_array([0x11; 32]); + let vanished = Pubkey::from_byte_array([0x22; 32]); + let admitted_high = Pubkey::from_byte_array([0x33; 32]); + let denied = Pubkey::from_byte_array([0x44; 32]); + + for (pubkey, is_admitted, is_vanished) in [ + (admitted_high, true, false), + (denied, false, false), + (vanished, true, true), + (admitted_low, true, false), + ] { + backend + .upsert(&patch( + pubkey, + FieldUpdate::Set(is_admitted), + FieldUpdate::Set(is_vanished), + )) + .await + .expect("the upsert"); + } + + let admitted = backend.find_admitted_pubkeys(10).await.expect("the query"); + assert_eq!(admitted, vec![admitted_low, admitted_high]); + + let limited = backend.find_admitted_pubkeys(1).await.expect("the query"); + assert_eq!(limited, vec![admitted_low]); + } } diff --git a/crates/nostream-storage/src/postgres/events.rs b/crates/nostream-storage/src/postgres/events.rs index 626b20255..4417cb0fe 100644 --- a/crates/nostream-storage/src/postgres/events.rs +++ b/crates/nostream-storage/src/postgres/events.rs @@ -375,6 +375,33 @@ where row.map(|row| super::rows::event_record(&row)).transpose() } +/// `findStoredReplaceable`: the primary slot of `(author, kind)`, newest `created_at` then +/// smallest id, with no liveness or NIP-56 predicate (`src/repositories/event-repository.ts:192-208`). +pub(crate) async fn find_stored_replaceable<'e, E>( + executor: E, + pubkey: &Pubkey, + kind: Kind, +) -> Result, StorageError> +where + E: Executor<'e, Database = Postgres>, +{ + let mut args = Args::default(); + let pubkey_slot = args.push(Arg::Bytes(pubkey.as_bytes().to_vec())); + let kind_slot = args.push(Arg::BigInt(i64::try_from(kind.0).unwrap_or(i64::MAX))); + let sql = format!( + "SELECT event_created_at, event_id FROM events \ + WHERE event_pubkey = {pubkey_slot} AND event_kind = {kind_slot} \ + ORDER BY event_created_at DESC, event_id ASC LIMIT 1" + ); + let row = EventQuery { sql, args } + .into_query() + .fetch_optional(executor) + .await?; + + row.map(|row| super::rows::reconciliation_item(&row)) + .transpose() +} + /// `delete_by_pubkey_and_ids`: a soft delete, never touching kind 62 or a deleted row. pub(crate) async fn delete_by_pubkey_and_ids<'e, E>( executor: E, diff --git a/crates/nostream-storage/src/postgres/repository.rs b/crates/nostream-storage/src/postgres/repository.rs index c68da46dd..e3164df4e 100644 --- a/crates/nostream-storage/src/postgres/repository.rs +++ b/crates/nostream-storage/src/postgres/repository.rs @@ -65,6 +65,14 @@ impl EventRepository for PostgresBackend { Box::pin(async move { events::find_stored(&self.master, id).await }) } + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option> { + Box::pin(async move { events::find_stored_replaceable(&self.master, pubkey, kind).await }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -203,6 +211,9 @@ impl UserRepository for PostgresBackend { Box::pin(async move { users::find_by_pubkey(&self.master, pubkey).await }) } + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async move { users::find_admitted_pubkeys(&self.master, limit).await }) + } fn upsert<'a>(&'a self, user: &'a UserPatch) -> StorageFuture<'a, u64> { Box::pin(async move { users::upsert(&self.master, user).await }) } @@ -483,6 +494,14 @@ impl UserRepository for PostgresTransaction { }) } + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + Box::pin(async move { + with_transaction!(self, |transaction| { + users::find_admitted_pubkeys(&mut **transaction, limit).await + }) + }) + } + fn upsert<'a>(&'a self, user: &'a UserPatch) -> StorageFuture<'a, u64> { Box::pin(async move { with_transaction!(self, |transaction| { diff --git a/crates/nostream-storage/src/postgres/users.rs b/crates/nostream-storage/src/postgres/users.rs index c41ae9cda..d21e5029b 100644 --- a/crates/nostream-storage/src/postgres/users.rs +++ b/crates/nostream-storage/src/postgres/users.rs @@ -32,6 +32,34 @@ where row.as_ref().map(super::rows::user).transpose() } +/// `findAdmittedPubkeys`: admitted, not vanished, ascending by pubkey +/// (`src/repositories/user-repository.ts:126-137`). NULL flags never satisfy either predicate, +/// which is the capture's `is_admitted = true AND is_vanished = false`. +pub(crate) async fn find_admitted_pubkeys<'e, E>( + executor: E, + limit: u64, +) -> Result, StorageError> +where + E: Executor<'e, Database = Postgres>, +{ + let mut args = Args::default(); + let limit_slot = args.push(Arg::BigInt(i64::try_from(limit).unwrap_or(i64::MAX))); + let sql = format!( + "SELECT pubkey FROM users WHERE is_admitted = true AND is_vanished = false \ + ORDER BY pubkey ASC LIMIT {limit_slot}" + ); + let rows = EventQuery { sql, args } + .into_query() + .fetch_all(executor) + .await?; + + rows.iter() + .map(|row| { + super::rows::bytes_to_pubkey(row.try_get::, _>("pubkey")?, "users.pubkey") + }) + .collect() +} + /// `upsert`: inserts the row or updates the fields the patch carries. `balance` and /// `created_at` are never touched. pub(crate) async fn upsert<'e, E>(executor: E, patch: &UserPatch) -> Result diff --git a/crates/nostream-storage/src/records.rs b/crates/nostream-storage/src/records.rs index 3019a551e..f6ff2a573 100644 --- a/crates/nostream-storage/src/records.rs +++ b/crates/nostream-storage/src/records.rs @@ -152,9 +152,15 @@ pub fn distinct_replacements(records: &[EventRecord]) -> Vec<&EventRecord> { /// `jsonb_build_array(pubkey, kind)` as `src/repositories/event-repository.ts:390-396` /// builds it: the pubkey hex string and the kind as a JSON number. pub fn default_deduplication(event: &Event) -> Vec { + default_deduplication_for(&event.pubkey, event.kind) +} + +/// The same value for one address, so a read that must build the writer's key does not have +/// to hold an [`Event`]. +pub fn default_deduplication_for(pubkey: &Pubkey, kind: Kind) -> Vec { vec![ - serde_json::Value::String(event.pubkey.to_string()), - serde_json::Value::Number(serde_json::Number::from(event.kind.0)), + serde_json::Value::String(pubkey.to_string()), + serde_json::Value::Number(serde_json::Number::from(kind.0)), ] } diff --git a/crates/nostream-storage/src/repositories.rs b/crates/nostream-storage/src/repositories.rs index e7894f8a0..cd8e568f4 100644 --- a/crates/nostream-storage/src/repositories.rs +++ b/crates/nostream-storage/src/repositories.rs @@ -659,6 +659,19 @@ pub trait EventRepository: Send + Sync { /// that answers a client keeps the gated path. fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option>; + /// The row that holds `(author, kind)`'s replaceable slot as `(created_at, event_id)`. + /// + /// Read from the **primary** slot, ignoring soft deletion, expiry and the NIP-56 gate: a + /// hidden row still occupies the slot and must be superseded for "exactly one". Defined + /// for a plain replaceable kind (`Kind::is_replaceable` and not + /// `is_parameterized_replaceable`), which is the class whose key is the default + /// deduplication `[pubkey hex, kind number]`. `None` when the slot is empty. + fn find_stored_replaceable<'a>( + &'a self, + pubkey: &'a Pubkey, + kind: Kind, + ) -> StorageFuture<'a, Option>; + /// Soft-deletes the given ids of one pubkey, returning the count. /// /// Two conditions are the store's own, implemented by both backends and not by a caller: @@ -845,6 +858,12 @@ pub trait UserRepository: Send + Sync { /// Revokes admission, returning the row count. fn revoke_admission<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, u64>; + + /// The admitted, not-vanished pubkeys in ascending byte order, at most `limit` + /// (`findAdmittedPubkeys`, `src/repositories/user-repository.ts:126-137`). + /// + /// Read from the write side, because the caller asks right after a membership write. + fn find_admitted_pubkeys<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec>; } /// NIP-05 verification storage (`src/@types/repositories.ts` diff --git a/crates/nostream-storage/tests/storage.rs b/crates/nostream-storage/tests/storage.rs index 1e7bc2cc2..c3851adbf 100644 --- a/crates/nostream-storage/tests/storage.rs +++ b/crates/nostream-storage/tests/storage.rs @@ -101,6 +101,14 @@ async fn the_repository_traits_are_dyn_compatible() { unsupported("noop::events::find_stored") } + fn find_stored_replaceable<'a>( + &'a self, + _pubkey: &'a Pubkey, + _kind: Kind, + ) -> StorageFuture<'a, Option> { + unsupported("noop::events::find_stored_replaceable") + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a Pubkey, @@ -238,6 +246,10 @@ async fn the_repository_traits_are_dyn_compatible() { fn revoke_admission<'a>(&'a self, _pubkey: &'a Pubkey) -> StorageFuture<'a, u64> { unsupported("noop::users::revoke_admission") } + + fn find_admitted_pubkeys<'a>(&'a self, _limit: u64) -> StorageFuture<'a, Vec> { + unsupported("noop::users::find_admitted_pubkeys") + } } impl Nip05VerificationRepository for Noop { diff --git a/docs/rewrite/crate-map.md b/docs/rewrite/crate-map.md index 5e85ea051..0f4112ab9 100644 --- a/docs/rewrite/crate-map.md +++ b/docs/rewrite/crate-map.md @@ -23,11 +23,14 @@ $ git diff --name-status 242a3001..9c25d743 -- src | cut -f1 | sort | uniq -c 62 M ``` -So of the capture's 298 modules, **296 are still in the tree and 2 were deleted**, and **61 -files were added** after the capture. 296 + 61 = 357 rows. The two deleted modules are named -below rather than given rows, because a row's left column must resolve in this tree. - -The 61 additions are not one wave: 20 under `src/utils/`, 13 controller factories, 12 admin +So of the capture's 298 modules, **296 are still in the tree and 2 were deleted**, and **62 +files were added** after the capture. 296 + 62 = 358 rows. One of the 62 is a v3-`main` +addition the capture-to-head window diff cannot produce — `src/utils/nip43-membership.ts`, +which landed on `main` after the capture and is ported here by job 053. The two deleted +modules are named below rather than given rows, because a row's left column must resolve in +this tree. + +The 62 additions are not one wave: 21 under `src/utils/`, 13 controller factories, 12 admin controllers, 4 `@types`, 3 NIP-77 handlers, and the rest single files (`src/utils/nip77.ts`, `src/utils/negentropy-sessions.ts`, `src/scripts/bench-gate.ts` and others). They are rows because a reader of the port meets them; they are a separate group because they were not @@ -52,8 +55,8 @@ eight `crates/*/src/lib.rs` files whose crates have a TypeScript ancestor; brace directory tokens were expanded to their files. 305 of the 357 head files are named by a `lib.rs` block; the others are named here from a call site, an ADR, or a recorded reason. -**Totals over the 357 rows**, by the crate named first in column 2: `nostream-admin` 91, `nostreamd` 14, `nostream-services` 38, `nostream-core` 39, `nostream-relay` 37, `nostream-cli` 22, `nostream-storage` 22, `nostream-config` 9; 85 rows -name no crate because nothing replaced them. By class: `moved` 214, `split` 28, +**Totals over the 358 rows**, by the crate named first in column 2: `nostream-admin` 91, `nostreamd` 14, `nostream-services` 38, `nostream-core` 39, `nostream-relay` 38, `nostream-cli` 22, `nostream-storage` 22, `nostream-config` 9; 85 rows +name no crate because nothing replaced them. By class: `moved` 213, `split` 30, `type-only` 30, and 85 rows that are `not moved`, naming `#865` 19, `#867` 41, `#868` 1, `#1036` 15, `#1336` 9. ## How to read a row @@ -341,8 +344,8 @@ The disposition's first word is the class, from the list the spec fixes: | `src/utils/nip25.ts` | `crates/nostream-core/src/nip25.rs` | `crates/nostream-core/src/lib.rs:16` | moved | | `src/utils/nip42-session.ts` | `crates/nostream-core/src/nip42.rs` | `crates/nostream-core/src/lib.rs:17` | moved | | `src/utils/nip42.ts` | `crates/nostream-core/src/nip42.rs` | `crates/nostream-core/src/lib.rs:16` | moved | -| `src/utils/nip43-invites.ts` | `crates/nostream-core/src/nip43.rs` | `crates/nostream-core/src/lib.rs:17` | moved | -| `src/utils/nip43.ts` | `crates/nostream-core/src/nip43.rs` | `crates/nostream-core/src/lib.rs:17` | moved | +| `src/utils/nip43-invites.ts` | `crates/nostream-core/src/nip43.rs` (`crates/nostream-relay/src/nip43_membership.rs`) | `crates/nostream-core/src/lib.rs:17`, `crates/nostream-relay/src/nip43_membership.rs:144-167` | split — `relay_self` is v3's `isRelaySelfConsistent`/`parseRelayPubkey`; the pure code parsing stays in core | +| `src/utils/nip43.ts` | `crates/nostream-core/src/nip43.rs` (`crates/nostream-relay/src/nip43_membership.rs`) | `crates/nostream-core/src/lib.rs:17`, `crates/nostream-relay/src/nip43_membership.rs:144-167` | split — `relay_self` is v3's `isRelaySelfConsistent`/`parseRelayPubkey`; the builder and parsing stay in core | | `src/utils/nip44.ts` | `crates/nostream-core/src/nip44.rs` | `crates/nostream-core/src/lib.rs:18` | moved | | `src/utils/nip56.ts` | `crates/nostream-core/src/nip56.rs` | `crates/nostream-core/src/lib.rs:18` | moved | | `src/utils/nip65.ts` | — | `crates/nostream-core/src/nip65.rs:16` | not moved (#867) — dropped: the entry is a modelled type; the reader is a Phase 1 stub | @@ -384,7 +387,7 @@ The disposition's first word is the class, from the list the spec fixes: | `src/utils/validation.ts` | `crates/nostream-core/src/validation.rs` | `crates/nostream-core/src/lib.rs:24` | moved | | `src/utils/wot-pow-policy.ts` | `crates/nostream-core/src/lib.rs` | `crates/nostream-core/src/lib.rs:24` | moved | -## Added after the capture (61 rows) +## Added after the capture (62 rows) These files did not exist at `242a3001`; each row has the same shape as the group above, and a disposition that postdates the capture @@ -447,6 +450,7 @@ says so. | `src/utils/moderation-rate-limit-stats.ts` | — | `crates/nostream-admin/src/utils/mod.rs:1-4` | not moved (#867) — added-after-capture: the Redis-sorted-set stats panel has no Rust counterpart | | `src/utils/negentropy-sessions.ts` | `crates/nostream-core/src/negentropy.rs` | `crates/nostream-core/src/lib.rs:48` | moved — added after the capture | | `src/utils/nip05-reverification.ts` | `crates/nostream-admin/src/utils/nip05.rs` | `crates/nostream-admin/src/utils/nip05.rs:2` | moved — added after the capture | +| `src/utils/nip43-membership.ts` | `crates/nostream-relay/src/nip43_membership.rs` | `crates/nostream-relay/src/lib.rs:58` | moved — added after the capture | | `src/utils/nip77.ts` | — | `crates/nostream-core/src/nip77.rs:19` | not moved (#1036) — added-after-capture: the session constants are unmodelled; the frame encoder is a Phase 1 stub | | `src/utils/ops-trust-notifications.ts` | — | `crates/nostream-config/src/notifications.rs:70-76` | not moved (#1036) — added-after-capture: dropped, the three toggles are modelled and the emitter is not | | `src/utils/peering-auth.ts` | — | `crates/nostream-config/src/settings.rs:805` | not moved (#1036) — added-after-capture: the settings model exists; the peer authenticator is #1036's | diff --git a/docs/rewrite/decisions/0004-wire-transport.md b/docs/rewrite/decisions/0004-wire-transport.md index 42c018824..d37606057 100644 --- a/docs/rewrite/decisions/0004-wire-transport.md +++ b/docs/rewrite/decisions/0004-wire-transport.md @@ -290,12 +290,17 @@ regenerated by `tests/capture/gen-ts-cases.mjs` from the capture tree. exemptions with a reason and the job that owns them (`processNip05Metadata`, the admission cache, admission fee schedules, the process-level shutdown deadline). -## NIP-43 `info.self` — hex only +## NIP-43 `info.self` — hex only for the invite mint -The capture accepts a hex pubkey or an `npub` in `info.self`; the port accepts hex and -refuses an `npub` with a log line, because the port's decoder has no bech32 and a -mistyped identity must not mint invite codes. Job 010 (NIP-05/bech32 surface) can widen -it. +The capture accepts a hex pubkey or an `npub` in `info.self`; the port's **invite mint** +(`subscribe.rs`) accepts hex and refuses an `npub` with a log line, because a mistyped +identity must not mint invite codes. + +`nip43.publishMembershipList` reads the same setting through the capture's full rule +(`nip43_membership::relay_self`): a matching hex or decodable `npub` publishes, a differing +one refuses with the mismatch line, a malformed `npub1…` refuses, and any other string is +treated as unset. `nostream_core::nip19` carries the decoder and its inverse; the mint keeps +its hex-only rule deliberately (job 053). ## WoT distance is unavailable, so adaptive PoW charges in full diff --git a/docs/rewrite/kpis.md b/docs/rewrite/kpis.md index 9b14fb7e7..a0dbb6852 100644 --- a/docs/rewrite/kpis.md +++ b/docs/rewrite/kpis.md @@ -158,7 +158,7 @@ should have caught it. passes while skipping every directory-pin test. A green run anywhere else is not evidence for this KPI, and the release record must name the host it ran on. -**Order of work.** The parity ledger is built and reports 15/25; the migration campaign still +**Order of work.** The parity ledger is built and reports 16/25 (at `b9ba0923`); the migration campaign still needs a committed harness before it can run per release; the rest are read from records that already exist. diff --git a/docs/rewrite/nip-porting.md b/docs/rewrite/nip-porting.md index e47cbafd4..3ff50539a 100644 --- a/docs/rewrite/nip-porting.md +++ b/docs/rewrite/nip-porting.md @@ -63,7 +63,7 @@ red, in the same shape as a `build.md` row's `inversion:`. | 33 | `nip-33.feature` | `nostream-relay/tests/strategies.rs::parameterized_replaceable_uses_the_first_d_tag_value`; `nip_vectors.rs::nip89_recommendation_and_handler_events_are_stored_and_served` | the dedup key becomes a later `d` value, or the older `d`-twin is served | ported | | 40 | `nip-40.feature` | `nostream-relay/tests/handlers.rs::an_expired_event_is_rejected`; `connection.rs::an_event_expired_when_the_read_starts_is_not_delivered` | an expired event is stored, or served by a read that started after expiry | ported | | 42 | `test/unit/adapters/web-socket-adapter.spec.ts`, `event-message-handler.spec.ts` | `nostream-relay/tests/handlers.rs::auth_outcomes_are_the_captures_seven`, `::a_restricted_read_delivers_only_to_the_author_or_a_p_tagged_reader` | one of the seven AUTH rejections becomes an accept, or a restricted REQ is served unauthenticated | ported | -| 43 | `test/unit/handlers/event-message-handler.spec.ts`, `event-strategies/invite-request-event-strategy.spec.ts`, `leave-request-event-strategy.spec.ts` | `nostream-relay/tests/handlers.rs::an_invite_request_mints_one_kind_28935_event_before_eose`; `strategies.rs::the_join_request_admits_and_answers_with_the_welcome` | the invite is minted twice, minted for an unauthenticated socket, or a join is admitted without spending the code | **partial** — no kind 13534 membership list and no relay-signed membership event | +| 43 | `test/unit/handlers/event-message-handler.spec.ts`, `event-strategies/invite-request-event-strategy.spec.ts`, `leave-request-event-strategy.spec.ts` | `nostream-relay/tests/handlers.rs::an_invite_request_mints_one_kind_28935_event_before_eose`; `strategies.rs::the_join_request_admits_and_answers_with_the_welcome`, `::join_publishes_the_membership_list`, `::leave_publishes_the_membership_list`, `::vanish_publishes_the_membership_list`; `nip43_membership.rs::two_publishes_in_one_second_leave_one_row_and_two_frames`, `::a_connected_client_receives_the_full_list`, `::the_gate_setting_off_publishes_nothing` | the invite is minted twice, minted for an unauthenticated socket, a join is admitted without spending the code, or the published list stops replacing the previous one | ported — the list is relay-signed and gated by `nip43.publishMembershipList` | | 44 | `test/unit/utils/nip44.spec.ts` | `nostream-core/tests/nip44_parity.rs::produces_the_canonical_payload_from_the_nip44_spec_test_vector`, `::decrypts_the_canonical_nip44_spec_test_vector` | one byte of the canonical v2 payload changes, in either direction | ported | | 45 | `nip-45.feature`, `test/unit/handlers/count-message-handler.spec.ts` | `nostream-relay/tests/handlers.rs::count_answers_with_the_count_object` | the `COUNT` reply shape changes, or a disabled COUNT is still answered | **partial** — every COUNT test counts an empty store; no non-empty match set is counted | | 50 | `nip-50.feature` | `nostream-storage/tests/parity_lmdb.rs::a_search_returns_the_recorded_rows_in_rank_order`, `::a_search_orders_by_proximity_then_event_id`, `::a_limited_count_counts_the_rank_page`; `nostream-relay/tests/nip_vectors.rs::nip50_a_search_filter_is_served_only_when_enabled` | the recorded rank order changes, a proximity tie stops breaking on event id, or a non-matching note is served with the setting on | **partial** — rank order is proven at the store; the relay test asserts membership only, so nothing asserts that the served frame order matches the store's rank | @@ -76,17 +76,18 @@ red, in the same shape as a `build.md` row's `inversion:`. status reads `ported`, out of 25. Nothing else is aggregated — a percentage over `partial` rows would mix a missing branch with a missing feature. -**Measured on `rewrite/main` at `f01cb5f3`: 15 of 25 `ported`, 8 `partial`, 2 `open`.** Every -Rust citation above was checked to exist at that commit, and the two `open` rows were read in -the code rather than inferred from a missing file. +**Measured at `b9ba0923` (job 053's branch head, based on `4c4f6a6d`): 16 of 25 `ported`, 7 +`partial`, 2 `open`.** Every Rust citation above was checked to exist at that commit, and the +citations job 053 added were checked there; the two `open` rows were read in the code rather +than inferred from a missing file. | status | nips | |---|---| -| ported | `02 03 09 12 14 15 16 17 20 22 33 40 42 44 65` | -| partial | `01 04 13 25 28 43 45 50` | +| ported | `02 03 09 12 14 15 16 17 20 22 33 40 42 43 44 65` | +| partial | `01 04 13 25 28 45 50` | | open | `11 77` | -## 5. What the missing ten cost +## 5. What the missing nine cost The gap is not uniform, and the fix differs per row, which is why the ledger lists them instead of a percentage: @@ -100,14 +101,10 @@ instead of a percentage: content and store/serve (25), kinds 43–49 (28), a non-empty `COUNT` (45), and served-frame order matching the store's rank (50). The behaviour exists in each case; only the test is missing. -- **One needs code, not a test.** NIP-43's kind 13534 membership list and its relay-signed - membership event do not exist in Rust: `JoinRequestStrategy` spends the invite, admits the - pubkey and answers the welcome, and nothing mints or serves a membership list. Counting it - among the "test-only" rows would let cutover work skip building it. - **One is a counting artefact worth naming.** NIP-15 is a tombstone whose behaviour is EOSE, so its row cites the base-protocol test; that is not double-counting NIP-01, because the two rows ask different questions of the same assertion. -So of the ten rows short of `ported`: two need a surface built (11, 77), one needs a feature -built (43), and seven need a test written. Only the last seven are cheap, and none of them is -optional — the gate counts `ported` rows, not intentions. +So of the nine rows short of `ported`: two need a surface built (11, 77) and seven need a test +written. Only those seven are cheap, and none of them is optional — the gate counts `ported` +rows, not intentions. diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 5f3e25a57..138c16ce9 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -112,6 +112,9 @@ nip43: # Pubkeys allowed to request invite codes. Empty means any authenticated pubkey # may request one; non-empty restricts minting to the listed pubkeys. inviteRequestWhitelist: [] + # Publish the relay-signed kind-13534 membership list after every join, leave or + # vanish. Off by default because it makes every member's pubkey public. + publishMembershipList: false nip45: enabled: true nip50: