@@ -155,27 +155,59 @@ def shut_down(self) -> None:
155
155
self ._shut_down = True
156
156
self .pool .shutdown (wait = True )
157
157
158
- async def _load_chain_from_store (self ) -> None :
158
+ def _initialize_caches (self ) -> None :
159
159
"""
160
- Initializes the state of the Blockchain class from the database .
160
+ Initialize the blockchain cache data structures .
161
161
"""
162
162
self .__block_records = {}
163
163
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 (
165
171
self .constants .BLOCKS_CACHE_SIZE
166
172
)
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
+ """
167
178
for block in block_records .values ():
168
179
self .add_block_record (block )
169
180
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
+ """
170
186
if len (block_records ) == 0 :
171
187
assert peak is None
172
188
self ._peak_height = None
173
189
return
174
190
175
191
assert peak is not None
176
192
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 ()
179
211
180
212
def get_peak (self ) -> Optional [BlockRecord ]:
181
213
"""
0 commit comments