Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

Commit 99e22a5

Browse files
committed
Fix race condition in updateBlockTotDifficulties
A tricky and rare case when fork block is imported with fixed TD and undeservedly became a canonical chain block. When that has happened there is no chance to re-branch back to canonical chain.
1 parent e6a5dd6 commit 99e22a5

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,8 +1092,37 @@ public void updateBlockTotDifficulties(long startFrom) {
10921092
while(true) {
10931093
synchronized (this) {
10941094
((IndexedBlockStore) blockStore).updateTotDifficulties(startFrom);
1095+
10951096
if (startFrom == bestBlock.getNumber()) {
10961097
totalDifficulty = blockStore.getTotalDifficultyForHash(bestBlock.getHash());
1098+
}
1099+
1100+
if (startFrom == blockStore.getMaxNumber()) {
1101+
Block bestStoredBlock = bestBlock;
1102+
BigInteger maxTD = totalDifficulty;
1103+
1104+
// traverse blocks toward max known number to get the best block
1105+
for (long num = bestBlock.getNumber() + 1; num <= blockStore.getMaxNumber(); num++) {
1106+
List<Block> blocks = ((IndexedBlockStore) blockStore).getBlocksByNumber(num);
1107+
for (Block block : blocks) {
1108+
BigInteger td = blockStore.getTotalDifficultyForHash(block.getHash());
1109+
if (maxTD.compareTo(td) < 0) {
1110+
maxTD = td;
1111+
bestStoredBlock = block;
1112+
}
1113+
}
1114+
}
1115+
1116+
if (totalDifficulty.compareTo(maxTD) < 0) {
1117+
blockStore.reBranch(bestStoredBlock);
1118+
bestBlock = bestStoredBlock;
1119+
totalDifficulty = maxTD;
1120+
repository = repository.getSnapshotTo(bestBlock.getStateRoot());
1121+
1122+
logger.info("totDifficulties update: re-branch to block {}, totalDifficulty {}",
1123+
bestBlock.getHeader().getShortDescr(), totalDifficulty);
1124+
}
1125+
10971126
break;
10981127
}
10991128
startFrom++;

0 commit comments

Comments
 (0)