From cefa14507abc234bba1064617144fa78a4d1562c Mon Sep 17 00:00:00 2001 From: Andrzej Cichocki Date: Fri, 7 Jul 2017 15:11:07 +0100 Subject: [PATCH] Retire HostAndPort (#962) * Don't attempt to parse a resolved InetSocketAddress toString * A mock node isn't reachable via an address --- .../client/jfx/model/NodeMonitorModel.kt | 4 +- .../net/corda/client/rpc/RPCStabilityTests.kt | 4 +- .../net/corda/client/rpc/CordaRPCClient.kt | 4 +- .../corda/client/rpc/internal/RPCClient.kt | 4 +- .../kotlin/net/corda/core/node/NodeInfo.kt | 4 +- .../core/utilities/NetworkHostAndPort.kt | 37 +++++++++++ .../CollectionExtensionTests.kt | 4 +- .../core/utilities/NetworkHostAndPortTest.kt | 60 ++++++++++++++++++ docs/source/changelog.rst | 2 +- .../nodeapi/ArtemisMessagingComponent.kt | 13 ++-- .../net/corda/nodeapi/ArtemisTcpTransport.kt | 4 +- .../corda/nodeapi/config/ConfigUtilities.kt | 7 ++- .../nodeapi/serialization/DefaultWhitelist.kt | 4 +- .../corda/nodeapi/config/ConfigParsingTest.kt | 14 ++--- .../node/services/BFTNotaryServiceTests.kt | 4 +- .../services/messaging/MQSecurityTest.kt | 6 +- .../net/corda/node/internal/AbstractNode.kt | 4 +- .../kotlin/net/corda/node/internal/Node.kt | 21 ++++--- .../node/services/config/NodeConfiguration.kt | 16 ++--- .../messaging/ArtemisMessagingServer.kt | 8 +-- .../services/messaging/NodeMessagingClient.kt | 6 +- .../services/transactions/BFTSMaRtConfig.kt | 12 ++-- .../transactions/RaftUniquenessProvider.kt | 5 +- .../net/corda/node/utilities/ConfigUtils.kt | 9 --- .../config/FullNodeConfigurationTest.kt | 6 +- .../messaging/ArtemisMessagingTests.kt | 6 +- .../transactions/BFTSMaRtConfigTests.kt | 4 +- .../DistributedImmutableMapTests.kt | 4 +- .../corda/attachmentdemo/AttachmentDemo.kt | 5 +- .../net/corda/bank/BankOfCordaDriver.kt | 6 +- .../corda/bank/api/BankOfCordaClientApi.kt | 4 +- .../kotlin/net/corda/irs/IRSDemoTest.kt | 4 +- .../src/test/kotlin/net/corda/irs/IRSDemo.kt | 8 +-- .../kotlin/net/corda/irs/IrsDemoClientApi.kt | 4 +- .../net/corda/demorun/util/DemoUtils.kt | 4 +- .../net/corda/notarydemo/BFTNotaryCordform.kt | 4 +- .../kotlin/net/corda/notarydemo/Notarise.kt | 4 +- .../corda/notarydemo/RaftNotaryCordform.kt | 4 +- .../kotlin/net/corda/traderdemo/TraderDemo.kt | 6 +- .../net/corda/smoketesting/NodeProcess.kt | 4 +- .../kotlin/net/corda/testing/CoreTestUtils.kt | 10 +-- .../main/kotlin/net/corda/testing/NodeApi.kt | 62 ------------------- .../kotlin/net/corda/testing/RPCDriver.kt | 35 ++++++----- .../kotlin/net/corda/testing/driver/Driver.kt | 31 +++++----- .../testing/driver/NetworkMapStartStrategy.kt | 4 +- .../kotlin/net/corda/testing/http/HttpApi.kt | 4 +- .../corda/testing/messaging/SimpleMQClient.kt | 4 +- .../corda/testing/node/MockNetworkMapCache.kt | 6 +- .../kotlin/net/corda/testing/node/MockNode.kt | 4 +- .../net/corda/testing/node/MockServices.kt | 3 +- .../net/corda/testing/node/SimpleNode.kt | 6 +- .../corda/demobench/model/InstallFactory.kt | 4 +- .../kotlin/net/corda/demobench/rpc/NodeRPC.kt | 4 +- .../corda/demobench/model/NodeConfigTest.kt | 4 +- .../net/corda/explorer/views/LoginView.kt | 6 +- .../net/corda/loadtest/ConnectionManager.kt | 4 +- .../net/corda/loadtest/NodeConnection.kt | 4 +- .../net/corda/verifier/VerifierDriver.kt | 14 ++--- .../kotlin/net/corda/verifier/Verifier.kt | 4 +- .../corda/webserver/WebserverDriverTests.kt | 4 +- .../net/corda/webserver/WebServerConfig.kt | 6 +- 61 files changed, 290 insertions(+), 266 deletions(-) create mode 100644 core/src/main/kotlin/net/corda/core/utilities/NetworkHostAndPort.kt rename core/src/test/kotlin/net/corda/core/{utilities => }/CollectionExtensionTests.kt (92%) create mode 100644 core/src/test/kotlin/net/corda/core/utilities/NetworkHostAndPortTest.kt delete mode 100644 node/src/main/kotlin/net/corda/node/utilities/ConfigUtils.kt delete mode 100644 test-utils/src/main/kotlin/net/corda/testing/NodeApi.kt diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt index 5a5e79cc34..e2b134bc8c 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt @@ -1,6 +1,5 @@ package net.corda.client.jfx.model -import com.google.common.net.HostAndPort import javafx.beans.property.SimpleObjectProperty import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClientConfiguration @@ -13,6 +12,7 @@ import net.corda.core.node.services.NetworkMapCache.MapChange import net.corda.core.node.services.Vault import net.corda.core.seconds import net.corda.core.transactions.SignedTransaction +import net.corda.core.utilities.NetworkHostAndPort import rx.Observable import rx.subjects.PublishSubject @@ -51,7 +51,7 @@ class NodeMonitorModel { * Register for updates to/from a given vault. * TODO provide an unsubscribe mechanism */ - fun register(nodeHostAndPort: HostAndPort, username: String, password: String) { + fun register(nodeHostAndPort: NetworkHostAndPort, username: String, password: String) { val client = CordaRPCClient( hostAndPort = nodeHostAndPort, configuration = CordaRPCClientConfiguration.default.copy( diff --git a/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/RPCStabilityTests.kt b/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/RPCStabilityTests.kt index 4a9dad7a36..a76ae661ad 100644 --- a/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/RPCStabilityTests.kt +++ b/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/RPCStabilityTests.kt @@ -5,13 +5,13 @@ import com.esotericsoftware.kryo.Serializer import com.esotericsoftware.kryo.io.Input import com.esotericsoftware.kryo.io.Output import com.esotericsoftware.kryo.pool.KryoPool -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import net.corda.client.rpc.internal.RPCClient import net.corda.client.rpc.internal.RPCClientConfiguration import net.corda.core.* import net.corda.core.crypto.random63BitValue import net.corda.core.messaging.RPCOps +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.driver.poll import net.corda.node.services.messaging.RPCServerConfiguration import net.corda.nodeapi.RPCApi @@ -78,7 +78,7 @@ class RPCStabilityTests { val executor = Executors.newScheduledThreadPool(1) fun startAndStop() { rpcDriver { - ErrorOr.catch { startRpcClient(HostAndPort.fromString("localhost:9999")).get() } + ErrorOr.catch { startRpcClient(NetworkHostAndPort("localhost", 9999)).get() } val server = startRpcServer(ops = DummyOps) ErrorOr.catch { startRpcClient( server.get().broker.hostAndPort!!, diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/CordaRPCClient.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/CordaRPCClient.kt index 199cdd6d67..78baa8d906 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/CordaRPCClient.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/CordaRPCClient.kt @@ -1,9 +1,9 @@ package net.corda.client.rpc -import com.google.common.net.HostAndPort import net.corda.client.rpc.internal.RPCClient import net.corda.client.rpc.internal.RPCClientConfiguration import net.corda.core.messaging.CordaRPCOps +import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport import net.corda.nodeapi.ConnectionDirection import net.corda.nodeapi.config.SSLConfiguration @@ -33,7 +33,7 @@ data class CordaRPCClientConfiguration( /** @see RPCClient */ class CordaRPCClient( - hostAndPort: HostAndPort, + hostAndPort: NetworkHostAndPort, sslConfiguration: SSLConfiguration? = null, configuration: CordaRPCClientConfiguration = CordaRPCClientConfiguration.default ) { diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt index 0412aeac36..a792c24faa 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt @@ -1,11 +1,11 @@ package net.corda.client.rpc.internal -import com.google.common.net.HostAndPort import net.corda.core.logElapsedTime import net.corda.core.messaging.RPCOps import net.corda.core.minutes import net.corda.core.crypto.random63BitValue import net.corda.core.seconds +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport import net.corda.nodeapi.ConnectionDirection @@ -88,7 +88,7 @@ class RPCClient( val rpcConfiguration: RPCClientConfiguration = RPCClientConfiguration.default ) { constructor( - hostAndPort: HostAndPort, + hostAndPort: NetworkHostAndPort, sslConfiguration: SSLConfiguration? = null, configuration: RPCClientConfiguration = RPCClientConfiguration.default ) : this(tcpTransport(ConnectionDirection.Outbound(), hostAndPort, sslConfiguration), configuration) diff --git a/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt b/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt index fc593fdfce..342e9997e1 100644 --- a/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt +++ b/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt @@ -1,11 +1,11 @@ package net.corda.core.node -import com.google.common.net.HostAndPort import net.corda.core.identity.Party import net.corda.core.identity.PartyAndCertificate import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceType import net.corda.core.serialization.CordaSerializable +import net.corda.core.utilities.NetworkHostAndPort /** * Information for an advertised service including the service specific identity information. @@ -19,7 +19,7 @@ data class ServiceEntry(val info: ServiceInfo, val identity: PartyAndCertificate */ // TODO We currently don't support multi-IP/multi-identity nodes, we only left slots in the data structures. @CordaSerializable -data class NodeInfo(val addresses: List, +data class NodeInfo(val addresses: List, val legalIdentityAndCert: PartyAndCertificate, //TODO This field will be removed in future PR which gets rid of services. val legalIdentitiesAndCerts: Set, val platformVersion: Int, diff --git a/core/src/main/kotlin/net/corda/core/utilities/NetworkHostAndPort.kt b/core/src/main/kotlin/net/corda/core/utilities/NetworkHostAndPort.kt new file mode 100644 index 0000000000..28d0e5c7dc --- /dev/null +++ b/core/src/main/kotlin/net/corda/core/utilities/NetworkHostAndPort.kt @@ -0,0 +1,37 @@ +package net.corda.core.utilities + +import java.net.URI + +/** + * Tuple of host and port. Use [parseNetworkHostAndPort] on untrusted data. + * @param host a hostname or IP address. IPv6 addresses must not be enclosed in square brackets. + * @param port a valid port number. + */ +data class NetworkHostAndPort(val host: String, val port: Int) { + companion object { + internal val invalidPortFormat = "Invalid port: %s" + internal val unparseableAddressFormat = "Unparseable address: %s" + internal val missingPortFormat = "Missing port: %s" + } + + init { + require(port in (0..0xffff)) { invalidPortFormat.format(port) } + } + + override fun toString() = if (':' in host) "[$host]:$port" else "$host:$port" +} + +/** + * Parses a string of the form host:port into a [NetworkHostAndPort]. + * The host part may be a hostname or IP address. If it's an IPv6 address, it must be enclosed in square brackets. + * Note this does not parse the toString of a resolved [java.net.InetSocketAddress], which is of a host/IP:port form. + * @throws IllegalArgumentException if the port is missing, the string is garbage, or the NetworkHostAndPort constructor rejected the parsed parts. + */ +fun String.parseNetworkHostAndPort() = run { + val uri = URI(null, this, null, null, null) + require(uri.host != null) { NetworkHostAndPort.unparseableAddressFormat.format(this) } + require(uri.port != -1) { NetworkHostAndPort.missingPortFormat.format(this) } + NetworkHostAndPort(bracketedHost.matchEntire(uri.host)?.groupValues?.get(1) ?: uri.host, uri.port) +} + +private val bracketedHost = "\\[(.*)]".toRegex() diff --git a/core/src/test/kotlin/net/corda/core/utilities/CollectionExtensionTests.kt b/core/src/test/kotlin/net/corda/core/CollectionExtensionTests.kt similarity index 92% rename from core/src/test/kotlin/net/corda/core/utilities/CollectionExtensionTests.kt rename to core/src/test/kotlin/net/corda/core/CollectionExtensionTests.kt index 169fab9793..1fab9fceaa 100644 --- a/core/src/test/kotlin/net/corda/core/utilities/CollectionExtensionTests.kt +++ b/core/src/test/kotlin/net/corda/core/CollectionExtensionTests.kt @@ -1,7 +1,5 @@ -package net.corda.core.utilities +package net.corda.core -import net.corda.core.indexOfOrThrow -import net.corda.core.noneOrSingle import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith diff --git a/core/src/test/kotlin/net/corda/core/utilities/NetworkHostAndPortTest.kt b/core/src/test/kotlin/net/corda/core/utilities/NetworkHostAndPortTest.kt new file mode 100644 index 0000000000..925773e2b3 --- /dev/null +++ b/core/src/test/kotlin/net/corda/core/utilities/NetworkHostAndPortTest.kt @@ -0,0 +1,60 @@ +package net.corda.core.utilities + +import org.junit.Test +import kotlin.test.assertEquals +import org.assertj.core.api.Assertions.assertThatThrownBy + +class NetworkHostAndPortTest { + /** + * If a host isn't known-good it should go via the parser, which does some validation. + */ + @Test + fun `constructor is not fussy about host`() { + assertEquals("", NetworkHostAndPort("", 1234).host) + assertEquals("x", NetworkHostAndPort("x", 1234).host) + assertEquals("500", NetworkHostAndPort("500", 1234).host) + assertEquals(" yo yo\t", NetworkHostAndPort(" yo yo\t", 1234).host) + assertEquals("[::1]", NetworkHostAndPort("[::1]", 1234).host) // Don't do this. + } + + @Test + fun `constructor requires a valid port`() { + assertEquals(0, NetworkHostAndPort("example.com", 0).port) + assertEquals(65535, NetworkHostAndPort("example.com", 65535).port) + listOf(65536, -1).forEach { + assertThatThrownBy { + NetworkHostAndPort("example.com", it) + }.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.invalidPortFormat.format(it)) + } + } + + @Test + fun `toString works`() { + assertEquals("example.com:1234", NetworkHostAndPort("example.com", 1234).toString()) + assertEquals("example.com:65535", NetworkHostAndPort("example.com", 65535).toString()) + assertEquals("1.2.3.4:1234", NetworkHostAndPort("1.2.3.4", 1234).toString()) + assertEquals("[::1]:1234", NetworkHostAndPort("::1", 1234).toString()) + // Brackets perhaps not necessary in unabbreviated case, but URI seems to need them for parsing: + assertEquals("[0:0:0:0:0:0:0:1]:1234", NetworkHostAndPort("0:0:0:0:0:0:0:1", 1234).toString()) + assertEquals(":1234", NetworkHostAndPort("", 1234).toString()) // URI won't parse this. + } + + @Test + fun `parseNetworkHostAndPort works`() { + assertEquals(NetworkHostAndPort("example.com", 1234), "example.com:1234".parseNetworkHostAndPort()) + assertEquals(NetworkHostAndPort("example.com", 65535), "example.com:65535".parseNetworkHostAndPort()) + assertEquals(NetworkHostAndPort("1.2.3.4", 1234), "1.2.3.4:1234".parseNetworkHostAndPort()) + assertEquals(NetworkHostAndPort("::1", 1234), "[::1]:1234".parseNetworkHostAndPort()) + assertEquals(NetworkHostAndPort("0:0:0:0:0:0:0:1", 1234), "[0:0:0:0:0:0:0:1]:1234".parseNetworkHostAndPort()) + listOf("0:0:0:0:0:0:0:1:1234", ":1234", "example.com:-1").forEach { + assertThatThrownBy { + it.parseNetworkHostAndPort() + }.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.unparseableAddressFormat.format(it)) + } + listOf("example.com:", "example.com").forEach { + assertThatThrownBy { + it.parseNetworkHostAndPort() + }.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.missingPortFormat.format(it)) + } + } +} diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 85c1d923a5..c2ab1cfba8 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -12,7 +12,7 @@ UNRELEASED * ``PhysicalLocation`` was renamed to ``WorldMapLocation`` to emphasise that it doesn't need to map to a truly physical location of the node server. * Slots for multiple IP addresses and ``legalIdentitiesAndCert``s were introduced. Addresses are no longer of type - ``SingleMessageRecipient``, but of ``HostAndPort``. + ``SingleMessageRecipient``, but of ``NetworkHostAndPort``. * ``ServiceHub.storageService`` has been removed. ``attachments`` and ``validatedTransactions`` are now direct members of ``ServiceHub``. diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisMessagingComponent.kt b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisMessagingComponent.kt index f31b75eaaa..a37a841f83 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisMessagingComponent.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisMessagingComponent.kt @@ -1,7 +1,5 @@ package net.corda.nodeapi -import com.google.common.annotations.VisibleForTesting -import com.google.common.net.HostAndPort import net.corda.core.crypto.toBase58String import net.corda.core.messaging.MessageRecipientGroup import net.corda.core.messaging.MessageRecipients @@ -11,6 +9,7 @@ import net.corda.core.node.services.ServiceType import net.corda.core.read import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.SingletonSerializeAsToken +import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.config.SSLConfiguration import java.security.KeyStore import java.security.PublicKey @@ -43,11 +42,11 @@ abstract class ArtemisMessagingComponent : SingletonSerializeAsToken() { } interface ArtemisPeerAddress : ArtemisAddress, SingleMessageRecipient { - val hostAndPort: HostAndPort + val hostAndPort: NetworkHostAndPort } @CordaSerializable - data class NetworkMapAddress(override val hostAndPort: HostAndPort) : ArtemisPeerAddress { + data class NetworkMapAddress(override val hostAndPort: NetworkHostAndPort) : ArtemisPeerAddress { override val queueName: String get() = NETWORK_MAP_QUEUE } @@ -63,13 +62,13 @@ abstract class ArtemisMessagingComponent : SingletonSerializeAsToken() { * @param hostAndPort The address of the node. */ @CordaSerializable - data class NodeAddress(override val queueName: String, override val hostAndPort: HostAndPort) : ArtemisPeerAddress { + data class NodeAddress(override val queueName: String, override val hostAndPort: NetworkHostAndPort) : ArtemisPeerAddress { companion object { - fun asPeer(peerIdentity: PublicKey, hostAndPort: HostAndPort): NodeAddress { + fun asPeer(peerIdentity: PublicKey, hostAndPort: NetworkHostAndPort): NodeAddress { return NodeAddress("$PEERS_PREFIX${peerIdentity.toBase58String()}", hostAndPort) } - fun asService(serviceIdentity: PublicKey, hostAndPort: HostAndPort): NodeAddress { + fun asService(serviceIdentity: PublicKey, hostAndPort: NetworkHostAndPort): NodeAddress { return NodeAddress("$SERVICES_PREFIX${serviceIdentity.toBase58String()}", hostAndPort) } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt index cdd0074a1b..5cda03946f 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt @@ -1,6 +1,6 @@ package net.corda.nodeapi -import com.google.common.net.HostAndPort +import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.config.SSLConfiguration import org.apache.activemq.artemis.api.core.TransportConfiguration import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory @@ -36,7 +36,7 @@ class ArtemisTcpTransport { fun tcpTransport( direction: ConnectionDirection, - hostAndPort: HostAndPort, + hostAndPort: NetworkHostAndPort, config: SSLConfiguration?, enableSSL: Boolean = true ): TransportConfiguration { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt b/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt index 9726136af0..f7cf998d7e 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt @@ -1,9 +1,10 @@ package net.corda.nodeapi.config -import com.google.common.net.HostAndPort import com.typesafe.config.Config import com.typesafe.config.ConfigUtil import net.corda.core.noneOrSingle +import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.parseNetworkHostAndPort import org.bouncycastle.asn1.x500.X500Name import org.slf4j.LoggerFactory import java.net.Proxy @@ -67,7 +68,7 @@ private fun Config.getSingleValue(path: String, type: KType): Any? { Boolean::class -> getBoolean(path) LocalDate::class -> LocalDate.parse(getString(path)) Instant::class -> Instant.parse(getString(path)) - HostAndPort::class -> HostAndPort.fromString(getString(path)) + NetworkHostAndPort::class -> getString(path).parseNetworkHostAndPort() Path::class -> Paths.get(getString(path)) URL::class -> URL(getString(path)) Properties::class -> getConfig(path).toProperties() @@ -95,7 +96,7 @@ private fun Config.getCollectionValue(path: String, type: KType): Collection getBooleanList(path) LocalDate::class -> getStringList(path).map(LocalDate::parse) Instant::class -> getStringList(path).map(Instant::parse) - HostAndPort::class -> getStringList(path).map(HostAndPort::fromString) + NetworkHostAndPort::class -> getStringList(path).map { it.parseNetworkHostAndPort() } Path::class -> getStringList(path).map { Paths.get(it) } URL::class -> getStringList(path).map(::URL) X500Name::class -> getStringList(path).map(::X500Name) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/serialization/DefaultWhitelist.kt b/node-api/src/main/kotlin/net/corda/nodeapi/serialization/DefaultWhitelist.kt index 31e9743eee..9e5b507cdb 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/serialization/DefaultWhitelist.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/serialization/DefaultWhitelist.kt @@ -1,9 +1,9 @@ package net.corda.nodeapi.serialization import com.esotericsoftware.kryo.KryoException -import com.google.common.net.HostAndPort import net.corda.core.node.CordaPluginRegistry import net.corda.core.serialization.SerializationCustomization +import net.corda.core.utilities.NetworkHostAndPort import org.apache.activemq.artemis.api.core.SimpleString import rx.Notification import rx.exceptions.OnErrorNotImplementedException @@ -33,7 +33,7 @@ class DefaultWhitelist : CordaPluginRegistry() { addToWhitelist(listOf(Unit).javaClass) // SingletonList addToWhitelist(setOf(Unit).javaClass) // SingletonSet addToWhitelist(mapOf(Unit to Unit).javaClass) // SingletonSet - addToWhitelist(HostAndPort::class.java) + addToWhitelist(NetworkHostAndPort::class.java) addToWhitelist(SimpleString::class.java) addToWhitelist(KryoException::class.java) addToWhitelist(StringBuffer::class.java) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/config/ConfigParsingTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/config/ConfigParsingTest.kt index 3a09140194..511eee6527 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/config/ConfigParsingTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/config/ConfigParsingTest.kt @@ -1,11 +1,11 @@ package net.corda.nodeapi.config -import com.google.common.net.HostAndPort import com.typesafe.config.Config import com.typesafe.config.ConfigFactory.empty import com.typesafe.config.ConfigRenderOptions.defaults import com.typesafe.config.ConfigValueFactory import net.corda.core.div +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.getTestX509Name import org.assertj.core.api.Assertions.assertThat import org.bouncycastle.asn1.x500.X500Name @@ -59,10 +59,10 @@ class ConfigParsingTest { } @Test - fun `HostAndPort`() { - testPropertyType( - HostAndPort.fromParts("localhost", 2223), - HostAndPort.fromParts("localhost", 2225), + fun `NetworkHostAndPort`() { + testPropertyType( + NetworkHostAndPort("localhost", 2223), + NetworkHostAndPort("localhost", 2225), valuesToString = true) } @@ -223,8 +223,8 @@ class ConfigParsingTest { data class LocalDateListData(override val values: List) : ListData data class InstantData(override val value: Instant) : SingleData data class InstantListData(override val values: List) : ListData - data class HostAndPortData(override val value: HostAndPort) : SingleData - data class HostAndPortListData(override val values: List) : ListData + data class NetworkHostAndPortData(override val value: NetworkHostAndPort) : SingleData + data class NetworkHostAndPortListData(override val values: List) : ListData data class PathData(override val value: Path) : SingleData data class PathListData(override val values: List) : ListData data class URLData(override val value: URL) : SingleData diff --git a/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt index d0aeb6547b..e996f9d43b 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt @@ -1,6 +1,5 @@ package net.corda.node.services -import com.google.common.net.HostAndPort import com.nhaarman.mockito_kotlin.whenever import net.corda.core.ErrorOr import net.corda.core.contracts.ContractState @@ -13,6 +12,7 @@ import net.corda.core.div import net.corda.core.getOrThrow import net.corda.core.identity.Party import net.corda.core.node.services.ServiceInfo +import net.corda.core.utilities.NetworkHostAndPort import net.corda.flows.NotaryError import net.corda.flows.NotaryException import net.corda.flows.NotaryFlow @@ -53,7 +53,7 @@ class BFTNotaryServiceTests { serviceType.id, clusterName) val bftNotaryService = ServiceInfo(serviceType, clusterName) - val notaryClusterAddresses = replicaIds.map { HostAndPort.fromParts("localhost", 11000 + it * 10) } + val notaryClusterAddresses = replicaIds.map { NetworkHostAndPort("localhost", 11000 + it * 10) } replicaIds.forEach { replicaId -> mockNet.createNode( node.network.myAddress, diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt index 3b99f6845f..9cae274260 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt @@ -1,7 +1,6 @@ package net.corda.services.messaging import co.paralleluniverse.fibers.Suspendable -import com.google.common.net.HostAndPort import net.corda.client.rpc.CordaRPCClient import net.corda.core.crypto.generateKeyPair import net.corda.core.crypto.toBase58String @@ -11,6 +10,7 @@ import net.corda.core.flows.InitiatingFlow import net.corda.core.getOrThrow import net.corda.core.identity.Party import net.corda.core.messaging.CordaRPCOps +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.crypto.random63BitValue import net.corda.testing.ALICE import net.corda.testing.BOB @@ -144,13 +144,13 @@ abstract class MQSecurityTest : NodeBasedTest() { assertAllQueueCreationAttacksFail(randomQueue) } - fun clientTo(target: HostAndPort, sslConfiguration: SSLConfiguration? = configureTestSSL()): SimpleMQClient { + fun clientTo(target: NetworkHostAndPort, sslConfiguration: SSLConfiguration? = configureTestSSL()): SimpleMQClient { val client = SimpleMQClient(target, sslConfiguration) clients += client return client } - fun loginToRPC(target: HostAndPort, rpcUser: User, sslConfiguration: SSLConfiguration? = null): CordaRPCOps { + fun loginToRPC(target: NetworkHostAndPort, rpcUser: User, sslConfiguration: SSLConfiguration? = null): CordaRPCOps { return CordaRPCClient(target, sslConfiguration).start(rpcUser.username, rpcUser.password).proxy } diff --git a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt index 2e754c518c..2f8d586e10 100644 --- a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt @@ -3,7 +3,6 @@ package net.corda.node.internal import com.codahale.metrics.MetricRegistry import com.google.common.annotations.VisibleForTesting import com.google.common.collect.MutableClassToInstanceMap -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.MoreExecutors import com.google.common.util.concurrent.SettableFuture @@ -24,6 +23,7 @@ import net.corda.core.serialization.SerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.deserialize import net.corda.core.transactions.SignedTransaction +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.debug import net.corda.flows.* import net.corda.node.services.* @@ -621,7 +621,7 @@ abstract class AbstractNode(open val configuration: NodeConfiguration, } /** Return list of node's addresses. It's overridden in MockNetwork as we don't have real addresses for MockNodes. */ - protected abstract fun myAddresses(): List + protected abstract fun myAddresses(): List /** This is overriden by the mock node implementation to enable operation without any network map service */ protected open fun noNetworkMapConfigured(): ListenableFuture { diff --git a/node/src/main/kotlin/net/corda/node/internal/Node.kt b/node/src/main/kotlin/net/corda/node/internal/Node.kt index 871bdd6307..c9ec5fcac3 100644 --- a/node/src/main/kotlin/net/corda/node/internal/Node.kt +++ b/node/src/main/kotlin/net/corda/node/internal/Node.kt @@ -1,7 +1,6 @@ package net.corda.node.internal import com.codahale.metrics.JmxReporter -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.SettableFuture @@ -12,7 +11,9 @@ import net.corda.core.node.ServiceHub import net.corda.core.node.services.ServiceInfo import net.corda.core.seconds import net.corda.core.success +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor +import net.corda.core.utilities.parseNetworkHostAndPort import net.corda.core.utilities.trace import net.corda.node.VersionInfo import net.corda.node.serialization.NodeClock @@ -155,21 +156,21 @@ open class Node(override val configuration: FullNodeConfiguration, advertisedAddress) } - private fun makeLocalMessageBroker(): HostAndPort { + private fun makeLocalMessageBroker(): NetworkHostAndPort { with(configuration) { messageBroker = ArtemisMessagingServer(this, p2pAddress.port, rpcAddress?.port, services.networkMapCache, userService) - return HostAndPort.fromParts("localhost", p2pAddress.port) + return NetworkHostAndPort("localhost", p2pAddress.port) } } - private fun getAdvertisedAddress(): HostAndPort { + private fun getAdvertisedAddress(): NetworkHostAndPort { return with(configuration) { val useHost = if (detectPublicIp) { tryDetectIfNotPublicHost(p2pAddress.host) ?: p2pAddress.host } else { p2pAddress.host } - HostAndPort.fromParts(useHost, p2pAddress.port) + NetworkHostAndPort(useHost, p2pAddress.port) } } @@ -201,7 +202,7 @@ open class Node(override val configuration: FullNodeConfiguration, * it back to the queue. * - Once the message is received the session is closed and the queue deleted. */ - private fun discoverPublicHost(serverAddress: HostAndPort): String? { + private fun discoverPublicHost(serverAddress: NetworkHostAndPort): String? { log.trace { "Trying to detect public hostname through the Network Map Service at $serverAddress" } val tcpTransport = ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), serverAddress, configuration) val locator = ActiveMQClient.createServerLocatorWithoutHA(tcpTransport).apply { @@ -227,14 +228,14 @@ open class Node(override val configuration: FullNodeConfiguration, val consumer = session.createConsumer(queueName) val artemisMessage: ClientMessage = consumer.receive(10.seconds.toMillis()) ?: throw IOException("Did not receive a response from the Network Map Service at $serverAddress") - val publicHostAndPort = HostAndPort.fromString(artemisMessage.getStringProperty(ipDetectResponseProperty)) + val publicHostAndPort = artemisMessage.getStringProperty(ipDetectResponseProperty) log.info("Detected public address: $publicHostAndPort") consumer.close() session.deleteQueue(queueName) clientFactory.close() - return publicHostAndPort.host.removePrefix("/") + return publicHostAndPort.removePrefix("/").parseNetworkHostAndPort().host } override fun startMessagingService(rpcOps: RPCOps) { @@ -257,7 +258,7 @@ open class Node(override val configuration: FullNodeConfiguration, return networkMapConnection.flatMap { super.registerWithNetworkMap() } } - override fun myAddresses(): List { + override fun myAddresses(): List { val address = network.myAddress as ArtemisMessagingComponent.ArtemisPeerAddress return listOf(address.hostAndPort) } @@ -359,4 +360,4 @@ open class Node(override val configuration: FullNodeConfiguration, class ConfigurationException(message: String) : Exception(message) -data class NetworkMapInfo(val address: HostAndPort, val legalName: X500Name) +data class NetworkMapInfo(val address: NetworkHostAndPort, val legalName: X500Name) diff --git a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt index a052e20968..da56b1e2fd 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt @@ -1,7 +1,7 @@ package net.corda.node.services.config -import com.google.common.net.HostAndPort import net.corda.core.node.services.ServiceInfo +import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.internal.NetworkMapInfo import net.corda.node.services.messaging.CertificateChainCheckPolicy import net.corda.node.services.network.NetworkMapService @@ -27,8 +27,8 @@ interface NodeConfiguration : NodeSSLConfiguration { val verifierType: VerifierType val messageRedeliveryDelaySeconds: Int val bftReplicaId: Int? - val notaryNodeAddress: HostAndPort? - val notaryClusterAddresses: List + val notaryNodeAddress: NetworkHostAndPort? + val notaryClusterAddresses: List } data class FullNodeConfiguration( @@ -50,15 +50,15 @@ data class FullNodeConfiguration( override val messageRedeliveryDelaySeconds: Int = 30, val useHTTPS: Boolean, @OldConfig("artemisAddress") - val p2pAddress: HostAndPort, - val rpcAddress: HostAndPort?, + val p2pAddress: NetworkHostAndPort, + val rpcAddress: NetworkHostAndPort?, // TODO This field is slightly redundant as p2pAddress is sufficient to hold the address of the node's MQ broker. // Instead this should be a Boolean indicating whether that broker is an internal one started by the node or an external one - val messagingServerAddress: HostAndPort?, + val messagingServerAddress: NetworkHostAndPort?, val extraAdvertisedServiceIds: List, override val bftReplicaId: Int?, - override val notaryNodeAddress: HostAndPort?, - override val notaryClusterAddresses: List, + override val notaryNodeAddress: NetworkHostAndPort?, + override val notaryClusterAddresses: List, override val certificateChainCheckPolicies: List, override val devMode: Boolean = false, val useTestClock: Boolean = false, diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt index cf5214e217..66b2da18f6 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt @@ -1,6 +1,5 @@ package net.corda.node.services.messaging -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.SettableFuture import io.netty.handler.ssl.SslHandler @@ -11,6 +10,7 @@ import net.corda.core.crypto.X509Utilities.CORDA_ROOT_CA import net.corda.core.node.NodeInfo import net.corda.core.node.services.NetworkMapCache import net.corda.core.node.services.NetworkMapCache.MapChange +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.debug import net.corda.core.utilities.loggerFor import net.corda.node.internal.Node @@ -376,7 +376,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration, } private fun createTcpTransport(connectionDirection: ConnectionDirection, host: String, port: Int, enableSSL: Boolean = true) = - ArtemisTcpTransport.tcpTransport(connectionDirection, HostAndPort.fromParts(host, port), config, enableSSL = enableSSL) + ArtemisTcpTransport.tcpTransport(connectionDirection, NetworkHostAndPort(host, port), config, enableSSL = enableSSL) /** * All nodes are expected to have a public facing address called [ArtemisMessagingComponent.P2P_QUEUE] for receiving @@ -384,7 +384,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration, * as defined by ArtemisAddress.queueName. A bridge is then created to forward messages from this queue to the node's * P2P address. */ - private fun deployBridge(queueName: String, target: HostAndPort, legalName: X500Name) { + private fun deployBridge(queueName: String, target: NetworkHostAndPort, legalName: X500Name) { val connectionDirection = ConnectionDirection.Outbound( connectorFactoryClassName = VerifyingNettyConnectorFactory::class.java.name, expectedCommonName = legalName @@ -420,7 +420,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration, private val ArtemisPeerAddress.bridgeName: String get() = getBridgeName(queueName, hostAndPort) - private fun getBridgeName(queueName: String, hostAndPort: HostAndPort): String = "$queueName -> $hostAndPort" + private fun getBridgeName(queueName: String, hostAndPort: NetworkHostAndPort): String = "$queueName -> $hostAndPort" // This is called on one of Artemis' background threads internal fun hostVerificationFail(expectedLegalName: X500Name, errorMsg: String?) { diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt b/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt index beaa4ddc12..713c1be649 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt @@ -1,6 +1,5 @@ package net.corda.node.services.messaging -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.ListenableFuture import net.corda.core.* import net.corda.core.crypto.random63BitValue @@ -12,6 +11,7 @@ import net.corda.core.node.services.PartyInfo import net.corda.core.node.services.TransactionVerifierService import net.corda.core.utilities.opaque import net.corda.core.transactions.LedgerTransaction +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.core.utilities.trace import net.corda.node.VersionInfo @@ -71,13 +71,13 @@ import javax.annotation.concurrent.ThreadSafe @ThreadSafe class NodeMessagingClient(override val config: NodeConfiguration, val versionInfo: VersionInfo, - val serverAddress: HostAndPort, + val serverAddress: NetworkHostAndPort, val myIdentity: PublicKey?, val nodeExecutor: AffinityExecutor.ServiceAffinityExecutor, val database: Database, val networkMapRegistrationFuture: ListenableFuture, val monitoringService: MonitoringService, - advertisedAddress: HostAndPort = serverAddress + advertisedAddress: NetworkHostAndPort = serverAddress ) : ArtemisMessagingComponent(), MessagingService { companion object { private val log = loggerFor() diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt index c11952c202..72c0212eb2 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt @@ -1,7 +1,7 @@ package net.corda.node.services.transactions -import com.google.common.net.HostAndPort import net.corda.core.div +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.debug import net.corda.core.utilities.loggerFor import java.io.FileWriter @@ -17,14 +17,14 @@ import java.util.concurrent.TimeUnit.MILLISECONDS * Each instance of this class creates such a configHome, accessible via [path]. * The files are deleted on [close] typically via [use], see [PathManager] for details. */ -class BFTSMaRtConfig(private val replicaAddresses: List, debug: Boolean = false) : PathManager(Files.createTempDirectory("bft-smart-config")) { +class BFTSMaRtConfig(private val replicaAddresses: List, debug: Boolean = false) : PathManager(Files.createTempDirectory("bft-smart-config")) { companion object { private val log = loggerFor() internal val portIsClaimedFormat = "Port %s is claimed by another replica: %s" } init { - val claimedPorts = mutableSetOf() + val claimedPorts = mutableSetOf() val n = replicaAddresses.size (0 until n).forEach { replicaId -> // Each replica claims the configured port and the next one: @@ -66,7 +66,7 @@ class BFTSMaRtConfig(private val replicaAddresses: List, debug: Boo log.debug { "Replica $peerId is ready for P2P." } } - private fun replicaPorts(replicaId: Int): List { + private fun replicaPorts(replicaId: Int): List { val base = replicaAddresses[replicaId] return BFTSMaRtPort.values().map { it.ofReplica(base) } } @@ -76,10 +76,10 @@ private enum class BFTSMaRtPort(private val off: Int) { FOR_CLIENTS(0), FOR_REPLICAS(1); - fun ofReplica(base: HostAndPort) = HostAndPort.fromParts(base.host, base.port + off) + fun ofReplica(base: NetworkHostAndPort) = NetworkHostAndPort(base.host, base.port + off) } -private fun HostAndPort.isListening() = try { +private fun NetworkHostAndPort.isListening() = try { Socket(host, port).use { true } // Will cause one error to be logged in the replica on success. } catch (e: SocketException) { false diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt b/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt index e0f514cc32..b12c7ce477 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt @@ -1,6 +1,5 @@ package net.corda.node.services.transactions -import com.google.common.net.HostAndPort import io.atomix.catalyst.buffer.BufferInput import io.atomix.catalyst.buffer.BufferOutput import io.atomix.catalyst.serializer.Serializer @@ -48,13 +47,13 @@ class RaftUniquenessProvider(services: ServiceHubInternal) : UniquenessProvider, /** Directory storing the Raft log and state machine snapshots */ private val storagePath: Path = services.configuration.baseDirectory /** Address of the Copycat node run by this Corda node */ - private val myAddress: HostAndPort = services.configuration.notaryNodeAddress + private val myAddress = services.configuration.notaryNodeAddress ?: throw IllegalArgumentException("notaryNodeAddress must be specified in configuration") /** * List of node addresses in the existing Copycat cluster. At least one active node must be * provided to join the cluster. If empty, a new cluster will be bootstrapped. */ - private val clusterAddresses: List = services.configuration.notaryClusterAddresses + private val clusterAddresses = services.configuration.notaryClusterAddresses /** The database to store the state machine state in */ private val db: Database = services.database /** SSL configuration */ diff --git a/node/src/main/kotlin/net/corda/node/utilities/ConfigUtils.kt b/node/src/main/kotlin/net/corda/node/utilities/ConfigUtils.kt deleted file mode 100644 index 5048cb8981..0000000000 --- a/node/src/main/kotlin/net/corda/node/utilities/ConfigUtils.kt +++ /dev/null @@ -1,9 +0,0 @@ -package net.corda.node.utilities - -import com.google.common.net.HostAndPort -import com.typesafe.config.Config -import java.nio.file.Path -import java.nio.file.Paths - -fun Config.getHostAndPort(name: String): HostAndPort = HostAndPort.fromString(getString(name)) -fun Config.getPath(name: String): Path = Paths.get(getString(name)) \ No newline at end of file diff --git a/node/src/test/kotlin/net/corda/node/services/config/FullNodeConfigurationTest.kt b/node/src/test/kotlin/net/corda/node/services/config/FullNodeConfigurationTest.kt index 3b8988ee0a..4cc7883c43 100644 --- a/node/src/test/kotlin/net/corda/node/services/config/FullNodeConfigurationTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/config/FullNodeConfigurationTest.kt @@ -1,7 +1,7 @@ package net.corda.node.services.config -import com.google.common.net.HostAndPort import net.corda.core.crypto.commonName +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.ALICE import net.corda.nodeapi.User import net.corda.testing.node.makeTestDataSourceProperties @@ -25,8 +25,8 @@ class FullNodeConfigurationTest { rpcUsers = emptyList(), verifierType = VerifierType.InMemory, useHTTPS = false, - p2pAddress = HostAndPort.fromParts("localhost", 0), - rpcAddress = HostAndPort.fromParts("localhost", 1), + p2pAddress = NetworkHostAndPort("localhost", 0), + rpcAddress = NetworkHostAndPort("localhost", 1), messagingServerAddress = null, extraAdvertisedServiceIds = emptyList(), bftReplicaId = null, diff --git a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt index b93802356b..d92bec8a22 100644 --- a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt @@ -1,13 +1,14 @@ package net.corda.node.services.messaging import com.codahale.metrics.MetricRegistry -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.SettableFuture import net.corda.core.crypto.generateKeyPair import net.corda.core.messaging.RPCOps import net.corda.core.node.services.DEFAULT_SESSION_ID +import net.corda.core.utilities.NetworkHostAndPort +import net.corda.testing.ALICE import net.corda.testing.LogHelper import net.corda.node.services.RPCUserService import net.corda.node.services.RPCUserServiceImpl @@ -20,7 +21,6 @@ import net.corda.node.services.transactions.PersistentUniquenessProvider import net.corda.node.utilities.AffinityExecutor.ServiceAffinityExecutor import net.corda.node.utilities.configureDatabase import net.corda.node.utilities.transaction -import net.corda.testing.ALICE import net.corda.testing.freeLocalHostAndPort import net.corda.testing.freePort import net.corda.testing.node.MOCK_VERSION_INFO @@ -218,7 +218,7 @@ class ArtemisMessagingTests { return messagingClient } - private fun createMessagingClient(server: HostAndPort = HostAndPort.fromParts("localhost", serverPort)): NodeMessagingClient { + private fun createMessagingClient(server: NetworkHostAndPort = NetworkHostAndPort("localhost", serverPort)): NodeMessagingClient { return database.transaction { NodeMessagingClient( config, diff --git a/node/src/test/kotlin/net/corda/node/services/transactions/BFTSMaRtConfigTests.kt b/node/src/test/kotlin/net/corda/node/services/transactions/BFTSMaRtConfigTests.kt index 0dd0af75dc..5fdee29f25 100644 --- a/node/src/test/kotlin/net/corda/node/services/transactions/BFTSMaRtConfigTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/transactions/BFTSMaRtConfigTests.kt @@ -1,6 +1,6 @@ package net.corda.node.services.transactions -import com.google.common.net.HostAndPort +import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.transactions.BFTSMaRtConfig.Companion.portIsClaimedFormat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Test @@ -28,7 +28,7 @@ class BFTSMaRtConfigTests { @Test fun `overlapping port ranges are rejected`() { - fun addresses(vararg ports: Int) = ports.map { HostAndPort.fromParts("localhost", it) } + fun addresses(vararg ports: Int) = ports.map { NetworkHostAndPort("localhost", it) } assertThatThrownBy { BFTSMaRtConfig(addresses(11000, 11001)).use {} } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage(portIsClaimedFormat.format("localhost:11001", setOf("localhost:11000", "localhost:11001"))) diff --git a/node/src/test/kotlin/net/corda/node/services/transactions/DistributedImmutableMapTests.kt b/node/src/test/kotlin/net/corda/node/services/transactions/DistributedImmutableMapTests.kt index fe57ded32c..7895f4defc 100644 --- a/node/src/test/kotlin/net/corda/node/services/transactions/DistributedImmutableMapTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/transactions/DistributedImmutableMapTests.kt @@ -1,6 +1,5 @@ package net.corda.node.services.transactions -import com.google.common.net.HostAndPort import io.atomix.catalyst.transport.Address import io.atomix.copycat.client.ConnectionStrategies import io.atomix.copycat.client.CopycatClient @@ -8,6 +7,7 @@ import io.atomix.copycat.server.CopycatServer import io.atomix.copycat.server.storage.Storage import io.atomix.copycat.server.storage.StorageLevel import net.corda.core.getOrThrow +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.LogHelper import net.corda.node.services.network.NetworkMapService import net.corda.node.utilities.configureDatabase @@ -87,7 +87,7 @@ class DistributedImmutableMapTests { return cluster.map { it.getOrThrow() } } - private fun createReplica(myAddress: HostAndPort, clusterAddress: HostAndPort? = null): CompletableFuture { + private fun createReplica(myAddress: NetworkHostAndPort, clusterAddress: NetworkHostAndPort? = null): CompletableFuture { val storage = Storage.builder().withStorageLevel(StorageLevel.MEMORY).build() val address = Address(myAddress.host, myAddress.port) diff --git a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt index f66506808e..22f54033f3 100644 --- a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt +++ b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt @@ -1,7 +1,6 @@ package net.corda.attachmentdemo import co.paralleluniverse.fibers.Suspendable -import com.google.common.net.HostAndPort import joptsimple.OptionParser import net.corda.client.rpc.CordaRPCClient import net.corda.core.contracts.Contract @@ -53,14 +52,14 @@ fun main(args: Array) { val role = options.valueOf(roleArg)!! when (role) { Role.SENDER -> { - val host = HostAndPort.fromString("localhost:10006") + val host = NetworkHostAndPort("localhost", 10006) println("Connecting to sender node ($host)") CordaRPCClient(host).start("demo", "demo").use { sender(it.proxy) } } Role.RECIPIENT -> { - val host = HostAndPort.fromString("localhost:10009") + val host = NetworkHostAndPort("localhost", 10009) println("Connecting to the recipient node ($host)") CordaRPCClient(host).start("demo", "demo").use { recipient(it.proxy) diff --git a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt index 3f9622d293..1517af2424 100644 --- a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt +++ b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt @@ -1,12 +1,12 @@ package net.corda.bank -import com.google.common.net.HostAndPort import joptsimple.OptionParser import net.corda.bank.api.BankOfCordaClientApi import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceType import net.corda.core.transactions.SignedTransaction +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.DUMMY_NOTARY import net.corda.flows.CashExitFlow import net.corda.flows.CashPaymentFlow @@ -72,13 +72,13 @@ private class BankOfCordaDriver { when (role) { Role.ISSUE_CASH_RPC -> { println("Requesting Cash via RPC ...") - val result = BankOfCordaClientApi(HostAndPort.fromString("localhost:10006")).requestRPCIssue(requestParams) + val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10006)).requestRPCIssue(requestParams) if (result is SignedTransaction) println("Success!! You transaction receipt is ${result.tx.id}") } Role.ISSUE_CASH_WEB -> { println("Requesting Cash via Web ...") - val result = BankOfCordaClientApi(HostAndPort.fromString("localhost:10007")).requestWebIssue(requestParams) + val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10007)).requestWebIssue(requestParams) if (result) println("Successfully processed Cash Issue request") } diff --git a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt index 7c5563d323..f8bf5df778 100644 --- a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt +++ b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt @@ -1,6 +1,5 @@ package net.corda.bank.api -import com.google.common.net.HostAndPort import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams import net.corda.client.rpc.CordaRPCClient import net.corda.core.contracts.Amount @@ -9,13 +8,14 @@ import net.corda.core.getOrThrow import net.corda.core.messaging.startFlow import net.corda.core.utilities.OpaqueBytes import net.corda.core.transactions.SignedTransaction +import net.corda.core.utilities.NetworkHostAndPort import net.corda.flows.IssuerFlow.IssuanceRequester import net.corda.testing.http.HttpApi /** * Interface for communicating with Bank of Corda node */ -class BankOfCordaClientApi(val hostAndPort: HostAndPort) { +class BankOfCordaClientApi(val hostAndPort: NetworkHostAndPort) { private val apiRoot = "api/bank" /** * HTTP API diff --git a/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt b/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt index ce8cfee139..ac93b3ec0b 100644 --- a/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt +++ b/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt @@ -1,11 +1,11 @@ package net.corda.irs -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import net.corda.client.rpc.CordaRPCClient import net.corda.core.getOrThrow import net.corda.core.node.services.ServiceInfo import net.corda.core.toFuture +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.DUMMY_BANK_A import net.corda.testing.DUMMY_BANK_B import net.corda.testing.DUMMY_NOTARY @@ -101,7 +101,7 @@ class IRSDemoTest : IntegrationTestCategory { assertThat(nodeApi.postJson("deals", tradeFile)).isTrue() } - private fun runUploadRates(host: HostAndPort) { + private fun runUploadRates(host: NetworkHostAndPort) { println("Running upload rates against $host") val fileContents = loadResourceFile("net/corda/irs/simulation/example.rates.txt") val url = URL("http://$host/api/irs/fixes") diff --git a/samples/irs-demo/src/test/kotlin/net/corda/irs/IRSDemo.kt b/samples/irs-demo/src/test/kotlin/net/corda/irs/IRSDemo.kt index fa4a2f020a..5b9f023933 100644 --- a/samples/irs-demo/src/test/kotlin/net/corda/irs/IRSDemo.kt +++ b/samples/irs-demo/src/test/kotlin/net/corda/irs/IRSDemo.kt @@ -2,8 +2,8 @@ package net.corda.irs -import com.google.common.net.HostAndPort import joptsimple.OptionParser +import net.corda.core.utilities.NetworkHostAndPort import kotlin.system.exitProcess enum class Role { @@ -29,9 +29,9 @@ fun main(args: Array) { val role = options.valueOf(roleArg)!! val value = options.valueOf(valueArg) when (role) { - Role.UploadRates -> IRSDemoClientApi(HostAndPort.fromString("localhost:10004")).runUploadRates() - Role.Trade -> IRSDemoClientApi(HostAndPort.fromString("localhost:10007")).runTrade(value) - Role.Date -> IRSDemoClientApi(HostAndPort.fromString("localhost:10010")).runDateChange(value) + Role.UploadRates -> IRSDemoClientApi(NetworkHostAndPort("localhost", 10004)).runUploadRates() + Role.Trade -> IRSDemoClientApi(NetworkHostAndPort("localhost", 10007)).runTrade(value) + Role.Date -> IRSDemoClientApi(NetworkHostAndPort("localhost", 10010)).runDateChange(value) } } diff --git a/samples/irs-demo/src/test/kotlin/net/corda/irs/IrsDemoClientApi.kt b/samples/irs-demo/src/test/kotlin/net/corda/irs/IrsDemoClientApi.kt index c983115559..31b3ccf13b 100644 --- a/samples/irs-demo/src/test/kotlin/net/corda/irs/IrsDemoClientApi.kt +++ b/samples/irs-demo/src/test/kotlin/net/corda/irs/IrsDemoClientApi.kt @@ -1,6 +1,6 @@ package net.corda.irs -import com.google.common.net.HostAndPort +import net.corda.core.utilities.NetworkHostAndPort import net.corda.irs.utilities.uploadFile import net.corda.testing.http.HttpApi import org.apache.commons.io.IOUtils @@ -9,7 +9,7 @@ import java.net.URL /** * Interface for communicating with nodes running the IRS demo. */ -class IRSDemoClientApi(private val hostAndPort: HostAndPort) { +class IRSDemoClientApi(private val hostAndPort: NetworkHostAndPort) { private val api = HttpApi.fromHostAndPort(hostAndPort, apiRoot) fun runTrade(tradeId: String): Boolean { diff --git a/samples/notary-demo/src/main/kotlin/net/corda/demorun/util/DemoUtils.kt b/samples/notary-demo/src/main/kotlin/net/corda/demorun/util/DemoUtils.kt index 45d25fdb43..6aa3cc1aa4 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/demorun/util/DemoUtils.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/demorun/util/DemoUtils.kt @@ -1,9 +1,9 @@ package net.corda.demorun.util -import com.google.common.net.HostAndPort import net.corda.cordform.CordformDefinition import net.corda.cordform.CordformNode import net.corda.core.node.services.ServiceInfo +import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.User import org.bouncycastle.asn1.x500.X500Name @@ -21,6 +21,6 @@ fun CordformNode.advertisedServices(vararg services: ServiceInfo) { advertisedServices = services.map { it.toString() } } -fun CordformNode.notaryClusterAddresses(vararg addresses: HostAndPort) { +fun CordformNode.notaryClusterAddresses(vararg addresses: NetworkHostAndPort) { notaryClusterAddresses = addresses.map { it.toString() } } diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt index 8abca6e424..3f6af7fc9f 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt @@ -1,6 +1,5 @@ package net.corda.notarydemo -import com.google.common.net.HostAndPort import net.corda.core.div import net.corda.core.node.services.ServiceInfo import net.corda.testing.ALICE @@ -14,6 +13,7 @@ import net.corda.cordform.CordformContext import net.corda.cordform.CordformNode import net.corda.core.stream import net.corda.core.toTypedArray +import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.transactions.minCorrectReplicas import org.bouncycastle.asn1.x500.X500Name @@ -38,7 +38,7 @@ object BFTNotaryCordform : CordformDefinition("build" / "notary-demo-nodes", not p2pPort(10005) rpcPort(10006) } - val clusterAddresses = (0 until clusterSize).stream().mapToObj { HostAndPort.fromParts("localhost", 11000 + it * 10) }.toTypedArray() + val clusterAddresses = (0 until clusterSize).stream().mapToObj { NetworkHostAndPort("localhost", 11000 + it * 10) }.toTypedArray() fun notaryNode(replicaId: Int, configure: CordformNode.() -> Unit) = node { name(notaryNames[replicaId]) advertisedServices(advertisedService) diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/Notarise.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/Notarise.kt index f85c9846b2..855fd1dd27 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/Notarise.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/Notarise.kt @@ -1,6 +1,5 @@ package net.corda.notarydemo -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture import net.corda.client.rpc.CordaRPCClient @@ -11,13 +10,14 @@ import net.corda.core.map import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.startFlow import net.corda.core.transactions.SignedTransaction +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.BOB import net.corda.notarydemo.flows.DummyIssueAndMove import net.corda.notarydemo.flows.RPCStartableNotaryFlowClient import kotlin.streams.asSequence fun main(args: Array) { - val address = HostAndPort.fromParts("localhost", 10003) + val address = NetworkHostAndPort("localhost", 10003) println("Connecting to the recipient node ($address)") CordaRPCClient(address).start(notaryDemoUser.username, notaryDemoUser.password).use { NotaryDemoClientApi(it.proxy).notarise(10) diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt index 1915d9ff69..10a94ea6a4 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt @@ -1,6 +1,5 @@ package net.corda.notarydemo -import com.google.common.net.HostAndPort import net.corda.core.crypto.appendToCommonName import net.corda.core.div import net.corda.core.node.services.ServiceInfo @@ -13,6 +12,7 @@ import net.corda.node.utilities.ServiceIdentityGenerator import net.corda.cordform.CordformDefinition import net.corda.cordform.CordformContext import net.corda.cordform.CordformNode +import net.corda.core.utilities.NetworkHostAndPort import net.corda.demorun.runNodes import net.corda.demorun.util.node import org.bouncycastle.asn1.x500.X500Name @@ -49,7 +49,7 @@ object RaftNotaryCordform : CordformDefinition("build" / "notary-demo-nodes", no p2pPort(10009) rpcPort(10010) } - val clusterAddress = HostAndPort.fromParts("localhost", 10008) // Otherwise each notary forms its own cluster. + val clusterAddress = NetworkHostAndPort("localhost", 10008) // Otherwise each notary forms its own cluster. notaryNode(1) { notaryNodePort(10012) p2pPort(10013) diff --git a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TraderDemo.kt b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TraderDemo.kt index bc84fdb459..7fba92d602 100644 --- a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TraderDemo.kt +++ b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TraderDemo.kt @@ -1,9 +1,9 @@ package net.corda.traderdemo -import com.google.common.net.HostAndPort import joptsimple.OptionParser import net.corda.client.rpc.CordaRPCClient import net.corda.core.contracts.DOLLARS +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.DUMMY_BANK_A import net.corda.core.utilities.loggerFor import org.slf4j.Logger @@ -42,12 +42,12 @@ private class TraderDemo { // will contact the buyer and actually make something happen. val role = options.valueOf(roleArg)!! if (role == Role.BUYER) { - val host = HostAndPort.fromString("localhost:10006") + val host = NetworkHostAndPort("localhost", 10006) CordaRPCClient(host).start("demo", "demo").use { TraderDemoClientApi(it.proxy).runBuyer() } } else { - val host = HostAndPort.fromString("localhost:10009") + val host = NetworkHostAndPort("localhost", 10009) CordaRPCClient(host).use("demo", "demo") { TraderDemoClientApi(it.proxy).runSeller(1000.DOLLARS, DUMMY_BANK_A.name) } diff --git a/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeProcess.kt b/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeProcess.kt index c939bd4758..f7a56f2be9 100644 --- a/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeProcess.kt +++ b/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeProcess.kt @@ -1,10 +1,10 @@ package net.corda.smoketesting -import com.google.common.net.HostAndPort import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCConnection import net.corda.core.createDirectories import net.corda.core.div +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import java.nio.file.Path import java.nio.file.Paths @@ -60,7 +60,7 @@ class NodeProcess( confFile.writeText(config.toText()) val process = startNode(nodeDir) - val client = CordaRPCClient(HostAndPort.fromParts("localhost", config.rpcPort)) + val client = CordaRPCClient(NetworkHostAndPort("localhost", config.rpcPort)) val user = config.users[0] val setupExecutor = Executors.newSingleThreadScheduledExecutor() diff --git a/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt b/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt index bffece9c57..6c36d638c6 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt @@ -3,7 +3,6 @@ package net.corda.testing -import com.google.common.net.HostAndPort import com.nhaarman.mockito_kotlin.spy import com.nhaarman.mockito_kotlin.whenever import net.corda.core.contracts.StateRef @@ -14,6 +13,7 @@ import net.corda.core.node.ServiceHub import net.corda.core.node.services.IdentityService import net.corda.core.utilities.OpaqueBytes import net.corda.core.transactions.TransactionBuilder +import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.config.VerifierType import net.corda.node.services.config.configureDevKeyAndTrustStores @@ -88,7 +88,7 @@ val ALL_TEST_KEYS: List get() = listOf(MEGA_CORP_KEY, MINI_CORP_KEY, AL val MOCK_IDENTITIES = listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_NOTARY_IDENTITY) val MOCK_IDENTITY_SERVICE: IdentityService get() = InMemoryIdentityService(MOCK_IDENTITIES, emptyMap(), DUMMY_CA.certificate.cert) -val MOCK_HOST_AND_PORT = HostAndPort.fromParts("mockHost", 30000) +val MOCK_HOST_AND_PORT = NetworkHostAndPort("mockHost", 30000) fun generateStateRef() = StateRef(SecureHash.randomSHA256(), 0) @@ -99,7 +99,7 @@ private val freePortCounter = AtomicInteger(30000) * Unsafe for getting multiple ports! * Use [getFreeLocalPorts] for getting multiple ports. */ -fun freeLocalHostAndPort(): HostAndPort = HostAndPort.fromParts("localhost", freePort()) +fun freeLocalHostAndPort() = NetworkHostAndPort("localhost", freePort()) /** * Returns a free port. @@ -115,9 +115,9 @@ fun freePort(): Int = freePortCounter.getAndAccumulate(0) { prev, _ -> 30000 + ( * Unlikely, but in the time between running this function and handing the ports * to the Node, some other process else could allocate the returned ports. */ -fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List { +fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List { val freePort = freePortCounter.getAndAccumulate(0) { prev, _ -> 30000 + (prev - 30000 + numberToAlloc) % 10000 } - return (freePort .. freePort + numberToAlloc - 1).map { HostAndPort.fromParts(hostName, it) } + return (freePort .. freePort + numberToAlloc - 1).map { NetworkHostAndPort(hostName, it) } } /** diff --git a/test-utils/src/main/kotlin/net/corda/testing/NodeApi.kt b/test-utils/src/main/kotlin/net/corda/testing/NodeApi.kt deleted file mode 100644 index c812beec84..0000000000 --- a/test-utils/src/main/kotlin/net/corda/testing/NodeApi.kt +++ /dev/null @@ -1,62 +0,0 @@ -package net.corda.testing - -import com.google.common.net.HostAndPort -import java.io.IOException -import java.io.InputStreamReader -import java.net.ConnectException -import java.net.HttpURLConnection -import java.net.SocketException -import java.net.URL -import kotlin.test.assertEquals - -class NodeApi { - class NodeDidNotStartException(message: String) : Exception(message) - - companion object { - // Increased timeout to two minutes. - val NODE_WAIT_RETRY_COUNT: Int = 600 - val NODE_WAIT_RETRY_DELAY_MS: Long = 200 - - fun ensureNodeStartsOrKill(proc: Process, nodeWebserverAddr: HostAndPort) { - try { - assertEquals(proc.isAlive, true) - waitForNodeStartup(nodeWebserverAddr) - } catch (e: Throwable) { - println("Forcibly killing node process") - proc.destroyForcibly() - throw e - } - } - - private fun waitForNodeStartup(nodeWebserverAddr: HostAndPort) { - val url = URL("http://$nodeWebserverAddr/api/status") - var retries = 0 - var respCode: Int - do { - retries++ - val err = try { - val conn = url.openConnection() as HttpURLConnection - conn.requestMethod = "GET" - respCode = conn.responseCode - InputStreamReader(conn.inputStream).readLines().joinToString { it } - } catch(e: ConnectException) { - // This is to be expected while it loads up - respCode = 404 - "Node hasn't started" - } catch(e: SocketException) { - respCode = -1 - "Could not connect: $e" - } catch (e: IOException) { - respCode = -1 - "IOException: $e" - } - - if (retries > NODE_WAIT_RETRY_COUNT) { - throw NodeDidNotStartException("The node did not start: " + err) - } - - Thread.sleep(NODE_WAIT_RETRY_DELAY_MS) - } while (respCode != 200) - } - } -} diff --git a/test-utils/src/main/kotlin/net/corda/testing/RPCDriver.kt b/test-utils/src/main/kotlin/net/corda/testing/RPCDriver.kt index 2276f19301..af6844273b 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/RPCDriver.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/RPCDriver.kt @@ -1,6 +1,5 @@ package net.corda.testing -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.ListenableFuture import net.corda.client.mock.Generator import net.corda.client.mock.generateOrFail @@ -11,6 +10,8 @@ import net.corda.client.rpc.internal.RPCClientConfiguration import net.corda.core.div import net.corda.core.map import net.corda.core.messaging.RPCOps +import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.parseNetworkHostAndPort import net.corda.core.crypto.random63BitValue import net.corda.testing.driver.ProcessUtilities import net.corda.node.services.RPCUserService @@ -109,7 +110,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface { maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE, maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE, configuration: RPCServerConfiguration = RPCServerConfiguration.default, - customPort: HostAndPort? = null, + customPort: NetworkHostAndPort? = null, ops : I ) : ListenableFuture @@ -124,7 +125,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface { */ fun startRpcClient( rpcOpsClass: Class, - rpcAddress: HostAndPort, + rpcAddress: NetworkHostAndPort, username: String = rpcTestUser.username, password: String = rpcTestUser.password, configuration: RPCClientConfiguration = RPCClientConfiguration.default @@ -140,7 +141,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface { */ fun startRandomRpcClient( rpcOpsClass: Class, - rpcAddress: HostAndPort, + rpcAddress: NetworkHostAndPort, username: String = rpcTestUser.username, password: String = rpcTestUser.password ): ListenableFuture @@ -153,7 +154,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface { * @param password The password to authenticate with. */ fun startArtemisSession( - rpcAddress: HostAndPort, + rpcAddress: NetworkHostAndPort, username: String = rpcTestUser.username, password: String = rpcTestUser.password ): ClientSession @@ -163,7 +164,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface { rpcUser: User = rpcTestUser, maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE, maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE, - customPort: HostAndPort? = null + customPort: NetworkHostAndPort? = null ): ListenableFuture fun startInVmRpcBroker( @@ -186,12 +187,12 @@ inline fun RPCDriverExposedDSLInterface.startInVmRpcClient( configuration: RPCClientConfiguration = RPCClientConfiguration.default ) = startInVmRpcClient(I::class.java, username, password, configuration) inline fun RPCDriverExposedDSLInterface.startRandomRpcClient( - hostAndPort: HostAndPort, + hostAndPort: NetworkHostAndPort, username: String = rpcTestUser.username, password: String = rpcTestUser.password ) = startRandomRpcClient(I::class.java, hostAndPort, username, password) inline fun RPCDriverExposedDSLInterface.startRpcClient( - rpcAddress: HostAndPort, + rpcAddress: NetworkHostAndPort, username: String = rpcTestUser.username, password: String = rpcTestUser.password, configuration: RPCClientConfiguration = RPCClientConfiguration.default @@ -200,7 +201,7 @@ inline fun RPCDriverExposedDSLInterface.startRpcClient( interface RPCDriverInternalDSLInterface : DriverDSLInternalInterface, RPCDriverExposedDSLInterface data class RpcBrokerHandle( - val hostAndPort: HostAndPort?, /** null if this is an InVM broker */ + val hostAndPort: NetworkHostAndPort?,/** null if this is an InVM broker */ val clientTransportConfiguration: TransportConfiguration, val serverControl: ActiveMQServerControl ) @@ -306,7 +307,7 @@ data class RPCDriverDSL( configureCommonSettings(maxFileSize, maxBufferedBytesPerClient) } } - fun createRpcServerArtemisConfig(maxFileSize: Int, maxBufferedBytesPerClient: Long, baseDirectory: Path, hostAndPort: HostAndPort): Configuration { + fun createRpcServerArtemisConfig(maxFileSize: Int, maxBufferedBytesPerClient: Long, baseDirectory: Path, hostAndPort: NetworkHostAndPort): Configuration { val connectionDirection = ConnectionDirection.Inbound(acceptorFactoryClassName = NettyAcceptorFactory::class.java.name) return ConfigurationImpl().apply { val artemisDir = "$baseDirectory/artemis" @@ -318,7 +319,7 @@ data class RPCDriverDSL( } } val inVmClientTransportConfiguration = TransportConfiguration(InVMConnectorFactory::class.java.name) - fun createNettyClientTransportConfiguration(hostAndPort: HostAndPort): TransportConfiguration { + fun createNettyClientTransportConfiguration(hostAndPort: NetworkHostAndPort): TransportConfiguration { return ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), hostAndPort, null) } } @@ -366,7 +367,7 @@ data class RPCDriverDSL( maxFileSize: Int, maxBufferedBytesPerClient: Long, configuration: RPCServerConfiguration, - customPort: HostAndPort?, + customPort: NetworkHostAndPort?, ops: I ): ListenableFuture { return startRpcBroker(serverName, rpcUser, maxFileSize, maxBufferedBytesPerClient, customPort).map { broker -> @@ -376,7 +377,7 @@ data class RPCDriverDSL( override fun startRpcClient( rpcOpsClass: Class, - rpcAddress: HostAndPort, + rpcAddress: NetworkHostAndPort, username: String, password: String, configuration: RPCClientConfiguration @@ -391,7 +392,7 @@ data class RPCDriverDSL( } } - override fun startRandomRpcClient(rpcOpsClass: Class, rpcAddress: HostAndPort, username: String, password: String): ListenableFuture { + override fun startRandomRpcClient(rpcOpsClass: Class, rpcAddress: NetworkHostAndPort, username: String, password: String): ListenableFuture { val processFuture = driverDSL.executorService.submit { ProcessUtilities.startJavaProcess(listOf(rpcOpsClass.name, rpcAddress.toString(), username, password)) } @@ -399,7 +400,7 @@ data class RPCDriverDSL( return processFuture } - override fun startArtemisSession(rpcAddress: HostAndPort, username: String, password: String): ClientSession { + override fun startArtemisSession(rpcAddress: NetworkHostAndPort, username: String, password: String): ClientSession { val locator = ActiveMQClient.createServerLocatorWithoutHA(createNettyClientTransportConfiguration(rpcAddress)) val sessionFactory = locator.createSessionFactory() val session = sessionFactory.createSession(username, password, false, true, true, false, DEFAULT_ACK_BATCH_SIZE) @@ -417,7 +418,7 @@ data class RPCDriverDSL( rpcUser: User, maxFileSize: Int, maxBufferedBytesPerClient: Long, - customPort: HostAndPort? + customPort: NetworkHostAndPort? ): ListenableFuture { val hostAndPort = customPort ?: driverDSL.portAllocation.nextHostAndPort() addressMustNotBeBound(driverDSL.executorService, hostAndPort) @@ -506,7 +507,7 @@ class RandomRpcUser { require(args.size == 4) @Suppress("UNCHECKED_CAST") val rpcClass = Class.forName(args[0]) as Class - val hostAndPort = HostAndPort.fromString(args[1]) + val hostAndPort = args[1].parseNetworkHostAndPort() val username = args[2] val password = args[3] val handle = RPCClient(hostAndPort, null).start(rpcClass, username, password) diff --git a/test-utils/src/main/kotlin/net/corda/testing/driver/Driver.kt b/test-utils/src/main/kotlin/net/corda/testing/driver/Driver.kt index 3d21d4c827..c176242b41 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/driver/Driver.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/driver/Driver.kt @@ -2,7 +2,6 @@ package net.corda.testing.driver -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.* import com.typesafe.config.Config import com.typesafe.config.ConfigRenderOptions @@ -20,8 +19,10 @@ import net.corda.core.messaging.CordaRPCOps import net.corda.core.node.NodeInfo import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceType +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.WHITESPACE import net.corda.core.utilities.loggerFor +import net.corda.core.utilities.parseNetworkHostAndPort import net.corda.node.internal.Node import net.corda.node.internal.NodeStartup import net.corda.node.serialization.NodeClock @@ -167,13 +168,13 @@ sealed class NodeHandle { abstract val nodeInfo: NodeInfo abstract val rpc: CordaRPCOps abstract val configuration: FullNodeConfiguration - abstract val webAddress: HostAndPort + abstract val webAddress: NetworkHostAndPort data class OutOfProcess( override val nodeInfo: NodeInfo, override val rpc: CordaRPCOps, override val configuration: FullNodeConfiguration, - override val webAddress: HostAndPort, + override val webAddress: NetworkHostAndPort, val debugPort: Int?, val process: Process ) : NodeHandle() @@ -182,7 +183,7 @@ sealed class NodeHandle { override val nodeInfo: NodeInfo, override val rpc: CordaRPCOps, override val configuration: FullNodeConfiguration, - override val webAddress: HostAndPort, + override val webAddress: NetworkHostAndPort, val node: Node, val nodeThread: Thread ) : NodeHandle() @@ -191,13 +192,13 @@ sealed class NodeHandle { } data class WebserverHandle( - val listenAddress: HostAndPort, + val listenAddress: NetworkHostAndPort, val process: Process ) sealed class PortAllocation { abstract fun nextPort(): Int - fun nextHostAndPort(): HostAndPort = HostAndPort.fromParts("localhost", nextPort()) + fun nextHostAndPort() = NetworkHostAndPort("localhost", nextPort()) class Incremental(startingPort: Int) : PortAllocation() { val portCounter = AtomicInteger(startingPort) @@ -298,16 +299,16 @@ fun getTimestampAsDirectoryName(): String { return DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(UTC).format(Instant.now()) } -class ListenProcessDeathException(hostAndPort: HostAndPort, listenProcess: Process) : Exception("The process that was expected to listen on $hostAndPort has died with status: ${listenProcess.exitValue()}") +class ListenProcessDeathException(hostAndPort: NetworkHostAndPort, listenProcess: Process) : Exception("The process that was expected to listen on $hostAndPort has died with status: ${listenProcess.exitValue()}") /** * @throws ListenProcessDeathException if [listenProcess] dies before the check succeeds, i.e. the check can't succeed as intended. */ -fun addressMustBeBound(executorService: ScheduledExecutorService, hostAndPort: HostAndPort, listenProcess: Process? = null) { +fun addressMustBeBound(executorService: ScheduledExecutorService, hostAndPort: NetworkHostAndPort, listenProcess: Process? = null) { addressMustBeBoundFuture(executorService, hostAndPort, listenProcess).getOrThrow() } -fun addressMustBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: HostAndPort, listenProcess: Process? = null): ListenableFuture { +fun addressMustBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: NetworkHostAndPort, listenProcess: Process? = null): ListenableFuture { return poll(executorService, "address $hostAndPort to bind") { if (listenProcess != null && !listenProcess.isAlive) { throw ListenProcessDeathException(hostAndPort, listenProcess) @@ -321,11 +322,11 @@ fun addressMustBeBoundFuture(executorService: ScheduledExecutorService, hostAndP } } -fun addressMustNotBeBound(executorService: ScheduledExecutorService, hostAndPort: HostAndPort) { +fun addressMustNotBeBound(executorService: ScheduledExecutorService, hostAndPort: NetworkHostAndPort) { addressMustNotBeBoundFuture(executorService, hostAndPort).getOrThrow() } -fun addressMustNotBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: HostAndPort): ListenableFuture { +fun addressMustNotBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: NetworkHostAndPort): ListenableFuture { return poll(executorService, "address $hostAndPort to unbind") { try { Socket(hostAndPort.host, hostAndPort.port).close() @@ -514,7 +515,7 @@ class DriverDSL( _executorService?.shutdownNow() } - private fun establishRpc(nodeAddress: HostAndPort, sslConfig: SSLConfiguration, processDeathFuture: ListenableFuture): ListenableFuture { + private fun establishRpc(nodeAddress: NetworkHostAndPort, sslConfig: SSLConfiguration, processDeathFuture: ListenableFuture): ListenableFuture { val client = CordaRPCClient(nodeAddress, sslConfig) val connectionFuture = poll(executorService, "RPC connection") { try { @@ -544,9 +545,9 @@ class DriverDSL( } } is NetworkMapStartStrategy.Nominated -> { - serviceConfig(HostAndPort.fromString(networkMapCandidates.filter { + serviceConfig(networkMapCandidates.filter { it.name == legalName.toString() - }.single().config.getString("p2pAddress"))).let { + }.single().config.getString("p2pAddress").parseNetworkHostAndPort()).let { { nodeName: X500Name -> if (nodeName == legalName) null else it } } } @@ -704,7 +705,7 @@ class DriverDSL( return startNodeInternal(config, webAddress, startInProcess) } - private fun startNodeInternal(config: Config, webAddress: HostAndPort, startInProcess: Boolean?): ListenableFuture { + private fun startNodeInternal(config: Config, webAddress: NetworkHostAndPort, startInProcess: Boolean?): ListenableFuture { val nodeConfiguration = config.parseAs() if (startInProcess ?: startNodesInProcess) { val nodeAndThreadFuture = startInProcessNode(executorService, nodeConfiguration, config) diff --git a/test-utils/src/main/kotlin/net/corda/testing/driver/NetworkMapStartStrategy.kt b/test-utils/src/main/kotlin/net/corda/testing/driver/NetworkMapStartStrategy.kt index 62248682ef..e185930198 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/driver/NetworkMapStartStrategy.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/driver/NetworkMapStartStrategy.kt @@ -1,13 +1,13 @@ package net.corda.testing.driver -import com.google.common.net.HostAndPort +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.DUMMY_MAP import org.bouncycastle.asn1.x500.X500Name sealed class NetworkMapStartStrategy { internal abstract val startDedicated: Boolean internal abstract val legalName: X500Name - internal fun serviceConfig(address: HostAndPort) = mapOf( + internal fun serviceConfig(address: NetworkHostAndPort) = mapOf( "address" to address.toString(), "legalName" to legalName.toString() ) diff --git a/test-utils/src/main/kotlin/net/corda/testing/http/HttpApi.kt b/test-utils/src/main/kotlin/net/corda/testing/http/HttpApi.kt index 42b3221264..dbbe571af5 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/http/HttpApi.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/http/HttpApi.kt @@ -1,7 +1,7 @@ package net.corda.testing.http import com.fasterxml.jackson.databind.ObjectMapper -import com.google.common.net.HostAndPort +import net.corda.core.utilities.NetworkHostAndPort import java.net.URL class HttpApi(val root: URL, val mapper: ObjectMapper = defaultMapper) { @@ -27,7 +27,7 @@ class HttpApi(val root: URL, val mapper: ObjectMapper = defaultMapper) { private fun toJson(any: Any) = any as? String ?: HttpUtils.defaultMapper.writeValueAsString(any) companion object { - fun fromHostAndPort(hostAndPort: HostAndPort, base: String, protocol: String = "http", mapper: ObjectMapper = defaultMapper): HttpApi + fun fromHostAndPort(hostAndPort: NetworkHostAndPort, base: String, protocol: String = "http", mapper: ObjectMapper = defaultMapper): HttpApi = HttpApi(URL("$protocol://$hostAndPort/$base/"), mapper) private val defaultMapper: ObjectMapper by lazy { net.corda.jackson.JacksonSupport.createNonRpcMapper() diff --git a/test-utils/src/main/kotlin/net/corda/testing/messaging/SimpleMQClient.kt b/test-utils/src/main/kotlin/net/corda/testing/messaging/SimpleMQClient.kt index dd521c8671..12ac044952 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/messaging/SimpleMQClient.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/messaging/SimpleMQClient.kt @@ -1,6 +1,6 @@ package net.corda.testing.messaging -import com.google.common.net.HostAndPort +import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.ArtemisMessagingComponent import net.corda.nodeapi.ArtemisTcpTransport import net.corda.nodeapi.ConnectionDirection @@ -12,7 +12,7 @@ import org.bouncycastle.asn1.x500.X500Name /** * As the name suggests this is a simple client for connecting to MQ brokers. */ -class SimpleMQClient(val target: HostAndPort, +class SimpleMQClient(val target: NetworkHostAndPort, override val config: SSLConfiguration? = configureTestSSL(DEFAULT_MQ_LEGAL_NAME)) : ArtemisMessagingComponent() { companion object { val DEFAULT_MQ_LEGAL_NAME = X500Name("CN=SimpleMQClient,O=R3,OU=corda,L=London,C=GB") diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/MockNetworkMapCache.kt b/test-utils/src/main/kotlin/net/corda/testing/node/MockNetworkMapCache.kt index c4de528dd1..a9b26e75bb 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/MockNetworkMapCache.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/MockNetworkMapCache.kt @@ -1,12 +1,12 @@ package net.corda.testing.node import co.paralleluniverse.common.util.VisibleForTesting -import com.google.common.net.HostAndPort import net.corda.core.crypto.entropyToKeyPair import net.corda.core.identity.Party import net.corda.core.node.NodeInfo import net.corda.core.node.ServiceHub import net.corda.core.node.services.NetworkMapCache +import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.network.InMemoryNetworkMapCache import net.corda.testing.getTestPartyAndCertificate import net.corda.testing.getTestX509Name @@ -21,8 +21,8 @@ class MockNetworkMapCache(serviceHub: ServiceHub) : InMemoryNetworkMapCache(serv private companion object { val BANK_C = getTestPartyAndCertificate(getTestX509Name("Bank C"), entropyToKeyPair(BigInteger.valueOf(1000)).public) val BANK_D = getTestPartyAndCertificate(getTestX509Name("Bank D"), entropyToKeyPair(BigInteger.valueOf(2000)).public) - val BANK_C_ADDR: HostAndPort = HostAndPort.fromParts("bankC", 8080) - val BANK_D_ADDR: HostAndPort = HostAndPort.fromParts("bankD", 8080) + val BANK_C_ADDR = NetworkHostAndPort("bankC", 8080) + val BANK_D_ADDR = NetworkHostAndPort("bankD", 8080) } override val changed: Observable = PublishSubject.create() diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/MockNode.kt b/test-utils/src/main/kotlin/net/corda/testing/node/MockNode.kt index 0dfd96d2fe..aaf1abb4ad 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/MockNode.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/MockNode.kt @@ -2,7 +2,6 @@ package net.corda.testing.node import com.google.common.jimfs.Configuration.unix import com.google.common.jimfs.Jimfs -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture import com.nhaarman.mockito_kotlin.whenever @@ -17,6 +16,7 @@ import net.corda.core.messaging.RPCOps import net.corda.core.messaging.SingleMessageRecipient import net.corda.core.node.CordaPluginRegistry import net.corda.core.node.ServiceEntry +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.node.WorldMapLocation import net.corda.core.node.services.IdentityService import net.corda.core.node.services.KeyManagementService @@ -222,7 +222,7 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false, override fun makeTransactionVerifierService() = InMemoryTransactionVerifierService(1) - override fun myAddresses(): List = listOf(HostAndPort.fromHost("mockHost")) + override fun myAddresses() = emptyList() override fun start(): MockNode { super.start() diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/MockServices.kt b/test-utils/src/main/kotlin/net/corda/testing/node/MockServices.kt index 804e8520b7..9e1fba3192 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/MockServices.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/MockServices.kt @@ -1,6 +1,5 @@ package net.corda.testing.node -import com.google.common.net.HostAndPort import net.corda.core.contracts.Attachment import net.corda.core.crypto.* import net.corda.core.flows.StateMachineRunId @@ -76,7 +75,7 @@ open class MockServices(vararg val keys: KeyPair) : ServiceHub { override val clock: Clock get() = Clock.systemUTC() override val myInfo: NodeInfo get() { val identity = getTestPartyAndCertificate(MEGA_CORP.name, key.public) - return NodeInfo(listOf(HostAndPort.fromHost("localhost")), identity, setOf(identity), 1) + return NodeInfo(emptyList(), identity, setOf(identity), 1) } override val transactionVerifierService: TransactionVerifierService get() = InMemoryTransactionVerifierService(2) diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt b/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt index 2527ae8e0b..d006e380ac 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/SimpleNode.kt @@ -1,13 +1,13 @@ package net.corda.testing.node import com.codahale.metrics.MetricRegistry -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.SettableFuture import net.corda.core.crypto.commonName import net.corda.core.crypto.generateKeyPair import net.corda.core.messaging.RPCOps import net.corda.core.node.services.IdentityService import net.corda.core.node.services.KeyManagementService +import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.RPCUserServiceImpl import net.corda.node.services.api.MonitoringService import net.corda.node.services.config.NodeConfiguration @@ -30,8 +30,8 @@ import kotlin.concurrent.thread * This is a bare-bones node which can only send and receive messages. It doesn't register with a network map service or * any other such task that would make it functional in a network and thus left to the user to do so manually. */ -class SimpleNode(val config: NodeConfiguration, val address: HostAndPort = freeLocalHostAndPort(), - rpcAddress: HostAndPort = freeLocalHostAndPort(), +class SimpleNode(val config: NodeConfiguration, val address: NetworkHostAndPort = freeLocalHostAndPort(), + rpcAddress: NetworkHostAndPort = freeLocalHostAndPort(), trustRoot: X509Certificate) : AutoCloseable { private val databaseWithCloseable: Pair = configureDatabase(config.dataSourceProperties) diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/model/InstallFactory.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/model/InstallFactory.kt index c546657e7b..cfec8b3757 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/model/InstallFactory.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/model/InstallFactory.kt @@ -1,7 +1,7 @@ package net.corda.demobench.model -import com.google.common.net.HostAndPort import com.typesafe.config.Config +import net.corda.core.utilities.parseNetworkHostAndPort import org.bouncycastle.asn1.x500.X500Name import tornadofx.* import java.io.IOException @@ -46,7 +46,7 @@ class InstallFactory : Controller() { private fun Config.parsePort(path: String): Int { val address = this.getString(path) - val port = HostAndPort.fromString(address).port + val port = address.parseNetworkHostAndPort().port require(nodeController.isPortValid(port), { "Invalid port $port from '$path'." }) return port } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt index e3d1f95c13..baeb40ba59 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt @@ -1,9 +1,9 @@ package net.corda.demobench.rpc -import com.google.common.net.HostAndPort import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCConnection import net.corda.core.messaging.CordaRPCOps +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.demobench.model.NodeConfig import java.util.* @@ -16,7 +16,7 @@ class NodeRPC(config: NodeConfig, start: (NodeConfig, CordaRPCOps) -> Unit, invo val oneSecond = SECONDS.toMillis(1) } - private val rpcClient = CordaRPCClient(HostAndPort.fromParts("localhost", config.rpcPort)) + private val rpcClient = CordaRPCClient(NetworkHostAndPort("localhost", config.rpcPort)) private var rpcConnection: CordaRPCConnection? = null private val timer = Timer() diff --git a/tools/demobench/src/test/kotlin/net/corda/demobench/model/NodeConfigTest.kt b/tools/demobench/src/test/kotlin/net/corda/demobench/model/NodeConfigTest.kt index 06fcfad0de..904a90f717 100644 --- a/tools/demobench/src/test/kotlin/net/corda/demobench/model/NodeConfigTest.kt +++ b/tools/demobench/src/test/kotlin/net/corda/demobench/model/NodeConfigTest.kt @@ -3,10 +3,10 @@ package net.corda.demobench.model import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature -import com.google.common.net.HostAndPort import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigValueFactory import net.corda.core.div +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.DUMMY_NOTARY import net.corda.node.internal.NetworkMapInfo import net.corda.node.services.config.FullNodeConfiguration @@ -270,5 +270,5 @@ class NodeConfigTest { users = users ) - private fun localPort(port: Int) = HostAndPort.fromParts("localhost", port) + private fun localPort(port: Int) = NetworkHostAndPort("localhost", port) } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/LoginView.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/LoginView.kt index df873028a2..ec0752d6c2 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/LoginView.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/LoginView.kt @@ -1,10 +1,10 @@ package net.corda.explorer.views -import com.google.common.net.HostAndPort import javafx.beans.property.SimpleIntegerProperty import javafx.scene.control.* import net.corda.client.jfx.model.NodeMonitorModel import net.corda.client.jfx.model.objectProperty +import net.corda.core.utilities.NetworkHostAndPort import net.corda.explorer.model.SettingsModel import org.controlsfx.dialog.ExceptionDialog import tornadofx.* @@ -27,8 +27,8 @@ class LoginView : View() { private val port by objectProperty(SettingsModel::portProperty) private val fullscreen by objectProperty(SettingsModel::fullscreenProperty) - fun login(host: String?, port: Int, username: String, password: String) { - getModel().register(HostAndPort.fromParts(host, port), username, password) + fun login(host: String, port: Int, username: String, password: String) { + getModel().register(NetworkHostAndPort(host, port), username, password) } fun login() { diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt index ef84237cbb..80167f0416 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt @@ -1,6 +1,5 @@ package net.corda.loadtest -import com.google.common.net.HostAndPort import com.jcraft.jsch.Buffer import com.jcraft.jsch.Identity import com.jcraft.jsch.IdentityRepository @@ -8,6 +7,7 @@ import com.jcraft.jsch.JSch import com.jcraft.jsch.agentproxy.AgentProxy import com.jcraft.jsch.agentproxy.connector.SSHAgentConnector import com.jcraft.jsch.agentproxy.usocket.JNAUSocketFactory +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.driver.PortAllocation import org.slf4j.LoggerFactory import java.util.* @@ -61,7 +61,7 @@ fun setupJSchWithSshAgent(): JSch { } class ConnectionManager(private val jSch: JSch) { - fun connectToNode(remoteNode: RemoteNode, localTunnelAddress: HostAndPort): NodeConnection { + fun connectToNode(remoteNode: RemoteNode, localTunnelAddress: NetworkHostAndPort): NodeConnection { val session = jSch.getSession(remoteNode.sshUserName, remoteNode.hostname, 22) // We don't check the host fingerprints because they may change often session.setConfig("StrictHostKeyChecking", "no") diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/NodeConnection.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/NodeConnection.kt index 55cd113430..cecca567b4 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/NodeConnection.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/NodeConnection.kt @@ -1,6 +1,5 @@ package net.corda.loadtest -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.ListenableFuture import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.Session @@ -9,6 +8,7 @@ import net.corda.client.rpc.CordaRPCConnection import net.corda.core.future import net.corda.core.messaging.CordaRPCOps import net.corda.core.node.NodeInfo +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.nodeapi.internal.addShutdownHook import java.io.ByteArrayOutputStream @@ -22,7 +22,7 @@ import java.io.OutputStream * [doWhileClientStopped], otherwise the RPC link will be broken. * TODO: Auto reconnect has been enable for RPC connection, investigate if we still need [doWhileClientStopped]. */ -class NodeConnection(val remoteNode: RemoteNode, private val jSchSession: Session, private val localTunnelAddress: HostAndPort) : Closeable { +class NodeConnection(val remoteNode: RemoteNode, private val jSchSession: Session, private val localTunnelAddress: NetworkHostAndPort) : Closeable { companion object { val log = loggerFor() } diff --git a/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierDriver.kt b/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierDriver.kt index f8adb129b1..66315907aa 100644 --- a/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierDriver.kt +++ b/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierDriver.kt @@ -1,6 +1,5 @@ package net.corda.verifier -import com.google.common.net.HostAndPort import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListeningScheduledExecutorService @@ -13,6 +12,7 @@ import net.corda.core.div import net.corda.core.map import net.corda.core.crypto.random63BitValue import net.corda.core.transactions.LedgerTransaction +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.driver.ProcessUtilities import net.corda.core.utilities.loggerFor import net.corda.node.services.config.configureDevKeyAndTrustStores @@ -50,7 +50,7 @@ interface VerifierExposedDSLInterface : DriverDSLExposedInterface { fun startVerificationRequestor(name: X500Name): ListenableFuture /** Starts an out of process verifier connected to [address] */ - fun startVerifier(address: HostAndPort): ListenableFuture + fun startVerifier(address: NetworkHostAndPort): ListenableFuture /** * Waits until [number] verifiers are listening for verification requests coming from the Node. Check @@ -106,7 +106,7 @@ data class VerifierHandle( /** A handle for the verification requestor */ data class VerificationRequestorHandle( - val p2pAddress: HostAndPort, + val p2pAddress: NetworkHostAndPort, private val responseAddress: SimpleString, private val session: ClientSession, private val requestProducer: ClientProducer, @@ -143,7 +143,7 @@ data class VerifierDriverDSL( companion object { private val log = loggerFor() - fun createConfiguration(baseDirectory: Path, nodeHostAndPort: HostAndPort): Config { + fun createConfiguration(baseDirectory: Path, nodeHostAndPort: NetworkHostAndPort): Config { return ConfigFactory.parseMap( mapOf( "baseDirectory" to baseDirectory.toString(), @@ -152,7 +152,7 @@ data class VerifierDriverDSL( ) } - fun createVerificationRequestorArtemisConfig(baseDirectory: Path, responseAddress: String, hostAndPort: HostAndPort, sslConfiguration: SSLConfiguration): Configuration { + fun createVerificationRequestorArtemisConfig(baseDirectory: Path, responseAddress: String, hostAndPort: NetworkHostAndPort, sslConfiguration: SSLConfiguration): Configuration { val connectionDirection = ConnectionDirection.Inbound(acceptorFactoryClassName = NettyAcceptorFactory::class.java.name) return ConfigurationImpl().apply { val artemisDir = "$baseDirectory/artemis" @@ -183,7 +183,7 @@ data class VerifierDriverDSL( } } - private fun startVerificationRequestorInternal(name: X500Name, hostAndPort: HostAndPort): VerificationRequestorHandle { + private fun startVerificationRequestorInternal(name: X500Name, hostAndPort: NetworkHostAndPort): VerificationRequestorHandle { val baseDir = driverDSL.driverDirectory / name.commonName val sslConfig = object : NodeSSLConfiguration { override val baseDirectory = baseDir @@ -247,7 +247,7 @@ data class VerifierDriverDSL( ) } - override fun startVerifier(address: HostAndPort): ListenableFuture { + override fun startVerifier(address: NetworkHostAndPort): ListenableFuture { log.info("Starting verifier connecting to address $address") val id = verifierCount.andIncrement val jdwpPort = if (driverDSL.isDebug) driverDSL.debugPortAllocation.nextPort() else null diff --git a/verifier/src/main/kotlin/net/corda/verifier/Verifier.kt b/verifier/src/main/kotlin/net/corda/verifier/Verifier.kt index a42b495072..ea54765408 100644 --- a/verifier/src/main/kotlin/net/corda/verifier/Verifier.kt +++ b/verifier/src/main/kotlin/net/corda/verifier/Verifier.kt @@ -1,12 +1,12 @@ package net.corda.verifier -import com.google.common.net.HostAndPort import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigParseOptions import net.corda.core.ErrorOr import net.corda.nodeapi.internal.addShutdownHook import net.corda.core.div +import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.debug import net.corda.core.utilities.loggerFor import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport @@ -23,7 +23,7 @@ data class VerifierConfiguration( override val baseDirectory: Path, val config: Config ) : NodeSSLConfiguration { - val nodeHostAndPort: HostAndPort by config + val nodeHostAndPort: NetworkHostAndPort by config override val keyStorePassword: String by config override val trustStorePassword: String by config } diff --git a/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt b/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt index 446545944c..dca27b20f1 100644 --- a/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt +++ b/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt @@ -1,7 +1,7 @@ package net.corda.webserver -import com.google.common.net.HostAndPort import net.corda.core.getOrThrow +import net.corda.core.utilities.NetworkHostAndPort import net.corda.testing.DUMMY_BANK_A import net.corda.testing.driver.WebserverHandle import net.corda.testing.driver.addressMustBeBound @@ -19,7 +19,7 @@ class DriverTests { addressMustBeBound(executorService, webserverHandle.listenAddress, webserverHandle.process) } - fun webserverMustBeDown(webserverAddr: HostAndPort) { + fun webserverMustBeDown(webserverAddr: NetworkHostAndPort) { addressMustNotBeBound(executorService, webserverAddr) } } diff --git a/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt b/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt index 194536869e..ab331c347e 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt @@ -1,7 +1,7 @@ package net.corda.webserver -import com.google.common.net.HostAndPort import com.typesafe.config.Config +import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.config.NodeSSLConfiguration import net.corda.nodeapi.config.getValue import java.nio.file.Path @@ -15,6 +15,6 @@ class WebServerConfig(override val baseDirectory: Path, val config: Config) : No val exportJMXto: String get() = "http" val useHTTPS: Boolean by config val myLegalName: String by config - val p2pAddress: HostAndPort by config // TODO: Use RPC port instead of P2P port (RPC requires authentication, P2P does not) - val webAddress: HostAndPort by config + val p2pAddress: NetworkHostAndPort by config // TODO: Use RPC port instead of P2P port (RPC requires authentication, P2P does not) + val webAddress: NetworkHostAndPort by config }