Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/nip11-pow-derivation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
88 changes: 48 additions & 40 deletions crates/nostream-relay/src/handlers/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -330,35 +326,47 @@ fn check_content_limit(event: &Event, limit: &ContentLimits) -> Option<String> {
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>,
) -> 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<Vec<WotPowThreshold>> =
settings.wot_thresholds.as_ref().map(|thresholds| {
adaptive.wot_thresholds.as_ref().map(|thresholds| {
thresholds
.iter()
.map(|threshold| WotPowThreshold {
Expand All @@ -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`).
Expand Down
34 changes: 6 additions & 28 deletions crates/nostream-relay/src/nip11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
Expand All @@ -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
Expand Down Expand Up @@ -304,32 +308,6 @@ fn content_length(content: Option<&ContentLimitsOrVec>) -> Option<u64> {
}
}

/// 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<u64> {
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 {
Expand Down
156 changes: 155 additions & 1 deletion crates/nostream-relay/tests/nip11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand All @@ -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};

Expand Down Expand Up @@ -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<Value> {
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();
Expand Down
Loading