From e8a346c852ef02e416d904cdc2cbd4e553f70231 Mon Sep 17 00:00:00 2001 From: Giacomo Pasini Date: Tue, 3 Jun 2025 10:42:46 +0200 Subject: [PATCH] Fix LIB calculations with short chain Fix LIB calculation where the chain is shorter than K and add a regression test for this case --- cryptarchia/cryptarchia.py | 2 +- cryptarchia/test_fork_choice.py | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/cryptarchia/cryptarchia.py b/cryptarchia/cryptarchia.py index a46ce89..2e1d5bc 100644 --- a/cryptarchia/cryptarchia.py +++ b/cryptarchia/cryptarchia.py @@ -401,7 +401,7 @@ class Follower: return # prune forks that do not descend from the last immutable block, this is needed to avoid Genesis rule to roll back # past the LIB - self.lib = next(islice(iter_chain(self.local_chain, self.ledger_state), self.config.k, None), self.local_chain).block.id() + self.lib = next(islice(iter_chain(self.local_chain, self.ledger_state), self.config.k, None), self.genesis_state).block.id() self.forks = [ f for f in self.forks if is_ancestor(self.lib, f, self.ledger_state) ] diff --git a/cryptarchia/test_fork_choice.py b/cryptarchia/test_fork_choice.py index c850f78..06e5c74 100644 --- a/cryptarchia/test_fork_choice.py +++ b/cryptarchia/test_fork_choice.py @@ -373,4 +373,27 @@ class TestForkChoice(TestCase): follower.on_block(b12) assert follower.tip_id() == b12.id() - assert follower.lib == b7.id(), follower.lib \ No newline at end of file + assert follower.lib == b7.id(), follower.lib + + def test_lib_calc_short_chain(self): + # Test that the LIB is correctly calculated for a short chain + n_a = Note(sk=0, value=10) + notes = [n_a] + config = mk_config(notes) + config.k = 10 + genesis = mk_genesis_state(notes) + follower = Follower(genesis, config) + follower.to_online() + + assert follower.lib == genesis.block.id(), follower.lib + blocks = [genesis.block] + for i in range(1, 11): + b = mk_block(blocks[-1], i, n_a) + blocks.append(b) + follower.on_block(b) + assert follower.lib == genesis.block.id(), follower.lib + + b11 = mk_block(blocks[-1], 11, n_a) + follower.on_block(b11) + + assert follower.lib == blocks[1].id(), follower.lib