-
Notifications
You must be signed in to change notification settings - Fork 233
feat(pow): add relay-load-aware adaptive PoW difficulty #756
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
cbb161e
c3555e5
b34c467
e454e26
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| --- | ||
| "nostream": minor | ||
| --- | ||
|
|
||
| feat: add relay-load-aware adaptive PoW difficulty (NIP-13) | ||
|
|
||
| Adds `limits.event.pow` settings that scale the required proof-of-work difficulty between a | ||
| configured floor and ceiling based on the observed event rate, in place of the existing static | ||
| `minLeadingZeroBits` values. The event rate is tracked per worker process with the same EWMA shape | ||
| already used by the relay's rate limiter. Disabled by default (`limits.event.pow.enabled: false`), | ||
| so existing static PoW configuration is unaffected unless explicitly opted in. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,7 @@ | ||
| import { | ||
| getCurrentDifficulty as getAdaptivePowDifficulty, | ||
| recordEvent as recordAdaptivePowEvent, | ||
| } from '../utils/adaptive-pow' | ||
| import { ContextMetadataKey, EventExpirationTimeMetadataKey, EventKinds } from '../constants/base' | ||
| import { attemptValidation } from '../utils/validation' | ||
| import { eventSchema } from '../schemas/event-schema' | ||
|
|
@@ -127,6 +131,16 @@ export class EventMessageHandler implements IMessageHandler { | |
| return | ||
| } | ||
|
|
||
| // Recorded here, not inside canAcceptEvent's PoW branch: only events that | ||
| // clear every admission check (PoW, blacklist, auth, NIP-05, dedup, ...) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Dedup is not actually cleared before this point -- the strategies only learn whether the write landed ( |
||
| // should count toward the load signal. Recording earlier would let cheap, | ||
| // easily-rejected spam (e.g. from rotating pubkeys) push the difficulty to | ||
| // ceiling for everyone without the attacker ever doing any real work. | ||
| const powSettings = this.settings().limits?.event?.pow | ||
| if (powSettings?.enabled) { | ||
| recordAdaptivePowEvent(powSettings.periodMs) | ||
| } | ||
|
|
||
| const strategy = this.strategyFactory([event, this.webSocket]) | ||
|
|
||
| if (typeof strategy?.execute !== 'function') { | ||
|
|
@@ -195,17 +209,31 @@ export class EventMessageHandler implements IMessageHandler { | |
| return `rejected: created_at is more than ${limits.createdAt.maxNegativeDelta} seconds in the past` | ||
| } | ||
|
|
||
| if (typeof limits.eventId?.minLeadingZeroBits !== 'undefined' && limits.eventId.minLeadingZeroBits > 0) { | ||
| if (limits.pow?.enabled) { | ||
|
Priyanshubhartistm marked this conversation as resolved.
|
||
| const requiredBits = getAdaptivePowDifficulty(limits.pow) | ||
|
|
||
| const pow = getEventProofOfWork(event.id) | ||
| if (pow < limits.eventId.minLeadingZeroBits) { | ||
| return `pow: difficulty ${pow}<${limits.eventId.minLeadingZeroBits}` | ||
| if (pow < requiredBits) { | ||
| return `pow: difficulty ${pow}<${requiredBits}` | ||
| } | ||
| } | ||
|
|
||
| if (typeof limits.pubkey?.minLeadingZeroBits !== 'undefined' && limits.pubkey.minLeadingZeroBits > 0) { | ||
| const pow = getPubkeyProofOfWork(event.pubkey) | ||
| if (pow < limits.pubkey.minLeadingZeroBits) { | ||
| return `pow: pubkey difficulty ${pow}<${limits.pubkey.minLeadingZeroBits}` | ||
| const pubkeyPow = getPubkeyProofOfWork(event.pubkey) | ||
| if (pubkeyPow < requiredBits) { | ||
| return `pow: pubkey difficulty ${pubkeyPow}<${requiredBits}` | ||
| } | ||
| } else { | ||
| if (typeof limits.eventId?.minLeadingZeroBits !== 'undefined' && limits.eventId.minLeadingZeroBits > 0) { | ||
| const pow = getEventProofOfWork(event.id) | ||
| if (pow < limits.eventId.minLeadingZeroBits) { | ||
| return `pow: difficulty ${pow}<${limits.eventId.minLeadingZeroBits}` | ||
| } | ||
| } | ||
|
|
||
| if (typeof limits.pubkey?.minLeadingZeroBits !== 'undefined' && limits.pubkey.minLeadingZeroBits > 0) { | ||
| const pow = getPubkeyProofOfWork(event.pubkey) | ||
| if (pow < limits.pubkey.minLeadingZeroBits) { | ||
| return `pow: pubkey difficulty ${pow}<${limits.pubkey.minLeadingZeroBits}` | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { AdaptivePowSettings } from '../@types/settings' | ||
| import { calculateEWMA } from './ewma-rate-limiter' | ||
|
|
||
| // Per-worker in-process state: adaptive PoW is a soft anti-spam gate, not a | ||
| // hard cross-worker limit, so there's no need to pay a Redis round-trip on | ||
| // every single event just to read a difficulty threshold. | ||
| let rate = 0 | ||
| // 0, not Date.now(): the first recordEvent() call computes a huge deltaT | ||
| // against it, which decays rOld (0) to effectively nothing before adding | ||
| // the new hit -- exactly "never recorded before" without a special case. | ||
| let lastEventAt = 0 | ||
|
|
||
| export const recordEvent = (periodMs: number, now: number = Date.now()): void => { | ||
| rate = calculateEWMA(rate, Math.max(0, now - lastEventAt), periodMs, 1) | ||
| lastEventAt = now | ||
| } | ||
|
|
||
| export const getCurrentRate = (): number => rate | ||
|
|
||
| // calculateEWMA's `rate` is a recency-weighted event count, not a per-second | ||
| // rate: at a steady R events/sec it converges to R * periodMs/1000/ln(2) -- | ||
| // about 86.6x R at the default 60s half-life. Divide back out by that same | ||
| // factor before comparing against targetEventsPerSecond, which is per-second. | ||
| export const getCurrentEventsPerSecond = (periodMs: number): number => rate / (periodMs / 1000 / Math.LN2) | ||
|
|
||
| export const resetAdaptivePowState = (): void => { | ||
| rate = 0 | ||
| lastEventAt = 0 | ||
| } | ||
|
|
||
| export const getCurrentDifficulty = (config: AdaptivePowSettings): number => { | ||
| const eventsPerSecond = getCurrentEventsPerSecond(config.periodMs) | ||
|
|
||
| if (config.targetEventsPerSecond <= 0 || eventsPerSecond <= config.targetEventsPerSecond) { | ||
| return config.floorBits | ||
| } | ||
|
|
||
| const ratio = eventsPerSecond / config.targetEventsPerSecond | ||
| const scaled = config.floorBits + Math.ceil((ratio - 1) * (config.ceilingBits - config.floorBits)) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This single |
||
|
|
||
| return Math.max(config.floorBits, Math.min(config.ceilingBits, scaled)) | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.