@@ -254,18 +254,42 @@ def _set_as_canonical_chain_head(
254
254
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
255
255
are no longer in the canonical chain
256
256
"""
257
- # performance optimization, short circuit if we're just adding a single header
258
257
try :
259
258
current_canonical_head = cls ._get_canonical_head_hash (db )
260
259
except CanonicalHeadNotFound :
261
260
current_canonical_head = None
261
+
262
+ new_canonical_headers : Tuple [BlockHeaderAPI , ...]
263
+ old_canonical_headers : Tuple [BlockHeaderAPI , ...]
264
+
262
265
if current_canonical_head and header .parent_hash == current_canonical_head :
263
- cls ._add_block_number_to_hash_lookup (db , header )
264
- db .set (SchemaV1 .make_canonical_head_hash_lookup_key (), header .hash )
265
- return (header ,), tuple ()
266
+ # the calls to _find_new_ancestors and _decanonicalize_old_headers are
267
+ # relatively expensive, it's better to skip them in this case, where we're
268
+ # extending the canonical chain by a header
269
+ new_canonical_headers = (header ,)
270
+ old_canonical_headers = ()
271
+ else :
272
+ new_canonical_headers = cast (
273
+ Tuple [BlockHeaderAPI , ...],
274
+ tuple (reversed (cls ._find_new_ancestors (db , header , genesis_parent_hash )))
275
+ )
276
+ old_canonical_headers = cls ._decanonicalize_old_headers (
277
+ db , new_canonical_headers
278
+ )
279
+
280
+ for h in new_canonical_headers :
281
+ cls ._add_block_number_to_hash_lookup (db , h )
282
+
283
+ db .set (SchemaV1 .make_canonical_head_hash_lookup_key (), header .hash )
266
284
267
- new_canonical_headers = tuple (reversed (
268
- cls ._find_new_ancestors (db , header , genesis_parent_hash )))
285
+ return new_canonical_headers , old_canonical_headers
286
+
287
+ @classmethod
288
+ def _decanonicalize_old_headers (
289
+ cls ,
290
+ db : DatabaseAPI ,
291
+ new_canonical_headers : Tuple [BlockHeaderAPI , ...]
292
+ ) -> Tuple [BlockHeaderAPI , ...]:
269
293
old_canonical_headers = []
270
294
271
295
for h in new_canonical_headers :
@@ -278,12 +302,7 @@ def _set_as_canonical_chain_head(
278
302
old_canonical_header = cls ._get_block_header_by_hash (db , old_canonical_hash )
279
303
old_canonical_headers .append (old_canonical_header )
280
304
281
- for h in new_canonical_headers :
282
- cls ._add_block_number_to_hash_lookup (db , h )
283
-
284
- db .set (SchemaV1 .make_canonical_head_hash_lookup_key (), header .hash )
285
-
286
- return new_canonical_headers , tuple (old_canonical_headers )
305
+ return tuple (old_canonical_headers )
287
306
288
307
@classmethod
289
308
@to_tuple
0 commit comments