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() .getLocalEnode()
.ifPresent( .ifPresent(
enode -> { enode -> {
if (enode.getDiscoveryPort().isPresent()) { enode
properties.setProperty( .getDiscoveryPort()
"discovery", String.valueOf(enode.getDiscoveryPort().getAsInt())); .ifPresent(
} discoveryPort ->
if (enode.getListeningPort().isPresent()) { properties.setProperty("discovery", String.valueOf(discoveryPort)));
properties.setProperty( enode
"p2p", String.valueOf(enode.getListeningPort().getAsInt())); .getListeningPort()
} .ifPresent(
listeningPort ->
properties.setProperty("p2p", String.valueOf(listeningPort)));
}); });
} }

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

@ -15,17 +15,17 @@
package org.hyperledger.besu.ethereum.p2p.discovery; package org.hyperledger.besu.ethereum.p2p.discovery;
import static com.google.common.base.Preconditions.checkArgument; 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 static org.hyperledger.besu.util.Preconditions.checkGuard;
import org.hyperledger.besu.ethereum.p2p.peers.EnodeURL; import org.hyperledger.besu.ethereum.p2p.peers.EnodeURL;
import org.hyperledger.besu.ethereum.rlp.RLPInput; import org.hyperledger.besu.ethereum.rlp.RLPInput;
import org.hyperledger.besu.ethereum.rlp.RLPOutput; 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.net.InetAddress;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalInt;
import com.google.common.net.InetAddresses; import com.google.common.net.InetAddresses;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
@ -37,23 +37,9 @@ import org.apache.tuweni.bytes.Bytes;
public class Endpoint { public class Endpoint {
private final String host; private final String host;
private final int udpPort; private final int udpPort;
private final OptionalInt tcpPort; private final Optional<Integer> tcpPort;
private static class IllegalPortException extends IllegalArgumentException { public Endpoint(final String host, final int udpPort, final Optional<Integer> tcpPort) {
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) {
checkArgument( checkArgument(
host != null && InetAddresses.isInetAddress(host), "host requires a valid IP address"); host != null && InetAddresses.isInetAddress(host), "host requires a valid IP address");
checkPort(udpPort, "UDP"); checkPort(udpPort, "UDP");
@ -72,7 +58,7 @@ public class Endpoint {
() -> () ->
new IllegalArgumentException( new IllegalArgumentException(
"Attempt to create a discovery endpoint for an enode with discovery disabled.")); "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); return new Endpoint(enode.getIp().getHostAddress(), discoveryPort, listeningPort);
} }
@ -93,7 +79,7 @@ public class Endpoint {
return udpPort; return udpPort;
} }
public OptionalInt getTcpPort() { public Optional<Integer> getTcpPort() {
return tcpPort; 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, // 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. // or to have an RLP NULL value for it.
OptionalInt tcpPort = OptionalInt.empty(); Optional<Integer> tcpPort = Optional.empty();
if (fieldCount == 3) { if (fieldCount == 3) {
if (in.nextIsNull()) { if (in.nextIsNull()) {
in.skipNext(); in.skipNext();
} else { } else {
tcpPort = OptionalInt.of(in.readIntScalar()); tcpPort = Optional.of(in.readIntScalar());
} }
} }
return new Endpoint(addr.getHostAddress(), udpPort, tcpPort); return new Endpoint(addr.getHostAddress(), udpPort, tcpPort);

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

@ -33,7 +33,7 @@ import java.io.IOException;
import java.net.BindException; import java.net.BindException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketException; import java.net.SocketException;
import java.util.OptionalInt; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.IntSupplier; import java.util.function.IntSupplier;
import java.util.function.Supplier; 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. // Acquire the senders coordinates to build a Peer representation from them.
final String host = datagram.sender().host(); final String host = datagram.sender().host();
final int port = datagram.sender().port(); 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()); handleIncomingPacket(endpoint, event.result());
} else { } else {
if (event.cause() instanceof PeerDiscoveryPacketDecodingException) { if (event.cause() instanceof PeerDiscoveryPacketDecodingException) {

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

@ -167,7 +167,7 @@ public class NettyConnectionInitializer implements ConnectionInitializer {
new Bootstrap() new Bootstrap()
.group(workers) .group(workers)
.channel(NioSocketChannel.class) .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.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_SECONDS * 1000) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_SECONDS * 1000)
.handler( .handler(

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

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

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

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

@ -53,7 +53,6 @@ import org.hyperledger.besu.nat.upnp.UpnpNatManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -257,7 +256,7 @@ public final class DefaultP2PNetworkTest {
network.start(); network.start();
final DiscoveryPeer peer = final DiscoveryPeer peer =
DiscoveryPeer.fromIdAndEndpoint( 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 = final PeerDiscoveryEvent.PeerBondedEvent peerBondedEvent =
new PeerDiscoveryEvent.PeerBondedEvent(peer, System.currentTimeMillis()); new PeerDiscoveryEvent.PeerBondedEvent(peer, System.currentTimeMillis());

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

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