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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,11 @@
package net.corda.core.node
import com.google.common.net.HostAndPort
import net.corda.core.identity.Party
import net.corda.core.identity.PartyAndCertificate
import net.corda.core.node.services.ServiceInfo
import net.corda.core.node.services.ServiceType
import net.corda.core.serialization.CordaSerializable
import net.corda.core.utilities.NetworkHostAndPort
/**
* Information for an advertised service including the service specific identity information.
@ -19,7 +19,7 @@ data class ServiceEntry(val info: ServiceInfo, val identity: PartyAndCertificate
*/
// TODO We currently don't support multi-IP/multi-identity nodes, we only left slots in the data structures.
@CordaSerializable
data class NodeInfo(val addresses: List<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 legalIdentitiesAndCerts: Set<PartyAndCertificate>,
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 kotlin.test.assertEquals
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
location of the node server.
* Slots for multiple IP addresses and ``legalIdentitiesAndCert``s were introduced. Addresses are no longer of type
``SingleMessageRecipient``, but of ``HostAndPort``.
``SingleMessageRecipient``, but of ``NetworkHostAndPort``.
* ``ServiceHub.storageService`` has been removed. ``attachments`` and ``validatedTransactions`` are now direct members of
``ServiceHub``.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,5 @@
package net.corda.node.services
import com.google.common.net.HostAndPort
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.ErrorOr
import net.corda.core.contracts.ContractState
@ -13,6 +12,7 @@ import net.corda.core.div
import net.corda.core.getOrThrow
import net.corda.core.identity.Party
import net.corda.core.node.services.ServiceInfo
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.flows.NotaryError
import net.corda.flows.NotaryException
import net.corda.flows.NotaryFlow
@ -53,7 +53,7 @@ class BFTNotaryServiceTests {
serviceType.id,
clusterName)
val bftNotaryService = ServiceInfo(serviceType, clusterName)
val notaryClusterAddresses = replicaIds.map { HostAndPort.fromParts("localhost", 11000 + it * 10) }
val notaryClusterAddresses = replicaIds.map { NetworkHostAndPort("localhost", 11000 + it * 10) }
replicaIds.forEach { replicaId ->
mockNet.createNode(
node.network.myAddress,

View File

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

View File

@ -3,7 +3,6 @@ package net.corda.node.internal
import com.codahale.metrics.MetricRegistry
import com.google.common.annotations.VisibleForTesting
import com.google.common.collect.MutableClassToInstanceMap
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import com.google.common.util.concurrent.SettableFuture
@ -24,6 +23,7 @@ import net.corda.core.serialization.SerializeAsToken
import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.serialization.deserialize
import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.debug
import net.corda.flows.*
import net.corda.node.services.*
@ -621,7 +621,7 @@ abstract class AbstractNode(open val configuration: NodeConfiguration,
}
/** Return list of node's addresses. It's overridden in MockNetwork as we don't have real addresses for MockNodes. */
protected abstract fun myAddresses(): List<HostAndPort>
protected abstract fun myAddresses(): List<NetworkHostAndPort>
/** This is overriden by the mock node implementation to enable operation without any network map service */
protected open fun noNetworkMapConfigured(): ListenableFuture<Unit> {

View File

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

View File

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

View File

@ -1,6 +1,5 @@
package net.corda.node.services.messaging
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.SettableFuture
import io.netty.handler.ssl.SslHandler
@ -11,6 +10,7 @@ import net.corda.core.crypto.X509Utilities.CORDA_ROOT_CA
import net.corda.core.node.NodeInfo
import net.corda.core.node.services.NetworkMapCache
import net.corda.core.node.services.NetworkMapCache.MapChange
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.debug
import net.corda.core.utilities.loggerFor
import net.corda.node.internal.Node
@ -376,7 +376,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration,
}
private fun createTcpTransport(connectionDirection: ConnectionDirection, host: String, port: Int, enableSSL: Boolean = true) =
ArtemisTcpTransport.tcpTransport(connectionDirection, HostAndPort.fromParts(host, port), config, enableSSL = enableSSL)
ArtemisTcpTransport.tcpTransport(connectionDirection, NetworkHostAndPort(host, port), config, enableSSL = enableSSL)
/**
* All nodes are expected to have a public facing address called [ArtemisMessagingComponent.P2P_QUEUE] for receiving
@ -384,7 +384,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration,
* as defined by ArtemisAddress.queueName. A bridge is then created to forward messages from this queue to the node's
* P2P address.
*/
private fun deployBridge(queueName: String, target: HostAndPort, legalName: X500Name) {
private fun deployBridge(queueName: String, target: NetworkHostAndPort, legalName: X500Name) {
val connectionDirection = ConnectionDirection.Outbound(
connectorFactoryClassName = VerifyingNettyConnectorFactory::class.java.name,
expectedCommonName = legalName
@ -420,7 +420,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration,
private val ArtemisPeerAddress.bridgeName: String get() = getBridgeName(queueName, hostAndPort)
private fun getBridgeName(queueName: String, hostAndPort: HostAndPort): String = "$queueName -> $hostAndPort"
private fun getBridgeName(queueName: String, hostAndPort: NetworkHostAndPort): String = "$queueName -> $hostAndPort"
// This is called on one of Artemis' background threads
internal fun hostVerificationFail(expectedLegalName: X500Name, errorMsg: String?) {

View File

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

View File

@ -1,7 +1,7 @@
package net.corda.node.services.transactions
import com.google.common.net.HostAndPort
import net.corda.core.div
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.debug
import net.corda.core.utilities.loggerFor
import java.io.FileWriter
@ -17,14 +17,14 @@ import java.util.concurrent.TimeUnit.MILLISECONDS
* Each instance of this class creates such a configHome, accessible via [path].
* The files are deleted on [close] typically via [use], see [PathManager] for details.
*/
class BFTSMaRtConfig(private val replicaAddresses: List<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 {
private val log = loggerFor<BFTSMaRtConfig>()
internal val portIsClaimedFormat = "Port %s is claimed by another replica: %s"
}
init {
val claimedPorts = mutableSetOf<HostAndPort>()
val claimedPorts = mutableSetOf<NetworkHostAndPort>()
val n = replicaAddresses.size
(0 until n).forEach { replicaId ->
// Each replica claims the configured port and the next one:
@ -66,7 +66,7 @@ class BFTSMaRtConfig(private val replicaAddresses: List<HostAndPort>, debug: Boo
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]
return BFTSMaRtPort.values().map { it.ofReplica(base) }
}
@ -76,10 +76,10 @@ private enum class BFTSMaRtPort(private val off: Int) {
FOR_CLIENTS(0),
FOR_REPLICAS(1);
fun ofReplica(base: HostAndPort) = HostAndPort.fromParts(base.host, base.port + off)
fun ofReplica(base: NetworkHostAndPort) = NetworkHostAndPort(base.host, base.port + off)
}
private fun HostAndPort.isListening() = try {
private fun NetworkHostAndPort.isListening() = try {
Socket(host, port).use { true } // Will cause one error to be logged in the replica on success.
} catch (e: SocketException) {
false

View File

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

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

View File

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

View File

@ -1,6 +1,6 @@
package net.corda.node.services.transactions
import com.google.common.net.HostAndPort
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.transactions.BFTSMaRtConfig.Companion.portIsClaimedFormat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
@ -28,7 +28,7 @@ class BFTSMaRtConfigTests {
@Test
fun `overlapping port ranges are rejected`() {
fun addresses(vararg ports: Int) = ports.map { HostAndPort.fromParts("localhost", it) }
fun addresses(vararg ports: Int) = ports.map { NetworkHostAndPort("localhost", it) }
assertThatThrownBy { BFTSMaRtConfig(addresses(11000, 11001)).use {} }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(portIsClaimedFormat.format("localhost:11001", setOf("localhost:11000", "localhost:11001")))

View File

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

View File

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

View File

@ -1,12 +1,12 @@
package net.corda.bank
import com.google.common.net.HostAndPort
import joptsimple.OptionParser
import net.corda.bank.api.BankOfCordaClientApi
import net.corda.bank.api.BankOfCordaWebApi.IssueRequestParams
import net.corda.core.node.services.ServiceInfo
import net.corda.core.node.services.ServiceType
import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.testing.DUMMY_NOTARY
import net.corda.flows.CashExitFlow
import net.corda.flows.CashPaymentFlow
@ -72,13 +72,13 @@ private class BankOfCordaDriver {
when (role) {
Role.ISSUE_CASH_RPC -> {
println("Requesting Cash via RPC ...")
val result = BankOfCordaClientApi(HostAndPort.fromString("localhost:10006")).requestRPCIssue(requestParams)
val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10006)).requestRPCIssue(requestParams)
if (result is SignedTransaction)
println("Success!! You transaction receipt is ${result.tx.id}")
}
Role.ISSUE_CASH_WEB -> {
println("Requesting Cash via Web ...")
val result = BankOfCordaClientApi(HostAndPort.fromString("localhost:10007")).requestWebIssue(requestParams)
val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10007)).requestWebIssue(requestParams)
if (result)
println("Successfully processed Cash Issue request")
}

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package net.corda.irs
import com.google.common.net.HostAndPort
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.irs.utilities.uploadFile
import net.corda.testing.http.HttpApi
import org.apache.commons.io.IOUtils
@ -9,7 +9,7 @@ import java.net.URL
/**
* Interface for communicating with nodes running the IRS demo.
*/
class IRSDemoClientApi(private val hostAndPort: HostAndPort) {
class IRSDemoClientApi(private val hostAndPort: NetworkHostAndPort) {
private val api = HttpApi.fromHostAndPort(hostAndPort, apiRoot)
fun runTrade(tradeId: String): Boolean {

View File

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

View File

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

View File

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

View File

@ -1,6 +1,5 @@
package net.corda.notarydemo
import com.google.common.net.HostAndPort
import net.corda.core.crypto.appendToCommonName
import net.corda.core.div
import net.corda.core.node.services.ServiceInfo
@ -13,6 +12,7 @@ import net.corda.node.utilities.ServiceIdentityGenerator
import net.corda.cordform.CordformDefinition
import net.corda.cordform.CordformContext
import net.corda.cordform.CordformNode
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.demorun.runNodes
import net.corda.demorun.util.node
import org.bouncycastle.asn1.x500.X500Name
@ -49,7 +49,7 @@ object RaftNotaryCordform : CordformDefinition("build" / "notary-demo-nodes", no
p2pPort(10009)
rpcPort(10010)
}
val clusterAddress = HostAndPort.fromParts("localhost", 10008) // Otherwise each notary forms its own cluster.
val clusterAddress = NetworkHostAndPort("localhost", 10008) // Otherwise each notary forms its own cluster.
notaryNode(1) {
notaryNodePort(10012)
p2pPort(10013)

View File

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

View File

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

View File

@ -3,7 +3,6 @@
package net.corda.testing
import com.google.common.net.HostAndPort
import com.nhaarman.mockito_kotlin.spy
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.StateRef
@ -14,6 +13,7 @@ import net.corda.core.node.ServiceHub
import net.corda.core.node.services.IdentityService
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.config.NodeConfiguration
import net.corda.node.services.config.VerifierType
import net.corda.node.services.config.configureDevKeyAndTrustStores
@ -88,7 +88,7 @@ val ALL_TEST_KEYS: List<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_IDENTITY_SERVICE: IdentityService get() = InMemoryIdentityService(MOCK_IDENTITIES, emptyMap(), DUMMY_CA.certificate.cert)
val MOCK_HOST_AND_PORT = HostAndPort.fromParts("mockHost", 30000)
val MOCK_HOST_AND_PORT = NetworkHostAndPort("mockHost", 30000)
fun generateStateRef() = StateRef(SecureHash.randomSHA256(), 0)
@ -99,7 +99,7 @@ private val freePortCounter = AtomicInteger(30000)
* Unsafe for getting multiple ports!
* Use [getFreeLocalPorts] for getting multiple ports.
*/
fun freeLocalHostAndPort(): HostAndPort = HostAndPort.fromParts("localhost", freePort())
fun freeLocalHostAndPort() = NetworkHostAndPort("localhost", freePort())
/**
* Returns a free port.
@ -115,9 +115,9 @@ fun freePort(): Int = freePortCounter.getAndAccumulate(0) { prev, _ -> 30000 + (
* Unlikely, but in the time between running this function and handing the ports
* to the Node, some other process else could allocate the returned ports.
*/
fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List<HostAndPort> {
fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List<NetworkHostAndPort> {
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
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.ListenableFuture
import net.corda.client.mock.Generator
import net.corda.client.mock.generateOrFail
@ -11,6 +10,8 @@ import net.corda.client.rpc.internal.RPCClientConfiguration
import net.corda.core.div
import net.corda.core.map
import net.corda.core.messaging.RPCOps
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.parseNetworkHostAndPort
import net.corda.core.crypto.random63BitValue
import net.corda.testing.driver.ProcessUtilities
import net.corda.node.services.RPCUserService
@ -109,7 +110,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE,
maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE,
configuration: RPCServerConfiguration = RPCServerConfiguration.default,
customPort: HostAndPort? = null,
customPort: NetworkHostAndPort? = null,
ops : I
) : ListenableFuture<RpcServerHandle>
@ -124,7 +125,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
*/
fun <I : RPCOps> startRpcClient(
rpcOpsClass: Class<I>,
rpcAddress: HostAndPort,
rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username,
password: String = rpcTestUser.password,
configuration: RPCClientConfiguration = RPCClientConfiguration.default
@ -140,7 +141,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
*/
fun <I : RPCOps> startRandomRpcClient(
rpcOpsClass: Class<I>,
rpcAddress: HostAndPort,
rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username,
password: String = rpcTestUser.password
): ListenableFuture<Process>
@ -153,7 +154,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
* @param password The password to authenticate with.
*/
fun startArtemisSession(
rpcAddress: HostAndPort,
rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username,
password: String = rpcTestUser.password
): ClientSession
@ -163,7 +164,7 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
rpcUser: User = rpcTestUser,
maxFileSize: Int = ArtemisMessagingServer.MAX_FILE_SIZE,
maxBufferedBytesPerClient: Long = 10L * ArtemisMessagingServer.MAX_FILE_SIZE,
customPort: HostAndPort? = null
customPort: NetworkHostAndPort? = null
): ListenableFuture<RpcBrokerHandle>
fun startInVmRpcBroker(
@ -186,12 +187,12 @@ inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startInVmRpcClient(
configuration: RPCClientConfiguration = RPCClientConfiguration.default
) = startInVmRpcClient(I::class.java, username, password, configuration)
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRandomRpcClient(
hostAndPort: HostAndPort,
hostAndPort: NetworkHostAndPort,
username: String = rpcTestUser.username,
password: String = rpcTestUser.password
) = startRandomRpcClient(I::class.java, hostAndPort, username, password)
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient(
rpcAddress: HostAndPort,
rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username,
password: String = rpcTestUser.password,
configuration: RPCClientConfiguration = RPCClientConfiguration.default
@ -200,7 +201,7 @@ inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient(
interface RPCDriverInternalDSLInterface : DriverDSLInternalInterface, RPCDriverExposedDSLInterface
data class RpcBrokerHandle(
val hostAndPort: HostAndPort?, /** null if this is an InVM broker */
val hostAndPort: NetworkHostAndPort?,/** null if this is an InVM broker */
val clientTransportConfiguration: TransportConfiguration,
val serverControl: ActiveMQServerControl
)
@ -306,7 +307,7 @@ data class RPCDriverDSL(
configureCommonSettings(maxFileSize, maxBufferedBytesPerClient)
}
}
fun createRpcServerArtemisConfig(maxFileSize: Int, maxBufferedBytesPerClient: Long, baseDirectory: Path, hostAndPort: HostAndPort): Configuration {
fun createRpcServerArtemisConfig(maxFileSize: Int, maxBufferedBytesPerClient: Long, baseDirectory: Path, hostAndPort: NetworkHostAndPort): Configuration {
val connectionDirection = ConnectionDirection.Inbound(acceptorFactoryClassName = NettyAcceptorFactory::class.java.name)
return ConfigurationImpl().apply {
val artemisDir = "$baseDirectory/artemis"
@ -318,7 +319,7 @@ data class RPCDriverDSL(
}
}
val inVmClientTransportConfiguration = TransportConfiguration(InVMConnectorFactory::class.java.name)
fun createNettyClientTransportConfiguration(hostAndPort: HostAndPort): TransportConfiguration {
fun createNettyClientTransportConfiguration(hostAndPort: NetworkHostAndPort): TransportConfiguration {
return ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), hostAndPort, null)
}
}
@ -366,7 +367,7 @@ data class RPCDriverDSL(
maxFileSize: Int,
maxBufferedBytesPerClient: Long,
configuration: RPCServerConfiguration,
customPort: HostAndPort?,
customPort: NetworkHostAndPort?,
ops: I
): ListenableFuture<RpcServerHandle> {
return startRpcBroker(serverName, rpcUser, maxFileSize, maxBufferedBytesPerClient, customPort).map { broker ->
@ -376,7 +377,7 @@ data class RPCDriverDSL(
override fun <I : RPCOps> startRpcClient(
rpcOpsClass: Class<I>,
rpcAddress: HostAndPort,
rpcAddress: NetworkHostAndPort,
username: String,
password: String,
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> {
ProcessUtilities.startJavaProcess<RandomRpcUser>(listOf(rpcOpsClass.name, rpcAddress.toString(), username, password))
}
@ -399,7 +400,7 @@ data class RPCDriverDSL(
return processFuture
}
override fun startArtemisSession(rpcAddress: HostAndPort, username: String, password: String): ClientSession {
override fun startArtemisSession(rpcAddress: NetworkHostAndPort, username: String, password: String): ClientSession {
val locator = ActiveMQClient.createServerLocatorWithoutHA(createNettyClientTransportConfiguration(rpcAddress))
val sessionFactory = locator.createSessionFactory()
val session = sessionFactory.createSession(username, password, false, true, true, false, DEFAULT_ACK_BATCH_SIZE)
@ -417,7 +418,7 @@ data class RPCDriverDSL(
rpcUser: User,
maxFileSize: Int,
maxBufferedBytesPerClient: Long,
customPort: HostAndPort?
customPort: NetworkHostAndPort?
): ListenableFuture<RpcBrokerHandle> {
val hostAndPort = customPort ?: driverDSL.portAllocation.nextHostAndPort()
addressMustNotBeBound(driverDSL.executorService, hostAndPort)
@ -506,7 +507,7 @@ class RandomRpcUser {
require(args.size == 4)
@Suppress("UNCHECKED_CAST")
val rpcClass = Class.forName(args[0]) as Class<RPCOps>
val hostAndPort = HostAndPort.fromString(args[1])
val hostAndPort = args[1].parseNetworkHostAndPort()
val username = args[2]
val password = args[3]
val handle = RPCClient<RPCOps>(hostAndPort, null).start(rpcClass, username, password)

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package net.corda.testing.messaging
import com.google.common.net.HostAndPort
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.ArtemisMessagingComponent
import net.corda.nodeapi.ArtemisTcpTransport
import net.corda.nodeapi.ConnectionDirection
@ -12,7 +12,7 @@ import org.bouncycastle.asn1.x500.X500Name
/**
* As the name suggests this is a simple client for connecting to MQ brokers.
*/
class SimpleMQClient(val target: HostAndPort,
class SimpleMQClient(val target: NetworkHostAndPort,
override val config: SSLConfiguration? = configureTestSSL(DEFAULT_MQ_LEGAL_NAME)) : ArtemisMessagingComponent() {
companion object {
val DEFAULT_MQ_LEGAL_NAME = X500Name("CN=SimpleMQClient,O=R3,OU=corda,L=London,C=GB")

View File

@ -1,12 +1,12 @@
package net.corda.testing.node
import co.paralleluniverse.common.util.VisibleForTesting
import com.google.common.net.HostAndPort
import net.corda.core.crypto.entropyToKeyPair
import net.corda.core.identity.Party
import net.corda.core.node.NodeInfo
import net.corda.core.node.ServiceHub
import net.corda.core.node.services.NetworkMapCache
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.network.InMemoryNetworkMapCache
import net.corda.testing.getTestPartyAndCertificate
import net.corda.testing.getTestX509Name
@ -21,8 +21,8 @@ class MockNetworkMapCache(serviceHub: ServiceHub) : InMemoryNetworkMapCache(serv
private companion object {
val BANK_C = getTestPartyAndCertificate(getTestX509Name("Bank C"), entropyToKeyPair(BigInteger.valueOf(1000)).public)
val BANK_D = getTestPartyAndCertificate(getTestX509Name("Bank D"), entropyToKeyPair(BigInteger.valueOf(2000)).public)
val BANK_C_ADDR: HostAndPort = HostAndPort.fromParts("bankC", 8080)
val BANK_D_ADDR: HostAndPort = HostAndPort.fromParts("bankD", 8080)
val BANK_C_ADDR = NetworkHostAndPort("bankC", 8080)
val BANK_D_ADDR = NetworkHostAndPort("bankD", 8080)
}
override val changed: Observable<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.Jimfs
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import com.nhaarman.mockito_kotlin.whenever
@ -17,6 +16,7 @@ import net.corda.core.messaging.RPCOps
import net.corda.core.messaging.SingleMessageRecipient
import net.corda.core.node.CordaPluginRegistry
import net.corda.core.node.ServiceEntry
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.node.WorldMapLocation
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.KeyManagementService
@ -222,7 +222,7 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
override fun makeTransactionVerifierService() = InMemoryTransactionVerifierService(1)
override fun myAddresses(): List<HostAndPort> = listOf(HostAndPort.fromHost("mockHost"))
override fun myAddresses() = emptyList<NetworkHostAndPort>()
override fun start(): MockNode {
super.start()

View File

@ -1,6 +1,5 @@
package net.corda.testing.node
import com.google.common.net.HostAndPort
import net.corda.core.contracts.Attachment
import net.corda.core.crypto.*
import net.corda.core.flows.StateMachineRunId
@ -76,7 +75,7 @@ open class MockServices(vararg val keys: KeyPair) : ServiceHub {
override val clock: Clock get() = Clock.systemUTC()
override val myInfo: NodeInfo get() {
val identity = getTestPartyAndCertificate(MEGA_CORP.name, key.public)
return NodeInfo(listOf(HostAndPort.fromHost("localhost")), identity, setOf(identity), 1)
return NodeInfo(emptyList(), identity, setOf(identity), 1)
}
override val transactionVerifierService: TransactionVerifierService get() = InMemoryTransactionVerifierService(2)

View File

@ -1,13 +1,13 @@
package net.corda.testing.node
import com.codahale.metrics.MetricRegistry
import com.google.common.net.HostAndPort
import com.google.common.util.concurrent.SettableFuture
import net.corda.core.crypto.commonName
import net.corda.core.crypto.generateKeyPair
import net.corda.core.messaging.RPCOps
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.KeyManagementService
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.RPCUserServiceImpl
import net.corda.node.services.api.MonitoringService
import net.corda.node.services.config.NodeConfiguration
@ -30,8 +30,8 @@ import kotlin.concurrent.thread
* This is a bare-bones node which can only send and receive messages. It doesn't register with a network map service or
* any other such task that would make it functional in a network and thus left to the user to do so manually.
*/
class SimpleNode(val config: NodeConfiguration, val address: HostAndPort = freeLocalHostAndPort(),
rpcAddress: HostAndPort = freeLocalHostAndPort(),
class SimpleNode(val config: NodeConfiguration, val address: NetworkHostAndPort = freeLocalHostAndPort(),
rpcAddress: NetworkHostAndPort = freeLocalHostAndPort(),
trustRoot: X509Certificate) : AutoCloseable {
private val databaseWithCloseable: Pair<Closeable, Database> = configureDatabase(config.dataSourceProperties)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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