Move bft block header creation/validation to common (#1708)

Aspects of the consensus mechanism associated with block creation, and validation have been moved
from the IBFT package, into into consensus/common, such that they can be reused for the QBFT
implementation.

Signed-off-by: Trent Mohay <trent.mohay@consensys.net>
This commit is contained in:
Trent Mohay
2021-01-05 15:36:39 +11:00
committed by GitHub
parent 318a77f5cf
commit 108efb8b0b
90 changed files with 800 additions and 814 deletions

View File

@@ -3,6 +3,7 @@ dependencies {
implementation project(':config')
implementation project(':consensus:clique')
implementation project(':consensus:ibft')
implementation project(':consensus:common')
implementation project(':crypto')
implementation project(':enclave')
implementation project(':ethereum:api')

View File

@@ -17,7 +17,7 @@ package org.hyperledger.besu.tests.acceptance.dsl.node.configuration.genesis;
import static java.util.stream.Collectors.toList;
import org.hyperledger.besu.consensus.clique.CliqueExtraData;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.tests.acceptance.dsl.node.RunnableNode;
@@ -49,8 +49,7 @@ public class GenesisConfigurationFactory {
public Optional<String> createIbft2GenesisConfig(
final Collection<? extends RunnableNode> validators, final String genesisFile) {
final String template = readGenesisFile(genesisFile);
return updateGenesisExtraData(
validators, template, IbftExtraData::createGenesisExtraDataString);
return updateGenesisExtraData(validators, template, BftExtraData::createGenesisExtraDataString);
}
public Optional<String> createIbft2GenesisConfigFilterBootnode(
@@ -61,14 +60,13 @@ public class GenesisConfigurationFactory {
.filter(node -> !node.getConfiguration().isBootnodeEligible())
.collect(toList());
return updateGenesisExtraData(
filteredList, template, IbftExtraData::createGenesisExtraDataString);
filteredList, template, BftExtraData::createGenesisExtraDataString);
}
public Optional<String> createPrivacyIbft2GenesisConfig(
final Collection<? extends RunnableNode> validators) {
final String template = readGenesisFile("/ibft/privacy-ibft.json");
return updateGenesisExtraData(
validators, template, IbftExtraData::createGenesisExtraDataString);
return updateGenesisExtraData(validators, template, BftExtraData::createGenesisExtraDataString);
}
private Optional<String> updateGenesisExtraData(

View File

@@ -20,7 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import org.hyperledger.besu.cli.DefaultCommandValues;
import org.hyperledger.besu.config.JsonGenesisConfigOptions;
import org.hyperledger.besu.config.JsonUtil;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.crypto.SECP256K1;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.Util;
@@ -217,7 +217,7 @@ class GenerateBlockchainConfig implements Runnable {
if (genesisConfigOptions.isIbft2()) {
LOG.info("Generating IBFT extra data.");
final String extraData =
IbftExtraData.fromAddresses(addressesForGenesisExtraData).encode().toString();
BftExtraData.fromAddresses(addressesForGenesisExtraData).encode().toString();
genesisConfig.put("extraData", extraData);
}
}

View File

@@ -14,7 +14,7 @@
*/
package org.hyperledger.besu.cli.subcommands.rlp;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.ethereum.core.Address;
import java.io.IOException;
@@ -39,9 +39,9 @@ public class IbftExtraDataCLIAdapter implements JSONToRLP {
return fromJsonAddresses(json).encode();
}
public static IbftExtraData fromJsonAddresses(final String jsonAddresses) throws IOException {
public static BftExtraData fromJsonAddresses(final String jsonAddresses) throws IOException {
final Collection<String> validatorAddresses = MAPPER.readValue(jsonAddresses, TYPE_REF);
return IbftExtraData.fromAddresses(
return BftExtraData.fromAddresses(
validatorAddresses.stream().map(Address::fromHexString).collect(Collectors.toList()));
}
}

View File

@@ -14,8 +14,8 @@
*/
package org.hyperledger.besu.controller;
import org.hyperledger.besu.config.BftConfigOptions;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.config.IbftConfigOptions;
import org.hyperledger.besu.config.IbftFork;
import org.hyperledger.besu.consensus.common.BftValidatorOverrides;
import org.hyperledger.besu.consensus.common.BlockInterface;
@@ -24,23 +24,23 @@ import org.hyperledger.besu.consensus.common.ForkingVoteTallyCache;
import org.hyperledger.besu.consensus.common.VoteProposer;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
import org.hyperledger.besu.consensus.common.VoteTallyUpdater;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.BftEventQueue;
import org.hyperledger.besu.consensus.common.bft.BftExecutors;
import org.hyperledger.besu.consensus.common.bft.BftProcessor;
import org.hyperledger.besu.consensus.common.bft.BftProtocolSchedule;
import org.hyperledger.besu.consensus.common.bft.BlockTimer;
import org.hyperledger.besu.consensus.common.bft.EthSynchronizerUpdater;
import org.hyperledger.besu.consensus.common.bft.EventMultiplexer;
import org.hyperledger.besu.consensus.common.bft.MessageTracker;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreatorFactory;
import org.hyperledger.besu.consensus.common.bft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.common.bft.statemachine.BftEventHandler;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.IbftGossip;
import org.hyperledger.besu.consensus.ibft.IbftProtocolSchedule;
import org.hyperledger.besu.consensus.ibft.UniqueMessageMulticaster;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreatorFactory;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftMiningCoordinator;
import org.hyperledger.besu.consensus.ibft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.ibft.jsonrpc.IbftJsonRpcMethods;
import org.hyperledger.besu.consensus.ibft.network.ValidatorPeers;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
@@ -83,13 +83,13 @@ public class IbftBesuControllerBuilder extends BesuControllerBuilder {
private static final Logger LOG = LogManager.getLogger();
private BftEventQueue bftEventQueue;
private IbftConfigOptions ibftConfig;
private BftConfigOptions ibftConfig;
private ValidatorPeers peers;
private final BlockInterface blockInterface = new IbftBlockInterface();
private final BlockInterface blockInterface = new BftBlockInterface();
@Override
protected void prepForBuild() {
ibftConfig = genesisConfig.getConfigOptions(genesisConfigOverrides).getIbft2ConfigOptions();
ibftConfig = genesisConfig.getConfigOptions(genesisConfigOverrides).getBftConfigOptions();
bftEventQueue = new BftEventQueue(ibftConfig.getMessageQueueLimit());
}
@@ -119,8 +119,8 @@ public class IbftBesuControllerBuilder extends BesuControllerBuilder {
final BftExecutors bftExecutors = BftExecutors.create(metricsSystem);
final Address localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey());
final IbftBlockCreatorFactory blockCreatorFactory =
new IbftBlockCreatorFactory(
final BftBlockCreatorFactory blockCreatorFactory =
new BftBlockCreatorFactory(
gasLimitCalculator,
transactionPool.getPendingTransactions(),
protocolContext,
@@ -132,7 +132,7 @@ public class IbftBesuControllerBuilder extends BesuControllerBuilder {
// NOTE: peers should not be used for accessing the network as it does not enforce the
// "only send once" filter applied by the UniqueMessageMulticaster.
final VoteTallyCache voteTallyCache =
protocolContext.getConsensusState(IbftContext.class).getVoteTallyCache();
protocolContext.getConsensusState(BftContext.class).getVoteTallyCache();
final ProposerSelector proposerSelector =
new ProposerSelector(blockchain, blockInterface, true, voteTallyCache);
@@ -213,7 +213,7 @@ public class IbftBesuControllerBuilder extends BesuControllerBuilder {
@Override
protected ProtocolSchedule createProtocolSchedule() {
return IbftProtocolSchedule.create(
return BftProtocolSchedule.create(
genesisConfig.getConfigOptions(genesisConfigOverrides),
privacyParameters,
isRevertReasonEnabled);
@@ -229,22 +229,22 @@ public class IbftBesuControllerBuilder extends BesuControllerBuilder {
}
@Override
protected IbftContext createConsensusContext(
protected BftContext createConsensusContext(
final Blockchain blockchain, final WorldStateArchive worldStateArchive) {
final GenesisConfigOptions configOptions =
genesisConfig.getConfigOptions(genesisConfigOverrides);
final IbftConfigOptions ibftConfig = configOptions.getIbft2ConfigOptions();
final BftConfigOptions ibftConfig = configOptions.getBftConfigOptions();
final EpochManager epochManager = new EpochManager(ibftConfig.getEpochLength());
final Map<Long, List<Address>> ibftValidatorForkMap =
convertIbftForks(configOptions.getTransitions().getIbftForks());
return new IbftContext(
return new BftContext(
new ForkingVoteTallyCache(
blockchain,
new VoteTallyUpdater(epochManager, new IbftBlockInterface()),
new VoteTallyUpdater(epochManager, new BftBlockInterface()),
epochManager,
new IbftBlockInterface(),
new BftBlockInterface(),
new BftValidatorOverrides(ibftValidatorForkMap)),
new VoteProposer(),
epochManager,

View File

@@ -14,13 +14,13 @@
*/
package org.hyperledger.besu.controller;
import org.hyperledger.besu.config.IbftConfigOptions;
import org.hyperledger.besu.config.BftConfigOptions;
import org.hyperledger.besu.consensus.common.BlockInterface;
import org.hyperledger.besu.consensus.common.EpochManager;
import org.hyperledger.besu.consensus.common.VoteProposer;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
import org.hyperledger.besu.consensus.common.VoteTallyUpdater;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.ibftlegacy.IbftLegacyBlockInterface;
import org.hyperledger.besu.consensus.ibftlegacy.IbftProtocolSchedule;
import org.hyperledger.besu.consensus.ibftlegacy.protocol.Istanbul64Protocol;
@@ -81,9 +81,9 @@ public class IbftLegacyBesuControllerBuilder extends BesuControllerBuilder {
}
@Override
protected IbftContext createConsensusContext(
protected BftContext createConsensusContext(
final Blockchain blockchain, final WorldStateArchive worldStateArchive) {
final IbftConfigOptions ibftConfig =
final BftConfigOptions ibftConfig =
genesisConfig.getConfigOptions(genesisConfigOverrides).getIbftLegacyConfigOptions();
final EpochManager epochManager = new EpochManager(ibftConfig.getEpochLength());
final VoteTallyCache voteTallyCache =
@@ -94,7 +94,7 @@ public class IbftLegacyBesuControllerBuilder extends BesuControllerBuilder {
blockInterface);
final VoteProposer voteProposer = new VoteProposer();
return new IbftContext(voteTallyCache, voteProposer, epochManager, blockInterface);
return new BftContext(voteTallyCache, voteProposer, epochManager, blockInterface);
}
@Override

View File

@@ -15,7 +15,7 @@
package org.hyperledger.besu.controller;
import org.hyperledger.besu.consensus.common.BlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.ibft.queries.IbftQueryServiceImpl;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.ethereum.chain.Blockchain;
@@ -36,7 +36,7 @@ public class IbftQueryPluginServiceFactory implements PluginServiceFactory {
@Override
public void appendPluginServices(final BesuPluginContextImpl besuContext) {
final BlockInterface blockInterface = new IbftBlockInterface();
final BlockInterface blockInterface = new BftBlockInterface();
final IbftQueryServiceImpl service =
new IbftQueryServiceImpl(blockInterface, blockchain, nodeKey);

View File

@@ -22,10 +22,10 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import org.apache.tuweni.bytes.Bytes;
public class IbftConfigOptions {
public class BftConfigOptions {
public static final IbftConfigOptions DEFAULT =
new IbftConfigOptions(JsonUtil.createEmptyObjectNode());
public static final BftConfigOptions DEFAULT =
new BftConfigOptions(JsonUtil.createEmptyObjectNode());
private static final long DEFAULT_EPOCH_LENGTH = 30_000;
private static final int DEFAULT_BLOCK_PERIOD_SECONDS = 1;
@@ -40,7 +40,7 @@ public class IbftConfigOptions {
private final ObjectNode ibftConfigRoot;
IbftConfigOptions(final ObjectNode ibftConfigRoot) {
BftConfigOptions(final ObjectNode ibftConfigRoot) {
this.ibftConfigRoot = ibftConfigRoot;
}

View File

@@ -33,11 +33,11 @@ public interface GenesisConfigOptions {
String getConsensusEngine();
IbftConfigOptions getIbftLegacyConfigOptions();
BftConfigOptions getIbftLegacyConfigOptions();
CliqueConfigOptions getCliqueConfigOptions();
IbftConfigOptions getIbft2ConfigOptions();
BftConfigOptions getBftConfigOptions();
EthashConfigOptions getEthashConfigOptions();

View File

@@ -125,17 +125,17 @@ public class JsonGenesisConfigOptions implements GenesisConfigOptions {
}
@Override
public IbftConfigOptions getIbftLegacyConfigOptions() {
public BftConfigOptions getIbftLegacyConfigOptions() {
return JsonUtil.getObjectNode(configRoot, IBFT_LEGACY_CONFIG_KEY)
.map(IbftConfigOptions::new)
.orElse(IbftConfigOptions.DEFAULT);
.map(BftConfigOptions::new)
.orElse(BftConfigOptions.DEFAULT);
}
@Override
public IbftConfigOptions getIbft2ConfigOptions() {
public BftConfigOptions getBftConfigOptions() {
return JsonUtil.getObjectNode(configRoot, IBFT2_CONFIG_KEY)
.map(IbftConfigOptions::new)
.orElse(IbftConfigOptions.DEFAULT);
.map(BftConfigOptions::new)
.orElse(BftConfigOptions.DEFAULT);
}
@Override
@@ -359,7 +359,7 @@ public class JsonGenesisConfigOptions implements GenesisConfigOptions {
builder.put("ibft", getIbftLegacyConfigOptions().asMap());
}
if (isIbft2()) {
builder.put("ibft2", getIbft2ConfigOptions().asMap());
builder.put("ibft2", getBftConfigOptions().asMap());
}
if (isQuorum()) {

View File

@@ -80,8 +80,8 @@ public class StubGenesisConfigOptions implements GenesisConfigOptions {
}
@Override
public IbftConfigOptions getIbftLegacyConfigOptions() {
return IbftConfigOptions.DEFAULT;
public BftConfigOptions getIbftLegacyConfigOptions() {
return BftConfigOptions.DEFAULT;
}
@Override
@@ -90,8 +90,8 @@ public class StubGenesisConfigOptions implements GenesisConfigOptions {
}
@Override
public IbftConfigOptions getIbft2ConfigOptions() {
return IbftConfigOptions.DEFAULT;
public BftConfigOptions getBftConfigOptions() {
return BftConfigOptions.DEFAULT;
}
@Override
@@ -258,7 +258,7 @@ public class StubGenesisConfigOptions implements GenesisConfigOptions {
builder.put("ibft", getIbftLegacyConfigOptions().asMap());
}
if (isIbft2()) {
builder.put("ibft2", getIbft2ConfigOptions().asMap());
builder.put("ibft2", getBftConfigOptions().asMap());
}
return builder.build();
}

View File

@@ -23,7 +23,7 @@ import java.util.Map;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
public class IbftConfigOptionsTest {
public class BftConfigOptionsTest {
private static final int EXPECTED_DEFAULT_EPOCH_LENGTH = 30_000;
private static final int EXPECTED_DEFAULT_BLOCK_PERIOD = 1;
@@ -36,151 +36,151 @@ public class IbftConfigOptionsTest {
@Test
public void shouldGetEpochLengthFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("EpochLength", 10_000));
final BftConfigOptions config = fromConfigOptions(singletonMap("EpochLength", 10_000));
assertThat(config.getEpochLength()).isEqualTo(10_000);
}
@Test
public void shouldFallbackToDefaultEpochLength() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getEpochLength()).isEqualTo(EXPECTED_DEFAULT_EPOCH_LENGTH);
}
@Test
public void shouldGetDefaultEpochLengthFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getEpochLength()).isEqualTo(EXPECTED_DEFAULT_EPOCH_LENGTH);
assertThat(BftConfigOptions.DEFAULT.getEpochLength()).isEqualTo(EXPECTED_DEFAULT_EPOCH_LENGTH);
}
@Test
public void shouldGetBlockPeriodFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("BlockPeriodSeconds", 5));
final BftConfigOptions config = fromConfigOptions(singletonMap("BlockPeriodSeconds", 5));
assertThat(config.getBlockPeriodSeconds()).isEqualTo(5);
}
@Test
public void shouldFallbackToDefaultBlockPeriod() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getBlockPeriodSeconds()).isEqualTo(EXPECTED_DEFAULT_BLOCK_PERIOD);
}
@Test
public void shouldGetDefaultBlockPeriodFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getBlockPeriodSeconds())
assertThat(BftConfigOptions.DEFAULT.getBlockPeriodSeconds())
.isEqualTo(EXPECTED_DEFAULT_BLOCK_PERIOD);
}
@Test
public void shouldGetRequestTimeoutFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("RequestTimeoutSeconds", 5));
final BftConfigOptions config = fromConfigOptions(singletonMap("RequestTimeoutSeconds", 5));
assertThat(config.getRequestTimeoutSeconds()).isEqualTo(5);
}
@Test
public void shouldFallbackToDefaultRequestTimeout() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getRequestTimeoutSeconds()).isEqualTo(EXPECTED_DEFAULT_REQUEST_TIMEOUT);
}
@Test
public void shouldGetDefaultRequestTimeoutFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getRequestTimeoutSeconds())
assertThat(BftConfigOptions.DEFAULT.getRequestTimeoutSeconds())
.isEqualTo(EXPECTED_DEFAULT_REQUEST_TIMEOUT);
}
@Test
public void shouldGetGossipedHistoryLimitFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("GossipedHistoryLimit", 100));
final BftConfigOptions config = fromConfigOptions(singletonMap("GossipedHistoryLimit", 100));
assertThat(config.getGossipedHistoryLimit()).isEqualTo(100);
}
@Test
public void shouldFallbackToDefaultGossipedHistoryLimit() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getGossipedHistoryLimit()).isEqualTo(EXPECTED_DEFAULT_GOSSIPED_HISTORY_LIMIT);
}
@Test
public void shouldGetDefaultGossipedHistoryLimitFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getGossipedHistoryLimit())
assertThat(BftConfigOptions.DEFAULT.getGossipedHistoryLimit())
.isEqualTo(EXPECTED_DEFAULT_GOSSIPED_HISTORY_LIMIT);
}
@Test
public void shouldGetMessageQueueLimitFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("MessageQueueLimit", 100));
final BftConfigOptions config = fromConfigOptions(singletonMap("MessageQueueLimit", 100));
assertThat(config.getMessageQueueLimit()).isEqualTo(100);
}
@Test
public void shouldFallbackToDefaultMessageQueueLimit() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getMessageQueueLimit()).isEqualTo(EXPECTED_DEFAULT_MESSAGE_QUEUE_LIMIT);
}
@Test
public void shouldGetDefaultMessageQueueLimitFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getMessageQueueLimit())
assertThat(BftConfigOptions.DEFAULT.getMessageQueueLimit())
.isEqualTo(EXPECTED_DEFAULT_MESSAGE_QUEUE_LIMIT);
}
@Test
public void shouldGetDuplicateMessageLimitFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("DuplicateMessageLimit", 50));
final BftConfigOptions config = fromConfigOptions(singletonMap("DuplicateMessageLimit", 50));
assertThat(config.getDuplicateMessageLimit()).isEqualTo(50);
}
@Test
public void shouldFallbackToDefaultDuplicateMessageLimit() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getDuplicateMessageLimit())
.isEqualTo(EXPECTED_DEFAULT_DUPLICATE_MESSAGE_LIMIT);
}
@Test
public void shouldGetDefaultDuplicateMessageLimitFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getDuplicateMessageLimit())
assertThat(BftConfigOptions.DEFAULT.getDuplicateMessageLimit())
.isEqualTo(EXPECTED_DEFAULT_DUPLICATE_MESSAGE_LIMIT);
}
@Test
public void shouldGetFutureMessagesLimitFromConfig() {
final IbftConfigOptions config = fromConfigOptions(singletonMap("FutureMessagesLimit", 50));
final BftConfigOptions config = fromConfigOptions(singletonMap("FutureMessagesLimit", 50));
assertThat(config.getFutureMessagesLimit()).isEqualTo(50);
}
@Test
public void shouldFallbackToDefaultFutureMessagesLimit() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getFutureMessagesLimit()).isEqualTo(EXPECTED_DEFAULT_FUTURE_MESSAGES_LIMIT);
}
@Test
public void shouldGetDefaultFutureMessagesLimitsFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getFutureMessagesLimit())
assertThat(BftConfigOptions.DEFAULT.getFutureMessagesLimit())
.isEqualTo(EXPECTED_DEFAULT_FUTURE_MESSAGES_LIMIT);
}
@Test
public void shouldGetFutureMessagesMaxDistanceFromConfig() {
final IbftConfigOptions config =
final BftConfigOptions config =
fromConfigOptions(singletonMap("FutureMessagesMaxDistance", 50));
assertThat(config.getFutureMessagesMaxDistance()).isEqualTo(50);
}
@Test
public void shouldFallbackToDefaultFutureMessagesMaxDistance() {
final IbftConfigOptions config = fromConfigOptions(emptyMap());
final BftConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.getFutureMessagesMaxDistance())
.isEqualTo(EXPECTED_DEFAULT_FUTURE_MESSAGES_MAX_DISTANCE);
}
@Test
public void shouldGetDefaultFutureMessagesMaxDistanceFromDefaultConfig() {
assertThat(IbftConfigOptions.DEFAULT.getFutureMessagesMaxDistance())
assertThat(BftConfigOptions.DEFAULT.getFutureMessagesMaxDistance())
.isEqualTo(EXPECTED_DEFAULT_FUTURE_MESSAGES_MAX_DISTANCE);
}
private IbftConfigOptions fromConfigOptions(final Map<String, Object> ibftConfigOptions) {
private BftConfigOptions fromConfigOptions(final Map<String, Object> ibftConfigOptions) {
final ObjectNode rootNode = JsonUtil.createEmptyObjectNode();
final ObjectNode configNode = JsonUtil.createEmptyObjectNode();
final ObjectNode options = JsonUtil.objectNodeFromMap(ibftConfigOptions);

View File

@@ -47,7 +47,7 @@ public class GenesisConfigOptionsTest {
public void shouldUseIbftLegacyWhenIbftInConfig() {
final GenesisConfigOptions config = fromConfigOptions(singletonMap("ibft", emptyMap()));
assertThat(config.isIbftLegacy()).isTrue();
assertThat(config.getIbftLegacyConfigOptions()).isNotSameAs(IbftConfigOptions.DEFAULT);
assertThat(config.getIbftLegacyConfigOptions()).isNotSameAs(BftConfigOptions.DEFAULT);
assertThat(config.getConsensusEngine()).isEqualTo("ibft");
}
@@ -55,7 +55,7 @@ public class GenesisConfigOptionsTest {
public void shouldNotUseIbftLegacyIfIbftNotPresent() {
final GenesisConfigOptions config = fromConfigOptions(emptyMap());
assertThat(config.isIbftLegacy()).isFalse();
assertThat(config.getIbftLegacyConfigOptions()).isSameAs(IbftConfigOptions.DEFAULT);
assertThat(config.getIbftLegacyConfigOptions()).isSameAs(BftConfigOptions.DEFAULT);
}
@Test

View File

@@ -123,10 +123,10 @@ public class JsonGenesisConfigOptionsTest {
final JsonGenesisConfigOptions configOptions =
JsonGenesisConfigOptions.fromJsonObject(configNode);
assertThat(configOptions.getIbft2ConfigOptions().getMiningBeneficiary()).isNotEmpty();
assertThat(configOptions.getIbft2ConfigOptions().getMiningBeneficiary().get())
assertThat(configOptions.getBftConfigOptions().getMiningBeneficiary()).isNotEmpty();
assertThat(configOptions.getBftConfigOptions().getMiningBeneficiary().get())
.isEqualTo("0x1234567890123456789012345678901234567890");
assertThat(configOptions.getIbft2ConfigOptions().getBlockRewardWei()).isEqualTo(21);
assertThat(configOptions.getBftConfigOptions().getBlockRewardWei()).isEqualTo(21);
}
@Test
@@ -138,7 +138,7 @@ public class JsonGenesisConfigOptionsTest {
final JsonGenesisConfigOptions configOptions =
JsonGenesisConfigOptions.fromJsonObject(configNode);
assertThat(configOptions.getIbft2ConfigOptions().getMiningBeneficiary()).isEmpty();
assertThat(configOptions.getBftConfigOptions().getMiningBeneficiary()).isEmpty();
}
@Test
@@ -150,7 +150,7 @@ public class JsonGenesisConfigOptionsTest {
final JsonGenesisConfigOptions configOptions =
JsonGenesisConfigOptions.fromJsonObject(configNode);
assertThat(configOptions.getIbft2ConfigOptions().getBlockRewardWei()).isEqualTo(0);
assertThat(configOptions.getBftConfigOptions().getBlockRewardWei()).isEqualTo(0);
}
@Test
@@ -162,6 +162,6 @@ public class JsonGenesisConfigOptionsTest {
final JsonGenesisConfigOptions configOptions =
JsonGenesisConfigOptions.fromJsonObject(configNode);
assertThat(configOptions.getIbft2ConfigOptions().getBlockRewardWei()).isEqualTo(12);
assertThat(configOptions.getBftConfigOptions().getBlockRewardWei()).isEqualTo(12);
}
}

View File

@@ -30,26 +30,35 @@ jar {
dependencies {
api project(':plugin-api')
implementation project(':config')
implementation project(':crypto')
implementation project(':ethereum:api')
implementation project(':ethereum:blockcreation')
implementation project(':ethereum:core')
implementation project(':ethereum:eth')
implementation project(':ethereum:p2p')
implementation project(':ethereum:rlp')
implementation project(':util')
implementation 'com.fasterxml.jackson.core:jackson-databind'
implementation 'com.google.guava:guava'
implementation 'org.apache.tuweni:bytes'
testImplementation project(':config')
testImplementation project(':crypto')
testImplementation project(':testutil')
testImplementation project( path: ':ethereum:core', configuration: 'testSupportArtifacts')
testImplementation project( path: ':crypto', configuration: 'testSupportArtifacts')
testImplementation project(':metrics:core')
testImplementation 'junit:junit'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.awaitility:awaitility'
testSupportImplementation 'org.mockito:mockito-core'
}
configurations { testArtifacts }
task testJar (type: Jar) {
archiveBaseName = "${project.name}-test"
@@ -58,4 +67,5 @@ task testJar (type: Jar) {
artifacts {
testArtifacts testJar
testSupportArtifacts testSupportJar
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -27,7 +27,7 @@ import java.util.stream.Collectors;
import org.apache.tuweni.bytes.Bytes;
public class IbftBlockHashing {
public class BftBlockHashing {
/**
* Constructs a hash of the block header suitable for signing as a committed seal. The extra data
@@ -35,18 +35,18 @@ public class IbftBlockHashing {
*
* @param header The header for which a proposer seal is to be calculated (with or without extra
* data)
* @param ibftExtraData The extra data block which is to be inserted to the header once seal is
* @param bftExtraData The extra data block which is to be inserted to the header once seal is
* calculated
* @return the hash of the header including the validator and proposer seal in the extra data
*/
public static Hash calculateDataHashForCommittedSeal(
final BlockHeader header, final IbftExtraData ibftExtraData) {
return Hash.hash(serializeHeader(header, ibftExtraData::encodeWithoutCommitSeals));
final BlockHeader header, final BftExtraData bftExtraData) {
return Hash.hash(serializeHeader(header, bftExtraData::encodeWithoutCommitSeals));
}
public static Hash calculateDataHashForCommittedSeal(final BlockHeader header) {
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
return Hash.hash(serializeHeader(header, ibftExtraData::encodeWithoutCommitSeals));
final BftExtraData bftExtraData = BftExtraData.decode(header);
return Hash.hash(serializeHeader(header, bftExtraData::encodeWithoutCommitSeals));
}
/**
@@ -56,25 +56,24 @@ public class IbftBlockHashing {
* @param header The header for which a block hash is to be calculated
* @return the hash of the header to be used when referencing the header on the blockchain
*/
public static Hash calculateHashOfIbftBlockOnChain(final BlockHeader header) {
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
return Hash.hash(
serializeHeader(header, ibftExtraData::encodeWithoutCommitSealsAndRoundNumber));
public static Hash calculateHashOfBftBlockOnChain(final BlockHeader header) {
final BftExtraData bftExtraData = BftExtraData.decode(header);
return Hash.hash(serializeHeader(header, bftExtraData::encodeWithoutCommitSealsAndRoundNumber));
}
/**
* Recovers the {@link Address} for each validator that contributed a committed seal to the block.
*
* @param header the block header that was signed by the committed seals
* @param ibftExtraData the parsed {@link IbftExtraData} from the header
* @param bftExtraData the parsed {@link BftExtraData} from the header
* @return the addresses of validators that provided a committed seal
*/
public static List<Address> recoverCommitterAddresses(
final BlockHeader header, final IbftExtraData ibftExtraData) {
final BlockHeader header, final BftExtraData bftExtraData) {
final Hash committerHash =
IbftBlockHashing.calculateDataHashForCommittedSeal(header, ibftExtraData);
BftBlockHashing.calculateDataHashForCommittedSeal(header, bftExtraData);
return ibftExtraData.getSeals().stream()
return bftExtraData.getSeals().stream()
.map(p -> Util.signatureToAddress(p, committerHash))
.collect(Collectors.toList());
}
@@ -85,7 +84,7 @@ public class IbftBlockHashing {
// create a block header which is a copy of the header supplied as parameter except of the
// extraData field
final BlockHeaderBuilder builder = BlockHeaderBuilder.fromHeader(header);
builder.blockHeaderFunctions(IbftBlockHeaderFunctions.forOnChainBlock());
builder.blockHeaderFunctions(BftBlockHeaderFunctions.forOnChainBlock());
// set the extraData field using the supplied extraDataSerializer if the block height is not 0
if (header.getNumber() == BlockHeader.GENESIS_BLOCK_NUMBER) {

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
@@ -20,16 +20,16 @@ import org.hyperledger.besu.ethereum.core.Hash;
import java.util.function.Function;
public class IbftBlockHeaderFunctions implements BlockHeaderFunctions {
public class BftBlockHeaderFunctions implements BlockHeaderFunctions {
private static final IbftBlockHeaderFunctions COMMITTED_SEAL =
new IbftBlockHeaderFunctions(IbftBlockHashing::calculateDataHashForCommittedSeal);
private static final IbftBlockHeaderFunctions ON_CHAIN =
new IbftBlockHeaderFunctions(IbftBlockHashing::calculateHashOfIbftBlockOnChain);
private static final BftBlockHeaderFunctions COMMITTED_SEAL =
new BftBlockHeaderFunctions(BftBlockHashing::calculateDataHashForCommittedSeal);
private static final BftBlockHeaderFunctions ON_CHAIN =
new BftBlockHeaderFunctions(BftBlockHashing::calculateHashOfBftBlockOnChain);
private final Function<BlockHeader, Hash> hashFunction;
private IbftBlockHeaderFunctions(final Function<BlockHeader, Hash> hashFunction) {
private BftBlockHeaderFunctions(final Function<BlockHeader, Hash> hashFunction) {
this.hashFunction = hashFunction;
}
@@ -47,7 +47,7 @@ public class IbftBlockHeaderFunctions implements BlockHeaderFunctions {
}
@Override
public IbftExtraData parseExtraData(final BlockHeader header) {
return IbftExtraData.decodeRaw(header.getExtraData());
public BftExtraData parseExtraData(final BlockHeader header) {
return BftExtraData.decodeRaw(header.getExtraData());
}
}

View File

@@ -12,11 +12,11 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.consensus.ibft.headervalidationrules.IbftCoinbaseValidationRule;
import org.hyperledger.besu.consensus.ibft.headervalidationrules.IbftCommitSealsValidationRule;
import org.hyperledger.besu.consensus.ibft.headervalidationrules.IbftValidatorsValidationRule;
import org.hyperledger.besu.consensus.common.bft.headervalidationrules.BftCoinbaseValidationRule;
import org.hyperledger.besu.consensus.common.bft.headervalidationrules.BftCommitSealsValidationRule;
import org.hyperledger.besu.consensus.common.bft.headervalidationrules.BftValidatorsValidationRule;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator;
@@ -29,16 +29,16 @@ import org.hyperledger.besu.ethereum.mainnet.headervalidationrules.TimestampMore
import org.apache.tuweni.units.bigints.UInt256;
public class IbftBlockHeaderValidationRulesetFactory {
public class BftBlockHeaderValidationRulesetFactory {
/**
* Produces a BlockHeaderValidator configured for assessing ibft block headers which are to form
* Produces a BlockHeaderValidator configured for assessing bft block headers which are to form
* part of the BlockChain (i.e. not proposed blocks, which do not contain commit seals)
*
* @param secondsBetweenBlocks the minimum number of seconds which must elapse between blocks.
* @return BlockHeaderValidator configured for assessing ibft block headers
* @return BlockHeaderValidator configured for assessing bft block headers
*/
public static BlockHeaderValidator.Builder ibftBlockHeaderValidator(
public static BlockHeaderValidator.Builder bftBlockHeaderValidator(
final long secondsBetweenBlocks) {
return new BlockHeaderValidator.Builder()
.addRule(new AncestryValidationRule())
@@ -48,7 +48,7 @@ public class IbftBlockHeaderValidationRulesetFactory {
.addRule(new TimestampMoreRecentThanParent(secondsBetweenBlocks))
.addRule(
new ConstantFieldValidationRule<>(
"MixHash", BlockHeader::getMixHash, IbftHelpers.EXPECTED_MIX_HASH))
"MixHash", BlockHeader::getMixHash, BftHelpers.EXPECTED_MIX_HASH))
.addRule(
new ConstantFieldValidationRule<>(
"OmmersHash", BlockHeader::getOmmersHash, Hash.EMPTY_LIST_HASH))
@@ -56,8 +56,8 @@ public class IbftBlockHeaderValidationRulesetFactory {
new ConstantFieldValidationRule<>(
"Difficulty", BlockHeader::getDifficulty, UInt256.ONE))
.addRule(new ConstantFieldValidationRule<>("Nonce", BlockHeader::getNonce, 0L))
.addRule(new IbftValidatorsValidationRule())
.addRule(new IbftCoinbaseValidationRule())
.addRule(new IbftCommitSealsValidationRule());
.addRule(new BftValidatorsValidationRule())
.addRule(new BftCoinbaseValidationRule())
.addRule(new BftCommitSealsValidationRule());
}
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.consensus.common.BlockInterface;
import org.hyperledger.besu.consensus.common.ValidatorVote;
@@ -26,7 +26,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import java.util.Collection;
import java.util.Optional;
public class IbftBlockInterface implements BlockInterface {
public class BftBlockInterface implements BlockInterface {
@Override
public Address getProposerOfBlock(final BlockHeader header) {
@@ -40,10 +40,10 @@ public class IbftBlockInterface implements BlockInterface {
@Override
public Optional<ValidatorVote> extractVoteFromHeader(final BlockHeader header) {
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
final BftExtraData bftExtraData = BftExtraData.decode(header);
if (ibftExtraData.getVote().isPresent()) {
final Vote headerVote = ibftExtraData.getVote().get();
if (bftExtraData.getVote().isPresent()) {
final Vote headerVote = bftExtraData.getVote().get();
final ValidatorVote vote =
new ValidatorVote(
headerVote.isAuth() ? VoteType.ADD : VoteType.DROP,
@@ -56,15 +56,15 @@ public class IbftBlockInterface implements BlockInterface {
@Override
public Collection<Address> validatorsInBlock(final BlockHeader header) {
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
return ibftExtraData.getValidators();
final BftExtraData bftExtraData = BftExtraData.decode(header);
return bftExtraData.getValidators();
}
public static Block replaceRoundInBlock(
final Block block, final int round, final BlockHeaderFunctions blockHeaderFunctions) {
final IbftExtraData prevExtraData = IbftExtraData.decode(block.getHeader());
final IbftExtraData substituteExtraData =
new IbftExtraData(
final BftExtraData prevExtraData = BftExtraData.decode(block.getHeader());
final BftExtraData substituteExtraData =
new BftExtraData(
prevExtraData.getVanityData(),
prevExtraData.getSeals(),
prevExtraData.getVote(),

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.consensus.common.BlockInterface;
import org.hyperledger.besu.consensus.common.EpochManager;
@@ -20,15 +20,15 @@ import org.hyperledger.besu.consensus.common.PoaContext;
import org.hyperledger.besu.consensus.common.VoteProposer;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
/** Holds the IBFT specific mutable state. */
public class IbftContext implements PoaContext {
/** Holds the BFT specific mutable state. */
public class BftContext implements PoaContext {
private final VoteTallyCache voteTallyCache;
private final VoteProposer voteProposer;
private final EpochManager epochManager;
private final BlockInterface blockInterface;
public IbftContext(
public BftContext(
final VoteTallyCache voteTallyCache,
final VoteProposer voteProposer,
final EpochManager epochManager,

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -36,9 +36,9 @@ import org.apache.tuweni.bytes.Bytes;
/**
* Represents the data structure stored in the extraData field of the BlockHeader used when
* operating under an IBFT 2.0 consensus mechanism.
* operating under an BFT consensus mechanism.
*/
public class IbftExtraData implements ParsedExtraData {
public class BftExtraData implements ParsedExtraData {
private static final Logger LOG = LogManager.getLogger();
public static final int EXTRA_VANITY_LENGTH = 32;
@@ -49,7 +49,7 @@ public class IbftExtraData implements ParsedExtraData {
private final int round;
private final Collection<Address> validators;
public IbftExtraData(
public BftExtraData(
final Bytes vanityData,
final Collection<Signature> seals,
final Optional<Vote> vote,
@@ -67,30 +67,30 @@ public class IbftExtraData implements ParsedExtraData {
this.vote = vote;
}
public static IbftExtraData fromAddresses(final Collection<Address> addresses) {
return new IbftExtraData(
public static BftExtraData fromAddresses(final Collection<Address> addresses) {
return new BftExtraData(
Bytes.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, addresses);
}
public static IbftExtraData decode(final BlockHeader blockHeader) {
public static BftExtraData decode(final BlockHeader blockHeader) {
final Object inputExtraData = blockHeader.getParsedExtraData();
if (inputExtraData instanceof IbftExtraData) {
return (IbftExtraData) inputExtraData;
if (inputExtraData instanceof BftExtraData) {
return (BftExtraData) inputExtraData;
}
LOG.warn(
"Expected a IbftExtraData instance but got {}. Reparsing required.",
"Expected a BftExtraData instance but got {}. Reparsing required.",
inputExtraData != null ? inputExtraData.getClass().getName() : "null");
return decodeRaw(blockHeader.getExtraData());
}
static IbftExtraData decodeRaw(final Bytes input) {
static BftExtraData decodeRaw(final Bytes input) {
if (input.isEmpty()) {
throw new IllegalArgumentException("Invalid Bytes supplied - Ibft Extra Data required.");
throw new IllegalArgumentException("Invalid Bytes supplied - Bft Extra Data required.");
}
final RLPInput rlpInput = new BytesValueRLPInput(input, false);
rlpInput.enterList(); // This accounts for the "root node" which contains IBFT data items.
rlpInput.enterList(); // This accounts for the "root node" which contains BFT data items.
final Bytes vanityData = rlpInput.readBytes();
final List<Address> validators = rlpInput.readList(Address::readFrom);
final Optional<Vote> vote;
@@ -104,7 +104,7 @@ public class IbftExtraData implements ParsedExtraData {
final List<Signature> seals = rlpInput.readList(rlp -> Signature.decode(rlp.readBytes()));
rlpInput.leaveList();
return new IbftExtraData(vanityData, seals, vote, round, validators);
return new BftExtraData(vanityData, seals, vote, round, validators);
}
public Bytes encode() {
@@ -149,8 +149,8 @@ public class IbftExtraData implements ParsedExtraData {
}
public static String createGenesisExtraDataString(final List<Address> validators) {
final IbftExtraData extraData =
new IbftExtraData(
final BftExtraData extraData =
new BftExtraData(
Bytes.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, validators);
return extraData.encode().toString();
}
@@ -178,7 +178,7 @@ public class IbftExtraData implements ParsedExtraData {
@Override
public String toString() {
return new StringJoiner(", ", IbftExtraData.class.getSimpleName() + "[", "]")
return new StringJoiner(", ", BftExtraData.class.getSimpleName() + "[", "]")
.add("vanityData=" + vanityData)
.add("seals=" + seals)
.add("vote=" + vote)

View File

@@ -12,11 +12,8 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.payload.PreparedCertificate;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangePayload;
import org.hyperledger.besu.crypto.SECP256K1.Signature;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -25,9 +22,8 @@ import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Util;
import java.util.Collection;
import java.util.Optional;
public class IbftHelpers {
public class BftHelpers {
public static final Hash EXPECTED_MIX_HASH =
Hash.fromHexString("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365");
@@ -43,10 +39,10 @@ public class IbftHelpers {
public static Block createSealedBlock(
final Block block, final Collection<Signature> commitSeals) {
final BlockHeader initialHeader = block.getHeader();
final IbftExtraData initialExtraData = IbftExtraData.decode(initialHeader);
final BftExtraData initialExtraData = BftExtraData.decode(initialHeader);
final IbftExtraData sealedExtraData =
new IbftExtraData(
final BftExtraData sealedExtraData =
new BftExtraData(
initialExtraData.getVanityData(),
commitSeals,
initialExtraData.getVote(),
@@ -56,33 +52,9 @@ public class IbftHelpers {
final BlockHeader sealedHeader =
BlockHeaderBuilder.fromHeader(initialHeader)
.extraData(sealedExtraData.encode())
.blockHeaderFunctions(IbftBlockHeaderFunctions.forOnChainBlock())
.blockHeaderFunctions(BftBlockHeaderFunctions.forOnChainBlock())
.buildBlockHeader();
return new Block(sealedHeader, block.getBody());
}
public static Optional<PreparedCertificate> findLatestPreparedCertificate(
final Collection<SignedData<RoundChangePayload>> msgs) {
Optional<PreparedCertificate> result = Optional.empty();
for (SignedData<RoundChangePayload> roundChangeMsg : msgs) {
final RoundChangePayload payload = roundChangeMsg.getPayload();
if (payload.getPreparedCertificate().isPresent()) {
if (!result.isPresent()) {
result = payload.getPreparedCertificate();
} else {
final PreparedCertificate currentLatest = result.get();
final PreparedCertificate nextCert = payload.getPreparedCertificate().get();
if (currentLatest.getProposalPayload().getPayload().getRoundIdentifier().getRoundNumber()
< nextCert.getProposalPayload().getPayload().getRoundIdentifier().getRoundNumber()) {
result = Optional.of(nextCert);
}
}
}
}
return result;
}
}

View File

@@ -12,12 +12,12 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static org.hyperledger.besu.consensus.ibft.IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator;
import static org.hyperledger.besu.consensus.common.bft.BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator;
import org.hyperledger.besu.config.BftConfigOptions;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.config.IbftConfigOptions;
import org.hyperledger.besu.ethereum.MainnetBlockValidator;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.PrivacyParameters;
@@ -30,8 +30,8 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSpecBuilder;
import java.math.BigInteger;
/** Defines the protocol behaviours for a blockchain using IBFT. */
public class IbftProtocolSchedule {
/** Defines the protocol behaviours for a blockchain using a BFT consensus mechanism. */
public class BftProtocolSchedule {
private static final BigInteger DEFAULT_CHAIN_ID = BigInteger.ONE;
@@ -43,7 +43,7 @@ public class IbftProtocolSchedule {
return new ProtocolScheduleBuilder(
config,
DEFAULT_CHAIN_ID,
builder -> applyIbftChanges(config.getIbft2ConfigOptions(), builder),
builder -> applyBftChanges(config.getBftConfigOptions(), builder),
privacyParameters,
isRevertReasonEnabled,
config.isQuorum())
@@ -59,33 +59,33 @@ public class IbftProtocolSchedule {
return create(config, PrivacyParameters.DEFAULT, false);
}
private static ProtocolSpecBuilder applyIbftChanges(
final IbftConfigOptions ibftConfig, final ProtocolSpecBuilder builder) {
private static ProtocolSpecBuilder applyBftChanges(
final BftConfigOptions configOptions, final ProtocolSpecBuilder builder) {
if (ibftConfig.getEpochLength() <= 0) {
if (configOptions.getEpochLength() <= 0) {
throw new IllegalArgumentException("Epoch length in config must be greater than zero");
}
if (ibftConfig.getBlockRewardWei().signum() < 0) {
throw new IllegalArgumentException("Ibft2 Block reward in config cannot be negative");
if (configOptions.getBlockRewardWei().signum() < 0) {
throw new IllegalArgumentException("Bft Block reward in config cannot be negative");
}
builder
.blockHeaderValidatorBuilder(ibftBlockHeaderValidator(ibftConfig.getBlockPeriodSeconds()))
.ommerHeaderValidatorBuilder(ibftBlockHeaderValidator(ibftConfig.getBlockPeriodSeconds()))
.blockHeaderValidatorBuilder(bftBlockHeaderValidator(configOptions.getBlockPeriodSeconds()))
.ommerHeaderValidatorBuilder(bftBlockHeaderValidator(configOptions.getBlockPeriodSeconds()))
.blockBodyValidatorBuilder(MainnetBlockBodyValidator::new)
.blockValidatorBuilder(MainnetBlockValidator::new)
.blockImporterBuilder(MainnetBlockImporter::new)
.difficultyCalculator((time, parent, protocolContext) -> BigInteger.ONE)
.blockReward(Wei.of(ibftConfig.getBlockRewardWei()))
.blockReward(Wei.of(configOptions.getBlockRewardWei()))
.skipZeroBlockRewards(true)
.blockHeaderFunctions(IbftBlockHeaderFunctions.forOnChainBlock());
.blockHeaderFunctions(BftBlockHeaderFunctions.forOnChainBlock());
if (ibftConfig.getMiningBeneficiary().isPresent()) {
if (configOptions.getMiningBeneficiary().isPresent()) {
final Address miningBeneficiary;
try {
// Precalculate beneficiary to ensure string is valid now, rather than on lambda execution.
miningBeneficiary = Address.fromHexString(ibftConfig.getMiningBeneficiary().get());
miningBeneficiary = Address.fromHexString(configOptions.getMiningBeneficiary().get());
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException(
"Mining beneficiary in config is not a valid ethereum address", e);

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import org.hyperledger.besu.consensus.common.VoteType;
import org.hyperledger.besu.ethereum.core.Address;

View File

@@ -12,10 +12,10 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.blockcreation;
package org.hyperledger.besu.consensus.common.bft.blockcreation;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.blockcreation.AbstractBlockCreator;
import org.hyperledger.besu.ethereum.blockcreation.GasLimitCalculator;
@@ -29,9 +29,9 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
// This class is responsible for creating a block without committer seals (basically it was just
// too hard to coordinate with the state machine).
public class IbftBlockCreator extends AbstractBlockCreator {
public class BftBlockCreator extends AbstractBlockCreator {
public IbftBlockCreator(
public BftBlockCreator(
final Address localAddress,
final ExtraDataCalculator extraDataCalculator,
final PendingTransactions pendingTransactions,
@@ -60,9 +60,9 @@ public class IbftBlockCreator extends AbstractBlockCreator {
final BlockHeaderBuilder builder =
BlockHeaderBuilder.create()
.populateFrom(sealableBlockHeader)
.mixHash(IbftHelpers.EXPECTED_MIX_HASH)
.mixHash(BftHelpers.EXPECTED_MIX_HASH)
.nonce(0L)
.blockHeaderFunctions(IbftBlockHeaderFunctions.forCommittedSeal());
.blockHeaderFunctions(BftBlockHeaderFunctions.forCommittedSeal());
return builder.buildBlockHeader();
}

View File

@@ -12,14 +12,14 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.blockcreation;
package org.hyperledger.besu.consensus.common.bft.blockcreation;
import org.hyperledger.besu.consensus.common.ConsensusHelpers;
import org.hyperledger.besu.consensus.common.ValidatorVote;
import org.hyperledger.besu.consensus.common.VoteTally;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.Vote;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.Vote;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.blockcreation.GasLimitCalculator;
import org.hyperledger.besu.ethereum.core.Address;
@@ -36,7 +36,7 @@ import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
public class IbftBlockCreatorFactory {
public class BftBlockCreatorFactory {
private final GasLimitCalculator gasLimitCalculator;
private final PendingTransactions pendingTransactions;
@@ -49,7 +49,7 @@ public class IbftBlockCreatorFactory {
private volatile Wei minTransactionGasPrice;
private volatile Double minBlockOccupancyRatio;
public IbftBlockCreatorFactory(
public BftBlockCreatorFactory(
final GasLimitCalculator gasLimitCalculator,
final PendingTransactions pendingTransactions,
final ProtocolContext protocolContext,
@@ -68,8 +68,8 @@ public class IbftBlockCreatorFactory {
this.miningBeneficiary = miningBeneficiary;
}
public IbftBlockCreator create(final BlockHeader parentHeader, final int round) {
return new IbftBlockCreator(
public BftBlockCreator create(final BlockHeader parentHeader, final int round) {
return new BftBlockCreator(
localAddress,
ph -> createExtraData(round, ph),
pendingTransactions,
@@ -97,21 +97,21 @@ public class IbftBlockCreatorFactory {
public Bytes createExtraData(final int round, final BlockHeader parentHeader) {
final VoteTally voteTally =
protocolContext
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteTallyCache()
.getVoteTallyAfterBlock(parentHeader);
final Optional<ValidatorVote> proposal =
protocolContext
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteProposer()
.getVote(localAddress, voteTally);
final List<Address> validators = new ArrayList<>(voteTally.getValidators());
final IbftExtraData extraData =
new IbftExtraData(
ConsensusHelpers.zeroLeftPad(vanityData, IbftExtraData.EXTRA_VANITY_LENGTH),
final BftExtraData extraData =
new BftExtraData(
ConsensusHelpers.zeroLeftPad(vanityData, BftExtraData.EXTRA_VANITY_LENGTH),
Collections.emptyList(),
toVote(proposal),
round,
@@ -120,7 +120,7 @@ public class IbftBlockCreatorFactory {
return extraData.encode();
}
void changeTargetGasLimit(final Long targetGasLimit) {
public void changeTargetGasLimit(final Long targetGasLimit) {
gasLimitCalculator.changeTargetGasLimit(targetGasLimit);
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.blockcreation;
package org.hyperledger.besu.consensus.common.bft.blockcreation;
import static com.google.common.base.Preconditions.checkArgument;

View File

@@ -12,10 +12,10 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import org.hyperledger.besu.consensus.common.ValidatorProvider;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -30,9 +30,9 @@ import org.apache.logging.log4j.Logger;
* Ensures that the coinbase (which corresponds to the block proposer) is included in the list of
* validators
*/
public class IbftCoinbaseValidationRule implements AttachedBlockHeaderValidationRule {
public class BftCoinbaseValidationRule implements AttachedBlockHeaderValidationRule {
private static final Logger LOGGER = LogManager.getLogger(IbftCoinbaseValidationRule.class);
private static final Logger LOGGER = LogManager.getLogger(BftCoinbaseValidationRule.class);
@Override
public boolean validate(
@@ -40,7 +40,7 @@ public class IbftCoinbaseValidationRule implements AttachedBlockHeaderValidation
final ValidatorProvider validatorProvider =
context
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteTallyCache()
.getVoteTallyAfterBlock(parent);
final Address proposer = header.getCoinbase();

View File

@@ -12,14 +12,14 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import static org.hyperledger.besu.consensus.ibft.IbftHelpers.calculateRequiredValidatorQuorum;
import static org.hyperledger.besu.consensus.common.bft.BftHelpers.calculateRequiredValidatorQuorum;
import org.hyperledger.besu.consensus.common.ValidatorProvider;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -39,7 +39,7 @@ import org.apache.logging.log4j.Logger;
*
* <p>This also ensures sufficient commit seals exist in the block to make it valid.
*/
public class IbftCommitSealsValidationRule implements AttachedBlockHeaderValidationRule {
public class BftCommitSealsValidationRule implements AttachedBlockHeaderValidationRule {
private static final Logger LOGGER = LogManager.getLogger();
@@ -48,13 +48,13 @@ public class IbftCommitSealsValidationRule implements AttachedBlockHeaderValidat
final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext) {
final ValidatorProvider validatorProvider =
protocolContext
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteTallyCache()
.getVoteTallyAfterBlock(parent);
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
final BftExtraData bftExtraData = BftExtraData.decode(header);
final List<Address> committers =
IbftBlockHashing.recoverCommitterAddresses(header, ibftExtraData);
BftBlockHashing.recoverCommitterAddresses(header, bftExtraData);
final List<Address> committersWithoutDuplicates = new ArrayList<>(new HashSet<>(committers));
if (committers.size() != committersWithoutDuplicates.size()) {

View File

@@ -12,11 +12,11 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import org.hyperledger.besu.consensus.common.ValidatorProvider;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -35,7 +35,7 @@ import org.apache.logging.log4j.Logger;
* Ensures the Validators listed in the block header match that tracked in memory (which was in-turn
* created by tracking votes included on the block chain).
*/
public class IbftValidatorsValidationRule implements AttachedBlockHeaderValidationRule {
public class BftValidatorsValidationRule implements AttachedBlockHeaderValidationRule {
private static final Logger LOGGER = LogManager.getLogger();
@@ -45,34 +45,34 @@ public class IbftValidatorsValidationRule implements AttachedBlockHeaderValidati
try {
final ValidatorProvider validatorProvider =
context
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteTallyCache()
.getVoteTallyAfterBlock(parent);
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
final BftExtraData bftExtraData = BftExtraData.decode(header);
final NavigableSet<Address> sortedReportedValidators =
new TreeSet<>(ibftExtraData.getValidators());
new TreeSet<>(bftExtraData.getValidators());
if (!Iterables.elementsEqual(ibftExtraData.getValidators(), sortedReportedValidators)) {
LOGGER.info(
"Invalid block header: Validators are not sorted in ascending order. Expected {} but got {}.",
if (!Iterables.elementsEqual(bftExtraData.getValidators(), sortedReportedValidators)) {
LOGGER.trace(
"Validators are not sorted in ascending order. Expected {} but got {}.",
sortedReportedValidators,
ibftExtraData.getValidators());
bftExtraData.getValidators());
return false;
}
final Collection<Address> storedValidators = validatorProvider.getValidators();
if (!Iterables.elementsEqual(ibftExtraData.getValidators(), storedValidators)) {
LOGGER.info(
"Invalid block header: Incorrect validators. Expected {} but got {}.",
if (!Iterables.elementsEqual(bftExtraData.getValidators(), storedValidators)) {
LOGGER.trace(
"Incorrect validators. Expected {} but got {}.",
storedValidators,
ibftExtraData.getValidators());
bftExtraData.getValidators());
return false;
}
} catch (final RLPException ex) {
LOGGER.info(
"Invalid block header: ExtraData field was unable to be deserialised into an IBFT Struct.",
"Invalid block header: ExtraData field was unable to be deserialized into an BFT Struct.",
ex);
return false;
} catch (final IllegalArgumentException ex) {

View File

@@ -12,9 +12,9 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.mainnet.AttachedBlockHeaderValidationRule;
@@ -22,17 +22,17 @@ import org.hyperledger.besu.ethereum.mainnet.AttachedBlockHeaderValidationRule;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class IbftVanityDataValidationRule implements AttachedBlockHeaderValidationRule {
public class BftVanityDataValidationRule implements AttachedBlockHeaderValidationRule {
private static final Logger LOG = LogManager.getLogger();
@Override
public boolean validate(
final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext) {
final IbftExtraData extraData = IbftExtraData.decode(header);
final BftExtraData extraData = BftExtraData.decode(header);
if (extraData.getVanityData().size() != IbftExtraData.EXTRA_VANITY_LENGTH) {
LOG.info("Invalid block header: Ibft Extra Data does not contain 32 bytes of vanity data.");
if (extraData.getVanityData().size() != BftExtraData.EXTRA_VANITY_LENGTH) {
LOG.info("Invalid block header: Bft Extra Data does not contain 32 bytes of vanity data.");
return false;
}
return true;

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -26,17 +26,17 @@ import org.hyperledger.besu.ethereum.core.Address;
import java.util.Collection;
public class IbftContextBuilder {
public class BftContextBuilder {
public static IbftContext setupContextWithValidators(final Collection<Address> validators) {
final IbftContext ibftContext = mock(IbftContext.class, withSettings().lenient());
public static BftContext setupContextWithValidators(final Collection<Address> validators) {
final BftContext bftContext = mock(BftContext.class, withSettings().lenient());
final VoteTallyCache mockCache = mock(VoteTallyCache.class, withSettings().lenient());
final VoteTally mockVoteTally = mock(VoteTally.class, withSettings().lenient());
when(ibftContext.getVoteTallyCache()).thenReturn(mockCache);
when(bftContext.getVoteTallyCache()).thenReturn(mockCache);
when(mockCache.getVoteTallyAfterBlock(any())).thenReturn(mockVoteTally);
when(mockVoteTally.getValidators()).thenReturn(validators);
when(ibftContext.getVoteProposer()).thenReturn(new VoteProposer());
when(bftContext.getVoteProposer()).thenReturn(new VoteProposer());
return ibftContext;
return bftContext;
}
}

View File

@@ -12,12 +12,12 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
@@ -38,14 +38,14 @@ import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftBlockHeaderValidationRulesetFactoryTest {
public class BftBlockHeaderValidationRulesetFactoryTest {
private final ProtocolContext protocolContext(final Collection<Address> validators) {
return new ProtocolContext(null, null, setupContextWithValidators(validators));
}
@Test
public void ibftValidateHeaderPasses() {
public void bftValidateHeaderPasses() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -57,7 +57,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerNodeKey, validators, parentHeader).buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -66,7 +66,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnExtraData() {
public void bftValidateHeaderFailsOnExtraData() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -78,7 +78,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerNodeKey, emptyList(), parentHeader).buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -87,7 +87,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnCoinbaseData() {
public void bftValidateHeaderFailsOnCoinbaseData() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -104,7 +104,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -113,7 +113,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnNonce() {
public void bftValidateHeaderFailsOnNonce() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -125,7 +125,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerNodeKey, validators, parentHeader).nonce(3).buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -134,7 +134,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnTimestamp() {
public void bftValidateHeaderFailsOnTimestamp() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -148,7 +148,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -157,7 +157,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnMixHash() {
public void bftValidateHeaderFailsOnMixHash() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -171,7 +171,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -180,7 +180,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnOmmers() {
public void bftValidateHeaderFailsOnOmmers() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -194,7 +194,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -203,7 +203,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnDifficulty() {
public void bftValidateHeaderFailsOnDifficulty() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -217,7 +217,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -226,7 +226,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnAncestor() {
public void bftValidateHeaderFailsOnAncestor() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -238,7 +238,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerNodeKey, validators, null).buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -247,7 +247,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnGasUsage() {
public void bftValidateHeaderFailsOnGasUsage() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -262,7 +262,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -271,7 +271,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
}
@Test
public void ibftValidateHeaderFailsOnGasLimitRange() {
public void bftValidateHeaderFailsOnGasLimitRange() {
final NodeKey proposerNodeKey = NodeKeyUtils.generate();
final Address proposerAddress = Util.publicKeyToAddress(proposerNodeKey.getPublicKey());
@@ -285,7 +285,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5).build();
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(5).build();
assertThat(
validator.validateHeader(
@@ -313,16 +313,16 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
builder.difficulty(Difficulty.ONE);
builder.coinbase(Util.publicKeyToAddress(proposerNodeKey.getPublicKey()));
final IbftExtraData ibftExtraData =
IbftExtraDataFixture.createExtraData(
final BftExtraData bftExtraData =
BftExtraDataFixture.createExtraData(
builder.buildHeader(),
Bytes.wrap(new byte[IbftExtraData.EXTRA_VANITY_LENGTH]),
Bytes.wrap(new byte[BftExtraData.EXTRA_VANITY_LENGTH]),
Optional.of(Vote.authVote(Address.fromHexString("1"))),
validators,
singletonList(proposerNodeKey),
0xDEADBEEF);
builder.extraData(ibftExtraData.encode());
builder.extraData(bftExtraData.encode());
return builder;
}
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static java.util.Collections.emptyList;
@@ -29,9 +29,9 @@ import java.util.stream.IntStream;
import org.apache.tuweni.bytes.Bytes;
public class IbftExtraDataFixture {
public class BftExtraDataFixture {
public static IbftExtraData createExtraData(
public static BftExtraData createExtraData(
final BlockHeader header,
final Bytes vanityData,
final Optional<Vote> vote,
@@ -41,7 +41,7 @@ public class IbftExtraDataFixture {
return createExtraData(header, vanityData, vote, validators, committerNodeKeys, 0);
}
public static IbftExtraData createExtraData(
public static BftExtraData createExtraData(
final BlockHeader header,
final Bytes vanityData,
final Optional<Vote> vote,
@@ -53,7 +53,7 @@ public class IbftExtraDataFixture {
header, vanityData, vote, validators, committerNodeKeys, roundNumber, false);
}
public static IbftExtraData createExtraData(
public static BftExtraData createExtraData(
final BlockHeader header,
final Bytes vanityData,
final Optional<Vote> vote,
@@ -62,8 +62,8 @@ public class IbftExtraDataFixture {
final int baseRoundNumber,
final boolean useDifferentRoundNumbersForCommittedSeals) {
final IbftExtraData ibftExtraDataNoCommittedSeals =
new IbftExtraData(vanityData, emptyList(), vote, baseRoundNumber, validators);
final BftExtraData bftExtraDataNoCommittedSeals =
new BftExtraData(vanityData, emptyList(), vote, baseRoundNumber, validators);
// if useDifferentRoundNumbersForCommittedSeals is true then each committed seal will be
// calculated for an extraData field with a different round number
@@ -73,30 +73,30 @@ public class IbftExtraDataFixture {
i -> {
final int round =
useDifferentRoundNumbersForCommittedSeals
? ibftExtraDataNoCommittedSeals.getRound() + i
: ibftExtraDataNoCommittedSeals.getRound();
? bftExtraDataNoCommittedSeals.getRound() + i
: bftExtraDataNoCommittedSeals.getRound();
IbftExtraData extraDataForCommittedSealCalculation =
new IbftExtraData(
ibftExtraDataNoCommittedSeals.getVanityData(),
BftExtraData extraDataForCommittedSealCalculation =
new BftExtraData(
bftExtraDataNoCommittedSeals.getVanityData(),
emptyList(),
ibftExtraDataNoCommittedSeals.getVote(),
bftExtraDataNoCommittedSeals.getVote(),
round,
ibftExtraDataNoCommittedSeals.getValidators());
bftExtraDataNoCommittedSeals.getValidators());
final Hash headerHashForCommitters =
IbftBlockHashing.calculateDataHashForCommittedSeal(
BftBlockHashing.calculateDataHashForCommittedSeal(
header, extraDataForCommittedSealCalculation);
return committerNodeKeys.get(i).sign(headerHashForCommitters);
})
.collect(Collectors.toList());
return new IbftExtraData(
ibftExtraDataNoCommittedSeals.getVanityData(),
return new BftExtraData(
bftExtraDataNoCommittedSeals.getVanityData(),
commitSeals,
ibftExtraDataNoCommittedSeals.getVote(),
ibftExtraDataNoCommittedSeals.getRound(),
ibftExtraDataNoCommittedSeals.getValidators());
bftExtraDataNoCommittedSeals.getVote(),
bftExtraDataNoCommittedSeals.getRound(),
bftExtraDataNoCommittedSeals.getValidators());
}
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -35,7 +35,7 @@ import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftExtraDataTest {
public class BftExtraDataTest {
private final String RAW_HEX_ENCODING_STRING =
"f8f1a00102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20ea9400000000000000000000000000000000000"
@@ -44,10 +44,10 @@ public class IbftExtraDataTest {
+ "0000000000000000000000000000000000a00b84100000000000000000000000000000000000000000000000000000000000000"
+ "0a000000000000000000000000000000000000000000000000000000000000000100";
private final IbftExtraData DECODED_EXTRA_DATA_FOR_RAW_HEX_ENCODING_STRING =
private final BftExtraData DECODED_EXTRA_DATA_FOR_RAW_HEX_ENCODING_STRING =
getDecodedExtraDataForRawHexEncodingString();
private static IbftExtraData getDecodedExtraDataForRawHexEncodingString() {
private static BftExtraData getDecodedExtraDataForRawHexEncodingString() {
final List<Address> validators =
Arrays.asList(Address.fromHexString("1"), Address.fromHexString("2"));
final Optional<Vote> vote = Optional.of(Vote.authVote(Address.fromHexString("1")));
@@ -61,7 +61,7 @@ public class IbftExtraDataTest {
final byte[] vanity_bytes = createNonEmptyVanityData();
final Bytes vanity_data = Bytes.wrap(vanity_bytes);
return new IbftExtraData(vanity_data, committerSeals, vote, round, validators);
return new BftExtraData(vanity_data, committerSeals, vote, round, validators);
}
@Test
@@ -91,7 +91,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
final IbftExtraData extraData = IbftExtraData.decodeRaw(bufferToInject);
final BftExtraData extraData = BftExtraData.decodeRaw(bufferToInject);
assertThat(extraData.getVanityData()).isEqualTo(vanity_data);
assertThat(extraData.getRound()).isEqualTo(round);
@@ -100,7 +100,7 @@ public class IbftExtraDataTest {
}
/**
* This test specifically verifies that {@link IbftExtraData#decode(BlockHeader)} uses {@link
* This test specifically verifies that {@link BftExtraData#decode(BlockHeader)} uses {@link
* RLPInput#readInt()} rather than {@link RLPInput#readIntScalar()} to decode the round number
*/
@Test
@@ -130,7 +130,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject))
assertThatThrownBy(() -> BftExtraData.decodeRaw(bufferToInject))
.isInstanceOf(RLPException.class);
}
@@ -158,7 +158,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
final IbftExtraData extraData = IbftExtraData.decodeRaw(bufferToInject);
final BftExtraData extraData = BftExtraData.decodeRaw(bufferToInject);
assertThat(extraData.getVanityData()).isEqualTo(vanity_data);
assertThat(extraData.getVote().isPresent()).isEqualTo(false);
@@ -178,10 +178,10 @@ public class IbftExtraDataTest {
final byte[] vanity_bytes = new byte[32];
final Bytes vanity_data = Bytes.wrap(vanity_bytes);
IbftExtraData expectedExtraData =
new IbftExtraData(vanity_data, committerSeals, vote, round, validators);
BftExtraData expectedExtraData =
new BftExtraData(vanity_data, committerSeals, vote, round, validators);
IbftExtraData actualExtraData = IbftExtraData.decodeRaw(expectedExtraData.encode());
BftExtraData actualExtraData = BftExtraData.decodeRaw(expectedExtraData.encode());
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@@ -211,7 +211,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
final IbftExtraData extraData = IbftExtraData.decodeRaw(bufferToInject);
final BftExtraData extraData = BftExtraData.decodeRaw(bufferToInject);
assertThat(extraData.getVanityData()).isEqualTo(vanity_data);
assertThat(extraData.getRound()).isEqualTo(round);
@@ -230,10 +230,10 @@ public class IbftExtraDataTest {
final byte[] vanity_bytes = new byte[32];
final Bytes vanity_data = Bytes.wrap(vanity_bytes);
IbftExtraData expectedExtraData =
new IbftExtraData(vanity_data, committerSeals, vote, round, validators);
BftExtraData expectedExtraData =
new BftExtraData(vanity_data, committerSeals, vote, round, validators);
IbftExtraData actualExtraData = IbftExtraData.decodeRaw(expectedExtraData.encode());
BftExtraData actualExtraData = BftExtraData.decodeRaw(expectedExtraData.encode());
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@@ -270,7 +270,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
final IbftExtraData extraData = IbftExtraData.decodeRaw(bufferToInject);
final BftExtraData extraData = BftExtraData.decodeRaw(bufferToInject);
assertThat(extraData.getVanityData()).isEqualTo(vanity_data);
assertThat(extraData.getVote())
@@ -295,10 +295,10 @@ public class IbftExtraDataTest {
final byte[] vanity_bytes = createNonEmptyVanityData();
final Bytes vanity_data = Bytes.wrap(vanity_bytes);
IbftExtraData expectedExtraData =
new IbftExtraData(vanity_data, committerSeals, vote, round, validators);
BftExtraData expectedExtraData =
new BftExtraData(vanity_data, committerSeals, vote, round, validators);
IbftExtraData actualExtraData = IbftExtraData.decodeRaw(expectedExtraData.encode());
BftExtraData actualExtraData = BftExtraData.decodeRaw(expectedExtraData.encode());
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@@ -313,10 +313,10 @@ public class IbftExtraDataTest {
@Test
public void decodingOfKnownRawHexStringMatchesKnowExtraDataObject() {
final IbftExtraData expectedExtraData = DECODED_EXTRA_DATA_FOR_RAW_HEX_ENCODING_STRING;
final BftExtraData expectedExtraData = DECODED_EXTRA_DATA_FOR_RAW_HEX_ENCODING_STRING;
Bytes rawDecoding = Bytes.fromHexString(RAW_HEX_ENCODING_STRING);
IbftExtraData actualExtraData = IbftExtraData.decodeRaw(rawDecoding);
BftExtraData actualExtraData = BftExtraData.decodeRaw(rawDecoding);
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@@ -350,7 +350,7 @@ public class IbftExtraDataTest {
Bytes expectedEncoding = encoder.encoded();
Bytes actualEncoding =
new IbftExtraData(vanity_data, committerSeals, vote, round, validators)
new BftExtraData(vanity_data, committerSeals, vote, round, validators)
.encodeWithoutCommitSeals();
assertThat(actualEncoding).isEqualTo(expectedEncoding);
@@ -384,7 +384,7 @@ public class IbftExtraDataTest {
Bytes expectedEncoding = encoder.encoded();
Bytes actualEncoding =
new IbftExtraData(vanity_data, committerSeals, vote, round, validators)
new BftExtraData(vanity_data, committerSeals, vote, round, validators)
.encodeWithoutCommitSealsAndRoundNumber();
assertThat(actualEncoding).isEqualTo(expectedEncoding);
@@ -416,7 +416,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject))
assertThatThrownBy(() -> BftExtraData.decodeRaw(bufferToInject))
.isInstanceOf(RLPException.class);
}
@@ -453,7 +453,7 @@ public class IbftExtraDataTest {
final Bytes bufferToInject = encoder.encoded();
assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject))
assertThatThrownBy(() -> BftExtraData.decodeRaw(bufferToInject))
.isInstanceOf(RLPException.class);
}
@@ -461,9 +461,9 @@ public class IbftExtraDataTest {
public void emptyExtraDataThrowsException() {
final Bytes bufferToInject = Bytes.EMPTY;
assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject))
assertThatThrownBy(() -> BftExtraData.decodeRaw(bufferToInject))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid Bytes supplied - Ibft Extra Data required.");
.hasMessage("Invalid Bytes supplied - Bft Extra Data required.");
}
private static byte[] createNonEmptyVanityData() {

View File

@@ -0,0 +1,66 @@
/*
* Copyright ConsenSys AG.
*
* 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.common.bft;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class BftHelpersTest {
@Test
public void calculateRequiredValidatorQuorum1Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(1)).isEqualTo(1);
}
@Test
public void calculateRequiredValidatorQuorum2Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(2)).isEqualTo(2);
}
@Test
public void calculateRequiredValidatorQuorum3Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(3)).isEqualTo(2);
}
@Test
public void calculateRequiredValidatorQuorum4Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(4)).isEqualTo(3);
}
@Test
public void calculateRequiredValidatorQuorum5Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(5)).isEqualTo(4);
}
@Test
public void calculateRequiredValidatorQuorum7Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(7)).isEqualTo(5);
}
@Test
public void calculateRequiredValidatorQuorum10Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(10)).isEqualTo(7);
}
@Test
public void calculateRequiredValidatorQuorum15Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(15)).isEqualTo(10);
}
@Test
public void calculateRequiredValidatorQuorum20Validator() {
Assertions.assertThat(BftHelpers.calculateRequiredValidatorQuorum(20)).isEqualTo(14);
}
}

View File

@@ -13,15 +13,15 @@
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.config.BftConfigOptions;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.config.IbftConfigOptions;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Wei;
@@ -33,7 +33,7 @@ import java.util.Optional;
import org.junit.Test;
public class IbftProtocolScheduleTest {
public class BftProtocolScheduleTest {
private final GenesisConfigOptions genesisConfig = mock(GenesisConfigOptions.class);
@@ -41,14 +41,14 @@ public class IbftProtocolScheduleTest {
public void ensureBlockRewardAndMiningBeneficiaryInProtocolSpecMatchConfig() {
final BigInteger arbitraryBlockReward = BigInteger.valueOf(5);
final String miningBeneficiary = Address.fromHexString("0x1").toString();
final IbftConfigOptions ibftConfig = mock(IbftConfigOptions.class);
when(ibftConfig.getMiningBeneficiary()).thenReturn(Optional.of(miningBeneficiary));
when(ibftConfig.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(ibftConfig.getEpochLength()).thenReturn(3000L);
final BftConfigOptions configOptions = mock(BftConfigOptions.class);
when(configOptions.getMiningBeneficiary()).thenReturn(Optional.of(miningBeneficiary));
when(configOptions.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(configOptions.getEpochLength()).thenReturn(3000L);
when(genesisConfig.getIbft2ConfigOptions()).thenReturn(ibftConfig);
when(genesisConfig.getBftConfigOptions()).thenReturn(configOptions);
final ProtocolSchedule schedule = IbftProtocolSchedule.create(genesisConfig);
final ProtocolSchedule schedule = BftProtocolSchedule.create(genesisConfig);
final ProtocolSpec spec = schedule.getByBlockNumber(1);
spec.getBlockReward();
@@ -61,13 +61,13 @@ public class IbftProtocolScheduleTest {
@Test
public void illegalMiningBeneficiaryStringThrowsException() {
final String miningBeneficiary = "notHexStringOfTwentyBytes";
final IbftConfigOptions ibftConfig = mock(IbftConfigOptions.class);
when(ibftConfig.getMiningBeneficiary()).thenReturn(Optional.of(miningBeneficiary));
when(genesisConfig.getIbft2ConfigOptions()).thenReturn(ibftConfig);
when(ibftConfig.getEpochLength()).thenReturn(3000L);
when(ibftConfig.getBlockRewardWei()).thenReturn(BigInteger.ZERO);
final BftConfigOptions configOptions = mock(BftConfigOptions.class);
when(configOptions.getMiningBeneficiary()).thenReturn(Optional.of(miningBeneficiary));
when(genesisConfig.getBftConfigOptions()).thenReturn(configOptions);
when(configOptions.getEpochLength()).thenReturn(3000L);
when(configOptions.getBlockRewardWei()).thenReturn(BigInteger.ZERO);
assertThatThrownBy(() -> IbftProtocolSchedule.create(genesisConfig))
assertThatThrownBy(() -> BftProtocolSchedule.create(genesisConfig))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Mining beneficiary in config is not a valid ethereum address");
}
@@ -75,13 +75,13 @@ public class IbftProtocolScheduleTest {
@Test
public void missingMiningBeneficiaryInConfigWillPayCoinbaseInHeader() {
final BigInteger arbitraryBlockReward = BigInteger.valueOf(3);
final IbftConfigOptions ibftConfig = mock(IbftConfigOptions.class);
when(ibftConfig.getMiningBeneficiary()).thenReturn(Optional.empty());
when(ibftConfig.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(ibftConfig.getEpochLength()).thenReturn(3000L);
when(genesisConfig.getIbft2ConfigOptions()).thenReturn(ibftConfig);
final BftConfigOptions configOptions = mock(BftConfigOptions.class);
when(configOptions.getMiningBeneficiary()).thenReturn(Optional.empty());
when(configOptions.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(configOptions.getEpochLength()).thenReturn(3000L);
when(genesisConfig.getBftConfigOptions()).thenReturn(configOptions);
final ProtocolSchedule schedule = IbftProtocolSchedule.create(genesisConfig);
final ProtocolSchedule schedule = BftProtocolSchedule.create(genesisConfig);
final ProtocolSpec spec = schedule.getByBlockNumber(1);
final Address headerCoinbase = Address.fromHexString("0x123");
@@ -96,27 +96,27 @@ public class IbftProtocolScheduleTest {
@Test
public void negativeBlockRewardThrowsException() {
final BigInteger arbitraryBlockReward = BigInteger.valueOf(-3);
final IbftConfigOptions ibftConfig = mock(IbftConfigOptions.class);
when(ibftConfig.getMiningBeneficiary()).thenReturn(Optional.empty());
when(ibftConfig.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(ibftConfig.getEpochLength()).thenReturn(3000L);
when(genesisConfig.getIbft2ConfigOptions()).thenReturn(ibftConfig);
final BftConfigOptions configOptions = mock(BftConfigOptions.class);
when(configOptions.getMiningBeneficiary()).thenReturn(Optional.empty());
when(configOptions.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(configOptions.getEpochLength()).thenReturn(3000L);
when(genesisConfig.getBftConfigOptions()).thenReturn(configOptions);
assertThatThrownBy(() -> IbftProtocolSchedule.create(genesisConfig))
assertThatThrownBy(() -> BftProtocolSchedule.create(genesisConfig))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Ibft2 Block reward in config cannot be negative");
.hasMessage("Bft Block reward in config cannot be negative");
}
@Test
public void zeroEpochLengthThrowsException() {
final BigInteger arbitraryBlockReward = BigInteger.valueOf(3);
final IbftConfigOptions ibftConfig = mock(IbftConfigOptions.class);
when(ibftConfig.getMiningBeneficiary()).thenReturn(Optional.empty());
when(ibftConfig.getEpochLength()).thenReturn(0L);
when(ibftConfig.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(genesisConfig.getIbft2ConfigOptions()).thenReturn(ibftConfig);
final BftConfigOptions configOptions = mock(BftConfigOptions.class);
when(configOptions.getMiningBeneficiary()).thenReturn(Optional.empty());
when(configOptions.getEpochLength()).thenReturn(0L);
when(configOptions.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(genesisConfig.getBftConfigOptions()).thenReturn(configOptions);
assertThatThrownBy(() -> IbftProtocolSchedule.create(genesisConfig))
assertThatThrownBy(() -> BftProtocolSchedule.create(genesisConfig))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Epoch length in config must be greater than zero");
}
@@ -124,13 +124,13 @@ public class IbftProtocolScheduleTest {
@Test
public void negativeEpochLengthThrowsException() {
final BigInteger arbitraryBlockReward = BigInteger.valueOf(3);
final IbftConfigOptions ibftConfig = mock(IbftConfigOptions.class);
when(ibftConfig.getMiningBeneficiary()).thenReturn(Optional.empty());
when(ibftConfig.getEpochLength()).thenReturn(-3000L);
when(ibftConfig.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(genesisConfig.getIbft2ConfigOptions()).thenReturn(ibftConfig);
final BftConfigOptions configOptions = mock(BftConfigOptions.class);
when(configOptions.getMiningBeneficiary()).thenReturn(Optional.empty());
when(configOptions.getEpochLength()).thenReturn(-3000L);
when(configOptions.getBlockRewardWei()).thenReturn(arbitraryBlockReward);
when(genesisConfig.getBftConfigOptions()).thenReturn(configOptions);
assertThatThrownBy(() -> IbftProtocolSchedule.create(genesisConfig))
assertThatThrownBy(() -> BftProtocolSchedule.create(genesisConfig))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Epoch length in config must be greater than zero");
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft;
package org.hyperledger.besu.consensus.common.bft;
import static org.assertj.core.api.Java6Assertions.assertThat;

View File

@@ -12,20 +12,20 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.blockcreation;
package org.hyperledger.besu.consensus.common.bft.blockcreation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.ethereum.core.InMemoryStorageProvider.createInMemoryWorldStateArchive;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderValidationRulesetFactory;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.IbftProtocolSchedule;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderValidationRulesetFactory;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftProtocolSchedule;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.Address;
@@ -51,7 +51,7 @@ import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftBlockCreatorTest {
public class BftBlockCreatorTest {
private final MetricsSystem metricsSystem = new NoOpMetricsSystem();
@Test
@@ -73,7 +73,7 @@ public class IbftBlockCreatorTest {
}
final ProtocolSchedule protocolSchedule =
IbftProtocolSchedule.create(
BftProtocolSchedule.create(
GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}")
.getConfigOptions());
final ProtocolContext protContext =
@@ -92,11 +92,11 @@ public class IbftBlockCreatorTest {
blockchain::getChainHeadHeader,
TransactionPoolConfiguration.DEFAULT_PRICE_BUMP);
final IbftBlockCreator blockCreator =
new IbftBlockCreator(
final BftBlockCreator blockCreator =
new BftBlockCreator(
initialValidatorList.get(0),
parent ->
new IbftExtraData(
new BftExtraData(
Bytes.wrap(new byte[32]),
Collections.emptyList(),
Optional.empty(),
@@ -116,7 +116,7 @@ public class IbftBlockCreatorTest {
final Block block = blockCreator.createBlock(parentHeader.getTimestamp() + 1);
final BlockHeaderValidator rules =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(secondsBetweenBlocks)
BftBlockHeaderValidationRulesetFactory.bftBlockHeaderValidator(secondsBetweenBlocks)
.build();
// NOTE: The header will not contain commit seals, so can only do light validation on header.
@@ -127,8 +127,8 @@ public class IbftBlockCreatorTest {
assertThat(validationResult).isTrue();
final BlockHeader header = block.getHeader();
final IbftExtraData extraData = IbftExtraData.decode(header);
final BftExtraData extraData = BftExtraData.decode(header);
assertThat(block.getHash())
.isEqualTo(IbftBlockHashing.calculateDataHashForCommittedSeal(header, extraData));
.isEqualTo(BftBlockHashing.calculateDataHashForCommittedSeal(header, extraData));
}
}

View File

@@ -12,7 +12,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.blockcreation;
package org.hyperledger.besu.consensus.common.bft.blockcreation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;

View File

@@ -12,14 +12,14 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.IbftExtraDataFixture;
import org.hyperledger.besu.consensus.ibft.Vote;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraDataFixture;
import org.hyperledger.besu.consensus.common.bft.Vote;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
import org.hyperledger.besu.ethereum.ProtocolContext;
@@ -36,7 +36,7 @@ import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftCoinbaseValidationRuleTest {
public class BftCoinbaseValidationRuleTest {
public static BlockHeader createProposedBlockHeader(
final NodeKey proposerNodeKey,
@@ -48,15 +48,15 @@ public class IbftCoinbaseValidationRuleTest {
builder.coinbase(Util.publicKeyToAddress(proposerNodeKey.getPublicKey()));
final BlockHeader header = builder.buildHeader();
final IbftExtraData ibftExtraData =
IbftExtraDataFixture.createExtraData(
final BftExtraData bftExtraData =
BftExtraDataFixture.createExtraData(
header,
Bytes.wrap(new byte[IbftExtraData.EXTRA_VANITY_LENGTH]),
Bytes.wrap(new byte[BftExtraData.EXTRA_VANITY_LENGTH]),
Optional.of(Vote.authVote(Address.fromHexString("1"))),
validators,
committerNodeKeys);
builder.extraData(ibftExtraData.encode());
builder.extraData(bftExtraData.encode());
return builder.buildHeader();
}
@@ -73,7 +73,7 @@ public class IbftCoinbaseValidationRuleTest {
final ProtocolContext context =
new ProtocolContext(null, null, setupContextWithValidators(validators));
final IbftCoinbaseValidationRule coinbaseValidationRule = new IbftCoinbaseValidationRule();
final BftCoinbaseValidationRule coinbaseValidationRule = new BftCoinbaseValidationRule();
BlockHeader header = createProposedBlockHeader(proposerNodeKey, validators, committers);
@@ -95,7 +95,7 @@ public class IbftCoinbaseValidationRuleTest {
final ProtocolContext context =
new ProtocolContext(null, null, setupContextWithValidators(validators));
final IbftCoinbaseValidationRule coinbaseValidationRule = new IbftCoinbaseValidationRule();
final BftCoinbaseValidationRule coinbaseValidationRule = new BftCoinbaseValidationRule();
BlockHeader header = createProposedBlockHeader(proposerNodeKey, validators, committers);

View File

@@ -12,15 +12,15 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.ibft.headervalidationrules.HeaderValidationTestHelpers.createProposedBlockHeader;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.headervalidationrules.HeaderValidationTestHelpers.createProposedBlockHeader;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
import org.hyperledger.besu.ethereum.ProtocolContext;
@@ -37,10 +37,10 @@ import java.util.stream.IntStream;
import com.google.common.collect.Lists;
import org.junit.Test;
public class IbftCommitSealsValidationRuleTest {
public class BftCommitSealsValidationRuleTest {
private final IbftCommitSealsValidationRule commitSealsValidationRule =
new IbftCommitSealsValidationRule();
private final BftCommitSealsValidationRule commitSealsValidationRule =
new BftCommitSealsValidationRule();
@Test
public void correctlyConstructedHeaderPassesValidation() {
@@ -73,8 +73,8 @@ public class IbftCommitSealsValidationRuleTest {
final BlockHeader header = createProposedBlockHeader(validators, emptyList(), false);
// Note that no committer seals are in the header's IBFT extra data.
final IbftExtraData headerExtraData = IbftExtraData.decode(header);
// Note that no committer seals are in the header's BFT extra data.
final BftExtraData headerExtraData = BftExtraData.decode(header);
assertThat(headerExtraData.getSeals().size()).isEqualTo(0);
assertThat(commitSealsValidationRule.validate(header, null, context)).isFalse();

View File

@@ -12,11 +12,11 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address;
@@ -28,10 +28,10 @@ import java.util.List;
import com.google.common.collect.Lists;
import org.junit.Test;
public class IbftValidatorsValidationRuleTest {
public class BftValidatorsValidationRuleTest {
private final IbftValidatorsValidationRule validatorsValidationRule =
new IbftValidatorsValidationRule();
private final BftValidatorsValidationRule validatorsValidationRule =
new BftValidatorsValidationRule();
@Test
public void correctlyConstructedHeaderPassesValidation() {

View File

@@ -12,22 +12,22 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftVanityDataValidationRuleTest {
public class BftVanityDataValidationRuleTest {
private final IbftVanityDataValidationRule validationRule = new IbftVanityDataValidationRule();
private final BftVanityDataValidationRule validationRule = new BftVanityDataValidationRule();
@Test
public void testCases() {
@@ -38,9 +38,8 @@ public class IbftVanityDataValidationRuleTest {
}
public boolean headerWithVanityDataOfSize(final int extraDataSize) {
final IbftExtraData extraData =
new IbftExtraData(
Bytes.wrap(new byte[extraDataSize]), emptyList(), empty(), 0, emptyList());
final BftExtraData extraData =
new BftExtraData(Bytes.wrap(new byte[extraDataSize]), emptyList(), empty(), 0, emptyList());
final BlockHeader header =
new BlockHeaderTestFixture().extraData(extraData.encode()).buildHeader();

View File

@@ -12,11 +12,11 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.ibft.headervalidationrules;
package org.hyperledger.besu.consensus.common.bft.headervalidationrules;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.IbftExtraDataFixture;
import org.hyperledger.besu.consensus.ibft.Vote;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftExtraDataFixture;
import org.hyperledger.besu.consensus.common.bft.Vote;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -39,17 +39,17 @@ public class HeaderValidationTestHelpers {
final BlockHeader header = builder.buildHeader();
final IbftExtraData ibftExtraData =
IbftExtraDataFixture.createExtraData(
final BftExtraData bftExtraData =
BftExtraDataFixture.createExtraData(
header,
Bytes.wrap(new byte[IbftExtraData.EXTRA_VANITY_LENGTH]),
Bytes.wrap(new byte[BftExtraData.EXTRA_VANITY_LENGTH]),
Optional.of(Vote.authVote(Address.fromHexString("1"))),
validators,
committerNodeKeys,
BASE_ROUND_NUMBER,
useDifferentRoundNumbersForCommittedSeals);
builder.extraData(ibftExtraData.encode());
builder.extraData(bftExtraData.encode());
return builder.buildHeader();
}
}

View File

@@ -28,8 +28,8 @@ jar {
}
dependencies {
implementation project(':config')
implementation project(':consensus:common')
implementation project(':config')
implementation project(':crypto')
implementation project(':ethereum:api')
implementation project(':ethereum:blockcreation')
@@ -50,10 +50,12 @@ dependencies {
testImplementation project(path: ':crypto', configuration: 'testSupportArtifacts')
testImplementation project(path: ':config', configuration: 'testSupportArtifacts')
testImplementation project(path: ':consensus:common', configuration: 'testArtifacts')
testImplementation project(path: ':consensus:common', configuration: 'testSupportArtifacts')
testImplementation project(path: ':ethereum:core', configuration: 'testSupportArtifacts')
testImplementation project(':metrics:core')
testImplementation project(':testutil')
integrationTestImplementation project(path: ':consensus:common', configuration: 'testSupportArtifacts')
integrationTestImplementation project(path: ':crypto', configuration: 'testSupportArtifacts')
integrationTestImplementation project(':metrics:core')
integrationTestImplementation project(':testutil')
@@ -66,9 +68,4 @@ dependencies {
testImplementation 'org.awaitility:awaitility'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
testSupportImplementation 'org.mockito:mockito-core'
}
artifacts { testSupportArtifacts testSupportJar }

View File

@@ -14,10 +14,10 @@
*/
package org.hyperledger.besu.consensus.ibft.support;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.payload.CommitPayload;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
@@ -34,11 +34,11 @@ public class IntegrationTestHelpers {
public static SignedData<CommitPayload> createSignedCommitPayload(
final ConsensusRoundIdentifier roundId, final Block block, final NodeKey nodeKey) {
final IbftExtraData extraData = IbftExtraData.decode(block.getHeader());
final BftExtraData extraData = BftExtraData.decode(block.getHeader());
final Signature commitSeal =
nodeKey.sign(
IbftBlockHashing.calculateDataHashForCommittedSeal(block.getHeader(), extraData));
BftBlockHashing.calculateDataHashForCommittedSeal(block.getHeader(), extraData));
final MessageFactory messageFactory = new MessageFactory(nodeKey);

View File

@@ -25,25 +25,25 @@ import org.hyperledger.besu.consensus.common.EpochManager;
import org.hyperledger.besu.consensus.common.VoteProposer;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
import org.hyperledger.besu.consensus.common.VoteTallyUpdater;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.BftEventQueue;
import org.hyperledger.besu.consensus.common.bft.BftExecutors;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.BftProtocolSchedule;
import org.hyperledger.besu.consensus.common.bft.BlockTimer;
import org.hyperledger.besu.consensus.common.bft.EventMultiplexer;
import org.hyperledger.besu.consensus.common.bft.Gossiper;
import org.hyperledger.besu.consensus.common.bft.MessageTracker;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.common.bft.SynchronizerUpdater;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreatorFactory;
import org.hyperledger.besu.consensus.common.bft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.common.bft.statemachine.BftEventHandler;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.IbftGossip;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.IbftProtocolSchedule;
import org.hyperledger.besu.consensus.ibft.UniqueMessageMulticaster;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreatorFactory;
import org.hyperledger.besu.consensus.ibft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
import org.hyperledger.besu.consensus.ibft.statemachine.FutureMessageBuffer;
import org.hyperledger.besu.consensus.ibft.statemachine.IbftBlockHeightManagerFactory;
@@ -174,7 +174,7 @@ public class TestContextBuilder {
final Block genesisBlock = createGenesisBlock(networkNodes.getValidatorAddresses());
final MutableBlockchain blockChain =
createInMemoryBlockchain(genesisBlock, IbftBlockHeaderFunctions.forOnChainBlock());
createInMemoryBlockchain(genesisBlock, BftBlockHeaderFunctions.forOnChainBlock());
// Use a stubbed version of the multicaster, to prevent creating PeerConnections etc.
final StubValidatorMulticaster multicaster = new StubValidatorMulticaster();
@@ -234,11 +234,11 @@ public class TestContextBuilder {
private static Block createGenesisBlock(final Set<Address> validators) {
final Address coinbase = Iterables.get(validators, 0);
final BlockHeaderTestFixture headerTestFixture = new BlockHeaderTestFixture();
final IbftExtraData extraData =
new IbftExtraData(
final BftExtraData extraData =
new BftExtraData(
Bytes.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, validators);
headerTestFixture.extraData(extraData.encode());
headerTestFixture.mixHash(IbftHelpers.EXPECTED_MIX_HASH);
headerTestFixture.mixHash(BftHelpers.EXPECTED_MIX_HASH);
headerTestFixture.difficulty(Difficulty.ONE);
headerTestFixture.ommersHash(Hash.EMPTY_LIST_HASH);
headerTestFixture.nonce(0);
@@ -273,20 +273,20 @@ public class TestContextBuilder {
final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions();
genesisConfigOptions.byzantiumBlock(0);
final ProtocolSchedule protocolSchedule = IbftProtocolSchedule.create(genesisConfigOptions);
final ProtocolSchedule protocolSchedule = BftProtocolSchedule.create(genesisConfigOptions);
/////////////////////////////////////////////////////////////////////////////////////
// From here down is BASICALLY taken from IbftBesuController
final EpochManager epochManager = new EpochManager(EPOCH_LENGTH);
final BlockInterface blockInterface = new IbftBlockInterface();
final BlockInterface blockInterface = new BftBlockInterface();
final VoteTallyCache voteTallyCache =
new VoteTallyCache(
blockChain,
new VoteTallyUpdater(epochManager, blockInterface),
epochManager,
new IbftBlockInterface());
new BftBlockInterface());
final VoteProposer voteProposer = new VoteProposer();
@@ -294,7 +294,7 @@ public class TestContextBuilder {
new ProtocolContext(
blockChain,
worldStateArchive,
new IbftContext(voteTallyCache, voteProposer, epochManager, blockInterface));
new BftContext(voteTallyCache, voteProposer, epochManager, blockInterface));
final PendingTransactions pendingTransactions =
new PendingTransactions(
@@ -307,8 +307,8 @@ public class TestContextBuilder {
TransactionPoolConfiguration.DEFAULT_PRICE_BUMP);
final Address localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey());
final IbftBlockCreatorFactory blockCreatorFactory =
new IbftBlockCreatorFactory(
final BftBlockCreatorFactory blockCreatorFactory =
new BftBlockCreatorFactory(
(gasLimit) -> gasLimit,
pendingTransactions, // changed from IbftBesuController
protocolContext,
@@ -323,7 +323,7 @@ public class TestContextBuilder {
final BftExecutors bftExecutors = BftExecutors.create(new NoOpMetricsSystem());
final IbftFinalState finalState =
new IbftFinalState(
protocolContext.getConsensusState(IbftContext.class).getVoteTallyCache(),
protocolContext.getConsensusState(BftContext.class).getVoteTallyCache(),
nodeKey,
Util.publicKeyToAddress(nodeKey.getPublicKey()),
proposerSelector,

View File

@@ -18,9 +18,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.emptyList;
import static org.hyperledger.besu.consensus.ibft.support.IntegrationTestHelpers.createSignedCommitPayload;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.events.NewChainHead;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
@@ -62,7 +62,7 @@ public class FutureHeightTest {
public void messagesForFutureHeightAreBufferedUntilChainHeightCatchesUp() {
final Block currentHeightBlock = context.createBlockForProposalFromChainHead(0, 30);
final Block signedCurrentHeightBlock =
IbftHelpers.createSealedBlock(currentHeightBlock, peers.sign(currentHeightBlock.getHash()));
BftHelpers.createSealedBlock(currentHeightBlock, peers.sign(currentHeightBlock.getHash()));
final Block futureHeightBlock =
context.createBlockForProposal(signedCurrentHeightBlock.getHeader(), 0, 60);
@@ -109,7 +109,7 @@ public class FutureHeightTest {
public void messagesFromPreviousHeightAreDiscarded() {
final Block currentHeightBlock = context.createBlockForProposalFromChainHead(0, 30);
final Block signedCurrentHeightBlock =
IbftHelpers.createSealedBlock(currentHeightBlock, peers.sign(currentHeightBlock.getHash()));
BftHelpers.createSealedBlock(currentHeightBlock, peers.sign(currentHeightBlock.getHash()));
peers.getProposer().injectProposal(roundId, currentHeightBlock);
peers.getNonProposing(0).injectPrepare(roundId, currentHeightBlock.getHash());
@@ -163,12 +163,12 @@ public class FutureHeightTest {
public void correctMessagesAreExtractedFromFutureHeightBuffer() {
final Block currentHeightBlock = context.createBlockForProposalFromChainHead(0, 30);
final Block signedCurrentHeightBlock =
IbftHelpers.createSealedBlock(currentHeightBlock, peers.sign(currentHeightBlock.getHash()));
BftHelpers.createSealedBlock(currentHeightBlock, peers.sign(currentHeightBlock.getHash()));
final Block nextHeightBlock =
context.createBlockForProposal(signedCurrentHeightBlock.getHeader(), 0, 60);
final Block signedNextHeightBlock =
IbftHelpers.createSealedBlock(nextHeightBlock, peers.sign(nextHeightBlock.getHash()));
BftHelpers.createSealedBlock(nextHeightBlock, peers.sign(nextHeightBlock.getHash()));
final Block futureHeightBlock =
context.createBlockForProposal(signedNextHeightBlock.getHeader(), 0, 90);

View File

@@ -16,8 +16,8 @@ package org.hyperledger.besu.consensus.ibft.tests;
import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
@@ -61,7 +61,7 @@ public class FutureRoundTest {
public void messagesForFutureRoundAreNotActionedUntilRoundIsActive() {
final Block futureBlock =
context.createBlockForProposalFromChainHead(futureRoundId.getRoundNumber(), 60);
final int quorum = IbftHelpers.calculateRequiredValidatorQuorum(NETWORK_SIZE);
final int quorum = BftHelpers.calculateRequiredValidatorQuorum(NETWORK_SIZE);
final ConsensusRoundIdentifier subsequentRoundId = new ConsensusRoundIdentifier(1, 6);
final RoundSpecificPeers subsequentRoles = context.roundSpecificPeers(subsequentRoundId);

View File

@@ -17,9 +17,9 @@ package org.hyperledger.besu.consensus.ibft.tests;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.events.NewChainHead;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.messagedata.ProposalMessageData;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
@@ -158,7 +158,7 @@ public class GossipTest {
@Test
public void futureMessageGetGossipedLater() {
final Block signedCurrentHeightBlock =
IbftHelpers.createSealedBlock(block, peers.sign(block.getHash()));
BftHelpers.createSealedBlock(block, peers.sign(block.getHash()));
ConsensusRoundIdentifier futureRoundId = new ConsensusRoundIdentifier(2, 0);
Prepare futurePrepare = sender.injectPrepare(futureRoundId, block.getHash());

View File

@@ -18,10 +18,10 @@ import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.hyperledger.besu.consensus.ibft.support.IntegrationTestHelpers.createValidPreparedRoundArtifacts;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.events.RoundExpiry;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
import org.hyperledger.besu.consensus.ibft.messagewrappers.RoundChange;
@@ -241,7 +241,7 @@ public class RoundChangeTest {
final ValidatorPeer transmitter = peers.getNonProposing(0);
for (int i = 0; i < IbftHelpers.calculateRequiredValidatorQuorum(NETWORK_SIZE); i++) {
for (int i = 0; i < BftHelpers.calculateRequiredValidatorQuorum(NETWORK_SIZE); i++) {
transmitter.injectRoundChange(targetRound, empty());
}

View File

@@ -17,16 +17,16 @@ package org.hyperledger.besu.consensus.ibft.tests.round;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreator;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreator;
import org.hyperledger.besu.consensus.ibft.network.IbftMessageTransmitter;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
import org.hyperledger.besu.consensus.ibft.statemachine.IbftRound;
@@ -71,7 +71,7 @@ public class IbftRoundIntegrationTest {
@Mock private WorldStateArchive worldStateArchive;
@Mock private BlockImporter blockImporter;
@Mock private IbftBlockCreator blockCreator;
@Mock private BftBlockCreator blockCreator;
@Mock private MessageValidator messageValidator;
@Mock private RoundTimer roundTimer;
@Mock private NodeKey nodeKey;
@@ -98,8 +98,8 @@ public class IbftRoundIntegrationTest {
throwingMessageFactory = new MessageFactory(nodeKey);
transmitter = new IbftMessageTransmitter(throwingMessageFactory, multicaster);
IbftExtraData proposedExtraData =
new IbftExtraData(Bytes.wrap(new byte[32]), emptyList(), empty(), 0, emptyList());
BftExtraData proposedExtraData =
new BftExtraData(Bytes.wrap(new byte[32]), emptyList(), empty(), 0, emptyList());
final BlockHeaderTestFixture headerTestFixture = new BlockHeaderTestFixture();
headerTestFixture.extraData(proposedExtraData.encode());
headerTestFixture.number(1);

View File

@@ -19,6 +19,7 @@ import static org.apache.logging.log4j.LogManager.getLogger;
import org.hyperledger.besu.consensus.common.bft.BftEventQueue;
import org.hyperledger.besu.consensus.common.bft.BftExecutors;
import org.hyperledger.besu.consensus.common.bft.BftProcessor;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreatorFactory;
import org.hyperledger.besu.consensus.common.bft.events.NewChainHead;
import org.hyperledger.besu.consensus.common.bft.statemachine.BftEventHandler;
import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator;
@@ -50,7 +51,7 @@ public class IbftMiningCoordinator implements MiningCoordinator, BlockAddedObser
private final BftEventHandler eventHandler;
private final BftProcessor bftProcessor;
private final IbftBlockCreatorFactory blockCreatorFactory;
private final BftBlockCreatorFactory blockCreatorFactory;
protected final Blockchain blockchain;
private final BftEventQueue eventQueue;
private final BftExecutors bftExecutors;
@@ -62,7 +63,7 @@ public class IbftMiningCoordinator implements MiningCoordinator, BlockAddedObser
final BftExecutors bftExecutors,
final BftEventHandler eventHandler,
final BftProcessor bftProcessor,
final IbftBlockCreatorFactory blockCreatorFactory,
final BftBlockCreatorFactory blockCreatorFactory,
final Blockchain blockchain,
final BftEventQueue eventQueue) {
this.bftExecutors = bftExecutors;

View File

@@ -19,8 +19,8 @@ import org.hyperledger.besu.consensus.common.EpochManager;
import org.hyperledger.besu.consensus.common.VoteProposer;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
import org.hyperledger.besu.consensus.common.VoteTallyUpdater;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.ibft.jsonrpc.methods.IbftDiscardValidatorVote;
import org.hyperledger.besu.consensus.ibft.jsonrpc.methods.IbftGetPendingVotes;
import org.hyperledger.besu.consensus.ibft.jsonrpc.methods.IbftGetSignerMetrics;
@@ -54,9 +54,8 @@ public class IbftJsonRpcMethods extends ApiGroupJsonRpcMethods {
final MutableBlockchain mutableBlockchain = context.getBlockchain();
final BlockchainQueries blockchainQueries =
new BlockchainQueries(context.getBlockchain(), context.getWorldStateArchive());
final VoteProposer voteProposer =
context.getConsensusState(IbftContext.class).getVoteProposer();
final BlockInterface blockInterface = new IbftBlockInterface();
final VoteProposer voteProposer = context.getConsensusState(BftContext.class).getVoteProposer();
final BlockInterface blockInterface = new BftBlockInterface();
final VoteTallyCache voteTallyCache = createVoteTallyCache(context, mutableBlockchain);
@@ -71,11 +70,9 @@ public class IbftJsonRpcMethods extends ApiGroupJsonRpcMethods {
private VoteTallyCache createVoteTallyCache(
final ProtocolContext context, final MutableBlockchain blockchain) {
final EpochManager epochManager =
context.getConsensusState(IbftContext.class).getEpochManager();
final IbftBlockInterface ibftBlockInterface = new IbftBlockInterface();
final VoteTallyUpdater voteTallyUpdater =
new VoteTallyUpdater(epochManager, ibftBlockInterface);
return new VoteTallyCache(blockchain, voteTallyUpdater, epochManager, ibftBlockInterface);
final EpochManager epochManager = context.getConsensusState(BftContext.class).getEpochManager();
final BftBlockInterface bftBlockInterface = new BftBlockInterface();
final VoteTallyUpdater voteTallyUpdater = new VoteTallyUpdater(epochManager, bftBlockInterface);
return new VoteTallyCache(blockchain, voteTallyUpdater, epochManager, bftBlockInterface);
}
}

View File

@@ -14,9 +14,9 @@
*/
package org.hyperledger.besu.consensus.ibft.messagewrappers;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.messagewrappers.BftMessage;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.payload.PayloadDeserializers;
import org.hyperledger.besu.consensus.ibft.payload.ProposalPayload;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangeCertificate;
@@ -77,7 +77,7 @@ public class Proposal extends BftMessage<ProposalPayload> {
rlpIn.enterList();
final SignedData<ProposalPayload> payload =
PayloadDeserializers.readSignedProposalPayloadFrom(rlpIn);
final Block proposedBlock = Block.readFrom(rlpIn, IbftBlockHeaderFunctions.forCommittedSeal());
final Block proposedBlock = Block.readFrom(rlpIn, BftBlockHeaderFunctions.forCommittedSeal());
final Optional<RoundChangeCertificate> roundChangeCertificate =
readRoundChangeCertificate(rlpIn);

View File

@@ -14,10 +14,10 @@
*/
package org.hyperledger.besu.consensus.ibft.messagewrappers;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.messagewrappers.BftMessage;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.payload.PayloadDeserializers;
import org.hyperledger.besu.consensus.ibft.payload.PreparedCertificate;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangePayload;
@@ -75,7 +75,7 @@ public class RoundChange extends BftMessage<RoundChangePayload> {
PayloadDeserializers.readSignedRoundChangePayloadFrom(rlpIn);
Optional<Block> block = Optional.empty();
if (!rlpIn.nextIsNull()) {
block = Optional.of(Block.readFrom(rlpIn, IbftBlockHeaderFunctions.forCommittedSeal()));
block = Optional.of(Block.readFrom(rlpIn, BftBlockHeaderFunctions.forCommittedSeal()));
} else {
rlpIn.skipNext();
}

View File

@@ -16,8 +16,8 @@ package org.hyperledger.besu.consensus.ibft.queries;
import org.hyperledger.besu.consensus.common.BlockInterface;
import org.hyperledger.besu.consensus.common.PoaQueryServiceImpl;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -40,7 +40,7 @@ public class IbftQueryServiceImpl extends PoaQueryServiceImpl implements IbftQue
@Override
public int getRoundNumberFrom(final org.hyperledger.besu.plugin.data.BlockHeader header) {
final BlockHeader headerFromChain = getHeaderFromChain(header);
final IbftExtraData extraData = IbftExtraData.decode(headerFromChain);
final BftExtraData extraData = BftExtraData.decode(headerFromChain);
return extraData.getRound();
}
@@ -48,10 +48,10 @@ public class IbftQueryServiceImpl extends PoaQueryServiceImpl implements IbftQue
public Collection<Address> getSignersFrom(
final org.hyperledger.besu.plugin.data.BlockHeader header) {
final BlockHeader headerFromChain = getHeaderFromChain(header);
final IbftExtraData extraData = IbftExtraData.decode(headerFromChain);
final BftExtraData extraData = BftExtraData.decode(headerFromChain);
return Collections.unmodifiableList(
IbftBlockHashing.recoverCommitterAddresses(headerFromChain, extraData));
BftBlockHashing.recoverCommitterAddresses(headerFromChain, extraData));
}
private BlockHeader getHeaderFromChain(

View File

@@ -14,7 +14,7 @@
*/
package org.hyperledger.besu.consensus.ibft.statemachine;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.ibft.validation.MessageValidatorFactory;
import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -50,7 +50,7 @@ public class IbftBlockHeightManagerFactory {
parentHeader,
finalState,
new RoundChangeManager(
IbftHelpers.calculateRequiredValidatorQuorum(finalState.getValidators().size()),
BftHelpers.calculateRequiredValidatorQuorum(finalState.getValidators().size()),
messageValidatorFactory.createRoundChangeMessageValidator(
parentHeader.getNumber() + 1L, parentHeader)),
roundFactory,

View File

@@ -15,12 +15,12 @@
package org.hyperledger.besu.consensus.ibft.statemachine;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.BlockTimer;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreatorFactory;
import org.hyperledger.besu.consensus.ibft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreatorFactory;
import org.hyperledger.besu.consensus.common.bft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.ibft.network.IbftMessageTransmitter;
import org.hyperledger.besu.consensus.ibft.network.ValidatorMulticaster;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
@@ -38,7 +38,7 @@ public class IbftFinalState {
private final ProposerSelector proposerSelector;
private final RoundTimer roundTimer;
private final BlockTimer blockTimer;
private final IbftBlockCreatorFactory blockCreatorFactory;
private final BftBlockCreatorFactory blockCreatorFactory;
private final MessageFactory messageFactory;
private final IbftMessageTransmitter messageTransmitter;
private final Clock clock;
@@ -51,7 +51,7 @@ public class IbftFinalState {
final ValidatorMulticaster validatorMulticaster,
final RoundTimer roundTimer,
final BlockTimer blockTimer,
final IbftBlockCreatorFactory blockCreatorFactory,
final BftBlockCreatorFactory blockCreatorFactory,
final MessageFactory messageFactory,
final Clock clock) {
this.voteTallyCache = voteTallyCache;
@@ -67,7 +67,7 @@ public class IbftFinalState {
}
public int getQuorum() {
return IbftHelpers.calculateRequiredValidatorQuorum(getValidators().size());
return BftHelpers.calculateRequiredValidatorQuorum(getValidators().size());
}
public Collection<Address> getValidators() {
@@ -98,7 +98,7 @@ public class IbftFinalState {
return blockTimer;
}
public IbftBlockCreatorFactory getBlockCreatorFactory() {
public BftBlockCreatorFactory getBlockCreatorFactory() {
return blockCreatorFactory;
}

View File

@@ -14,14 +14,14 @@
*/
package org.hyperledger.besu.consensus.ibft.statemachine;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreator;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreator;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
@@ -52,7 +52,7 @@ public class IbftRound {
private final Subscribers<MinedBlockObserver> observers;
private final RoundState roundState;
private final IbftBlockCreator blockCreator;
private final BftBlockCreator blockCreator;
private final ProtocolContext protocolContext;
private final BlockImporter blockImporter;
private final NodeKey nodeKey;
@@ -61,7 +61,7 @@ public class IbftRound {
public IbftRound(
final RoundState roundState,
final IbftBlockCreator blockCreator,
final BftBlockCreator blockCreator,
final ProtocolContext protocolContext,
final BlockImporter blockImporter,
final Subscribers<MinedBlockObserver> observers,
@@ -87,7 +87,7 @@ public class IbftRound {
public void createAndSendProposalMessage(final long headerTimeStampSeconds) {
final Block block = blockCreator.createBlock(headerTimeStampSeconds);
final IbftExtraData extraData = IbftExtraData.decode(block.getHeader());
final BftExtraData extraData = BftExtraData.decode(block.getHeader());
LOG.debug("Creating proposed block. round={}", roundState.getRoundIdentifier());
LOG.trace(
"Creating proposed block with extraData={} blockHeader={}", extraData, block.getHeader());
@@ -108,10 +108,10 @@ public class IbftRound {
LOG.debug(
"Sending proposal from PreparedCertificate. round={}", roundState.getRoundIdentifier());
blockToPublish =
IbftBlockInterface.replaceRoundInBlock(
BftBlockInterface.replaceRoundInBlock(
bestBlockFromRoundChange.get(),
getRoundIdentifier().getRoundNumber(),
IbftBlockHeaderFunctions.forCommittedSeal());
BftBlockHeaderFunctions.forCommittedSeal());
}
updateStateWithProposalAndTransmit(blockToPublish, Optional.of(roundChangeCertificate));
@@ -234,11 +234,11 @@ public class IbftRound {
private void importBlockToChain() {
final Block blockToImport =
IbftHelpers.createSealedBlock(
BftHelpers.createSealedBlock(
roundState.getProposedBlock().get(), roundState.getCommitSeals());
final long blockNumber = blockToImport.getHeader().getNumber();
final IbftExtraData extraData = IbftExtraData.decode(blockToImport.getHeader());
final BftExtraData extraData = BftExtraData.decode(blockToImport.getHeader());
LOG.log(
getRoundIdentifier().getRoundNumber() > 0 ? Level.INFO : Level.DEBUG,
"Importing block to chain. round={}, hash={}",
@@ -260,9 +260,9 @@ public class IbftRound {
private Signature createCommitSeal(final Block block) {
final BlockHeader proposedHeader = block.getHeader();
final IbftExtraData extraData = IbftExtraData.decode(proposedHeader);
final BftExtraData extraData = BftExtraData.decode(proposedHeader);
final Hash commitHash =
IbftBlockHashing.calculateDataHashForCommittedSeal(proposedHeader, extraData);
BftBlockHashing.calculateDataHashForCommittedSeal(proposedHeader, extraData);
return nodeKey.sign(commitHash);
}

View File

@@ -15,8 +15,8 @@
package org.hyperledger.besu.consensus.ibft.statemachine;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreator;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreatorFactory;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreator;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreatorFactory;
import org.hyperledger.besu.consensus.ibft.validation.MessageValidatorFactory;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.chain.MinedBlockObserver;
@@ -26,7 +26,7 @@ import org.hyperledger.besu.util.Subscribers;
public class IbftRoundFactory {
private final IbftFinalState finalState;
private final IbftBlockCreatorFactory blockCreatorFactory;
private final BftBlockCreatorFactory blockCreatorFactory;
private final ProtocolContext protocolContext;
private final ProtocolSchedule protocolSchedule;
private final Subscribers<MinedBlockObserver> minedBlockObservers;
@@ -63,7 +63,7 @@ public class IbftRoundFactory {
public IbftRound createNewRoundWithState(
final BlockHeader parentHeader, final RoundState roundState) {
final ConsensusRoundIdentifier roundIdentifier = roundState.getRoundIdentifier();
final IbftBlockCreator blockCreator =
final BftBlockCreator blockCreator =
blockCreatorFactory.create(parentHeader, roundIdentifier.getRoundNumber());
return new IbftRound(

View File

@@ -14,8 +14,8 @@
*/
package org.hyperledger.besu.consensus.ibft.statemachine;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
@@ -98,7 +98,7 @@ public class RoundState {
private void updateState() {
// NOTE: The quorum for Prepare messages is 1 less than the quorum size as the proposer
// does not supply a prepare message
final long prepareQuorum = IbftHelpers.prepareMessageCountForQuorum(quorum);
final long prepareQuorum = BftHelpers.prepareMessageCountForQuorum(quorum);
prepared = (prepareMessages.size() >= prepareQuorum) && proposalMessage.isPresent();
committed = (commitMessages.size() >= quorum) && proposalMessage.isPresent();
LOG.trace(

View File

@@ -14,10 +14,10 @@
*/
package org.hyperledger.besu.consensus.ibft.validation;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.blockcreation.ProposerSelector;
import org.hyperledger.besu.consensus.common.bft.blockcreation.ProposerSelector;
import org.hyperledger.besu.ethereum.BlockValidator;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address;
@@ -43,7 +43,7 @@ public class MessageValidatorFactory {
private Collection<Address> getValidatorsAfterBlock(final BlockHeader parentHeader) {
return protocolContext
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteTallyCache()
.getVoteTallyAfterBlock(parentHeader)
.getValidators();
@@ -83,8 +83,8 @@ public class MessageValidatorFactory {
new RoundChangePayloadValidator(
(roundIdentifier) -> createSignedDataValidator(roundIdentifier, parentHeader),
validators,
IbftHelpers.prepareMessageCountForQuorum(
IbftHelpers.calculateRequiredValidatorQuorum(validators.size())),
BftHelpers.prepareMessageCountForQuorum(
BftHelpers.calculateRequiredValidatorQuorum(validators.size())),
chainHeight),
new ProposalBlockConsistencyValidator());
}

View File

@@ -14,9 +14,9 @@
*/
package org.hyperledger.besu.consensus.ibft.validation;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.payload.ProposalPayload;
import org.hyperledger.besu.ethereum.core.Block;
@@ -51,7 +51,7 @@ public class ProposalBlockConsistencyValidator {
private boolean validateBlockMatchesProposalRound(
final ProposalPayload payload, final Block block) {
final ConsensusRoundIdentifier msgRound = payload.getRoundIdentifier();
final IbftExtraData extraData = IbftExtraData.decode(block.getHeader());
final BftExtraData extraData = BftExtraData.decode(block.getHeader());
if (extraData.getRound() != msgRound.getRoundNumber()) {
LOG.info("Invalid Proposal message, round number in block does not match that in message.");
return false;

View File

@@ -14,11 +14,11 @@
*/
package org.hyperledger.besu.consensus.ibft.validation;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.payload.SignedData;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.payload.PreparedCertificate;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangeCertificate;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangePayload;
@@ -47,7 +47,7 @@ public class RoundChangeCertificateValidator {
final long chainHeight) {
this.validators = validators;
this.messageValidatorFactory = messageValidatorFactory;
this.quorum = IbftHelpers.calculateRequiredValidatorQuorum(validators.size());
this.quorum = BftHelpers.calculateRequiredValidatorQuorum(validators.size());
this.chainHeight = chainHeight;
}
@@ -78,7 +78,7 @@ public class RoundChangeCertificateValidator {
new RoundChangePayloadValidator(
messageValidatorFactory,
validators,
IbftHelpers.prepareMessageCountForQuorum(quorum),
BftHelpers.prepareMessageCountForQuorum(quorum),
chainHeight);
if (!roundChangeCert.getRoundChangePayloads().stream()
@@ -109,7 +109,7 @@ public class RoundChangeCertificateValidator {
roundChangeCert.getRoundChangePayloads();
final Optional<PreparedCertificate> latestPreparedCertificate =
IbftHelpers.findLatestPreparedCertificate(roundChangePayloads);
findLatestPreparedCertificate(roundChangePayloads);
if (!latestPreparedCertificate.isPresent()) {
LOG.debug(
@@ -120,7 +120,7 @@ public class RoundChangeCertificateValidator {
// Need to check that if we substitute the LatestPrepareCert round number into the supplied
// block that we get the SAME hash as PreparedCert.
final Block currentBlockWithOldRound =
IbftBlockInterface.replaceRoundInBlock(
BftBlockInterface.replaceRoundInBlock(
proposedBlock,
latestPreparedCertificate
.get()
@@ -128,7 +128,7 @@ public class RoundChangeCertificateValidator {
.getPayload()
.getRoundIdentifier()
.getRoundNumber(),
IbftBlockHeaderFunctions.forCommittedSeal());
BftBlockHeaderFunctions.forCommittedSeal());
if (!currentBlockWithOldRound
.getHash()
@@ -140,4 +140,28 @@ public class RoundChangeCertificateValidator {
return true;
}
public static Optional<PreparedCertificate> findLatestPreparedCertificate(
final Collection<SignedData<RoundChangePayload>> msgs) {
Optional<PreparedCertificate> result = Optional.empty();
for (SignedData<RoundChangePayload> roundChangeMsg : msgs) {
final RoundChangePayload payload = roundChangeMsg.getPayload();
if (payload.getPreparedCertificate().isPresent()) {
if (!result.isPresent()) {
result = payload.getPreparedCertificate();
} else {
final PreparedCertificate currentLatest = result.get();
final PreparedCertificate nextCert = payload.getPreparedCertificate().get();
if (currentLatest.getProposalPayload().getPayload().getRoundIdentifier().getRoundNumber()
< nextCert.getProposalPayload().getPayload().getRoundIdentifier().getRoundNumber()) {
result = Optional.of(nextCert);
}
}
}
}
return result;
}
}

View File

@@ -17,6 +17,10 @@ package org.hyperledger.besu.consensus.ibft;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.Vote;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
import org.hyperledger.besu.crypto.SECP256K1.KeyPair;
@@ -41,7 +45,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test;
public class IbftBlockHashingTest {
public class BftBlockHashingTest {
private static final List<NodeKey> COMMITTERS_NODE_KEYS = committersNodeKeys();
private static final List<Address> VALIDATORS =
@@ -55,15 +59,15 @@ public class IbftBlockHashingTest {
@Test
public void testCalculateHashOfIbft2BlockOnChain() {
Hash actualHeaderHash = IbftBlockHashing.calculateHashOfIbftBlockOnChain(HEADER_TO_BE_HASHED);
Hash actualHeaderHash = BftBlockHashing.calculateHashOfBftBlockOnChain(HEADER_TO_BE_HASHED);
assertThat(actualHeaderHash).isEqualTo(EXPECTED_HEADER_HASH);
}
@Test
public void testRecoverCommitterAddresses() {
List<Address> actualCommitterAddresses =
IbftBlockHashing.recoverCommitterAddresses(
HEADER_TO_BE_HASHED, IbftExtraData.decode(HEADER_TO_BE_HASHED));
BftBlockHashing.recoverCommitterAddresses(
HEADER_TO_BE_HASHED, BftExtraData.decode(HEADER_TO_BE_HASHED));
List<Address> expectedCommitterAddresses =
COMMITTERS_NODE_KEYS.stream()
@@ -76,8 +80,8 @@ public class IbftBlockHashingTest {
@Test
public void testCalculateDataHashForCommittedSeal() {
Hash dataHahsForCommittedSeal =
IbftBlockHashing.calculateDataHashForCommittedSeal(
HEADER_TO_BE_HASHED, IbftExtraData.decode(HEADER_TO_BE_HASHED));
BftBlockHashing.calculateDataHashForCommittedSeal(
HEADER_TO_BE_HASHED, BftExtraData.decode(HEADER_TO_BE_HASHED));
BlockHeaderBuilder builder = setHeaderFieldsExceptForExtraData();
@@ -86,8 +90,8 @@ public class IbftBlockHashingTest {
.map(nodeKey -> nodeKey.sign(dataHahsForCommittedSeal))
.collect(Collectors.toList());
IbftExtraData extraDataWithCommitSeals =
new IbftExtraData(VANITY_DATA, commitSeals, VOTE, ROUND, VALIDATORS);
BftExtraData extraDataWithCommitSeals =
new BftExtraData(VANITY_DATA, commitSeals, VOTE, ROUND, VALIDATORS);
builder.extraData(extraDataWithCommitSeals.encode());
BlockHeader actualHeader = builder.buildBlockHeader();
@@ -133,7 +137,7 @@ public class IbftBlockHashingTest {
builder.mixHash(
Hash.fromHexString("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365"));
builder.nonce(0);
builder.blockHeaderFunctions(IbftBlockHeaderFunctions.forOnChainBlock());
builder.blockHeaderFunctions(BftBlockHeaderFunctions.forOnChainBlock());
return builder;
}
@@ -149,7 +153,7 @@ public class IbftBlockHashingTest {
BlockHeaderBuilder builder = setHeaderFieldsExceptForExtraData();
builder.extraData(
new IbftExtraData(VANITY_DATA, emptyList(), VOTE, ROUND, VALIDATORS)
new BftExtraData(VANITY_DATA, emptyList(), VOTE, ROUND, VALIDATORS)
.encodeWithoutCommitSeals());
BytesValueRLPOutput rlpForHeaderFroCommittersSigning = new BytesValueRLPOutput();
@@ -160,8 +164,8 @@ public class IbftBlockHashingTest {
.map(nodeKey -> nodeKey.sign(Hash.hash(rlpForHeaderFroCommittersSigning.encoded())))
.collect(Collectors.toList());
IbftExtraData extraDataWithCommitSeals =
new IbftExtraData(VANITY_DATA, commitSeals, VOTE, ROUND, VALIDATORS);
BftExtraData extraDataWithCommitSeals =
new BftExtraData(VANITY_DATA, commitSeals, VOTE, ROUND, VALIDATORS);
builder.extraData(extraDataWithCommitSeals.encode());
return builder.buildBlockHeader();
@@ -171,7 +175,7 @@ public class IbftBlockHashingTest {
BlockHeaderBuilder builder = setHeaderFieldsExceptForExtraData();
builder.extraData(
new IbftExtraData(VANITY_DATA, emptyList(), VOTE, 0, VALIDATORS)
new BftExtraData(VANITY_DATA, emptyList(), VOTE, 0, VALIDATORS)
.encodeWithoutCommitSealsAndRoundNumber());
BytesValueRLPOutput rlpOutput = new BytesValueRLPOutput();

View File

@@ -1,158 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* 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.ibft;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
import org.hyperledger.besu.consensus.ibft.payload.PreparedCertificate;
import org.hyperledger.besu.consensus.ibft.statemachine.PreparedRoundArtifacts;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.Hash;
import java.util.Optional;
import com.google.common.collect.Lists;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class IbftHelpersTest {
@Test
public void calculateRequiredValidatorQuorum1Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(1)).isEqualTo(1);
}
@Test
public void calculateRequiredValidatorQuorum2Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(2)).isEqualTo(2);
}
@Test
public void calculateRequiredValidatorQuorum3Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(3)).isEqualTo(2);
}
@Test
public void calculateRequiredValidatorQuorum4Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(4)).isEqualTo(3);
}
@Test
public void calculateRequiredValidatorQuorum5Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(5)).isEqualTo(4);
}
@Test
public void calculateRequiredValidatorQuorum7Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(7)).isEqualTo(5);
}
@Test
public void calculateRequiredValidatorQuorum10Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(10)).isEqualTo(7);
}
@Test
public void calculateRequiredValidatorQuorum15Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(15)).isEqualTo(10);
}
@Test
public void calculateRequiredValidatorQuorum20Validator() {
Assertions.assertThat(IbftHelpers.calculateRequiredValidatorQuorum(20)).isEqualTo(14);
}
@Test
public void latestPreparedCertificateIsExtractedFromRoundChangeCertificate() {
// NOTE: This function does not validate that all RoundCHanges/Prepares etc. come from valid
// sources, it is only responsible for determine which of the list or RoundChange messages
// contains the newest
// NOTE: This capability is tested as part of the NewRoundMessageValidationTests.
final NodeKey proposerKey = NodeKeyUtils.generate();
final MessageFactory proposerMessageFactory = new MessageFactory(proposerKey);
final Block proposedBlock = mock(Block.class);
when(proposedBlock.getHash()).thenReturn(Hash.fromHexStringLenient("1"));
final ConsensusRoundIdentifier roundIdentifier = new ConsensusRoundIdentifier(1, 4);
final ConsensusRoundIdentifier preparedRound = TestHelpers.createFrom(roundIdentifier, 0, -1);
final Proposal differentProposal =
proposerMessageFactory.createProposal(preparedRound, proposedBlock, Optional.empty());
final Optional<PreparedRoundArtifacts> latterPreparedRoundArtifacts =
Optional.of(
new PreparedRoundArtifacts(
differentProposal,
Lists.newArrayList(
proposerMessageFactory.createPrepare(roundIdentifier, proposedBlock.getHash()),
proposerMessageFactory.createPrepare(
roundIdentifier, proposedBlock.getHash()))));
// An earlier PrepareCert is added to ensure the path to find the latest PrepareCert
// is correctly followed.
final ConsensusRoundIdentifier earlierPreparedRound =
TestHelpers.createFrom(roundIdentifier, 0, -2);
final Proposal earlierProposal =
proposerMessageFactory.createProposal(
earlierPreparedRound, proposedBlock, Optional.empty());
final Optional<PreparedRoundArtifacts> earlierPreparedRoundArtifacts =
Optional.of(
new PreparedRoundArtifacts(
earlierProposal,
Lists.newArrayList(
proposerMessageFactory.createPrepare(
earlierPreparedRound, proposedBlock.getHash()),
proposerMessageFactory.createPrepare(
earlierPreparedRound, proposedBlock.getHash()))));
final Optional<PreparedCertificate> newestCert =
IbftHelpers.findLatestPreparedCertificate(
Lists.newArrayList(
proposerMessageFactory
.createRoundChange(roundIdentifier, earlierPreparedRoundArtifacts)
.getSignedPayload(),
proposerMessageFactory
.createRoundChange(roundIdentifier, latterPreparedRoundArtifacts)
.getSignedPayload()));
assertThat(newestCert.get())
.isEqualTo(latterPreparedRoundArtifacts.get().getPreparedCertificate());
}
@Test
public void allRoundChangeHaveNoPreparedReturnsEmptyOptional() {
final NodeKey proposerKey = NodeKeyUtils.generate();
final MessageFactory proposerMessageFactory = new MessageFactory(proposerKey);
final ConsensusRoundIdentifier roundIdentifier = new ConsensusRoundIdentifier(1, 4);
final Optional<PreparedCertificate> newestCert =
IbftHelpers.findLatestPreparedCertificate(
Lists.newArrayList(
proposerMessageFactory
.createRoundChange(roundIdentifier, Optional.empty())
.getSignedPayload(),
proposerMessageFactory
.createRoundChange(roundIdentifier, Optional.empty())
.getSignedPayload()));
assertThat(newestCert).isEmpty();
}
}

View File

@@ -16,6 +16,8 @@ package org.hyperledger.besu.consensus.ibft;
import static java.util.Collections.singletonList;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
@@ -49,7 +51,7 @@ public class TestHelpers {
public static Block createProposalBlock(
final List<Address> validators, final ConsensusRoundIdentifier roundId) {
final Bytes extraData =
new IbftExtraData(
new BftExtraData(
Bytes.wrap(new byte[32]),
Collections.emptyList(),
Optional.empty(),
@@ -60,7 +62,7 @@ public class TestHelpers {
BlockOptions.create()
.setExtraData(extraData)
.setBlockNumber(roundId.getSequenceNumber())
.setBlockHeaderFunctions(IbftBlockHeaderFunctions.forCommittedSeal());
.setBlockHeaderFunctions(BftBlockHeaderFunctions.forCommittedSeal());
return new BlockDataGenerator().block(blockOptions);
}

View File

@@ -22,6 +22,7 @@ import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.BftEventQueue;
import org.hyperledger.besu.consensus.common.bft.BftExecutors;
import org.hyperledger.besu.consensus.common.bft.BftProcessor;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreatorFactory;
import org.hyperledger.besu.consensus.common.bft.events.NewChainHead;
import org.hyperledger.besu.consensus.common.bft.statemachine.BftEventHandler;
import org.hyperledger.besu.ethereum.chain.BlockAddedEvent;
@@ -47,7 +48,7 @@ public class IbftMiningCoordinatorTest {
@Mock private BftEventHandler controller;
@Mock private BftExecutors bftExecutors;
@Mock private BftProcessor bftProcessor;
@Mock private IbftBlockCreatorFactory ibftBlockCreatorFactory;
@Mock private BftBlockCreatorFactory bftBlockCreatorFactory;
@Mock private Blockchain blockChain;
@Mock private Block block;
@Mock private BlockBody blockBody;
@@ -59,12 +60,7 @@ public class IbftMiningCoordinatorTest {
public void setup() {
ibftMiningCoordinator =
new IbftMiningCoordinator(
bftExecutors,
controller,
bftProcessor,
ibftBlockCreatorFactory,
blockChain,
eventQueue);
bftExecutors, controller, bftProcessor, bftBlockCreatorFactory, blockChain, eventQueue);
when(block.getBody()).thenReturn(blockBody);
when(block.getHeader()).thenReturn(blockHeader);
when(blockBody.getTransactions()).thenReturn(Lists.emptyList());
@@ -89,7 +85,7 @@ public class IbftMiningCoordinatorTest {
@Test
public void getsMinTransactionGasPrice() {
final Wei minGasPrice = Wei.of(10);
when(ibftBlockCreatorFactory.getMinTransactionGasPrice()).thenReturn(minGasPrice);
when(bftBlockCreatorFactory.getMinTransactionGasPrice()).thenReturn(minGasPrice);
assertThat(ibftMiningCoordinator.getMinTransactionGasPrice()).isEqualTo(minGasPrice);
}
@@ -97,7 +93,7 @@ public class IbftMiningCoordinatorTest {
public void setsTheExtraData() {
final Bytes extraData = Bytes.fromHexStringLenient("0x1234");
ibftMiningCoordinator.setExtraData(extraData);
verify(ibftBlockCreatorFactory).setExtraData(extraData);
verify(bftBlockCreatorFactory).setExtraData(extraData);
}
@Test

View File

@@ -16,7 +16,7 @@ package org.hyperledger.besu.consensus.ibft.jsonrpc.methods;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
@@ -45,14 +45,14 @@ public class IbftGetValidatorsByBlockHashTest {
@Mock private Blockchain blockchain;
@Mock private BlockHeader blockHeader;
@Mock private IbftBlockInterface ibftBlockInterface;
@Mock private BftBlockInterface bftBlockInterface;
@Mock private JsonRpcRequestContext request;
private IbftGetValidatorsByBlockHash method;
@Before
public void setUp() {
method = new IbftGetValidatorsByBlockHash(blockchain, ibftBlockInterface);
method = new IbftGetValidatorsByBlockHash(blockchain, bftBlockInterface);
}
@Test
@@ -65,7 +65,7 @@ public class IbftGetValidatorsByBlockHashTest {
when(blockchain.getBlockHeader(Hash.ZERO)).thenReturn(Optional.of(blockHeader));
final List<Address> addresses = Collections.singletonList(Address.ID);
final List<String> expectedOutput = Collections.singletonList(Address.ID.toString());
when(ibftBlockInterface.validatorsInBlock(blockHeader)).thenReturn(addresses);
when(bftBlockInterface.validatorsInBlock(blockHeader)).thenReturn(addresses);
request = requestWithParams(ZERO_HASH);
JsonRpcSuccessResponse response = (JsonRpcSuccessResponse) method.response(request);
Assertions.assertThat(response.getResult()).isEqualTo(expectedOutput);

View File

@@ -17,7 +17,7 @@ package org.hyperledger.besu.consensus.ibft.jsonrpc.methods;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter;
@@ -40,14 +40,14 @@ public class IbftGetValidatorsByBlockNumberTest {
@Mock private BlockchainQueries blockchainQueries;
@Mock private BlockHeader blockHeader;
@Mock private IbftBlockInterface ibftBlockInterface;
@Mock private BftBlockInterface bftBlockInterface;
@Mock private JsonRpcRequestContext request;
private IbftGetValidatorsByBlockNumber method;
@Before
public void setUp() {
method = new IbftGetValidatorsByBlockNumber(blockchainQueries, ibftBlockInterface);
method = new IbftGetValidatorsByBlockNumber(blockchainQueries, bftBlockInterface);
}
@Test
@@ -68,7 +68,7 @@ public class IbftGetValidatorsByBlockNumberTest {
when(blockchainQueries.getBlockHeaderByNumber(12)).thenReturn(Optional.of(blockHeader));
final List<Address> addresses = Collections.singletonList(Address.ID);
final List<String> expectedOutput = Collections.singletonList(Address.ID.toString());
when(ibftBlockInterface.validatorsInBlock(blockHeader)).thenReturn(addresses);
when(bftBlockInterface.validatorsInBlock(blockHeader)).thenReturn(addresses);
Object result = method.resultByBlockNumber(request, 12);
assertThat(result).isEqualTo(expectedOutput);
}

View File

@@ -18,10 +18,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
import org.hyperledger.besu.crypto.SECP256K1.Signature;
@@ -58,7 +58,7 @@ public class IbftQueryServiceImplTest {
private final List<NodeKey> signingKeys = Lists.newArrayList(validatorKeys.get(0));
private final int ROUND_NUMBER_IN_BLOCK = 5;
private IbftExtraData signedExtraData;
private BftExtraData signedExtraData;
private BlockHeader blockHeader;
@Before
@@ -69,8 +69,8 @@ public class IbftQueryServiceImplTest {
.map(validatorKeys -> Util.publicKeyToAddress(validatorKeys.getPublicKey()))
.collect(Collectors.toList());
final IbftExtraData unsignedExtraData =
new IbftExtraData(
final BftExtraData unsignedExtraData =
new BftExtraData(
Bytes.wrap(new byte[32]),
Collections.emptyList(),
Optional.empty(),
@@ -79,7 +79,7 @@ public class IbftQueryServiceImplTest {
final BlockHeaderTestFixture blockHeaderTestFixture = new BlockHeaderTestFixture();
blockHeaderTestFixture.number(1); // can't be genesis block (due to extradata serialisation)
blockHeaderTestFixture.blockHeaderFunctions(IbftBlockHeaderFunctions.forOnChainBlock());
blockHeaderTestFixture.blockHeaderFunctions(BftBlockHeaderFunctions.forOnChainBlock());
blockHeaderTestFixture.extraData(unsignedExtraData.encode());
final BlockHeader unsignedBlockHeader = blockHeaderTestFixture.buildHeader();
@@ -89,11 +89,11 @@ public class IbftQueryServiceImplTest {
.map(
nodeKey ->
nodeKey.sign(
IbftBlockHashing.calculateDataHashForCommittedSeal(unsignedBlockHeader)))
BftBlockHashing.calculateDataHashForCommittedSeal(unsignedBlockHeader)))
.collect(Collectors.toList());
signedExtraData =
new IbftExtraData(
new BftExtraData(
Bytes.wrap(new byte[32]),
validatorSignatures,
Optional.empty(),
@@ -107,7 +107,7 @@ public class IbftQueryServiceImplTest {
@Test
public void roundNumberFromBlockIsReturned() {
final IbftQueryService service =
new IbftQueryServiceImpl(new IbftBlockInterface(), blockchain, null);
new IbftQueryServiceImpl(new BftBlockInterface(), blockchain, null);
assertThat(service.getRoundNumberFrom(blockHeader)).isEqualTo(ROUND_NUMBER_IN_BLOCK);
}
@@ -119,7 +119,7 @@ public class IbftQueryServiceImplTest {
when(blockchain.getBlockHeader(blockHeader.getHash())).thenReturn(Optional.empty());
final IbftQueryService service =
new IbftQueryServiceImpl(new IbftBlockInterface(), blockchain, null);
new IbftQueryServiceImpl(new BftBlockInterface(), blockchain, null);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> service.getRoundNumberFrom(header));
}
@@ -127,7 +127,7 @@ public class IbftQueryServiceImplTest {
@Test
public void getSignersReturnsAddressesOfSignersInBlock() {
final IbftQueryService service =
new IbftQueryServiceImpl(new IbftBlockInterface(), blockchain, null);
new IbftQueryServiceImpl(new BftBlockInterface(), blockchain, null);
final List<Address> signers =
signingKeys.stream()
@@ -144,7 +144,7 @@ public class IbftQueryServiceImplTest {
when(blockchain.getBlockHeader(blockHeader.getHash())).thenReturn(Optional.empty());
final IbftQueryService service =
new IbftQueryServiceImpl(new IbftBlockInterface(), blockchain, null);
new IbftQueryServiceImpl(new BftBlockInterface(), blockchain, null);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> service.getSignersFrom(header));
}

View File

@@ -17,7 +17,7 @@ package org.hyperledger.besu.consensus.ibft.statemachine;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.ibft.TestHelpers.createFrom;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -30,12 +30,12 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.BlockTimer;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreator;
import org.hyperledger.besu.consensus.common.bft.events.RoundExpiry;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreator;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
@@ -90,7 +90,7 @@ public class IbftBlockHeightManagerTest {
@Mock private IbftRoundFactory roundFactory;
@Mock private Clock clock;
@Mock private MessageValidatorFactory messageValidatorFactory;
@Mock private IbftBlockCreator blockCreator;
@Mock private BftBlockCreator blockCreator;
@Mock private BlockImporter blockImporter;
@Mock private BlockTimer blockTimer;
@Mock private RoundTimer roundTimer;
@@ -107,8 +107,8 @@ public class IbftBlockHeightManagerTest {
private void buildCreatedBlock() {
final IbftExtraData extraData =
new IbftExtraData(Bytes.wrap(new byte[32]), emptyList(), Optional.empty(), 0, validators);
final BftExtraData extraData =
new BftExtraData(Bytes.wrap(new byte[32]), emptyList(), Optional.empty(), 0, validators);
headerTestFixture.extraData(extraData.encode());
final BlockHeader header = headerTestFixture.buildHeader();

View File

@@ -17,7 +17,7 @@ package org.hyperledger.besu.consensus.ibft.statemachine;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
@@ -28,11 +28,11 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.BftBlockHashing;
import org.hyperledger.besu.consensus.common.bft.BftExtraData;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.common.bft.RoundTimer;
import org.hyperledger.besu.consensus.ibft.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibft.IbftExtraData;
import org.hyperledger.besu.consensus.ibft.blockcreation.IbftBlockCreator;
import org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreator;
import org.hyperledger.besu.consensus.ibft.network.IbftMessageTransmitter;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangeCertificate;
@@ -80,14 +80,14 @@ public class IbftRoundTest {
@Mock private BlockImporter blockImporter;
@Mock private IbftMessageTransmitter transmitter;
@Mock private MinedBlockObserver minedBlockObserver;
@Mock private IbftBlockCreator blockCreator;
@Mock private BftBlockCreator blockCreator;
@Mock private MessageValidator messageValidator;
@Mock private RoundTimer roundTimer;
@Captor private ArgumentCaptor<Block> blockCaptor;
private Block proposedBlock;
private IbftExtraData proposedExtraData;
private BftExtraData proposedExtraData;
private final Signature remoteCommitSeal =
Signature.create(BigInteger.ONE, BigInteger.ONE, (byte) 1);
@@ -102,7 +102,7 @@ public class IbftRoundTest {
when(messageValidator.validateCommit(any())).thenReturn(true);
proposedExtraData =
new IbftExtraData(Bytes.wrap(new byte[32]), emptyList(), empty(), 0, emptyList());
new BftExtraData(Bytes.wrap(new byte[32]), emptyList(), empty(), 0, emptyList());
final BlockHeaderTestFixture headerTestFixture = new BlockHeaderTestFixture();
headerTestFixture.extraData(proposedExtraData.encode());
headerTestFixture.number(1);
@@ -214,7 +214,7 @@ public class IbftRoundTest {
roundTimer);
final Hash commitSealHash =
IbftBlockHashing.calculateDataHashForCommittedSeal(
BftBlockHashing.calculateDataHashForCommittedSeal(
proposedBlock.getHeader(), proposedExtraData);
final Signature localCommitSeal = nodeKey.sign(commitSealHash);
@@ -236,8 +236,8 @@ public class IbftRoundTest {
verify(blockImporter, times(1)).importBlock(any(), capturedBlock.capture(), any());
// Ensure imported block contains both commit seals.
final IbftExtraData importedExtraData =
IbftExtraData.decode(capturedBlock.getValue().getHeader());
final BftExtraData importedExtraData =
BftExtraData.decode(capturedBlock.getValue().getHeader());
assertThat(importedExtraData.getSeals()).containsOnly(remoteCommitSeal, localCommitSeal);
}
@@ -257,7 +257,7 @@ public class IbftRoundTest {
roundTimer);
final Hash commitSealHash =
IbftBlockHashing.calculateDataHashForCommittedSeal(
BftBlockHashing.calculateDataHashForCommittedSeal(
proposedBlock.getHeader(), proposedExtraData);
final Signature localCommitSeal = nodeKey.sign(commitSealHash);
@@ -335,8 +335,7 @@ public class IbftRoundTest {
blockCaptor.capture(),
eq(Optional.of(roundChangeArtifacts.getRoundChangeCertificate())));
final IbftExtraData proposedExtraData =
IbftExtraData.decode(blockCaptor.getValue().getHeader());
final BftExtraData proposedExtraData = BftExtraData.decode(blockCaptor.getValue().getHeader());
assertThat(proposedExtraData.getRound()).isEqualTo(roundIdentifier.getRoundNumber());
// Inject a single Prepare message, and confirm the roundState has gone to Prepared (which

View File

@@ -19,8 +19,8 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.BftHelpers;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.IbftHelpers;
import org.hyperledger.besu.consensus.ibft.TestHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
@@ -99,8 +99,8 @@ public class RoundChangeManagerTest {
new RoundChangePayloadValidator(
messageValidatorFactory,
validators,
IbftHelpers.calculateRequiredValidatorQuorum(
IbftHelpers.calculateRequiredValidatorQuorum(validators.size())),
BftHelpers.calculateRequiredValidatorQuorum(
BftHelpers.calculateRequiredValidatorQuorum(validators.size())),
2),
proposalConsistencyValidator);
manager = new RoundChangeManager(2, roundChangeMessageValidator);

View File

@@ -23,8 +23,8 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.ibft.TestHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Commit;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Prepare;
@@ -90,7 +90,7 @@ public class MessageValidatorTest {
protocolContext =
new ProtocolContext(
mock(MutableBlockchain.class), mock(WorldStateArchive.class), mock(IbftContext.class));
mock(MutableBlockchain.class), mock(WorldStateArchive.class), mock(BftContext.class));
when(blockValidator.validateAndProcessBlock(any(), any(), any(), any()))
.thenReturn(Optional.of(new BlockProcessingOutputs(null, null)));

View File

@@ -16,9 +16,9 @@ package org.hyperledger.besu.consensus.ibft.validation;
import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftBlockInterface;
import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftBlockInterface;
import org.hyperledger.besu.consensus.ibft.TestHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
@@ -57,10 +57,10 @@ public class ProposalBlockConsistencyValidatorTest {
proposerMessageFactory.createProposal(roundIdentifier, block, Optional.empty());
final Block misMatchedBlock =
IbftBlockInterface.replaceRoundInBlock(
BftBlockInterface.replaceRoundInBlock(
block,
roundIdentifier.getRoundNumber() + 1,
IbftBlockHeaderFunctions.forCommittedSeal());
BftBlockHeaderFunctions.forCommittedSeal());
assertThat(
consistencyChecker.validateProposalMatchesBlock(

View File

@@ -25,6 +25,7 @@ import org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.TestHelpers;
import org.hyperledger.besu.consensus.ibft.messagewrappers.Proposal;
import org.hyperledger.besu.consensus.ibft.payload.MessageFactory;
import org.hyperledger.besu.consensus.ibft.payload.PreparedCertificate;
import org.hyperledger.besu.consensus.ibft.payload.RoundChangeCertificate;
import org.hyperledger.besu.consensus.ibft.statemachine.PreparedRoundArtifacts;
import org.hyperledger.besu.consensus.ibft.validation.RoundChangePayloadValidator.MessageValidatorForHeightFactory;
@@ -32,6 +33,7 @@ import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.NodeKeyUtils;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Util;
import java.util.Collections;
@@ -221,4 +223,79 @@ public class RoundChangeCertificateValidatorTest {
roundIdentifier, roundChangeCert))
.isFalse();
}
@Test
public void latestPreparedCertificateIsExtractedFromRoundChangeCertificate() {
// NOTE: This function does not validate that all RoundCHanges/Prepares etc. come from valid
// sources, it is only responsible for determine which of the list or RoundChange messages
// contains the newest
// NOTE: This capability is tested as part of the NewRoundMessageValidationTests.
final NodeKey proposerKey = NodeKeyUtils.generate();
final MessageFactory proposerMessageFactory = new MessageFactory(proposerKey);
final Block proposedBlock = mock(Block.class);
when(proposedBlock.getHash()).thenReturn(Hash.fromHexStringLenient("1"));
final ConsensusRoundIdentifier roundIdentifier = new ConsensusRoundIdentifier(1, 4);
final ConsensusRoundIdentifier preparedRound = TestHelpers.createFrom(roundIdentifier, 0, -1);
final Proposal differentProposal =
proposerMessageFactory.createProposal(preparedRound, proposedBlock, Optional.empty());
final Optional<PreparedRoundArtifacts> latterPreparedRoundArtifacts =
Optional.of(
new PreparedRoundArtifacts(
differentProposal,
Lists.newArrayList(
proposerMessageFactory.createPrepare(roundIdentifier, proposedBlock.getHash()),
proposerMessageFactory.createPrepare(
roundIdentifier, proposedBlock.getHash()))));
// An earlier PrepareCert is added to ensure the path to find the latest PrepareCert
// is correctly followed.
final ConsensusRoundIdentifier earlierPreparedRound =
TestHelpers.createFrom(roundIdentifier, 0, -2);
final Proposal earlierProposal =
proposerMessageFactory.createProposal(
earlierPreparedRound, proposedBlock, Optional.empty());
final Optional<PreparedRoundArtifacts> earlierPreparedRoundArtifacts =
Optional.of(
new PreparedRoundArtifacts(
earlierProposal,
Lists.newArrayList(
proposerMessageFactory.createPrepare(
earlierPreparedRound, proposedBlock.getHash()),
proposerMessageFactory.createPrepare(
earlierPreparedRound, proposedBlock.getHash()))));
final Optional<PreparedCertificate> newestCert =
RoundChangeCertificateValidator.findLatestPreparedCertificate(
Lists.newArrayList(
proposerMessageFactory
.createRoundChange(roundIdentifier, earlierPreparedRoundArtifacts)
.getSignedPayload(),
proposerMessageFactory
.createRoundChange(roundIdentifier, latterPreparedRoundArtifacts)
.getSignedPayload()));
assertThat(newestCert.get())
.isEqualTo(latterPreparedRoundArtifacts.get().getPreparedCertificate());
}
@Test
public void allRoundChangeHaveNoPreparedReturnsEmptyOptional() {
final NodeKey proposerKey = NodeKeyUtils.generate();
final MessageFactory proposerMessageFactory = new MessageFactory(proposerKey);
final ConsensusRoundIdentifier roundIdentifier = new ConsensusRoundIdentifier(1, 4);
final Optional<PreparedCertificate> newestCert =
RoundChangeCertificateValidator.findLatestPreparedCertificate(
Lists.newArrayList(
proposerMessageFactory
.createRoundChange(roundIdentifier, Optional.empty())
.getSignedPayload(),
proposerMessageFactory
.createRoundChange(roundIdentifier, Optional.empty())
.getSignedPayload()));
assertThat(newestCert).isEmpty();
}
}

View File

@@ -31,6 +31,7 @@ dependencies {
implementation 'org.apache.tuweni:bytes'
implementation 'org.apache.tuweni:units'
testImplementation project(path: ':consensus:common', configuration: 'testSupportArtifacts')
testImplementation project(path: ':consensus:ibft', configuration: 'testSupportArtifacts')
testImplementation project(path: ':ethereum:core', configuration: 'testSupportArtifacts')
testImplementation project(':metrics:core')

View File

@@ -16,8 +16,8 @@ package org.hyperledger.besu.consensus.ibftlegacy;
import static org.hyperledger.besu.consensus.ibftlegacy.IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator;
import org.hyperledger.besu.config.BftConfigOptions;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.config.IbftConfigOptions;
import org.hyperledger.besu.ethereum.MainnetBlockValidator;
import org.hyperledger.besu.ethereum.core.PrivacyParameters;
import org.hyperledger.besu.ethereum.core.Wei;
@@ -38,7 +38,7 @@ public class IbftProtocolSchedule {
final GenesisConfigOptions config,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled) {
final IbftConfigOptions ibftConfig = config.getIbftLegacyConfigOptions();
final BftConfigOptions ibftConfig = config.getIbftLegacyConfigOptions();
final long blockPeriod = ibftConfig.getBlockPeriodSeconds();
return new ProtocolScheduleBuilder(

View File

@@ -15,7 +15,7 @@
package org.hyperledger.besu.consensus.ibftlegacy.headervalidationrules;
import org.hyperledger.besu.consensus.common.ValidatorProvider;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.consensus.ibftlegacy.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibftlegacy.IbftExtraData;
import org.hyperledger.besu.consensus.ibftlegacy.IbftHelpers;
@@ -55,7 +55,7 @@ public class IbftExtraDataValidationRule implements AttachedBlockHeaderValidatio
try {
final ValidatorProvider validatorProvider =
context
.getConsensusState(IbftContext.class)
.getConsensusState(BftContext.class)
.getVoteTallyCache()
.getVoteTallyAfterBlock(parent);
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);

View File

@@ -30,7 +30,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class IbftBlockHashingTest {
public class BftBlockHashingTest {
private static final Address PROPOSER_IN_HEADER =
Address.fromHexString("0x24defc2d149861d3d245749b81fe0e6b28e04f31");

View File

@@ -23,7 +23,7 @@ import static org.mockito.Mockito.when;
import org.hyperledger.besu.consensus.common.VoteTally;
import org.hyperledger.besu.consensus.common.VoteTallyCache;
import org.hyperledger.besu.consensus.ibft.IbftContext;
import org.hyperledger.besu.consensus.common.bft.BftContext;
import org.hyperledger.besu.crypto.SECP256K1;
import org.hyperledger.besu.crypto.SECP256K1.KeyPair;
import org.hyperledger.besu.crypto.SECP256K1.Signature;
@@ -43,17 +43,17 @@ import java.util.List;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftBlockHeaderValidationRulesetFactoryTest {
public class BftBlockHeaderValidationRulesetFactoryTest {
private ProtocolContext setupContextWithValidators(final Collection<Address> validators) {
final IbftContext ibftContext = mock(IbftContext.class);
final BftContext bftContext = mock(BftContext.class);
final VoteTallyCache mockCache = mock(VoteTallyCache.class);
final VoteTally mockVoteTally = mock(VoteTally.class);
when(ibftContext.getVoteTallyCache()).thenReturn(mockCache);
when(bftContext.getVoteTallyCache()).thenReturn(mockCache);
when(mockCache.getVoteTallyAfterBlock(any())).thenReturn(mockVoteTally);
when(mockVoteTally.getValidators()).thenReturn(validators);
return new ProtocolContext(null, null, ibftContext);
return new ProtocolContext(null, null, bftContext);
}
@Test

View File

@@ -31,7 +31,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
public class IbftExtraDataTest {
public class BftExtraDataTest {
@Test
public void emptyListsConstituteValidContent() {

View File

@@ -15,7 +15,7 @@
package org.hyperledger.besu.consensus.ibftlegacy.blockcreation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.ethereum.core.InMemoryStorageProvider.createInMemoryWorldStateArchive;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -52,7 +52,7 @@ import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class IbftBlockCreatorTest {
public class BftBlockCreatorTest {
private final MetricsSystem metricsSystem = new NoOpMetricsSystem();
@Test

View File

@@ -17,7 +17,7 @@ package org.hyperledger.besu.consensus.ibftlegacy.headervalidationrules;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import static org.hyperledger.besu.consensus.common.bft.BftContextBuilder.setupContextWithValidators;
import org.hyperledger.besu.consensus.ibftlegacy.IbftBlockHashing;
import org.hyperledger.besu.consensus.ibftlegacy.IbftExtraData;
@@ -41,7 +41,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class IbftExtraDataValidationRuleTest {
public class BftExtraDataValidationRuleTest {
private BlockHeader createProposedBlockHeader(
final KeyPair proposerKeyPair, final List<Address> validators) {

View File

@@ -35,6 +35,7 @@ dependencies {
implementation project(':config')
implementation project(':crypto')
implementation project(':consensus:clique')
implementation project(':consensus:common')
implementation project(':consensus:ibft')
implementation project(':ethereum:api')
implementation project(':ethereum:core')

View File

@@ -16,8 +16,8 @@
package org.hyperledger.besu.evmtool;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.consensus.clique.CliqueBlockHeaderFunctions;
import org.hyperledger.besu.consensus.clique.CliqueProtocolSchedule;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.crypto.KeyPairSecurityModule;
import org.hyperledger.besu.crypto.NodeKey;
import org.hyperledger.besu.crypto.SECP256K1;
@@ -45,6 +45,6 @@ class CliqueGenesisFileModule extends GenesisFileModule {
@Override
BlockHeaderFunctions blockHashFunction() {
return IbftBlockHeaderFunctions.forOnChainBlock();
return new CliqueBlockHeaderFunctions();
}
}

View File

@@ -16,8 +16,8 @@
package org.hyperledger.besu.evmtool;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.consensus.ibft.IbftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.ibft.IbftProtocolSchedule;
import org.hyperledger.besu.consensus.common.bft.BftBlockHeaderFunctions;
import org.hyperledger.besu.consensus.common.bft.BftProtocolSchedule;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
@@ -33,11 +33,11 @@ class IBFTGenesisFileModule extends GenesisFileModule {
ProtocolSchedule provideProtocolSchedule(
final GenesisConfigOptions configOptions,
@Named("RevertReasonEnabled") final boolean revertReasonEnabled) {
return IbftProtocolSchedule.create(configOptions);
return BftProtocolSchedule.create(configOptions);
}
@Override
BlockHeaderFunctions blockHashFunction() {
return IbftBlockHeaderFunctions.forOnChainBlock();
return BftBlockHeaderFunctions.forOnChainBlock();
}
}