nomos-specs/cryptarchia/test_leader.py
davidrusu d2f6ad579a
Stake Relativization Specification + Fixes (#86)
* cryptarchia/relative-stake: failing test showing lack of inference

* implement stake-relativization spec

* test total stake inference in empty epoch

* move TestNode to test_common

* fix bug in Follower re-org logic

* improve orphan proof test coverage

* force orphans to already have been in one of the existing branches

* rename initial_inferred_total_stake ==> initial_total_stake

* add simple orphan import test

* Follower.unimported_orphans: ensure no orphans from same branch

* remove unnecessary LedgerState.slot

* cryptarchia: doc fixes

* factor out total stake inference

* docs for total stake inference

* rename total_stake to total_active_stake

* replace prints in cryptarchia with logging.logger
2024-03-23 05:50:00 +04:00

53 lines
1.5 KiB
Python

from unittest import TestCase
import numpy as np
from .cryptarchia import (
Leader,
Config,
EpochState,
LedgerState,
Coin,
phi,
TimeConfig,
Slot,
)
from .test_common import mk_config
class TestLeader(TestCase):
def test_slot_leader_statistics(self):
epoch = EpochState(
stake_distribution_snapshot=LedgerState(),
nonce_snapshot=LedgerState(nonce=b"1010101010"),
inferred_total_active_stake=1000,
)
coin = Coin(sk=0, value=10)
f = 0.05
l = Leader(
config=mk_config([coin]).replace(active_slot_coeff=f),
coin=coin,
)
# We'll use the Margin of Error equation to decide how many samples we need.
# https://en.wikipedia.org/wiki/Margin_of_error
margin_of_error = 1e-4
p = phi(f=f, alpha=10 / epoch.total_active_stake())
std = np.sqrt(p * (1 - p))
Z = 3 # we want 3 std from the mean to be within the margin of error
N = int((Z * std / margin_of_error) ** 2)
# After N slots, the measured leader rate should be within the
# interval `p +- margin_of_error` with high probabiltiy
leader_rate = (
sum(
l.try_prove_slot_leader(epoch, Slot(slot), bytes(32)) is not None
for slot in range(N)
)
/ N
)
assert (
abs(leader_rate - p) < margin_of_error
), f"{leader_rate} != {p}, err={abs(leader_rate - p)} > {margin_of_error}"