Source code for fleetmesh_core.peering.badpeer

"""A node that misbehaves on purpose, with a switch per offence.

The severity ladder is the part of this protocol that decides what happens to a
peer, and until now it was only ever exercised by hand-built counters. A ladder
tested against arithmetic somebody wrote for the test is not tested. This is the
thing the specification's conformance section asks for: a peer that actually
commits each offence, so the finding is produced by the code path a real session
would take rather than by a fixture.

Seven offences, named by ยง Conformance:

  overrun-and-admit       spends far past its limits and reports it truthfully
  overrun-and-lie         spends the same and reports counters inside the limit
  out-of-scope-push       delivers events outside the interest it was given
  duplicate-flood         delivers events the receiver already holds
  over-long-path          a delivery envelope with more hops than delivery allows
  replayed-receipt        re-sends an earlier receipt rather than a new one
  forged-hop-signature    a path entry whose signature is not the node's

The first four are session behaviour and ride on fleetmesh_core/storage/sync.py. The last three are
envelope and receipt behaviour, which a session never produces; they are built
here directly so the same switch covers all seven.

An implementation claiming conformance should be run against this, in the role
of the honest side, and should reach the same findings core/tests/test_badpeer.py
asserts. Standard library only.
"""
from __future__ import annotations

import copy
from typing import Any, Mapping, Optional, Sequence

from ..storage import replication, sync
from ..wire.interfaces import DeliveryEnvelope, NostrEvent, ReceiptBody

OFFENCES: tuple[str, ...] = (
    'overrun-and-admit', 'overrun-and-lie', 'out-of-scope-push',
    'duplicate-flood', 'over-long-path', 'replayed-receipt',
    'forged-hop-signature'
)

SESSION_OFFENCES: tuple[str, ...] = (
    'overrun-and-admit', 'overrun-and-lie', 'out-of-scope-push',
    'duplicate-flood'
)


[docs]class BadPeer(sync.Session): """A sync/1.0 responder that breaks one rule and behaves normally otherwise. offence=None is an honest peer, which is the control every one of these cases needs: the same code path with the switch off must produce no finding at all, or the finding says nothing about the offence. flood is how many times a duplicate-flood repeats what it sends, and how far an overrun goes past what it was asked for. Both are multipliers rather than counts so a test can state the overrun it wants and let the tier ceiling come from constants.json. """
[docs] def __init__( self, *args: Any, offence: Optional[str] = None, flood: int = 8, **kwargs: Any, ) -> None: self.offence: Optional[str] = offence self.flood: int = flood if self.offence is not None and self.offence not in OFFENCES: raise ValueError('no such offence: %s' % self.offence) super().__init__(*args, **kwargs) # What it pushed, which is what the other side will measure. A receipt # is a claim about this, so a lie is a claim that differs from it. self.pushed: dict[str, int] = {'events_in': 0, 'bytes_in': 0} self._receipts: list[ReceiptBody] = []
# ---- serving ---------------------------------------------------------
[docs] def on_need(self, message: Mapping[str, Any]) -> Mapping[str, Any]: if self.offence not in SESSION_OFFENCES: m = super().on_need(message) self._account(m) return m self.counters['bytes_in'] += sync.wire_bytes(message) events = self._misbehave(message['body']['ids']) m = self._msg('deliver', {'count': len(events), 'events': events}) self.counters['bytes_out'] += sync.wire_bytes(m) self._account(m) return m
def _account(self, deliver: Mapping[str, Any]) -> None: """Track what this peer put on the wire, honestly, for its own use. The receipt lies about this later if the switch says so. Keeping the truth here is what makes the lie measurable rather than asserted. """ events = deliver['body'].get('events') or [] self.pushed['events_in'] += len(events) self.pushed['bytes_in'] += sync.wire_bytes(deliver) def _misbehave(self, wanted: list[str]) -> list[Mapping[str, Any]]: held = self.store.items_range({}, 0, 2 ** 31, self.now) by_id: dict[str, Mapping[str, Any]] = {} for _, eid in held: ev = self.store.get_event(eid) if ev is not None: by_id[eid] = ev if self.offence == 'out-of-scope-push': # Everything it holds, the granted push scope ignored. An honest # responder drops these and files an S0 against itself instead. return list(by_id.values()) asked = [by_id[i] for i in wanted if i in by_id] if self.offence == 'duplicate-flood': # The same events again and again. Reconciliation told it these # were wanted once; sending them repeatedly is the offence. return asked * self.flood # Both overruns push the same traffic. They differ only in the receipt. return [by_id[i] for i in sorted(by_id)] * self.flood # ---- accounting ------------------------------------------------------
[docs] def receipt(self, seq: int = 0, prev: Optional[str] = None, at: Optional[int] = None) -> ReceiptBody: """A budget/1.0 receipt over what it pushed, or a lie about it. overrun-and-lie halves the counters until they sit inside the limit it was granted, which is the shape of the lie that matters: not a wild number, but the largest believable one. """ if self.offence == 'replayed-receipt' and self._receipts: # Not a new claim at all. Same seq, same prev, same counters, as # though the window had not moved. return copy.deepcopy(self._receipts[0]) counters = dict(self.pushed) if self.offence == 'overrun-and-lie': counters = {k: self._inside_limit(k, v) for k, v in counters.items()} body: ReceiptBody = { 'grant': self.grant.event_id, 'window': self.now // self.grant.window, 'seq': seq, 'prev': prev or '00' * 32, 'counters': {k: v for k, v in counters.items() if v}, 'at': at if at is not None else self.now, } self._receipts.append(copy.deepcopy(body)) return body
def _inside_limit(self, name: str, value: int) -> int: limit = self.grant.limits.get(name) if not limit: return value return min(value, int(limit * 0.9)) # ---- envelopes, which a session never builds --------------------------
[docs] def envelope( self, event: NostrEvent, hop_keys: Sequence[tuple[str, str]], at: int = 1787000000, ) -> DeliveryEnvelope: """A delivery envelope carrying whichever envelope offence is switched on. hop_keys are (did, secret key hex) in path order. An honest envelope is produced when the switch is off or is a session offence, so the same call is the control. """ env: DeliveryEnvelope = {'event': event, 'path': []} keys = list(hop_keys) if self.offence == 'over-long-path': limit = replication.CONSTANTS['delivery']['max_forward_hops'] while len(keys) <= limit: keys.append(keys[-1]) for i, (did, sk) in enumerate(keys): env = replication.append_hop(env, did, sk, at + i) if self.offence == 'forged-hop-signature': # The path says one node signed it. The signature is another's, so # the hop verifies against nothing the path claims. env['path'][-1]['sig'] = env['path'][0]['sig'] return env