```python
def handle_block(new_block):
if not is_new_head(new_block):
return
set_head(new_block)
if --casper-fork-choice is on:
check_and_finalize_new_checkpoint(new_block)
def is_new_head(new_block):
if --casper-fork-choice is off
return new_block.total_difficuty > current_head.total_difficulty
if new_block is in --exclude list or one of its descendants
return false
# don't revert finalized blocks
if db.last_finalized_block is not in new_block.ancestors:
return false
return highest_justified_epoch(new_block) * 10**40 + new_block.total_difficuty >
highest_justified_epoch(current_head) * 10**40 + current_head.total_difficulty
def highest_justified_epoch(block):
casper = block.post_state.casper_contract
return casper.highest_justified_epoch(NON_REVERT_MIN_DEPOSITS)
def check_and_finalize_new_checkpoint(new_block):
casper = new_block.post_state.casper_contract
# If no finalized blocks, db.last_finalized_epoch initialized to -1
finalized_epoch = casper.highest_finalized_epoch(NON_REVERT_MIN_DEPOSITS)
if finalized_epoch > db.last_finalized_epoch:
finalized_hash = casper.checkpoint_hashes(finalized_epoch)
# ensure not trivially finalized
if finalized_hash == b'\x00' * 32:
return
db.last_finalized_epoch = finalized_epoch
db.last_finalized_block = finalized_hash
```