#!/usr/bin/env python3
"""Reference implementation of the strain record and the direction rule.
Standard library only. Every constant is read from schema/constants.json rather
than hardcoded, so this file and the protocol version digest cannot disagree.
Everything a node survives is currently thrown away. A restart, a partition, an
aborted session, a reconnect, a clock that drifted - each is correctly refused as
a finding about a peer, because the protocol must never conclude something about
a peer from an absence, and then it is discarded entirely. The accusation goes
and the information goes with it.
Kept, it sets the node's own reserves. Two rules make that safe.
**Local and defensive only.** A strain record never becomes a finding and never
crosses the wire, and a peer's own account of what it has weathered is a claim
rather than evidence and is not read. If the whole of a node's response to being
stressed is to become better prepared for that exact stress, then an attacker
who causes it has done the node a favour and there is nothing to farm. Anything
that instead paid a node in reputation or authority for having been attacked
would be an invitation to manufacture the attack.
**Directions, never magnitude.** A reserve grows with the number of independent
directions the stress came from and never with how much came from any one of
them. A tree grows straight because the wind turns; where the wind is strong and
always from one quarter the result is a flag tree, bent and one-sided and weaker
overall. Each direction is capped, and weighted by the tier this node granted
that peer - probation is 0.0, so free identities buy no directions at all, and a
tier is only ever raised by a person. The sybil is priced by a constant that
already existed.
"""
from __future__ import annotations
from typing import Callable, Mapping, Optional
from ..wire import schema_files
from ..wire.interfaces import StrainDirection
_C = schema_files.load_constants()
C = _C['resilience']
TIER_WEIGHT: dict[str, float] = _C['trust']['tier_weight']
KINDS: tuple[int, ...] = tuple(C['kinds'])
[docs]def direction(peer: Optional[str] = None, shard: Optional[str] = None, transport: Optional[str] = None) -> StrainDirection:
"""The unit adaptation counts: one peer, one shard, one transport."""
return (peer or '', shard or '', transport or '')
[docs]def weigh(strain_by_direction: Mapping[StrainDirection, int | float], tier_of: Optional[Callable[[str], str]] = None) -> float:
"""Weighted directions, saturating. Never a function of magnitude.
`strain_by_direction` maps a direction to how much stress came from it, in
whatever unit the caller counts; only whether it crossed the cap matters,
which is the whole point. `tier_of` answers what tier this node granted a
peer, defaulting to probation - weight zero - so an unknown peer buys
nothing.
"""
cap = float(C['per_direction_cap'])
total = 0.0
for (peer, _shard, _transport), amount in sorted(strain_by_direction.items()):
tier = (tier_of(peer) if tier_of else 'probation') or 'probation'
total += min(cap, float(amount)) * TIER_WEIGHT.get(tier, 0.0)
return min(total, float(C['saturates_at']))
[docs]def multiple(weight: float) -> float:
"""What a reserve is multiplied by, from 1.0 up to max_multiple.
Linear in weighted directions and flat once saturated. A node that has been
stressed from four trusted directions holds four times what it would have.
"""
sat, top = float(C['saturates_at']), float(C['max_multiple'])
if sat <= 0:
return 1.0
return 1.0 + (top - 1.0) * min(1.0, max(0.0, weight) / sat)
[docs]def reserve(base: float, strain_by_direction: Mapping[StrainDirection, int | float], tier_of: Optional[Callable[[str], str]] = None) -> float:
"""A local reserve, thickened by how many directions have tested it."""
return float(base * multiple(weigh(strain_by_direction, tier_of)))
[docs]def external(strain_by_direction: Mapping[StrainDirection, int | float]) -> dict[StrainDirection, int | float]:
"""Only the directions a node can be dependent ON.
A direction naming neither a peer nor a transport is the node's own event.
A restart names nothing, so on a node that has just started it was the whole
of the strain and the flag-tree warning fired at once, against an empty
direction, on a sample of one. Found on hardware within a minute of the
first deploy. Dependence is something a node has on somebody else.
"""
return {(peer, shard, transport): n
for (peer, shard, transport), n in strain_by_direction.items()
if peer or transport}
[docs]def dominant(strain_by_direction: Mapping[StrainDirection, int | float]) -> tuple[Optional[StrainDirection], float]:
"""(direction, share) of the external direction accounting for most strain.
A node whose stress is nearly all one direction is a flag tree: it is
structurally dependent on that peer and will snap when it leaves. Reported
to the operator and never a finding about the peer, which has done nothing
but be the only one there.
"""
ext = external(strain_by_direction)
total = sum(float(v) for v in ext.values())
if total <= 0:
return None, 0.0
key = max(sorted(ext), key=lambda k: ext[k])
return key, ext[key] / total
[docs]def flag_tree(strain_by_direction: Mapping[StrainDirection, int | float]) -> tuple[Optional[StrainDirection], float]:
"""Whether one direction dominates far enough to be worth saying out loud.
Needs both a share and a sample: one event is a Tuesday, not a dependence.
"""
ext = external(strain_by_direction)
if sum(float(v) for v in ext.values()) < C['flag_tree_min_events']:
return None, dominant(strain_by_direction)[1]
key, share = dominant(strain_by_direction)
return (key, share) if key is not None and share >= C['flag_tree_share'] else (None, share)