Files
meshcore-tth/src/helpers/FairnessLimiter.h
T

192 lines
9.1 KiB
C++

#pragma once
// CUSTOM (TeTeHacko): port of Beanow's "fairness limiter" (upstream proposal
// meshcore-dev/MeshCore#1502, branch beanow/wp-repeat). Token-bucket rate
// limiting of FORWARDED packets, bucketed by the 1-byte identifiers that are
// already in the clear on the air -- so it needs no protocol change and no
// decryption. It is an approximation by design: buckets collide (masks below)
// and every key is sender-controlled, so this is containment of accidental or
// lazy floods, not security. DIRECT (routed) traffic is never limited.
//
// Deviations from Beanow's branch, on purpose:
// * no RTCClock dependency -- it was only feeding log timestamps; logging
// goes through MESH_DEBUG_PRINTLN like the rest of this tree, which also
// lets the class run in native unit tests without a clock mock.
// * allowPacket() bounds-checks payload_len before reading payload bytes.
// The whole CI suite runs under ASAN because of earlier OOB parses; a
// limiter keyed on payload[1] must not be the next one.
#include <Packet.h>
#include <stdint.h>
#include "AdvertWindow.h"
// Sender hashes 0x00 and 0xFF are NOT special here. Our firmware never creates
// such an identity (re-roll on create, validatePrivateKey() on import), but the
// mesh still carries them: over 30 days (Sep-Oct 2026, CZ mesh) 50 floods of
// REQ/PATH/TXT_MSG/RESPONSE came from 0x00/0xFF senders -- older identities and
// other implementations. And for ANON_REQ payload[1] is the first byte of a
// random ephemeral key, so "always deny" also dropped 2 in 256 anonymous
// requests from anyone. Denying them always (as the original branch did)
// dropped every such flood; now they are limited like any other bucket.
// Note: mask, cap and refill interval are highly connected parameters.
#define GROUP_MASK 0b00011111 // 5-bit address
#define SENDER_NORMAL_MASK 0b00111111 // 6-bit address
#define SENDER_LOW_MASK 0b01111111 // 7-bit address
// Refill intervals: ONE token per bucket per interval. Steady-state rate is
// 1/interval, cap bounds the burst. Overridable per env from platformio ini.
//
// Sized from real traffic (6 Sep - 6 Oct 2026: 207k floods heard on the CZ
// mesh at one-site, replayed through this limiter with
// tools/fairness_replay.py -- rerun it when the traffic changes). The zero-loss frontier
// over those 30 days was group 60 s/cap 60, sender 10 s/cap 60, advert 600 s/
// cap 12; the defaults below keep about 2x headroom on top. The busiest
// legitimate channel runs ~26 msg/h around the clock, so the limiter is a net
// for runaway floods (the bot that prompted it sent ~330 msg/h), not a quota.
// The earlier defaults (cap 20/30/4, refill 180 s/240 s/7200 s) would have
// shed 9 % of channel messages, 15 % of sender-keyed traffic and 15 % of adverts.
#ifndef FAIRNESS_GROUP_REFILL_MS
#define FAIRNESS_GROUP_REFILL_MS (30 * 1000)
#endif
#ifndef FAIRNESS_SENDER_NORMAL_REFILL_MS
#define FAIRNESS_SENDER_NORMAL_REFILL_MS (10 * 1000)
#endif
#ifndef FAIRNESS_SENDER_LOW_REFILL_MS
#define FAIRNESS_SENDER_LOW_REFILL_MS (10 * 60 * 1000)
#endif
// Capacity (max burst) per bucket. uint8_t, so at most 255.
#ifndef FAIRNESS_GROUP_CAP
#define FAIRNESS_GROUP_CAP 100
#endif
#ifndef FAIRNESS_SENDER_NORMAL_CAP
#define FAIRNESS_SENDER_NORMAL_CAP 150
#endif
#ifndef FAIRNESS_SENDER_LOW_CAP
#define FAIRNESS_SENDER_LOW_CAP 30
#endif
// Simply allow all direct messages?
#ifndef FAIRNESS_ALLOW_DIRECT
#define FAIRNESS_ALLOW_DIRECT 1
#endif
// Derived from the masks, WONT fit in uint8 when full 0xFF mask.
#define GROUP_MAP_SIZE (GROUP_MASK + 1)
#define SENDER_NORMAL_MAP_SIZE (SENDER_NORMAL_MASK + 1)
#define SENDER_LOW_MAP_SIZE (SENDER_LOW_MASK + 1)
/**
* A token bucket rate limiter, which attempts to limit by sender or group channel.
*
* It provides some mitigation against accidental spam, as well as DoS attacks.
* However it's merely an approximation, as there will be ID collisions and easy
* ways to game it.
*
* Until a V2 protocol provides new means of limiting, the goal is a "better than
* nothing" reduction in wasteful repeats, freeing airtime for useful repeats.
*/
// Why a packet was shed (lastShed()). WINDOW = per-origin advert window.
enum FairShed : uint8_t { FAIR_SHED_NONE = 0, FAIR_SHED_GROUP, FAIR_SHED_SENDER, FAIR_SHED_ADVERT, FAIR_SHED_WINDOW,
FAIR_SHED_N };
class FairnessLimiter {
// Capacity of when a bucket is full. Runtime-settable (setGroupCap etc.) so
// limits can be loosened over RF admin without a reflash -- 0 to a setter
// resets to the build default below.
uint8_t group_cap = FAIRNESS_GROUP_CAP, sender_normal_cap = FAIRNESS_SENDER_NORMAL_CAP,
sender_low_cap = FAIRNESS_SENDER_LOW_CAP;
// Deny stats
uint32_t denied_group = 0, denied_sender_normal = 0, denied_sender_low = 0;
// Token buckets
uint8_t sender_normal_map[SENDER_NORMAL_MAP_SIZE] = {};
uint8_t sender_low_map[SENDER_LOW_MAP_SIZE] = {};
uint8_t group_map[GROUP_MAP_SIZE] = {};
// Per-bucket deny counters -- the "grid": which hash buckets we are actually
// shedding, so a shed is visible instead of a bare total. Saturating uint16.
uint16_t group_deny[GROUP_MAP_SIZE] = {};
uint16_t sender_normal_deny[SENDER_NORMAL_MAP_SIZE] = {};
uint16_t sender_low_deny[SENDER_LOW_MAP_SIZE] = {};
// Per-origin advert window (issue #2), runs ahead of the advert bucket so a
// repeat advert never takes a token a legitimate one would need.
AdvertWindow advert_window;
uint32_t denied_window = 0;
// Buckets on/off (`fairness on|off`); the window has its own switch (hours).
bool buckets_enabled = true;
// Dry-run (issue #1): every verdict is counted as if enforced, but the packet
// is forwarded anyway -- sizes a setting on a live mast before it bites.
bool dry_run = false;
FairShed last_shed = FAIR_SHED_NONE;
// Estimated airtime of what was shed (or would have been, in dry-run), ms,
// per FairShed reason. Fed by the caller, which owns the radio.
uint32_t shed_air_ms[FAIR_SHED_N] = {};
bool shed(FairShed why) { last_shed = why; return dry_run; }
public:
FairnessLimiter() {}
uint8_t peekGroup(const uint8_t* hash);
void refillGroup();
uint8_t peekSenderNormal(const uint8_t* hash);
void refillSenderNormal();
uint8_t peekSenderLow(const uint8_t* hash);
void refillSenderLow();
/**
* \brief Classify the packet and take a token from the matching bucket.
* CONSUMES a token when one is available -- call it only for a packet that
* would otherwise be forwarded, and only once per packet.
* \returns true if the packet should be forwarded
*/
bool allowPacket(const mesh::Packet* pkt, uint32_t now_ms);
// Without a clock: the advert window sees every call at t=0. For tests and
// callers that never enable the window.
bool allowPacket(const mesh::Packet* pkt) { return allowPacket(pkt, 0); }
// What the LAST allowPacket() call shed (FAIR_SHED_NONE = passed on its
// merits). In dry-run it is set although allowPacket() returned true.
FairShed lastShed() const { return last_shed; }
void addShedAirtime(FairShed why, uint32_t ms) { if (why < FAIR_SHED_N) shed_air_ms[why] += ms; }
uint32_t shedAirtimeMs(FairShed why) const { return why < FAIR_SHED_N ? shed_air_ms[why] : 0; }
void setBucketsEnabled(bool on) { buckets_enabled = on; }
bool bucketsEnabled() const { return buckets_enabled; }
void setDryRun(bool on) { dry_run = on; }
bool dryRun() const { return dry_run; }
AdvertWindow& advertWindow() { return advert_window; }
const AdvertWindow& advertWindow() const { return advert_window; }
uint32_t deniedWindow() const { return denied_window; }
// Inspect stats
uint32_t deniedSenderNormal() const { return denied_sender_normal; }
uint32_t deniedSenderLow() const { return denied_sender_low; }
uint32_t deniedGroup() const { return denied_group; }
// Runtime cap tuning (0 = restore the build default for that bucket).
void setGroupCap(uint8_t c) { group_cap = c ? c : FAIRNESS_GROUP_CAP; }
void setSenderNormalCap(uint8_t c) { sender_normal_cap = c ? c : FAIRNESS_SENDER_NORMAL_CAP; }
void setSenderLowCap(uint8_t c) { sender_low_cap = c ? c : FAIRNESS_SENDER_LOW_CAP; }
uint8_t groupCap() const { return group_cap; }
uint8_t senderNormalCap() const { return sender_normal_cap; }
uint8_t senderLowCap() const { return sender_low_cap; }
// The grid: append "<pfx>=<count>" for each bucket with denies, per category,
// busiest first, into `out` (bounded by max_len). Returns chars written.
// `pfx` is the low bits of the sender/channel hash -- cross-reference the
// observer feed / CoreScope to map a hot bucket back to an actual node.
int formatGrid(char* out, int max_len) const;
static int sender_normal_idx(const uint8_t* hash) { return hash[0] & SENDER_NORMAL_MASK; }
static int sender_low_idx(const uint8_t* hash) { return hash[0] & SENDER_LOW_MASK; }
static int group_idx(const uint8_t* hash) { return hash[0] & GROUP_MASK; }
protected:
bool takeSenderNormal(const uint8_t* hash);
bool takeSenderLow(const uint8_t* hash);
bool takeGroup(const uint8_t* hash);
};