Skip to content

Commit

Permalink
feat: Implement Finalize stage in Play-Grandpa-Round. (#750)
Browse files Browse the repository at this point in the history
# Description

- Implemented Finalize stage in Play-Grandpa-Round
- Added callback to GrandpaRound, that should be included in the
attemptToFinalize method implementation


Fixes #729

---------

Co-authored-by: Hristiyan Mitov <[email protected]>
  • Loading branch information
hMitov and Hristiyan Mitov authored Feb 7, 2025
1 parent bc0e0e0 commit bd77340
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
40 changes: 39 additions & 1 deletion src/main/java/com/limechain/grandpa/round/FinalizeStage.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,51 @@
package com.limechain.grandpa.round;

import com.limechain.exception.grandpa.GrandpaGenericException;
import com.limechain.network.protocol.warp.dto.BlockHeader;
import lombok.extern.java.Log;

@Log
public class FinalizeStage implements StageState {

@Override
public void start(GrandpaRound round) {

log.fine(String.format("Round %d entered the Finalize stage.", round.getRoundNumber()));

if (isRoundReadyToBeFinalized(round)) {
end(round);
return;
}

round.setOnFinalizeHandler(() -> {
if (isRoundReadyToBeFinalized(round)) {
end(round);
}
});
}

@Override
public void end(GrandpaRound round) {
log.info(String.format("Round %d met finalization conditions and will be finalized.", round.getRoundNumber()));
round.setOnFinalizeHandler(null);
round.attemptToFinalizeAt();
log.fine(String.format("Round %d exits Finalize stage.", round.getRoundNumber()));

round.end();
}
}

private boolean isRoundReadyToBeFinalized(GrandpaRound round) {
BlockHeader finalized;
try {
finalized = round.getFinalizedBlock();
} catch (GrandpaGenericException e) {
log.warning("Finalized block not found, round cannot be finalized.");
return false;
}

BlockHeader prevBestFinalCandidate = round.getPrevBestFinalCandidate();

return prevBestFinalCandidate != null
&& finalized.getBlockNumber().compareTo(prevBestFinalCandidate.getBlockNumber()) >= 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public BlockHeader getBestFinalCandidate() {
return Optional.ofNullable(finalizeEstimate).orElse(lastFinalizedBlock);
}

private void attemptToFinalizeAt() {
public void attemptToFinalizeAt() {

BlockState blockState = stateManager.getBlockState();
BigInteger lastFinalizedBlockNumber = blockState.getHighestFinalizedNumber();
Expand Down

0 comments on commit bd77340

Please sign in to comment.