Skip to content

Commit

Permalink
After merge add a rule to check that the current block is more recent…
Browse files Browse the repository at this point in the history
… than its parent (hyperledger#4066)

* After merge add a rule to check that the current block is more recent than its parent

Signed-off-by: Fabio Di Fabio <fabio.difabio@consensys.net>

* Update CHANGELOG

Signed-off-by: Fabio Di Fabio <fabio.difabio@consensys.net>

* Unit test

Signed-off-by: Fabio Di Fabio <fabio.difabio@consensys.net>
  • Loading branch information
fab-10 authored and eum602 committed Nov 3, 2023
1 parent 60b52d7 commit 1488e9d
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 5 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
### Additions and Improvements

### Bug Fixes
- Return the correct latest valid hash in case of bad block when calling engine methods [#4056](https://github.com/hyperledger/besu/pull/4056)
- Add a PoS block header rule to check that the current block is more recent than its parent [#4066](https://github.com/hyperledger/besu/pull/4066)
- Fixed a trie log layer issue on bonsai during reorg [#4069](https://github.com/hyperledger/besu/pull/4069)

## 22.7.0-RC1
Expand All @@ -22,7 +24,6 @@
- Support free gas networks in the London fee market [#4003](https://github.com/hyperledger/besu/pull/4003)
- Limit the size of outgoing eth subprotocol messages. [#4034](https://github.com/hyperledger/besu/pull/4034)
- Fixed a state root mismatch issue on bonsai that may appear occasionally [#4041](https://github.com/hyperledger/besu/pull/4041)
- Return the correct latest valid hash in case of bad block when calling engine methods [#4056](https://github.com/hyperledger/besu/pull/4056)

### Download links
- https://hyperledger.jfrog.io/artifactory/besu-binaries/besu/22.7.0-RC1/besu-22.7.0-RC1.tar.gz / sha256: `60ad8b53402beb62c24ad791799d9cfe444623a58f6f6cf1d0728459cb641e63`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package org.hyperledger.besu.consensus.merge;

import org.hyperledger.besu.consensus.merge.headervalidationrules.ConstantOmmersHashRule;
import org.hyperledger.besu.consensus.merge.headervalidationrules.IncrementalTimestampRule;
import org.hyperledger.besu.consensus.merge.headervalidationrules.MergeUnfinalizedValidationRule;
import org.hyperledger.besu.consensus.merge.headervalidationrules.NoDifficultyRule;
import org.hyperledger.besu.consensus.merge.headervalidationrules.NoNonceRule;
Expand Down Expand Up @@ -59,7 +60,8 @@ public static BlockHeaderValidator.Builder mergeBlockHeaderValidator(final FeeMa
.addRule(new MergeUnfinalizedValidationRule())
.addRule(new ConstantOmmersHashRule())
.addRule(new NoNonceRule())
.addRule(new NoDifficultyRule());
.addRule(new NoDifficultyRule())
.addRule(new IncrementalTimestampRule());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright Hyperledger Besu Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.hyperledger.besu.consensus.merge.headervalidationrules;

import static org.hyperledger.besu.consensus.merge.TransitionUtils.isTerminalProofOfWorkBlock;

import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.BlockHeader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IncrementalTimestampRule extends MergeConsensusRule {

private static final Logger LOG = LoggerFactory.getLogger(IncrementalTimestampRule.class);

@Override
public boolean validate(
final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext) {

if (super.shouldUsePostMergeRules(header, protocolContext)
&& !isTerminalProofOfWorkBlock(header, protocolContext)) {
final long blockTimestamp = header.getTimestamp();
final long parentTimestamp = parent.getTimestamp();
final boolean isMoreRecent = blockTimestamp > parentTimestamp;

LOG.trace(
"Is block timestamp more recent that its parent? {}, [block timestamp {}, parent timestamp {}]",
isMoreRecent,
blockTimestamp,
parentTimestamp);

return isMoreRecent;
} else {
return true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ protected boolean shouldUsePostMergeRules(
if (parentChainTotalDifficulty
.get()
.add(header.getDifficulty() == null ? Difficulty.ZERO : header.getDifficulty())
.greaterThan(configuredTotalTerminalDifficulty)) {
.greaterOrEqualThan(configuredTotalTerminalDifficulty)) {
return true;
} else { // still PoWing
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ private List<Block> subChain(
0,
15000000))
.gasLimit(newParent.getGasLimit())
.timestamp(newParent.getTimestamp() + 1)
.stateRoot(newParent.getStateRoot());
if (each.greaterOrEqualThan(Difficulty.ZERO)) {
headerGenerator.difficulty(each);
Expand All @@ -194,6 +195,7 @@ private BlockHeader terminalPowBlock(final BlockHeader parent, final Difficulty
0,
15000000l))
.gasLimit(parent.getGasLimit())
.timestamp(parent.getTimestamp() + 1)
.stateRoot(parent.getStateRoot())
.buildHeader();
return terminal;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright Hyperledger Besu Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.hyperledger.besu.consensus.merge.headervalidationrules;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.hyperledger.besu.consensus.merge.MergeContext;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;

import java.util.Optional;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class IncrementalTimestampValidationTest {

@Mock private ProtocolContext protocolContext;
@Mock private MutableBlockchain blockchain;
@Mock private MergeContext mergeContext;

@Before
public void setUp() {
when(blockchain.getTotalDifficultyByHash(any())).thenReturn(Optional.of(Difficulty.ONE));
when(protocolContext.getBlockchain()).thenReturn(blockchain);
when(mergeContext.getTerminalTotalDifficulty()).thenReturn(Difficulty.ZERO);
when(protocolContext.getConsensusContext(MergeContext.class)).thenReturn(mergeContext);
}

@Test
public void validWhenTimestampMoreRecentThanParent() {
final IncrementalTimestampRule rule = new IncrementalTimestampRule();
final long now = System.currentTimeMillis();
final BlockHeader parentHeader = mock(BlockHeader.class);
when(parentHeader.getTimestamp()).thenReturn(now);
final BlockHeader validHeader = mock(BlockHeader.class);
when(validHeader.getNumber()).thenReturn(1337L);
when(validHeader.getTimestamp()).thenReturn(now + 1);

assertThat(rule.validate(validHeader, parentHeader, protocolContext)).isTrue();
}

@Test
public void invalidWhenTimestampNotMoreRecentThanParent() {
final IncrementalTimestampRule rule = new IncrementalTimestampRule();
final long now = System.currentTimeMillis();
final BlockHeader parentHeader = mock(BlockHeader.class);
when(parentHeader.getTimestamp()).thenReturn(now);
final BlockHeader validHeader = mock(BlockHeader.class);
when(validHeader.getNumber()).thenReturn(1337L);
when(validHeader.getTimestamp()).thenReturn(now);

assertThat(rule.validate(validHeader, parentHeader, protocolContext)).isFalse();
}

@Test
public void alwaysValidWhenTTDNotReached() {
when(mergeContext.getTerminalTotalDifficulty()).thenReturn(Difficulty.of(2L));

final IncrementalTimestampRule rule = new IncrementalTimestampRule();
final BlockHeader parentHeader = mock(BlockHeader.class);
final BlockHeader validHeader = mock(BlockHeader.class);
when(validHeader.getNumber()).thenReturn(1337L);

assertThat(rule.validate(validHeader, parentHeader, protocolContext)).isTrue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -261,11 +261,10 @@ protected Void saveBlock(final Block block) {
getBackwardChain().addBadChainToManager(badBlocksManager, block.getHash());
throw new BackwardSyncException(
"Cannot save block "
+ block.getHash()
+ block.toLogString()
+ " because of "
+ optResult.errorMessage.orElseThrow());
}
optResult.blockProcessingOutputs.ifPresent(result -> {});

return null;
}
Expand Down

0 comments on commit 1488e9d

Please sign in to comment.