Skip to content

Commit cb00c5b

Browse files
committed
Factor _load_chain_from_store into pieces
1 parent be85a0b commit cb00c5b

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

chia/consensus/blockchain.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,27 +155,59 @@ def shut_down(self) -> None:
155155
self._shut_down = True
156156
self.pool.shutdown(wait=True)
157157

158-
async def _load_chain_from_store(self) -> None:
158+
def _initialize_caches(self) -> None:
159159
"""
160-
Initializes the state of the Blockchain class from the database.
160+
Initialize the blockchain cache data structures.
161161
"""
162162
self.__block_records = {}
163163
self.__heights_in_cache = {}
164-
block_records, peak = await self.consensus_store.get_block_records_close_to_peak(
164+
165+
async def _load_recent_blocks_from_store(self) -> tuple[dict[bytes32, BlockRecord], Optional[bytes32]]:
166+
"""
167+
Load recent blocks from the consensus store.
168+
Returns block records and peak hash.
169+
"""
170+
return await self.consensus_store.get_block_records_close_to_peak(
165171
self.constants.BLOCKS_CACHE_SIZE
166172
)
173+
174+
def _populate_cache_with_blocks(self, block_records: dict[bytes32, BlockRecord]) -> None:
175+
"""
176+
Add the loaded block records to the cache.
177+
"""
167178
for block in block_records.values():
168179
self.add_block_record(block)
169180

181+
def _set_peak_height_from_blocks(self, block_records: dict[bytes32, BlockRecord], peak: Optional[bytes32]) -> None:
182+
"""
183+
Set the peak height based on loaded blocks.
184+
Handles the case where no blocks are loaded (empty blockchain).
185+
"""
170186
if len(block_records) == 0:
171187
assert peak is None
172188
self._peak_height = None
173189
return
174190

175191
assert peak is not None
176192
self._peak_height = self.block_record(peak).height
177-
assert self.consensus_store.contains_height(self._peak_height)
178-
assert not self.consensus_store.contains_height(uint32(self._peak_height + 1))
193+
194+
def _validate_blockchain_state(self) -> None:
195+
"""
196+
Validate the loaded blockchain state for consistency.
197+
"""
198+
if self._peak_height is not None:
199+
assert self.consensus_store.contains_height(self._peak_height)
200+
assert not self.consensus_store.contains_height(uint32(self._peak_height + 1))
201+
202+
async def _load_chain_from_store(self) -> None:
203+
"""
204+
Initializes the state of the Blockchain class from the database.
205+
"""
206+
self._initialize_caches()
207+
block_records, peak = await self._load_recent_blocks_from_store()
208+
self._populate_cache_with_blocks(block_records)
209+
self._set_peak_height_from_blocks(block_records, peak)
210+
self._validate_blockchain_state()
179211

180212
def get_peak(self) -> Optional[BlockRecord]:
181213
"""

0 commit comments

Comments
 (0)