Migrate some OptionalInt's to Optional<Integer>s (#1242)

Signed-off-by: Ratan Rai Sur <ratan.r.sur@gmail.com>
pull/1250/head
Ratan (Rai) Sur 4 years ago committed by GitHub
parent b939b98898
commit c231d0e704
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 18
      besu/src/main/java/org/hyperledger/besu/Runner.java
  2. 2
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/NetServices.java
  3. 30
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/Endpoint.java
  4. 9
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryAgent.java
  5. 4
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/VertxPeerDiscoveryAgent.java
  6. 77
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURL.java
  7. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/netty/NettyConnectionInitializer.java
  8. 4
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PacketTest.java
  9. 20
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerTableTest.java
  10. 22
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PingPacketDataTest.java
  11. 8
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PongPacketDataTest.java
  12. 3
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/DefaultP2PNetworkTest.java
  13. 12
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/P2PNetworkTest.java
  14. 52
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURLTest.java
  15. 21
      util/src/main/java/org/hyperledger/besu/util/IllegalPortException.java
  16. 8
      util/src/main/java/org/hyperledger/besu/util/NetworkUtility.java

@ -215,14 +215,16 @@ public class Runner implements AutoCloseable {
.getLocalEnode()
.ifPresent(
enode -> {
if (enode.getDiscoveryPort().isPresent()) {
properties.setProperty(
"discovery", String.valueOf(enode.getDiscoveryPort().getAsInt()));
}
if (enode.getListeningPort().isPresent()) {
properties.setProperty(
"p2p", String.valueOf(enode.getListeningPort().getAsInt()));
}
enode
.getDiscoveryPort()
.ifPresent(
discoveryPort ->
properties.setProperty("discovery", String.valueOf(discoveryPort)));
enode
.getListeningPort()
.ifPresent(
listeningPort ->
properties.setProperty("p2p", String.valueOf(listeningPort)));
});
}

