nomos-specs/cryptarchia/test_leader.py
davidrusu 2d3f463bb7
cryptarchia: Update epoch stabilization schedule to 334 (from 433) (#79)
* feat(cryptarchia/epoch-schedule): switch to 334 schedule (from 433)

* factor out common test config building code

* feat(cryptarchia): test_leader uses common test config object

* cryptarchia: update test_ledger_state_is_properly_updated_on_reorg

* cryptarchia: update test_epoch_transition test

* move to .tip() in tests instead of tip_id()

* cryptarchia: wrap long comments

* cryptarchia: move mk_block to test_common

* cryptarchia: move mk_genesis_state to test_common

* cryptarchia: refactor fork test to use mk_chain

* cryptarchia: fork choice rules tests use mk_chain helper

* cryptarchia: rename fork choice test suite to TestForkChoice

* cryptarchia: config.s is always 3k/f or 3*base_period_length

* cryptarchia: hardcode epoch schedule in specification

* un-hard code epoch sched. params + provide a v0.0.1 spec for params
2024-03-09 17:34:08 +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(
total_stake=1000,
),
nonce_snapshot=LedgerState(nonce=b"1010101010"),
)
f = 0.05
l = Leader(
config=mk_config().replace(active_slot_coeff=f),
coin=Coin(sk=0, value=10),
)
# 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 / 1000)
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}"