Files
paperspec/tests/test_receipts.py
T
alexmandClaude a8fc7237ae Add the pytest suite and fix the bugs it found
The suite takes its data from the vectors and fixtures: 3635 tests, 97.9% branch
coverage, and paperspec check and paperspec stress give the same results as before.
Fixed: receipts.verify_signature raised KeyError for a record without a format;
traces.DOC_TAG matched a tag followed by a line feed; paperspec load and paperspec check
left SQLite connections open; the site builder copied the output folder's subfolders into
itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B8cL4zN4XpaQF5cBtASzfq
2026-10-19 04:32:44 -04:00

857 lines
30 KiB
Python

# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Scienting
#
# Source Code: https://git.scient.ing/papers/paperspec
# See the LICENSE.md file for full license terms.
"""Receipts: signing, statuses, revocations, spot-check samples, error bounds and levels (paperspec.receipts)."""
import base64
import json
from fractions import Fraction
from math import comb
import pytest
from hypothesis import given, settings, strategies as st
from conftest import FIXTURES, vector_cases
from helpers_lib2 import (
HALE,
PROPS,
RECORDS,
fixture_receipts,
fixture_roster,
receipt,
revocation,
roster_key,
roster_of,
sealed,
secret,
)
from paperspec import crypto, mldsa, package, receipts as rcp, vrf
from paperspec.text import record_id
NODES = [(f"node{c}", c * 64) for c in "abcdef"]
ROSTER = roster_of(
roster_key("ana", role="owner"),
roster_key("ben"),
roster_key("cara", role="reader"),
roster_key("ben-spot", purposes=("spot-check",)),
roster_key("dana", scheme="ml-dsa-65"),
)
SIGNATURES = {c["id"]: c for c in vector_cases("signatures")}
SPOTCHECKS = vector_cases("spotcheck")
def status_of(rec, records=None, roster=ROSTER):
"""The status of `rec` among `records` (itself, by default)."""
return rcp.receipt_status(rec, records or [rec], roster)
# --- record hashes and signatures -----------------------------------------------------------------
def test_receipt_vector_record_hash_payload_and_signature():
case = SIGNATURES["receipt-r1"]
rec = case["receipt"]
assert rcp.record_hash(rec) == case["record_hash"]
assert rcp.signing_payload(rec).decode() == case["payload"]
assert record_id(rcp.record_hash(rec)) == case["record_id"] == rec["id"]
roster = {"ana": {"scheme": "ed25519", "public": case["public"]}}
assert rcp.verify_signature(rec, roster)
def test_record_hash_ignores_id_signature_and_key_order():
rec = sealed(receipt(NODES))
shuffled = dict(reversed(list(rec.items())))
assert rcp.record_hash(shuffled) == rcp.record_hash(rec)
assert rcp.record_hash(
{k: v for k, v in rec.items() if k != "id"}
) == rcp.record_hash(rec)
assert rcp.record_hash(dict(rec, at="2026-10-11T12:00:01Z")) != rcp.record_hash(rec)
def test_the_signing_payload_names_the_format_and_the_hash():
rec = receipt(NODES)
payload = json.loads(rcp.signing_payload(rec))
assert payload == {"format": rec["format"], "hash": rcp.record_hash(rec)}
def test_signed_formats_are_the_four_signed_records():
assert rcp.SIGNED_FORMATS == (
"scienting-receipt/1",
"scienting-revocation/1",
"scienting-policy/1",
"scienting-qa-report/1",
)
def test_seal_fills_in_the_root_the_id_and_a_signature_that_verifies():
rec = sealed(receipt(NODES))
assert rec["root"] == crypto.merkle_root(crypto.receipt_items(rec))
assert rec["id"] == record_id(rcp.record_hash(rec))
assert rec["signature"]["scheme"] == "ed25519"
assert rec["signature"]["key"] == "ana"
assert len(base64.b64decode(rec["signature"]["value"])) == 64
assert rcp.verify_signature(rec, ROSTER)
def test_sealing_a_sealed_receipt_again_changes_nothing():
rec = sealed(receipt(NODES))
assert sealed(rec) == rec
def test_sealing_does_not_change_its_argument():
rec = receipt(NODES)
before = json.dumps(rec, sort_keys=True)
sealed(rec)
assert json.dumps(rec, sort_keys=True) == before
def test_sealing_a_revocation_adds_no_root():
rev = revocation("ana", receipt="abc")
assert "root" not in rev
assert rcp.verify_signature(rev, ROSTER)
def test_the_ml_dsa_fixture_receipt_verifies_and_is_reproduced_by_sealing():
rec = json.loads((RECORDS / "receipt-ml-dsa.json").read_text(encoding="utf-8"))
roster = fixture_roster()
assert rec["signature"]["scheme"] == "ml-dsa-65"
assert rcp.verify_signature(rec, roster)
assert not rcp.verify_signature(dict(rec, at="2026-10-13T09:00:01Z"), roster)
resealed = rcp.seal_mldsa(rec, mldsa.keygen(secret("dana"))[1], "dana")
assert resealed == rec
def test_an_ml_dsa_receipt_is_valid_under_a_roster_that_holds_its_key():
secret_key = mldsa.keygen(secret("dana"))[1]
rec = rcp.seal_mldsa(receipt(NODES, by="dana", level="F2"), secret_key, "dana")
assert rec["root"] == crypto.merkle_root(crypto.receipt_items(rec))
assert status_of(rec) == "valid"
def test_an_ml_dsa_revocation_has_no_root_and_verifies():
revocation_record = {
"format": "scienting-revocation/1",
"receipt": "abc",
"reason": "Revoked for a test.",
"by": "dana",
"at": "2026-10-11T13:00:00Z",
}
rec = rcp.seal_mldsa(revocation_record, mldsa.keygen(secret("dana"))[1], "dana")
assert "root" not in rec
assert rec["signature"]["scheme"] == "ml-dsa-65"
assert rcp.verify_signature(rec, ROSTER)
def verifies(rec, roster=ROSTER):
"""Whether the signature of `rec` verifies under `roster`."""
return rcp.verify_signature(rec, roster)
def signature_with(rec, **changes):
"""`rec` with fields of its signature replaced; a value of None removes the field."""
sig = {**rec["signature"], **changes}
return dict(rec, signature={k: v for k, v in sig.items() if v is not None})
def test_a_signature_does_not_verify_for_a_changed_record():
rec = sealed(receipt(NODES))
assert verifies(rec)
assert not verifies(dict(rec, level="F2"))
@pytest.mark.parametrize(
"tamper",
[
lambda r: {k: v for k, v in r.items() if k != "signature"},
lambda r: dict(r, signature=None),
lambda r: dict(r, signature="ana"),
lambda r: signature_with(r, key="nobody"),
lambda r: signature_with(r, key=None),
lambda r: signature_with(r, key="ben"),
lambda r: signature_with(r, scheme="ml-dsa-65"),
lambda r: signature_with(r, scheme="rsa"),
lambda r: signature_with(r, value="not base64!"),
lambda r: signature_with(r, value=None),
lambda r: signature_with(r, value=7),
lambda r: signature_with(r, value=base64.b64encode(bytes(63)).decode()),
lambda r: signature_with(r, value=base64.b64encode(bytes(64)).decode()),
],
ids=[
"no-signature",
"signature-null",
"signature-not-an-object",
"unknown-key",
"no-key",
"another-key",
"scheme-differs-from-the-roster",
"unimplemented-scheme",
"value-not-base64",
"no-value",
"value-not-text",
"value-too-short",
"value-zeros",
],
)
def test_signatures_that_cannot_verify_do_not(tamper):
assert not verifies(tamper(sealed(receipt(NODES))))
@pytest.mark.parametrize(
"key",
[
{"scheme": "ed25519", "public": "not base64!"},
{"scheme": "ed25519", "public": base64.b64encode(bytes(31)).decode()},
{"scheme": "ed25519"},
{"scheme": "ml-dsa-65", "public": base64.b64encode(bytes(32)).decode()},
{"scheme": "rsa", "public": base64.b64encode(bytes(32)).decode()},
{},
],
ids=[
"public-not-base64",
"short-public",
"no-public",
"short-ml-dsa",
"rsa",
"empty",
],
)
def test_a_roster_key_that_cannot_verify_does_not(key):
rec = sealed(receipt(NODES))
scheme = key.get("scheme", "ed25519")
rec = signature_with(rec, scheme=scheme)
assert not verifies(rec, {"ana": key})
def test_a_record_that_has_no_canonical_form_does_not_verify():
rec = sealed(receipt(NODES))
assert not verifies(dict(rec, extra=float("nan")))
def test_a_record_without_a_format_does_not_verify_and_does_not_raise():
rec = sealed(receipt(NODES))
assert not verifies({k: v for k, v in rec.items() if k != "format"})
@pytest.mark.parametrize(
("at", "valid"),
[
("2026-08-31T23:59:59Z", False),
("2026-09-01T00:00:00Z", True),
("2026-10-01T00:00:00Z", True),
("2026-10-15T00:00:00Z", False),
("2026-12-01T00:00:00Z", False),
],
)
def test_a_key_is_valid_from_registration_until_revocation(at, valid):
key = {
"registered_at": "2026-09-01T00:00:00Z",
"revoked_at": "2026-10-15T00:00:00Z",
}
assert rcp.key_valid_at(key, at) is valid
def test_a_key_without_a_revocation_date_stays_valid():
key = {"registered_at": "2026-09-01T00:00:00Z"}
assert rcp.key_valid_at(key, "2099-01-01T00:00:00Z")
assert rcp.key_valid_at({**key, "revoked_at": None}, "2099-01-01T00:00:00Z")
# --- spot-checks ------------------------------------------------------------------------------------
FULL_SAMPLE = next(c for c in SPOTCHECKS if "seed" in c)
def test_the_spot_check_vector_reproduces_seed_payload_beta_and_sample():
case = FULL_SAMPLE
seed = base64.b64decode(case["seed"])
checker = base64.b64decode(case["checker_public"])
assert rcp.seed_payload(case["receipt"]).decode() == case["seed_payload"]
assert (
vrf.verify(checker, case["seed_payload"].encode(), seed).hex() == case["beta"]
)
assert (
rcp.sample(case["receipt"], seed, case["rate"], case["minimum"])
== case["sample"]
)
assert len(case["sample"]) == case["size"]
def test_the_seed_of_the_spot_check_vector_is_the_checkers_vrf_proof():
case = FULL_SAMPLE
seed = rcp.make_seed(case["receipt"], secret("ben-spot"))
assert base64.b64encode(seed).decode() == case["seed"]
@pytest.mark.parametrize(
"case", [c for c in SPOTCHECKS if "seed" not in c], ids=lambda c: c["id"]
)
def test_sample_size_vectors(case):
assert rcp.sample_size(case["n"], case["rate"], case["minimum"]) == case["size"]
@pytest.mark.parametrize(
("n", "rate", "minimum", "size"),
[
(0, "0.05", 10, 0),
(5, "0.05", 10, 5),
(400, "0.05", 10, 20),
(401, "0.05", 10, 21),
(7, "1", 1, 7),
(9, "1/3", 1, 3),
(100, "0.5", 100, 100),
],
)
def test_sample_size_is_the_ceiling_of_the_rate_bounded_by_the_minimum_and_n(
n, rate, minimum, size
):
assert rcp.sample_size(n, rate, minimum) == size
def spot_check_receipt(n):
"""A receipt over `n` nodes, for sampling."""
return {"nodes": [[f"n{i:03d}", f"{i:064x}"] for i in range(n)]}
def test_sample_depends_on_the_seed_and_not_on_the_order_of_the_nodes():
rec = spot_check_receipt(60)
seed = rcp.make_seed(rec, secret("ben-spot"))
picked = rcp.sample(rec, seed)
reordered = {"nodes": rec["nodes"][::-1]}
assert rcp.sample(reordered, seed) == picked
assert picked == sorted(picked)
assert len(set(picked)) == len(picked) == 10
other = rcp.make_seed(rec, secret("ben"))
assert rcp.sample(rec, other) != picked
def test_sample_takes_every_node_of_a_small_receipt():
rec = spot_check_receipt(4)
seed = rcp.make_seed(rec, secret("ben-spot"))
assert rcp.sample(rec, seed) == [n for n, _ in rec["nodes"]]
@pytest.mark.parametrize("seed", [b"", bytes(79), b"x" * 81, b"\xff" * 80])
def test_a_seed_that_is_no_vrf_proof_is_refused(seed):
with pytest.raises(ValueError, match="not a VRF proof"):
rcp.sample(spot_check_receipt(12), seed)
@given(
st.integers(1, 80),
st.sampled_from(["0.05", "0.1", "0.5", "1"]),
st.integers(1, 15),
)
@settings(PROPS, max_examples=25)
def test_a_sample_has_the_size_the_rule_gives(n, rate, minimum):
rec = spot_check_receipt(n)
seed = rcp.make_seed(rec, secret("ben-spot"))
picked = rcp.sample(rec, seed, rate, minimum)
assert len(picked) == rcp.sample_size(n, rate, minimum)
assert set(picked) <= {nid for nid, _ in rec["nodes"]}
# --- error bounds -----------------------------------------------------------------------------------
BOUNDS = vector_cases("bounds")
@pytest.mark.parametrize("case", BOUNDS, ids=lambda c: c["id"])
def test_bound_vectors(case):
assert (
rcp.bound_string(case["errors"], case["sampled"], case["confidence"])
== case["bound"]
)
approx = rcp.upper_bound(case["errors"], case["sampled"], case["confidence"])
assert approx == pytest.approx(case["approx"], abs=1e-9)
def test_zero_errors_in_300_bound_the_rate_below_one_percent():
assert Fraction(rcp.bound_string(0, 300)) < Fraction(1, 100)
@pytest.mark.parametrize("n", [0, -3])
def test_bounds_need_a_positive_sample(n):
with pytest.raises(ValueError, match="n must be positive"):
rcp.bound_string(0, n)
with pytest.raises(ValueError, match="n must be positive"):
rcp.upper_bound(0, n)
@pytest.mark.parametrize("errors", [10, 11])
def test_all_errors_bound_the_rate_by_one(errors):
assert rcp.bound_string(errors, 10) == "1.000000"
assert rcp.upper_bound(errors, 10) == 1.0
def test_a_higher_confidence_gives_a_higher_bound():
assert Fraction(rcp.bound_string(2, 50, "0.99")) > Fraction(
rcp.bound_string(2, 50, "0.95")
)
assert rcp.upper_bound(2, 50, "0.99") > rcp.upper_bound(2, 50, "0.95")
@given(st.integers(1, 60), st.integers(0, 60), st.sampled_from(["0.9", "0.95", "0.99"]))
@settings(PROPS, max_examples=40)
def test_the_bound_is_the_least_six_decimal_rate_whose_tail_is_within_alpha(
n, k, confidence
):
k = min(k, n)
text = rcp.bound_string(k, n, confidence)
assert len(text.split(".")[1]) == 6
if k == n:
assert text == "1.000000"
return
alpha = 1 - Fraction(confidence)
def tail(p):
return sum(comb(n, i) * p**i * (1 - p) ** (n - i) for i in range(k + 1))
bound = Fraction(text)
assert tail(bound) <= alpha
assert bound == 0 or tail(bound - Fraction(1, 10**6)) > alpha
assert rcp.upper_bound(k, n, confidence) == pytest.approx(float(bound), abs=2e-6)
@given(st.integers(2, 60), st.integers(0, 58))
@settings(PROPS, max_examples=30)
def test_one_more_error_never_lowers_the_bound(n, k):
k = min(k, n - 2)
assert Fraction(rcp.bound_string(k + 1, n)) >= Fraction(rcp.bound_string(k, n))
# --- revocations -------------------------------------------------------------------------------------
def test_revoked_by_the_id_of_the_receipt():
rec = {"id": "r1", "by": "ana", "at": "2026-10-11T12:00:00Z"}
assert rcp.revoked(rec, [{"receipt": "r1"}])
assert not rcp.revoked(rec, [{"receipt": "r2"}])
assert not rcp.revoked(rec, [])
@pytest.mark.parametrize(
("period", "hit"),
[
({"from": "2026-10-11T00:00:00Z", "to": "2026-10-12T00:00:00Z"}, True),
({"from": "2026-10-11T12:00:00Z", "to": "2026-10-12T00:00:00Z"}, True),
({"from": "2026-10-01T00:00:00Z", "to": "2026-10-11T12:00:00Z"}, True),
({"from": "2026-10-11T12:00:01Z", "to": "2026-10-12T00:00:00Z"}, False),
({"from": "2026-10-01T00:00:00Z", "to": "2026-10-11T11:59:59Z"}, False),
(None, False),
],
ids=[
"inside",
"from-inclusive",
"to-inclusive",
"starts-after",
"ends-before",
"no-period",
],
)
def test_revoked_by_the_signer_and_a_period(period, hit):
rec = {"id": "r1", "by": "ana", "at": "2026-10-11T12:00:00Z"}
assert rcp.revoked(rec, [{"signer": "ana", "period": period}]) is hit
assert not rcp.revoked(rec, [{"signer": "ben", "period": period}])
def test_only_revocations_signed_by_someone_entitled_to_them_count():
own = sealed(receipt(NODES, by="ben"))
by_id = {own["id"]: own}
by_signer = revocation("ben", receipt=own["id"])
by_owner = revocation("ana", receipt=own["id"])
by_stranger = revocation("cara", receipt=own["id"])
names_signer = revocation("ben", signer="ben", period={"from": "a", "to": "b"})
names_other = revocation("cara", signer="ben", period={"from": "a", "to": "b"})
forged = dict(by_owner, reason="Changed after signing.")
unknown = revocation("zed", receipt=own["id"])
revs = [
by_signer,
by_owner,
by_stranger,
names_signer,
names_other,
forged,
unknown,
]
assert rcp.valid_revocations(revs, by_id, ROSTER) == [
by_signer,
by_owner,
names_signer,
]
def test_an_owner_may_revoke_a_receipt_nobody_holds():
rev = revocation("ana", receipt="vanished")
assert rcp.valid_revocations([rev], {}, ROSTER) == [rev]
assert (
rcp.valid_revocations([revocation("ben", receipt="vanished")], {}, ROSTER) == []
)
# --- statuses ----------------------------------------------------------------------------------------
def test_a_signed_receipt_of_a_registered_key_is_valid():
assert status_of(sealed(receipt(NODES))) == "valid"
def test_statuses_of_the_main_examples_receipts():
records = fixture_receipts()
status = rcp.statuses(records, fixture_roster())
assert status == {
"vskq18t5sxydz": "valid",
"fhhvg9qrzqp0n": "valid",
"mvjmb94nz7rdh": "valid",
"q465jpwz8afhe": "revoked",
"gx2s84z9jf9xv": "suspended",
"ksx5sc327xp97": "valid",
"yt70fcc3qm0xb": "valid",
}
def test_a_receipt_among_records_that_do_not_hold_it_is_invalid():
rec = sealed(receipt(NODES))
assert rcp.receipt_status(rec, [], ROSTER) == "invalid"
assert rcp.receipt_status({}, [rec], ROSTER) == "invalid"
def test_statuses_ignore_records_that_are_not_receipts():
rec = sealed(receipt(NODES))
assert rcp.statuses([{"format": "scienting-policy/1", "id": "p"}, rec], ROSTER) == {
rec["id"]: "valid"
}
INVALID_RECEIPTS = {
"changed-after-signing": lambda: dict(
sealed(receipt(NODES)), at="2026-10-11T12:00:01Z"
),
"wrong-id": lambda: dict(sealed(receipt(NODES)), id="aaaaaaaaaaaaa"),
"wrong-root": lambda: dict(sealed(receipt(NODES)), root="00" * 32),
"no-root": lambda: {k: v for k, v in sealed(receipt(NODES)).items() if k != "root"},
"signer-not-in-roster": lambda: sealed(receipt(NODES, by="zed")),
"signed-by-another-key": lambda: sealed(receipt(NODES, by="ana"), signer="ben"),
"no-time": lambda: sealed({k: v for k, v in receipt(NODES).items() if k != "at"}),
"time-not-comparable": lambda: sealed(receipt(NODES, at=5)),
"no-signer": lambda: sealed(
{k: v for k, v in receipt(NODES).items() if k != "by"}, signer="ana"
),
"before-registration": lambda: sealed(receipt(NODES, at="2026-08-01T00:00:00Z")),
"after-key-revocation": lambda: sealed(
receipt(NODES, by="ben", at="2026-10-20T00:00:00Z")
),
}
@pytest.mark.parametrize("name", INVALID_RECEIPTS)
def test_receipts_that_break_a_condition_are_invalid(name):
roster = {**ROSTER, "ben": roster_key("ben", revoked_at="2026-10-15T00:00:00Z")}
assert status_of(INVALID_RECEIPTS[name](), roster=roster) == "invalid"
def test_a_receipt_signed_before_its_key_was_revoked_stays_valid():
roster = {**ROSTER, "ben": roster_key("ben", revoked_at="2026-10-15T00:00:00Z")}
rec = sealed(receipt(NODES, by="ben", at="2026-10-14T00:00:00Z"))
assert status_of(rec, roster=roster) == "valid"
def test_a_receipt_is_revoked_by_a_valid_revocation_and_not_by_a_forged_one():
rec = sealed(receipt(NODES))
assert status_of(rec, [rec, revocation("ana", receipt=rec["id"])]) == "revoked"
forged = dict(revocation("ana", receipt=rec["id"]), reason="Changed.")
assert status_of(rec, [rec, forged]) == "valid"
assert status_of(rec, [rec, revocation("cara", receipt=rec["id"])]) == "valid"
def test_a_receipt_is_revoked_by_a_revocation_of_its_signer_over_a_period():
rec = sealed(receipt(NODES, by="ben"))
period = {"from": "2026-10-11T00:00:00Z", "to": "2026-10-12T00:00:00Z"}
covering = revocation("ben", signer="ben", period=period)
assert status_of(rec, [rec, covering]) == "revoked"
elsewhere = revocation(
"ben",
signer="ben",
period={"from": "2026-11-01T00:00:00Z", "to": "2026-11-02T00:00:00Z"},
)
assert status_of(rec, [rec, elsewhere]) == "valid"
def test_the_revocation_of_a_revocation_signer_key_is_not_a_revocation_of_receipts():
rec = sealed(receipt(NODES, by="ben"))
bare = revocation("ben", signer="ben")
assert status_of(rec, [rec, bare]) == "valid"
def qa_receipt(of, by, found_errors, at):
"""A receipt that records a spot-check of the receipt `of`; `found_errors` is a list of node IDs."""
qa = {"of": of["id"], "errors": [{"node": n} for n in found_errors]}
return sealed(
receipt(NODES[:2], by=by, at=at, level="F1", scope="qa:" + of["id"], qa=qa)
)
def test_a_spot_check_that_found_an_error_suspends_the_receipt_it_checked():
original = sealed(receipt(NODES))
check = qa_receipt(original, "ben", ["nodea"], "2026-10-12T09:00:00Z")
status = rcp.statuses([original, check], ROSTER)
assert status == {original["id"]: "suspended", check["id"]: "valid"}
def test_a_spot_check_that_found_nothing_suspends_nothing():
original = sealed(receipt(NODES))
check = qa_receipt(original, "ben", [], "2026-10-12T09:00:00Z")
assert rcp.statuses([original, check], ROSTER)[original["id"]] == "valid"
def test_a_spot_check_that_is_not_valid_suspends_nothing():
original = sealed(receipt(NODES))
stranger = qa_receipt(original, "zed", ["nodea"], "2026-10-12T09:00:00Z")
revoked_check = qa_receipt(original, "ben", ["nodea"], "2026-10-12T10:00:00Z")
records = [
original,
stranger,
revoked_check,
revocation("ana", receipt=revoked_check["id"]),
]
status = rcp.statuses(records, ROSTER)
assert status[original["id"]] == "valid"
assert status[stranger["id"]] == "invalid"
assert status[revoked_check["id"]] == "revoked"
def test_a_spot_check_of_a_receipt_that_is_not_there_suspends_nothing():
original = sealed(receipt(NODES))
check = qa_receipt(original, "ben", ["nodea"], "2026-10-12T09:00:00Z")
assert rcp.statuses([check], ROSTER) == {check["id"]: "valid"}
@pytest.mark.parametrize("qa", ["checked", None, ["errors"], 3], ids=repr)
def test_a_receipt_whose_qa_is_not_an_object_is_an_ordinary_receipt(qa):
rec = sealed(receipt(NODES, qa=qa))
assert status_of(rec) == "valid"
def test_chains_of_spot_checks_alternate_from_the_last_unchecked_one():
chain = [sealed(receipt(NODES))]
for i in range(7):
chain.append(
qa_receipt(chain[-1], "ben", ["nodea"], f"2026-10-12T09:{i:02d}:00Z")
)
status = rcp.statuses(chain, ROSTER)
expected = ["valid", "suspended"] * 4
assert [status[r["id"]] for r in reversed(chain)] == expected[:8]
def test_two_spot_checks_of_one_receipt_suspend_it_if_either_is_valid():
original = sealed(receipt(NODES))
first = qa_receipt(original, "ben", ["nodea"], "2026-10-12T09:00:00Z")
second = qa_receipt(original, "ana", ["nodeb"], "2026-10-12T10:00:00Z")
both = rcp.statuses([original, first, second], ROSTER)
assert both[original["id"]] == "suspended"
third = qa_receipt(first, "ana", ["nodea"], "2026-10-12T11:00:00Z")
fourth = qa_receipt(second, "ben", ["nodeb"], "2026-10-12T12:00:00Z")
nested = rcp.statuses([original, first, second, third, fourth], ROSTER)
assert nested[first["id"]] == "suspended"
assert nested[second["id"]] == "suspended"
assert nested[original["id"]] == "valid"
# --- carried hashes and levels ----------------------------------------------------------------------------
def values_of(**hashes):
"""Node values holding only the `node_hash` of each node."""
return {nid: {"node_hash": h} for nid, h in hashes.items()}
def emend(target, before, after, **extra):
"""A correction that changes `target` from the hash `before` to `after`."""
return {"op": "emend", "target": target, "before": before, "after": after, **extra}
def test_carried_hashes_without_corrections_are_the_current_ones():
assert rcp.carried_hashes(values_of(a="h1", b="h2"), []) == {
"a": {"h1"},
"b": {"h2"},
}
def test_carried_hashes_follow_a_chain_of_corrections_that_keep_the_level():
corrections = [emend("a", "h0", "h1"), emend("a", "h1", "h2")]
assert rcp.carried_hashes(values_of(a="h2"), corrections) == {
"a": {"h2", "h1", "h0"}
}
def test_relink_and_resolve_keep_the_level_like_emend():
corrections = [
{"op": "resolve", "target": "a", "before": "h0", "after": "h1"},
{"op": "relink", "target": "a", "before": "h1", "after": "h2"},
]
assert rcp.carried_hashes(values_of(a="h2"), corrections)["a"] == {"h2", "h1", "h0"}
@pytest.mark.parametrize(
"breaker",
[
{"op": "replace", "target": "a", "before": "h1", "after": "h2"},
{"op": "merge", "target": "z", "touched": ["a"], "before": "x", "after": "y"},
{"op": "split", "target": "z", "path": ["a"], "before": "x", "after": "y"},
{"op": "delete", "target": "z", "to_path": ["a"], "before": "x", "after": "y"},
{"op": "insert", "target": "z", "created": ["a"], "before": "x", "after": "y"},
{"op": "merge", "target": "z", "retired": ["a"], "before": "x", "after": "y"},
],
ids=["replace", "touched", "path", "to-path", "created", "retired"],
)
def test_a_correction_that_does_not_keep_the_level_ends_the_chain(breaker):
corrections = [emend("a", "h0", "h1"), breaker]
assert rcp.carried_hashes(values_of(a="h2"), corrections) == {"a": {"h2"}}
@pytest.mark.parametrize(
"link",
[
emend("a", "h0", "other"),
{"op": "emend", "target": "a", "after": "h2"},
{"op": "emend", "target": "a", "before": "", "after": "h2"},
emend("z", "h0", "h2", touched=["a"]),
],
ids=["after-differs", "no-before", "empty-before", "targets-another-node"],
)
def test_a_link_that_does_not_lead_to_the_hash_reached_ends_the_chain(link):
assert rcp.carried_hashes(values_of(a="h2"), [link]) == {"a": {"h2"}}
def test_corrections_of_nodes_without_values_are_ignored():
corrections = [
emend("gone", "h0", "h1"),
{"op": "delete", "target": "gone", "path": None},
]
assert rcp.carried_hashes(values_of(a="h2"), corrections) == {"a": {"h2"}}
def test_a_chain_of_one_node_is_independent_of_the_others():
corrections = [
emend("a", "h0", "h1"),
emend("b", "k0", "k1"),
emend("a", "h1", "h2"),
]
carried = rcp.carried_hashes(values_of(a="h2", b="k1"), corrections)
assert carried == {"a": {"h2", "h1", "h0"}, "b": {"k1", "k0"}}
NODES_AT = [
{"id": "nodea", "fidelity": "F1"},
{"id": "nodeb", "fidelity": "F2"},
{"id": "nodec"},
]
VALUES = values_of(nodea="aa" * 32, nodeb="bb" * 32, nodec="cc" * 32)
def levels(records, corrections=(), values=VALUES, roster=ROSTER):
"""The effective levels of the three nodes of `NODES_AT`."""
return rcp.effective_levels(NODES_AT, values, records, roster, corrections)
def test_without_receipts_a_leaf_keeps_its_recorded_level_and_other_nodes_have_none():
assert levels([]) == {"nodea": "F1", "nodeb": "F2"}
def test_a_valid_receipt_at_the_current_hash_raises_the_level():
rec = sealed(receipt([("nodea", "aa" * 32), ("nodeb", "bb" * 32)], level="F3"))
assert levels([rec]) == {"nodea": "F3", "nodeb": "F3"}
def test_a_receipt_never_lowers_a_level_and_ignores_nodes_without_one():
rec = sealed(
receipt(
[("nodea", "aa" * 32), ("nodeb", "bb" * 32), ("nodec", "cc" * 32)],
level="F1",
)
)
assert levels([rec]) == {"nodea": "F1", "nodeb": "F2"}
def test_a_receipt_for_an_old_hash_raises_nothing():
rec = sealed(receipt([("nodea", "00" * 32)], level="F3"))
assert levels([rec]) == {"nodea": "F1", "nodeb": "F2"}
def test_a_receipt_for_an_emended_hash_still_counts():
rec = sealed(receipt([("nodea", "00" * 32)], level="F3"))
kept = [emend("nodea", "00" * 32, "aa" * 32)]
replaced = [
{"op": "replace", "target": "nodea", "before": "00" * 32, "after": "aa" * 32}
]
assert levels([rec], kept)["nodea"] == "F3"
assert levels([rec], replaced)["nodea"] == "F1"
def test_receipts_that_are_not_valid_raise_nothing():
good = receipt([("nodea", "aa" * 32)], level="F3")
tampered = dict(sealed(good), at="2026-10-11T12:00:01Z")
stranger = sealed(dict(good, by="zed"))
original = sealed(good)
revoked = [original, revocation("ana", receipt=original["id"])]
for records in ([tampered], [stranger], revoked):
assert levels(records)["nodea"] == "F1"
def test_a_suspended_receipt_raises_nothing():
original = sealed(receipt([("nodea", "aa" * 32)], level="F3"))
check = qa_receipt(original, "ben", ["nodeb"], "2026-10-12T09:00:00Z")
assert levels([original, check])["nodea"] == "F1"
def test_a_spot_check_does_not_raise_the_nodes_it_found_in_error():
original = sealed(receipt(NODES))
found = {"of": original["id"], "errors": [{"node": "nodea"}]}
check = sealed(
receipt(
[("nodea", "aa" * 32), ("nodeb", "bb" * 32)],
by="ben",
at="2026-10-12T09:00:00Z",
scope="qa:" + original["id"],
qa=found,
)
)
assert levels([original, check]) == {"nodea": "F1", "nodeb": "F3"}
def test_revocations_among_the_records_are_not_read_as_receipts():
original = sealed(receipt([("nodea", "aa" * 32)], level="F2"))
assert levels([original, revocation("ana", receipt="x")])["nodea"] == "F2"
def test_the_main_examples_levels_recompute_the_distribution_it_reports():
root = FIXTURES / "packages" / HALE
state = package.read_state(str(root))
document = json.loads((root / "document.json").read_text(encoding="utf-8"))
effective = rcp.effective_levels(
state.nodes,
state.index().values,
fixture_receipts(),
fixture_roster(),
state.corrections,
)
assert rcp.distribution(effective) == document["fidelity"]
def test_distribution_counts_each_level_and_names_the_lowest():
assert rcp.distribution({"a": "F2", "b": "F3", "c": "F2"}) == {
"lowest": "F2",
"counts": {"F0": 0, "F1": 0, "F2": 2, "F3": 1},
}
def test_the_distribution_of_nothing_has_no_lowest_level():
assert rcp.distribution({}) == {
"lowest": None,
"counts": {"F0": 0, "F1": 0, "F2": 0, "F3": 0},
}