Skip to content

Commit 55385ca

Browse files
committed
correction: Bound alignment cache
Limit attacker-keyed syndrome alignment state to eight recent entries while retaining reuse for normal correction work. Add churn and cache-hit regression coverage.\n\nFixes #21.
1 parent c118a83 commit 55385ca

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

‎src/codex32/correction.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
from collections.abc import Callable, Sequence
2525
from dataclasses import dataclass, replace
26-
from functools import cache
26+
from functools import cache, lru_cache
2727
from math import comb
2828
from time import monotonic
2929
from typing import Literal
@@ -250,6 +250,10 @@ class _Spec:
250250
1023,
251251
)
252252

253+
# Keep all six standard ms target lengths hot without letting arbitrary HRPs
254+
# create process-lifetime state.
255+
_ALIGNMENT_CACHE_SIZE = 8
256+
253257

254258
def _spec_for_checksum(checksum: _Checksum) -> _Spec:
255259
if checksum is _CODEX32:
@@ -276,7 +280,7 @@ def _pack_syndromes(values: tuple[int, ...]) -> int:
276280
return sum(value << (10 * index) for index, value in enumerate(values))
277281

278282

279-
@cache
283+
@lru_cache(maxsize=_ALIGNMENT_CACHE_SIZE)
280284
def _syndrome_alignment(spec: _Spec, hrp: str, length: int) -> tuple[int, tuple[tuple[int, ...], ...]]:
281285
base = _pack_syndromes(_syndromes(spec, _residue(spec, hrp, [0] * length), target=True))
282286
powers = _poly_powers(spec.generator, length)

‎tests/test_alignment.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from codex32._alignment import _IncrementalSyndromes, _View
88
from codex32.correction import (
9+
_ALIGNMENT_CACHE_SIZE,
910
_LONG_SPEC,
1011
_SHORT_SPEC,
1112
_pack_syndromes,
@@ -15,6 +16,29 @@
1516
)
1617

1718

19+
def test_syndrome_alignment_cache_is_bounded_for_untrusted_hrps():
20+
_syndrome_alignment.cache_clear()
21+
22+
for index in range(_ALIGNMENT_CACHE_SIZE + 5):
23+
_syndrome_alignment(_SHORT_SPEC, f"attacker{index}", 45)
24+
25+
info = _syndrome_alignment.cache_info()
26+
assert info.maxsize == _ALIGNMENT_CACHE_SIZE
27+
assert info.currsize == _ALIGNMENT_CACHE_SIZE
28+
29+
30+
def test_syndrome_alignment_cache_still_reuses_recent_entries():
31+
_syndrome_alignment.cache_clear()
32+
first = _syndrome_alignment(_SHORT_SPEC, "ms", 45)
33+
before = _syndrome_alignment.cache_info()
34+
35+
second = _syndrome_alignment(_SHORT_SPEC, "ms", 45)
36+
37+
after = _syndrome_alignment.cache_info()
38+
assert first is second
39+
assert after.hits == before.hits + 1
40+
41+
1842
@pytest.mark.parametrize(
1943
("hrp", "length", "spec"),
2044
(

0 commit comments

Comments
 (0)