diff --git a/CODING-CONVENTIONS.md b/CODING-CONVENTIONS.md index 8fded79354..5f1ddb5a31 100644 --- a/CODING-CONVENTIONS.md +++ b/CODING-CONVENTIONS.md @@ -149,7 +149,9 @@ Method parameters must be final. Class level and local fields should be final w * Getters follow idiomatic format with `get` prefix. For example, `getBlock()` gets a block property. * Setters follow idiomatic format with `set` prefix. For example, `setBlock(Block block)` sets a block property. -* For `toString methods`, use the Guava 18+ `MoreObjects.toStringHelper` +* The Setter pattern should not be used for chained builder methods. +* Methods returning a `Stream` should be prefixed with `stream`. For example `streamIdlePeers()` returns a stream of the idle peers. +* For `toString` methods use the Guava 18+ `MoreObjects.toStringHelper` * Equals and `hashCode()` methods use the `Object.equals` and `Object.hash` methods (this is the _Java 7+_ template in IntelliJ. Don’t accept subclasses and don’t use getters) ## 4.2.4 Testing diff --git a/config/src/main/java/tech/pegasys/pantheon/config/GenesisConfigFile.java b/config/src/main/java/tech/pegasys/pantheon/config/GenesisConfigFile.java index bb40077160..6824ccb8f4 100644 --- a/config/src/main/java/tech/pegasys/pantheon/config/GenesisConfigFile.java +++ b/config/src/main/java/tech/pegasys/pantheon/config/GenesisConfigFile.java @@ -64,7 +64,7 @@ public GenesisConfigOptions getConfigOptions() { return new JsonGenesisConfigOptions(configRoot.getJsonObject("config")); } - public Stream getAllocations() { + public Stream streamAllocations() { final JsonObject allocations = configRoot.getJsonObject("alloc", new JsonObject()); return allocations.fieldNames().stream() .map(key -> new GenesisAllocation(key, allocations.getJsonObject(key))); diff --git a/config/src/test/java/tech/pegasys/pantheon/config/GenesisConfigFileTest.java b/config/src/test/java/tech/pegasys/pantheon/config/GenesisConfigFileTest.java index fcfc757306..00b7a52015 100644 --- a/config/src/test/java/tech/pegasys/pantheon/config/GenesisConfigFileTest.java +++ b/config/src/test/java/tech/pegasys/pantheon/config/GenesisConfigFileTest.java @@ -35,7 +35,7 @@ public void shouldLoadMainnetConfigFile() { // Sanity check some basic properties to confirm this is the mainnet file. assertThat(config.getConfigOptions().isEthHash()).isTrue(); assertThat(config.getConfigOptions().getChainId()).hasValue(MAINNET_CHAIN_ID); - assertThat(config.getAllocations().map(GenesisAllocation::getAddress)) + assertThat(config.streamAllocations().map(GenesisAllocation::getAddress)) .contains( "000d836201318ec6899a67540690382780743280", "001762430ea9c3a26e5749afdb70da5f78ddbb8c", @@ -48,7 +48,7 @@ public void shouldLoadDevelopmentConfigFile() { // Sanity check some basic properties to confirm this is the dev file. assertThat(config.getConfigOptions().isEthHash()).isTrue(); assertThat(config.getConfigOptions().getChainId()).hasValue(DEVELOPMENT_CHAIN_ID); - assertThat(config.getAllocations().map(GenesisAllocation::getAddress)) + assertThat(config.streamAllocations().map(GenesisAllocation::getAddress)) .contains( "fe3b557e8fb62b89f4916b721be55ceb828dbd73", "627306090abab3a6e1400e9345bc60c78a8bef57", @@ -155,7 +155,7 @@ public void shouldGetAllocations() { final Map allocations = config - .getAllocations() + .streamAllocations() .collect( Collectors.toMap(GenesisAllocation::getAddress, GenesisAllocation::getBalance)); assertThat(allocations) @@ -168,7 +168,7 @@ public void shouldGetAllocations() { @Test public void shouldGetEmptyAllocationsWhenAllocNotPresent() { final GenesisConfigFile config = GenesisConfigFile.fromConfig("{}"); - assertThat(config.getAllocations()).isEmpty(); + assertThat(config.streamAllocations()).isEmpty(); } @Test diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisState.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisState.java index ae38832264..51f400dcdb 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisState.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisState.java @@ -189,7 +189,7 @@ private static Hash parseMixHash(final GenesisConfigFile genesis) { } private static Stream parseAllocations(final GenesisConfigFile genesis) { - return genesis.getAllocations().map(GenesisAccount::fromAllocation); + return genesis.streamAllocations().map(GenesisAccount::fromAllocation); } private static long parseNonce(final GenesisConfigFile genesis) { diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/WorldState.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/WorldState.java index 675ed32fcd..4bc4808ff7 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/WorldState.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/WorldState.java @@ -37,5 +37,5 @@ public interface WorldState extends WorldView { * @return a stream of all the accounts (in no particular order) contained in the world state * represented by the root hash of this object at the time of the call. */ - Stream accounts(); + Stream streamAccounts(); } diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DebuggableMutableWorldState.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DebuggableMutableWorldState.java index b6aa0904b7..0be107524d 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DebuggableMutableWorldState.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DebuggableMutableWorldState.java @@ -73,7 +73,7 @@ public WorldUpdater updater() { } @Override - public Stream accounts() { + public Stream streamAccounts() { return info.accounts.stream().map(this::get).filter(Objects::nonNull); } @@ -81,7 +81,7 @@ public Stream accounts() { public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(rootHash()).append(":\n"); - accounts() + streamAccounts() .forEach( account -> { final Address address = account.getAddress(); diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DefaultMutableWorldState.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DefaultMutableWorldState.java index f83d0f4e3d..cde611886e 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DefaultMutableWorldState.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/worldstate/DefaultMutableWorldState.java @@ -103,13 +103,13 @@ public Account get(final Address address) { private AccountState deserializeAccount( final Address address, final Hash addressHash, final BytesValue encoded) throws RLPException { final RLPInput in = RLP.input(encoded); - StateTrieAccountValue accountValue = StateTrieAccountValue.readFrom(in); + final StateTrieAccountValue accountValue = StateTrieAccountValue.readFrom(in); return new AccountState(address, addressHash, accountValue); } private static BytesValue serializeAccount( final long nonce, final Wei balance, final Hash storageRoot, final Hash codeHash) { - StateTrieAccountValue accountValue = + final StateTrieAccountValue accountValue = new StateTrieAccountValue(nonce, balance, storageRoot, codeHash); return RLP.encode(accountValue::writeTo); } @@ -120,7 +120,7 @@ public WorldUpdater updater() { } @Override - public Stream accounts() { + public Stream streamAccounts() { // TODO: the current trie implementation doesn't have walking capability yet (pending NC-746) // so this can't be implemented. throw new UnsupportedOperationException("TODO"); @@ -226,7 +226,7 @@ public BytesValue getCode() { return updatedCode; } // No code is common, save the KV-store lookup. - Hash codeHash = getCodeHash(); + final Hash codeHash = getCodeHash(); if (codeHash.equals(Hash.EMPTY)) { return BytesValue.EMPTY; } diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/EthPeers.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/EthPeers.java index 75ea1a7795..c5f77eafd5 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/EthPeers.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/EthPeers.java @@ -119,12 +119,12 @@ public int peerCount() { return connections.size(); } - public Stream availablePeers() { + public Stream streamAvailablePeers() { return connections.values().stream().filter(EthPeer::readyForRequests); } public Optional bestPeer() { - return availablePeers().max(BEST_CHAIN); + return streamAvailablePeers().max(BEST_CHAIN); } @FunctionalInterface diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/PendingPeerRequest.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/PendingPeerRequest.java index 3cd1d1d964..365617e523 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/PendingPeerRequest.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/PendingPeerRequest.java @@ -81,7 +81,7 @@ private Optional getLeastBusySuitablePeer() { return peer.isPresent() ? peer : ethPeers - .availablePeers() + .streamAvailablePeers() .filter(peer -> peer.chainState().getEstimatedHeight() >= minimumBlockNumber) .min(EthPeers.LEAST_TO_MOST_BUSY); } diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcaster.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcaster.java index 6291489bc3..9c256d508a 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcaster.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcaster.java @@ -34,14 +34,14 @@ public void propagate(final Block block, final UInt256 totalDifficulty) { final NewBlockMessage newBlockMessage = NewBlockMessage.create(block, totalDifficulty); ethContext .getEthPeers() - .availablePeers() + .streamAvailablePeers() .filter(ethPeer -> !ethPeer.hasSeenBlock(block.getHash())) .forEach( ethPeer -> { ethPeer.registerKnownBlock(block.getHash()); try { ethPeer.send(newBlockMessage); - } catch (PeerConnection.PeerNotConnected e) { + } catch (final PeerConnection.PeerNotConnected e) { LOG.trace("Failed to broadcast new block to peer", e); } }); diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiter.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiter.java index 69a017666a..1227cb3386 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiter.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiter.java @@ -56,7 +56,7 @@ public void enforceTrailingPeerLimit() { final long maxTrailingPeers = requirements.getMaxTrailingPeers(); final List trailingPeers = ethPeers - .availablePeers() + .streamAvailablePeers() .filter(peer -> peer.chainState().hasEstimatedHeight()) .filter(peer -> peer.chainState().getEstimatedHeight() < minimumHeightToBeUpToDate) .sorted(BY_CHAIN_HEIGHT) diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/fastsync/PivotBlockRetriever.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/fastsync/PivotBlockRetriever.java index e238089832..6218eb7f11 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/fastsync/PivotBlockRetriever.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/fastsync/PivotBlockRetriever.java @@ -75,7 +75,7 @@ private CompletableFuture[] requestHeaderFromAllPeers() { final List peersToQuery = ethContext .getEthPeers() - .availablePeers() + .streamAvailablePeers() .filter(peer -> peer.chainState().getEstimatedHeight() >= pivotBlockNumber) .collect(Collectors.toList()); diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/transactions/TransactionSender.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/transactions/TransactionSender.java index 90c74ba6e6..6b4e90a9f1 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/transactions/TransactionSender.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/transactions/TransactionSender.java @@ -35,7 +35,7 @@ public TransactionSender( public void onTransactionsAdded(final Iterable transactions) { ethContext .getEthPeers() - .availablePeers() + .streamAvailablePeers() .forEach( peer -> transactions.forEach( diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/RespondingEthPeer.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/RespondingEthPeer.java index 8838703c2d..3e5b23ff62 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/RespondingEthPeer.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/RespondingEthPeer.java @@ -214,7 +214,7 @@ public Optional peekNextOutgoingRequest() { return Optional.of(outgoingMessages.peek().messageData); } - public Stream pendingOutgoingRequests() { + public Stream streamPendingOutgoingRequests() { return outgoingMessages.stream().map(OutgoingMessage::messageData); } diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcasterTest.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcasterTest.java index e2ec83a3ee..a1d2fa5957 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcasterTest.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockBroadcasterTest.java @@ -40,7 +40,7 @@ public class BlockBroadcasterTest { public void blockPropagationUnitTest() throws PeerConnection.PeerNotConnected { final EthPeer ethPeer = mock(EthPeer.class); final EthPeers ethPeers = mock(EthPeers.class); - when(ethPeers.availablePeers()).thenReturn(Stream.of(ethPeer)); + when(ethPeers.streamAvailablePeers()).thenReturn(Stream.of(ethPeer)); final EthContext ethContext = mock(EthContext.class); when(ethContext.getEthPeers()).thenReturn(ethPeers); @@ -63,7 +63,7 @@ public void blockPropagationUnitTestSeenUnseen() throws PeerConnection.PeerNotCo final EthPeer ethPeer1 = mock(EthPeer.class); final EthPeers ethPeers = mock(EthPeers.class); - when(ethPeers.availablePeers()).thenReturn(Stream.of(ethPeer0, ethPeer1)); + when(ethPeers.streamAvailablePeers()).thenReturn(Stream.of(ethPeer0, ethPeer1)); final EthContext ethContext = mock(EthContext.class); when(ethContext.getEthPeers()).thenReturn(ethPeers); diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiterTest.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiterTest.java index e94dd8ba06..dffc3676d9 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiterTest.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/TrailingPeerLimiterTest.java @@ -55,7 +55,7 @@ public class TrailingPeerLimiterTest { @Before public void setUp() { - when(ethPeers.availablePeers()).then(invocation -> peers.stream()); + when(ethPeers.streamAvailablePeers()).then(invocation -> peers.stream()); } @Test diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/FullSyncChainDownloaderTest.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/FullSyncChainDownloaderTest.java index 43a35f2fca..6100e942c1 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/FullSyncChainDownloaderTest.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/FullSyncChainDownloaderTest.java @@ -414,7 +414,7 @@ public void requestsCheckpointsFromSyncTarget() { // Check that any requests for checkpoint headers are only sent to the best peer final long checkpointRequestsToOtherPeers = otherPeers.stream() - .map(RespondingEthPeer::pendingOutgoingRequests) + .map(RespondingEthPeer::streamPendingOutgoingRequests) .flatMap(Function.identity()) .filter(m -> m.getCode() == EthPV62.GET_BLOCK_HEADERS) .map(GetBlockHeadersMessage::readFrom) diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetrics.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetrics.java index 7320a0168d..b0a04bf503 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetrics.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetrics.java @@ -39,7 +39,9 @@ public String getName() { @Override public JsonRpcResponse response(final JsonRpcRequest request) { final Map observations = new HashMap<>(); - metricsSystem.getMetrics().forEach(observation -> addObservation(observations, observation)); + metricsSystem + .streamObservations() + .forEach(observation -> addObservation(observations, observation)); return new JsonRpcSuccessResponse(request.getId(), observations); } diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetricsTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetricsTest.java index e89a03827e..ed4f209349 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetricsTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/DebugMetricsTest.java @@ -45,7 +45,7 @@ public void shouldHaveCorrectName() { @Test public void shouldReportUnlabelledObservationsByCategory() { - when(metricsSystem.getMetrics()) + when(metricsSystem.streamObservations()) .thenReturn( Stream.of( new Observation(PEERS, "peer1", "peer1Value", Collections.emptyList()), @@ -62,7 +62,7 @@ public void shouldReportUnlabelledObservationsByCategory() { @Test public void shouldNestObservationsByLabel() { - when(metricsSystem.getMetrics()) + when(metricsSystem.streamObservations()) .thenReturn( Stream.of( new Observation(PEERS, "peer1", "value1", asList("label1A", "label2A")), diff --git a/ethereum/mock-p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/testing/MockNetwork.java b/ethereum/mock-p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/testing/MockNetwork.java index 074dcafe7e..a74e913b94 100644 --- a/ethereum/mock-p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/testing/MockNetwork.java +++ b/ethereum/mock-p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/testing/MockNetwork.java @@ -129,7 +129,7 @@ public Collection getPeers() { } @Override - public Stream getDiscoveredPeers() { + public Stream streamDiscoveredPeers() { return Stream.empty(); } diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/NoopP2PNetwork.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/NoopP2PNetwork.java index bc14cc67a6..35911af1c3 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/NoopP2PNetwork.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/NoopP2PNetwork.java @@ -35,7 +35,7 @@ public Collection getPeers() { } @Override - public Stream getDiscoveredPeers() { + public Stream streamDiscoveredPeers() { return Stream.empty(); } diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/api/P2PNetwork.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/api/P2PNetwork.java index aee2c95e4f..e3d0d8190c 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/api/P2PNetwork.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/api/P2PNetwork.java @@ -42,7 +42,7 @@ public interface P2PNetwork extends Closeable { * * @return A stream of discovered peers on the network. */ - Stream getDiscoveredPeers(); + Stream streamDiscoveredPeers(); /** * Connects to a {@link Peer}. diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgent.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgent.java index 43396f1ed8..9f1fd72083 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgent.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgent.java @@ -162,7 +162,7 @@ public void addPeerRequirement(final PeerRequirement peerRequirement) { } private void startController() { - PeerDiscoveryController controller = createController(); + final PeerDiscoveryController controller = createController(); this.controller = Optional.of(controller); controller.start(); } @@ -240,8 +240,8 @@ protected void handleOutgoingPacket(final DiscoveryPeer peer, final Packet packe }); } - public Stream getPeers() { - return controller.map(PeerDiscoveryController::getPeers).orElse(Stream.empty()); + public Stream streamDiscoveredPeers() { + return controller.map(PeerDiscoveryController::streamDiscoveredPeers).orElse(Stream.empty()); } public Optional getAdvertisedPeer() { diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Bucket.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Bucket.java index ca67ddd351..04d0136114 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Bucket.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Bucket.java @@ -134,7 +134,7 @@ synchronized boolean evict(final PeerId peer) { * * @return immutable view of the peer array */ - synchronized List peers() { + synchronized List getPeers() { return unmodifiableList(asList(Arrays.copyOf(kBucket, tailIndex + 1))); } diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryController.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryController.java index 1d585498c1..968294f990 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryController.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryController.java @@ -219,7 +219,7 @@ public void start() { // if smart contract permissioning is enabled, bond with bootnodes if (nodePermissioningController.get().getSyncStatusNodePermissioningProvider().isPresent()) { - for (DiscoveryPeer p : initialDiscoveryPeers) { + for (final DiscoveryPeer p : initialDiscoveryPeers) { bond(p); } } @@ -554,8 +554,8 @@ private void dispatchEvent( * * @return List of peers. */ - public Stream getPeers() { - return peerTable.getAllPeers(); + public Stream streamDiscoveredPeers() { + return peerTable.streamAllPeers(); } public void setRetryDelayFunction(final RetryDelayFunction retryDelayFunction) { diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java index 91744ddff7..a2357a2fe9 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java @@ -154,7 +154,7 @@ public EvictResult tryEvict(final PeerId peer) { distanceCache.remove(id); - if (table[distance].peers().isEmpty()) { + if (table[distance].getPeers().isEmpty()) { return EvictResult.absent(); } @@ -176,7 +176,7 @@ public EvictResult tryEvict(final PeerId peer) { private void buildBloomFilter() { final BloomFilter bf = BloomFilter.create((id, val) -> val.putBytes(id.extractArray()), maxEntriesCnt, 0.001); - getAllPeers().map(Peer::getId).forEach(bf::put); + streamAllPeers().map(Peer::getId).forEach(bf::put); this.evictionCnt = 0; this.idBloom = bf; } @@ -191,15 +191,15 @@ private void buildBloomFilter() { */ public List nearestPeers(final BytesValue target, final int limit) { final BytesValue keccak256 = Hash.keccak256(target); - return getAllPeers() + return streamAllPeers() .filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDED) .sorted(comparingInt((peer) -> distance(peer.keccak256(), keccak256))) .limit(limit) .collect(toList()); } - public Stream getAllPeers() { - return Arrays.stream(table).flatMap(e -> e.peers().stream()); + public Stream streamAllPeers() { + return Arrays.stream(table).flatMap(e -> e.getPeers().stream()); } /** diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetwork.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetwork.java index fd8baf683c..b989af1d14 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetwork.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetwork.java @@ -400,7 +400,7 @@ void attemptPeerConnections() { } final List peers = - getDiscoveredPeers() + streamDiscoveredPeers() .filter(peer -> peer.getStatus() == PeerDiscoveryStatus.BONDED) .filter(peer -> !isConnected(peer) && !isConnecting(peer)) .collect(Collectors.toList()); @@ -426,8 +426,8 @@ public Collection getPeers() { } @Override - public Stream getDiscoveredPeers() { - return peerDiscoveryAgent.getPeers(); + public Stream streamDiscoveredPeers() { + return peerDiscoveryAgent.streamDiscoveredPeers(); } @Override diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgentTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgentTest.java index 2a6c118d9b..b8e5356da4 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgentTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryAgentTest.java @@ -46,7 +46,7 @@ public class PeerDiscoveryAgentTest { public void neighborsPacketFromUnbondedPeerIsDropped() { // Start an agent with no bootstrap peers. final MockPeerDiscoveryAgent agent = helper.startDiscoveryAgent(Collections.emptyList()); - assertThat(agent.getPeers()).isEmpty(); + assertThat(agent.streamDiscoveredPeers()).isEmpty(); // Start a test peer final MockPeerDiscoveryAgent otherNode = helper.startDiscoveryAgent(); @@ -57,7 +57,7 @@ public void neighborsPacketFromUnbondedPeerIsDropped() { final Packet packet = Packet.create(PacketType.NEIGHBORS, data, otherNode.getKeyPair()); helper.sendMessageBetweenAgents(otherNode, agent, packet); - assertThat(agent.getPeers()).isEmpty(); + assertThat(agent.streamDiscoveredPeers()).isEmpty(); } @Test @@ -77,8 +77,9 @@ public void neighborsPacketLimited() { // list. By moving to a contains we make sure that all the peers are loaded with tolerance for // duplicates. If we fix the duplication problem we should use containsExactlyInAnyOrder to // hedge against missing one and duplicating another. - assertThat(agent.getPeers()).contains(otherPeers.toArray(new DiscoveryPeer[20])); - assertThat(agent.getPeers()).allMatch(p -> p.getStatus() == PeerDiscoveryStatus.BONDED); + assertThat(agent.streamDiscoveredPeers()).contains(otherPeers.toArray(new DiscoveryPeer[20])); + assertThat(agent.streamDiscoveredPeers()) + .allMatch(p -> p.getStatus() == PeerDiscoveryStatus.BONDED); // Use additional agent to exchange messages with agent final MockPeerDiscoveryAgent testAgent = helper.startDiscoveryAgent(); @@ -96,12 +97,12 @@ public void neighborsPacketLimited() { helper.sendMessageBetweenAgents(testAgent, agent, packet); // Check response packet - List incomingPackets = + final List incomingPackets = testAgent.getIncomingPackets().stream() .filter(p -> p.packet.getType().equals(PacketType.NEIGHBORS)) .collect(toList()); assertThat(incomingPackets.size()).isEqualTo(1); - IncomingPacket neighborsPacket = incomingPackets.get(0); + final IncomingPacket neighborsPacket = incomingPackets.get(0); assertThat(neighborsPacket.fromAgent).isEqualTo(agent); // Assert that we only received 16 items. @@ -128,12 +129,12 @@ public void shouldEvictPeerOnDisconnect() { final MockPeerDiscoveryAgent peerDiscoveryAgent2 = helper.startDiscoveryAgent(peer); peerDiscoveryAgent2.start(BROADCAST_TCP_PORT).join(); - assertThat(peerDiscoveryAgent2.getPeers().collect(toList()).size()).isEqualTo(1); + assertThat(peerDiscoveryAgent2.streamDiscoveredPeers().collect(toList()).size()).isEqualTo(1); final PeerConnection peerConnection = createAnonymousPeerConnection(peer.getId()); peerDiscoveryAgent2.onDisconnect(peerConnection, DisconnectReason.REQUESTED, true); - assertThat(peerDiscoveryAgent2.getPeers().collect(toList()).size()).isEqualTo(0); + assertThat(peerDiscoveryAgent2.streamDiscoveredPeers().collect(toList()).size()).isEqualTo(0); } @Test @@ -148,24 +149,24 @@ public void doesNotBlacklistPeerForNormalDisconnect() { // Bond to peer bondViaIncomingPing(agent, otherNode); - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); // Disconnect with innocuous reason blacklist.onDisconnect(wirePeer, DisconnectReason.TOO_MANY_PEERS, false); agent.onDisconnect(wirePeer, DisconnectReason.TOO_MANY_PEERS, false); // Confirm peer was removed - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); // Bond again bondViaIncomingPing(agent, otherNode); // Check peer was allowed to connect - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); } protected void bondViaIncomingPing( final MockPeerDiscoveryAgent agent, final MockPeerDiscoveryAgent otherNode) { - Packet pingPacket = helper.createPingPacket(otherNode, agent); + final Packet pingPacket = helper.createPingPacket(otherNode, agent); helper.sendMessageBetweenAgents(otherNode, agent, pingPacket); } @@ -181,19 +182,19 @@ public void blacklistPeerForBadBehavior() { // Bond to peer bondViaIncomingPing(agent, otherNode); - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); // Disconnect with problematic reason blacklist.onDisconnect(wirePeer, DisconnectReason.BREACH_OF_PROTOCOL, false); agent.onDisconnect(wirePeer, DisconnectReason.BREACH_OF_PROTOCOL, false); // Confirm peer was removed - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); // Bond again bondViaIncomingPing(agent, otherNode); // Check peer was not allowed to connect - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); } @Test @@ -208,19 +209,19 @@ public void doesNotBlacklistPeerForOurBadBehavior() throws Exception { // Bond to peer bondViaIncomingPing(agent, otherNode); - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); // Disconnect with problematic reason blacklist.onDisconnect(wirePeer, DisconnectReason.BREACH_OF_PROTOCOL, true); agent.onDisconnect(wirePeer, DisconnectReason.BREACH_OF_PROTOCOL, true); // Confirm peer was removed - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); // Bond again bondViaIncomingPing(agent, otherNode); // Check peer was allowed to connect - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); } @Test @@ -235,19 +236,19 @@ public void blacklistIncompatiblePeer() throws Exception { // Bond to peer bondViaIncomingPing(agent, otherNode); - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); // Disconnect blacklist.onDisconnect(wirePeer, DisconnectReason.INCOMPATIBLE_P2P_PROTOCOL_VERSION, false); agent.onDisconnect(wirePeer, DisconnectReason.INCOMPATIBLE_P2P_PROTOCOL_VERSION, false); // Confirm peer was removed - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); // Bond again bondViaIncomingPing(agent, otherNode); // Check peer was not allowed to connect - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); } @Test @@ -262,24 +263,24 @@ public void blacklistIncompatiblePeerWhoIssuesDisconnect() throws Exception { // Bond to peer bondViaIncomingPing(agent, otherNode); - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); // Disconnect blacklist.onDisconnect(wirePeer, DisconnectReason.INCOMPATIBLE_P2P_PROTOCOL_VERSION, true); agent.onDisconnect(wirePeer, DisconnectReason.INCOMPATIBLE_P2P_PROTOCOL_VERSION, true); // Confirm peer was removed - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); // Bond again bondViaIncomingPing(agent, otherNode); // Check peer was not allowed to connect - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); } @Test public void shouldBeActiveWhenConfigIsTrue() { - AgentBuilder agentBuilder = helper.agentBuilder().active(true); + final AgentBuilder agentBuilder = helper.agentBuilder().active(true); final MockPeerDiscoveryAgent agent = helper.startDiscoveryAgent(agentBuilder); assertThat(agent.isActive()).isTrue(); @@ -287,15 +288,15 @@ public void shouldBeActiveWhenConfigIsTrue() { @Test public void shouldNotBeActiveWhenConfigIsFalse() { - AgentBuilder agentBuilder = helper.agentBuilder().active(false); + final AgentBuilder agentBuilder = helper.agentBuilder().active(false); final MockPeerDiscoveryAgent agent = helper.startDiscoveryAgent(agentBuilder); assertThat(agent.isActive()).isFalse(); } private PeerConnection createAnonymousPeerConnection(final BytesValue id) { - PeerConnection conn = mock(PeerConnection.class); - PeerInfo peerInfo = new PeerInfo(0, null, null, 0, id); + final PeerConnection conn = mock(PeerConnection.class); + final PeerInfo peerInfo = new PeerInfo(0, null, null, 0, id); when(conn.getPeerInfo()).thenReturn(peerInfo); return conn; } diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBondingTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBondingTest.java index 67555dde81..6e458c0261 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBondingTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBondingTest.java @@ -53,8 +53,9 @@ public void pongSentUponPing() { assertThat(pong.getTo()).isEqualTo(otherAgent.getAdvertisedPeer().get().getEndpoint()); // The agent considers the test peer BONDED. - assertThat(agent.getPeers()).hasSize(1); - assertThat(agent.getPeers()).allMatch(p -> p.getStatus() == PeerDiscoveryStatus.BONDED); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()) + .allMatch(p -> p.getStatus() == PeerDiscoveryStatus.BONDED); } @Test @@ -67,7 +68,7 @@ public void neighborsPacketNotSentUnlessBonded() throws InterruptedException { // we haven't bonded. final MockPeerDiscoveryAgent otherNode = helper.startDiscoveryAgent(); final FindNeighborsPacketData data = FindNeighborsPacketData.create(otherNode.getId()); - Packet packet = Packet.create(PacketType.FIND_NEIGHBORS, data, otherNode.getKeyPair()); + final Packet packet = Packet.create(PacketType.FIND_NEIGHBORS, data, otherNode.getKeyPair()); helper.sendMessageBetweenAgents(otherNode, agent, packet); // No responses received @@ -84,7 +85,7 @@ public void neighborsPacketNotSentUnlessBonded() throws InterruptedException { .filter(p -> p.packet.getType().equals(PacketType.PONG)) .collect(Collectors.toList()); assertThat(incomingPongs.size()).isEqualTo(1); - Optional maybePongData = + final Optional maybePongData = incomingPongs.get(0).packet.getPacketData(PongPacketData.class); assertThat(maybePongData).isPresent(); assertThat(maybePongData.get().getTo()) diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBootstrappingTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBootstrappingTest.java index fc2b31e39a..a549991434 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBootstrappingTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryBootstrappingTest.java @@ -48,7 +48,7 @@ public void bootstrappingPingsSentSingleBootstrapPeer() { .filter(p -> p.packet.getType().equals(PacketType.PING)) .collect(toList()); assertThat(incomingPackets.size()).isEqualTo(1); - Packet pingPacket = incomingPackets.get(0).packet; + final Packet pingPacket = incomingPackets.get(0).packet; assertThat(pingPacket.getNodeId()).isEqualTo(agent.getAdvertisedPeer().get().getId()); final PingPacketData pingData = pingPacket.getPacketData(PingPacketData.class).get(); @@ -69,7 +69,7 @@ public void bootstrappingPingsSentMultipleBootstrapPeers() { .collect(toList()); // Start five agents. - List agents = helper.startDiscoveryAgents(5, bootstrapPeers); + final List agents = helper.startDiscoveryAgents(5, bootstrapPeers); // Assert that all test peers received a Find Neighbors packet. for (final MockPeerDiscoveryAgent bootstrapAgent : bootstrapAgents) { @@ -91,7 +91,7 @@ public void bootstrappingPingsSentMultipleBootstrapPeers() { assertThat(senderIds).containsExactlyInAnyOrderElementsOf(agentIds); // Traverse all received pings. - List pingPackets = + final List pingPackets = packets.stream().filter(p -> p.getType().equals(PacketType.PING)).collect(toList()); for (final Packet packet : pingPackets) { // Assert that the packet was a Find Neighbors one. @@ -118,11 +118,11 @@ public void bootstrappingPeersListUpdated() { final BytesValue[] otherPeersIds = otherAgents.stream().map(PeerDiscoveryAgent::getId).toArray(BytesValue[]::new); - assertThat(bootstrapAgent.getPeers()) + assertThat(bootstrapAgent.streamDiscoveredPeers()) .extracting(Peer::getId) .containsExactlyInAnyOrder(otherPeersIds); - assertThat(bootstrapAgent.getPeers()) + assertThat(bootstrapAgent.streamDiscoveredPeers()) .allMatch(p -> p.getStatus() == PeerDiscoveryStatus.BONDED); // This agent will bootstrap off the bootstrap peer, will add all nodes returned by the latter, @@ -130,6 +130,6 @@ public void bootstrappingPeersListUpdated() { // bond with them, ultimately adding all 7 nodes in the network to its table. final PeerDiscoveryAgent newAgent = helper.startDiscoveryAgent(bootstrapAgent.getAdvertisedPeer().get()); - assertThat(newAgent.getPeers()).hasSize(6); + assertThat(newAgent.streamDiscoveredPeers()).hasSize(6); } } diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryTimestampsTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryTimestampsTest.java index 0ce29d3458..cc845ff247 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryTimestampsTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryTimestampsTest.java @@ -49,8 +49,8 @@ public void lastSeenAndFirstDiscoveredTimestampsUpdatedOnMessage() { final MockPeerDiscoveryAgent agent = mock(MockPeerDiscoveryAgent.class); when(agent.getAdvertisedPeer()).thenReturn(Optional.of(peers.get(0))); - DiscoveryPeer localPeer = peers.get(0); - KeyPair localKeyPair = keypairs.get(0); + final DiscoveryPeer localPeer = peers.get(0); + final KeyPair localKeyPair = keypairs.get(0); final PeerDiscoveryController controller = new PeerDiscoveryController( @@ -79,9 +79,9 @@ public void lastSeenAndFirstDiscoveredTimestampsUpdatedOnMessage() { final AtomicLong lastSeen = new AtomicLong(); final AtomicLong firstDiscovered = new AtomicLong(); - assertThat(controller.getPeers()).hasSize(1); + assertThat(controller.streamDiscoveredPeers()).hasSize(1); - DiscoveryPeer p = controller.getPeers().iterator().next(); + DiscoveryPeer p = controller.streamDiscoveredPeers().iterator().next(); assertThat(p.getLastSeen()).isGreaterThan(0); assertThat(p.getFirstDiscovered()).isGreaterThan(0); @@ -90,9 +90,9 @@ public void lastSeenAndFirstDiscoveredTimestampsUpdatedOnMessage() { controller.onMessage(packet, peers.get(1)); - assertThat(controller.getPeers()).hasSize(1); + assertThat(controller.streamDiscoveredPeers()).hasSize(1); - p = controller.getPeers().iterator().next(); + p = controller.streamDiscoveredPeers().iterator().next(); assertThat(p.getLastSeen()).isGreaterThan(lastSeen.get()); assertThat(p.getFirstDiscovered()).isEqualTo(firstDiscovered.get()); } @@ -100,20 +100,20 @@ public void lastSeenAndFirstDiscoveredTimestampsUpdatedOnMessage() { @Test public void lastContactedTimestampUpdatedOnOutboundMessage() { final MockPeerDiscoveryAgent agent = helper.startDiscoveryAgent(Collections.emptyList()); - assertThat(agent.getPeers()).hasSize(0); + assertThat(agent.streamDiscoveredPeers()).hasSize(0); // Start a test peer and send a PING packet to the agent under test. final MockPeerDiscoveryAgent testAgent = helper.startDiscoveryAgent(); final Packet ping = helper.createPingPacket(testAgent, agent); helper.sendMessageBetweenAgents(testAgent, agent, ping); - assertThat(agent.getPeers()).hasSize(1); + assertThat(agent.streamDiscoveredPeers()).hasSize(1); final AtomicLong lastContacted = new AtomicLong(); final AtomicLong lastSeen = new AtomicLong(); final AtomicLong firstDiscovered = new AtomicLong(); - DiscoveryPeer peer = agent.getPeers().iterator().next(); + DiscoveryPeer peer = agent.streamDiscoveredPeers().iterator().next(); final long lc = peer.getLastContacted(); final long ls = peer.getLastSeen(); final long fd = peer.getFirstDiscovered(); @@ -129,7 +129,7 @@ public void lastContactedTimestampUpdatedOnOutboundMessage() { // Send another packet and ensure that timestamps are updated accordingly. helper.sendMessageBetweenAgents(testAgent, agent, ping); - peer = agent.getPeers().iterator().next(); + peer = agent.streamDiscoveredPeers().iterator().next(); assertThat(peer.getLastContacted()).isGreaterThan(lastContacted.get()); assertThat(peer.getLastSeen()).isGreaterThan(lastSeen.get()); diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/BucketTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/BucketTest.java index 8a2421fd3d..58fe9edfd3 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/BucketTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/BucketTest.java @@ -59,7 +59,7 @@ public void movedToHead() { kBucket.add(peer); } kBucket.getAndTouch(peers.get(0).getId()); - assertThat(kBucket.peers().indexOf(peers.get(0))).isEqualTo(0); + assertThat(kBucket.getPeers().indexOf(peers.get(0))).isEqualTo(0); } @Test @@ -70,7 +70,7 @@ public void evictPeer() { kBucket.add(p); } kBucket.evict(peers.get(4)); - assertFalse(kBucket.peers().contains(peers.get(4))); + assertFalse(kBucket.getPeers().contains(peers.get(4))); } @Test @@ -103,19 +103,19 @@ public void allActionsOnBucket() { // 16. assertThatThrownBy(() -> kBucket.add(peers.get(0))) .isInstanceOf(IllegalArgumentException.class); - assertThat(kBucket.peers()).hasSize(16); + assertThat(kBucket.getPeers()).hasSize(16); // Try to evict a peer that doesn't exist, and check the result is false. assertThat(kBucket.evict(peers.get(17))).isFalse(); - assertThat(kBucket.peers()).hasSize(16); + assertThat(kBucket.getPeers()).hasSize(16); // Evict a peer from head, another from the middle, and the tail. assertThat(kBucket.evict(peers.get(0))).isTrue(); - assertThat(kBucket.peers()).hasSize(15); + assertThat(kBucket.getPeers()).hasSize(15); assertThat(kBucket.evict(peers.get(7))).isTrue(); - assertThat(kBucket.peers()).hasSize(14); + assertThat(kBucket.getPeers()).hasSize(14); assertThat(kBucket.evict(peers.get(15))).isTrue(); - assertThat(kBucket.peers()).hasSize(13); + assertThat(kBucket.getPeers()).hasSize(13); // Check that we can now add peers again. assertThat(kBucket.add(peers.get(0))).isNotPresent(); @@ -127,7 +127,7 @@ public void allActionsOnBucket() { assertThat(kBucket.getAndTouch(peers.get(6).getId())).isPresent().get().isEqualTo(peers.get(6)); assertThat(kBucket.getAndTouch(peers.get(9).getId())).isPresent().get().isEqualTo(peers.get(9)); - assertThat(kBucket.peers()) + assertThat(kBucket.getPeers()) .containsSequence( peers.get(9), peers.get(6), diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java index 3366a5a493..c401156a5d 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java @@ -145,7 +145,7 @@ public void bootstrapPeersRetriesSent() { .send(eq(p), matchPacketOfType(PacketType.PING))); controller - .getPeers() + .streamDiscoveredPeers() .forEach(p -> assertThat(p.getStatus()).isEqualTo(PeerDiscoveryStatus.BONDING)); } @@ -283,7 +283,10 @@ public void bootstrapPeersPongReceived_HashMatched() { controller.start(); - assertThat(controller.getPeers().filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) + assertThat( + controller + .streamDiscoveredPeers() + .filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) .hasSize(3); // Simulate PONG messages from all peers @@ -307,9 +310,15 @@ public void bootstrapPeersPongReceived_HashMatched() { .send(eq(peers.get(i)), matchPacketOfType(PacketType.FIND_NEIGHBORS)); } - assertThat(controller.getPeers().filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) + assertThat( + controller + .streamDiscoveredPeers() + .filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) .hasSize(0); - assertThat(controller.getPeers().filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDED)) + assertThat( + controller + .streamDiscoveredPeers() + .filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDED)) .hasSize(3); } @@ -334,7 +343,10 @@ public void bootstrapPeersPongReceived_HashUnmatched() { controller.start(); - assertThat(controller.getPeers().filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) + assertThat( + controller + .streamDiscoveredPeers() + .filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) .hasSize(3); // Send a PONG packet from peer 1, with an incorrect hash. @@ -347,7 +359,10 @@ public void bootstrapPeersPongReceived_HashUnmatched() { verify(outboundMessageHandler, never()) .send(eq(peers.get(1)), matchPacketOfType(PacketType.FIND_NEIGHBORS)); - assertThat(controller.getPeers().filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) + assertThat( + controller + .streamDiscoveredPeers() + .filter(p -> p.getStatus() == PeerDiscoveryStatus.BONDING)) .hasSize(3); } @@ -399,8 +414,8 @@ public void findNeighborsSentAfterBondingFinished() { final FindNeighborsPacketData data = maybeData.get(); assertThat(data.getTarget()).isEqualTo(localPeer.getId()); - assertThat(controller.getPeers()).hasSize(1); - assertThat(controller.getPeers().findFirst().get().getStatus()) + assertThat(controller.streamDiscoveredPeers()).hasSize(1); + assertThat(controller.streamDiscoveredPeers().findFirst().get().getStatus()) .isEqualTo(PeerDiscoveryStatus.BONDED); } @@ -452,11 +467,11 @@ public void peerSeenTwice() throws InterruptedException { respondWithPong(peers.get(0), keyPairs.get(0), pingPacket.getHash()); // Assert that we're bonding with the third peer. - assertThat(controller.getPeers()).hasSize(2); - assertThat(controller.getPeers()) + assertThat(controller.streamDiscoveredPeers()).hasSize(2); + assertThat(controller.streamDiscoveredPeers()) .filteredOn(p -> p.getStatus() == PeerDiscoveryStatus.BONDING) .hasSize(1); - assertThat(controller.getPeers()) + assertThat(controller.streamDiscoveredPeers()) .filteredOn(p -> p.getStatus() == PeerDiscoveryStatus.BONDED) .hasSize(1); @@ -477,8 +492,8 @@ public void peerSeenTwice() throws InterruptedException { controller.onMessage(neighborsPacket0, peers.get(0)); // Assert that we're bonded with the third peer. - assertThat(controller.getPeers()).hasSize(2); - assertThat(controller.getPeers()) + assertThat(controller.streamDiscoveredPeers()).hasSize(2); + assertThat(controller.streamDiscoveredPeers()) .filteredOn(p -> p.getStatus() == PeerDiscoveryStatus.BONDED) .hasSize(2); @@ -500,7 +515,7 @@ public void peerSeenTwice() throws InterruptedException { controller.onMessage(pongPacket2, peers.get(2)); // Assert we're now bonded with peer[2]. - assertThat(controller.getPeers()) + assertThat(controller.streamDiscoveredPeers()) .filteredOn(p -> p.equals(peers.get(2)) && p.getStatus() == PeerDiscoveryStatus.BONDED) .hasSize(1); @@ -529,7 +544,7 @@ public void shouldAddNewPeerWhenReceivedPingAndPeerTableBucketIsNotFull() { final Packet pingPacket = mockPingPacket(peers.get(0), localPeer); controller.onMessage(pingPacket, peers.get(0)); - assertThat(controller.getPeers()).contains(peers.get(0)); + assertThat(controller.streamDiscoveredPeers()).contains(peers.get(0)); } @Test @@ -540,7 +555,7 @@ public void shouldNotAddSelfWhenReceivedPingFromSelf() { final Packet pingPacket = mockPingPacket(this.localPeer, this.localPeer); controller.onMessage(pingPacket, localPeer); - assertThat(controller.getPeers()).doesNotContain(localPeer); + assertThat(controller.streamDiscoveredPeers()).doesNotContain(localPeer); } @Test @@ -555,9 +570,9 @@ public void shouldAddNewPeerWhenReceivedPingAndPeerTableBucketIsFull() { final Packet pingPacket = mockPingPacket(peers.get(16), localPeer); controller.onMessage(pingPacket, peers.get(16)); - assertThat(controller.getPeers()).contains(peers.get(16)); + assertThat(controller.streamDiscoveredPeers()).contains(peers.get(16)); // The first peer added should have been evicted. - assertThat(controller.getPeers()).doesNotContain(peers.get(0)); + assertThat(controller.streamDiscoveredPeers()).doesNotContain(peers.get(0)); } @Test @@ -566,12 +581,12 @@ public void shouldNotRemoveExistingPeerWhenReceivedPing() { startPeerDiscoveryController(); peerTable.tryAdd(peers.get(0)); - assertThat(controller.getPeers()).contains(peers.get(0)); + assertThat(controller.streamDiscoveredPeers()).contains(peers.get(0)); final Packet pingPacket = mockPingPacket(peers.get(0), localPeer); controller.onMessage(pingPacket, peers.get(0)); - assertThat(controller.getPeers()).contains(peers.get(0)); + assertThat(controller.streamDiscoveredPeers()).contains(peers.get(0)); } @Test @@ -638,10 +653,10 @@ public void shouldNotAddNewPeerWhenReceivedPongFromBlacklistedPeer() { MockPacketDataFactory.mockPongPacket(otherPeer2, pingPacket2.getHash()); controller.onMessage(pongPacket2, otherPeer2); - assertThat(controller.getPeers()).hasSize(2); - assertThat(controller.getPeers()).contains(discoPeer); - assertThat(controller.getPeers()).contains(otherPeer); - assertThat(controller.getPeers()).doesNotContain(otherPeer2); + assertThat(controller.streamDiscoveredPeers()).hasSize(2); + assertThat(controller.streamDiscoveredPeers()).contains(discoPeer); + assertThat(controller.streamDiscoveredPeers()).contains(otherPeer); + assertThat(controller.streamDiscoveredPeers()).doesNotContain(otherPeer2); } private PacketData matchPingDataForPeer(final DiscoveryPeer peer) { @@ -864,7 +879,7 @@ public void shouldAddNewPeerWhenReceivedPongAndPeerTableBucketIsNotFull() { MockPacketDataFactory.mockPongPacket(peers.get(0), pingPacket.getHash()); controller.onMessage(pongPacket, peers.get(0)); - assertThat(controller.getPeers()).contains(peers.get(0)); + assertThat(controller.streamDiscoveredPeers()).contains(peers.get(0)); } @Test @@ -920,15 +935,15 @@ public void shouldAddNewPeerWhenReceivedPongAndPeerTableBucketIsFull() { MockPacketDataFactory.mockPongPacket(peers.get(16), pingPacket.getHash()); controller.onMessage(pongPacket16, peers.get(16)); - assertThat(controller.getPeers()).contains(peers.get(16)); - assertThat(controller.getPeers().collect(Collectors.toList())).hasSize(16); + assertThat(controller.streamDiscoveredPeers()).contains(peers.get(16)); + assertThat(controller.streamDiscoveredPeers().collect(Collectors.toList())).hasSize(16); assertThat(evictedPeerFromBucket(bootstrapPeers, controller)).isTrue(); } private boolean evictedPeerFromBucket( final List peers, final PeerDiscoveryController controller) { for (final DiscoveryPeer peer : peers) { - if (controller.getPeers().noneMatch(candidate -> candidate.equals(peer))) { + if (controller.streamDiscoveredPeers().noneMatch(candidate -> candidate.equals(peer))) { return true; } } @@ -964,7 +979,7 @@ public void shouldNotAddPeerInNeighborsPacketWithoutBonding() { verify(outboundMessageHandler, times(1)) .send(eq(peers.get(0)), matchPacketOfType(PacketType.FIND_NEIGHBORS)); - assertThat(controller.getPeers()).doesNotContain(peers.get(1)); + assertThat(controller.streamDiscoveredPeers()).doesNotContain(peers.get(1)); } @Test @@ -1047,7 +1062,7 @@ public void shouldNotRespondToPingFromNonWhitelistedDiscoveryPeer() { final Packet pingPacket = mockPingPacket(peers.get(0), localPeer); controller.onMessage(pingPacket, peers.get(0)); - assertThat(controller.getPeers()).doesNotContain(peers.get(0)); + assertThat(controller.streamDiscoveredPeers()).doesNotContain(peers.get(0)); } @Test @@ -1065,7 +1080,7 @@ public void whenPeerIsNotEvictedDropFromTableShouldReturnFalseAndNotifyZeroObser controller = getControllerBuilder().peerDroppedObservers(peerDroppedSubscribers).build(); controller.start(); - boolean dropped = controller.dropFromPeerTable(peer); + final boolean dropped = controller.dropFromPeerTable(peer); assertThat(dropped).isFalse(); verifyZeroInteractions(peerDroppedEventConsumer); diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryTableRefreshTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryTableRefreshTest.java index f14c8b70f5..7547c3d469 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryTableRefreshTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerDiscoveryTableRefreshTest.java @@ -46,8 +46,8 @@ public class PeerDiscoveryTableRefreshTest { public void tableRefreshSingleNode() { final List keypairs = PeerDiscoveryTestHelper.generateKeyPairs(2); final List peers = helper.createDiscoveryPeers(keypairs); - DiscoveryPeer localPeer = peers.get(0); - KeyPair localKeyPair = keypairs.get(0); + final DiscoveryPeer localPeer = peers.get(0); + final KeyPair localKeyPair = keypairs.get(0); // Create and start the PeerDiscoveryController final OutboundMessageHandler outboundMessageHandler = mock(OutboundMessageHandler.class); @@ -78,7 +78,7 @@ public void tableRefreshSingleNode() { controller.onMessage(pingPacket, peers.get(1)); // Wait until the controller has added the newly found peer. - assertThat(controller.getPeers()).hasSize(1); + assertThat(controller.streamDiscoveredPeers()).hasSize(1); // Simulate a PONG message from peer 0. final PongPacketData pongPacketData = @@ -92,7 +92,7 @@ public void tableRefreshSingleNode() { controller.getRecursivePeerRefreshState().cancel(); timer.runPeriodicHandlers(); - controller.getPeers().forEach(p -> p.setStatus(PeerDiscoveryStatus.KNOWN)); + controller.streamDiscoveredPeers().forEach(p -> p.setStatus(PeerDiscoveryStatus.KNOWN)); controller.onMessage(pingPacket, peers.get(1)); } verify(outboundMessageHandler, atLeast(5)).send(eq(peers.get(1)), captor.capture()); @@ -105,7 +105,7 @@ public void tableRefreshSingleNode() { // Collect targets from find neighbors packets final List targets = new ArrayList<>(); for (final Packet captured : capturedFindNeighborsPackets) { - Optional maybeData = + final Optional maybeData = captured.getPacketData(FindNeighborsPacketData.class); assertThat(maybeData).isPresent(); final FindNeighborsPacketData neighborsData = maybeData.get(); diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTableTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTableTest.java index d912888cba..9587770e88 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTableTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTableTest.java @@ -39,7 +39,7 @@ public void addPeer() { assertThat(result.getOutcome()).isEqualTo(AddOutcome.ADDED); } - assertThat(table.getAllPeers()).hasSize(5); + assertThat(table.streamAllPeers()).hasSize(5); } @Test @@ -55,7 +55,7 @@ public void addSelf() { final PeerTable.AddResult result = table.tryAdd(localPeer); assertThat(result.getOutcome()).isEqualTo(AddOutcome.SELF); - assertThat(table.getAllPeers()).hasSize(0); + assertThat(table.streamAllPeers()).hasSize(0); } @Test @@ -80,7 +80,7 @@ public void evictExistingPeerShouldEvict() { table.tryAdd(peer); - EvictResult evictResult = table.tryEvict(peer); + final EvictResult evictResult = table.tryEvict(peer); assertThat(evictResult.getOutcome()).isEqualTo(EvictOutcome.EVICTED); } @@ -89,7 +89,7 @@ public void evictPeerFromEmptyTableShouldNotEvict() { final PeerTable table = new PeerTable(Peer.randomId(), 16); final DiscoveryPeer peer = helper.createDiscoveryPeer(); - EvictResult evictResult = table.tryEvict(peer); + final EvictResult evictResult = table.tryEvict(peer); assertThat(evictResult.getOutcome()).isEqualTo(EvictOutcome.ABSENT); } @@ -100,7 +100,7 @@ public void evictAbsentPeerShouldNotEvict() { final List otherPeers = helper.createDiscoveryPeers(5); otherPeers.forEach(table::tryAdd); - EvictResult evictResult = table.tryEvict(peer); + final EvictResult evictResult = table.tryEvict(peer); assertThat(evictResult.getOutcome()).isEqualTo(EvictOutcome.ABSENT); } @@ -109,7 +109,7 @@ public void evictSelfPeerShouldReturnSelfOutcome() { final DiscoveryPeer peer = helper.createDiscoveryPeer(); final PeerTable table = new PeerTable(peer.getId(), 16); - EvictResult evictResult = table.tryEvict(peer); + final EvictResult evictResult = table.tryEvict(peer); assertThat(evictResult.getOutcome()).isEqualTo(EvictOutcome.SELF); } } diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetworkTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetworkTest.java index 4e309a1dee..bc7679a0bc 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetworkTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/DefaultP2PNetworkTest.java @@ -80,7 +80,7 @@ public final class DefaultP2PNetworkTest { @Mock private Blockchain blockchain; - private ArgumentCaptor observerCaptor = + private final ArgumentCaptor observerCaptor = ArgumentCaptor.forClass(BlockAddedObserver.class); private final Vertx vertx = Vertx.vertx(); @@ -312,7 +312,7 @@ public void removePeerReturnsFalseIfNotInMaintainedListButDisconnectsPeer() { final Peer remotePeer = mockPeer("127.0.0.2", 30302); final PeerConnection peerConnection = mockPeerConnection(remotePeer); - CompletableFuture future = network.connect(remotePeer); + final CompletableFuture future = network.connect(remotePeer); assertThat(network.peerMaintainConnectionList.contains(remotePeer)).isFalse(); assertThat(network.pendingConnections.containsKey(remotePeer)).isTrue(); @@ -343,10 +343,10 @@ public void afterStartingNetworkEnodeURLShouldBePresent() { @Test public void handlePeerBondedEvent_forPeerWithNoTcpPort() { final DefaultP2PNetwork network = mockNetwork(); - DiscoveryPeer peer = + final DiscoveryPeer peer = DiscoveryPeer.fromIdAndEndpoint( Peer.randomId(), new Endpoint("127.0.0.1", 999, OptionalInt.empty())); - PeerBondedEvent peerBondedEvent = new PeerBondedEvent(peer, System.currentTimeMillis()); + final PeerBondedEvent peerBondedEvent = new PeerBondedEvent(peer, System.currentTimeMillis()); network.handlePeerBondedEvent().accept(peerBondedEvent); verify(network, times(1)).connect(peer); @@ -362,8 +362,8 @@ public void attemptPeerConnections_connectsToValidPeer() { DiscoveryPeer peer = createDiscoveryPeer(); peer.setStatus(PeerDiscoveryStatus.BONDED); - doReturn(Stream.of(peer)).when(network).getDiscoveredPeers(); - ArgumentCaptor peerCapture = ArgumentCaptor.forClass(DiscoveryPeer.class); + doReturn(Stream.of(peer)).when(network).streamDiscoveredPeers(); + final ArgumentCaptor peerCapture = ArgumentCaptor.forClass(DiscoveryPeer.class); doReturn(CompletableFuture.completedFuture(mock(PeerConnection.class))) .when(network) .connect(peerCapture.capture()); @@ -383,7 +383,7 @@ public void attemptPeerConnections_ignoresUnbondedPeer() { DiscoveryPeer peer = createDiscoveryPeer(); peer.setStatus(PeerDiscoveryStatus.KNOWN); - doReturn(Stream.of(peer)).when(network).getDiscoveredPeers(); + doReturn(Stream.of(peer)).when(network).streamDiscoveredPeers(); network.attemptPeerConnections(); verify(network, times(0)).connect(any()); @@ -400,7 +400,7 @@ public void attemptPeerConnections_ignoresConnectingPeer() { peer.setStatus(PeerDiscoveryStatus.BONDED); doReturn(true).when(network).isConnecting(peer); - doReturn(Stream.of(peer)).when(network).getDiscoveredPeers(); + doReturn(Stream.of(peer)).when(network).streamDiscoveredPeers(); network.attemptPeerConnections(); verify(network, times(0)).connect(any()); @@ -417,7 +417,7 @@ public void attemptPeerConnections_ignoresConnectedPeer() { peer.setStatus(PeerDiscoveryStatus.BONDED); doReturn(true).when(network).isConnected(peer); - doReturn(Stream.of(peer)).when(network).getDiscoveredPeers(); + doReturn(Stream.of(peer)).when(network).streamDiscoveredPeers(); network.attemptPeerConnections(); verify(network, times(0)).connect(any()); @@ -430,7 +430,7 @@ public void attemptPeerConnections_withSlotsAvailable() { mockNetwork(() -> RlpxConfiguration.create().setMaxPeers(maxPeers)); doReturn(2).when(network).connectionCount(); - List peers = + final List peers = Stream.iterate(1, n -> n + 1) .limit(10) .map( @@ -441,8 +441,8 @@ public void attemptPeerConnections_withSlotsAvailable() { }) .collect(Collectors.toList()); - doReturn(peers.stream()).when(network).getDiscoveredPeers(); - ArgumentCaptor peerCapture = ArgumentCaptor.forClass(DiscoveryPeer.class); + doReturn(peers.stream()).when(network).streamDiscoveredPeers(); + final ArgumentCaptor peerCapture = ArgumentCaptor.forClass(DiscoveryPeer.class); doReturn(CompletableFuture.completedFuture(mock(PeerConnection.class))) .when(network) .connect(peerCapture.capture()); @@ -459,7 +459,7 @@ public void attemptPeerConnections_withNoSlotsAvailable() { mockNetwork(() -> RlpxConfiguration.create().setMaxPeers(maxPeers)); doReturn(maxPeers).when(network).connectionCount(); - List peers = + final List peers = Stream.iterate(1, n -> n + 1) .limit(10) .map( @@ -470,7 +470,7 @@ public void attemptPeerConnections_withNoSlotsAvailable() { }) .collect(Collectors.toList()); - lenient().doReturn(peers.stream()).when(network).getDiscoveredPeers(); + lenient().doReturn(peers.stream()).when(network).streamDiscoveredPeers(); network.attemptPeerConnections(); verify(network, times(0)).connect(any()); @@ -518,7 +518,7 @@ private DefaultP2PNetwork mockNetwork() { } private DefaultP2PNetwork mockNetwork(final Supplier rlpxConfig) { - DefaultP2PNetwork network = spy(network(rlpxConfig)); + final DefaultP2PNetwork network = spy(network(rlpxConfig)); lenient().doReturn(new CompletableFuture<>()).when(network).connect(any()); return network; } diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/NetworkingServiceLifecycleTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/NetworkingServiceLifecycleTest.java index ee0d3bc223..3ee08b803b 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/NetworkingServiceLifecycleTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/network/NetworkingServiceLifecycleTest.java @@ -59,7 +59,7 @@ public void createP2PNetwork() throws IOException { assertEquals(config.getDiscovery().getAdvertisedHost(), enode.getIpAsString()); assertThat(udpPort).isNotZero(); assertThat(tcpPort).isNotZero(); - assertThat(service.getDiscoveredPeers()).hasSize(0); + assertThat(service.streamDiscoveredPeers()).hasSize(0); } } @@ -146,7 +146,7 @@ public void startDiscoveryPortInUse() throws IOException { @Test public void createP2PNetwork_NoActivePeers() throws IOException { try (final P2PNetwork agent = builder().build()) { - assertTrue(agent.getDiscoveredPeers().collect(toList()).isEmpty()); + assertTrue(agent.streamDiscoveredPeers().collect(toList()).isEmpty()); assertEquals(0, agent.getPeers().size()); } } diff --git a/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/MetricsSystem.java b/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/MetricsSystem.java index 329c639d67..cdd5b70d7f 100644 --- a/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/MetricsSystem.java +++ b/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/MetricsSystem.java @@ -52,9 +52,9 @@ default void createLongGauge( createGauge(category, name, help, () -> (double) valueSupplier.get()); } - Stream getMetrics(MetricCategory category); + Stream streamObservations(MetricCategory category); - default Stream getMetrics() { - return Stream.of(MetricCategory.values()).flatMap(this::getMetrics); + default Stream streamObservations() { + return Stream.of(MetricCategory.values()).flatMap(this::streamObservations); } } diff --git a/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/noop/NoOpMetricsSystem.java b/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/noop/NoOpMetricsSystem.java index 5f2ad501f5..524ecf1fa1 100644 --- a/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/noop/NoOpMetricsSystem.java +++ b/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/noop/NoOpMetricsSystem.java @@ -88,12 +88,12 @@ public void createGauge( final Supplier valueSupplier) {} @Override - public Stream getMetrics(final MetricCategory category) { + public Stream streamObservations(final MetricCategory category) { return Stream.empty(); } @Override - public Stream getMetrics() { + public Stream streamObservations() { return Stream.empty(); } diff --git a/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystem.java b/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystem.java index 0348699965..c3b9ca84d5 100644 --- a/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystem.java +++ b/metrics/core/src/main/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystem.java @@ -160,7 +160,7 @@ private void addCollectorUnchecked(final MetricCategory category, final Collecto } @Override - public Stream getMetrics(final MetricCategory category) { + public Stream streamObservations(final MetricCategory category) { return collectors.getOrDefault(category, Collections.emptySet()).stream() .flatMap(collector -> collector.collect().stream()) .flatMap(familySamples -> convertSamplesToObservations(category, familySamples)); diff --git a/metrics/core/src/test/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystemTest.java b/metrics/core/src/test/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystemTest.java index d1ca2a6792..cf4f57c211 100644 --- a/metrics/core/src/test/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystemTest.java +++ b/metrics/core/src/test/java/tech/pegasys/pantheon/metrics/prometheus/PrometheusMetricsSystemTest.java @@ -50,11 +50,11 @@ public void shouldCreateObservationFromCounter() { final Counter counter = metricsSystem.createCounter(PEERS, "connected", "Some help string"); counter.inc(); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactly(new Observation(PEERS, "connected", 1d, emptyList())); counter.inc(); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactly(new Observation(PEERS, "connected", 2d, emptyList())); } @@ -67,11 +67,11 @@ public void shouldHandleDuplicateCounterCreation() { assertThat(counter1).isEqualTo(counter2); counter1.labels().inc(); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactly(new Observation(PEERS, "connected", 1d, emptyList())); counter2.labels().inc(); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactly(new Observation(PEERS, "connected", 2d, emptyList())); } @@ -84,7 +84,7 @@ public void shouldCreateSeparateObservationsForEachCounterLabelValue() { counter.labels("value2").inc(); counter.labels("value1").inc(); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactlyInAnyOrder( new Observation(PEERS, "connected", 2d, singletonList("value1")), new Observation(PEERS, "connected", 1d, singletonList("value2"))); @@ -95,11 +95,11 @@ public void shouldIncrementCounterBySpecifiedAmount() { final Counter counter = metricsSystem.createCounter(PEERS, "connected", "Some help string"); counter.inc(5); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactly(new Observation(PEERS, "connected", 5d, emptyList())); counter.inc(6); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactly(new Observation(PEERS, "connected", 11d, emptyList())); } @@ -110,7 +110,7 @@ public void shouldCreateObservationsFromTimer() { final TimingContext context = timer.startTimer(); context.stopTimer(); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .usingElementComparator(IGNORE_VALUES) .containsExactlyInAnyOrder( new Observation(RPC, "request", null, asList("quantile", "0.2")), @@ -140,7 +140,7 @@ public void shouldCreateObservationsFromTimerWithLabels() { //noinspection EmptyTryBlock try (final TimingContext ignored = timer.labels("method").startTimer()) {} - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .usingElementComparator(IGNORE_VALUES) // We don't know how long it will actually take. .containsExactlyInAnyOrder( new Observation(RPC, "request", null, asList("method", "quantile", "0.2")), @@ -157,7 +157,7 @@ public void shouldCreateObservationsFromTimerWithLabels() { public void shouldCreateObservationFromGauge() { metricsSystem.createGauge(JVM, "myValue", "Help", () -> 7d); - assertThat(metricsSystem.getMetrics()) + assertThat(metricsSystem.streamObservations()) .containsExactlyInAnyOrder(new Observation(JVM, "myValue", 7d, emptyList())); } @@ -184,7 +184,7 @@ public void shouldOnlyObserveEnabledMetrics() { assertThat(counterN).isSameAs(NoOpMetricsSystem.NO_OP_LABELLED_1_COUNTER); counterN.labels("show").inc(); - assertThat(localMetricSystem.getMetrics()).isEmpty(); + assertThat(localMetricSystem.streamObservations()).isEmpty(); // do a category we are watching final LabelledMetric counterR = @@ -192,7 +192,7 @@ public void shouldOnlyObserveEnabledMetrics() { assertThat(counterR).isNotSameAs(NoOpMetricsSystem.NO_OP_LABELLED_1_COUNTER); counterR.labels("op").inc(); - assertThat(localMetricSystem.getMetrics()) + assertThat(localMetricSystem.streamObservations()) .containsExactly(new Observation(RPC, "name", 1.0, singletonList("op"))); }