Revert "[PAN-2950] Use java.time.Clock instead of System.currentTimeMillis()" (#1768)

This reverts commit 814b36e4
The needed chantes to get rid of Instant.now (which is also needed to get rid
of the wall clock dependency) are too deep and intrusive into IBFT to try and
speed patch them in that some APIs require re-work, so in the interst of test
stability this gets sheleved until it is all ready.
Signed-off-by: Adrian Sutton <adrian.sutton@consensys.net>
This commit is contained in:
Danno Ferrin
2019-07-26 11:53:36 -06:00
committed by GitHub
parent 8128a7c34b
commit 6f52d8bd83
104 changed files with 370 additions and 767 deletions

View File

@@ -63,16 +63,14 @@ public class ThreadPantheonNodeRunner implements PantheonNodeRunner {
private final Map<Node, PantheonPluginContextImpl> pantheonPluginContextMap = new HashMap<>();
private PantheonPluginContextImpl buildPluginContext(
final PantheonNode node, final CommandLine commandLine) {
final PantheonPluginContextImpl pantheonPluginContext = new PantheonPluginContextImpl();
private PantheonPluginContextImpl buildPluginContext(final PantheonNode node) {
PantheonPluginContextImpl pantheonPluginContext = new PantheonPluginContextImpl();
final Path pluginsPath = node.homeDirectory().resolve("plugins");
final File pluginsDirFile = pluginsPath.toFile();
if (!pluginsDirFile.isDirectory()) {
pluginsDirFile.mkdirs();
pluginsDirFile.deleteOnExit();
}
pantheonPluginContext.addService(PicoCLIOptions.class, new PicoCLIOptionsImpl(commandLine));
System.setProperty("pantheon.plugins.dir", pluginsPath.toString());
pantheonPluginContext.registerPlugins(pluginsPath);
return pantheonPluginContext;
@@ -87,7 +85,8 @@ public class ThreadPantheonNodeRunner implements PantheonNodeRunner {
final CommandLine commandLine = new CommandLine(CommandSpec.create());
final PantheonPluginContextImpl pantheonPluginContext =
pantheonPluginContextMap.computeIfAbsent(node, n -> buildPluginContext(node, commandLine));
pantheonPluginContextMap.computeIfAbsent(node, n -> buildPluginContext(node));
pantheonPluginContext.addService(PicoCLIOptions.class, new PicoCLIOptionsImpl(commandLine));
commandLine.parseArgs(node.getConfiguration().getExtraCLIOptions().toArray(new String[0]));
@@ -127,7 +126,7 @@ public class ThreadPantheonNodeRunner implements PantheonNodeRunner {
final RunnerBuilder runnerBuilder = new RunnerBuilder();
if (node.getPermissioningConfiguration().isPresent()) {
final PermissioningConfiguration permissioningConfiguration =
PermissioningConfiguration permissioningConfiguration =
node.getPermissioningConfiguration().get();
runnerBuilder.permissioningConfiguration(permissioningConfiguration);
@@ -152,7 +151,6 @@ public class ThreadPantheonNodeRunner implements PantheonNodeRunner {
.webSocketConfiguration(node.webSocketConfiguration())
.dataDir(node.homeDirectory())
.metricsSystem(noOpMetricsSystem)
.clock(Clock.systemUTC())
.metricsConfiguration(node.metricsConfiguration())
.p2pEnabled(node.isP2pEnabled())
.graphQLConfiguration(GraphQLConfiguration.createDefault())
@@ -169,7 +167,7 @@ public class ThreadPantheonNodeRunner implements PantheonNodeRunner {
@Override
public void stopNode(final PantheonNode node) {
final PantheonPluginContextImpl pluginContext = pantheonPluginContextMap.remove(node);
PantheonPluginContextImpl pluginContext = pantheonPluginContextMap.remove(node);
if (pluginContext != null) {
pluginContext.stopPlugins();
}

View File

@@ -28,8 +28,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.GasUsageVali
import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampBoundedByFutureParameter;
import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampMoreRecentThanParent;
import java.time.Clock;
public class BlockHeaderValidationRulesetFactory {
/**
@@ -40,17 +38,16 @@ public class BlockHeaderValidationRulesetFactory {
*
* @param secondsBetweenBlocks the minimum number of seconds which must elapse between blocks.
* @param epochManager an object which determines if a given block is an epoch block.
* @param clock System clock
* @return the header validator.
*/
public static BlockHeaderValidator<CliqueContext> cliqueBlockHeaderValidator(
final long secondsBetweenBlocks, final EpochManager epochManager, final Clock clock) {
final long secondsBetweenBlocks, final EpochManager epochManager) {
return new BlockHeaderValidator.Builder<CliqueContext>()
.addRule(new AncestryValidationRule())
.addRule(new GasUsageValidationRule())
.addRule(new GasLimitRangeAndDeltaValidationRule(5000, 0x7fffffffffffffffL))
.addRule(new TimestampBoundedByFutureParameter(10, clock))
.addRule(new TimestampBoundedByFutureParameter(10))
.addRule(new TimestampMoreRecentThanParent(secondsBetweenBlocks))
.addRule(new ConstantFieldValidationRule<>("MixHash", BlockHeader::getMixHash, Hash.ZERO))
.addRule(

View File

@@ -30,7 +30,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.ProtocolScheduleBuilder;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSpecBuilder;
import java.math.BigInteger;
import java.time.Clock;
/** Defines the protocol behaviours for a blockchain using Clique. */
public class CliqueProtocolSchedule {
@@ -41,8 +40,7 @@ public class CliqueProtocolSchedule {
final GenesisConfigOptions config,
final KeyPair nodeKeys,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
final CliqueConfigOptions cliqueConfig = config.getCliqueConfigOptions();
@@ -54,37 +52,28 @@ public class CliqueProtocolSchedule {
DEFAULT_CHAIN_ID,
builder ->
applyCliqueSpecificModifications(
epochManager,
cliqueConfig.getBlockPeriodSeconds(),
localNodeAddress,
builder,
clock),
epochManager, cliqueConfig.getBlockPeriodSeconds(), localNodeAddress, builder),
privacyParameters,
isRevertReasonEnabled,
clock)
isRevertReasonEnabled)
.createProtocolSchedule();
}
public static ProtocolSchedule<CliqueContext> create(
final GenesisConfigOptions config,
final KeyPair nodeKeys,
final boolean isRevertReasonEnabled,
final Clock clock) {
return create(config, nodeKeys, PrivacyParameters.DEFAULT, isRevertReasonEnabled, clock);
final boolean isRevertReasonEnabled) {
return create(config, nodeKeys, PrivacyParameters.DEFAULT, isRevertReasonEnabled);
}
private static ProtocolSpecBuilder<CliqueContext> applyCliqueSpecificModifications(
final EpochManager epochManager,
final long secondsBetweenBlocks,
final Address localNodeAddress,
final ProtocolSpecBuilder<Void> specBuilder,
final Clock clock) {
final ProtocolSpecBuilder<Void> specBuilder) {
return specBuilder
.changeConsensusContextType(
difficultyCalculator ->
cliqueBlockHeaderValidator(secondsBetweenBlocks, epochManager, clock),
difficultyCalculator ->
cliqueBlockHeaderValidator(secondsBetweenBlocks, epochManager, clock),
difficultyCalculator -> cliqueBlockHeaderValidator(secondsBetweenBlocks, epochManager),
difficultyCalculator -> cliqueBlockHeaderValidator(secondsBetweenBlocks, epochManager),
MainnetBlockBodyValidator::new,
MainnetBlockValidator::new,
MainnetBlockImporter::new,

View File

@@ -20,7 +20,6 @@ import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
import tech.pegasys.pantheon.ethereum.core.Wei;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSpec;
import tech.pegasys.pantheon.testutil.TestClock;
import org.junit.Test;
@@ -42,7 +41,7 @@ public class CliqueProtocolScheduleTest {
final GenesisConfigOptions config = GenesisConfigFile.fromConfig(jsonInput).getConfigOptions();
final ProtocolSchedule<CliqueContext> protocolSchedule =
CliqueProtocolSchedule.create(config, NODE_KEYS, false, TestClock.fixed());
CliqueProtocolSchedule.create(config, NODE_KEYS, false);
final ProtocolSpec<CliqueContext> homesteadSpec = protocolSchedule.getByBlockNumber(1);
final ProtocolSpec<CliqueContext> tangerineWhistleSpec = protocolSchedule.getByBlockNumber(2);
@@ -58,7 +57,7 @@ public class CliqueProtocolScheduleTest {
public void parametersAlignWithMainnetWithAdjustments() {
final ProtocolSpec<CliqueContext> homestead =
CliqueProtocolSchedule.create(
GenesisConfigFile.DEFAULT.getConfigOptions(), NODE_KEYS, false, TestClock.fixed())
GenesisConfigFile.DEFAULT.getConfigOptions(), NODE_KEYS, false)
.getByBlockNumber(0);
assertThat(homestead.getName()).isEqualTo("Frontier");

View File

@@ -76,10 +76,7 @@ public class CliqueBlockCreatorTest {
public void setup() {
protocolSchedule =
CliqueProtocolSchedule.create(
GenesisConfigFile.DEFAULT.getConfigOptions(),
proposerKeyPair,
false,
TestClock.fixed());
GenesisConfigFile.DEFAULT.getConfigOptions(), proposerKeyPair, false);
final Address otherAddress = Util.publicKeyToAddress(otherKeyPair.getPublicKey());
validatorList.add(otherAddress);

View File

@@ -90,8 +90,7 @@ public class CliqueMinerExecutorTest {
new CliqueMinerExecutor(
cliqueProtocolContext,
Executors.newSingleThreadExecutor(),
CliqueProtocolSchedule.create(
GENESIS_CONFIG_OPTIONS, proposerKeyPair, false, TestClock.fixed()),
CliqueProtocolSchedule.create(GENESIS_CONFIG_OPTIONS, proposerKeyPair, false),
new PendingTransactions(
TransactionPoolConfiguration.DEFAULT_TX_RETENTION_HOURS,
1,
@@ -128,8 +127,7 @@ public class CliqueMinerExecutorTest {
new CliqueMinerExecutor(
cliqueProtocolContext,
Executors.newSingleThreadExecutor(),
CliqueProtocolSchedule.create(
GENESIS_CONFIG_OPTIONS, proposerKeyPair, false, TestClock.fixed()),
CliqueProtocolSchedule.create(GENESIS_CONFIG_OPTIONS, proposerKeyPair, false),
new PendingTransactions(
TransactionPoolConfiguration.DEFAULT_TX_RETENTION_HOURS,
1,
@@ -166,8 +164,7 @@ public class CliqueMinerExecutorTest {
new CliqueMinerExecutor(
cliqueProtocolContext,
Executors.newSingleThreadExecutor(),
CliqueProtocolSchedule.create(
GENESIS_CONFIG_OPTIONS, proposerKeyPair, false, TestClock.fixed()),
CliqueProtocolSchedule.create(GENESIS_CONFIG_OPTIONS, proposerKeyPair, false),
new PendingTransactions(
TransactionPoolConfiguration.DEFAULT_TX_RETENTION_HOURS,
1,

View File

@@ -12,7 +12,6 @@
*/
package tech.pegasys.pantheon.consensus.ibft.support;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.mockito.Mockito.mock;
import static tech.pegasys.pantheon.ethereum.core.InMemoryStorageProvider.createInMemoryBlockchain;
@@ -160,8 +159,6 @@ public class TestContextBuilder {
}
public TestContext build() {
checkNotNull(clock);
final NetworkLayout networkNodes =
NetworkLayout.createNetworkLayout(validatorCount, indexOfFirstLocallyProposedBlock);
@@ -266,7 +263,7 @@ public class TestContextBuilder {
genesisConfigOptions.byzantiumBlock(0);
final ProtocolSchedule<IbftContext> protocolSchedule =
IbftProtocolSchedule.create(genesisConfigOptions, Clock.systemUTC());
IbftProtocolSchedule.create(genesisConfigOptions);
/////////////////////////////////////////////////////////////////////////////////////
// From here down is BASICALLY taken from IbftPantheonController

View File

@@ -26,8 +26,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampBou
import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampMoreRecentThanParent;
import tech.pegasys.pantheon.util.uint.UInt256;
import java.time.Clock;
public class IbftBlockHeaderValidationRulesetFactory {
/**
@@ -35,16 +33,15 @@ public class IbftBlockHeaderValidationRulesetFactory {
* 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.
* @param clock System clock
* @return BlockHeaderValidator configured for assessing ibft block headers
*/
public static BlockHeaderValidator<IbftContext> ibftBlockHeaderValidator(
final long secondsBetweenBlocks, final Clock clock) {
final long secondsBetweenBlocks) {
return new BlockHeaderValidator.Builder<IbftContext>()
.addRule(new AncestryValidationRule())
.addRule(new GasUsageValidationRule())
.addRule(new GasLimitRangeAndDeltaValidationRule(5000, 0x7fffffffffffffffL))
.addRule(new TimestampBoundedByFutureParameter(1, clock))
.addRule(new TimestampBoundedByFutureParameter(1))
.addRule(new TimestampMoreRecentThanParent(secondsBetweenBlocks))
.addRule(
new ConstantFieldValidationRule<>(

View File

@@ -26,7 +26,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.ProtocolScheduleBuilder;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSpecBuilder;
import java.math.BigInteger;
import java.time.Clock;
/** Defines the protocol behaviours for a blockchain using IBFT. */
public class IbftProtocolSchedule {
@@ -36,37 +35,34 @@ public class IbftProtocolSchedule {
public static ProtocolSchedule<IbftContext> create(
final GenesisConfigOptions config,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
final IbftConfigOptions ibftConfig = config.getIbftLegacyConfigOptions();
final long blockPeriod = ibftConfig.getBlockPeriodSeconds();
return new ProtocolScheduleBuilder<>(
config,
DEFAULT_CHAIN_ID,
builder -> applyIbftChanges(blockPeriod, builder, clock),
builder -> applyIbftChanges(blockPeriod, builder),
privacyParameters,
isRevertReasonEnabled,
clock)
isRevertReasonEnabled)
.createProtocolSchedule();
}
public static ProtocolSchedule<IbftContext> create(
final GenesisConfigOptions config, final boolean isRevertReasonEnabled, final Clock clock) {
return create(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled, clock);
final GenesisConfigOptions config, final boolean isRevertReasonEnabled) {
return create(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled);
}
public static ProtocolSchedule<IbftContext> create(
final GenesisConfigOptions config, final Clock clock) {
return create(config, PrivacyParameters.DEFAULT, false, clock);
public static ProtocolSchedule<IbftContext> create(final GenesisConfigOptions config) {
return create(config, PrivacyParameters.DEFAULT, false);
}
private static ProtocolSpecBuilder<IbftContext> applyIbftChanges(
final long secondsBetweenBlocks, final ProtocolSpecBuilder<Void> builder, final Clock clock) {
final long secondsBetweenBlocks, final ProtocolSpecBuilder<Void> builder) {
return builder
.<IbftContext>changeConsensusContextType(
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks, clock),
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks, clock),
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks),
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks),
MainnetBlockBodyValidator::new,
MainnetBlockValidator::new,
MainnetBlockImporter::new,

View File

@@ -26,7 +26,6 @@ import tech.pegasys.pantheon.ethereum.core.Hash;
import tech.pegasys.pantheon.ethereum.core.Util;
import tech.pegasys.pantheon.ethereum.mainnet.BlockHeaderValidator;
import tech.pegasys.pantheon.ethereum.mainnet.HeaderValidationMode;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import tech.pegasys.pantheon.util.uint.UInt256;
@@ -55,7 +54,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerKeyPair, validators, parentHeader).buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -76,7 +75,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerKeyPair, emptyList(), parentHeader).buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -101,7 +100,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -122,7 +121,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerKeyPair, validators, parentHeader).nonce(3).buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -145,7 +144,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -168,7 +167,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -191,7 +190,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -214,7 +213,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -235,7 +234,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(2, proposerKeyPair, validators, null).buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -259,7 +258,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -282,7 +281,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
.buildHeader();
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(

View File

@@ -75,8 +75,7 @@ public class IbftBlockCreatorTest {
final ProtocolSchedule<IbftContext> protocolSchedule =
IbftProtocolSchedule.create(
GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}")
.getConfigOptions(),
TestClock.fixed());
.getConfigOptions());
final ProtocolContext<IbftContext> protContext =
new ProtocolContext<>(
blockchain,
@@ -111,7 +110,7 @@ public class IbftBlockCreatorTest {
final Block block = blockCreator.createBlock(Instant.now().getEpochSecond());
final BlockHeaderValidator<IbftContext> rules =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(0, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(0);
// NOTE: The header will not contain commit seals, so can only do light validation on header.
final boolean validationResult =

View File

@@ -26,8 +26,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampBou
import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampMoreRecentThanParent;
import tech.pegasys.pantheon.util.uint.UInt256;
import java.time.Clock;
public class IbftBlockHeaderValidationRulesetFactory {
/**
@@ -35,12 +33,11 @@ public class IbftBlockHeaderValidationRulesetFactory {
* 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.
* @param clock System clock
* @return BlockHeaderValidator configured for assessing ibft block headers
*/
public static BlockHeaderValidator<IbftContext> ibftBlockHeaderValidator(
final long secondsBetweenBlocks, final Clock clock) {
return createValidator(secondsBetweenBlocks, true, clock);
final long secondsBetweenBlocks) {
return createValidator(secondsBetweenBlocks, true);
}
/**
@@ -48,21 +45,20 @@ public class IbftBlockHeaderValidationRulesetFactory {
* which need to be vetted by the validators, and do not contain commit seals).
*
* @param secondsBetweenBlocks the minimum number of seconds which must elapse between blocks.
* @param clock System clock
* @return BlockHeaderValidator configured for assessing ibft block headers
*/
public static BlockHeaderValidator<IbftContext> ibftProposedBlockValidator(
final long secondsBetweenBlocks, final Clock clock) {
return createValidator(secondsBetweenBlocks, false, clock);
final long secondsBetweenBlocks) {
return createValidator(secondsBetweenBlocks, false);
}
private static BlockHeaderValidator<IbftContext> createValidator(
final long secondsBetweenBlocks, final boolean validateCommitSeals, final Clock clock) {
final long secondsBetweenBlocks, final boolean validateCommitSeals) {
return new BlockHeaderValidator.Builder<IbftContext>()
.addRule(new AncestryValidationRule())
.addRule(new GasUsageValidationRule())
.addRule(new GasLimitRangeAndDeltaValidationRule(5000, 0x7fffffffffffffffL))
.addRule(new TimestampBoundedByFutureParameter(1, clock))
.addRule(new TimestampBoundedByFutureParameter(1))
.addRule(new TimestampMoreRecentThanParent(secondsBetweenBlocks))
.addRule(
new ConstantFieldValidationRule<>(

View File

@@ -27,7 +27,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.ProtocolScheduleBuilder;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSpecBuilder;
import java.math.BigInteger;
import java.time.Clock;
/** Defines the protocol behaviours for a blockchain using IBFT. */
public class IbftProtocolSchedule {
@@ -37,32 +36,30 @@ public class IbftProtocolSchedule {
public static ProtocolSchedule<IbftContext> create(
final GenesisConfigOptions config,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
final IbftConfigOptions ibftConfig = config.getIbftLegacyConfigOptions();
final long blockPeriod = ibftConfig.getBlockPeriodSeconds();
return new ProtocolScheduleBuilder<>(
config,
DEFAULT_CHAIN_ID,
builder -> applyIbftChanges(blockPeriod, builder, clock),
builder -> applyIbftChanges(blockPeriod, builder),
privacyParameters,
isRevertReasonEnabled,
clock)
isRevertReasonEnabled)
.createProtocolSchedule();
}
public static ProtocolSchedule<IbftContext> create(
final GenesisConfigOptions config, final boolean isRevertReasonEnabled, final Clock clock) {
return create(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled, clock);
final GenesisConfigOptions config, final boolean isRevertReasonEnabled) {
return create(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled);
}
private static ProtocolSpecBuilder<IbftContext> applyIbftChanges(
final long secondsBetweenBlocks, final ProtocolSpecBuilder<Void> builder, final Clock clock) {
final long secondsBetweenBlocks, final ProtocolSpecBuilder<Void> builder) {
return builder
.<IbftContext>changeConsensusContextType(
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks, clock),
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks, clock),
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks),
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks),
MainnetBlockBodyValidator::new,
MainnetBlockValidator::new,
MainnetBlockImporter::new,

View File

@@ -32,7 +32,6 @@ import tech.pegasys.pantheon.ethereum.core.BlockHeaderTestFixture;
import tech.pegasys.pantheon.ethereum.core.Hash;
import tech.pegasys.pantheon.ethereum.mainnet.BlockHeaderValidator;
import tech.pegasys.pantheon.ethereum.mainnet.HeaderValidationMode;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import tech.pegasys.pantheon.util.uint.UInt256;
@@ -68,7 +67,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
final BlockHeader blockHeader = buildBlockHeader(2, proposerKeyPair, validators, parentHeader);
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(
@@ -91,7 +90,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
final BlockHeader blockHeader = buildBlockHeader(2, proposerKeyPair, validators, null);
final BlockHeaderValidator<IbftContext> validator =
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5, TestClock.fixed());
IbftBlockHeaderValidationRulesetFactory.ibftBlockHeaderValidator(5);
assertThat(
validator.validateHeader(

View File

@@ -43,7 +43,7 @@ import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@@ -78,13 +78,11 @@ public class IbftBlockCreatorTest {
Address.fromHexString(String.format("%020d", 4)),
localAddr);
Clock testClock = TestClock.fixed();
final ProtocolSchedule<IbftContext> protocolSchedule =
IbftProtocolSchedule.create(
GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}")
.getConfigOptions(),
false,
testClock);
false);
final ProtocolContext<IbftContext> protContext =
new ProtocolContext<>(
blockchain,
@@ -104,7 +102,7 @@ public class IbftBlockCreatorTest {
new PendingTransactions(
TransactionPoolConfiguration.DEFAULT_TX_RETENTION_HOURS,
1,
testClock,
TestClock.fixed(),
metricsSystem),
protContext,
protocolSchedule,
@@ -113,10 +111,10 @@ public class IbftBlockCreatorTest {
Wei.ZERO,
parentHeader);
final Block block = blockCreator.createBlock(testClock.instant().getEpochSecond());
final Block block = blockCreator.createBlock(Instant.now().getEpochSecond());
final BlockHeaderValidator<IbftContext> rules =
IbftBlockHeaderValidationRulesetFactory.ibftProposedBlockValidator(0, testClock);
IbftBlockHeaderValidationRulesetFactory.ibftProposedBlockValidator(0);
final boolean validationResult =
rules.validateHeader(

View File

@@ -15,6 +15,7 @@ package tech.pegasys.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import java.util.Map;
@@ -22,7 +23,6 @@ import java.util.Map;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.matchers.Description;
@@ -34,15 +34,12 @@ import com.sun.source.tree.MethodInvocationTree;
@BugPattern(
name = "BannedMethod",
summary = "Some methods should not be used, make sure that doesn't happen.",
severity = WARNING,
linkType = LinkType.NONE)
severity = WARNING)
public class BannedMethod extends BugChecker implements MethodInvocationTreeMatcher {
private static final ImmutableMap<Matcher<ExpressionTree>, String> BANNED_METHOD_LIST =
ImmutableMap.of(
staticMethod().onClass("java.lang.System").named("currentTimeMillis"),
"Do not use System.currentTimeMillis(), use a java.time.Clock passed into a constructor or as a static method parameter.",
staticMethod().onClass("com.google.common.base.Objects").withAnyName(),
allOf(staticMethod().onClass("com.google.common.base.Objects").withAnyName()),
"Do not use com.google.common.base.Objects methods, use java.util.Objects methods instead.");
@Override

View File

@@ -13,7 +13,6 @@
package tech.pegasys.errorpronechecks;
import java.util.Objects;
import java.time.Clock;
public class BannedMethodNegativeCases {
@@ -24,9 +23,4 @@ public class BannedMethodNegativeCases {
public void callsObjectsHashCode() throws Exception {
Objects.hash("1", "1");
}
public void callsClockMillis(final Clock clock) throws Exception {
clock.millis();
}
}

View File

@@ -27,10 +27,4 @@ public class BannedMethodPositiveCases {
// java.util.Objects methods instead.
Objects.hashCode("1", "1");
}
public void callsSystemCurrentTimeMillis() throws Exception {
// BUG: Diagnostic contains: Do not use System.currentTimeMillis(), use a java.time.Clock
// passed into a constructor or as a static method parameter.
System.currentTimeMillis();
}
}

View File

@@ -93,8 +93,7 @@ public class BlockTransactionSelectorTest {
@Test
public void emptyPendingTransactionsResultsInEmptyVettingResult() {
final ProtocolSchedule<Void> protocolSchedule =
FixedDifficultyProtocolSchedule.create(
GenesisConfigFile.development().getConfigOptions(), TestClock.fixed());
FixedDifficultyProtocolSchedule.create(GenesisConfigFile.development().getConfigOptions());
final TransactionProcessor mainnetTransactionProcessor =
protocolSchedule.getByBlockNumber(0).getTransactionProcessor();

View File

@@ -58,10 +58,8 @@ public class EthHashBlockCreatorTest {
BigInteger.valueOf(42),
Function.identity(),
PrivacyParameters.DEFAULT,
false,
TestClock.fixed())
false)
.createProtocolSchedule())
.clock(TestClock.fixed())
.build();
@Test

View File

@@ -30,7 +30,6 @@ import tech.pegasys.pantheon.util.uint.UInt256;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import com.google.common.io.MoreFiles;
import com.google.common.io.RecursiveDeleteOption;
@@ -58,10 +57,7 @@ public class OperationBenchmarkHelper {
new NoOpMetricsSystem());
final ExecutionContextTestFixture executionContext =
ExecutionContextTestFixture.builder()
.keyValueStorage(keyValueStorage)
.clock(Clock.systemUTC())
.build();
ExecutionContextTestFixture.builder().keyValueStorage(keyValueStorage).build();
final MutableBlockchain blockchain = executionContext.getBlockchain();
for (int i = 1; i < 256; i++) {

View File

@@ -17,32 +17,27 @@ import tech.pegasys.pantheon.ethereum.core.PrivacyParameters;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolScheduleBuilder;
import java.time.Clock;
/** A ProtocolSchedule which behaves similarly to MainNet, but with a much reduced difficulty. */
public class FixedDifficultyProtocolSchedule {
public static ProtocolSchedule<Void> create(
final GenesisConfigOptions config,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
return new ProtocolScheduleBuilder<>(
config,
builder -> builder.difficultyCalculator(FixedDifficultyCalculators.calculator(config)),
privacyParameters,
isRevertReasonEnabled,
clock)
isRevertReasonEnabled)
.createProtocolSchedule();
}
public static ProtocolSchedule<Void> create(
final GenesisConfigOptions config, final boolean isRevertReasonEnabled, final Clock clock) {
return create(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled, clock);
final GenesisConfigOptions config, final boolean isRevertReasonEnabled) {
return create(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled);
}
public static ProtocolSchedule<Void> create(
final GenesisConfigOptions config, final Clock clock) {
return create(config, PrivacyParameters.DEFAULT, false, clock);
public static ProtocolSchedule<Void> create(final GenesisConfigOptions config) {
return create(config, PrivacyParameters.DEFAULT, false);
}
}

View File

@@ -24,8 +24,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampBou
import tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules.TimestampMoreRecentThanParent;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
public final class MainnetBlockHeaderValidator {
public static final BytesValue DAO_EXTRA_DATA =
@@ -36,13 +34,13 @@ public final class MainnetBlockHeaderValidator {
public static final int MINIMUM_SECONDS_SINCE_PARENT = 1;
public static BlockHeaderValidator<Void> create(
final DifficultyCalculator<Void> difficultyCalculator, final Clock clock) {
return createValidator(difficultyCalculator, clock).build();
final DifficultyCalculator<Void> difficultyCalculator) {
return createValidator(difficultyCalculator).build();
}
static BlockHeaderValidator<Void> createDaoValidator(
final DifficultyCalculator<Void> difficultyCalculator, final Clock clock) {
return createValidator(difficultyCalculator, clock)
public static BlockHeaderValidator<Void> createDaoValidator(
final DifficultyCalculator<Void> difficultyCalculator) {
return createValidator(difficultyCalculator)
.addRule(
new ConstantFieldValidationRule<>(
"extraData", BlockHeader::getExtraData, DAO_EXTRA_DATA))
@@ -67,14 +65,14 @@ public final class MainnetBlockHeaderValidator {
}
private static BlockHeaderValidator.Builder<Void> createValidator(
final DifficultyCalculator<Void> difficultyCalculator, final Clock clock) {
final DifficultyCalculator<Void> difficultyCalculator) {
return new BlockHeaderValidator.Builder<Void>()
.addRule(new CalculatedDifficultyValidationRule<>(difficultyCalculator))
.addRule(new AncestryValidationRule())
.addRule(new GasLimitRangeAndDeltaValidationRule(MIN_GAS_LIMIT, MAX_GAS_LIMIT))
.addRule(new GasUsageValidationRule())
.addRule(new TimestampMoreRecentThanParent(MINIMUM_SECONDS_SINCE_PARENT))
.addRule(new TimestampBoundedByFutureParameter(TIMESTAMP_TOLERANCE_S, clock))
.addRule(new TimestampBoundedByFutureParameter(TIMESTAMP_TOLERANCE_S))
.addRule(new ExtraDataMaxLengthValidationRule(BlockHeader.MAX_EXTRA_DATA_BYTES))
.addRule(new ProofOfWorkValidationRule());
}

View File

@@ -19,7 +19,6 @@ import tech.pegasys.pantheon.ethereum.difficulty.fixed.FixedDifficultyCalculator
import tech.pegasys.pantheon.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule;
import java.math.BigInteger;
import java.time.Clock;
import java.util.function.Function;
/** Provides {@link ProtocolSpec} lookups for mainnet hard forks. */
@@ -27,9 +26,9 @@ public class MainnetProtocolSchedule {
public static final BigInteger DEFAULT_CHAIN_ID = BigInteger.ONE;
public static ProtocolSchedule<Void> create(final Clock clock) {
public static ProtocolSchedule<Void> create() {
return fromConfig(
GenesisConfigFile.mainnet().getConfigOptions(), PrivacyParameters.DEFAULT, false, clock);
GenesisConfigFile.mainnet().getConfigOptions(), PrivacyParameters.DEFAULT, false);
}
/**
@@ -39,25 +38,18 @@ public class MainnetProtocolSchedule {
* starting points
* @param privacyParameters the parameters set for private transactions
* @param isRevertReasonEnabled whether storing the revert reason is for failed transactions
* @param clock System clock
* @return A configured mainnet protocol schedule
*/
public static ProtocolSchedule<Void> fromConfig(
final GenesisConfigOptions config,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
if (FixedDifficultyCalculators.isFixedDifficultyInConfig(config)) {
return FixedDifficultyProtocolSchedule.create(
config, privacyParameters, isRevertReasonEnabled, clock);
config, privacyParameters, isRevertReasonEnabled);
}
return new ProtocolScheduleBuilder<Void>(
config,
DEFAULT_CHAIN_ID,
Function.identity(),
privacyParameters,
isRevertReasonEnabled,
clock)
return new ProtocolScheduleBuilder<>(
config, DEFAULT_CHAIN_ID, Function.identity(), privacyParameters, isRevertReasonEnabled)
.createProtocolSchedule();
}
@@ -67,12 +59,11 @@ public class MainnetProtocolSchedule {
* @param config {@link GenesisConfigOptions} containing the config options for the milestone
* starting points
* @param isRevertReasonEnabled whether storing the revert reason is for failed transactions
* @param clock System clock
* @return A configured mainnet protocol schedule
*/
public static ProtocolSchedule<Void> fromConfig(
final GenesisConfigOptions config, final boolean isRevertReasonEnabled, final Clock clock) {
return fromConfig(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled, clock);
final GenesisConfigOptions config, final boolean isRevertReasonEnabled) {
return fromConfig(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled);
}
/**
@@ -80,11 +71,9 @@ public class MainnetProtocolSchedule {
*
* @param config {@link GenesisConfigOptions} containing the config options for the milestone
* starting points
* @param clock System clock
* @return A configured mainnet protocol schedule
*/
public static ProtocolSchedule<Void> fromConfig(
final GenesisConfigOptions config, final Clock clock) {
return fromConfig(config, PrivacyParameters.DEFAULT, false, clock);
public static ProtocolSchedule<Void> fromConfig(final GenesisConfigOptions config) {
return fromConfig(config, PrivacyParameters.DEFAULT, false);
}
}

View File

@@ -34,7 +34,6 @@ import tech.pegasys.pantheon.ethereum.privacy.PrivateTransactionValidator;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -73,9 +72,7 @@ public abstract class MainnetProtocolSpecs {
private MainnetProtocolSpecs() {}
public static ProtocolSpecBuilder<Void> frontierDefinition(
final OptionalInt configContractSizeLimit,
final OptionalInt configStackSizeLimit,
final Clock clock) {
final OptionalInt configContractSizeLimit, final OptionalInt configStackSizeLimit) {
final int contractSizeLimit = configContractSizeLimit.orElse(FRONTIER_CONTRACT_SIZE_LIMIT);
final int stackSizeLimit = configStackSizeLimit.orElse(DEFAULT_MAX_STACK_SIZE);
return new ProtocolSpecBuilder<Void>()
@@ -123,8 +120,7 @@ public abstract class MainnetProtocolSpecs {
Account.DEFAULT_VERSION,
new PrivateTransactionValidator(Optional.empty())))
.difficultyCalculator(MainnetDifficultyCalculators.FRONTIER)
.blockHeaderValidatorBuilder(
difficultyCalculator -> MainnetBlockHeaderValidator.create(difficultyCalculator, clock))
.blockHeaderValidatorBuilder(MainnetBlockHeaderValidator::create)
.ommerHeaderValidatorBuilder(MainnetBlockHeaderValidator::createOmmerValidator)
.blockBodyValidatorBuilder(MainnetBlockBodyValidator::new)
.transactionReceiptFactory(MainnetProtocolSpecs::frontierTransactionReceiptFactory)
@@ -139,11 +135,9 @@ public abstract class MainnetProtocolSpecs {
}
public static ProtocolSpecBuilder<Void> homesteadDefinition(
final OptionalInt configContractSizeLimit,
final OptionalInt configStackSizeLimit,
final Clock clock) {
final OptionalInt configContractSizeLimit, final OptionalInt configStackSizeLimit) {
final int contractSizeLimit = configContractSizeLimit.orElse(FRONTIER_CONTRACT_SIZE_LIMIT);
return frontierDefinition(configContractSizeLimit, configStackSizeLimit, clock)
return frontierDefinition(configContractSizeLimit, configStackSizeLimit)
.gasCalculator(HomesteadGasCalculator::new)
.evmBuilder(MainnetEvmRegistries::homestead)
.contractCreationProcessorBuilder(
@@ -161,13 +155,9 @@ public abstract class MainnetProtocolSpecs {
}
public static ProtocolSpecBuilder<Void> daoRecoveryInitDefinition(
final OptionalInt contractSizeLimit,
final OptionalInt configStackSizeLimit,
final Clock clock) {
return homesteadDefinition(contractSizeLimit, configStackSizeLimit, clock)
.blockHeaderValidatorBuilder(
difficultyCalculator ->
MainnetBlockHeaderValidator.createDaoValidator(difficultyCalculator, clock))
final OptionalInt contractSizeLimit, final OptionalInt configStackSizeLimit) {
return homesteadDefinition(contractSizeLimit, configStackSizeLimit)
.blockHeaderValidatorBuilder(MainnetBlockHeaderValidator::createDaoValidator)
.blockProcessorBuilder(
(transactionProcessor,
transactionReceiptFactory,
@@ -183,19 +173,15 @@ public abstract class MainnetProtocolSpecs {
}
public static ProtocolSpecBuilder<Void> daoRecoveryTransitionDefinition(
final OptionalInt contractSizeLimit,
final OptionalInt configStackSizeLimit,
final Clock clock) {
return daoRecoveryInitDefinition(contractSizeLimit, configStackSizeLimit, clock)
final OptionalInt contractSizeLimit, final OptionalInt configStackSizeLimit) {
return daoRecoveryInitDefinition(contractSizeLimit, configStackSizeLimit)
.blockProcessorBuilder(MainnetBlockProcessor::new)
.name("DaoRecoveryTransition");
}
public static ProtocolSpecBuilder<Void> tangerineWhistleDefinition(
final OptionalInt contractSizeLimit,
final OptionalInt configStackSizeLimit,
final Clock clock) {
return homesteadDefinition(contractSizeLimit, configStackSizeLimit, clock)
final OptionalInt contractSizeLimit, final OptionalInt configStackSizeLimit) {
return homesteadDefinition(contractSizeLimit, configStackSizeLimit)
.gasCalculator(TangerineWhistleGasCalculator::new)
.name("TangerineWhistle");
}
@@ -203,13 +189,12 @@ public abstract class MainnetProtocolSpecs {
public static ProtocolSpecBuilder<Void> spuriousDragonDefinition(
final Optional<BigInteger> chainId,
final OptionalInt configContractSizeLimit,
final OptionalInt configStackSizeLimit,
final Clock clock) {
final OptionalInt configStackSizeLimit) {
final int contractSizeLimit =
configContractSizeLimit.orElse(SPURIOUS_DRAGON_CONTRACT_SIZE_LIMIT);
final int stackSizeLimit = configStackSizeLimit.orElse(DEFAULT_MAX_STACK_SIZE);
return tangerineWhistleDefinition(OptionalInt.empty(), configStackSizeLimit, clock)
return tangerineWhistleDefinition(OptionalInt.empty(), configStackSizeLimit)
.gasCalculator(SpuriousDragonGasCalculator::new)
.messageCallProcessorBuilder(
(evm, precompileContractRegistry) ->
@@ -264,9 +249,8 @@ public abstract class MainnetProtocolSpecs {
final Optional<BigInteger> chainId,
final OptionalInt contractSizeLimit,
final OptionalInt configStackSizeLimit,
final boolean enableRevertReason,
final Clock clock) {
return spuriousDragonDefinition(chainId, contractSizeLimit, configStackSizeLimit, clock)
final boolean enableRevertReason) {
return spuriousDragonDefinition(chainId, contractSizeLimit, configStackSizeLimit)
.evmBuilder(MainnetEvmRegistries::byzantium)
.precompileContractRegistryBuilder(MainnetPrecompiledContractRegistries::byzantium)
.difficultyCalculator(MainnetDifficultyCalculators.BYZANTIUM)
@@ -283,10 +267,8 @@ public abstract class MainnetProtocolSpecs {
final Optional<BigInteger> chainId,
final OptionalInt contractSizeLimit,
final OptionalInt configStackSizeLimit,
final boolean enableRevertReason,
final Clock clock) {
return byzantiumDefinition(
chainId, contractSizeLimit, configStackSizeLimit, enableRevertReason, clock)
final boolean enableRevertReason) {
return byzantiumDefinition(chainId, contractSizeLimit, configStackSizeLimit, enableRevertReason)
.difficultyCalculator(MainnetDifficultyCalculators.CONSTANTINOPLE)
.gasCalculator(ConstantinopleGasCalculator::new)
.evmBuilder(MainnetEvmRegistries::constantinople)
@@ -298,10 +280,9 @@ public abstract class MainnetProtocolSpecs {
final Optional<BigInteger> chainId,
final OptionalInt contractSizeLimit,
final OptionalInt configStackSizeLimit,
final boolean enableRevertReason,
final Clock clock) {
final boolean enableRevertReason) {
return constantinopleDefinition(
chainId, contractSizeLimit, configStackSizeLimit, enableRevertReason, clock)
chainId, contractSizeLimit, configStackSizeLimit, enableRevertReason)
.gasCalculator(ConstantinopleFixGasCalculator::new)
.name("ConstantinopleFix");
}
@@ -310,14 +291,13 @@ public abstract class MainnetProtocolSpecs {
final Optional<BigInteger> chainId,
final OptionalInt configContractSizeLimit,
final OptionalInt configStackSizeLimit,
final boolean enableRevertReason,
final Clock clock) {
final boolean enableRevertReason) {
checkArgument(chainId.isPresent(), "Istanbul requires the use of chainId");
final int contractSizeLimit =
configContractSizeLimit.orElse(SPURIOUS_DRAGON_CONTRACT_SIZE_LIMIT);
final int stackSizeLimit = configStackSizeLimit.orElse(DEFAULT_MAX_STACK_SIZE);
return constantinopleFixDefinition(
chainId, configContractSizeLimit, configStackSizeLimit, enableRevertReason, clock)
chainId, configContractSizeLimit, configStackSizeLimit, enableRevertReason)
.gasCalculator(IstanbulGasCalculator::new)
.evmBuilder(gasCalculator -> MainnetEvmRegistries.istanbul(gasCalculator, chainId.get()))
.precompileContractRegistryBuilder(MainnetPrecompiledContractRegistries::istanbul)

View File

@@ -17,7 +17,6 @@ import tech.pegasys.pantheon.ethereum.core.PrivacyParameters;
import tech.pegasys.pantheon.ethereum.privacy.PrivateTransactionValidator;
import java.math.BigInteger;
import java.time.Clock;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.Function;
@@ -33,37 +32,27 @@ public class ProtocolScheduleBuilder<C> {
private final Optional<BigInteger> defaultChainId;
private final PrivacyParameters privacyParameters;
private final boolean isRevertReasonEnabled;
private final Clock clock;
public ProtocolScheduleBuilder(
final GenesisConfigOptions config,
final BigInteger defaultChainId,
final Function<ProtocolSpecBuilder<Void>, ProtocolSpecBuilder<C>> protocolSpecAdapter,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
this(
config,
Optional.of(defaultChainId),
protocolSpecAdapter,
privacyParameters,
isRevertReasonEnabled,
clock);
isRevertReasonEnabled);
}
public ProtocolScheduleBuilder(
final GenesisConfigOptions config,
final Function<ProtocolSpecBuilder<Void>, ProtocolSpecBuilder<C>> protocolSpecAdapter,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
this(
config,
Optional.empty(),
protocolSpecAdapter,
privacyParameters,
isRevertReasonEnabled,
clock);
final boolean isRevertReasonEnabled) {
this(config, Optional.empty(), protocolSpecAdapter, privacyParameters, isRevertReasonEnabled);
}
private ProtocolScheduleBuilder(
@@ -71,18 +60,17 @@ public class ProtocolScheduleBuilder<C> {
final Optional<BigInteger> defaultChainId,
final Function<ProtocolSpecBuilder<Void>, ProtocolSpecBuilder<C>> protocolSpecAdapter,
final PrivacyParameters privacyParameters,
final boolean isRevertReasonEnabled,
final Clock clock) {
final boolean isRevertReasonEnabled) {
this.config = config;
this.defaultChainId = defaultChainId;
this.protocolSpecAdapter = protocolSpecAdapter;
this.privacyParameters = privacyParameters;
this.isRevertReasonEnabled = isRevertReasonEnabled;
this.clock = clock;
}
public ProtocolSchedule<C> createProtocolSchedule() {
final Optional<BigInteger> chainId = config.getChainId().or(() -> defaultChainId);
final Optional<BigInteger> chainId =
config.getChainId().map(Optional::of).orElse(defaultChainId);
final MutableProtocolSchedule<C> protocolSchedule = new MutableProtocolSchedule<>(chainId);
validateForkOrdering();
@@ -91,12 +79,12 @@ public class ProtocolScheduleBuilder<C> {
protocolSchedule,
OptionalLong.of(0),
MainnetProtocolSpecs.frontierDefinition(
config.getContractSizeLimit(), config.getEvmStackSize(), clock));
config.getContractSizeLimit(), config.getEvmStackSize()));
addProtocolSpec(
protocolSchedule,
config.getHomesteadBlockNumber(),
MainnetProtocolSpecs.homesteadDefinition(
config.getContractSizeLimit(), config.getEvmStackSize(), clock));
config.getContractSizeLimit(), config.getEvmStackSize()));
config
.getDaoForkBlock()
@@ -108,12 +96,12 @@ public class ProtocolScheduleBuilder<C> {
protocolSchedule,
OptionalLong.of(daoBlockNumber),
MainnetProtocolSpecs.daoRecoveryInitDefinition(
config.getContractSizeLimit(), config.getEvmStackSize(), clock));
config.getContractSizeLimit(), config.getEvmStackSize()));
addProtocolSpec(
protocolSchedule,
OptionalLong.of(daoBlockNumber + 1),
MainnetProtocolSpecs.daoRecoveryTransitionDefinition(
config.getContractSizeLimit(), config.getEvmStackSize(), clock));
config.getContractSizeLimit(), config.getEvmStackSize()));
// Return to the previous protocol spec after the dao fork has completed.
protocolSchedule.putMilestone(daoBlockNumber + 10, originalProtocolSpec);
@@ -123,12 +111,12 @@ public class ProtocolScheduleBuilder<C> {
protocolSchedule,
config.getTangerineWhistleBlockNumber(),
MainnetProtocolSpecs.tangerineWhistleDefinition(
config.getContractSizeLimit(), config.getEvmStackSize(), clock));
config.getContractSizeLimit(), config.getEvmStackSize()));
addProtocolSpec(
protocolSchedule,
config.getSpuriousDragonBlockNumber(),
MainnetProtocolSpecs.spuriousDragonDefinition(
chainId, config.getContractSizeLimit(), config.getEvmStackSize(), clock));
chainId, config.getContractSizeLimit(), config.getEvmStackSize()));
addProtocolSpec(
protocolSchedule,
config.getByzantiumBlockNumber(),
@@ -136,8 +124,7 @@ public class ProtocolScheduleBuilder<C> {
chainId,
config.getContractSizeLimit(),
config.getEvmStackSize(),
isRevertReasonEnabled,
clock));
isRevertReasonEnabled));
addProtocolSpec(
protocolSchedule,
config.getConstantinopleBlockNumber(),
@@ -145,8 +132,7 @@ public class ProtocolScheduleBuilder<C> {
chainId,
config.getContractSizeLimit(),
config.getEvmStackSize(),
isRevertReasonEnabled,
clock));
isRevertReasonEnabled));
addProtocolSpec(
protocolSchedule,
config.getConstantinopleFixBlockNumber(),
@@ -154,8 +140,7 @@ public class ProtocolScheduleBuilder<C> {
chainId,
config.getContractSizeLimit(),
config.getEvmStackSize(),
isRevertReasonEnabled,
clock));
isRevertReasonEnabled));
addProtocolSpec(
protocolSchedule,
config.getIstanbulBlockNumber(),
@@ -163,8 +148,7 @@ public class ProtocolScheduleBuilder<C> {
chainId,
config.getContractSizeLimit(),
config.getEvmStackSize(),
isRevertReasonEnabled,
clock));
isRevertReasonEnabled));
LOG.info("Protocol schedule created with milestones: {}", protocolSchedule.listMilestones());
return protocolSchedule;

View File

@@ -15,7 +15,7 @@ package tech.pegasys.pantheon.ethereum.mainnet.headervalidationrules;
import tech.pegasys.pantheon.ethereum.core.BlockHeader;
import tech.pegasys.pantheon.ethereum.mainnet.DetachedBlockHeaderValidationRule;
import java.time.Clock;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -28,12 +28,9 @@ public class TimestampBoundedByFutureParameter implements DetachedBlockHeaderVal
private final Logger LOG = LogManager.getLogger();
private final long acceptableClockDriftSeconds;
private final Clock clock;
public TimestampBoundedByFutureParameter(
final long acceptableClockDriftSeconds, final Clock clock) {
public TimestampBoundedByFutureParameter(final long acceptableClockDriftSeconds) {
this.acceptableClockDriftSeconds = acceptableClockDriftSeconds;
this.clock = clock;
}
@Override
@@ -46,7 +43,9 @@ public class TimestampBoundedByFutureParameter implements DetachedBlockHeaderVal
}
private boolean validateHeaderNotAheadOfCurrentSystemTime(final long timestamp) {
final long timestampMargin = clock.instant().getEpochSecond() + acceptableClockDriftSeconds;
final long timestampMargin =
TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
+ acceptableClockDriftSeconds;
if (Long.compareUnsigned(timestamp, timestampMargin) > 0) {
LOG.trace(
"Invalid block header: timestamp {} is greater than the timestamp margin {}",

View File

@@ -12,8 +12,6 @@
*/
package tech.pegasys.pantheon.ethereum.core;
import static com.google.common.base.Preconditions.checkNotNull;
import tech.pegasys.pantheon.config.GenesisConfigFile;
import tech.pegasys.pantheon.config.StubGenesisConfigOptions;
import tech.pegasys.pantheon.ethereum.ProtocolContext;
@@ -29,10 +27,8 @@ import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.services.kvstore.InMemoryKeyValueStorage;
import tech.pegasys.pantheon.services.kvstore.KeyValueStorage;
import tech.pegasys.pantheon.testutil.TestClock;
import java.math.BigInteger;
import java.time.Clock;
import java.util.function.Function;
public class ExecutionContextTestFixture {
@@ -64,7 +60,7 @@ public class ExecutionContextTestFixture {
}
public static ExecutionContextTestFixture create() {
return new Builder().clock(TestClock.fixed()).build();
return new Builder().build();
}
public static Builder builder() {
@@ -99,7 +95,6 @@ public class ExecutionContextTestFixture {
private KeyValueStorage keyValueStorage;
private ProtocolSchedule<Void> protocolSchedule;
private Clock clock;
public Builder keyValueStorage(final KeyValueStorage keyValueStorage) {
this.keyValueStorage = keyValueStorage;
@@ -111,14 +106,7 @@ public class ExecutionContextTestFixture {
return this;
}
public Builder clock(final Clock clock) {
this.clock = clock;
return this;
}
public ExecutionContextTestFixture build() {
checkNotNull(clock);
if (protocolSchedule == null) {
protocolSchedule =
new ProtocolScheduleBuilder<>(
@@ -126,8 +114,7 @@ public class ExecutionContextTestFixture {
BigInteger.valueOf(42),
Function.identity(),
new PrivacyParameters(),
false,
clock)
false)
.createProtocolSchedule();
}
if (keyValueStorage == null) {

View File

@@ -21,7 +21,6 @@ import tech.pegasys.pantheon.ethereum.vm.Code;
import tech.pegasys.pantheon.ethereum.vm.MessageFrame;
import tech.pegasys.pantheon.ethereum.vm.OperationTracer;
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.math.BigInteger;
@@ -36,11 +35,7 @@ public class TestCodeExecutor {
private static final Address SENDER_ADDRESS = AddressHelpers.ofValue(244259721);
public TestCodeExecutor(final ProtocolSchedule<Void> protocolSchedule) {
fixture =
ExecutionContextTestFixture.builder()
.protocolSchedule(protocolSchedule)
.clock(TestClock.fixed())
.build();
fixture = ExecutionContextTestFixture.builder().protocolSchedule(protocolSchedule).build();
}
public MessageFrame executeCode(

View File

@@ -23,12 +23,9 @@ import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPOutput;
import tech.pegasys.pantheon.ethereum.storage.keyvalue.WorldStateKeyValueStorage;
import tech.pegasys.pantheon.ethereum.worldstate.DefaultMutableWorldState;
import tech.pegasys.pantheon.services.kvstore.InMemoryKeyValueStorage;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import tech.pegasys.pantheon.util.uint.UInt256;
import java.time.Clock;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import org.bouncycastle.util.encoders.Hex;
@@ -36,8 +33,6 @@ import org.junit.Test;
public final class GenesisStateTest {
final Clock testClock = new TestClock();
/** Known RLP encoded bytes of the Olympic Genesis Block. */
private static final String OLYMPIC_RLP =
"f901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a09178d0f23c965d81f0834a4c72c6253ce6830f4022b1359aaebfc1ecba442d4ea056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080832fefd8808080a0000000000000000000000000000000000000000000000000000000000000000088000000000000002ac0c0";
@@ -54,7 +49,7 @@ public final class GenesisStateTest {
final GenesisState genesisState =
GenesisState.fromJson(
Resources.toString(GenesisStateTest.class.getResource("genesis1.json"), Charsets.UTF_8),
MainnetProtocolSchedule.create(testClock));
MainnetProtocolSchedule.create());
final BlockHeader header = genesisState.getBlock().getHeader();
assertThat(header.getStateRoot())
.isEqualTo(
@@ -83,7 +78,7 @@ public final class GenesisStateTest {
final GenesisState genesisState =
GenesisState.fromJson(
Resources.toString(GenesisStateTest.class.getResource("genesis2.json"), Charsets.UTF_8),
MainnetProtocolSchedule.create(testClock));
MainnetProtocolSchedule.create());
final BlockHeader header = genesisState.getBlock().getHeader();
assertThat(header.getStateRoot()).isEqualTo(Hash.EMPTY_TRIE_HASH);
assertThat(header.getTransactionsRoot()).isEqualTo(Hash.EMPTY_TRIE_HASH);
@@ -98,7 +93,7 @@ public final class GenesisStateTest {
final GenesisState genesisState =
GenesisState.fromJson(
Resources.toString(GenesisStateTest.class.getResource(sourceFile), Charsets.UTF_8),
MainnetProtocolSchedule.create(testClock));
MainnetProtocolSchedule.create());
final BlockHeader header = genesisState.getBlock().getHeader();
assertThat(header.getHash()).isEqualTo(Hash.fromHexString(blockHash));
@@ -137,7 +132,7 @@ public final class GenesisStateTest {
GenesisState.fromJson(
Resources.toString(
GenesisStateTest.class.getResource("genesisNonce.json"), Charsets.UTF_8),
MainnetProtocolSchedule.create(testClock));
MainnetProtocolSchedule.create());
final BlockHeader header = genesisState.getBlock().getHeader();
assertThat(header.getHash())
.isEqualTo(
@@ -151,7 +146,7 @@ public final class GenesisStateTest {
GenesisState.fromJson(
Resources.toString(
GenesisStateTest.class.getResource("genesis-olympic.json"), Charsets.UTF_8),
MainnetProtocolSchedule.create(testClock));
MainnetProtocolSchedule.create());
final BytesValueRLPOutput tmp = new BytesValueRLPOutput();
genesisState.getBlock().writeTo(tmp);
assertThat(Hex.toHexString(genesisState.getBlock().getHeader().getHash().extractArray()))

View File

@@ -18,7 +18,6 @@ import tech.pegasys.pantheon.config.GenesisConfigFile;
import tech.pegasys.pantheon.ethereum.core.BlockHeader;
import tech.pegasys.pantheon.ethereum.core.BlockHeaderTestFixture;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.testutil.TestClock;
import org.junit.Test;
@@ -28,8 +27,7 @@ public class FixedProtocolScheduleTest {
public void reportedDifficultyForAllBlocksIsAFixedValue() {
final ProtocolSchedule<Void> schedule =
FixedDifficultyProtocolSchedule.create(
GenesisConfigFile.development().getConfigOptions(), TestClock.fixed());
FixedDifficultyProtocolSchedule.create(GenesisConfigFile.development().getConfigOptions());
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();

View File

@@ -16,7 +16,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import tech.pegasys.pantheon.ethereum.ProtocolContext;
import tech.pegasys.pantheon.testutil.TestClock;
import org.junit.Test;
@@ -29,8 +28,7 @@ public final class MainnetBlockHeaderValidatorTest {
@Test
public void validHeaderFrontier() throws Exception {
final BlockHeaderValidator<Void> headerValidator =
MainnetBlockHeaderValidator.create(
MainnetDifficultyCalculators.FRONTIER, TestClock.fixed());
MainnetBlockHeaderValidator.create(MainnetDifficultyCalculators.FRONTIER);
assertThat(
headerValidator.validateHeader(
ValidationTestUtils.readHeader(300006),
@@ -43,8 +41,7 @@ public final class MainnetBlockHeaderValidatorTest {
@Test
public void validHeaderHomestead() throws Exception {
final BlockHeaderValidator<Void> headerValidator =
MainnetBlockHeaderValidator.create(
MainnetDifficultyCalculators.HOMESTEAD, TestClock.fixed());
MainnetBlockHeaderValidator.create(MainnetDifficultyCalculators.HOMESTEAD);
assertThat(
headerValidator.validateHeader(
ValidationTestUtils.readHeader(1200001),
@@ -57,8 +54,7 @@ public final class MainnetBlockHeaderValidatorTest {
@Test
public void invalidParentHash() throws Exception {
final BlockHeaderValidator<Void> headerValidator =
MainnetBlockHeaderValidator.create(
MainnetDifficultyCalculators.HOMESTEAD, TestClock.fixed());
MainnetBlockHeaderValidator.create(MainnetDifficultyCalculators.HOMESTEAD);
assertThat(
headerValidator.validateHeader(
ValidationTestUtils.readHeader(1200001),
@@ -71,8 +67,7 @@ public final class MainnetBlockHeaderValidatorTest {
@Test
public void validHeaderByzantium() throws Exception {
final BlockHeaderValidator<Void> headerValidator =
MainnetBlockHeaderValidator.create(
MainnetDifficultyCalculators.BYZANTIUM, TestClock.fixed());
MainnetBlockHeaderValidator.create(MainnetDifficultyCalculators.BYZANTIUM);
assertThat(
headerValidator.validateHeader(
ValidationTestUtils.readHeader(4400001),

View File

@@ -13,7 +13,6 @@
package tech.pegasys.pantheon.ethereum.mainnet;
import tech.pegasys.pantheon.config.GenesisConfigFile;
import tech.pegasys.pantheon.testutil.TestClock;
import java.nio.charset.StandardCharsets;
@@ -26,7 +25,7 @@ public class MainnetProtocolScheduleTest {
@Test
public void shouldReturnDefaultProtocolSpecsWhenCustomNumbersAreNotUsed() {
final ProtocolSchedule<Void> sched = MainnetProtocolSchedule.create(TestClock.fixed());
final ProtocolSchedule<Void> sched = MainnetProtocolSchedule.create();
Assertions.assertThat(sched.getByBlockNumber(1L).getName()).isEqualTo("Frontier");
Assertions.assertThat(sched.getByBlockNumber(1_150_000L).getName()).isEqualTo("Homestead");
Assertions.assertThat(sched.getByBlockNumber(1_920_000L).getName())
@@ -50,8 +49,7 @@ public class MainnetProtocolScheduleTest {
public void shouldOnlyUseFrontierWhenEmptyJsonConfigIsUsed() {
final JsonObject json = new JsonObject("{}");
final ProtocolSchedule<Void> sched =
MainnetProtocolSchedule.fromConfig(
GenesisConfigFile.fromConfig(json).getConfigOptions(), TestClock.fixed());
MainnetProtocolSchedule.fromConfig(GenesisConfigFile.fromConfig(json).getConfigOptions());
Assertions.assertThat(sched.getByBlockNumber(1L).getName()).isEqualTo("Frontier");
Assertions.assertThat(sched.getByBlockNumber(Long.MAX_VALUE).getName()).isEqualTo("Frontier");
}
@@ -62,8 +60,7 @@ public class MainnetProtocolScheduleTest {
new JsonObject(
"{\"config\": {\"homesteadBlock\": 2, \"daoForkBlock\": 3, \"eip150Block\": 14, \"eip158Block\": 15, \"byzantiumBlock\": 16, \"constantinopleBlock\": 18, \"constantinopleFixBlock\": 19, \"chainId\":1234}}");
final ProtocolSchedule<Void> sched =
MainnetProtocolSchedule.fromConfig(
GenesisConfigFile.fromConfig(json).getConfigOptions(), TestClock.fixed());
MainnetProtocolSchedule.fromConfig(GenesisConfigFile.fromConfig(json).getConfigOptions());
Assertions.assertThat(sched.getByBlockNumber(1).getName()).isEqualTo("Frontier");
Assertions.assertThat(sched.getByBlockNumber(2).getName()).isEqualTo("Homestead");
Assertions.assertThat(sched.getByBlockNumber(3).getName()).isEqualTo("DaoRecoveryInit");
@@ -87,7 +84,7 @@ public class MainnetProtocolScheduleTest {
.isThrownBy(
() ->
MainnetProtocolSchedule.fromConfig(
GenesisConfigFile.fromConfig(json).getConfigOptions(), TestClock.fixed()));
GenesisConfigFile.fromConfig(json).getConfigOptions()));
}
@Test
@@ -97,8 +94,7 @@ public class MainnetProtocolScheduleTest {
GenesisConfigFile.fromConfig(
Resources.toString(
this.getClass().getResource("/ropsten.json"), StandardCharsets.UTF_8))
.getConfigOptions(),
TestClock.fixed());
.getConfigOptions());
Assertions.assertThat(sched.getByBlockNumber(0).getName()).isEqualTo("TangerineWhistle");
Assertions.assertThat(sched.getByBlockNumber(1).getName()).isEqualTo("TangerineWhistle");
Assertions.assertThat(sched.getByBlockNumber(10).getName()).isEqualTo("SpuriousDragon");

View File

@@ -22,7 +22,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.MainnetProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions;
import tech.pegasys.pantheon.ethereum.mainnet.ValidationTestUtils;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.uint.UInt256;
import java.io.IOException;
@@ -110,8 +109,7 @@ public class ProofOfWorkValidationRuleTest {
}
private BlockHeaderFunctions mainnetBlockHashFunction() {
final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
return ScheduleBasedBlockHeaderFunctions.create(protocolSchedule);
}
}

View File

@@ -16,7 +16,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import tech.pegasys.pantheon.ethereum.core.BlockHeader;
import tech.pegasys.pantheon.ethereum.core.BlockHeaderTestFixture;
import tech.pegasys.pantheon.testutil.TestClock;
import java.util.concurrent.TimeUnit;
import org.assertj.core.api.Assertions;
import org.junit.Test;
@@ -25,8 +26,7 @@ public class TimestampValidationRuleTest {
@Test
public void headerTimestampSufficientlyFarIntoFutureVadidatesSuccessfully() {
final TimestampBoundedByFutureParameter uut00 =
new TimestampBoundedByFutureParameter(0, TestClock.fixed());
final TimestampBoundedByFutureParameter uut00 = new TimestampBoundedByFutureParameter(0);
final TimestampMoreRecentThanParent uut01 = new TimestampMoreRecentThanParent(10);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
@@ -50,8 +50,7 @@ public class TimestampValidationRuleTest {
@Test
public void headerTimestampTooCloseToParentFailsValidation() {
final TimestampBoundedByFutureParameter uut00 =
new TimestampBoundedByFutureParameter(0, TestClock.fixed());
final TimestampBoundedByFutureParameter uut00 = new TimestampBoundedByFutureParameter(0);
final TimestampMoreRecentThanParent uut01 = new TimestampMoreRecentThanParent(10);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
@@ -69,8 +68,7 @@ public class TimestampValidationRuleTest {
@Test
public void headerTimestampIsBehindParentFailsValidation() {
final TimestampBoundedByFutureParameter uut00 =
new TimestampBoundedByFutureParameter(0, TestClock.fixed());
final TimestampBoundedByFutureParameter uut00 = new TimestampBoundedByFutureParameter(0);
final TimestampMoreRecentThanParent uut01 = new TimestampMoreRecentThanParent(10);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
@@ -91,13 +89,14 @@ public class TimestampValidationRuleTest {
final long acceptableClockDrift = 5;
final TimestampBoundedByFutureParameter uut00 =
new TimestampBoundedByFutureParameter(acceptableClockDrift, TestClock.fixed());
new TimestampBoundedByFutureParameter(acceptableClockDrift);
final TimestampMoreRecentThanParent uut01 = new TimestampMoreRecentThanParent(10);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
// Create Parent Header @ 'now'
headerBuilder.timestamp(TestClock.fixed().instant().getEpochSecond());
headerBuilder.timestamp(
TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS));
final BlockHeader parent = headerBuilder.buildHeader();
// Create header for validation with a timestamp in the future (1 second too far away)
@@ -113,12 +112,14 @@ public class TimestampValidationRuleTest {
final long acceptableClockDrift = 5;
final TimestampBoundedByFutureParameter uut00 =
new TimestampBoundedByFutureParameter(acceptableClockDrift, TestClock.fixed());
new TimestampBoundedByFutureParameter(acceptableClockDrift);
final TimestampMoreRecentThanParent uut01 = new TimestampMoreRecentThanParent(10);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
headerBuilder.timestamp(TestClock.fixed().instant().getEpochSecond());
// Create Parent Header @ 'now'
headerBuilder.timestamp(
TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS));
final BlockHeader parent = headerBuilder.buildHeader();
// Create header for validation with a timestamp in the future (1 second too far away)

View File

@@ -19,7 +19,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolScheduleBuilder;
import java.math.BigInteger;
import java.time.Clock;
import java.util.Map;
import java.util.function.Function;
@@ -68,12 +67,7 @@ public class ReferenceTestProtocolSchedules {
private static ProtocolSchedule<Void> createSchedule(final GenesisConfigOptions options) {
return new ProtocolScheduleBuilder<>(
options,
CHAIN_ID,
Function.identity(),
PrivacyParameters.DEFAULT,
false,
Clock.systemUTC())
options, CHAIN_ID, Function.identity(), PrivacyParameters.DEFAULT, false)
.createProtocolSchedule();
}
}

View File

@@ -31,7 +31,6 @@ import tech.pegasys.pantheon.ethereum.worldstate.DefaultMutableWorldState;
import tech.pegasys.pantheon.testutil.JsonTestParameters;
import java.math.BigInteger;
import java.time.Clock;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Optional;
@@ -122,8 +121,7 @@ public class VMReferenceTest extends AbstractRetryingTest {
final EnvironmentInformation execEnv = spec.getExec();
final ProtocolSpec<Void> protocolSpec =
MainnetProtocolSpecs.frontierDefinition(
OptionalInt.empty(), OptionalInt.empty(), Clock.systemUTC())
MainnetProtocolSpecs.frontierDefinition(OptionalInt.empty(), OptionalInt.empty())
.privacyParameters(PrivacyParameters.DEFAULT)
.privateTransactionValidatorBuilder(() -> new PrivateTransactionValidator(CHAIN_ID))
.build(new MutableProtocolSchedule<>(CHAIN_ID));

View File

@@ -22,7 +22,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.MainnetProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.vm.MessageFrame;
import tech.pegasys.pantheon.ethereum.vm.MessageFrame.State;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.uint.UInt256;
import org.junit.Before;
@@ -36,8 +35,7 @@ import org.junit.runners.Parameterized.Parameters;
public class ConstantinopleSStoreOperationGasCostTest {
private static final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.fromConfig(
new StubGenesisConfigOptions().constantinopleBlock(0), TestClock.fixed());
MainnetProtocolSchedule.fromConfig(new StubGenesisConfigOptions().constantinopleBlock(0));
@Parameters(name = "Code: {0}, Original: {1}")
public static Object[][] scenarios() {

View File

@@ -109,7 +109,7 @@ public class EthPeer {
public void recordUselessResponse(final String requestType) {
LOG.debug("Received useless response for {} from peer {}", requestType, this);
reputation.recordUselessResponse(clock.millis()).ifPresent(this::disconnect);
reputation.recordUselessResponse(System.currentTimeMillis()).ifPresent(this::disconnect);
}
public void disconnect(final DisconnectReason reason) {

View File

@@ -967,8 +967,7 @@ public final class EthProtocolManagerTest {
.isEqualTo(Collections.singletonList(EthProtocol.ETH63));
// assert that all messages transmitted contain the expected block & total difficulty.
final ProtocolSchedule<Void> protocolSchdeule =
MainnetProtocolSchedule.create(TestClock.fixed());
final ProtocolSchedule<Void> protocolSchdeule = MainnetProtocolSchedule.create();
for (final NewBlockMessage msg : messageSentCaptor.getAllValues()) {
assertThat(msg.block(protocolSchdeule)).isEqualTo(minedBlock);
assertThat(msg.totalDifficulty(protocolSchdeule)).isEqualTo(expectedTotalDifficulty);

View File

@@ -65,8 +65,7 @@ public class EthProtocolManagerTestUtil {
}
public static EthProtocolManager create(final EthScheduler ethScheduler) {
final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
final GenesisConfigFile config = GenesisConfigFile.mainnet();
final GenesisState genesisState = GenesisState.fromConfig(config, protocolSchedule);
final Blockchain blockchain = createInMemoryBlockchain(genesisState.getBlock());

View File

@@ -32,7 +32,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions;
import tech.pegasys.pantheon.ethereum.util.RawBlockIterator;
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.testutil.BlockTestUtil;
import tech.pegasys.pantheon.testutil.TestClock;
import java.io.IOException;
import java.net.URISyntaxException;
@@ -92,8 +91,7 @@ public class BlockchainSetupUtil<C> {
}
public static BlockchainSetupUtil<Void> forTesting() {
final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
final TemporaryFolder temp = new TemporaryFolder();
try {
temp.create();

View File

@@ -23,7 +23,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.RawMessage;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPInput;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.ethereum.rlp.RLPInput;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.io.IOException;
@@ -67,7 +66,7 @@ public final class BlockBodiesMessageTest {
message
.bodies(
FixedDifficultyProtocolSchedule.create(
GenesisConfigFile.development().getConfigOptions(), false, TestClock.fixed()))
GenesisConfigFile.development().getConfigOptions(), false))
.iterator();
for (int i = 0; i < 50; ++i) {
Assertions.assertThat(readBodies.next()).isEqualTo(bodies.get(i));

View File

@@ -21,7 +21,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.RawMessage;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPInput;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.ethereum.rlp.RLPInput;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.io.IOException;
@@ -59,7 +58,7 @@ public final class BlockHeadersMessageTest {
final List<BlockHeader> readHeaders =
message.getHeaders(
FixedDifficultyProtocolSchedule.create(
GenesisConfigFile.development().getConfigOptions(), false, TestClock.fixed()));
GenesisConfigFile.development().getConfigOptions(), false));
for (int i = 0; i < 50; ++i) {
Assertions.assertThat(readHeaders.get(i)).isEqualTo(headers.get(i));

View File

@@ -21,15 +21,13 @@ import tech.pegasys.pantheon.ethereum.mainnet.MainnetProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.RawMessage;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPOutput;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import tech.pegasys.pantheon.util.uint.UInt256;
import org.junit.Test;
public class NewBlockMessageTest {
private static final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
private static final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
@Test
public void roundTripNewBlockMessage() {

View File

@@ -29,7 +29,6 @@ import tech.pegasys.pantheon.ethereum.eth.messages.GetBlockHeadersMessage;
import tech.pegasys.pantheon.ethereum.mainnet.MainnetBlockHeaderValidator;
import tech.pegasys.pantheon.ethereum.mainnet.MainnetProtocolSchedule;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.List;
@@ -56,7 +55,7 @@ public class DaoForkPeerValidatorTest {
PeerValidator validator =
new DaoForkPeerValidator(
ethProtocolManager.ethContext(),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
new NoOpMetricsSystem(),
daoBlockNumber,
0);
@@ -88,7 +87,7 @@ public class DaoForkPeerValidatorTest {
PeerValidator validator =
new DaoForkPeerValidator(
ethProtocolManager.ethContext(),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
new NoOpMetricsSystem(),
daoBlockNumber,
0);
@@ -116,7 +115,7 @@ public class DaoForkPeerValidatorTest {
PeerValidator validator =
new DaoForkPeerValidator(
ethProtocolManager.ethContext(),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
new NoOpMetricsSystem(),
daoBlockNumber,
0);
@@ -145,7 +144,7 @@ public class DaoForkPeerValidatorTest {
PeerValidator validator =
new DaoForkPeerValidator(
ethProtocolManager.ethContext(),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
new NoOpMetricsSystem(),
daoBlockNumber,
0);
@@ -184,7 +183,7 @@ public class DaoForkPeerValidatorTest {
PeerValidator validator =
new DaoForkPeerValidator(
ethProtocolManager.ethContext(),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
new NoOpMetricsSystem(),
daoBlockNumber,
buffer);

View File

@@ -27,7 +27,6 @@ import tech.pegasys.pantheon.ethereum.eth.manager.RespondingEthPeer.Responder;
import tech.pegasys.pantheon.ethereum.eth.manager.ethtaskutils.BlockchainSetupUtil;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.uint.UInt256;
import org.junit.Test;
@@ -46,7 +45,7 @@ public class ChainHeadTrackerTest {
0);
private final ProtocolSchedule<Void> protocolSchedule =
FixedDifficultyProtocolSchedule.create(
GenesisConfigFile.development().getConfigOptions(), false, TestClock.fixed());
GenesisConfigFile.development().getConfigOptions(), false);
private final TrailingPeerLimiter trailingPeerLimiter = mock(TrailingPeerLimiter.class);
private final ChainHeadTracker chainHeadTracker =

View File

@@ -32,7 +32,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.MainnetProtocolSchedule;
import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -59,8 +58,7 @@ public class FullSyncTargetManagerTest {
final BlockchainSetupUtil<Void> localBlockchainSetup = BlockchainSetupUtil.forTesting();
localBlockchain = localBlockchainSetup.getBlockchain();
final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
final ProtocolContext<Void> protocolContext =
new ProtocolContext<>(localBlockchain, localWorldState, null);
ethProtocolManager =

View File

@@ -34,7 +34,6 @@ import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule;
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.uint.UInt256;
import java.io.IOException;
@@ -54,8 +53,7 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class DetermineCommonAncestorTaskParameterizedTest {
private final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
private final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
private static final BlockDataGenerator blockDataGenerator = new BlockDataGenerator();
private final MetricsSystem metricsSystem = new NoOpMetricsSystem();

View File

@@ -46,7 +46,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.D
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.ExceptionUtils;
import java.util.List;
@@ -59,8 +58,7 @@ import org.junit.Test;
public class DetermineCommonAncestorTaskTest {
private final ProtocolSchedule<?> protocolSchedule =
MainnetProtocolSchedule.create(TestClock.fixed());
private final ProtocolSchedule<?> protocolSchedule = MainnetProtocolSchedule.create();
private final BlockDataGenerator blockDataGenerator = new BlockDataGenerator();
private final MetricsSystem metricsSystem = new NoOpMetricsSystem();
private final int defaultHeaderRequestSize = 10;

View File

@@ -892,10 +892,7 @@ public class WorldStateDownloaderTest {
RespondingEthPeer.blockchainResponder(mock(Blockchain.class), remoteWorldStateArchive);
final Responder partialResponder =
RespondingEthPeer.partialResponder(
mock(Blockchain.class),
remoteWorldStateArchive,
MainnetProtocolSchedule.create(TestClock.fixed()),
.5f);
mock(Blockchain.class), remoteWorldStateArchive, MainnetProtocolSchedule.create(), .5f);
final Responder emptyResponder = RespondingEthPeer.emptyResponder();
// Send a few partial responses

View File

@@ -95,7 +95,7 @@ public class TestNode implements Closeable {
final GenesisConfigFile genesisConfigFile = GenesisConfigFile.development();
final ProtocolSchedule<Void> protocolSchedule =
FixedDifficultyProtocolSchedule.create(
GenesisConfigFile.development().getConfigOptions(), false, TestClock.fixed());
GenesisConfigFile.development().getConfigOptions(), false);
final GenesisState genesisState = GenesisState.fromConfig(genesisConfigFile, protocolSchedule);
final BlockHeaderFunctions blockHeaderFunctions =
@@ -130,7 +130,6 @@ public class TestNode implements Closeable {
.keyPair(this.kp)
.config(networkingConfiguration)
.metricsSystem(new NoOpMetricsSystem())
.clock(TestClock.fixed())
.supportedCapabilities(capabilities)
.build())
.metricsSystem(new NoOpMetricsSystem())

View File

@@ -44,7 +44,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.Capability;
import tech.pegasys.pantheon.ethereum.util.RawBlockIterator;
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.testutil.BlockTestUtil;
import tech.pegasys.pantheon.testutil.TestClock;
import java.net.URL;
import java.nio.file.Paths;
@@ -98,7 +97,7 @@ public abstract class AbstractEthGraphQLHttpServiceTest {
@BeforeClass
public static void setupConstants() throws Exception {
PROTOCOL_SCHEDULE = MainnetProtocolSchedule.create(TestClock.fixed());
PROTOCOL_SCHEDULE = MainnetProtocolSchedule.create();
final URL blocksUrl = BlockTestUtil.getTestBlockchainUrl();

View File

@@ -23,7 +23,6 @@ import tech.pegasys.pantheon.ethereum.util.RawBlockIterator;
import java.net.URL;
import java.nio.file.Paths;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
@@ -41,7 +40,7 @@ public class BlockchainImporter {
public BlockchainImporter(final URL blocksUrl, final String genesisJson) throws Exception {
protocolSchedule =
MainnetProtocolSchedule.fromConfig(
GenesisConfigFile.fromConfig(genesisJson).getConfigOptions(), Clock.systemUTC());
GenesisConfigFile.fromConfig(genesisJson).getConfigOptions());
blocks = new ArrayList<>();
try (final RawBlockIterator iterator =

View File

@@ -43,7 +43,6 @@ import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration;
import java.time.Clock;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
@@ -103,7 +102,7 @@ public class JsonRpcTestMethodsFactory {
peerDiscovery,
blockchainQueries,
synchronizer,
MainnetProtocolSchedule.create(Clock.systemUTC()),
MainnetProtocolSchedule.create(),
filterManager,
transactionPool,
miningCoordinator,

View File

@@ -54,7 +54,6 @@ import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration;
import tech.pegasys.pantheon.testutil.BlockTestUtil;
import tech.pegasys.pantheon.testutil.TestClock;
import java.net.URL;
import java.nio.file.Paths;
@@ -116,7 +115,7 @@ public abstract class AbstractEthJsonRpcHttpServiceTest {
@BeforeClass
public static void setupConstants() throws Exception {
PROTOCOL_SCHEDULE = MainnetProtocolSchedule.create(TestClock.fixed());
PROTOCOL_SCHEDULE = MainnetProtocolSchedule.create();
final URL blocksUrl = BlockTestUtil.getTestBlockchainUrl();
@@ -180,7 +179,7 @@ public abstract class AbstractEthJsonRpcHttpServiceTest {
peerDiscoveryMock,
blockchainQueries,
synchronizerMock,
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
filterManager,
transactionPoolMock,
miningCoordinatorMock,

View File

@@ -34,7 +34,6 @@ import tech.pegasys.pantheon.ethereum.permissioning.AccountLocalConfigPermission
import tech.pegasys.pantheon.ethereum.permissioning.NodeLocalConfigPermissioningController;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration;
import tech.pegasys.pantheon.testutil.TestClock;
import java.io.IOException;
import java.math.BigInteger;
@@ -100,8 +99,7 @@ public class JsonRpcHttpServiceHostWhitelistTest {
MainnetProtocolSchedule.fromConfig(
new StubGenesisConfigOptions()
.constantinopleBlock(0)
.chainId(BigInteger.valueOf(CHAIN_ID)),
TestClock.fixed()),
.chainId(BigInteger.valueOf(CHAIN_ID))),
mock(FilterManager.class),
mock(TransactionPool.class),
mock(EthHashMiningCoordinator.class),

View File

@@ -38,7 +38,6 @@ import tech.pegasys.pantheon.ethereum.p2p.network.P2PNetwork;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.Capability;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration;
import tech.pegasys.pantheon.testutil.TestClock;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -128,7 +127,7 @@ public class JsonRpcHttpServiceLoginTest {
peerDiscoveryMock,
blockchainQueries,
synchronizer,
MainnetProtocolSchedule.fromConfig(genesisConfigOptions, TestClock.fixed()),
MainnetProtocolSchedule.fromConfig(genesisConfigOptions),
mock(FilterManager.class),
mock(TransactionPool.class),
mock(EthHashMiningCoordinator.class),

View File

@@ -43,7 +43,6 @@ import tech.pegasys.pantheon.ethereum.permissioning.AccountLocalConfigPermission
import tech.pegasys.pantheon.ethereum.permissioning.NodeLocalConfigPermissioningController;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration;
import tech.pegasys.pantheon.testutil.TestClock;
import java.io.IOException;
import java.util.ArrayList;
@@ -194,7 +193,7 @@ public class JsonRpcHttpServiceRpcApisTest {
mock(P2PNetwork.class),
blockchainQueries,
mock(Synchronizer.class),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
mock(FilterManager.class),
mock(TransactionPool.class),
mock(EthHashMiningCoordinator.class),
@@ -252,7 +251,6 @@ public class JsonRpcHttpServiceRpcApisTest {
.vertx(vertx)
.config(config)
.metricsSystem(new NoOpMetricsSystem())
.clock(TestClock.fixed())
.build();
p2pNetwork.start();
@@ -285,7 +283,7 @@ public class JsonRpcHttpServiceRpcApisTest {
p2pNetwork,
blockchainQueries,
mock(Synchronizer.class),
MainnetProtocolSchedule.create(TestClock.fixed()),
MainnetProtocolSchedule.create(),
mock(FilterManager.class),
mock(TransactionPool.class),
mock(EthHashMiningCoordinator.class),

View File

@@ -49,7 +49,6 @@ import tech.pegasys.pantheon.ethereum.permissioning.AccountLocalConfigPermission
import tech.pegasys.pantheon.ethereum.permissioning.NodeLocalConfigPermissioningController;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import tech.pegasys.pantheon.util.bytes.BytesValues;
import tech.pegasys.pantheon.util.uint.UInt256;
@@ -127,8 +126,7 @@ public class JsonRpcHttpServiceTest {
MainnetProtocolSchedule.fromConfig(
new StubGenesisConfigOptions()
.constantinopleBlock(0)
.chainId(BigInteger.valueOf(CHAIN_ID)),
TestClock.fixed()),
.chainId(BigInteger.valueOf(CHAIN_ID))),
mock(FilterManager.class),
mock(TransactionPool.class),
mock(EthHashMiningCoordinator.class),

View File

@@ -35,7 +35,6 @@ import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.time.Clock;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
@@ -65,7 +64,6 @@ public abstract class PeerDiscoveryAgent {
private final List<PeerRequirement> peerRequirements = new CopyOnWriteArrayList<>();
private final PeerPermissions peerPermissions;
private final Optional<UpnpNatManager> natManager;
private final Clock clock;
private final MetricsSystem metricsSystem;
/* The peer controller, which takes care of the state machine of peers. */
protected Optional<PeerDiscoveryController> controller = Optional.empty();
@@ -89,23 +87,20 @@ public abstract class PeerDiscoveryAgent {
final DiscoveryConfiguration config,
final PeerPermissions peerPermissions,
final Optional<UpnpNatManager> natManager,
final MetricsSystem metricsSystem,
final Clock clock) {
final MetricsSystem metricsSystem) {
this.metricsSystem = metricsSystem;
checkArgument(keyPair != null, "keypair cannot be null");
checkArgument(config != null, "provided configuration cannot be null");
checkArgument(clock != null, "provided clock cannot be null");
validateConfiguration(config);
this.keyPair = keyPair;
this.config = config;
this.peerPermissions = peerPermissions;
this.natManager = natManager;
this.bootstrapPeers =
config.getBootnodes().stream().map(DiscoveryPeer::fromEnode).collect(Collectors.toList());
this.metricsSystem = metricsSystem;
this.clock = clock;
this.config = config;
this.keyPair = keyPair;
id = keyPair.getPublicKey().getEncodedBytes();
}
@@ -193,7 +188,6 @@ public abstract class PeerDiscoveryAgent {
.peerPermissions(peerPermissions)
.peerBondedObservers(peerBondedObservers)
.metricsSystem(metricsSystem)
.clock(clock)
.build();
}
@@ -248,7 +242,7 @@ public abstract class PeerDiscoveryAgent {
}
return;
}
peer.setLastContacted(clock.millis());
peer.setLastContacted(System.currentTimeMillis());
});
}

View File

@@ -31,7 +31,6 @@ import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.time.Clock;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
@@ -62,9 +61,8 @@ public class VertxPeerDiscoveryAgent extends PeerDiscoveryAgent {
final DiscoveryConfiguration config,
final PeerPermissions peerPermissions,
final Optional<UpnpNatManager> natManager,
final MetricsSystem metricsSystem,
final Clock clock) {
super(keyPair, config, peerPermissions, natManager, metricsSystem, clock);
final MetricsSystem metricsSystem) {
super(keyPair, config, peerPermissions, natManager, metricsSystem);
checkArgument(vertx != null, "vertx instance cannot be null");
this.vertx = vertx;

View File

@@ -18,8 +18,6 @@ import tech.pegasys.pantheon.ethereum.rlp.RLPInput;
import tech.pegasys.pantheon.ethereum.rlp.RLPOutput;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
public class FindNeighborsPacketData implements PacketData {
private static final int TARGET_SIZE = 64;
@@ -37,9 +35,9 @@ public class FindNeighborsPacketData implements PacketData {
this.expiration = expiration;
}
public static FindNeighborsPacketData create(final BytesValue target, final Clock clock) {
public static FindNeighborsPacketData create(final BytesValue target) {
return new FindNeighborsPacketData(
target, clock.millis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
target, System.currentTimeMillis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
}
@Override

View File

@@ -18,7 +18,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.DiscoveryPeer;
import tech.pegasys.pantheon.ethereum.rlp.RLPInput;
import tech.pegasys.pantheon.ethereum.rlp.RLPOutput;
import java.time.Clock;
import java.util.List;
public class NeighborsPacketData implements PacketData {
@@ -37,8 +36,9 @@ public class NeighborsPacketData implements PacketData {
}
@SuppressWarnings("unchecked")
public static NeighborsPacketData create(final List<DiscoveryPeer> peers, final Clock clock) {
return new NeighborsPacketData(peers, clock.millis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
public static NeighborsPacketData create(final List<DiscoveryPeer> peers) {
return new NeighborsPacketData(
peers, System.currentTimeMillis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
}
public static NeighborsPacketData readFrom(final RLPInput in) {

View File

@@ -35,7 +35,6 @@ import tech.pegasys.pantheon.metrics.PantheonMetricCategory;
import tech.pegasys.pantheon.util.Subscribers;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -143,8 +142,6 @@ public class PeerDiscoveryController {
private RecursivePeerRefreshState recursivePeerRefreshState;
private final Clock clock;
private PeerDiscoveryController(
final KeyPair keypair,
final DiscoveryPeer localPeer,
@@ -158,8 +155,7 @@ public class PeerDiscoveryController {
final PeerRequirement peerRequirement,
final PeerPermissions peerPermissions,
final Subscribers<PeerBondedObserver> peerBondedObservers,
final MetricsSystem metricsSystem,
final Clock clock) {
final MetricsSystem metricsSystem) {
this.timerUtil = timerUtil;
this.keypair = keypair;
this.localPeer = localPeer;
@@ -171,7 +167,6 @@ public class PeerDiscoveryController {
this.peerRequirement = peerRequirement;
this.outboundMessageHandler = outboundMessageHandler;
this.peerBondedObservers = peerBondedObservers;
this.clock = clock;
this.discoveryProtocolLogger = new DiscoveryProtocolLogger(metricsSystem);
this.peerPermissions = new PeerDiscoveryPermissions(localPeer, peerPermissions);
@@ -362,7 +357,7 @@ public class PeerDiscoveryController {
}
// Reset the last seen timestamp.
final long now = clock.millis();
final long now = System.currentTimeMillis();
if (peer.getFirstDiscovered() == 0) {
peer.setFirstDiscovered(now);
}
@@ -401,7 +396,7 @@ public class PeerDiscoveryController {
}
private void refreshTableIfRequired() {
final long now = clock.millis();
final long now = System.currentTimeMillis();
if (lastRefreshTime + tableRefreshIntervalMs <= now) {
LOG.debug("Peer table refresh triggered by timer expiry");
refreshTable();
@@ -430,7 +425,7 @@ public class PeerDiscoveryController {
final BytesValue target = Peer.randomId();
final List<DiscoveryPeer> initialPeers = peerTable.nearestPeers(Peer.randomId(), 16);
recursivePeerRefreshState.start(initialPeers, target);
lastRefreshTime = clock.millis();
lastRefreshTime = System.currentTimeMillis();
}
/**
@@ -440,13 +435,13 @@ public class PeerDiscoveryController {
*/
@VisibleForTesting
void bond(final DiscoveryPeer peer) {
peer.setFirstDiscovered(clock.millis());
peer.setFirstDiscovered(System.currentTimeMillis());
peer.setStatus(PeerDiscoveryStatus.BONDING);
final Consumer<PeerInteractionState> action =
interaction -> {
final PingPacketData data =
PingPacketData.create(localPeer.getEndpoint(), peer.getEndpoint(), clock);
PingPacketData.create(localPeer.getEndpoint(), peer.getEndpoint());
createPacket(
PacketType.PING,
data,
@@ -510,7 +505,7 @@ public class PeerDiscoveryController {
private void findNodes(final DiscoveryPeer peer, final BytesValue target) {
final Consumer<PeerInteractionState> action =
(interaction) -> {
final FindNeighborsPacketData data = FindNeighborsPacketData.create(target, clock);
final FindNeighborsPacketData data = FindNeighborsPacketData.create(target);
sendPacket(peer, PacketType.FIND_NEIGHBORS, data);
};
final PeerInteractionState interaction =
@@ -537,7 +532,7 @@ public class PeerDiscoveryController {
private void respondToPing(
final PingPacketData packetData, final BytesValue pingHash, final DiscoveryPeer sender) {
final PongPacketData data = PongPacketData.create(packetData.getFrom(), pingHash, clock);
final PongPacketData data = PongPacketData.create(packetData.getFrom(), pingHash);
sendPacket(sender, PacketType.PONG, data);
}
@@ -546,7 +541,7 @@ public class PeerDiscoveryController {
// TODO: for now return 16 peers. Other implementations calculate how many
// peers they can fit in a 1280-byte payload.
final List<DiscoveryPeer> peers = peerTable.nearestPeers(packetData.getTarget(), 16);
final PacketData data = NeighborsPacketData.create(peers, clock);
final PacketData data = NeighborsPacketData.create(peers);
sendPacket(sender, PacketType.NEIGHBORS, data);
}
@@ -667,7 +662,6 @@ public class PeerDiscoveryController {
private TimerUtil timerUtil;
private AsyncExecutor workerExecutor;
private MetricsSystem metricsSystem;
private Clock clock;
private Builder() {}
@@ -691,8 +685,7 @@ public class PeerDiscoveryController {
peerRequirement,
peerPermissions,
peerBondedObservers,
metricsSystem,
clock);
metricsSystem);
}
private void validate() {
@@ -702,7 +695,6 @@ public class PeerDiscoveryController {
validateRequiredDependency(workerExecutor, "AsyncExecutor");
validateRequiredDependency(metricsSystem, "MetricsSystem");
validateRequiredDependency(peerBondedObservers, "PeerBondedObservers");
validateRequiredDependency(clock, "Clock");
}
private void validateRequiredDependency(final Object object, final String name) {
@@ -785,11 +777,5 @@ public class PeerDiscoveryController {
this.metricsSystem = metricsSystem;
return this;
}
public Builder clock(final Clock clock) {
checkNotNull(clock);
this.clock = clock;
return this;
}
}
}

View File

@@ -18,8 +18,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.Endpoint;
import tech.pegasys.pantheon.ethereum.rlp.RLPInput;
import tech.pegasys.pantheon.ethereum.rlp.RLPOutput;
import java.time.Clock;
public class PingPacketData implements PacketData {
/* Fixed value that represents we're using v4 of the P2P discovery protocol. */
@@ -44,8 +42,9 @@ public class PingPacketData implements PacketData {
this.expiration = expiration;
}
public static PingPacketData create(final Endpoint from, final Endpoint to, final Clock clock) {
return new PingPacketData(from, to, clock.millis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
public static PingPacketData create(final Endpoint from, final Endpoint to) {
return new PingPacketData(
from, to, System.currentTimeMillis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
}
public static PingPacketData readFrom(final RLPInput in) {

View File

@@ -17,8 +17,6 @@ import tech.pegasys.pantheon.ethereum.rlp.RLPInput;
import tech.pegasys.pantheon.ethereum.rlp.RLPOutput;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
public class PongPacketData implements PacketData {
/* Destination. */
@@ -36,10 +34,9 @@ public class PongPacketData implements PacketData {
this.expiration = expiration;
}
public static PongPacketData create(
final Endpoint to, final BytesValue pingHash, final Clock clock) {
public static PongPacketData create(final Endpoint to, final BytesValue pingHash) {
return new PongPacketData(
to, pingHash, clock.millis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
to, pingHash, System.currentTimeMillis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS);
}
public static PongPacketData readFrom(final RLPInput in) {

View File

@@ -43,7 +43,6 @@ import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.nat.upnp.UpnpNatManager;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
@@ -410,7 +409,6 @@ public class DefaultP2PNetwork implements P2PNetwork {
private Optional<UpnpNatManager> natManager = Optional.empty();
private MetricsSystem metricsSystem;
private Clock clock;
public P2PNetwork build() {
validate();
@@ -428,7 +426,7 @@ public class DefaultP2PNetwork implements P2PNetwork {
MutableLocalNode.create(config.getRlpx().getClientId(), 5, supportedCapabilities);
final PeerPrivileges peerPrivileges = new DefaultPeerPrivileges(maintainedPeers);
peerDiscoveryAgent = peerDiscoveryAgent == null ? createDiscoveryAgent() : peerDiscoveryAgent;
rlpxAgent = rlpxAgent == null ? createRlpxAgent(localNode, peerPrivileges, clock) : rlpxAgent;
rlpxAgent = rlpxAgent == null ? createRlpxAgent(localNode, peerPrivileges) : rlpxAgent;
return new DefaultP2PNetwork(
localNode,
@@ -449,18 +447,17 @@ public class DefaultP2PNetwork implements P2PNetwork {
supportedCapabilities != null && supportedCapabilities.size() > 0,
"Supported capabilities must be set and non-empty.");
checkState(metricsSystem != null, "MetricsSystem must be set.");
checkState(clock != null, "Clock must be set.");
checkState(peerDiscoveryAgent != null || vertx != null, "Vertx must be set.");
}
private PeerDiscoveryAgent createDiscoveryAgent() {
return new VertxPeerDiscoveryAgent(
vertx, keyPair, config.getDiscovery(), peerPermissions, natManager, metricsSystem, clock);
vertx, keyPair, config.getDiscovery(), peerPermissions, natManager, metricsSystem);
}
private RlpxAgent createRlpxAgent(
final LocalNode localNode, final PeerPrivileges peerPrivileges, final Clock clock) {
final LocalNode localNode, final PeerPrivileges peerPrivileges) {
return RlpxAgent.builder()
.keyPair(keyPair)
.config(config.getRlpx())
@@ -468,7 +465,6 @@ public class DefaultP2PNetwork implements P2PNetwork {
.peerPrivileges(peerPrivileges)
.localNode(localNode)
.metricsSystem(metricsSystem)
.clock(clock)
.build();
}
@@ -525,12 +521,6 @@ public class DefaultP2PNetwork implements P2PNetwork {
return this;
}
public Builder clock(final Clock clock) {
checkNotNull(clock);
this.clock = clock;
return this;
}
public Builder natManager(final UpnpNatManager natManager) {
this.natManager = Optional.ofNullable(natManager);
return this;

View File

@@ -39,7 +39,6 @@ import tech.pegasys.pantheon.util.FutureUtils;
import tech.pegasys.pantheon.util.Subscribers;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -68,7 +67,6 @@ public class RlpxAgent {
private final PeerPrivileges peerPrivileges;
private final int maxConnections;
private final int maxRemotelyInitiatedConnections;
private final Clock clock;
@VisibleForTesting
final Map<BytesValue, RlpxConnection> connectionsById = new ConcurrentHashMap<>();
@@ -86,8 +84,7 @@ public class RlpxAgent {
final PeerPrivileges peerPrivileges,
final int maxConnections,
final int maxRemotelyInitiatedConnections,
final MetricsSystem metricsSystem,
final Clock clock) {
final MetricsSystem metricsSystem) {
this.localNode = localNode;
this.connectionEvents = connectionEvents;
this.connectionInitializer = connectionInitializer;
@@ -96,7 +93,6 @@ public class RlpxAgent {
this.maxConnections = maxConnections;
this.maxRemotelyInitiatedConnections =
Math.min(maxConnections, maxRemotelyInitiatedConnections);
this.clock = clock;
// Setup metrics
connectedPeersCounter =
@@ -235,8 +231,7 @@ public class RlpxAgent {
// We're initiating a new connection
final CompletableFuture<PeerConnection> future = initiateOutboundConnection(peer);
connectionFuture.set(future);
RlpxConnection newConnection =
RlpxConnection.outboundConnection(peer, future, clock.millis());
RlpxConnection newConnection = RlpxConnection.outboundConnection(peer, future);
newConnection.subscribeConnectionEstablished(
(conn) -> {
this.dispatchConnect(conn.getPeerConnection());
@@ -304,7 +299,7 @@ public class RlpxAgent {
private CompletableFuture<PeerConnection> initiateOutboundConnection(final Peer peer) {
LOG.trace("Initiating connection to peer: {}", peer.getEnodeURL());
if (peer instanceof DiscoveryPeer) {
((DiscoveryPeer) peer).setLastAttemptedConnection(clock.millis());
((DiscoveryPeer) peer).setLastAttemptedConnection(System.currentTimeMillis());
}
return connectionInitializer
@@ -344,8 +339,7 @@ public class RlpxAgent {
// Track this new connection, deduplicating existing connection if necessary
final AtomicBoolean newConnectionAccepted = new AtomicBoolean(false);
final RlpxConnection inboundConnection =
RlpxConnection.inboundConnection(peerConnection, clock.millis());
final RlpxConnection inboundConnection = RlpxConnection.inboundConnection(peerConnection);
// Our disconnect handler runs connectionsById.compute(), so don't actually execute the
// disconnect command until we've returned from our compute() calculation
final AtomicReference<Runnable> disconnectAction = new AtomicReference<>();
@@ -509,7 +503,6 @@ public class RlpxAgent {
private ConnectionInitializer connectionInitializer;
private PeerConnectionEvents connectionEvents;
private MetricsSystem metricsSystem;
private Clock clock;
private Builder() {}
@@ -535,8 +528,7 @@ public class RlpxAgent {
peerPrivileges,
config.getMaxPeers(),
config.getMaxRemotelyInitiatedConnections(),
metricsSystem,
clock);
metricsSystem);
}
private void validate() {
@@ -546,7 +538,6 @@ public class RlpxAgent {
checkState(peerPrivileges != null, "PeerPrivileges must be configured");
checkState(peerPermissions != null, "PeerPermissions must be configured");
checkState(metricsSystem != null, "MetricsSystem must be configured");
checkState(clock != null, "Clock must be configured");
}
public Builder keyPair(final KeyPair keyPair) {
@@ -596,11 +587,5 @@ public class RlpxAgent {
this.metricsSystem = metricsSystem;
return this;
}
public Builder clock(final Clock clock) {
checkNotNull(clock);
this.clock = clock;
return this;
}
}
}

View File

@@ -24,19 +24,18 @@ public abstract class RlpxConnection {
private final long initiatedAt;
protected final CompletableFuture<PeerConnection> future;
private RlpxConnection(final CompletableFuture<PeerConnection> future, final long initiatedAt) {
private RlpxConnection(final CompletableFuture<PeerConnection> future) {
this.future = future;
this.initiatedAt = initiatedAt;
this.initiatedAt = System.currentTimeMillis();
}
public static RlpxConnection inboundConnection(
final PeerConnection peerConnection, final long initiatedAt) {
return new RemotelyInitiatedRlpxConnection(peerConnection, initiatedAt);
public static RlpxConnection inboundConnection(final PeerConnection peerConnection) {
return new RemotelyInitiatedRlpxConnection(peerConnection);
}
public static RlpxConnection outboundConnection(
final Peer peer, final CompletableFuture<PeerConnection> future, final long initiatedAt) {
return new LocallyInitiatedRlpxConnection(peer, future, initiatedAt);
final Peer peer, final CompletableFuture<PeerConnection> future) {
return new LocallyInitiatedRlpxConnection(peer, future);
}
public abstract Peer getPeer();
@@ -85,9 +84,8 @@ public abstract class RlpxConnection {
private final PeerConnection peerConnection;
private RemotelyInitiatedRlpxConnection(
final PeerConnection peerConnection, final long initiatedAt) {
super(CompletableFuture.completedFuture(peerConnection), initiatedAt);
private RemotelyInitiatedRlpxConnection(final PeerConnection peerConnection) {
super(CompletableFuture.completedFuture(peerConnection));
this.peerConnection = peerConnection;
}
@@ -149,8 +147,8 @@ public abstract class RlpxConnection {
private final Peer peer;
private LocallyInitiatedRlpxConnection(
final Peer peer, final CompletableFuture<PeerConnection> future, final long initiatedAt) {
super(future, initiatedAt);
final Peer peer, final CompletableFuture<PeerConnection> future) {
super(future);
this.peer = peer;
}

View File

@@ -16,6 +16,7 @@ import static com.google.common.base.Preconditions.checkState;
import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
import tech.pegasys.pantheon.ethereum.p2p.config.RlpxConfiguration;
import tech.pegasys.pantheon.ethereum.p2p.discovery.DiscoveryPeer;
import tech.pegasys.pantheon.ethereum.p2p.peers.EnodeURL;
import tech.pegasys.pantheon.ethereum.p2p.peers.LocalNode;
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
@@ -163,6 +164,10 @@ public class NettyConnectionInitializer implements ConnectionInitializer {
public CompletableFuture<PeerConnection> connect(final Peer peer) {
final CompletableFuture<PeerConnection> connectionFuture = new CompletableFuture<>();
if (peer instanceof DiscoveryPeer) {
((DiscoveryPeer) peer).setLastAttemptedConnection(System.currentTimeMillis());
}
final EnodeURL enode = peer.getEnodeURL();
new Bootstrap()
.group(workers)

View File

@@ -32,7 +32,6 @@ import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions.Action;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissionsBlacklist;
import tech.pegasys.pantheon.testutil.TestClock;
import java.util.Collections;
import java.util.List;
@@ -74,7 +73,7 @@ public class PeerDiscoveryAgentTest {
// Generate an out-of-band NEIGHBORS message.
final List<DiscoveryPeer> peers = helper.createDiscoveryPeers(5);
final NeighborsPacketData data = NeighborsPacketData.create(peers, TestClock.fixed());
final NeighborsPacketData data = NeighborsPacketData.create(peers);
final Packet packet = Packet.create(PacketType.NEIGHBORS, data, otherNode.getKeyPair());
helper.sendMessageBetweenAgents(otherNode, agent, packet);
@@ -113,8 +112,7 @@ public class PeerDiscoveryAgentTest {
packet =
Packet.create(
PacketType.FIND_NEIGHBORS,
FindNeighborsPacketData.create(
otherAgents.get(0).getAdvertisedPeer().get().getId(), TestClock.fixed()),
FindNeighborsPacketData.create(otherAgents.get(0).getAdvertisedPeer().get().getId()),
testAgent.getKeyPair());
helper.sendMessageBetweenAgents(testAgent, agent, packet);
@@ -206,7 +204,7 @@ public class PeerDiscoveryAgentTest {
// Start an agent with no bootstrap peers.
final PeerPermissions peerPermissions = mock(PeerPermissions.class);
final MockPeerDiscoveryAgent agent =
helper.startDiscoveryAgent(Collections.emptyList(), peerPermissions, TestClock.fixed());
helper.startDiscoveryAgent(Collections.emptyList(), peerPermissions);
final Peer localNode = agent.getAdvertisedPeer().get();
// Setup peer and permissions
@@ -233,7 +231,7 @@ public class PeerDiscoveryAgentTest {
// Start an agent with no bootstrap peers.
final PeerPermissions peerPermissions = mock(PeerPermissions.class);
final MockPeerDiscoveryAgent agent =
helper.startDiscoveryAgent(Collections.emptyList(), peerPermissions, TestClock.fixed());
helper.startDiscoveryAgent(Collections.emptyList(), peerPermissions);
final Peer localNode = agent.getAdvertisedPeer().get();
// Setup peer and permissions
@@ -474,8 +472,7 @@ public class PeerDiscoveryAgentTest {
protected void requestNeighbors(
final MockPeerDiscoveryAgent fromAgent, final MockPeerDiscoveryAgent toAgent) {
final FindNeighborsPacketData data =
FindNeighborsPacketData.create(Peer.randomId(), TestClock.fixed());
final FindNeighborsPacketData data = FindNeighborsPacketData.create(Peer.randomId());
final Packet packet = Packet.create(PacketType.FIND_NEIGHBORS, data, fromAgent.getKeyPair());
helper.sendMessageBetweenAgents(fromAgent, toAgent, packet);
}

View File

@@ -21,7 +21,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.MockPeerDiscoveryAg
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.Packet;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PacketType;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PongPacketData;
import tech.pegasys.pantheon.testutil.TestClock;
import java.util.Collections;
import java.util.List;
@@ -68,8 +67,7 @@ public class PeerDiscoveryBondingTest {
// ignored because
// we haven't bonded.
final MockPeerDiscoveryAgent otherNode = helper.startDiscoveryAgent();
final FindNeighborsPacketData data =
FindNeighborsPacketData.create(otherNode.getId(), TestClock.fixed());
final FindNeighborsPacketData data = FindNeighborsPacketData.create(otherNode.getId());
final Packet packet = Packet.create(PacketType.FIND_NEIGHBORS, data, otherNode.getKeyPair());
helper.sendMessageBetweenAgents(otherNode, agent, packet);

View File

@@ -23,7 +23,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.Packet;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PacketType;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PingPacketData;
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.List;
@@ -54,7 +53,7 @@ public class PeerDiscoveryBootstrappingTest {
final PingPacketData pingData = pingPacket.getPacketData(PingPacketData.class).get();
assertThat(pingData.getExpiration())
.isGreaterThanOrEqualTo(TestClock.fixed().millis() / 1000 - 10000);
.isGreaterThanOrEqualTo(System.currentTimeMillis() / 1000 - 10000);
assertThat(pingData.getFrom()).isEqualTo(agent.getAdvertisedPeer().get().getEndpoint());
assertThat(pingData.getTo()).isEqualTo(testAgent.getAdvertisedPeer().get().getEndpoint());
}
@@ -101,7 +100,7 @@ public class PeerDiscoveryBootstrappingTest {
// Assert on the content of the packet data.
final PingPacketData ping = packet.getPacketData(PingPacketData.class).get();
assertThat(ping.getExpiration())
.isGreaterThanOrEqualTo(TestClock.fixed().millis() / 1000 - 10000);
.isGreaterThanOrEqualTo(System.currentTimeMillis() / 1000 - 10000);
assertThat(ping.getTo()).isEqualTo(bootstrapAgent.getAdvertisedPeer().get().getEndpoint());
}
}

View File

@@ -16,7 +16,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import tech.pegasys.pantheon.ethereum.p2p.discovery.PeerDiscoveryEvent.PeerBondedEvent;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.MockPeerDiscoveryAgent;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.ArrayList;
@@ -103,7 +102,7 @@ public class PeerDiscoveryObserversTest {
// Create a discovery agent (which we'll assert on), using the above two peers as bootstrap
// peers.
final MockPeerDiscoveryAgent agent = helper.createDiscoveryAgent(peers2, TestClock.fixed());
final MockPeerDiscoveryAgent agent = helper.createDiscoveryAgent(peers2);
// A queue for storing peer bonded events.
final List<PeerBondedEvent> events = new ArrayList<>(10);
agent.observePeerBondedEvents(events::add);

View File

@@ -24,7 +24,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PacketData;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PacketType;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.ethereum.rlp.RLPException;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import tech.pegasys.pantheon.util.bytes.MutableBytesValue;
@@ -44,8 +43,7 @@ public class PeerDiscoveryPacketSedesTest {
final BytesValue target = BytesValue.wrap(r);
final SECP256K1.KeyPair kp = SECP256K1.KeyPair.generate();
final FindNeighborsPacketData packetData =
FindNeighborsPacketData.create(target, TestClock.fixed());
final FindNeighborsPacketData packetData = FindNeighborsPacketData.create(target);
final Packet packet = Packet.create(PacketType.FIND_NEIGHBORS, packetData, kp);
final Buffer encoded = packet.encode();
assertNotNull(encoded);
@@ -63,8 +61,7 @@ public class PeerDiscoveryPacketSedesTest {
new Random().nextBytes(r);
final BytesValue target = BytesValue.wrap(r);
final FindNeighborsPacketData packet =
FindNeighborsPacketData.create(target, TestClock.fixed());
final FindNeighborsPacketData packet = FindNeighborsPacketData.create(target);
final BytesValue serialized = RLP.encode(packet::writeTo);
assertNotNull(serialized);
@@ -75,14 +72,14 @@ public class PeerDiscoveryPacketSedesTest {
// assertion.
assertThat(deserialized.getExpiration())
.isCloseTo(
TestClock.fixed().millis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS, offset(1500L));
System.currentTimeMillis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS, offset(1500L));
}
@Test
public void neighborsPacketData() {
final List<DiscoveryPeer> peers = helper.createDiscoveryPeers(5);
final NeighborsPacketData packet = NeighborsPacketData.create(peers, TestClock.fixed());
final NeighborsPacketData packet = NeighborsPacketData.create(peers);
final BytesValue serialized = RLP.encode(packet::writeTo);
assertNotNull(serialized);
@@ -92,7 +89,7 @@ public class PeerDiscoveryPacketSedesTest {
// assertion.
assertThat(deserialized.getExpiration())
.isCloseTo(
TestClock.fixed().millis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS, offset(1500L));
System.currentTimeMillis() + PacketData.DEFAULT_EXPIRATION_PERIOD_MS, offset(1500L));
}
@Test(expected = RLPException.class)
@@ -101,8 +98,7 @@ public class PeerDiscoveryPacketSedesTest {
new Random().nextBytes(r);
final BytesValue target = BytesValue.wrap(r);
final FindNeighborsPacketData packet =
FindNeighborsPacketData.create(target, TestClock.fixed());
final FindNeighborsPacketData packet = FindNeighborsPacketData.create(target);
final BytesValue serialized = RLP.encode(packet::writeTo);
assertNotNull(serialized);
@@ -117,7 +113,7 @@ public class PeerDiscoveryPacketSedesTest {
final SECP256K1.KeyPair kp = SECP256K1.KeyPair.generate();
final FindNeighborsPacketData data = FindNeighborsPacketData.create(target, TestClock.fixed());
final FindNeighborsPacketData data = FindNeighborsPacketData.create(target);
final Packet packet = Packet.create(PacketType.FIND_NEIGHBORS, data, kp);
final BytesValue encoded = BytesValue.wrapBuffer(packet.encode());

View File

@@ -24,10 +24,8 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PingPacketData;
import tech.pegasys.pantheon.ethereum.p2p.peers.EnodeURL;
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.time.Clock;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -82,8 +80,7 @@ public class PeerDiscoveryTestHelper {
PacketType.PING,
PingPacketData.create(
fromAgent.getAdvertisedPeer().get().getEndpoint(),
toAgent.getAdvertisedPeer().get().getEndpoint(),
TestClock.fixed()),
toAgent.getAdvertisedPeer().get().getEndpoint()),
fromAgent.getKeyPair());
}
@@ -125,19 +122,7 @@ public class PeerDiscoveryTestHelper {
* @return a list of discovery agents.
*/
public MockPeerDiscoveryAgent startDiscoveryAgent(final List<DiscoveryPeer> bootstrapPeers) {
return startDiscoveryAgent(bootstrapPeers, TestClock.fixed());
}
/**
* Start a single discovery agent with the provided bootstrap peers.
*
* @param bootstrapPeers the list of bootstrap peers
* @param clock the clock to sample timestamps from
* @return a list of discovery agents.
*/
public MockPeerDiscoveryAgent startDiscoveryAgent(
final List<DiscoveryPeer> bootstrapPeers, final Clock clock) {
final AgentBuilder agentBuilder = agentBuilder().bootstrapPeers(bootstrapPeers).clock(clock);
final AgentBuilder agentBuilder = agentBuilder().bootstrapPeers(bootstrapPeers);
return startDiscoveryAgent(agentBuilder);
}
@@ -148,12 +133,6 @@ public class PeerDiscoveryTestHelper {
return startDiscoveryAgent(agentBuilder);
}
public MockPeerDiscoveryAgent startDiscoveryAgent(final Clock clock) {
final AgentBuilder agentBuilder = agentBuilder().bootstrapPeers(List.of()).clock(clock);
return startDiscoveryAgent(agentBuilder);
}
/**
* Start a single discovery agent with the provided bootstrap peers.
*
@@ -162,11 +141,9 @@ public class PeerDiscoveryTestHelper {
* @return a list of discovery agents.
*/
public MockPeerDiscoveryAgent startDiscoveryAgent(
final List<DiscoveryPeer> bootstrapPeers,
final PeerPermissions peerPermissions,
final Clock clock) {
final List<DiscoveryPeer> bootstrapPeers, final PeerPermissions peerPermissions) {
final AgentBuilder agentBuilder =
agentBuilder().bootstrapPeers(bootstrapPeers).peerPermissions(peerPermissions).clock(clock);
agentBuilder().bootstrapPeers(bootstrapPeers).peerPermissions(peerPermissions);
return startDiscoveryAgent(agentBuilder);
}
@@ -177,9 +154,8 @@ public class PeerDiscoveryTestHelper {
return agent;
}
public MockPeerDiscoveryAgent createDiscoveryAgent(
final List<DiscoveryPeer> bootstrapPeers, final Clock clock) {
final AgentBuilder agentBuilder = agentBuilder().bootstrapPeers(bootstrapPeers).clock(clock);
public MockPeerDiscoveryAgent createDiscoveryAgent(final List<DiscoveryPeer> bootstrapPeers) {
final AgentBuilder agentBuilder = agentBuilder().bootstrapPeers(bootstrapPeers);
return createDiscoveryAgent(agentBuilder);
}
@@ -203,7 +179,6 @@ public class PeerDiscoveryTestHelper {
private List<EnodeURL> bootnodes = Collections.emptyList();
private boolean active = true;
private PeerPermissions peerPermissions = PeerPermissions.noop();
private Clock clock = TestClock.fixed();
private AgentBuilder(
final Map<BytesValue, MockPeerDiscoveryAgent> agents,
@@ -240,11 +215,6 @@ public class PeerDiscoveryTestHelper {
return this;
}
public AgentBuilder clock(final Clock clock) {
this.clock = clock;
return this;
}
public MockPeerDiscoveryAgent build() {
final DiscoveryConfiguration config = new DiscoveryConfiguration();
config.setBootnodes(bootnodes);
@@ -252,7 +222,7 @@ public class PeerDiscoveryTestHelper {
config.setActive(active);
return new MockPeerDiscoveryAgent(
SECP256K1.KeyPair.generate(), config, peerPermissions, agents, clock);
SECP256K1.KeyPair.generate(), config, peerPermissions, agents);
}
}
}

View File

@@ -26,7 +26,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PeerDiscoveryContro
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PeerTable;
import tech.pegasys.pantheon.ethereum.p2p.discovery.internal.PingPacketData;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.Subscribers;
import java.util.Collections;
@@ -39,7 +38,6 @@ import org.junit.Test;
public class PeerDiscoveryTimestampsTest {
private final PeerDiscoveryTestHelper helper = new PeerDiscoveryTestHelper();
private final TestClock testClock = new TestClock();
@Test
public void lastSeenAndFirstDiscoveredTimestampsUpdatedOnMessage() {
@@ -62,14 +60,11 @@ public class PeerDiscoveryTimestampsTest {
.tableRefreshIntervalMs(TimeUnit.HOURS.toMillis(1))
.peerBondedObservers(Subscribers.create())
.metricsSystem(new NoOpMetricsSystem())
.clock(testClock)
.build();
controller.start();
testClock.stepMillis(1_000);
final PingPacketData ping =
PingPacketData.create(
peers.get(1).getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(peers.get(1).getEndpoint(), peers.get(0).getEndpoint());
final Packet packet = Packet.create(PacketType.PING, ping, keypairs.get(1));
controller.onMessage(packet, peers.get(1));
@@ -79,7 +74,6 @@ public class PeerDiscoveryTimestampsTest {
assertThat(controller.streamDiscoveredPeers()).hasSize(1);
testClock.stepMillis(1_000);
DiscoveryPeer p = controller.streamDiscoveredPeers().iterator().next();
assertThat(p.getLastSeen()).isGreaterThan(0);
assertThat(p.getFirstDiscovered()).isGreaterThan(0);
@@ -87,7 +81,6 @@ public class PeerDiscoveryTimestampsTest {
lastSeen.set(p.getLastSeen());
firstDiscovered.set(p.getFirstDiscovered());
testClock.stepMillis(1_000);
controller.onMessage(packet, peers.get(1));
assertThat(controller.streamDiscoveredPeers()).hasSize(1);
@@ -99,12 +92,11 @@ public class PeerDiscoveryTimestampsTest {
@Test
public void lastContactedTimestampUpdatedOnOutboundMessage() {
final MockPeerDiscoveryAgent agent =
helper.startDiscoveryAgent(Collections.emptyList(), testClock);
final MockPeerDiscoveryAgent agent = helper.startDiscoveryAgent(Collections.emptyList());
assertThat(agent.streamDiscoveredPeers()).hasSize(0);
// Start a test peer and send a PING packet to the agent under test.
final MockPeerDiscoveryAgent testAgent = helper.startDiscoveryAgent(testClock);
final MockPeerDiscoveryAgent testAgent = helper.startDiscoveryAgent();
final Packet ping = helper.createPingPacket(testAgent, agent);
helper.sendMessageBetweenAgents(testAgent, agent, ping);
@@ -128,7 +120,6 @@ public class PeerDiscoveryTimestampsTest {
firstDiscovered.set(fd);
// Send another packet and ensure that timestamps are updated accordingly.
testClock.stepMillis(1_000);
helper.sendMessageBetweenAgents(testAgent, agent, ping);
peer = agent.streamDiscoveredPeers().iterator().next();

View File

@@ -17,7 +17,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPOutput;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import org.junit.Test;
@@ -25,11 +24,10 @@ import org.junit.Test;
public class FindNeighborsPacketDataTest {
@Test
public void serializeDeserialize() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final BytesValue target = Peer.randomId();
final FindNeighborsPacketData packet =
FindNeighborsPacketData.create(target, TestClock.fixed());
final FindNeighborsPacketData packet = FindNeighborsPacketData.create(target);
final BytesValue serialized = RLP.encode(packet::writeTo);
final FindNeighborsPacketData deserialized =
FindNeighborsPacketData.readFrom(RLP.input(serialized));
@@ -40,7 +38,7 @@ public class FindNeighborsPacketDataTest {
@Test
public void readFrom() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final BytesValue target = Peer.randomId();
BytesValueRLPOutput out = new BytesValueRLPOutput();
@@ -58,7 +56,7 @@ public class FindNeighborsPacketDataTest {
@Test
public void readFrom_withExtraFields() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final BytesValue target = Peer.randomId();
BytesValueRLPOutput out = new BytesValueRLPOutput();

View File

@@ -18,7 +18,6 @@ import static org.mockito.Mockito.when;
import tech.pegasys.pantheon.ethereum.p2p.discovery.DiscoveryPeer;
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.Bytes32;
import tech.pegasys.pantheon.util.bytes.BytesValue;
@@ -31,8 +30,7 @@ public class MockPacketDataFactory {
final DiscoveryPeer from, final DiscoveryPeer... neighbors) {
final Packet packet = mock(Packet.class);
final NeighborsPacketData packetData =
NeighborsPacketData.create(Arrays.asList(neighbors), TestClock.fixed());
final NeighborsPacketData packetData = NeighborsPacketData.create(Arrays.asList(neighbors));
when(packet.getPacketData(any())).thenReturn(Optional.of(packetData));
final BytesValue id = from.getId();
@@ -46,8 +44,7 @@ public class MockPacketDataFactory {
public static Packet mockPongPacket(final DiscoveryPeer from, final BytesValue pingHash) {
final Packet packet = mock(Packet.class);
final PongPacketData pongPacketData =
PongPacketData.create(from.getEndpoint(), pingHash, TestClock.fixed());
final PongPacketData pongPacketData = PongPacketData.create(from.getEndpoint(), pingHash);
when(packet.getPacketData(any())).thenReturn(Optional.of(pongPacketData));
final BytesValue id = from.getId();
when(packet.getNodeId()).thenReturn(id);
@@ -63,8 +60,7 @@ public class MockPacketDataFactory {
BytesValue.fromHexString(
"0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40");
final FindNeighborsPacketData packetData =
FindNeighborsPacketData.create(target, TestClock.fixed());
final FindNeighborsPacketData packetData = FindNeighborsPacketData.create(target);
when(packet.getPacketData(any())).thenReturn(Optional.of(packetData));
final BytesValue id = from.getId();
when(packet.getNodeId()).thenReturn(id);

View File

@@ -22,7 +22,6 @@ import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.net.InetSocketAddress;
import java.time.Clock;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
@@ -40,9 +39,8 @@ public class MockPeerDiscoveryAgent extends PeerDiscoveryAgent {
final KeyPair keyPair,
final DiscoveryConfiguration config,
final PeerPermissions peerPermissions,
final Map<BytesValue, MockPeerDiscoveryAgent> agentNetwork,
final Clock clock) {
super(keyPair, config, peerPermissions, Optional.empty(), new NoOpMetricsSystem(), clock);
final Map<BytesValue, MockPeerDiscoveryAgent> agentNetwork) {
super(keyPair, config, peerPermissions, Optional.empty(), new NoOpMetricsSystem());
this.agentNetwork = agentNetwork;
}

View File

@@ -18,7 +18,6 @@ import static tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper.enode;
import tech.pegasys.pantheon.ethereum.p2p.discovery.DiscoveryPeer;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPOutput;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.Arrays;
@@ -30,11 +29,11 @@ public class NeighborsPacketDataTest {
@Test
public void serializeDeserialize() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final List<DiscoveryPeer> peers =
Arrays.asList(DiscoveryPeer.fromEnode(enode()), DiscoveryPeer.fromEnode(enode()));
final NeighborsPacketData packet = NeighborsPacketData.create(peers, TestClock.fixed());
final NeighborsPacketData packet = NeighborsPacketData.create(peers);
final BytesValue serialized = RLP.encode(packet::writeTo);
final NeighborsPacketData deserialized = NeighborsPacketData.readFrom(RLP.input(serialized));
@@ -44,7 +43,7 @@ public class NeighborsPacketDataTest {
@Test
public void readFrom() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final List<DiscoveryPeer> peers =
Arrays.asList(DiscoveryPeer.fromEnode(enode()), DiscoveryPeer.fromEnode(enode()));
@@ -62,7 +61,7 @@ public class NeighborsPacketDataTest {
@Test
public void readFrom_extraFields() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final List<DiscoveryPeer> peers =
Arrays.asList(DiscoveryPeer.fromEnode(enode()), DiscoveryPeer.fromEnode(enode()));

View File

@@ -41,7 +41,6 @@ import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions.Action;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissionsBlacklist;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.Subscribers;
import tech.pegasys.pantheon.util.bytes.Bytes32;
import tech.pegasys.pantheon.util.bytes.BytesValue;
@@ -114,8 +113,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet, so that we can control the hash,
// which gets validated when receiving the PONG.
final PingPacketData mockPing =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet mockPacket = Packet.create(PacketType.PING, mockPing, keyPairs.get(0));
mockPingPacketCreation(mockPacket);
@@ -185,8 +183,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet, so that we can control the hash,
// which gets validated when receiving the PONG.
final PingPacketData mockPing =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet mockPacket = Packet.create(PacketType.PING, mockPing, keyPairs.get(0));
mockPingPacketCreation(mockPacket);
@@ -204,7 +201,7 @@ public class PeerDiscoveryControllerTest {
// Simulate a PONG message from peer 0.
final PongPacketData packetData =
PongPacketData.create(localPeer.getEndpoint(), mockPacket.getHash(), TestClock.fixed());
PongPacketData.create(localPeer.getEndpoint(), mockPacket.getHash());
final Packet packet = Packet.create(PacketType.PONG, packetData, keyPairs.get(0));
controller.onMessage(packet, peers.get(0));
@@ -240,8 +237,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet, so that we can control the hash,
// which gets validated when receiving the PONG.
final PingPacketData mockPing =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet mockPacket = Packet.create(PacketType.PING, mockPing, keyPairs.get(0));
mockPingPacketCreation(mockPacket);
@@ -276,8 +272,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet, so that we can control the hash, which gets validated
// when receiving the PONG.
final PingPacketData mockPing =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet mockPacket = Packet.create(PacketType.PING, mockPing, keyPairs.get(0));
mockPingPacketCreation(mockPacket);
@@ -292,7 +287,7 @@ public class PeerDiscoveryControllerTest {
// Simulate PONG messages from all peers
for (int i = 0; i < 3; i++) {
final PongPacketData packetData =
PongPacketData.create(localPeer.getEndpoint(), mockPacket.getHash(), TestClock.fixed());
PongPacketData.create(localPeer.getEndpoint(), mockPacket.getHash());
final Packet packet0 = Packet.create(PacketType.PONG, packetData, keyPairs.get(i));
controller.onMessage(packet0, peers.get(i));
}
@@ -337,8 +332,7 @@ public class PeerDiscoveryControllerTest {
// when
// processing the PONG.
final PingPacketData mockPing =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet mockPacket = Packet.create(PacketType.PING, mockPing, keyPairs.get(0));
mockPingPacketCreation(mockPacket);
@@ -352,8 +346,7 @@ public class PeerDiscoveryControllerTest {
// Send a PONG packet from peer 1, with an incorrect hash.
final PongPacketData packetData =
PongPacketData.create(
localPeer.getEndpoint(), BytesValue.fromHexString("1212"), TestClock.fixed());
PongPacketData.create(localPeer.getEndpoint(), BytesValue.fromHexString("1212"));
final Packet packet = Packet.create(PacketType.PONG, packetData, keyPairs.get(1));
controller.onMessage(packet, peers.get(1));
@@ -388,8 +381,7 @@ public class PeerDiscoveryControllerTest {
// when
// processing the PONG.
final PingPacketData mockPing =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet mockPacket = Packet.create(PacketType.PING, mockPing, keyPairs.get(0));
mockPingPacketCreation(mockPacket);
controller.setRetryDelayFunction((prev) -> 999999999L);
@@ -431,8 +423,7 @@ public class PeerDiscoveryControllerTest {
private void respondWithPong(
final DiscoveryPeer discoveryPeer, final KeyPair keyPair, final BytesValue hash) {
final PongPacketData packetData0 =
PongPacketData.create(localPeer.getEndpoint(), hash, TestClock.fixed());
final PongPacketData packetData0 = PongPacketData.create(localPeer.getEndpoint(), hash);
final Packet pongPacket0 = Packet.create(PacketType.PONG, packetData0, keyPair);
controller.onMessage(pongPacket0, discoveryPeer);
}
@@ -454,8 +445,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet, so that we can control the hash, which gets validated
// when processing the PONG.
final PingPacketData pingPacketData =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPingPacketCreation(pingPacket);
@@ -481,7 +471,7 @@ public class PeerDiscoveryControllerTest {
.hasSize(1);
final PongPacketData pongPacketData =
PongPacketData.create(localPeer.getEndpoint(), pingPacket.getHash(), TestClock.fixed());
PongPacketData.create(localPeer.getEndpoint(), pingPacket.getHash());
final Packet pongPacket = Packet.create(PacketType.PONG, pongPacketData, keyPairs.get(1));
controller.onMessage(pongPacket, peers.get(1));
@@ -491,7 +481,7 @@ public class PeerDiscoveryControllerTest {
// Simulate a NEIGHBORS message from peer[0] listing peer[2].
final NeighborsPacketData neighbors0 =
NeighborsPacketData.create(Collections.singletonList(peers.get(2)), TestClock.fixed());
NeighborsPacketData.create(Collections.singletonList(peers.get(2)));
final Packet neighborsPacket0 =
Packet.create(PacketType.NEIGHBORS, neighbors0, keyPairs.get(0));
controller.onMessage(neighborsPacket0, peers.get(0));
@@ -505,7 +495,7 @@ public class PeerDiscoveryControllerTest {
// Simulate bonding and neighbors packet from the second bootstrap peer, with peer[2] reported
// in the peer list.
final NeighborsPacketData neighbors1 =
NeighborsPacketData.create(Collections.singletonList(peers.get(2)), TestClock.fixed());
NeighborsPacketData.create(Collections.singletonList(peers.get(2)));
final Packet neighborsPacket1 =
Packet.create(PacketType.NEIGHBORS, neighbors1, keyPairs.get(1));
controller.onMessage(neighborsPacket1, peers.get(1));
@@ -515,7 +505,7 @@ public class PeerDiscoveryControllerTest {
// Send a PONG packet from peer[2], to transition it to the BONDED state.
final PongPacketData packetData2 =
PongPacketData.create(localPeer.getEndpoint(), pingPacket.getHash(), TestClock.fixed());
PongPacketData.create(localPeer.getEndpoint(), pingPacket.getHash());
final Packet pongPacket2 = Packet.create(PacketType.PONG, packetData2, keyPairs.get(2));
controller.onMessage(pongPacket2, peers.get(2));
@@ -615,8 +605,7 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to discoPeer
List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
PingPacketData pingPacketData =
PingPacketData.create(localEndpoint, discoPeer.getEndpoint(), TestClock.fixed());
PingPacketData pingPacketData = PingPacketData.create(localEndpoint, discoPeer.getEndpoint());
final Packet discoPeerPing = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, discoPeer, discoPeerPing);
@@ -633,15 +622,13 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to otherPeer after neighbors packet is received
keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
pingPacketData =
PingPacketData.create(localEndpoint, otherPeer.getEndpoint(), TestClock.fixed());
pingPacketData = PingPacketData.create(localEndpoint, otherPeer.getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, otherPeer, pingPacket);
// Setup ping to be sent to otherPeer2 after neighbors packet is received
keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
pingPacketData =
PingPacketData.create(localEndpoint, otherPeer2.getEndpoint(), TestClock.fixed());
pingPacketData = PingPacketData.create(localEndpoint, otherPeer2.getEndpoint());
final Packet pingPacket2 = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, otherPeer2, pingPacket2);
@@ -696,8 +683,7 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to discoPeer
List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
PingPacketData pingPacketData =
PingPacketData.create(localEndpoint, discoPeer.getEndpoint(), TestClock.fixed());
PingPacketData pingPacketData = PingPacketData.create(localEndpoint, discoPeer.getEndpoint());
final Packet discoPeerPing = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, discoPeer, discoPeerPing);
@@ -713,15 +699,13 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to otherPeer after neighbors packet is received
keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
pingPacketData =
PingPacketData.create(localEndpoint, otherPeer.getEndpoint(), TestClock.fixed());
pingPacketData = PingPacketData.create(localEndpoint, otherPeer.getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, otherPeer, pingPacket);
// Setup ping to be sent to otherPeer2 after neighbors packet is received
keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
pingPacketData =
PingPacketData.create(localEndpoint, otherPeer2.getEndpoint(), TestClock.fixed());
pingPacketData = PingPacketData.create(localEndpoint, otherPeer2.getEndpoint());
final Packet pingPacket2 = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, otherPeer2, pingPacket2);
@@ -754,7 +738,7 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to discoPeer
final List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
final PingPacketData pingPacketData =
PingPacketData.create(localEndpoint, discoPeer.getEndpoint(), TestClock.fixed());
PingPacketData.create(localEndpoint, discoPeer.getEndpoint());
final Packet discoPeerPing = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, discoPeer, discoPeerPing);
@@ -794,7 +778,7 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to discoPeer
final List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
final PingPacketData pingPacketData =
PingPacketData.create(localEndpoint, discoPeer.getEndpoint(), TestClock.fixed());
PingPacketData.create(localEndpoint, discoPeer.getEndpoint());
final Packet discoPeerPing = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, discoPeer, discoPeerPing);
@@ -835,7 +819,7 @@ public class PeerDiscoveryControllerTest {
// Setup ping to be sent to discoPeer
final List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
final PingPacketData pingPacketData =
PingPacketData.create(localEndpoint, discoPeer.getEndpoint(), TestClock.fixed());
PingPacketData.create(localEndpoint, discoPeer.getEndpoint());
final Packet discoPeerPing = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPacketCreation(PacketType.PING, discoPeer, discoPeerPing);
@@ -864,8 +848,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet to control hash for PONG.
final List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
final PingPacketData pingPacketData =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
final OutboundMessageHandler outboundMessageHandler = mock(OutboundMessageHandler.class);
@@ -904,8 +887,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of PING packets to control hash PONG packets.
final List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
final PingPacketData pingPacketData =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
mockPingPacketCreation(pingPacket);
@@ -964,8 +946,7 @@ public class PeerDiscoveryControllerTest {
// Mock the creation of the PING packet to control hash for PONG.
final List<SECP256K1.KeyPair> keyPairs = PeerDiscoveryTestHelper.generateKeyPairs(1);
final PingPacketData pingPacketData =
PingPacketData.create(
localPeer.getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(localPeer.getEndpoint(), peers.get(0).getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, pingPacketData, keyPairs.get(0));
final OutboundMessageHandler outboundMessageHandler = mock(OutboundMessageHandler.class);
@@ -1196,7 +1177,7 @@ public class PeerDiscoveryControllerTest {
final Packet packet = mock(Packet.class);
final PingPacketData pingPacketData =
PingPacketData.create(from.getEndpoint(), to.getEndpoint(), TestClock.fixed());
PingPacketData.create(from.getEndpoint(), to.getEndpoint());
when(packet.getPacketData(any())).thenReturn(Optional.of(pingPacketData));
final BytesValue id = from.getId();
when(packet.getNodeId()).thenReturn(id);
@@ -1328,7 +1309,6 @@ public class PeerDiscoveryControllerTest {
.peerPermissions(peerPermissions)
.peerBondedObservers(peerBondedObservers)
.metricsSystem(new NoOpMetricsSystem())
.clock(TestClock.fixed())
.build());
}
}

View File

@@ -25,7 +25,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.DiscoveryPeer;
import tech.pegasys.pantheon.ethereum.p2p.discovery.PeerDiscoveryStatus;
import tech.pegasys.pantheon.ethereum.p2p.discovery.PeerDiscoveryTestHelper;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.Subscribers;
import tech.pegasys.pantheon.util.bytes.BytesValue;
@@ -63,14 +62,12 @@ public class PeerDiscoveryTableRefreshTest {
.tableRefreshIntervalMs(0)
.peerBondedObservers(Subscribers.create())
.metricsSystem(new NoOpMetricsSystem())
.clock(TestClock.fixed())
.build());
controller.start();
// Send a PING, so as to add a Peer in the controller.
final PingPacketData ping =
PingPacketData.create(
peers.get(1).getEndpoint(), peers.get(0).getEndpoint(), TestClock.fixed());
PingPacketData.create(peers.get(1).getEndpoint(), peers.get(0).getEndpoint());
final Packet pingPacket = Packet.create(PacketType.PING, ping, keypairs.get(1));
controller.onMessage(pingPacket, peers.get(1));
@@ -79,7 +76,7 @@ public class PeerDiscoveryTableRefreshTest {
// Simulate a PONG message from peer 0.
final PongPacketData pongPacketData =
PongPacketData.create(localPeer.getEndpoint(), pingPacket.getHash(), TestClock.fixed());
PongPacketData.create(localPeer.getEndpoint(), pingPacket.getHash());
final Packet pongPacket = Packet.create(PacketType.PONG, pongPacketData, keypairs.get(0));
final ArgumentCaptor<Packet> captor = ArgumentCaptor.forClass(Packet.class);

View File

@@ -17,7 +17,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import tech.pegasys.pantheon.ethereum.p2p.discovery.Endpoint;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPOutput;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.OptionalInt;
@@ -28,11 +27,11 @@ public class PingPacketDataTest {
@Test
public void serializeDeserialize() {
final long currentTime = TestClock.fixed().millis();
final long currentTime = System.currentTimeMillis();
final Endpoint from = new Endpoint("127.0.0.1", 30303, OptionalInt.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final PingPacketData packet = PingPacketData.create(from, to, TestClock.fixed());
final PingPacketData packet = PingPacketData.create(from, to);
final BytesValue serialized = RLP.encode(packet::writeTo);
final PingPacketData deserialized = PingPacketData.readFrom(RLP.input(serialized));
@@ -46,7 +45,7 @@ public class PingPacketDataTest {
final int version = 4;
final Endpoint from = new Endpoint("127.0.0.1", 30303, OptionalInt.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
out.startList();
@@ -69,7 +68,7 @@ public class PingPacketDataTest {
final int version = 4;
final Endpoint from = new Endpoint("127.0.0.1", 30303, OptionalInt.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
out.startList();
@@ -94,7 +93,7 @@ public class PingPacketDataTest {
final int version = 99;
final Endpoint from = new Endpoint("127.0.0.1", 30303, OptionalInt.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
out.startList();

View File

@@ -17,7 +17,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import tech.pegasys.pantheon.ethereum.p2p.discovery.Endpoint;
import tech.pegasys.pantheon.ethereum.rlp.BytesValueRLPOutput;
import tech.pegasys.pantheon.ethereum.rlp.RLP;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.Bytes32;
import tech.pegasys.pantheon.util.bytes.BytesValue;
@@ -29,11 +28,11 @@ public class PongPacketDataTest {
@Test
public void serializeDeserialize() {
final long currentTime = TestClock.fixed().millis();
final long currentTime = System.currentTimeMillis();
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Bytes32 hash = Bytes32.fromHexStringLenient("0x1234");
final PongPacketData packet = PongPacketData.create(to, hash, TestClock.fixed());
final PongPacketData packet = PongPacketData.create(to, hash);
final BytesValue serialized = RLP.encode(packet::writeTo);
final PongPacketData deserialized = PongPacketData.readFrom(RLP.input(serialized));
@@ -44,7 +43,7 @@ public class PongPacketDataTest {
@Test
public void readFrom() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Bytes32 hash = Bytes32.fromHexStringLenient("0x1234");
@@ -64,7 +63,7 @@ public class PongPacketDataTest {
@Test
public void readFrom_withExtraFields() {
final long time = TestClock.fixed().millis();
final long time = System.currentTimeMillis();
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Bytes32 hash = Bytes32.fromHexStringLenient("0x1234");

View File

@@ -44,7 +44,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.D
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.nat.upnp.UpnpNatManager;
import tech.pegasys.pantheon.nat.upnp.UpnpNatManager.Protocol;
import tech.pegasys.pantheon.testutil.TestClock;
import java.util.ArrayList;
import java.util.List;
@@ -216,7 +215,7 @@ public final class DefaultP2PNetworkTest {
when(natManager.queryExternalIPAddress())
.thenReturn(CompletableFuture.completedFuture(externalIp));
final P2PNetwork network = builder().natManager(natManager).clock(TestClock.fixed()).build();
final P2PNetwork network = builder().natManager(natManager).build();
network.start();
verify(natManager)
@@ -232,7 +231,7 @@ public final class DefaultP2PNetworkTest {
final DefaultP2PNetwork network = network();
network.start();
final DiscoveryPeer peer = DiscoveryPeer.fromEnode(enode());
final PeerBondedEvent peerBondedEvent = new PeerBondedEvent(peer, TestClock.fixed().millis());
final PeerBondedEvent peerBondedEvent = new PeerBondedEvent(peer, System.currentTimeMillis());
discoverySubscriberCaptor.getValue().onPeerBonded(peerBondedEvent);
verify(rlpxAgent, times(1)).connect(peer);
@@ -245,7 +244,7 @@ public final class DefaultP2PNetworkTest {
final DiscoveryPeer peer =
DiscoveryPeer.fromIdAndEndpoint(
Peer.randomId(), new Endpoint("127.0.0.1", 999, OptionalInt.empty()));
final PeerBondedEvent peerBondedEvent = new PeerBondedEvent(peer, TestClock.fixed().millis());
final PeerBondedEvent peerBondedEvent = new PeerBondedEvent(peer, System.currentTimeMillis());
discoverySubscriberCaptor.getValue().onPeerBonded(peerBondedEvent);
verify(rlpxAgent, times(1)).connect(peer);
@@ -306,7 +305,7 @@ public final class DefaultP2PNetworkTest {
}
private DefaultP2PNetwork network() {
return (DefaultP2PNetwork) builder().clock(TestClock.fixed()).build();
return (DefaultP2PNetwork) builder().build();
}
private DefaultP2PNetwork.Builder builder() {

View File

@@ -25,7 +25,6 @@ import tech.pegasys.pantheon.ethereum.p2p.discovery.PeerDiscoveryServiceExceptio
import tech.pegasys.pantheon.ethereum.p2p.peers.EnodeURL;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.Capability;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import java.io.IOException;
import java.util.Arrays;
@@ -158,7 +157,6 @@ public class NetworkingServiceLifecycleTest {
.keyPair(keyPair)
.config(config)
.metricsSystem(new NoOpMetricsSystem())
.clock(TestClock.fixed())
.supportedCapabilities(Arrays.asList(Capability.create("eth", 63)));
}
}

View File

@@ -36,7 +36,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.Capability;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.SubProtocol;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.net.InetAddress;
@@ -327,7 +326,6 @@ public class P2PNetworkTest {
.config(config)
.keyPair(KeyPair.generate())
.metricsSystem(new NoOpMetricsSystem())
.clock(TestClock.fixed())
.supportedCapabilities(Arrays.asList(Capability.create("eth", 63)));
}
}

View File

@@ -49,7 +49,6 @@ import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.D
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.PingMessage;
import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.testutil.TestClock;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.Arrays;
@@ -972,7 +971,6 @@ public class RlpxAgentTest {
.peerPrivileges(peerPrivileges)
.localNode(localNode)
.metricsSystem(metrics)
.clock(TestClock.fixed())
.connectionInitializer(connectionInitializer)
.connectionEvents(peerConnectionEvents)
.build();

View File

@@ -21,7 +21,6 @@ import static tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper.createPeer
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.connections.RlpxConnection.ConnectionNotEstablishedException;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason;
import tech.pegasys.pantheon.testutil.TestClock;
import java.util.concurrent.CompletableFuture;
@@ -33,8 +32,7 @@ public class RlpxConnectionTest {
public void getPeer_pendingOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
assertThat(conn.getPeer()).isEqualTo(peer);
}
@@ -43,8 +41,7 @@ public class RlpxConnectionTest {
public void getPeer_establishedOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
future.complete(peerConnection(peer));
assertThat(conn.getPeer()).isEqualTo(peer);
@@ -54,8 +51,7 @@ public class RlpxConnectionTest {
public void getPeer_inboundConnection() {
final Peer peer = createPeer();
final PeerConnection peerConnection = peerConnection(peer);
final RlpxConnection conn =
RlpxConnection.inboundConnection(peerConnection, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.inboundConnection(peerConnection);
assertThat(conn.getPeer()).isEqualTo(peer);
}
@@ -64,8 +60,7 @@ public class RlpxConnectionTest {
public void disconnect_pendingOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
final DisconnectReason reason = DisconnectReason.REQUESTED;
conn.disconnect(reason);
@@ -84,8 +79,7 @@ public class RlpxConnectionTest {
public void disconnect_activeOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
final PeerConnection peerConnection = peerConnection(peer);
future.complete(peerConnection);
@@ -101,8 +95,7 @@ public class RlpxConnectionTest {
public void disconnect_failedOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
future.completeExceptionally(new IllegalStateException("whoops"));
assertThat(conn.isFailedOrDisconnected()).isTrue();
@@ -115,8 +108,7 @@ public class RlpxConnectionTest {
public void disconnect_inboundConnection() {
final Peer peer = createPeer();
final PeerConnection peerConnection = peerConnection(peer);
final RlpxConnection conn =
RlpxConnection.inboundConnection(peerConnection, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.inboundConnection(peerConnection);
assertThat(conn.isFailedOrDisconnected()).isFalse();
final DisconnectReason reason = DisconnectReason.REQUESTED;
@@ -131,8 +123,7 @@ public class RlpxConnectionTest {
public void getPeerConnection_pendingOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
assertThatThrownBy(conn::getPeerConnection)
.isInstanceOf(ConnectionNotEstablishedException.class);
@@ -142,8 +133,7 @@ public class RlpxConnectionTest {
public void getPeerConnection_activeOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
final PeerConnection peerConnection = peerConnection(peer);
future.complete(peerConnection);
@@ -154,8 +144,7 @@ public class RlpxConnectionTest {
public void getPeerConnection_failedOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
future.completeExceptionally(new IllegalStateException("whoops"));
assertThatThrownBy(conn::getPeerConnection)
@@ -166,8 +155,7 @@ public class RlpxConnectionTest {
public void getPeerConnection_disconnectedOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
final PeerConnection peerConnection = peerConnection(peer);
future.complete(peerConnection);
conn.disconnect(DisconnectReason.REQUESTED);
@@ -179,8 +167,7 @@ public class RlpxConnectionTest {
public void getPeerConnection_activeInboundConnection() {
final Peer peer = createPeer();
final PeerConnection peerConnection = peerConnection(peer);
final RlpxConnection conn =
RlpxConnection.inboundConnection(peerConnection, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.inboundConnection(peerConnection);
assertThat(conn.getPeerConnection()).isEqualTo(peerConnection);
}
@@ -189,8 +176,7 @@ public class RlpxConnectionTest {
public void getPeerConnection_disconnectedInboundConnection() {
final Peer peer = createPeer();
final PeerConnection peerConnection = peerConnection(peer);
final RlpxConnection conn =
RlpxConnection.inboundConnection(peerConnection, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.inboundConnection(peerConnection);
conn.disconnect(DisconnectReason.REQUESTED);
assertThat(conn.getPeerConnection()).isEqualTo(peerConnection);
@@ -200,8 +186,7 @@ public class RlpxConnectionTest {
public void checkState_pendingOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
assertThat(conn.initiatedRemotely()).isFalse();
assertThat(conn.isActive()).isFalse();
@@ -213,8 +198,7 @@ public class RlpxConnectionTest {
public void checkState_activeOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
final PeerConnection peerConnection = peerConnection(peer);
future.complete(peerConnection);
@@ -228,8 +212,7 @@ public class RlpxConnectionTest {
public void checkState_failedOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
future.completeExceptionally(new IllegalStateException("whoops"));
assertThat(conn.initiatedRemotely()).isFalse();
@@ -242,8 +225,7 @@ public class RlpxConnectionTest {
public void checkState_disconnectedOutboundConnection() {
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
final RlpxConnection conn =
RlpxConnection.outboundConnection(peer, future, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);
final PeerConnection peerConnection = peerConnection(peer);
future.complete(peerConnection);
conn.disconnect(DisconnectReason.UNKNOWN);
@@ -258,8 +240,7 @@ public class RlpxConnectionTest {
public void checkState_activeInboundConnection() {
final Peer peer = createPeer();
final PeerConnection peerConnection = peerConnection(peer);
final RlpxConnection conn =
RlpxConnection.inboundConnection(peerConnection, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.inboundConnection(peerConnection);
assertThat(conn.initiatedRemotely()).isTrue();
assertThat(conn.isActive()).isTrue();
@@ -271,8 +252,7 @@ public class RlpxConnectionTest {
public void checkState_disconnectedInboundConnection() {
final Peer peer = createPeer();
final PeerConnection peerConnection = peerConnection(peer);
final RlpxConnection conn =
RlpxConnection.inboundConnection(peerConnection, TestClock.fixed().millis());
final RlpxConnection conn = RlpxConnection.inboundConnection(peerConnection);
conn.disconnect(DisconnectReason.UNKNOWN);
assertThat(conn.initiatedRemotely()).isTrue();

View File

@@ -35,7 +35,6 @@ import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.PantheonMetricCategory;
import java.io.IOException;
import java.time.Clock;
import com.google.common.io.Resources;
import org.junit.Test;
@@ -52,8 +51,7 @@ public class NodeSmartContractPermissioningControllerTest {
private NodeSmartContractPermissioningController setupController(
final String resourceName, final String contractAddressString) throws IOException {
final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(Clock.systemUTC());
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
final String emptyContractFile =
Resources.toString(this.getClass().getResource(resourceName), UTF_8);

View File

@@ -39,7 +39,6 @@ import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.io.IOException;
import java.math.BigInteger;
import java.time.Clock;
import com.google.common.io.Resources;
import org.junit.Test;
@@ -56,8 +55,7 @@ public class TransactionSmartContractPermissioningControllerTest {
private TransactionSmartContractPermissioningController setupController(
final String resourceName, final String contractAddressString) throws IOException {
final ProtocolSchedule<Void> protocolSchedule =
MainnetProtocolSchedule.create(Clock.systemUTC());
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
final String emptyContractFile =
Resources.toString(this.getClass().getResource(resourceName), UTF_8);

View File

@@ -20,8 +20,6 @@ import tech.pegasys.pantheon.services.PantheonPluginContextImpl;
import tech.pegasys.pantheon.util.BlockExporter;
import tech.pegasys.pantheon.util.BlockImporter;
import java.time.Clock;
import org.apache.logging.log4j.Logger;
import picocli.CommandLine.RunLast;
@@ -42,7 +40,6 @@ public final class Pantheon {
new RunnerBuilder(),
new PantheonController.Builder(),
new PantheonPluginContextImpl(),
Clock.systemUTC(),
System.getenv());
pantheonCommand.parse(

View File

@@ -12,8 +12,6 @@
*/
package tech.pegasys.pantheon;
import static com.google.common.base.Preconditions.checkNotNull;
import tech.pegasys.pantheon.cli.config.EthNetworkConfig;
import tech.pegasys.pantheon.controller.PantheonController;
import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
@@ -87,7 +85,6 @@ import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -98,6 +95,7 @@ import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import graphql.GraphQL;
import io.vertx.core.Vertx;
@@ -126,7 +124,6 @@ public class RunnerBuilder {
private MetricsSystem metricsSystem;
private Optional<PermissioningConfiguration> permissioningConfiguration = Optional.empty();
private Collection<EnodeURL> staticNodes = Collections.emptyList();
private Clock clock;
public RunnerBuilder vertx(final Vertx vertx) {
this.vertx = vertx;
@@ -237,14 +234,9 @@ public class RunnerBuilder {
return this;
}
public RunnerBuilder clock(final Clock clock) {
this.clock = clock;
return this;
}
public Runner build() {
checkNotNull(pantheonController);
checkNotNull(clock);
Preconditions.checkNotNull(pantheonController);
final DiscoveryConfiguration discoveryConfiguration;
if (discovery) {
@@ -321,7 +313,6 @@ public class RunnerBuilder {
.config(networkingConfiguration)
.peerPermissions(peerPermissions)
.metricsSystem(metricsSystem)
.clock(clock)
.supportedCapabilities(caps)
.natManager(natManager)
.build();

View File

@@ -622,7 +622,6 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
private Optional<PermissioningConfiguration> permissioningConfiguration;
private Collection<EnodeURL> staticNodes;
private PantheonController<?> pantheonController;
private Clock clock;
private final Supplier<MetricsSystem> metricsSystem =
Suppliers.memoize(() -> PrometheusMetricsSystem.init(metricsConfiguration()));
@@ -634,7 +633,6 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
final RunnerBuilder runnerBuilder,
final PantheonController.Builder controllerBuilderFactory,
final PantheonPluginContextImpl pantheonPluginContext,
final Clock clock,
final Map<String, String> environment) {
this.logger = logger;
this.blockImporter = blockImporter;
@@ -642,7 +640,6 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
this.runnerBuilder = runnerBuilder;
this.controllerBuilderFactory = controllerBuilderFactory;
this.pantheonPluginContext = pantheonPluginContext;
this.clock = clock;
this.environment = environment;
}
@@ -886,7 +883,7 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
.nodePrivateKeyFile(nodePrivateKeyFile())
.metricsSystem(metricsSystem.get())
.privacyParameters(privacyParameters())
.clock(clock)
.clock(Clock.systemUTC())
.isRevertReasonEnabled(isRevertReasonEnabled)
.build();
} catch (final InvalidConfigurationException e) {
@@ -1202,7 +1199,6 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
.metricsSystem(metricsSystem)
.metricsConfiguration(metricsConfiguration)
.staticNodes(staticNodes)
.clock(clock)
.build();
addShutdownHook(runner);

View File

@@ -121,11 +121,7 @@ public class CliquePantheonControllerBuilder extends PantheonControllerBuilder<C
@Override
protected ProtocolSchedule<CliqueContext> createProtocolSchedule() {
return CliqueProtocolSchedule.create(
genesisConfig.getConfigOptions(),
nodeKeys,
privacyParameters,
isRevertReasonEnabled,
clock);
genesisConfig.getConfigOptions(), nodeKeys, privacyParameters, isRevertReasonEnabled);
}
@Override

View File

@@ -64,7 +64,7 @@ public class IbftLegacyPantheonControllerBuilder extends PantheonControllerBuild
@Override
protected ProtocolSchedule<IbftContext> createProtocolSchedule() {
return IbftProtocolSchedule.create(
genesisConfig.getConfigOptions(), privacyParameters, isRevertReasonEnabled, clock);
genesisConfig.getConfigOptions(), privacyParameters, isRevertReasonEnabled);
}
@Override

View File

@@ -211,7 +211,7 @@ public class IbftPantheonControllerBuilder extends PantheonControllerBuilder<Ibf
@Override
protected ProtocolSchedule<IbftContext> createProtocolSchedule() {
return IbftProtocolSchedule.create(
genesisConfig.getConfigOptions(), privacyParameters, isRevertReasonEnabled, clock);
genesisConfig.getConfigOptions(), privacyParameters, isRevertReasonEnabled);
}
@Override

View File

@@ -86,6 +86,6 @@ public class MainnetPantheonControllerBuilder extends PantheonControllerBuilder<
@Override
protected ProtocolSchedule<Void> createProtocolSchedule() {
return MainnetProtocolSchedule.fromConfig(
genesisConfig.getConfigOptions(), privacyParameters, isRevertReasonEnabled, clock);
genesisConfig.getConfigOptions(), privacyParameters, isRevertReasonEnabled);
}
}

Some files were not shown because too many files have changed in this diff Show More