@ -74,7 +74,7 @@ public class NetServices implements JsonRpcMethod {
servicesMapBuilder.put(
"p2p",
createServiceDetailsMap(
enode.getIpAsString(), enode.getListeningPort().getAsInt())));
enode.getIpAsString(), enode.getListeningPort().get())));
}
if (metricsConfiguration.isEnabled()) {
servicesMapBuilder.put(

@ -15,17 +15,17 @@
package org.hyperledger.besu.ethereum.p2p.discovery;
import static com.google.common.base.Preconditions.checkArgument;
import static org.hyperledger.besu.util.NetworkUtility.checkPort;
import static org.hyperledger.besu.util.Preconditions.checkGuard;
import org.hyperledger.besu.ethereum.p2p.peers.EnodeURL;
import org.hyperledger.besu.ethereum.rlp.RLPInput;
import org.hyperledger.besu.ethereum.rlp.RLPOutput;
import org.hyperledger.besu.util.NetworkUtility;
import org.hyperledger.besu.util.IllegalPortException;
import java.net.InetAddress;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import com.google.common.net.InetAddresses;
import org.apache.tuweni.bytes.Bytes;
@ -37,23 +37,9 @@ import org.apache.tuweni.bytes.Bytes;
public class Endpoint {
private final String host;
private final int udpPort;
private final OptionalInt tcpPort;
private final Optional<Integer> tcpPort;
private static class IllegalPortException extends IllegalArgumentException {
IllegalPortException(final String message) {
super(message);
}
}
private static void checkPort(final int port, final String portTypeName) {
if (!NetworkUtility.isValidPort(port)) {
throw new IllegalPortException(
String.format(
"%s port requires a value between 1 and 65535. Got %d.", portTypeName, port));
}
}
public Endpoint(final String host, final int udpPort, final OptionalInt tcpPort) {
public Endpoint(final String host, final int udpPort, final Optional<Integer> tcpPort) {
checkArgument(
host != null && InetAddresses.isInetAddress(host), "host requires a valid IP address");
checkPort(udpPort, "UDP");
@ -72,7 +58,7 @@ public class Endpoint {
() ->
new IllegalArgumentException(
"Attempt to create a discovery endpoint for an enode with discovery disabled."));
final OptionalInt listeningPort = enode.getListeningPort();
final Optional<Integer> listeningPort = enode.getListeningPort();
return new Endpoint(enode.getIp().getHostAddress(), discoveryPort, listeningPort);
}
@ -93,7 +79,7 @@ public class Endpoint {
return udpPort;
}
public OptionalInt getTcpPort() {
public Optional<Integer> getTcpPort() {
return tcpPort;
}
@ -182,12 +168,12 @@ public class Endpoint {
// Some mainnet packets have been shown to either not have the TCP port field at all,
// or to have an RLP NULL value for it.
OptionalInt tcpPort = OptionalInt.empty();
Optional<Integer> tcpPort = Optional.empty();
if (fieldCount == 3) {
if (in.nextIsNull()) {
in.skipNext();
} else {
tcpPort = OptionalInt.of(in.readIntScalar());
tcpPort = Optional.of(in.readIntScalar());
}
}
return new Endpoint(addr.getHostAddress(), udpPort, tcpPort);

@ -38,7 +38,6 @@ import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
@ -187,13 +186,7 @@ public abstract class PeerDiscoveryAgent {
packet
.getPacketData(PingPacketData.class)
.flatMap(PingPacketData::getFrom)
.flatMap(
fromEndpoint -> {
final OptionalInt maybePort = fromEndpoint.getTcpPort();
return maybePort.isPresent()
? Optional.of(maybePort.getAsInt())
: Optional.empty();
})
.flatMap(Endpoint::getTcpPort)
.orElse(udpPort);
// Notify the peer controller.

@ -33,7 +33,7 @@ import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.OptionalInt;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
@ -216,7 +216,7 @@ public class VertxPeerDiscoveryAgent extends PeerDiscoveryAgent {
// Acquire the senders coordinates to build a Peer representation from them.
final String host = datagram.sender().host();
final int port = datagram.sender().port();
final Endpoint endpoint = new Endpoint(host, port, OptionalInt.empty());
final Endpoint endpoint = new Endpoint(host, port, Optional.empty());
handleIncomingPacket(endpoint, event.result());
} else {
if (event.cause() instanceof PeerDiscoveryPacketDecodingException) {

@ -22,6 +22,7 @@ import org.hyperledger.besu.util.NetworkUtility;
import java.net.InetAddress;
import java.net.URI;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -40,22 +41,18 @@ public class EnodeURL {
private final Bytes nodeId;
private final InetAddress ip;
private final OptionalInt listeningPort;
private final OptionalInt discoveryPort;
private final Optional<Integer> listeningPort;
private final Optional<Integer> discoveryPort;
private EnodeURL(
final Bytes nodeId,
final InetAddress address,
final OptionalInt listeningPort,
final OptionalInt discoveryPort) {
final Optional<Integer> listeningPort,
final Optional<Integer> discoveryPort) {
checkArgument(
nodeId.size() == NODE_ID_SIZE, "Invalid node id. Expected id of length: 64 bytes.");
checkArgument(
!listeningPort.isPresent() || NetworkUtility.isValidPort(listeningPort.getAsInt()),
"Invalid listening port. Port should be between 1 - 65535.");
checkArgument(
!discoveryPort.isPresent() || NetworkUtility.isValidPort(discoveryPort.getAsInt()),
"Invalid discovery port. Port should be between 1 - 65535.");
listeningPort.ifPresent(port -> NetworkUtility.checkPort(port, "listening"));
discoveryPort.ifPresent(port -> NetworkUtility.checkPort(port, "discovery"));
this.nodeId = nodeId;
this.ip = address;
@ -98,17 +95,16 @@ public class EnodeURL {
int tcpPort = uri.getPort();
// Parse discport if it exists
OptionalInt discoveryPort = OptionalInt.empty();
Optional<Integer> discoveryPort = Optional.empty();
String query = uri.getQuery();
if (query != null) {
final Matcher discPortMatcher = DISCPORT_QUERY_STRING_REGEX.matcher(query);
if (discPortMatcher.matches()) {
Integer discPort = Ints.tryParse(discPortMatcher.group(1));
discoveryPort = discPort == null ? discoveryPort : OptionalInt.of(discPort);
discoveryPort = Optional.ofNullable(Ints.tryParse(discPortMatcher.group(1)));
}
checkArgument(discoveryPort.isPresent(), "Invalid discovery port: '" + query + "'.");
} else {
discoveryPort = OptionalInt.of(tcpPort);
discoveryPort = Optional.of(tcpPort);
}
return builder()
@ -208,7 +204,7 @@ public class EnodeURL {
return discoveryPort.isPresent();
}
public OptionalInt getListeningPort() {
public Optional<Integer> getListeningPort() {
return listeningPort;
}
@ -216,7 +212,7 @@ public class EnodeURL {
return listeningPort.orElse(0);
}
public OptionalInt getDiscoveryPort() {
public Optional<Integer> getDiscoveryPort() {
return discoveryPort;
}
@ -252,11 +248,11 @@ public class EnodeURL {
public static class Builder {
private Bytes nodeId;
private OptionalInt listeningPort;
private OptionalInt discoveryPort;
private Optional<Integer> listeningPort;
private Optional<Integer> discoveryPort;
private InetAddress ip;
private Builder() {};
private Builder() {}
public EnodeURL build() {
validate();
@ -315,12 +311,12 @@ public class EnodeURL {
}
public Builder disableListening() {
this.listeningPort = OptionalInt.empty();
this.listeningPort = Optional.empty();
return this;
}
public Builder disableDiscovery() {
this.discoveryPort = OptionalInt.empty();
this.discoveryPort = Optional.empty();
return this;
}
@ -333,16 +329,12 @@ public class EnodeURL {
* An optional listening port value. If the value is empty of equal to 0, the listening port
* will be empty - indicating the corresponding node is not listening.
*
* @param listeningPort If non-empty represents the port to listen on, if empty means the node
* is not listening
* @param maybeListeningPort If non-empty represents the port to listen on, if empty means the
* node is not listening
* @return The modified builder
*/
public Builder listeningPort(final OptionalInt listeningPort) {
if (listeningPort.isPresent() && listeningPort.getAsInt() == 0) {
this.listeningPort = OptionalInt.empty();
} else {
this.listeningPort = listeningPort;
}
public Builder listeningPort(final Optional<Integer> maybeListeningPort) {
this.listeningPort = maybeListeningPort.filter(port -> port != 0);
return this;
}
@ -354,29 +346,19 @@ public class EnodeURL {
* @return The modified builder
*/
public Builder listeningPort(final int listeningPort) {
if (listeningPort == 0) {
this.listeningPort = OptionalInt.empty();
} else {
this.listeningPort = OptionalInt.of(listeningPort);
}
return this;
return listeningPort(Optional.of(listeningPort));
}
/**
* The port on which to listen for discovery messages. A value that is empty or equal to 0,
* indicates that the node is not listening for discovery messages.
*
* @param discoveryPort If non-empty and non-zero, represents the port on which to listen for
* discovery messages. Otherwise, indicates that the node is not running discovery.
* @param maybeDiscoveryPort If non-empty and non-zero, represents the port on which to listen
* for discovery messages. Otherwise, indicates that the node is not running discovery.
* @return The modified builder
*/
public Builder discoveryPort(final OptionalInt discoveryPort) {
if (discoveryPort.isPresent() && discoveryPort.getAsInt() == 0) {
this.discoveryPort = OptionalInt.empty();
} else {
this.discoveryPort = discoveryPort;
}
public Builder discoveryPort(final Optional<Integer> maybeDiscoveryPort) {
this.discoveryPort = maybeDiscoveryPort.filter(port -> port != 0);
return this;
}
@ -389,12 +371,7 @@ public class EnodeURL {
* @return The modified builder
*/
public Builder discoveryPort(final int discoveryPort) {
if (discoveryPort == 0) {
this.discoveryPort = OptionalInt.empty();
} else {
this.discoveryPort = OptionalInt.of(discoveryPort);
}
return this;
return discoveryPort(Optional.of(discoveryPort));
}
}
}

@ -167,7 +167,7 @@ public class NettyConnectionInitializer implements ConnectionInitializer {
new Bootstrap()
.group(workers)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(enode.getIp(), enode.getListeningPort().getAsInt()))
.remoteAddress(new InetSocketAddress(enode.getIp(), enode.getListeningPort().get()))
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_SECONDS * 1000)
.handler(

@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.p2p.discovery.Endpoint;
import java.util.OptionalInt;
import java.util.Optional;
import io.vertx.core.buffer.Buffer;
import org.apache.tuweni.bytes.Bytes;
@ -37,7 +37,7 @@ public class PacketTest {
assertThat(packet.getType()).isSameAs(PacketType.PONG);
assertThat(packetData.getTo())
.isEqualTo(new Endpoint("180.181.122.26", 1025, OptionalInt.of(30303)));
.isEqualTo(new Endpoint("180.181.122.26", 1025, Optional.of(30303)));
assertThat(packetData.getPingHash())
.isEqualTo(
Bytes.fromHexString(

@ -27,7 +27,7 @@ import org.hyperledger.besu.ethereum.p2p.peers.EnodeURL;
import org.hyperledger.besu.ethereum.p2p.peers.Peer;
import java.util.List;
import java.util.OptionalInt;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
@ -84,14 +84,12 @@ public class PeerTableTest {
final PeerTable table = new PeerTable(Peer.randomId(), 16);
final Bytes peerId = KeyPair.generate().getPublicKey().getEncodedBytes();
final DiscoveryPeer peer =
DiscoveryPeer.fromIdAndEndpoint(
peerId, new Endpoint("1.1.1.1", 30303, OptionalInt.empty()));
DiscoveryPeer.fromIdAndEndpoint(peerId, new Endpoint("1.1.1.1", 30303, Optional.empty()));
assertThat(table.tryAdd(peer).getOutcome()).isEqualTo(AddOutcome.ADDED);
final DiscoveryPeer duplicatePeer =
DiscoveryPeer.fromIdAndEndpoint(
peerId, new Endpoint("1.1.1.2", 30303, OptionalInt.empty()));
DiscoveryPeer.fromIdAndEndpoint(peerId, new Endpoint("1.1.1.2", 30303, Optional.empty()));
assertThat(table.tryAdd(duplicatePeer))
.satisfies(
result -> {
@ -105,14 +103,12 @@ public class PeerTableTest {
final PeerTable table = new PeerTable(Peer.randomId(), 16);
final Bytes peerId = KeyPair.generate().getPublicKey().getEncodedBytes();
final DiscoveryPeer peer =
DiscoveryPeer.fromIdAndEndpoint(
peerId, new Endpoint("1.1.1.1", 30303, OptionalInt.empty()));
DiscoveryPeer.fromIdAndEndpoint(peerId, new Endpoint("1.1.1.1", 30303, Optional.empty()));
assertThat(table.tryAdd(peer).getOutcome()).isEqualTo(AddOutcome.ADDED);
final DiscoveryPeer duplicatePeer =
DiscoveryPeer.fromIdAndEndpoint(
peerId, new Endpoint("1.1.1.1", 30301, OptionalInt.empty()));
DiscoveryPeer.fromIdAndEndpoint(peerId, new Endpoint("1.1.1.1", 30301, Optional.empty()));
assertThat(table.tryAdd(duplicatePeer))
.satisfies(
result -> {
@ -126,14 +122,12 @@ public class PeerTableTest {
final PeerTable table = new PeerTable(Peer.randomId(), 16);
final Bytes peerId = KeyPair.generate().getPublicKey().getEncodedBytes();
final DiscoveryPeer peer =
DiscoveryPeer.fromIdAndEndpoint(
peerId, new Endpoint("1.1.1.1", 30303, OptionalInt.empty()));
DiscoveryPeer.fromIdAndEndpoint(peerId, new Endpoint("1.1.1.1", 30303, Optional.empty()));
assertThat(table.tryAdd(peer).getOutcome()).isEqualTo(AddOutcome.ADDED);
final DiscoveryPeer duplicatePeer =
DiscoveryPeer.fromIdAndEndpoint(
peerId, new Endpoint("1.1.1.2", 30301, OptionalInt.empty()));
DiscoveryPeer.fromIdAndEndpoint(peerId, new Endpoint("1.1.1.2", 30301, Optional.empty()));
assertThat(table.tryAdd(duplicatePeer))
.satisfies(
result -> {

@ -21,7 +21,7 @@ import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput;
import org.hyperledger.besu.ethereum.rlp.RLP;
import java.time.Instant;
import java.util.OptionalInt;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
@ -32,8 +32,8 @@ public class PingPacketDataTest {
public void serializeDeserialize() {
final long currentTimeSec = Instant.now().getEpochSecond();
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 Endpoint from = new Endpoint("127.0.0.1", 30303, Optional.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final PingPacketData packet = PingPacketData.create(from, to);
final Bytes serialized = RLP.encode(packet::writeTo);
final PingPacketData deserialized = PingPacketData.readFrom(RLP.input(serialized));
@ -46,8 +46,8 @@ public class PingPacketDataTest {
@Test
public void readFrom() {
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 Endpoint from = new Endpoint("127.0.0.1", 30303, Optional.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
@ -69,8 +69,8 @@ public class PingPacketDataTest {
@Test
public void readFrom_withExtraFields() {
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 Endpoint from = new Endpoint("127.0.0.1", 30303, Optional.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
@ -94,8 +94,8 @@ public class PingPacketDataTest {
@Test
public void readFrom_unknownVersion() {
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 Endpoint from = new Endpoint("127.0.0.1", 30303, Optional.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
@ -117,8 +117,8 @@ public class PingPacketDataTest {
@Test
public void readFrom_lowPortValues() {
final int version = 4;
final Endpoint from = new Endpoint("0.1.2.1", 1, OptionalInt.of(1));
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Endpoint from = new Endpoint("0.1.2.1", 1, Optional.of(1));
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();

@ -21,7 +21,7 @@ import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput;
import org.hyperledger.besu.ethereum.rlp.RLP;
import java.time.Instant;
import java.util.OptionalInt;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
@ -32,7 +32,7 @@ public class PongPacketDataTest {
@Test
public void serializeDeserialize() {
final long currentTimeSec = Instant.now().getEpochSecond();
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final Bytes32 hash = Bytes32.fromHexStringLenient("0x1234");
final PongPacketData packet = PongPacketData.create(to, hash);
@ -47,7 +47,7 @@ public class PongPacketDataTest {
@Test
public void readFrom() {
final long time = System.currentTimeMillis();
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final Bytes32 hash = Bytes32.fromHexStringLenient("0x1234");
BytesValueRLPOutput out = new BytesValueRLPOutput();
@ -67,7 +67,7 @@ public class PongPacketDataTest {
@Test
public void readFrom_withExtraFields() {
final long time = System.currentTimeMillis();
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final Endpoint to = new Endpoint("127.0.0.2", 30303, Optional.empty());
final Bytes32 hash = Bytes32.fromHexStringLenient("0x1234");
BytesValueRLPOutput out = new BytesValueRLPOutput();

@ -53,7 +53,6 @@ import org.hyperledger.besu.nat.upnp.UpnpNatManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -257,7 +256,7 @@ public final class DefaultP2PNetworkTest {
network.start();
final DiscoveryPeer peer =
DiscoveryPeer.fromIdAndEndpoint(
Peer.randomId(), new Endpoint("127.0.0.1", 999, OptionalInt.empty()));
Peer.randomId(), new Endpoint("127.0.0.1", 999, Optional.empty()));
final PeerDiscoveryEvent.PeerBondedEvent peerBondedEvent =
new PeerDiscoveryEvent.PeerBondedEvent(peer, System.currentTimeMillis());

@ -74,7 +74,7 @@ public class P2PNetworkTest {
connector.start();
final EnodeURL listenerEnode = listener.getLocalEnode().get();
final Bytes listenId = listenerEnode.getNodeId();
final int listenPort = listenerEnode.getListeningPort().getAsInt();
final int listenPort = listenerEnode.getListeningPort().get();
Assertions.assertThat(
connector
@ -96,7 +96,7 @@ public class P2PNetworkTest {
connector.start();
final EnodeURL listenerEnode = listener.getLocalEnode().get();
final Bytes listenId = listenerEnode.getNodeId();
final int listenPort = listenerEnode.getListeningPort().getAsInt();
final int listenPort = listenerEnode.getListeningPort().get();
final CompletableFuture<PeerConnection> firstFuture =
connector.connect(createPeer(listenId, listenPort));
@ -140,7 +140,7 @@ public class P2PNetworkTest {
connector1.start();
final EnodeURL listenerEnode = listener.getLocalEnode().get();
final Bytes listenId = listenerEnode.getNodeId();
final int listenPort = listenerEnode.getListeningPort().getAsInt();
final int listenPort = listenerEnode.getListeningPort().get();
final Peer listeningPeer = createPeer(listenId, listenPort);
Assertions.assertThat(
@ -191,7 +191,7 @@ public class P2PNetworkTest {
connector.start();
final EnodeURL listenerEnode = listener.getLocalEnode().get();
final Bytes listenId = listenerEnode.getNodeId();
final int listenPort = listenerEnode.getListeningPort().getAsInt();
final int listenPort = listenerEnode.getListeningPort().get();
final Peer listenerPeer = createPeer(listenId, listenPort);
final CompletableFuture<PeerConnection> connectFuture = connector.connect(listenerPeer);
@ -211,11 +211,11 @@ public class P2PNetworkTest {
final EnodeURL localEnode = localNetwork.getLocalEnode().get();
final Bytes localId = localEnode.getNodeId();
final int localPort = localEnode.getListeningPort().getAsInt();
final int localPort = localEnode.getListeningPort().get();
final EnodeURL remoteEnode = remoteNetwork.getLocalEnode().get();
final Bytes remoteId = remoteEnode.getNodeId();
final int remotePort = remoteEnode.getListeningPort().getAsInt();
final int remotePort = remoteEnode.getListeningPort().get();
final Peer localPeer = createPeer(localId, localPort);
final Peer remotePeer = createPeer(remoteId, remotePort);

@ -15,13 +15,18 @@
package org.hyperledger.besu.ethereum.p2p.peers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.hyperledger.besu.util.IllegalPortException;
import java.net.URI;
import java.util.OptionalInt;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.tuweni.bytes.Bytes;
import org.assertj.core.api.ThrowableAssert;
import org.junit.Test;
public class EnodeURLTest {
@ -42,7 +47,7 @@ public class EnodeURLTest {
.nodeId(VALID_NODE_ID)
.ipAddress(IPV4_ADDRESS)
.listeningPort(P2P_PORT)
.discoveryPort(OptionalInt.of(P2P_PORT))
.discoveryPort(Optional.of(P2P_PORT))
.build();
assertThat(enode.getListeningPortOrZero()).isEqualTo(P2P_PORT);
assertThat(enode.getDiscoveryPortOrZero()).isEqualTo(P2P_PORT);
@ -55,7 +60,7 @@ public class EnodeURLTest {
.nodeId(VALID_NODE_ID)
.ipAddress(IPV4_ADDRESS)
.listeningPort(P2P_PORT)
.discoveryPort(OptionalInt.of(DISCOVERY_PORT))
.discoveryPort(Optional.of(DISCOVERY_PORT))
.build();
assertThat(enode.getListeningPortOrZero()).isEqualTo(P2P_PORT);
assertThat(enode.getDiscoveryPortOrZero()).isEqualTo(DISCOVERY_PORT);
@ -68,7 +73,7 @@ public class EnodeURLTest {
.nodeId(VALID_NODE_ID)
.ipAddress(IPV4_ADDRESS)
.listeningPort(P2P_PORT)
.discoveryPort(OptionalInt.of(DISCOVERY_PORT))
.discoveryPort(Optional.of(DISCOVERY_PORT))
.build();
final String enodeURLString =
"enode://" + VALID_NODE_ID + "@" + IPV4_ADDRESS + ":" + P2P_PORT + "?" + DISCOVERY_QUERY;
@ -102,7 +107,7 @@ public class EnodeURLTest {
.nodeId(VALID_NODE_ID)
.ipAddress(IPV6_FULL_ADDRESS)
.listeningPort(P2P_PORT)
.discoveryPort(OptionalInt.of(DISCOVERY_PORT))
.discoveryPort(Optional.of(DISCOVERY_PORT))
.build();
final String enodeURLString =
"enode://"
@ -126,7 +131,7 @@ public class EnodeURLTest {
.nodeId(VALID_NODE_ID)
.ipAddress(IPV6_COMPACT_ADDRESS)
.listeningPort(P2P_PORT)
.discoveryPort(OptionalInt.of(DISCOVERY_PORT))
.discoveryPort(Optional.of(DISCOVERY_PORT))
.build();
final String enodeURLString =
"enode://"
@ -153,7 +158,7 @@ public class EnodeURLTest {
EnodeURL enodeURL = EnodeURL.fromString(enodeURLString);
assertThat(enodeURL.getNodeId().toUnprefixedHexString()).isEqualTo(VALID_NODE_ID);
assertThat("[" + enodeURL.getIpAsString() + "]").isEqualTo(IPV6_FULL_ADDRESS);
assertThat(enodeURL.getListeningPort()).isEqualTo(OptionalInt.of(P2P_PORT));
assertThat(enodeURL.getListeningPort()).isEqualTo(Optional.of(P2P_PORT));
assertThat(enodeURL.getDiscoveryPortOrZero()).isEqualTo(0);
assertThat(enodeURL.isListening()).isTrue();
assertThat(enodeURL.isRunningDiscovery()).isFalse();
@ -250,9 +255,7 @@ public class EnodeURLTest {
final String enodeURLString = "enode://" + VALID_NODE_ID + "@" + IPV4_ADDRESS + ":";
final Throwable thrown = catchThrowable(() -> EnodeURL.fromString(enodeURLString));
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid listening port.");
assertThat(thrown).hasCauseInstanceOf(IllegalPortException.class);
}
@Test
@ -261,9 +264,7 @@ public class EnodeURLTest {
"enode://" + VALID_NODE_ID + "@" + IPV4_ADDRESS + ":?discport=30301";
final Throwable thrown = catchThrowable(() -> EnodeURL.fromString(enodeURLString));
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid listening port.");
assertThat(thrown).hasCauseInstanceOf(IllegalPortException.class);
}
@Test
@ -271,9 +272,7 @@ public class EnodeURLTest {
final String enodeURLString = "enode://" + VALID_NODE_ID + "@" + IPV4_ADDRESS + ":98765";
final Throwable thrown = catchThrowable(() -> EnodeURL.fromString(enodeURLString));
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid listening port.");
assertThat(thrown).hasCauseInstanceOf(IllegalPortException.class);
}
@Test
@ -282,9 +281,7 @@ public class EnodeURLTest {
"enode://" + VALID_NODE_ID + "@" + IPV4_ADDRESS + ":" + P2P_PORT + "?discport=98765";
final Throwable thrown = catchThrowable(() -> EnodeURL.fromString(enodeURLString));
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid discovery port.");
assertThat(thrown).hasCauseInstanceOf(IllegalPortException.class);
}
@Test
@ -398,6 +395,19 @@ public class EnodeURLTest {
assertThat(createdURI).isEqualTo(expectedURI);
}
@Test
public void builder_setInvalidPorts() {
final EnodeURL.Builder validBuilder =
EnodeURL.builder().nodeId(VALID_NODE_ID).ipAddress(IPV4_ADDRESS);
Stream.<ThrowableAssert.ThrowingCallable>of(
() -> validBuilder.listeningPort(200_000).disableDiscovery().build(),
() -> validBuilder.listeningPort(-2).disableDiscovery().build(),
() -> validBuilder.discoveryPort(-1).disableListening().build(),
() -> validBuilder.discoveryPort(100_000).disableListening().build())
.forEach(assertThatExceptionOfType(IllegalPortException.class)::isThrownBy);
}
@Test
public void builder_setEachPortExplicitly() {
final EnodeURL enodeURL =
@ -559,7 +569,7 @@ public class EnodeURLTest {
EnodeURL.builder()
.nodeId(VALID_NODE_ID)
.ipAddress(IPV4_ADDRESS)
.discoveryPort(OptionalInt.empty())
.discoveryPort(Optional.empty())
.listeningPort(P2P_PORT)
.build();
@ -578,7 +588,7 @@ public class EnodeURLTest {
.nodeId(VALID_NODE_ID)
.ipAddress(IPV4_ADDRESS)
.discoveryPort(P2P_PORT)
.listeningPort(OptionalInt.empty())
.listeningPort(Optional.empty())
.build();
assertThat(enodeURL.getNodeId().toUnprefixedHexString()).isEqualTo(VALID_NODE_ID);

@ -0,0 +1,21 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.util;
public class IllegalPortException extends IllegalArgumentException {
IllegalPortException(final String message) {
super(message);
}
}

@ -90,4 +90,12 @@ public class NetworkUtility {
public static boolean isUnspecifiedAddress(final String ipAddress) {
return INADDR_ANY.equals(ipAddress) || INADDR6_ANY.equals(ipAddress);
}
public static void checkPort(final int port, final String portTypeName) {
if (!isValidPort(port)) {
throw new IllegalPortException(
String.format(
"%s port requires a value between 1 and 65535. Got %d.", portTypeName, port));
}
}
}

Loading…
Cancel
Save