diff --git a/.changeset/nip11-pow-derivation.md b/.changeset/nip11-pow-derivation.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/nip11-pow-derivation.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/crates/nostream-relay/src/handlers/event.rs b/crates/nostream-relay/src/handlers/event.rs index b12c29c06..e297dff23 100644 --- a/crates/nostream-relay/src/handlers/event.rs +++ b/crates/nostream-relay/src/handlers/event.rs @@ -5,7 +5,7 @@ //! validity → expiry → event rate limit → acceptance gate → authentication → protected //! events → request-to-vanish → admission → NIP-05 → adaptive-PoW sample → strategy dispatch. -use nostream_config::settings::{ContentLimits, ContentLimitsOrVec, Settings}; +use nostream_config::settings::{ContentLimits, ContentLimitsOrVec, EventLimits, Settings}; use nostream_core::adaptive_pow::{self, AdaptivePowConfig, WotPowThreshold}; use nostream_core::constants::ALL_RELAYS; use nostream_core::nip05; @@ -228,24 +228,20 @@ fn can_accept_event( return Some(error.to_string()); } - if let Some(pow_settings) = limits.pow.as_ref().filter(|pow| pow.enabled) { - let required = required_difficulty(pow_settings, context, event); - let observed = pow::leading_zero_bits(event.id.as_bytes()); - - if observed < required { - return Some(format!("pow: difficulty {observed}<{required}")); - } - } else if let Some(minimum) = limits - .event_id - .as_ref() - .and_then(|event_id| event_id.min_leading_zero_bits) - .filter(|minimum| *minimum > 0) - { - let observed = pow::leading_zero_bits(event.id.as_bytes()); + let rate = limits.pow.as_ref().map_or(0.0, |pow| { + context + .pow + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .current_events_per_second(pow.period_ms) + }); + // The graph's lookup is asynchronous and this gate is synchronous, so no WoT distance + // reaches the policy yet (`wot.rs`, ADR 0004): the reduction is granted to nobody. + let required = required_difficulty(Some(limits), rate, None); + let observed = pow::leading_zero_bits(event.id.as_bytes()); - if observed < minimum { - return Some(format!("pow: difficulty {observed}<{minimum}")); - } + if observed < required { + return Some(format!("pow: difficulty {observed}<{required}")); } if let Some(minimum) = limits @@ -330,35 +326,47 @@ fn check_content_limit(event: &Event, limit: &ContentLimits) -> Option { applies.then(|| format!("rejected: content is longer than {max_length} bytes")) } -/// The adaptive difficulty after the WoT reduction (`getCurrentDifficulty` + -/// `applyWotPowPolicy`). +/// The required proof-of-work difficulty: the floor enforced at `events_per_second`, reduced by +/// the WoT policy for a publisher's `distance`. /// -/// The WoT distance is `nostream-services`' graph, which no crate implements yet, so the -/// lookup yields `None` — the capture's own treatment of a pubkey outside the trust graph. -fn required_difficulty( - settings: &nostream_config::settings::AdaptivePowSettings, - context: &HandlerContext, - _event: &Event, +/// The adaptive arm scales `floor_bits` up to `ceiling_bits` with the measured rate +/// (`getCurrentDifficulty`) and then applies the closest eligible threshold (`applyWotPowPolicy`); +/// otherwise the static event-id floor answers. `0` means no requirement. +/// +/// The NIP-11 document answers this with a zero rate and no distance, which is the lowest +/// difficulty any client may be accepted at. The capture's +/// `ceil(floor_bits × difficulty_factor)` discount is therefore not advertised while no +/// distance reaches the handler: the graph's lookup resolves asynchronously and the event gate +/// is synchronous, so nothing supplies one yet. +pub fn required_difficulty( + event: Option<&EventLimits>, + events_per_second: f64, + distance: Option, ) -> u32 { - let config = AdaptivePowConfig { - enabled: settings.enabled, - floor_bits: settings.floor_bits, - ceiling_bits: settings.ceiling_bits, - target_events_per_second: settings.target_events_per_second, - period_ms: settings.period_ms, + let Some(event) = event else { + return 0; + }; + let Some(adaptive) = event.pow.as_ref().filter(|pow| pow.enabled) else { + return event + .event_id + .as_ref() + .and_then(|event_id| event_id.min_leading_zero_bits) + .unwrap_or(0); }; - let observed = context - .pow - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .current_events_per_second(settings.period_ms); + let config = AdaptivePowConfig { + enabled: adaptive.enabled, + floor_bits: adaptive.floor_bits, + ceiling_bits: adaptive.ceiling_bits, + target_events_per_second: adaptive.target_events_per_second, + period_ms: adaptive.period_ms, + }; let computed = - adaptive_pow::compute_difficulty(&config, observed).unwrap_or(settings.floor_bits); + adaptive_pow::compute_difficulty(&config, events_per_second).unwrap_or(adaptive.floor_bits); let thresholds: Option> = - settings.wot_thresholds.as_ref().map(|thresholds| { + adaptive.wot_thresholds.as_ref().map(|thresholds| { thresholds .iter() .map(|threshold| WotPowThreshold { @@ -368,7 +376,7 @@ fn required_difficulty( .collect() }); - adaptive_pow::apply_wot_pow_policy(computed, None, thresholds.as_deref()) + adaptive_pow::apply_wot_pow_policy(computed, distance, thresholds.as_deref()) } /// `isAuthenticationRequired` (`:285-297`). diff --git a/crates/nostream-relay/src/nip11.rs b/crates/nostream-relay/src/nip11.rs index 8c05e447f..7adbf736b 100644 --- a/crates/nostream-relay/src/nip11.rs +++ b/crates/nostream-relay/src/nip11.rs @@ -14,7 +14,7 @@ //! `supported_mips` and `fees.subscription` have no Rust source at all, and `payments_url` and //! `peering` name surfaces this relay does not serve. -use nostream_config::settings::{ContentLimitsOrVec, EventLimits, FeeSchedule, Settings}; +use nostream_config::settings::{ContentLimitsOrVec, FeeSchedule, Settings}; use nostream_core::Pubkey; use nostream_core::constants::SUPPORTED_NIPS; use nostream_storage::DEFAULT_PAGE_ROWS; @@ -261,6 +261,10 @@ fn limitation(settings: &Settings) -> Limitation { .and_then(|limits| limits.client.as_ref()) .and_then(|client| client.subscription.as_ref()); + // The document answers the enforced derivation at a zero rate and no distance — the lowest + // difficulty any client may be accepted at (`handlers::event::required_difficulty`). + let required = crate::handlers::event::required_difficulty(event, 0.0, None); + Limitation { max_message_length: u64::try_from(crate::transport::max_payload_size(settings)) .unwrap_or(u64::MAX), @@ -272,7 +276,7 @@ fn limitation(settings: &Settings) -> Limitation { subscription.and_then(|limits| limits.max_subscription_id_length), ), max_content_length: content_length(event.and_then(|event| event.content.as_ref())), - min_pow_difficulty: min_pow_difficulty(event), + min_pow_difficulty: (required > 0).then_some(u64::from(required)), auth_required: false, payment_required: settings.payments.as_ref().map(|payments| payments.enabled), created_at_lower_limit: event @@ -304,32 +308,6 @@ fn content_length(content: Option<&ContentLimitsOrVec>) -> Option { } } -/// The lowest difficulty any client may be accepted at: what `required_difficulty` enforces. -/// -/// That function passes `None` as the WoT distance (`handlers/event.rs:371`) because the graph is -/// `nostream-services`' and no crate supplies one yet, and with no distance -/// `apply_wot_pow_policy` answers the computed difficulty unchanged -/// (`nostream_core::adaptive_pow`), which is `floor_bits` at rest. The capture's -/// `ceil(floor_bits × difficulty_factor)` discount is therefore granted to nobody here: it only -/// applies once a distance exists, so advertising it would promise a bound the handler rejects. -/// With the adaptive check off, the static event-id floor is the enforced one. -fn min_pow_difficulty(event: Option<&EventLimits>) -> Option { - let pow = event - .and_then(|event| event.pow.as_ref()) - .filter(|pow| pow.enabled); - let difficulty = match pow { - Some(pow) => u64::from(pow.floor_bits), - None => u64::from( - event - .and_then(|event| event.event_id.as_ref()) - .and_then(|event_id| event_id.min_leading_zero_bits) - .unwrap_or(0), - ), - }; - - (difficulty > 0).then_some(difficulty) -} - /// The enabled fee schedules, and only while payments are on — the predicate the admission /// check applies. fn fees(settings: &Settings) -> Fees { diff --git a/crates/nostream-relay/tests/nip11.rs b/crates/nostream-relay/tests/nip11.rs index cc488cd35..a9475b9f7 100644 --- a/crates/nostream-relay/tests/nip11.rs +++ b/crates/nostream-relay/tests/nip11.rs @@ -5,6 +5,7 @@ //! | `the_key_set_is_the_decided_one` | the nine always-present keys, the four kept-when-set keys, and every dropped key absent | //! | `supported_nips_is_the_advertised_set_filtered_by_what_runs` | 43/50 follow their switches, 77 never appears, and the order is `SUPPORTED_NIPS`'s | //! | `the_limitation_block_reports_the_enforced_limits` | the enforced numbers, and a configured `0` omitted | +//! | `the_advertised_difficulty_is_the_shared_functions_answer` | `min_pow_difficulty` is `required_difficulty`'s answer at a zero rate and no distance, over six settings rows | //! | `restricted_writes_folds_the_arms_the_event_handler_enforces` | each arm alone flips it; the all-off fixture is false; a subscription plan alone does not | //! | `fees_reports_enabled_schedules_in_msats` | enabled schedules only, `publication` only when configured, empty under `payments.enabled: false` | //! | `self_is_the_published_identity_or_absent` | the published key wins over `info.self`; no key means no `self` | @@ -18,10 +19,12 @@ use std::path::Path; use nostream_config::settings::{ - EventIdLimits, FeeSchedule, Settings, SubscriptionPlan, WotPowThreshold, + AdaptivePowSettings, EventIdLimits, EventLimits, FeeSchedule, Settings, SubscriptionPlan, + WotPowThreshold, }; use nostream_core::constants::SUPPORTED_NIPS; use nostream_core::{Kind, KindSelector, Pubkey, SettingsPubkey}; +use nostream_relay::handlers::event::required_difficulty; use nostream_relay::nip11; use serde_json::{Value, json}; @@ -233,6 +236,157 @@ fn the_limitation_block_reports_the_enforced_limits() { ); } +/// The document's `limitation.min_pow_difficulty` for `limits.event = event`: the key's value, +/// or `None` when it is absent. +fn advertised_floor(event: Option<&EventLimits>) -> Option { + let mut settings = shipped(); + settings.limits.as_mut().expect("the shipped limits").event = event.cloned(); + let document = value(&settings, "0.1.0", None); + document["limitation"].get("min_pow_difficulty").cloned() +} + +/// The advertised floor is the shared derivation's answer, not a second reading of the same +/// settings: each row is one `EventLimits` value, the function is asked directly, and the +/// document is its answer at a zero rate and no distance, folded to an absent key when nothing +/// is required. M5's and M6's extra answers pin the distance and rate arms, which the document +/// deliberately does not take. +#[test] +fn the_advertised_difficulty_is_the_shared_functions_answer() { + // M1 — no `limits.event`: nothing is required and nothing is advertised. + assert_eq!(required_difficulty(None, 0.0, None), 0, "M1: the function"); + assert_eq!( + advertised_floor(None), + None, + "M1: the document omits the key" + ); + + // M2 — pow present and disabled: the static event-id floor is the enforced one. + let m2 = EventLimits { + pow: Some(AdaptivePowSettings { + enabled: false, + floor_bits: 16, + ceiling_bits: 32, + target_events_per_second: 50.0, + period_ms: 60_000, + wot_thresholds: None, + }), + event_id: Some(EventIdLimits { + min_leading_zero_bits: Some(20), + }), + ..Default::default() + }; + assert_eq!( + required_difficulty(Some(&m2), 0.0, None), + 20, + "M2: the static floor" + ); + assert_eq!( + advertised_floor(Some(&m2)), + Some(json!(20)), + "M2: the document" + ); + + // M3 — pow enabled with a zero floor wins over the static floor: nothing is required. + let m3 = EventLimits { + pow: Some(AdaptivePowSettings { + enabled: true, + floor_bits: 0, + ceiling_bits: 32, + target_events_per_second: 50.0, + period_ms: 60_000, + wot_thresholds: None, + }), + event_id: Some(EventIdLimits { + min_leading_zero_bits: Some(20), + }), + ..Default::default() + }; + assert_eq!( + required_difficulty(Some(&m3), 0.0, None), + 0, + "M3: the adaptive floor wins" + ); + assert_eq!( + advertised_floor(Some(&m3)), + None, + "M3: the document omits the key" + ); + + // M4 — pow enabled with a 16-bit floor and no thresholds: the floor is both ends' answer. + let m4 = EventLimits { + pow: Some(AdaptivePowSettings { + enabled: true, + floor_bits: 16, + ceiling_bits: 32, + target_events_per_second: 50.0, + period_ms: 60_000, + wot_thresholds: None, + }), + ..Default::default() + }; + assert_eq!( + required_difficulty(Some(&m4), 0.0, None), + 16, + "M4: the floor at rest" + ); + assert_eq!( + advertised_floor(Some(&m4)), + Some(json!(16)), + "M4: the document" + ); + + // M5 — the same floor with a `maxDistance: 2, difficultyFactor: 0.5` threshold: the policy + // would discount an eligible distance to 8, but no distance reaches the handler, so both + // ends answer 16 and the document advertises it. + let m5 = EventLimits { + pow: Some(AdaptivePowSettings { + enabled: true, + floor_bits: 16, + ceiling_bits: 32, + target_events_per_second: 50.0, + period_ms: 60_000, + wot_thresholds: Some(vec![WotPowThreshold { + max_distance: 2, + difficulty_factor: 0.5, + }]), + }), + ..Default::default() + }; + assert_eq!( + required_difficulty(Some(&m5), 0.0, None), + 16, + "M5: no distance, no discount" + ); + assert_eq!( + required_difficulty(Some(&m5), 0.0, Some(2)), + 8, + "M5: the distance arm" + ); + assert_eq!( + advertised_floor(Some(&m5)), + Some(json!(16)), + "M5: the document keeps the floor" + ); + + // M6 — M5's settings under a 100/s rate scale to the 32-bit ceiling; the document, asked at + // a zero rate, still advertises the 16 the lowest rate requires. + assert_eq!( + required_difficulty(Some(&m5), 100.0, None), + 32, + "M6: the rate arm" + ); + assert_eq!( + required_difficulty(Some(&m5), 0.0, None), + 16, + "M6: the floor at rest" + ); + assert_eq!( + advertised_floor(Some(&m5)), + Some(json!(16)), + "M6: the document" + ); +} + /// The shipped defaults with every write-restriction arm off. fn all_arms_off() -> Settings { let mut settings = shipped();