Skip to content

Commit

Permalink
Dagger controller tests (#7341)
Browse files Browse the repository at this point in the history
* daggerize PrivacyReorgTest
* inline as many dagger bits into tests as possible
* refactored to use inner classes
* BesuComponent can now be provided


---------

Signed-off-by: Justin Florentine <[email protected]>
Signed-off-by: Sally MacFarlane <[email protected]>
Co-authored-by: Sally MacFarlane <[email protected]>
  • Loading branch information
jflo and macfarla authored Aug 2, 2024
1 parent 2ddfc2c commit 38a025b
Show file tree
Hide file tree
Showing 31 changed files with 1,064 additions and 261 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,16 @@
import java.nio.file.Path;
import java.util.Collection;

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

public class AllowListContainsKeyAndValue implements Condition {
private final ALLOWLIST_TYPE allowlistType;
private final Collection<String> allowlistValues;
private final Path configFilePath;

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

public AllowListContainsKeyAndValue(
final ALLOWLIST_TYPE allowlistType,
final Collection<String> allowlistValues,
Expand All @@ -47,6 +52,7 @@ public void verify(final Node node) {
allowlistType, allowlistValues, configFilePath);
} catch (final Exception e) {
result = false;
LOG.error("Error verifying allowlist contains key and value", e);
}
assertThat(result).isTrue();
}
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ private PrivacyStorageProvider createKeyValueStorageProvider(
final Path dataLocation, final Path dbLocation) {
final var besuConfiguration = new BesuConfigurationImpl();
besuConfiguration
.init(dataLocation, dbLocation, null)
.init(dataLocation, dbLocation, besuConfig.getDataStorageConfiguration())
.withMiningParameters(besuConfig.getMiningParameters());
return new PrivacyKeyValueStorageProviderBuilder()
.withStorageFactory(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public void setUp() throws Exception {
final BesuNodeRunner besuNodeRunner = new ThreadBesuNodeRunner();
noDiscoveryCluster = new Cluster(clusterConfiguration, net, besuNodeRunner);
final BesuNode noDiscoveryNode = besu.createNodeWithNoDiscovery("noDiscovery");
fullNode = besu.createArchiveNode("node2");
fullNode = besu.createArchiveNode("archive");
noDiscoveryCluster.start(noDiscoveryNode, fullNode);
}

Expand Down
2 changes: 2 additions & 0 deletions besu/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ dependencies {
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.testcontainers:testcontainers'
testImplementation 'tech.pegasys.discovery:discovery'
testImplementation 'com.google.dagger:dagger'

annotationProcessor 'com.google.dagger:dagger-compiler'
testAnnotationProcessor 'com.google.dagger:dagger-compiler'
}
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ public BesuController build() {
checkNotNull(evmConfiguration, "Missing evm config");
checkNotNull(networkingConfiguration, "Missing network configuration");
checkNotNull(dataStorageConfiguration, "Missing data storage configuration");

prepForBuild();

final ProtocolSchedule protocolSchedule = createProtocolSchedule();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.inject.Inject;

/** The Blockchain service implementation. */
@Unstable
Expand All @@ -44,6 +45,7 @@ public class BlockchainServiceImpl implements BlockchainService {
private MutableBlockchain blockchain;

/** Instantiates a new Blockchain service implementation. */
@Inject
public BlockchainServiceImpl() {}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.hyperledger.besu.plugin.services.permissioning.NodeMessagePermissioningProvider;

import java.util.List;
import javax.inject.Inject;

import com.google.common.collect.Lists;

Expand All @@ -29,6 +30,7 @@ public class PermissioningServiceImpl implements PermissioningService {
Lists.newArrayList();

/** Default Constructor. */
@Inject
public PermissioningServiceImpl() {}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -48,6 +49,7 @@ public class RpcEndpointServiceImpl implements RpcEndpointService {
private Map<String, JsonRpcMethod> inProcessRpcMethods;

/** Default Constructor. */
@Inject
public RpcEndpointServiceImpl() {}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,18 @@
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import javax.inject.Inject;

/** The Security module service implementation. */
public class SecurityModuleServiceImpl implements SecurityModuleService {
private final Map<String, Supplier<SecurityModule>> securityModuleSuppliers =
new ConcurrentHashMap<>();

/** Default Constructor. */
@Inject
public SecurityModuleServiceImpl() {}

private final Map<String, Supplier<SecurityModule>> securityModuleSuppliers =
new ConcurrentHashMap<>();

@Override
public void register(final String name, final Supplier<SecurityModule> securityModuleSupplier) {
securityModuleSuppliers.put(name, securityModuleSupplier);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Inject;

/** The Storage service implementation. */
public class StorageServiceImpl implements StorageService {
Expand All @@ -31,6 +32,7 @@ public class StorageServiceImpl implements StorageService {
private final Map<String, KeyValueStorageFactory> factories;

/** Instantiates a new Storage service. */
@Inject
public StorageServiceImpl() {
this.segments = List.of(KeyValueSegmentIdentifier.values());
this.factories = new ConcurrentHashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@
import org.hyperledger.besu.plugin.services.txvalidator.PluginTransactionPoolValidatorFactory;

import java.util.Optional;
import javax.inject.Inject;

/** The Transaction pool validator service implementation. */
public class TransactionPoolValidatorServiceImpl implements TransactionPoolValidatorService {

private Optional<PluginTransactionPoolValidatorFactory> factory = Optional.empty();

/** Default Constructor. */
@Inject
public TransactionPoolValidatorServiceImpl() {}

private Optional<PluginTransactionPoolValidatorFactory> factory = Optional.empty();

@Override
public PluginTransactionPoolValidator createTransactionValidator() {
return factory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@
import org.hyperledger.besu.plugin.services.txselection.PluginTransactionSelectorFactory;

import java.util.Optional;
import javax.inject.Inject;

/** The Transaction Selection service implementation. */
public class TransactionSelectionServiceImpl implements TransactionSelectionService {

private Optional<PluginTransactionSelectorFactory> factory = Optional.empty();

/** Default Constructor. */
@Inject
public TransactionSelectionServiceImpl() {}

private Optional<PluginTransactionSelectorFactory> factory = Optional.empty();

@Override
public PluginTransactionSelector createPluginTransactionSelector() {
return factory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.hyperledger.besu.plugin.services.TransactionSimulationService;

import java.util.Optional;
import javax.inject.Inject;

/** TransactionSimulationServiceImpl */
@Unstable
Expand All @@ -43,6 +44,7 @@ public class TransactionSimulationServiceImpl implements TransactionSimulationSe
private TransactionSimulator transactionSimulator;

/** Create an instance to be configured */
@Inject
public TransactionSimulationServiceImpl() {}

/**
Expand Down
168 changes: 168 additions & 0 deletions besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright contributors to Hyperledger Besu.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.ethereum.core.PrivacyParameters.FLEXIBLE_PRIVACY;

import org.hyperledger.besu.components.BesuComponent;
import org.hyperledger.besu.components.BesuPluginContextModule;
import org.hyperledger.besu.components.MockBesuCommandModule;
import org.hyperledger.besu.components.NoOpMetricsSystemModule;
import org.hyperledger.besu.components.PrivacyTestModule;
import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.controller.BesuController;
import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.enclave.EnclaveFactory;
import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider;
import org.hyperledger.besu.ethereum.core.MiningParameters;
import org.hyperledger.besu.ethereum.core.PrivacyParameters;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.sync.SyncMode;
import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration;
import org.hyperledger.besu.ethereum.eth.transactions.BlobCacheModule;
import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolConfiguration;
import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration;
import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider;
import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoaderModule;
import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration;
import org.hyperledger.besu.evm.internal.EvmConfiguration;
import org.hyperledger.besu.evm.precompile.PrecompiledContract;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.testutil.TestClock;

import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Component;
import dagger.Module;
import dagger.Provides;
import io.vertx.core.Vertx;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

class FlexGroupPrivacyTest {

private final Vertx vertx = Vertx.vertx();

@AfterEach
public void cleanUp() {
vertx.close();
}

@Test
void flexibleEnabledPrivacy() {
final BesuController besuController =
DaggerFlexGroupPrivacyTest_FlexGroupPrivacyTestComponent.builder()
.build()
.getBesuController();

final PrecompiledContract flexiblePrecompiledContract =
getPrecompile(besuController, FLEXIBLE_PRIVACY);

assertThat(flexiblePrecompiledContract.getName()).isEqualTo("FlexiblePrivacy");
}

private PrecompiledContract getPrecompile(
final BesuController besuController, final Address defaultPrivacy) {
return besuController
.getProtocolSchedule()
.getByBlockHeader(blockHeader(0))
.getPrecompileContractRegistry()
.get(defaultPrivacy);
}

private BlockHeader blockHeader(final long number) {
return new BlockHeaderTestFixture().number(number).buildHeader();
}

@Singleton
@Component(
modules = {
FlexGroupPrivacyParametersModule.class,
FlexGroupPrivacyTest.PrivacyTestBesuControllerModule.class,
PrivacyTestModule.class,
MockBesuCommandModule.class,
BonsaiCachedMerkleTrieLoaderModule.class,
NoOpMetricsSystemModule.class,
BesuPluginContextModule.class,
BlobCacheModule.class
})
interface FlexGroupPrivacyTestComponent extends BesuComponent {
BesuController getBesuController();
}

@Module
static class FlexGroupPrivacyParametersModule {

@Provides
PrivacyParameters providePrivacyParameters(
final PrivacyStorageProvider storageProvider, final Vertx vertx) {
try {
return new PrivacyParameters.Builder()
.setEnabled(true)
.setEnclaveUrl(new URI("http://127.0.0.1:8000"))
.setStorageProvider(storageProvider)
.setEnclaveFactory(new EnclaveFactory(vertx))
.setFlexiblePrivacyGroupsEnabled(true)
.build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}

@Module
static class PrivacyTestBesuControllerModule {

@Provides
@Singleton
@SuppressWarnings("CloseableProvides")
BesuController provideBesuController(
final PrivacyParameters privacyParameters,
final DataStorageConfiguration dataStorageConfiguration,
final FlexGroupPrivacyTestComponent context,
@Named("dataDir") final Path dataDir) {

return new BesuController.Builder()
.fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.FULL)
.synchronizerConfiguration(SynchronizerConfiguration.builder().build())
.ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.storageProvider(new InMemoryKeyValueStorageProvider())
.networkId(BigInteger.ONE)
.miningParameters(MiningParameters.newDefault())
.dataStorageConfiguration(dataStorageConfiguration)
.nodeKey(NodeKeyUtils.generate())
.metricsSystem(new NoOpMetricsSystem())
.dataDirectory(dataDir)
.clock(TestClock.fixed())
.privacyParameters(privacyParameters)
.transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT)
.gasLimitCalculator(GasLimitCalculator.constant())
.evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create())
.besuComponent(context)
.build();
}
}
}
Loading

0 comments on commit 38a025b

Please sign in to comment.