Retire HostAndPort (#962)

* Don't attempt to parse a resolved InetSocketAddress toString
* A mock node isn't reachable via an address
This commit is contained in:
Andrzej Cichocki 2017-07-07 15:11:07 +01:00 committed by GitHub
parent 7822118835
commit cefa14507a
61 changed files with 290 additions and 266 deletions

View File

@ -1,6 +1,5 @@
package net.corda.client.jfx.model package net.corda.client.jfx.model
import com.google.common.net.HostAndPort
import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleObjectProperty
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.client.rpc.CordaRPCClientConfiguration 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.node.services.Vault
import net.corda.core.seconds import net.corda.core.seconds
import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import rx.Observable import rx.Observable
import rx.subjects.PublishSubject import rx.subjects.PublishSubject
@ -51,7 +51,7 @@ class NodeMonitorModel {
* Register for updates to/from a given vault. * Register for updates to/from a given vault.
* TODO provide an unsubscribe mechanism * TODO provide an unsubscribe mechanism
*/ */
fun register(nodeHostAndPort: HostAndPort, username: String, password: String) { fun register(nodeHostAndPort: NetworkHostAndPort, username: String, password: String) {
val client = CordaRPCClient( val client = CordaRPCClient(
hostAndPort = nodeHostAndPort, hostAndPort = nodeHostAndPort,
configuration = CordaRPCClientConfiguration.default.copy( configuration = CordaRPCClientConfiguration.default.copy(

View File

@ -5,13 +5,13 @@ import com.esotericsoftware.kryo.Serializer
import com.esotericsoftware.kryo.io.Input import com.esotericsoftware.kryo.io.Input
import com.esotericsoftware.kryo.io.Output import com.esotericsoftware.kryo.io.Output
import com.esotericsoftware.kryo.pool.KryoPool import com.esotericsoftware.kryo.pool.KryoPool
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import net.corda.client.rpc.internal.RPCClient import net.corda.client.rpc.internal.RPCClient
import net.corda.client.rpc.internal.RPCClientConfiguration import net.corda.client.rpc.internal.RPCClientConfiguration
import net.corda.core.* import net.corda.core.*
import net.corda.core.crypto.random63BitValue import net.corda.core.crypto.random63BitValue
import net.corda.core.messaging.RPCOps import net.corda.core.messaging.RPCOps
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.driver.poll import net.corda.testing.driver.poll
import net.corda.node.services.messaging.RPCServerConfiguration import net.corda.node.services.messaging.RPCServerConfiguration
import net.corda.nodeapi.RPCApi import net.corda.nodeapi.RPCApi
@ -78,7 +78,7 @@ class RPCStabilityTests {
val executor = Executors.newScheduledThreadPool(1) val executor = Executors.newScheduledThreadPool(1)
fun startAndStop() { fun startAndStop() {
rpcDriver { rpcDriver {
ErrorOr.catch { startRpcClient<RPCOps>(HostAndPort.fromString("localhost:9999")).get() } ErrorOr.catch { startRpcClient<RPCOps>(NetworkHostAndPort("localhost", 9999)).get() }
val server = startRpcServer<RPCOps>(ops = DummyOps) val server = startRpcServer<RPCOps>(ops = DummyOps)
ErrorOr.catch { startRpcClient<RPCOps>( ErrorOr.catch { startRpcClient<RPCOps>(
server.get().broker.hostAndPort!!, server.get().broker.hostAndPort!!,

View File

@ -1,9 +1,9 @@
package net.corda.client.rpc package net.corda.client.rpc
import com.google.common.net.HostAndPort
import net.corda.client.rpc.internal.RPCClient import net.corda.client.rpc.internal.RPCClient
import net.corda.client.rpc.internal.RPCClientConfiguration import net.corda.client.rpc.internal.RPCClientConfiguration
import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport
import net.corda.nodeapi.ConnectionDirection import net.corda.nodeapi.ConnectionDirection
import net.corda.nodeapi.config.SSLConfiguration import net.corda.nodeapi.config.SSLConfiguration
@ -33,7 +33,7 @@ data class CordaRPCClientConfiguration(
/** @see RPCClient */ /** @see RPCClient */
class CordaRPCClient( class CordaRPCClient(
hostAndPort: HostAndPort, hostAndPort: NetworkHostAndPort,
sslConfiguration: SSLConfiguration? = null, sslConfiguration: SSLConfiguration? = null,
configuration: CordaRPCClientConfiguration = CordaRPCClientConfiguration.default configuration: CordaRPCClientConfiguration = CordaRPCClientConfiguration.default
) { ) {

View File

@ -1,11 +1,11 @@
package net.corda.client.rpc.internal package net.corda.client.rpc.internal
import com.google.common.net.HostAndPort
import net.corda.core.logElapsedTime import net.corda.core.logElapsedTime
import net.corda.core.messaging.RPCOps import net.corda.core.messaging.RPCOps
import net.corda.core.minutes import net.corda.core.minutes
import net.corda.core.crypto.random63BitValue import net.corda.core.crypto.random63BitValue
import net.corda.core.seconds import net.corda.core.seconds
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport
import net.corda.nodeapi.ConnectionDirection import net.corda.nodeapi.ConnectionDirection
@ -88,7 +88,7 @@ class RPCClient<I : RPCOps>(
val rpcConfiguration: RPCClientConfiguration = RPCClientConfiguration.default val rpcConfiguration: RPCClientConfiguration = RPCClientConfiguration.default
) { ) {
constructor( constructor(
hostAndPort: HostAndPort, hostAndPort: NetworkHostAndPort,
sslConfiguration: SSLConfiguration? = null, sslConfiguration: SSLConfiguration? = null,
configuration: RPCClientConfiguration = RPCClientConfiguration.default configuration: RPCClientConfiguration = RPCClientConfiguration.default
) : this(tcpTransport(ConnectionDirection.Outbound(), hostAndPort, sslConfiguration), configuration) ) : this(tcpTransport(ConnectionDirection.Outbound(), hostAndPort, sslConfiguration), configuration)

View File

@ -1,11 +1,11 @@
package net.corda.core.node package net.corda.core.node
import com.google.common.net.HostAndPort
import net.corda.core.identity.Party import net.corda.core.identity.Party
import net.corda.core.identity.PartyAndCertificate import net.corda.core.identity.PartyAndCertificate
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.node.services.ServiceType import net.corda.core.node.services.ServiceType
import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.CordaSerializable
import net.corda.core.utilities.NetworkHostAndPort
/** /**
* Information for an advertised service including the service specific identity information. * 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. // TODO We currently don't support multi-IP/multi-identity nodes, we only left slots in the data structures.
@CordaSerializable @CordaSerializable
data class NodeInfo(val addresses: List<HostAndPort>, data class NodeInfo(val addresses: List<NetworkHostAndPort>,
val legalIdentityAndCert: PartyAndCertificate, //TODO This field will be removed in future PR which gets rid of services. val legalIdentityAndCert: PartyAndCertificate, //TODO This field will be removed in future PR which gets rid of services.
val legalIdentitiesAndCerts: Set<PartyAndCertificate>, val legalIdentitiesAndCerts: Set<PartyAndCertificate>,
val platformVersion: Int, val platformVersion: Int,

View File

@ -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()

View File

@ -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 org.junit.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertFailsWith import kotlin.test.assertFailsWith

View File

@ -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))
}
}
}

View File

@ -12,7 +12,7 @@ UNRELEASED
* ``PhysicalLocation`` was renamed to ``WorldMapLocation`` to emphasise that it doesn't need to map to a truly physical * ``PhysicalLocation`` was renamed to ``WorldMapLocation`` to emphasise that it doesn't need to map to a truly physical
location of the node server. location of the node server.
* Slots for multiple IP addresses and ``legalIdentitiesAndCert``s were introduced. Addresses are no longer of type * 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.storageService`` has been removed. ``attachments`` and ``validatedTransactions`` are now direct members of
``ServiceHub``. ``ServiceHub``.

View File

@ -1,7 +1,5 @@
package net.corda.nodeapi 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.crypto.toBase58String
import net.corda.core.messaging.MessageRecipientGroup import net.corda.core.messaging.MessageRecipientGroup
import net.corda.core.messaging.MessageRecipients 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.read
import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.CordaSerializable
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.config.SSLConfiguration import net.corda.nodeapi.config.SSLConfiguration
import java.security.KeyStore import java.security.KeyStore
import java.security.PublicKey import java.security.PublicKey
@ -43,11 +42,11 @@ abstract class ArtemisMessagingComponent : SingletonSerializeAsToken() {
} }
interface ArtemisPeerAddress : ArtemisAddress, SingleMessageRecipient { interface ArtemisPeerAddress : ArtemisAddress, SingleMessageRecipient {
val hostAndPort: HostAndPort val hostAndPort: NetworkHostAndPort
} }
@CordaSerializable @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 override val queueName: String get() = NETWORK_MAP_QUEUE
} }
@ -63,13 +62,13 @@ abstract class ArtemisMessagingComponent : SingletonSerializeAsToken() {
* @param hostAndPort The address of the node. * @param hostAndPort The address of the node.
*/ */
@CordaSerializable @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 { companion object {
fun asPeer(peerIdentity: PublicKey, hostAndPort: HostAndPort): NodeAddress { fun asPeer(peerIdentity: PublicKey, hostAndPort: NetworkHostAndPort): NodeAddress {
return NodeAddress("$PEERS_PREFIX${peerIdentity.toBase58String()}", hostAndPort) 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) return NodeAddress("$SERVICES_PREFIX${serviceIdentity.toBase58String()}", hostAndPort)
} }
} }

View File

@ -1,6 +1,6 @@
package net.corda.nodeapi package net.corda.nodeapi
import com.google.common.net.HostAndPort import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.config.SSLConfiguration import net.corda.nodeapi.config.SSLConfiguration
import org.apache.activemq.artemis.api.core.TransportConfiguration import org.apache.activemq.artemis.api.core.TransportConfiguration
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory
@ -36,7 +36,7 @@ class ArtemisTcpTransport {
fun tcpTransport( fun tcpTransport(
direction: ConnectionDirection, direction: ConnectionDirection,
hostAndPort: HostAndPort, hostAndPort: NetworkHostAndPort,
config: SSLConfiguration?, config: SSLConfiguration?,
enableSSL: Boolean = true enableSSL: Boolean = true
): TransportConfiguration { ): TransportConfiguration {

View File

@ -1,9 +1,10 @@
package net.corda.nodeapi.config package net.corda.nodeapi.config
import com.google.common.net.HostAndPort
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigUtil import com.typesafe.config.ConfigUtil
import net.corda.core.noneOrSingle 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.bouncycastle.asn1.x500.X500Name
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import java.net.Proxy import java.net.Proxy
@ -67,7 +68,7 @@ private fun Config.getSingleValue(path: String, type: KType): Any? {
Boolean::class -> getBoolean(path) Boolean::class -> getBoolean(path)
LocalDate::class -> LocalDate.parse(getString(path)) LocalDate::class -> LocalDate.parse(getString(path))
Instant::class -> Instant.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)) Path::class -> Paths.get(getString(path))
URL::class -> URL(getString(path)) URL::class -> URL(getString(path))
Properties::class -> getConfig(path).toProperties() Properties::class -> getConfig(path).toProperties()
@ -95,7 +96,7 @@ private fun Config.getCollectionValue(path: String, type: KType): Collection<Any
Boolean::class -> getBooleanList(path) Boolean::class -> getBooleanList(path)
LocalDate::class -> getStringList(path).map(LocalDate::parse) LocalDate::class -> getStringList(path).map(LocalDate::parse)
Instant::class -> getStringList(path).map(Instant::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) } Path::class -> getStringList(path).map { Paths.get(it) }
URL::class -> getStringList(path).map(::URL) URL::class -> getStringList(path).map(::URL)
X500Name::class -> getStringList(path).map(::X500Name) X500Name::class -> getStringList(path).map(::X500Name)

View File

@ -1,9 +1,9 @@
package net.corda.nodeapi.serialization package net.corda.nodeapi.serialization
import com.esotericsoftware.kryo.KryoException import com.esotericsoftware.kryo.KryoException
import com.google.common.net.HostAndPort
import net.corda.core.node.CordaPluginRegistry import net.corda.core.node.CordaPluginRegistry
import net.corda.core.serialization.SerializationCustomization import net.corda.core.serialization.SerializationCustomization
import net.corda.core.utilities.NetworkHostAndPort
import org.apache.activemq.artemis.api.core.SimpleString import org.apache.activemq.artemis.api.core.SimpleString
import rx.Notification import rx.Notification
import rx.exceptions.OnErrorNotImplementedException import rx.exceptions.OnErrorNotImplementedException
@ -33,7 +33,7 @@ class DefaultWhitelist : CordaPluginRegistry() {
addToWhitelist(listOf(Unit).javaClass) // SingletonList addToWhitelist(listOf(Unit).javaClass) // SingletonList
addToWhitelist(setOf(Unit).javaClass) // SingletonSet addToWhitelist(setOf(Unit).javaClass) // SingletonSet
addToWhitelist(mapOf(Unit to Unit).javaClass) // SingletonSet addToWhitelist(mapOf(Unit to Unit).javaClass) // SingletonSet
addToWhitelist(HostAndPort::class.java) addToWhitelist(NetworkHostAndPort::class.java)
addToWhitelist(SimpleString::class.java) addToWhitelist(SimpleString::class.java)
addToWhitelist(KryoException::class.java) addToWhitelist(KryoException::class.java)
addToWhitelist(StringBuffer::class.java) addToWhitelist(StringBuffer::class.java)

View File

@ -1,11 +1,11 @@
package net.corda.nodeapi.config package net.corda.nodeapi.config
import com.google.common.net.HostAndPort
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory.empty import com.typesafe.config.ConfigFactory.empty
import com.typesafe.config.ConfigRenderOptions.defaults import com.typesafe.config.ConfigRenderOptions.defaults
import com.typesafe.config.ConfigValueFactory import com.typesafe.config.ConfigValueFactory
import net.corda.core.div import net.corda.core.div
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.getTestX509Name import net.corda.testing.getTestX509Name
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
@ -59,10 +59,10 @@ class ConfigParsingTest {
} }
@Test @Test
fun `HostAndPort`() { fun `NetworkHostAndPort`() {
testPropertyType<HostAndPortData, HostAndPortListData, HostAndPort>( testPropertyType<NetworkHostAndPortData, NetworkHostAndPortListData, NetworkHostAndPort>(
HostAndPort.fromParts("localhost", 2223), NetworkHostAndPort("localhost", 2223),
HostAndPort.fromParts("localhost", 2225), NetworkHostAndPort("localhost", 2225),
valuesToString = true) valuesToString = true)
} }
@ -223,8 +223,8 @@ class ConfigParsingTest {
data class LocalDateListData(override val values: List<LocalDate>) : ListData<LocalDate> data class LocalDateListData(override val values: List<LocalDate>) : ListData<LocalDate>
data class InstantData(override val value: Instant) : SingleData<Instant> data class InstantData(override val value: Instant) : SingleData<Instant>
data class InstantListData(override val values: List<Instant>) : ListData<Instant> data class InstantListData(override val values: List<Instant>) : ListData<Instant>
data class HostAndPortData(override val value: HostAndPort) : SingleData<HostAndPort> data class NetworkHostAndPortData(override val value: NetworkHostAndPort) : SingleData<NetworkHostAndPort>
data class HostAndPortListData(override val values: List<HostAndPort>) : ListData<HostAndPort> data class NetworkHostAndPortListData(override val values: List<NetworkHostAndPort>) : ListData<NetworkHostAndPort>
data class PathData(override val value: Path) : SingleData<Path> data class PathData(override val value: Path) : SingleData<Path>
data class PathListData(override val values: List<Path>) : ListData<Path> data class PathListData(override val values: List<Path>) : ListData<Path>
data class URLData(override val value: URL) : SingleData<URL> data class URLData(override val value: URL) : SingleData<URL>

View File

@ -1,6 +1,5 @@
package net.corda.node.services package net.corda.node.services
import com.google.common.net.HostAndPort
import com.nhaarman.mockito_kotlin.whenever import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.ErrorOr import net.corda.core.ErrorOr
import net.corda.core.contracts.ContractState import net.corda.core.contracts.ContractState
@ -13,6 +12,7 @@ import net.corda.core.div
import net.corda.core.getOrThrow import net.corda.core.getOrThrow
import net.corda.core.identity.Party import net.corda.core.identity.Party
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.flows.NotaryError import net.corda.flows.NotaryError
import net.corda.flows.NotaryException import net.corda.flows.NotaryException
import net.corda.flows.NotaryFlow import net.corda.flows.NotaryFlow
@ -53,7 +53,7 @@ class BFTNotaryServiceTests {
serviceType.id, serviceType.id,
clusterName) clusterName)
val bftNotaryService = ServiceInfo(serviceType, 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 -> replicaIds.forEach { replicaId ->
mockNet.createNode( mockNet.createNode(
node.network.myAddress, node.network.myAddress,

View File

@ -1,7 +1,6 @@
package net.corda.services.messaging package net.corda.services.messaging
import co.paralleluniverse.fibers.Suspendable import co.paralleluniverse.fibers.Suspendable
import com.google.common.net.HostAndPort
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.core.crypto.generateKeyPair import net.corda.core.crypto.generateKeyPair
import net.corda.core.crypto.toBase58String 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.getOrThrow
import net.corda.core.identity.Party import net.corda.core.identity.Party
import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.crypto.random63BitValue import net.corda.core.crypto.random63BitValue
import net.corda.testing.ALICE import net.corda.testing.ALICE
import net.corda.testing.BOB import net.corda.testing.BOB
@ -144,13 +144,13 @@ abstract class MQSecurityTest : NodeBasedTest() {
assertAllQueueCreationAttacksFail(randomQueue) assertAllQueueCreationAttacksFail(randomQueue)
} }
fun clientTo(target: HostAndPort, sslConfiguration: SSLConfiguration? = configureTestSSL()): SimpleMQClient { fun clientTo(target: NetworkHostAndPort, sslConfiguration: SSLConfiguration? = configureTestSSL()): SimpleMQClient {
val client = SimpleMQClient(target, sslConfiguration) val client = SimpleMQClient(target, sslConfiguration)
clients += client clients += client
return 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 return CordaRPCClient(target, sslConfiguration).start(rpcUser.username, rpcUser.password).proxy
} }

View File

@ -3,7 +3,6 @@ package net.corda.node.internal
import com.codahale.metrics.MetricRegistry import com.codahale.metrics.MetricRegistry
import com.google.common.annotations.VisibleForTesting import com.google.common.annotations.VisibleForTesting
import com.google.common.collect.MutableClassToInstanceMap 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.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors import com.google.common.util.concurrent.MoreExecutors
import com.google.common.util.concurrent.SettableFuture 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.SingletonSerializeAsToken
import net.corda.core.serialization.deserialize import net.corda.core.serialization.deserialize
import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.debug import net.corda.core.utilities.debug
import net.corda.flows.* import net.corda.flows.*
import net.corda.node.services.* 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. */ /** 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<HostAndPort> protected abstract fun myAddresses(): List<NetworkHostAndPort>
/** This is overriden by the mock node implementation to enable operation without any network map service */ /** This is overriden by the mock node implementation to enable operation without any network map service */
protected open fun noNetworkMapConfigured(): ListenableFuture<Unit> { protected open fun noNetworkMapConfigured(): ListenableFuture<Unit> {

View File

@ -1,7 +1,6 @@
package net.corda.node.internal package net.corda.node.internal
import com.codahale.metrics.JmxReporter import com.codahale.metrics.JmxReporter
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.SettableFuture 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.node.services.ServiceInfo
import net.corda.core.seconds import net.corda.core.seconds
import net.corda.core.success import net.corda.core.success
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.core.utilities.parseNetworkHostAndPort
import net.corda.core.utilities.trace import net.corda.core.utilities.trace
import net.corda.node.VersionInfo import net.corda.node.VersionInfo
import net.corda.node.serialization.NodeClock import net.corda.node.serialization.NodeClock
@ -155,21 +156,21 @@ open class Node(override val configuration: FullNodeConfiguration,
advertisedAddress) advertisedAddress)
} }
private fun makeLocalMessageBroker(): HostAndPort { private fun makeLocalMessageBroker(): NetworkHostAndPort {
with(configuration) { with(configuration) {
messageBroker = ArtemisMessagingServer(this, p2pAddress.port, rpcAddress?.port, services.networkMapCache, userService) 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) { return with(configuration) {
val useHost = if (detectPublicIp) { val useHost = if (detectPublicIp) {
tryDetectIfNotPublicHost(p2pAddress.host) ?: p2pAddress.host tryDetectIfNotPublicHost(p2pAddress.host) ?: p2pAddress.host
} else { } else {
p2pAddress.host 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. * it back to the queue.
* - Once the message is received the session is closed and the queue deleted. * - 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" } log.trace { "Trying to detect public hostname through the Network Map Service at $serverAddress" }
val tcpTransport = ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), serverAddress, configuration) val tcpTransport = ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), serverAddress, configuration)
val locator = ActiveMQClient.createServerLocatorWithoutHA(tcpTransport).apply { val locator = ActiveMQClient.createServerLocatorWithoutHA(tcpTransport).apply {
@ -227,14 +228,14 @@ open class Node(override val configuration: FullNodeConfiguration,
val consumer = session.createConsumer(queueName) val consumer = session.createConsumer(queueName)
val artemisMessage: ClientMessage = consumer.receive(10.seconds.toMillis()) ?: val artemisMessage: ClientMessage = consumer.receive(10.seconds.toMillis()) ?:
throw IOException("Did not receive a response from the Network Map Service at $serverAddress") 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") log.info("Detected public address: $publicHostAndPort")
consumer.close() consumer.close()
session.deleteQueue(queueName) session.deleteQueue(queueName)
clientFactory.close() clientFactory.close()
return publicHostAndPort.host.removePrefix("/") return publicHostAndPort.removePrefix("/").parseNetworkHostAndPort().host
} }
override fun startMessagingService(rpcOps: RPCOps) { override fun startMessagingService(rpcOps: RPCOps) {
@ -257,7 +258,7 @@ open class Node(override val configuration: FullNodeConfiguration,
return networkMapConnection.flatMap { super.registerWithNetworkMap() } return networkMapConnection.flatMap { super.registerWithNetworkMap() }
} }
override fun myAddresses(): List<HostAndPort> { override fun myAddresses(): List<NetworkHostAndPort> {
val address = network.myAddress as ArtemisMessagingComponent.ArtemisPeerAddress val address = network.myAddress as ArtemisMessagingComponent.ArtemisPeerAddress
return listOf(address.hostAndPort) return listOf(address.hostAndPort)
} }
@ -359,4 +360,4 @@ open class Node(override val configuration: FullNodeConfiguration,
class ConfigurationException(message: String) : Exception(message) class ConfigurationException(message: String) : Exception(message)
data class NetworkMapInfo(val address: HostAndPort, val legalName: X500Name) data class NetworkMapInfo(val address: NetworkHostAndPort, val legalName: X500Name)

View File

@ -1,7 +1,7 @@
package net.corda.node.services.config package net.corda.node.services.config
import com.google.common.net.HostAndPort
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.internal.NetworkMapInfo import net.corda.node.internal.NetworkMapInfo
import net.corda.node.services.messaging.CertificateChainCheckPolicy import net.corda.node.services.messaging.CertificateChainCheckPolicy
import net.corda.node.services.network.NetworkMapService import net.corda.node.services.network.NetworkMapService
@ -27,8 +27,8 @@ interface NodeConfiguration : NodeSSLConfiguration {
val verifierType: VerifierType val verifierType: VerifierType
val messageRedeliveryDelaySeconds: Int val messageRedeliveryDelaySeconds: Int
val bftReplicaId: Int? val bftReplicaId: Int?
val notaryNodeAddress: HostAndPort? val notaryNodeAddress: NetworkHostAndPort?
val notaryClusterAddresses: List<HostAndPort> val notaryClusterAddresses: List<NetworkHostAndPort>
} }
data class FullNodeConfiguration( data class FullNodeConfiguration(
@ -50,15 +50,15 @@ data class FullNodeConfiguration(
override val messageRedeliveryDelaySeconds: Int = 30, override val messageRedeliveryDelaySeconds: Int = 30,
val useHTTPS: Boolean, val useHTTPS: Boolean,
@OldConfig("artemisAddress") @OldConfig("artemisAddress")
val p2pAddress: HostAndPort, val p2pAddress: NetworkHostAndPort,
val rpcAddress: HostAndPort?, val rpcAddress: NetworkHostAndPort?,
// TODO This field is slightly redundant as p2pAddress is sufficient to hold the address of the node's MQ broker. // 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 // 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<String>, val extraAdvertisedServiceIds: List<String>,
override val bftReplicaId: Int?, override val bftReplicaId: Int?,
override val notaryNodeAddress: HostAndPort?, override val notaryNodeAddress: NetworkHostAndPort?,
override val notaryClusterAddresses: List<HostAndPort>, override val notaryClusterAddresses: List<NetworkHostAndPort>,
override val certificateChainCheckPolicies: List<CertChainPolicyConfig>, override val certificateChainCheckPolicies: List<CertChainPolicyConfig>,
override val devMode: Boolean = false, override val devMode: Boolean = false,
val useTestClock: Boolean = false, val useTestClock: Boolean = false,

View File

@ -1,6 +1,5 @@
package net.corda.node.services.messaging 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.ListenableFuture
import com.google.common.util.concurrent.SettableFuture import com.google.common.util.concurrent.SettableFuture
import io.netty.handler.ssl.SslHandler 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.NodeInfo
import net.corda.core.node.services.NetworkMapCache import net.corda.core.node.services.NetworkMapCache
import net.corda.core.node.services.NetworkMapCache.MapChange 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.debug
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.node.internal.Node 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) = 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 * 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 * as defined by ArtemisAddress.queueName. A bridge is then created to forward messages from this queue to the node's
* P2P address. * P2P address.
*/ */
private fun deployBridge(queueName: String, target: HostAndPort, legalName: X500Name) { private fun deployBridge(queueName: String, target: NetworkHostAndPort, legalName: X500Name) {
val connectionDirection = ConnectionDirection.Outbound( val connectionDirection = ConnectionDirection.Outbound(
connectorFactoryClassName = VerifyingNettyConnectorFactory::class.java.name, connectorFactoryClassName = VerifyingNettyConnectorFactory::class.java.name,
expectedCommonName = legalName expectedCommonName = legalName
@ -420,7 +420,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration,
private val ArtemisPeerAddress.bridgeName: String get() = getBridgeName(queueName, hostAndPort) 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 // This is called on one of Artemis' background threads
internal fun hostVerificationFail(expectedLegalName: X500Name, errorMsg: String?) { internal fun hostVerificationFail(expectedLegalName: X500Name, errorMsg: String?) {

View File

@ -1,6 +1,5 @@
package net.corda.node.services.messaging 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.ListenableFuture
import net.corda.core.* import net.corda.core.*
import net.corda.core.crypto.random63BitValue 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.node.services.TransactionVerifierService
import net.corda.core.utilities.opaque import net.corda.core.utilities.opaque
import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.LedgerTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.core.utilities.trace import net.corda.core.utilities.trace
import net.corda.node.VersionInfo import net.corda.node.VersionInfo
@ -71,13 +71,13 @@ import javax.annotation.concurrent.ThreadSafe
@ThreadSafe @ThreadSafe
class NodeMessagingClient(override val config: NodeConfiguration, class NodeMessagingClient(override val config: NodeConfiguration,
val versionInfo: VersionInfo, val versionInfo: VersionInfo,
val serverAddress: HostAndPort, val serverAddress: NetworkHostAndPort,
val myIdentity: PublicKey?, val myIdentity: PublicKey?,
val nodeExecutor: AffinityExecutor.ServiceAffinityExecutor, val nodeExecutor: AffinityExecutor.ServiceAffinityExecutor,
val database: Database, val database: Database,
val networkMapRegistrationFuture: ListenableFuture<Unit>, val networkMapRegistrationFuture: ListenableFuture<Unit>,
val monitoringService: MonitoringService, val monitoringService: MonitoringService,
advertisedAddress: HostAndPort = serverAddress advertisedAddress: NetworkHostAndPort = serverAddress
) : ArtemisMessagingComponent(), MessagingService { ) : ArtemisMessagingComponent(), MessagingService {
companion object { companion object {
private val log = loggerFor<NodeMessagingClient>() private val log = loggerFor<NodeMessagingClient>()

View File

@ -1,7 +1,7 @@
package net.corda.node.services.transactions package net.corda.node.services.transactions
import com.google.common.net.HostAndPort
import net.corda.core.div import net.corda.core.div
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.debug import net.corda.core.utilities.debug
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import java.io.FileWriter 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]. * 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. * The files are deleted on [close] typically via [use], see [PathManager] for details.
*/ */
class BFTSMaRtConfig(private val replicaAddresses: List<HostAndPort>, debug: Boolean = false) : PathManager<BFTSMaRtConfig>(Files.createTempDirectory("bft-smart-config")) { class BFTSMaRtConfig(private val replicaAddresses: List<NetworkHostAndPort>, debug: Boolean = false) : PathManager<BFTSMaRtConfig>(Files.createTempDirectory("bft-smart-config")) {
companion object { companion object {
private val log = loggerFor<BFTSMaRtConfig>() private val log = loggerFor<BFTSMaRtConfig>()
internal val portIsClaimedFormat = "Port %s is claimed by another replica: %s" internal val portIsClaimedFormat = "Port %s is claimed by another replica: %s"
} }
init { init {
val claimedPorts = mutableSetOf<HostAndPort>() val claimedPorts = mutableSetOf<NetworkHostAndPort>()
val n = replicaAddresses.size val n = replicaAddresses.size
(0 until n).forEach { replicaId -> (0 until n).forEach { replicaId ->
// Each replica claims the configured port and the next one: // Each replica claims the configured port and the next one:
@ -66,7 +66,7 @@ class BFTSMaRtConfig(private val replicaAddresses: List<HostAndPort>, debug: Boo
log.debug { "Replica $peerId is ready for P2P." } log.debug { "Replica $peerId is ready for P2P." }
} }
private fun replicaPorts(replicaId: Int): List<HostAndPort> { private fun replicaPorts(replicaId: Int): List<NetworkHostAndPort> {
val base = replicaAddresses[replicaId] val base = replicaAddresses[replicaId]
return BFTSMaRtPort.values().map { it.ofReplica(base) } return BFTSMaRtPort.values().map { it.ofReplica(base) }
} }
@ -76,10 +76,10 @@ private enum class BFTSMaRtPort(private val off: Int) {
FOR_CLIENTS(0), FOR_CLIENTS(0),
FOR_REPLICAS(1); 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. Socket(host, port).use { true } // Will cause one error to be logged in the replica on success.
} catch (e: SocketException) { } catch (e: SocketException) {
false false

View File

@ -1,6 +1,5 @@
package net.corda.node.services.transactions package net.corda.node.services.transactions
import com.google.common.net.HostAndPort
import io.atomix.catalyst.buffer.BufferInput import io.atomix.catalyst.buffer.BufferInput
import io.atomix.catalyst.buffer.BufferOutput import io.atomix.catalyst.buffer.BufferOutput
import io.atomix.catalyst.serializer.Serializer import io.atomix.catalyst.serializer.Serializer
@ -48,13 +47,13 @@ class RaftUniquenessProvider(services: ServiceHubInternal) : UniquenessProvider,
/** Directory storing the Raft log and state machine snapshots */ /** Directory storing the Raft log and state machine snapshots */
private val storagePath: Path = services.configuration.baseDirectory private val storagePath: Path = services.configuration.baseDirectory
/** Address of the Copycat node run by this Corda node */ /** 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") ?: throw IllegalArgumentException("notaryNodeAddress must be specified in configuration")
/** /**
* List of node addresses in the existing Copycat cluster. At least one active node must be * 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. * provided to join the cluster. If empty, a new cluster will be bootstrapped.
*/ */
private val clusterAddresses: List<HostAndPort> = services.configuration.notaryClusterAddresses private val clusterAddresses = services.configuration.notaryClusterAddresses
/** The database to store the state machine state in */ /** The database to store the state machine state in */
private val db: Database = services.database private val db: Database = services.database
/** SSL configuration */ /** SSL configuration */

View File

@ -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))

View File

@ -1,7 +1,7 @@
package net.corda.node.services.config package net.corda.node.services.config
import com.google.common.net.HostAndPort
import net.corda.core.crypto.commonName import net.corda.core.crypto.commonName
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.ALICE import net.corda.testing.ALICE
import net.corda.nodeapi.User import net.corda.nodeapi.User
import net.corda.testing.node.makeTestDataSourceProperties import net.corda.testing.node.makeTestDataSourceProperties
@ -25,8 +25,8 @@ class FullNodeConfigurationTest {
rpcUsers = emptyList(), rpcUsers = emptyList(),
verifierType = VerifierType.InMemory, verifierType = VerifierType.InMemory,
useHTTPS = false, useHTTPS = false,
p2pAddress = HostAndPort.fromParts("localhost", 0), p2pAddress = NetworkHostAndPort("localhost", 0),
rpcAddress = HostAndPort.fromParts("localhost", 1), rpcAddress = NetworkHostAndPort("localhost", 1),
messagingServerAddress = null, messagingServerAddress = null,
extraAdvertisedServiceIds = emptyList(), extraAdvertisedServiceIds = emptyList(),
bftReplicaId = null, bftReplicaId = null,

View File

@ -1,13 +1,14 @@
package net.corda.node.services.messaging package net.corda.node.services.messaging
import com.codahale.metrics.MetricRegistry import com.codahale.metrics.MetricRegistry
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.SettableFuture import com.google.common.util.concurrent.SettableFuture
import net.corda.core.crypto.generateKeyPair import net.corda.core.crypto.generateKeyPair
import net.corda.core.messaging.RPCOps import net.corda.core.messaging.RPCOps
import net.corda.core.node.services.DEFAULT_SESSION_ID 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.testing.LogHelper
import net.corda.node.services.RPCUserService import net.corda.node.services.RPCUserService
import net.corda.node.services.RPCUserServiceImpl 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.AffinityExecutor.ServiceAffinityExecutor
import net.corda.node.utilities.configureDatabase import net.corda.node.utilities.configureDatabase
import net.corda.node.utilities.transaction import net.corda.node.utilities.transaction
import net.corda.testing.ALICE
import net.corda.testing.freeLocalHostAndPort import net.corda.testing.freeLocalHostAndPort
import net.corda.testing.freePort import net.corda.testing.freePort
import net.corda.testing.node.MOCK_VERSION_INFO import net.corda.testing.node.MOCK_VERSION_INFO
@ -218,7 +218,7 @@ class ArtemisMessagingTests {
return messagingClient return messagingClient
} }
private fun createMessagingClient(server: HostAndPort = HostAndPort.fromParts("localhost", serverPort)): NodeMessagingClient { private fun createMessagingClient(server: NetworkHostAndPort = NetworkHostAndPort("localhost", serverPort)): NodeMessagingClient {
return database.transaction { return database.transaction {
NodeMessagingClient( NodeMessagingClient(
config, config,

View File

@ -1,6 +1,6 @@
package net.corda.node.services.transactions 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 net.corda.node.services.transactions.BFTSMaRtConfig.Companion.portIsClaimedFormat
import org.assertj.core.api.Assertions.assertThatThrownBy import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test import org.junit.Test
@ -28,7 +28,7 @@ class BFTSMaRtConfigTests {
@Test @Test
fun `overlapping port ranges are rejected`() { 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 {} } assertThatThrownBy { BFTSMaRtConfig(addresses(11000, 11001)).use {} }
.isInstanceOf(IllegalArgumentException::class.java) .isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(portIsClaimedFormat.format("localhost:11001", setOf("localhost:11000", "localhost:11001"))) .hasMessage(portIsClaimedFormat.format("localhost:11001", setOf("localhost:11000", "localhost:11001")))

View File

@ -1,6 +1,5 @@
package net.corda.node.services.transactions package net.corda.node.services.transactions
import com.google.common.net.HostAndPort
import io.atomix.catalyst.transport.Address import io.atomix.catalyst.transport.Address
import io.atomix.copycat.client.ConnectionStrategies import io.atomix.copycat.client.ConnectionStrategies
import io.atomix.copycat.client.CopycatClient 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.Storage
import io.atomix.copycat.server.storage.StorageLevel import io.atomix.copycat.server.storage.StorageLevel
import net.corda.core.getOrThrow import net.corda.core.getOrThrow
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.LogHelper import net.corda.testing.LogHelper
import net.corda.node.services.network.NetworkMapService import net.corda.node.services.network.NetworkMapService
import net.corda.node.utilities.configureDatabase import net.corda.node.utilities.configureDatabase
@ -87,7 +87,7 @@ class DistributedImmutableMapTests {
return cluster.map { it.getOrThrow() } return cluster.map { it.getOrThrow() }
} }
private fun createReplica(myAddress: HostAndPort, clusterAddress: HostAndPort? = null): CompletableFuture<Member> { private fun createReplica(myAddress: NetworkHostAndPort, clusterAddress: NetworkHostAndPort? = null): CompletableFuture<Member> {
val storage = Storage.builder().withStorageLevel(StorageLevel.MEMORY).build() val storage = Storage.builder().withStorageLevel(StorageLevel.MEMORY).build()
val address = Address(myAddress.host, myAddress.port) val address = Address(myAddress.host, myAddress.port)

View File

@ -1,7 +1,6 @@
package net.corda.attachmentdemo package net.corda.attachmentdemo
import co.paralleluniverse.fibers.Suspendable import co.paralleluniverse.fibers.Suspendable
import com.google.common.net.HostAndPort
import joptsimple.OptionParser import joptsimple.OptionParser
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.core.contracts.Contract import net.corda.core.contracts.Contract
@ -53,14 +52,14 @@ fun main(args: Array<String>) {
val role = options.valueOf(roleArg)!! val role = options.valueOf(roleArg)!!
when (role) { when (role) {
Role.SENDER -> { Role.SENDER -> {
val host = HostAndPort.fromString("localhost:10006") val host = NetworkHostAndPort("localhost", 10006)
println("Connecting to sender node ($host)") println("Connecting to sender node ($host)")
CordaRPCClient(host).start("demo", "demo").use { CordaRPCClient(host).start("demo", "demo").use {
sender(it.proxy) sender(it.proxy)
} }
} }
Role.RECIPIENT -> { Role.RECIPIENT -> {
val host = HostAndPort.fromString("localhost:10009") val host = NetworkHostAndPort("localhost", 10009)
println("Connecting to the recipient node ($host)") println("Connecting to the recipient node ($host)")
CordaRPCClient(host).start("demo", "demo").use { CordaRPCClient(host).start("demo", "demo").use {
recipient(it.proxy) recipient(it.proxy)

View File

@ -1,12 +1,12 @@
package net.corda.bank package net.corda.bank
import com.google.common.net.HostAndPort
import joptsimple.OptionParser import joptsimple.OptionParser
import net.corda.bank.api.BankOfCordaClientApi import net.corda.bank.api.BankOfCordaClientApi
import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.node.services.ServiceType import net.corda.core.node.services.ServiceType
import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_NOTARY import net.corda.testing.DUMMY_NOTARY
import net.corda.flows.CashExitFlow import net.corda.flows.CashExitFlow
import net.corda.flows.CashPaymentFlow import net.corda.flows.CashPaymentFlow
@ -72,13 +72,13 @@ private class BankOfCordaDriver {
when (role) { when (role) {
Role.ISSUE_CASH_RPC -> { Role.ISSUE_CASH_RPC -> {
println("Requesting Cash via 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) if (result is SignedTransaction)
println("Success!! You transaction receipt is ${result.tx.id}") println("Success!! You transaction receipt is ${result.tx.id}")
} }
Role.ISSUE_CASH_WEB -> { Role.ISSUE_CASH_WEB -> {
println("Requesting Cash via 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) if (result)
println("Successfully processed Cash Issue request") println("Successfully processed Cash Issue request")
} }

View File

@ -1,6 +1,5 @@
package net.corda.bank.api package net.corda.bank.api
import com.google.common.net.HostAndPort
import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.core.contracts.Amount 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.messaging.startFlow
import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.OpaqueBytes
import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.flows.IssuerFlow.IssuanceRequester import net.corda.flows.IssuerFlow.IssuanceRequester
import net.corda.testing.http.HttpApi import net.corda.testing.http.HttpApi
/** /**
* Interface for communicating with Bank of Corda node * Interface for communicating with Bank of Corda node
*/ */
class BankOfCordaClientApi(val hostAndPort: HostAndPort) { class BankOfCordaClientApi(val hostAndPort: NetworkHostAndPort) {
private val apiRoot = "api/bank" private val apiRoot = "api/bank"
/** /**
* HTTP API * HTTP API

View File

@ -1,11 +1,11 @@
package net.corda.irs package net.corda.irs
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.core.getOrThrow import net.corda.core.getOrThrow
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.toFuture import net.corda.core.toFuture
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_BANK_A import net.corda.testing.DUMMY_BANK_A
import net.corda.testing.DUMMY_BANK_B import net.corda.testing.DUMMY_BANK_B
import net.corda.testing.DUMMY_NOTARY import net.corda.testing.DUMMY_NOTARY
@ -101,7 +101,7 @@ class IRSDemoTest : IntegrationTestCategory {
assertThat(nodeApi.postJson("deals", tradeFile)).isTrue() assertThat(nodeApi.postJson("deals", tradeFile)).isTrue()
} }
private fun runUploadRates(host: HostAndPort) { private fun runUploadRates(host: NetworkHostAndPort) {
println("Running upload rates against $host") println("Running upload rates against $host")
val fileContents = loadResourceFile("net/corda/irs/simulation/example.rates.txt") val fileContents = loadResourceFile("net/corda/irs/simulation/example.rates.txt")
val url = URL("http://$host/api/irs/fixes") val url = URL("http://$host/api/irs/fixes")

View File

@ -2,8 +2,8 @@
package net.corda.irs package net.corda.irs
import com.google.common.net.HostAndPort
import joptsimple.OptionParser import joptsimple.OptionParser
import net.corda.core.utilities.NetworkHostAndPort
import kotlin.system.exitProcess import kotlin.system.exitProcess
enum class Role { enum class Role {
@ -29,9 +29,9 @@ fun main(args: Array<String>) {
val role = options.valueOf(roleArg)!! val role = options.valueOf(roleArg)!!
val value = options.valueOf(valueArg) val value = options.valueOf(valueArg)
when (role) { when (role) {
Role.UploadRates -> IRSDemoClientApi(HostAndPort.fromString("localhost:10004")).runUploadRates() Role.UploadRates -> IRSDemoClientApi(NetworkHostAndPort("localhost", 10004)).runUploadRates()
Role.Trade -> IRSDemoClientApi(HostAndPort.fromString("localhost:10007")).runTrade(value) Role.Trade -> IRSDemoClientApi(NetworkHostAndPort("localhost", 10007)).runTrade(value)
Role.Date -> IRSDemoClientApi(HostAndPort.fromString("localhost:10010")).runDateChange(value) Role.Date -> IRSDemoClientApi(NetworkHostAndPort("localhost", 10010)).runDateChange(value)
} }
} }

View File

@ -1,6 +1,6 @@
package net.corda.irs 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.irs.utilities.uploadFile
import net.corda.testing.http.HttpApi import net.corda.testing.http.HttpApi
import org.apache.commons.io.IOUtils import org.apache.commons.io.IOUtils
@ -9,7 +9,7 @@ import java.net.URL
/** /**
* Interface for communicating with nodes running the IRS demo. * 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) private val api = HttpApi.fromHostAndPort(hostAndPort, apiRoot)
fun runTrade(tradeId: String): Boolean { fun runTrade(tradeId: String): Boolean {

View File

@ -1,9 +1,9 @@
package net.corda.demorun.util package net.corda.demorun.util
import com.google.common.net.HostAndPort
import net.corda.cordform.CordformDefinition import net.corda.cordform.CordformDefinition
import net.corda.cordform.CordformNode import net.corda.cordform.CordformNode
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.User import net.corda.nodeapi.User
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
@ -21,6 +21,6 @@ fun CordformNode.advertisedServices(vararg services: ServiceInfo) {
advertisedServices = services.map { it.toString() } advertisedServices = services.map { it.toString() }
} }
fun CordformNode.notaryClusterAddresses(vararg addresses: HostAndPort) { fun CordformNode.notaryClusterAddresses(vararg addresses: NetworkHostAndPort) {
notaryClusterAddresses = addresses.map { it.toString() } notaryClusterAddresses = addresses.map { it.toString() }
} }

View File

@ -1,6 +1,5 @@
package net.corda.notarydemo package net.corda.notarydemo
import com.google.common.net.HostAndPort
import net.corda.core.div import net.corda.core.div
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.testing.ALICE import net.corda.testing.ALICE
@ -14,6 +13,7 @@ import net.corda.cordform.CordformContext
import net.corda.cordform.CordformNode import net.corda.cordform.CordformNode
import net.corda.core.stream import net.corda.core.stream
import net.corda.core.toTypedArray import net.corda.core.toTypedArray
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.transactions.minCorrectReplicas import net.corda.node.services.transactions.minCorrectReplicas
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
@ -38,7 +38,7 @@ object BFTNotaryCordform : CordformDefinition("build" / "notary-demo-nodes", not
p2pPort(10005) p2pPort(10005)
rpcPort(10006) 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 { fun notaryNode(replicaId: Int, configure: CordformNode.() -> Unit) = node {
name(notaryNames[replicaId]) name(notaryNames[replicaId])
advertisedServices(advertisedService) advertisedServices(advertisedService)

View File

@ -1,6 +1,5 @@
package net.corda.notarydemo package net.corda.notarydemo
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import net.corda.client.rpc.CordaRPCClient 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.CordaRPCOps
import net.corda.core.messaging.startFlow import net.corda.core.messaging.startFlow
import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.BOB import net.corda.testing.BOB
import net.corda.notarydemo.flows.DummyIssueAndMove import net.corda.notarydemo.flows.DummyIssueAndMove
import net.corda.notarydemo.flows.RPCStartableNotaryFlowClient import net.corda.notarydemo.flows.RPCStartableNotaryFlowClient
import kotlin.streams.asSequence import kotlin.streams.asSequence
fun main(args: Array<String>) { fun main(args: Array<String>) {
val address = HostAndPort.fromParts("localhost", 10003) val address = NetworkHostAndPort("localhost", 10003)
println("Connecting to the recipient node ($address)") println("Connecting to the recipient node ($address)")
CordaRPCClient(address).start(notaryDemoUser.username, notaryDemoUser.password).use { CordaRPCClient(address).start(notaryDemoUser.username, notaryDemoUser.password).use {
NotaryDemoClientApi(it.proxy).notarise(10) NotaryDemoClientApi(it.proxy).notarise(10)

View File

@ -1,6 +1,5 @@
package net.corda.notarydemo package net.corda.notarydemo
import com.google.common.net.HostAndPort
import net.corda.core.crypto.appendToCommonName import net.corda.core.crypto.appendToCommonName
import net.corda.core.div import net.corda.core.div
import net.corda.core.node.services.ServiceInfo 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.CordformDefinition
import net.corda.cordform.CordformContext import net.corda.cordform.CordformContext
import net.corda.cordform.CordformNode import net.corda.cordform.CordformNode
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.demorun.runNodes import net.corda.demorun.runNodes
import net.corda.demorun.util.node import net.corda.demorun.util.node
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
@ -49,7 +49,7 @@ object RaftNotaryCordform : CordformDefinition("build" / "notary-demo-nodes", no
p2pPort(10009) p2pPort(10009)
rpcPort(10010) 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) { notaryNode(1) {
notaryNodePort(10012) notaryNodePort(10012)
p2pPort(10013) p2pPort(10013)

View File

@ -1,9 +1,9 @@
package net.corda.traderdemo package net.corda.traderdemo
import com.google.common.net.HostAndPort
import joptsimple.OptionParser import joptsimple.OptionParser
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.core.contracts.DOLLARS import net.corda.core.contracts.DOLLARS
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_BANK_A import net.corda.testing.DUMMY_BANK_A
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import org.slf4j.Logger import org.slf4j.Logger
@ -42,12 +42,12 @@ private class TraderDemo {
// will contact the buyer and actually make something happen. // will contact the buyer and actually make something happen.
val role = options.valueOf(roleArg)!! val role = options.valueOf(roleArg)!!
if (role == Role.BUYER) { if (role == Role.BUYER) {
val host = HostAndPort.fromString("localhost:10006") val host = NetworkHostAndPort("localhost", 10006)
CordaRPCClient(host).start("demo", "demo").use { CordaRPCClient(host).start("demo", "demo").use {
TraderDemoClientApi(it.proxy).runBuyer() TraderDemoClientApi(it.proxy).runBuyer()
} }
} else { } else {
val host = HostAndPort.fromString("localhost:10009") val host = NetworkHostAndPort("localhost", 10009)
CordaRPCClient(host).use("demo", "demo") { CordaRPCClient(host).use("demo", "demo") {
TraderDemoClientApi(it.proxy).runSeller(1000.DOLLARS, DUMMY_BANK_A.name) TraderDemoClientApi(it.proxy).runSeller(1000.DOLLARS, DUMMY_BANK_A.name)
} }

View File

@ -1,10 +1,10 @@
package net.corda.smoketesting package net.corda.smoketesting
import com.google.common.net.HostAndPort
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.client.rpc.CordaRPCConnection import net.corda.client.rpc.CordaRPCConnection
import net.corda.core.createDirectories import net.corda.core.createDirectories
import net.corda.core.div import net.corda.core.div
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import java.nio.file.Path import java.nio.file.Path
import java.nio.file.Paths import java.nio.file.Paths
@ -60,7 +60,7 @@ class NodeProcess(
confFile.writeText(config.toText()) confFile.writeText(config.toText())
val process = startNode(nodeDir) 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 user = config.users[0]
val setupExecutor = Executors.newSingleThreadScheduledExecutor() val setupExecutor = Executors.newSingleThreadScheduledExecutor()

View File

@ -3,7 +3,6 @@
package net.corda.testing package net.corda.testing
import com.google.common.net.HostAndPort
import com.nhaarman.mockito_kotlin.spy import com.nhaarman.mockito_kotlin.spy
import com.nhaarman.mockito_kotlin.whenever import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.StateRef 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.node.services.IdentityService
import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.OpaqueBytes
import net.corda.core.transactions.TransactionBuilder 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.NodeConfiguration
import net.corda.node.services.config.VerifierType import net.corda.node.services.config.VerifierType
import net.corda.node.services.config.configureDevKeyAndTrustStores import net.corda.node.services.config.configureDevKeyAndTrustStores
@ -88,7 +88,7 @@ val ALL_TEST_KEYS: List<KeyPair> get() = listOf(MEGA_CORP_KEY, MINI_CORP_KEY, AL
val MOCK_IDENTITIES = listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_NOTARY_IDENTITY) 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_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) fun generateStateRef() = StateRef(SecureHash.randomSHA256(), 0)
@ -99,7 +99,7 @@ private val freePortCounter = AtomicInteger(30000)
* Unsafe for getting multiple ports! * Unsafe for getting multiple ports!
* Use [getFreeLocalPorts] 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. * 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 * 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. * to the Node, some other process else could allocate the returned ports.
*/ */
fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List<HostAndPort> { fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List<NetworkHostAndPort> {
val freePort = freePortCounter.getAndAccumulate(0) { prev, _ -> 30000 + (prev - 30000 + numberToAlloc) % 10000 } 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) }
} }
/** /**

View File

@ -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)
}
}
}

View File

@ -1,6 +1,5 @@
package net.corda.testing package net.corda.testing
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import net.corda.client.mock.Generator import net.corda.client.mock.Generator
import net.corda.client.mock.generateOrFail 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.div
import net.corda.core.map import net.corda.core.map
import net.corda.core.messaging.RPCOps 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.core.crypto.random63BitValue
import net.corda.testing.driver.ProcessUtilities import net.corda.testing.driver.ProcessUtilities
import net.corda.node.services.RPCUserService import net.corda.node.services.RPCUserService
@ -109,7 +110,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE, maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE,
maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE, maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE,
configuration: RPCServerConfiguration = RPCServerConfiguration.default, configuration: RPCServerConfiguration = RPCServerConfiguration.default,
customPort: HostAndPort? = null, customPort: NetworkHostAndPort? = null,
ops : I ops : I
) : ListenableFuture<RpcServerHandle> ) : ListenableFuture<RpcServerHandle>
@ -124,7 +125,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
*/ */
fun <I : RPCOps> startRpcClient( fun <I : RPCOps> startRpcClient(
rpcOpsClass: Class<I>, rpcOpsClass: Class<I>,
rpcAddress: HostAndPort, rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username, username: String = rpcTestUser.username,
password: String = rpcTestUser.password, password: String = rpcTestUser.password,
configuration: RPCClientConfiguration = RPCClientConfiguration.default configuration: RPCClientConfiguration = RPCClientConfiguration.default
@ -140,7 +141,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
*/ */
fun <I : RPCOps> startRandomRpcClient( fun <I : RPCOps> startRandomRpcClient(
rpcOpsClass: Class<I>, rpcOpsClass: Class<I>,
rpcAddress: HostAndPort, rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username, username: String = rpcTestUser.username,
password: String = rpcTestUser.password password: String = rpcTestUser.password
): ListenableFuture<Process> ): ListenableFuture<Process>
@ -153,7 +154,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
* @param password The password to authenticate with. * @param password The password to authenticate with.
*/ */
fun startArtemisSession( fun startArtemisSession(
rpcAddress: HostAndPort, rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username, username: String = rpcTestUser.username,
password: String = rpcTestUser.password password: String = rpcTestUser.password
): ClientSession ): ClientSession
@ -163,7 +164,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
rpcUser: User = rpcTestUser, rpcUser: User = rpcTestUser,
maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE, maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE,
maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE, maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE,
customPort: HostAndPort? = null customPort: NetworkHostAndPort? = null
): ListenableFuture<RpcBrokerHandle> ): ListenableFuture<RpcBrokerHandle>
fun startInVmRpcBroker( fun startInVmRpcBroker(
@ -186,12 +187,12 @@ inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startInVmRpcClient(
configuration: RPCClientConfiguration = RPCClientConfiguration.default configuration: RPCClientConfiguration = RPCClientConfiguration.default
) = startInVmRpcClient(I::class.java, username, password, configuration) ) = startInVmRpcClient(I::class.java, username, password, configuration)
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRandomRpcClient( inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRandomRpcClient(
hostAndPort: HostAndPort, hostAndPort: NetworkHostAndPort,
username: String = rpcTestUser.username, username: String = rpcTestUser.username,
password: String = rpcTestUser.password password: String = rpcTestUser.password
) = startRandomRpcClient(I::class.java, hostAndPort, username, password) ) = startRandomRpcClient(I::class.java, hostAndPort, username, password)
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient( inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient(
rpcAddress: HostAndPort, rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username, username: String = rpcTestUser.username,
password: String = rpcTestUser.password, password: String = rpcTestUser.password,
configuration: RPCClientConfiguration = RPCClientConfiguration.default configuration: RPCClientConfiguration = RPCClientConfiguration.default
@ -200,7 +201,7 @@ inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient(
interface RPCDriverInternalDSLInterface : DriverDSLInternalInterface, RPCDriverExposedDSLInterface interface RPCDriverInternalDSLInterface : DriverDSLInternalInterface, RPCDriverExposedDSLInterface
data class RpcBrokerHandle( 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 clientTransportConfiguration: TransportConfiguration,
val serverControl: ActiveMQServerControl val serverControl: ActiveMQServerControl
) )
@ -306,7 +307,7 @@ data class RPCDriverDSL(
configureCommonSettings(maxFileSize, maxBufferedBytesPerClient) 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) val connectionDirection = ConnectionDirection.Inbound(acceptorFactoryClassName = NettyAcceptorFactory::class.java.name)
return ConfigurationImpl().apply { return ConfigurationImpl().apply {
val artemisDir = "$baseDirectory/artemis" val artemisDir = "$baseDirectory/artemis"
@ -318,7 +319,7 @@ data class RPCDriverDSL(
} }
} }
val inVmClientTransportConfiguration = TransportConfiguration(InVMConnectorFactory::class.java.name) val inVmClientTransportConfiguration = TransportConfiguration(InVMConnectorFactory::class.java.name)
fun createNettyClientTransportConfiguration(hostAndPort: HostAndPort): TransportConfiguration { fun createNettyClientTransportConfiguration(hostAndPort: NetworkHostAndPort): TransportConfiguration {
return ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), hostAndPort, null) return ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), hostAndPort, null)
} }
} }
@ -366,7 +367,7 @@ data class RPCDriverDSL(
maxFileSize: Int, maxFileSize: Int,
maxBufferedBytesPerClient: Long, maxBufferedBytesPerClient: Long,
configuration: RPCServerConfiguration, configuration: RPCServerConfiguration,
customPort: HostAndPort?, customPort: NetworkHostAndPort?,
ops: I ops: I
): ListenableFuture<RpcServerHandle> { ): ListenableFuture<RpcServerHandle> {
return startRpcBroker(serverName, rpcUser, maxFileSize, maxBufferedBytesPerClient, customPort).map { broker -> return startRpcBroker(serverName, rpcUser, maxFileSize, maxBufferedBytesPerClient, customPort).map { broker ->
@ -376,7 +377,7 @@ data class RPCDriverDSL(
override fun <I : RPCOps> startRpcClient( override fun <I : RPCOps> startRpcClient(
rpcOpsClass: Class<I>, rpcOpsClass: Class<I>,
rpcAddress: HostAndPort, rpcAddress: NetworkHostAndPort,
username: String, username: String,
password: String, password: String,
configuration: RPCClientConfiguration configuration: RPCClientConfiguration
@ -391,7 +392,7 @@ data class RPCDriverDSL(
} }
} }
override fun <I : RPCOps> startRandomRpcClient(rpcOpsClass: Class<I>, rpcAddress: HostAndPort, username: String, password: String): ListenableFuture<Process> { override fun <I : RPCOps> startRandomRpcClient(rpcOpsClass: Class<I>, rpcAddress: NetworkHostAndPort, username: String, password: String): ListenableFuture<Process> {
val processFuture = driverDSL.executorService.submit<Process> { val processFuture = driverDSL.executorService.submit<Process> {
ProcessUtilities.startJavaProcess<RandomRpcUser>(listOf(rpcOpsClass.name, rpcAddress.toString(), username, password)) ProcessUtilities.startJavaProcess<RandomRpcUser>(listOf(rpcOpsClass.name, rpcAddress.toString(), username, password))
} }
@ -399,7 +400,7 @@ data class RPCDriverDSL(
return processFuture 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 locator = ActiveMQClient.createServerLocatorWithoutHA(createNettyClientTransportConfiguration(rpcAddress))
val sessionFactory = locator.createSessionFactory() val sessionFactory = locator.createSessionFactory()
val session = sessionFactory.createSession(username, password, false, true, true, false, DEFAULT_ACK_BATCH_SIZE) val session = sessionFactory.createSession(username, password, false, true, true, false, DEFAULT_ACK_BATCH_SIZE)
@ -417,7 +418,7 @@ data class RPCDriverDSL(
rpcUser: User, rpcUser: User,
maxFileSize: Int, maxFileSize: Int,
maxBufferedBytesPerClient: Long, maxBufferedBytesPerClient: Long,
customPort: HostAndPort? customPort: NetworkHostAndPort?
): ListenableFuture<RpcBrokerHandle> { ): ListenableFuture<RpcBrokerHandle> {
val hostAndPort = customPort ?: driverDSL.portAllocation.nextHostAndPort() val hostAndPort = customPort ?: driverDSL.portAllocation.nextHostAndPort()
addressMustNotBeBound(driverDSL.executorService, hostAndPort) addressMustNotBeBound(driverDSL.executorService, hostAndPort)
@ -506,7 +507,7 @@ class RandomRpcUser {
require(args.size == 4) require(args.size == 4)
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val rpcClass = Class.forName(args[0]) as Class<RPCOps> val rpcClass = Class.forName(args[0]) as Class<RPCOps>
val hostAndPort = HostAndPort.fromString(args[1]) val hostAndPort = args[1].parseNetworkHostAndPort()
val username = args[2] val username = args[2]
val password = args[3] val password = args[3]
val handle = RPCClient<RPCOps>(hostAndPort, null).start(rpcClass, username, password) val handle = RPCClient<RPCOps>(hostAndPort, null).start(rpcClass, username, password)

View File

@ -2,7 +2,6 @@
package net.corda.testing.driver package net.corda.testing.driver
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.* import com.google.common.util.concurrent.*
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigRenderOptions 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.NodeInfo
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.node.services.ServiceType import net.corda.core.node.services.ServiceType
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.WHITESPACE import net.corda.core.utilities.WHITESPACE
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.core.utilities.parseNetworkHostAndPort
import net.corda.node.internal.Node import net.corda.node.internal.Node
import net.corda.node.internal.NodeStartup import net.corda.node.internal.NodeStartup
import net.corda.node.serialization.NodeClock import net.corda.node.serialization.NodeClock
@ -167,13 +168,13 @@ sealed class NodeHandle {
abstract val nodeInfo: NodeInfo abstract val nodeInfo: NodeInfo
abstract val rpc: CordaRPCOps abstract val rpc: CordaRPCOps
abstract val configuration: FullNodeConfiguration abstract val configuration: FullNodeConfiguration
abstract val webAddress: HostAndPort abstract val webAddress: NetworkHostAndPort
data class OutOfProcess( data class OutOfProcess(
override val nodeInfo: NodeInfo, override val nodeInfo: NodeInfo,
override val rpc: CordaRPCOps, override val rpc: CordaRPCOps,
override val configuration: FullNodeConfiguration, override val configuration: FullNodeConfiguration,
override val webAddress: HostAndPort, override val webAddress: NetworkHostAndPort,
val debugPort: Int?, val debugPort: Int?,
val process: Process val process: Process
) : NodeHandle() ) : NodeHandle()
@ -182,7 +183,7 @@ sealed class NodeHandle {
override val nodeInfo: NodeInfo, override val nodeInfo: NodeInfo,
override val rpc: CordaRPCOps, override val rpc: CordaRPCOps,
override val configuration: FullNodeConfiguration, override val configuration: FullNodeConfiguration,
override val webAddress: HostAndPort, override val webAddress: NetworkHostAndPort,
val node: Node, val node: Node,
val nodeThread: Thread val nodeThread: Thread
) : NodeHandle() ) : NodeHandle()
@ -191,13 +192,13 @@ sealed class NodeHandle {
} }
data class WebserverHandle( data class WebserverHandle(
val listenAddress: HostAndPort, val listenAddress: NetworkHostAndPort,
val process: Process val process: Process
) )
sealed class PortAllocation { sealed class PortAllocation {
abstract fun nextPort(): Int abstract fun nextPort(): Int
fun nextHostAndPort(): HostAndPort = HostAndPort.fromParts("localhost", nextPort()) fun nextHostAndPort() = NetworkHostAndPort("localhost", nextPort())
class Incremental(startingPort: Int) : PortAllocation() { class Incremental(startingPort: Int) : PortAllocation() {
val portCounter = AtomicInteger(startingPort) val portCounter = AtomicInteger(startingPort)
@ -298,16 +299,16 @@ fun getTimestampAsDirectoryName(): String {
return DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(UTC).format(Instant.now()) 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. * @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() addressMustBeBoundFuture(executorService, hostAndPort, listenProcess).getOrThrow()
} }
fun addressMustBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: HostAndPort, listenProcess: Process? = null): ListenableFuture<Unit> { fun addressMustBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: NetworkHostAndPort, listenProcess: Process? = null): ListenableFuture<Unit> {
return poll(executorService, "address $hostAndPort to bind") { return poll(executorService, "address $hostAndPort to bind") {
if (listenProcess != null && !listenProcess.isAlive) { if (listenProcess != null && !listenProcess.isAlive) {
throw ListenProcessDeathException(hostAndPort, listenProcess) 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() addressMustNotBeBoundFuture(executorService, hostAndPort).getOrThrow()
} }
fun addressMustNotBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: HostAndPort): ListenableFuture<Unit> { fun addressMustNotBeBoundFuture(executorService: ScheduledExecutorService, hostAndPort: NetworkHostAndPort): ListenableFuture<Unit> {
return poll(executorService, "address $hostAndPort to unbind") { return poll(executorService, "address $hostAndPort to unbind") {
try { try {
Socket(hostAndPort.host, hostAndPort.port).close() Socket(hostAndPort.host, hostAndPort.port).close()
@ -514,7 +515,7 @@ class DriverDSL(
_executorService?.shutdownNow() _executorService?.shutdownNow()
} }
private fun establishRpc(nodeAddress: HostAndPort, sslConfig: SSLConfiguration, processDeathFuture: ListenableFuture<out Throwable>): ListenableFuture<CordaRPCOps> { private fun establishRpc(nodeAddress: NetworkHostAndPort, sslConfig: SSLConfiguration, processDeathFuture: ListenableFuture<out Throwable>): ListenableFuture<CordaRPCOps> {
val client = CordaRPCClient(nodeAddress, sslConfig) val client = CordaRPCClient(nodeAddress, sslConfig)
val connectionFuture = poll(executorService, "RPC connection") { val connectionFuture = poll(executorService, "RPC connection") {
try { try {
@ -544,9 +545,9 @@ class DriverDSL(
} }
} }
is NetworkMapStartStrategy.Nominated -> { is NetworkMapStartStrategy.Nominated -> {
serviceConfig(HostAndPort.fromString(networkMapCandidates.filter { serviceConfig(networkMapCandidates.filter {
it.name == legalName.toString() it.name == legalName.toString()
}.single().config.getString("p2pAddress"))).let { }.single().config.getString("p2pAddress").parseNetworkHostAndPort()).let {
{ nodeName: X500Name -> if (nodeName == legalName) null else it } { nodeName: X500Name -> if (nodeName == legalName) null else it }
} }
} }
@ -704,7 +705,7 @@ class DriverDSL(
return startNodeInternal(config, webAddress, startInProcess) return startNodeInternal(config, webAddress, startInProcess)
} }
private fun startNodeInternal(config: Config, webAddress: HostAndPort, startInProcess: Boolean?): ListenableFuture<out NodeHandle> { private fun startNodeInternal(config: Config, webAddress: NetworkHostAndPort, startInProcess: Boolean?): ListenableFuture<out NodeHandle> {
val nodeConfiguration = config.parseAs<FullNodeConfiguration>() val nodeConfiguration = config.parseAs<FullNodeConfiguration>()
if (startInProcess ?: startNodesInProcess) { if (startInProcess ?: startNodesInProcess) {
val nodeAndThreadFuture = startInProcessNode(executorService, nodeConfiguration, config) val nodeAndThreadFuture = startInProcessNode(executorService, nodeConfiguration, config)

View File

@ -1,13 +1,13 @@
package net.corda.testing.driver package net.corda.testing.driver
import com.google.common.net.HostAndPort import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_MAP import net.corda.testing.DUMMY_MAP
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
sealed class NetworkMapStartStrategy { sealed class NetworkMapStartStrategy {
internal abstract val startDedicated: Boolean internal abstract val startDedicated: Boolean
internal abstract val legalName: X500Name internal abstract val legalName: X500Name
internal fun serviceConfig(address: HostAndPort) = mapOf( internal fun serviceConfig(address: NetworkHostAndPort) = mapOf(
"address" to address.toString(), "address" to address.toString(),
"legalName" to legalName.toString() "legalName" to legalName.toString()
) )

View File

@ -1,7 +1,7 @@
package net.corda.testing.http package net.corda.testing.http
import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.ObjectMapper
import com.google.common.net.HostAndPort import net.corda.core.utilities.NetworkHostAndPort
import java.net.URL import java.net.URL
class HttpApi(val root: URL, val mapper: ObjectMapper = defaultMapper) { 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) private fun toJson(any: Any) = any as? String ?: HttpUtils.defaultMapper.writeValueAsString(any)
companion object { 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) = HttpApi(URL("$protocol://$hostAndPort/$base/"), mapper)
private val defaultMapper: ObjectMapper by lazy { private val defaultMapper: ObjectMapper by lazy {
net.corda.jackson.JacksonSupport.createNonRpcMapper() net.corda.jackson.JacksonSupport.createNonRpcMapper()

View File

@ -1,6 +1,6 @@
package net.corda.testing.messaging 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.ArtemisMessagingComponent
import net.corda.nodeapi.ArtemisTcpTransport import net.corda.nodeapi.ArtemisTcpTransport
import net.corda.nodeapi.ConnectionDirection 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. * 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() { override val config: SSLConfiguration? = configureTestSSL(DEFAULT_MQ_LEGAL_NAME)) : ArtemisMessagingComponent() {
companion object { companion object {
val DEFAULT_MQ_LEGAL_NAME = X500Name("CN=SimpleMQClient,O=R3,OU=corda,L=London,C=GB") val DEFAULT_MQ_LEGAL_NAME = X500Name("CN=SimpleMQClient,O=R3,OU=corda,L=London,C=GB")

View File

@ -1,12 +1,12 @@
package net.corda.testing.node package net.corda.testing.node
import co.paralleluniverse.common.util.VisibleForTesting import co.paralleluniverse.common.util.VisibleForTesting
import com.google.common.net.HostAndPort
import net.corda.core.crypto.entropyToKeyPair import net.corda.core.crypto.entropyToKeyPair
import net.corda.core.identity.Party import net.corda.core.identity.Party
import net.corda.core.node.NodeInfo import net.corda.core.node.NodeInfo
import net.corda.core.node.ServiceHub import net.corda.core.node.ServiceHub
import net.corda.core.node.services.NetworkMapCache import net.corda.core.node.services.NetworkMapCache
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.network.InMemoryNetworkMapCache import net.corda.node.services.network.InMemoryNetworkMapCache
import net.corda.testing.getTestPartyAndCertificate import net.corda.testing.getTestPartyAndCertificate
import net.corda.testing.getTestX509Name import net.corda.testing.getTestX509Name
@ -21,8 +21,8 @@ class MockNetworkMapCache(serviceHub: ServiceHub) : InMemoryNetworkMapCache(serv
private companion object { private companion object {
val BANK_C = getTestPartyAndCertificate(getTestX509Name("Bank C"), entropyToKeyPair(BigInteger.valueOf(1000)).public) 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_D = getTestPartyAndCertificate(getTestX509Name("Bank D"), entropyToKeyPair(BigInteger.valueOf(2000)).public)
val BANK_C_ADDR: HostAndPort = HostAndPort.fromParts("bankC", 8080) val BANK_C_ADDR = NetworkHostAndPort("bankC", 8080)
val BANK_D_ADDR: HostAndPort = HostAndPort.fromParts("bankD", 8080) val BANK_D_ADDR = NetworkHostAndPort("bankD", 8080)
} }
override val changed: Observable<NetworkMapCache.MapChange> = PublishSubject.create<NetworkMapCache.MapChange>() override val changed: Observable<NetworkMapCache.MapChange> = PublishSubject.create<NetworkMapCache.MapChange>()

View File

@ -2,7 +2,6 @@ package net.corda.testing.node
import com.google.common.jimfs.Configuration.unix import com.google.common.jimfs.Configuration.unix
import com.google.common.jimfs.Jimfs 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.Futures
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import com.nhaarman.mockito_kotlin.whenever 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.messaging.SingleMessageRecipient
import net.corda.core.node.CordaPluginRegistry import net.corda.core.node.CordaPluginRegistry
import net.corda.core.node.ServiceEntry import net.corda.core.node.ServiceEntry
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.node.WorldMapLocation import net.corda.core.node.WorldMapLocation
import net.corda.core.node.services.IdentityService import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.KeyManagementService 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 makeTransactionVerifierService() = InMemoryTransactionVerifierService(1)
override fun myAddresses(): List<HostAndPort> = listOf(HostAndPort.fromHost("mockHost")) override fun myAddresses() = emptyList<NetworkHostAndPort>()
override fun start(): MockNode { override fun start(): MockNode {
super.start() super.start()

View File

@ -1,6 +1,5 @@
package net.corda.testing.node package net.corda.testing.node
import com.google.common.net.HostAndPort
import net.corda.core.contracts.Attachment import net.corda.core.contracts.Attachment
import net.corda.core.crypto.* import net.corda.core.crypto.*
import net.corda.core.flows.StateMachineRunId 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 clock: Clock get() = Clock.systemUTC()
override val myInfo: NodeInfo get() { override val myInfo: NodeInfo get() {
val identity = getTestPartyAndCertificate(MEGA_CORP.name, key.public) 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) override val transactionVerifierService: TransactionVerifierService get() = InMemoryTransactionVerifierService(2)

View File

@ -1,13 +1,13 @@
package net.corda.testing.node package net.corda.testing.node
import com.codahale.metrics.MetricRegistry import com.codahale.metrics.MetricRegistry
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.SettableFuture import com.google.common.util.concurrent.SettableFuture
import net.corda.core.crypto.commonName import net.corda.core.crypto.commonName
import net.corda.core.crypto.generateKeyPair import net.corda.core.crypto.generateKeyPair
import net.corda.core.messaging.RPCOps import net.corda.core.messaging.RPCOps
import net.corda.core.node.services.IdentityService import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.KeyManagementService import net.corda.core.node.services.KeyManagementService
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.RPCUserServiceImpl import net.corda.node.services.RPCUserServiceImpl
import net.corda.node.services.api.MonitoringService import net.corda.node.services.api.MonitoringService
import net.corda.node.services.config.NodeConfiguration 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 * 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. * 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(), class SimpleNode(val config: NodeConfiguration, val address: NetworkHostAndPort = freeLocalHostAndPort(),
rpcAddress: HostAndPort = freeLocalHostAndPort(), rpcAddress: NetworkHostAndPort = freeLocalHostAndPort(),
trustRoot: X509Certificate) : AutoCloseable { trustRoot: X509Certificate) : AutoCloseable {
private val databaseWithCloseable: Pair<Closeable, Database> = configureDatabase(config.dataSourceProperties) private val databaseWithCloseable: Pair<Closeable, Database> = configureDatabase(config.dataSourceProperties)

View File

@ -1,7 +1,7 @@
package net.corda.demobench.model package net.corda.demobench.model
import com.google.common.net.HostAndPort
import com.typesafe.config.Config import com.typesafe.config.Config
import net.corda.core.utilities.parseNetworkHostAndPort
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
import tornadofx.* import tornadofx.*
import java.io.IOException import java.io.IOException
@ -46,7 +46,7 @@ class InstallFactory : Controller() {
private fun Config.parsePort(path: String): Int { private fun Config.parsePort(path: String): Int {
val address = this.getString(path) 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'." }) require(nodeController.isPortValid(port), { "Invalid port $port from '$path'." })
return port return port
} }

View File

@ -1,9 +1,9 @@
package net.corda.demobench.rpc package net.corda.demobench.rpc
import com.google.common.net.HostAndPort
import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClient
import net.corda.client.rpc.CordaRPCConnection import net.corda.client.rpc.CordaRPCConnection
import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.demobench.model.NodeConfig import net.corda.demobench.model.NodeConfig
import java.util.* import java.util.*
@ -16,7 +16,7 @@ class NodeRPC(config: NodeConfig, start: (NodeConfig, CordaRPCOps) -> Unit, invo
val oneSecond = SECONDS.toMillis(1) 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 var rpcConnection: CordaRPCConnection? = null
private val timer = Timer() private val timer = Timer()

View File

@ -3,10 +3,10 @@ package net.corda.demobench.model
import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.SerializationFeature
import com.google.common.net.HostAndPort
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigValueFactory import com.typesafe.config.ConfigValueFactory
import net.corda.core.div import net.corda.core.div
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_NOTARY import net.corda.testing.DUMMY_NOTARY
import net.corda.node.internal.NetworkMapInfo import net.corda.node.internal.NetworkMapInfo
import net.corda.node.services.config.FullNodeConfiguration import net.corda.node.services.config.FullNodeConfiguration
@ -270,5 +270,5 @@ class NodeConfigTest {
users = users users = users
) )
private fun localPort(port: Int) = HostAndPort.fromParts("localhost", port) private fun localPort(port: Int) = NetworkHostAndPort("localhost", port)
} }

View File

@ -1,10 +1,10 @@
package net.corda.explorer.views package net.corda.explorer.views
import com.google.common.net.HostAndPort
import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleIntegerProperty
import javafx.scene.control.* import javafx.scene.control.*
import net.corda.client.jfx.model.NodeMonitorModel import net.corda.client.jfx.model.NodeMonitorModel
import net.corda.client.jfx.model.objectProperty import net.corda.client.jfx.model.objectProperty
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.explorer.model.SettingsModel import net.corda.explorer.model.SettingsModel
import org.controlsfx.dialog.ExceptionDialog import org.controlsfx.dialog.ExceptionDialog
import tornadofx.* import tornadofx.*
@ -27,8 +27,8 @@ class LoginView : View() {
private val port by objectProperty(SettingsModel::portProperty) private val port by objectProperty(SettingsModel::portProperty)
private val fullscreen by objectProperty(SettingsModel::fullscreenProperty) private val fullscreen by objectProperty(SettingsModel::fullscreenProperty)
fun login(host: String?, port: Int, username: String, password: String) { fun login(host: String, port: Int, username: String, password: String) {
getModel<NodeMonitorModel>().register(HostAndPort.fromParts(host, port), username, password) getModel<NodeMonitorModel>().register(NetworkHostAndPort(host, port), username, password)
} }
fun login() { fun login() {

View File

@ -1,6 +1,5 @@
package net.corda.loadtest package net.corda.loadtest
import com.google.common.net.HostAndPort
import com.jcraft.jsch.Buffer import com.jcraft.jsch.Buffer
import com.jcraft.jsch.Identity import com.jcraft.jsch.Identity
import com.jcraft.jsch.IdentityRepository 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.AgentProxy
import com.jcraft.jsch.agentproxy.connector.SSHAgentConnector import com.jcraft.jsch.agentproxy.connector.SSHAgentConnector
import com.jcraft.jsch.agentproxy.usocket.JNAUSocketFactory import com.jcraft.jsch.agentproxy.usocket.JNAUSocketFactory
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.PortAllocation
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import java.util.* import java.util.*
@ -61,7 +61,7 @@ fun setupJSchWithSshAgent(): JSch {
} }
class ConnectionManager(private val jSch: 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) val session = jSch.getSession(remoteNode.sshUserName, remoteNode.hostname, 22)
// We don't check the host fingerprints because they may change often // We don't check the host fingerprints because they may change often
session.setConfig("StrictHostKeyChecking", "no") session.setConfig("StrictHostKeyChecking", "no")

View File

@ -1,6 +1,5 @@
package net.corda.loadtest package net.corda.loadtest
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.Session import com.jcraft.jsch.Session
@ -9,6 +8,7 @@ import net.corda.client.rpc.CordaRPCConnection
import net.corda.core.future import net.corda.core.future
import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.CordaRPCOps
import net.corda.core.node.NodeInfo import net.corda.core.node.NodeInfo
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.nodeapi.internal.addShutdownHook import net.corda.nodeapi.internal.addShutdownHook
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
@ -22,7 +22,7 @@ import java.io.OutputStream
* [doWhileClientStopped], otherwise the RPC link will be broken. * [doWhileClientStopped], otherwise the RPC link will be broken.
* TODO: Auto reconnect has been enable for RPC connection, investigate if we still need [doWhileClientStopped]. * 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 { companion object {
val log = loggerFor<NodeConnection>() val log = loggerFor<NodeConnection>()
} }

View File

@ -1,6 +1,5 @@
package net.corda.verifier package net.corda.verifier
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.ListeningScheduledExecutorService 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.map
import net.corda.core.crypto.random63BitValue import net.corda.core.crypto.random63BitValue
import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.LedgerTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.driver.ProcessUtilities import net.corda.testing.driver.ProcessUtilities
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.node.services.config.configureDevKeyAndTrustStores import net.corda.node.services.config.configureDevKeyAndTrustStores
@ -50,7 +50,7 @@ interface VerifierExposedDSLInterface : DriverDSLExposedInterface {
fun startVerificationRequestor(name: X500Name): ListenableFuture<VerificationRequestorHandle> fun startVerificationRequestor(name: X500Name): ListenableFuture<VerificationRequestorHandle>
/** Starts an out of process verifier connected to [address] */ /** Starts an out of process verifier connected to [address] */
fun startVerifier(address: HostAndPort): ListenableFuture<VerifierHandle> fun startVerifier(address: NetworkHostAndPort): ListenableFuture<VerifierHandle>
/** /**
* Waits until [number] verifiers are listening for verification requests coming from the Node. Check * 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 */ /** A handle for the verification requestor */
data class VerificationRequestorHandle( data class VerificationRequestorHandle(
val p2pAddress: HostAndPort, val p2pAddress: NetworkHostAndPort,
private val responseAddress: SimpleString, private val responseAddress: SimpleString,
private val session: ClientSession, private val session: ClientSession,
private val requestProducer: ClientProducer, private val requestProducer: ClientProducer,
@ -143,7 +143,7 @@ data class VerifierDriverDSL(
companion object { companion object {
private val log = loggerFor<VerifierDriverDSL>() private val log = loggerFor<VerifierDriverDSL>()
fun createConfiguration(baseDirectory: Path, nodeHostAndPort: HostAndPort): Config { fun createConfiguration(baseDirectory: Path, nodeHostAndPort: NetworkHostAndPort): Config {
return ConfigFactory.parseMap( return ConfigFactory.parseMap(
mapOf( mapOf(
"baseDirectory" to baseDirectory.toString(), "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) val connectionDirection = ConnectionDirection.Inbound(acceptorFactoryClassName = NettyAcceptorFactory::class.java.name)
return ConfigurationImpl().apply { return ConfigurationImpl().apply {
val artemisDir = "$baseDirectory/artemis" 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 baseDir = driverDSL.driverDirectory / name.commonName
val sslConfig = object : NodeSSLConfiguration { val sslConfig = object : NodeSSLConfiguration {
override val baseDirectory = baseDir override val baseDirectory = baseDir
@ -247,7 +247,7 @@ data class VerifierDriverDSL(
) )
} }
override fun startVerifier(address: HostAndPort): ListenableFuture<VerifierHandle> { override fun startVerifier(address: NetworkHostAndPort): ListenableFuture<VerifierHandle> {
log.info("Starting verifier connecting to address $address") log.info("Starting verifier connecting to address $address")
val id = verifierCount.andIncrement val id = verifierCount.andIncrement
val jdwpPort = if (driverDSL.isDebug) driverDSL.debugPortAllocation.nextPort() else null val jdwpPort = if (driverDSL.isDebug) driverDSL.debugPortAllocation.nextPort() else null

View File

@ -1,12 +1,12 @@
package net.corda.verifier package net.corda.verifier
import com.google.common.net.HostAndPort
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigParseOptions import com.typesafe.config.ConfigParseOptions
import net.corda.core.ErrorOr import net.corda.core.ErrorOr
import net.corda.nodeapi.internal.addShutdownHook import net.corda.nodeapi.internal.addShutdownHook
import net.corda.core.div import net.corda.core.div
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.debug import net.corda.core.utilities.debug
import net.corda.core.utilities.loggerFor import net.corda.core.utilities.loggerFor
import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport
@ -23,7 +23,7 @@ data class VerifierConfiguration(
override val baseDirectory: Path, override val baseDirectory: Path,
val config: Config val config: Config
) : NodeSSLConfiguration { ) : NodeSSLConfiguration {
val nodeHostAndPort: HostAndPort by config val nodeHostAndPort: NetworkHostAndPort by config
override val keyStorePassword: String by config override val keyStorePassword: String by config
override val trustStorePassword: String by config override val trustStorePassword: String by config
} }

View File

@ -1,7 +1,7 @@
package net.corda.webserver package net.corda.webserver
import com.google.common.net.HostAndPort
import net.corda.core.getOrThrow import net.corda.core.getOrThrow
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_BANK_A import net.corda.testing.DUMMY_BANK_A
import net.corda.testing.driver.WebserverHandle import net.corda.testing.driver.WebserverHandle
import net.corda.testing.driver.addressMustBeBound import net.corda.testing.driver.addressMustBeBound
@ -19,7 +19,7 @@ class DriverTests {
addressMustBeBound(executorService, webserverHandle.listenAddress, webserverHandle.process) addressMustBeBound(executorService, webserverHandle.listenAddress, webserverHandle.process)
} }
fun webserverMustBeDown(webserverAddr: HostAndPort) { fun webserverMustBeDown(webserverAddr: NetworkHostAndPort) {
addressMustNotBeBound(executorService, webserverAddr) addressMustNotBeBound(executorService, webserverAddr)
} }
} }

View File

@ -1,7 +1,7 @@
package net.corda.webserver package net.corda.webserver
import com.google.common.net.HostAndPort
import com.typesafe.config.Config import com.typesafe.config.Config
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.config.NodeSSLConfiguration import net.corda.nodeapi.config.NodeSSLConfiguration
import net.corda.nodeapi.config.getValue import net.corda.nodeapi.config.getValue
import java.nio.file.Path 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 exportJMXto: String get() = "http"
val useHTTPS: Boolean by config val useHTTPS: Boolean by config
val myLegalName: String 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 p2pAddress: NetworkHostAndPort by config // TODO: Use RPC port instead of P2P port (RPC requires authentication, P2P does not)
val webAddress: HostAndPort by config val webAddress: NetworkHostAndPort by config
} }