From 7839d78338b4175af677ca81809258479a1e10ba Mon Sep 17 00:00:00 2001 From: Chris Rankin Date: Wed, 4 Jul 2018 09:15:54 +0100 Subject: [PATCH 1/9] CORDA-1704: Suppress ProGuard's "note" output (#3499) * Reduce ProGuard output for kotlin-metadata artifact. * Configure ProGuard not to display "notes" about potential configuration issues. Keep notes for the "checkDeterminism" steps, though. * Also resolve some of the issues that we would now be ignoring. --- buildSrc/jarfilter/kotlin-metadata/build.gradle | 4 ++-- core-deterministic/build.gradle | 3 ++- .../src/main/kotlin/net/corda/core/flows/StateMachineRunId.kt | 2 +- .../main/kotlin/net/corda/core/internal/FlowStateMachine.kt | 2 ++ serialization-deterministic/build.gradle | 3 ++- .../main/kotlin/net/corda/serialization/internal/OrdinalIO.kt | 1 + .../net/corda/serialization/internal/amqp/CustomSerializer.kt | 2 ++ .../net/corda/serialization/internal/amqp/TransformTypes.kt | 1 + .../net/corda/serialization/internal/amqp/TransformsSchema.kt | 1 + 9 files changed, 14 insertions(+), 5 deletions(-) diff --git a/buildSrc/jarfilter/kotlin-metadata/build.gradle b/buildSrc/jarfilter/kotlin-metadata/build.gradle index b509187551..561cea19a1 100644 --- a/buildSrc/jarfilter/kotlin-metadata/build.gradle +++ b/buildSrc/jarfilter/kotlin-metadata/build.gradle @@ -39,7 +39,6 @@ task metadata(type: ProGuardTask) { keepattributes '*' dontoptimize - printseeds verbose dontwarn 'com.sun.jna.**' @@ -47,6 +46,7 @@ task metadata(type: ProGuardTask) { dontwarn 'org.jetbrains.kotlin.com.intellij.**' dontwarn 'org.jetbrains.kotlin.com.google.j2objc.annotations.**' dontwarn 'org.jetbrains.kotlin.com.google.errorprone.annotations.**' + dontnote keep 'class org.jetbrains.kotlin.load.java.JvmAnnotationNames { *; }' keep 'class org.jetbrains.kotlin.metadata.** { *; }', includedescriptorclasses: true @@ -68,6 +68,7 @@ task validate(type: ProGuardTask) { verbose dontwarn 'org.jetbrains.kotlin.com.google.errorprone.annotations.**' + dontnote keep 'class *' } @@ -77,5 +78,4 @@ artifacts { } defaultTasks "metadata" -assemble.dependsOn metadata metadata.finalizedBy validate diff --git a/core-deterministic/build.gradle b/core-deterministic/build.gradle index 80a0232dbf..5768501551 100644 --- a/core-deterministic/build.gradle +++ b/core-deterministic/build.gradle @@ -78,6 +78,7 @@ task predeterminise(type: ProGuardTask) { dontpreverify dontobfuscate dontoptimize + dontnote printseeds verbose @@ -121,6 +122,7 @@ task determinise(type: ProGuardTask) { keepattributes '*' keepdirectories dontobfuscate + dontnote printseeds verbose @@ -166,7 +168,6 @@ task checkDeterminism(type: ProGuardTask, dependsOn: jdkTask) { defaultTasks "determinise" determinise.finalizedBy metafix metafix.finalizedBy checkDeterminism -assemble.dependsOn checkDeterminism def deterministicJar = metafix.outputs.files.singleFile artifacts { diff --git a/core/src/main/kotlin/net/corda/core/flows/StateMachineRunId.kt b/core/src/main/kotlin/net/corda/core/flows/StateMachineRunId.kt index 98956e1c24..47de376947 100644 --- a/core/src/main/kotlin/net/corda/core/flows/StateMachineRunId.kt +++ b/core/src/main/kotlin/net/corda/core/flows/StateMachineRunId.kt @@ -8,10 +8,10 @@ import java.util.* * A unique identifier for a single state machine run, valid across node restarts. Note that a single run always * has at least one flow, but that flow may also invoke sub-flows: they all share the same run id. */ +@DeleteForDJVM @CordaSerializable data class StateMachineRunId(val uuid: UUID) { companion object { - @DeleteForDJVM fun createRandom(): StateMachineRunId = StateMachineRunId(UUID.randomUUID()) } diff --git a/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt b/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt index 1cdf50f088..d055f3ec12 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt @@ -1,6 +1,7 @@ package net.corda.core.internal import co.paralleluniverse.fibers.Suspendable +import net.corda.core.DeleteForDJVM import net.corda.core.DoNotImplement import net.corda.core.concurrent.CordaFuture import net.corda.core.context.InvocationContext @@ -10,6 +11,7 @@ import net.corda.core.node.ServiceHub import org.slf4j.Logger /** This is an internal interface that is implemented by code in the node module. You should look at [FlowLogic]. */ +@DeleteForDJVM @DoNotImplement interface FlowStateMachine { @Suspendable diff --git a/serialization-deterministic/build.gradle b/serialization-deterministic/build.gradle index 54530bad3e..9a30fc5862 100644 --- a/serialization-deterministic/build.gradle +++ b/serialization-deterministic/build.gradle @@ -74,6 +74,7 @@ task predeterminise(type: ProGuardTask, dependsOn: project(':core-deterministic' dontpreverify dontobfuscate dontoptimize + dontnote printseeds verbose @@ -114,6 +115,7 @@ task determinise(type: ProGuardTask) { keepattributes '*' keepdirectories dontobfuscate + dontnote printseeds verbose @@ -152,7 +154,6 @@ task checkDeterminism(type: ProGuardTask, dependsOn: jdkTask) { defaultTasks "determinise" determinise.finalizedBy metafix metafix.finalizedBy checkDeterminism -assemble.dependsOn checkDeterminism def deterministicJar = metafix.outputs.files.singleFile artifacts { diff --git a/serialization/src/main/kotlin/net/corda/serialization/internal/OrdinalIO.kt b/serialization/src/main/kotlin/net/corda/serialization/internal/OrdinalIO.kt index cc8082bb5b..23e1e3b159 100644 --- a/serialization/src/main/kotlin/net/corda/serialization/internal/OrdinalIO.kt +++ b/serialization/src/main/kotlin/net/corda/serialization/internal/OrdinalIO.kt @@ -8,6 +8,7 @@ import java.nio.ByteBuffer @KeepForDJVM class OrdinalBits(private val ordinal: Int) { + @KeepForDJVM interface OrdinalWriter { val bits: OrdinalBits @JvmDefault val encodedSize get() = 1 diff --git a/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/CustomSerializer.kt b/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/CustomSerializer.kt index f920b6e792..f99a842758 100644 --- a/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/CustomSerializer.kt +++ b/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/CustomSerializer.kt @@ -1,5 +1,6 @@ package net.corda.serialization.internal.amqp +import net.corda.core.KeepForDJVM import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.SerializationContext import net.corda.serialization.internal.amqp.SerializerFactory.Companion.nameForType @@ -58,6 +59,7 @@ abstract class CustomSerializer : AMQPSerializer, SerializerFor { * subclass in the schema, so that we can distinguish between subclasses. */ // TODO: should this be a custom serializer at all, or should it just be a plain AMQPSerializer? + @KeepForDJVM class SubClass(private val clazz: Class<*>, private val superClassSerializer: CustomSerializer) : CustomSerializer() { // TODO: should this be empty or contain the schema of the super? override val schemaForDocumentation = Schema(emptyList()) diff --git a/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformTypes.kt b/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformTypes.kt index 3356ab2e47..74c2582ee3 100644 --- a/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformTypes.kt +++ b/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformTypes.kt @@ -70,6 +70,7 @@ enum class TransformTypes(val build: (Annotation) -> Transform) : DescribedType * @param constants The list of enum constants on the type the transforms are being applied to */ override fun validate(list: List, constants: Map) { + @KeepForDJVM data class Node(val transform: RenameSchemaTransform, var next: Node?, var prev: Node?, var visitedBy: Node? = null) { fun visit(visitedBy: Node) { this.visitedBy = visitedBy diff --git a/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformsSchema.kt b/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformsSchema.kt index 0d63078cd4..d2eda87085 100644 --- a/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformsSchema.kt +++ b/serialization/src/main/kotlin/net/corda/serialization/internal/amqp/TransformsSchema.kt @@ -154,6 +154,7 @@ class EnumDefaultSchemaTransform(val old: String, val new: String) : Transform() * @property from the name of the property or constant prior to being changed, i.e. what it was * @property to the new name of the property or constant after the change has been made, i.e. what it is now */ +@KeepForDJVM class RenameSchemaTransform(val from: String, val to: String) : Transform() { companion object : DescribedTypeConstructor { /** From 15dea871091e451af50b42c80eca85b14c36574a Mon Sep 17 00:00:00 2001 From: Joel Dudley Date: Wed, 4 Jul 2018 10:22:39 +0100 Subject: [PATCH 2/9] Clarifies how to run a network across machines (#3508) * Update tutorial-cordapp.rst * Adds warning box. --- docs/source/tutorial-cordapp.rst | 42 ++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/source/tutorial-cordapp.rst b/docs/source/tutorial-cordapp.rst index 961b17c6dd..eba4a85348 100644 --- a/docs/source/tutorial-cordapp.rst +++ b/docs/source/tutorial-cordapp.rst @@ -411,32 +411,38 @@ For more information on the client RPC interface and how to build an RPC client Running nodes across machines ----------------------------- -The nodes can be split across different machines and configured to communicate across the network. +The nodes can be configured to communicate as a network even when distributed across several machines: -After deploying the nodes, navigate to the build folder (``kotlin-source/build/nodes``) and for each node that needs to -be moved to another machine open its config file and change the Artemis messaging address to the IP address of the machine -where the node will run (e.g. ``p2pAddress="10.18.0.166:10007"``). +* Deploy the nodes as usual: -These changes require new node-info files to be distributed amongst the nodes. Use the network bootstrapper tool -(see :doc:`network-bootstrapper` for more information on this and how to built it) to update the files and have -them distributed locally. + * Unix/Mac OSX: ``./gradlew deployNodes`` + * Windows: ``gradlew.bat deployNodes`` -``java -jar network-bootstrapper.jar kotlin-source/build/nodes`` +* Navigate to the build folder (``kotlin-source/build/nodes``) +* For each node, open its ``node.conf`` file and change ``localhost`` in its ``p2pAddress`` to the IP address of the machine + where the node will be run (e.g. ``p2pAddress="10.18.0.166:10007"``) +* These changes require new node-info files to be distributed amongst the nodes. Use the network bootstrapper tool + (see :doc:`network-bootstrapper`) to update the files and have them distributed locally: -Once that's done move the node folders to their designated machines (e.g. using a USB key). It is important that none of the -nodes - including the notary - end up on more than one machine. Each computer should also have a copy of ``runnodes`` -and ``runnodes.bat``. + ``java -jar network-bootstrapper.jar kotlin-source/build/nodes`` -For example, you may end up with the following layout: +* Move the node folders to their individual machines (e.g. using a USB key). It is important that none of the + nodes - including the notary - end up on more than one machine. Each computer should also have a copy of ``runnodes`` + and ``runnodes.bat``. -* Machine 1: ``Notary``, ``PartyA``, ``runnodes``, ``runnodes.bat`` -* Machine 2: ``PartyB``, ``PartyC``, ``runnodes``, ``runnodes.bat`` + For example, you may end up with the following layout: -After starting each node, the nodes will be able to see one another and agree IOUs among themselves. + * Machine 1: ``Notary``, ``PartyA``, ``runnodes``, ``runnodes.bat`` + * Machine 2: ``PartyB``, ``PartyC``, ``runnodes``, ``runnodes.bat`` -.. note:: If you are using H2 and wish to use the same ``h2port`` value for all the nodes, then only assign them that - value after the nodes have been moved to their machines. The initial bootstrapping process requires access to the nodes' - databases and if they share the same H2 port then the process will fail. +* After starting each node, the nodes will be able to see one another and agree IOUs among themselves + +.. warning:: The bootstrapper must be run **after** the ``node.conf`` files have been modified, but **before** the nodes + are distributed across machines. Otherwise, the nodes will not be able to communicate. + +.. note:: If you are using H2 and wish to use the same ``h2port`` value for two or more nodes, you must only assign them that + value after the nodes have been moved to their individual machines. The initial bootstrapping process requires access to the + nodes' databases and if two nodes share the same H2 port, the process will fail. Testing and debugging --------------------- From f103bdc98a2346bcff0cee73636c4c04bb104c8d Mon Sep 17 00:00:00 2001 From: Joel Dudley Date: Wed, 4 Jul 2018 10:41:38 +0100 Subject: [PATCH 3/9] Document node command-line options (#3490) * Document node command-line options * Addresses review feedback. --- docs/source/running-a-node.rst | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/docs/source/running-a-node.rst b/docs/source/running-a-node.rst index 6f325bc1c2..296f7d9cdd 100644 --- a/docs/source/running-a-node.rst +++ b/docs/source/running-a-node.rst @@ -43,6 +43,27 @@ Optionally run the node's webserver as well by opening a terminal window in the .. warning:: The node webserver is for testing purposes only and will be removed soon. +Command-line options +~~~~~~~~~~~~~~~~~~~~ +The node can optionally be started with the following command-line options: + +* ``--base-directory``: The node working directory where all the files are kept (default: ``.``) +* ``--bootstrap-raft-cluster``: Bootstraps Raft cluster. The node forms a single node cluster (ignoring otherwise configured peer + addresses), acting as a seed for other nodes to join the cluster +* ``--config-file``: The path to the config file (default: ``node.conf``) +* ``--help`` +* ``--initial-registration``: Start initial node registration with Corda network to obtain certificate from the permissioning + server +* ``--just-generate-node-info``: Perform the node start-up task necessary to generate its nodeInfo, save it to disk, then + quit +* ``--log-to-console``: If set, prints logging to the console as well as to a file +* ``--logging-level <[ERROR,WARN,INFO, DEBUG,TRACE]>``: Enable logging at this level and higher (default: INFO) +* ``--network-root-truststore``: Network root trust store obtained from network operator +* ``--network-root-truststore-password``: Network root trust store password obtained from network operator +* ``--no-local-shell``: Do not start the embedded shell locally +* ``--sshd``: Enables SSHD server for node administration +* ``--version``: Print the version and exit + Enabling remote debugging ~~~~~~~~~~~~~~~~~~~~~~~~~ To enable remote debugging of the node, run the following from the terminal window: @@ -51,8 +72,11 @@ To enable remote debugging of the node, run the following from the terminal wind This command line will start the debugger on port 5005 and pause the process awaiting debugger attachment. -Starting all nodes at once from the command line (native) ---------------------------------------------------------- +Starting all nodes at once from the command line +------------------------------------------------ + +Native +~~~~~~ If you created your nodes using ``deployNodes``, a ``runnodes`` shell script (or batch file on Windows) will have been generated to allow you to quickly start up all nodes and their webservers. ``runnodes`` should only be used for testing purposes. @@ -69,8 +93,8 @@ If you receive an ``OutOfMemoryError`` exception when interacting with the nodes Java heap memory available to them, which you can do when running them individually. See :ref:`starting-an-individual-corda-node`. -Starting all nodes at once from the command line (docker-compose) ------------------------------------------------------------------ +docker-compose +~~~~~~~~~~~~~~ If you created your nodes using ``Dockerform``, the ``docker-compose.yml`` file and corresponding ``Dockerfile`` for nodes has been created and configured appropriately. Navigate to ``build/nodes`` directory and run ``docker-compose up`` command. This will startup nodes inside new, internal network. From f19564f9f8654cae812ae1ebf895671576148ce6 Mon Sep 17 00:00:00 2001 From: Stefano Franz Date: Wed, 4 Jul 2018 11:33:21 +0100 Subject: [PATCH 4/9] add simple network verification cordapp (#3412) * add simple network verification cordapp * add ability to filter checked counterparties to specific x500 --- samples/network-verifier/build.gradle | 49 +++++++++++ .../net/corda/verification/TestCommsFlow.kt | 81 +++++++++++++++++++ .../net/corda/verification/TestNotaryFlow.kt | 65 +++++++++++++++ .../TestCommsFlowInitiatorTest.kt | 34 ++++++++ settings.gradle | 1 + 5 files changed, 230 insertions(+) create mode 100644 samples/network-verifier/build.gradle create mode 100644 samples/network-verifier/src/main/kotlin/net/corda/verification/TestCommsFlow.kt create mode 100644 samples/network-verifier/src/main/kotlin/net/corda/verification/TestNotaryFlow.kt create mode 100644 samples/network-verifier/src/test/kotlin/net/corda/configsample/TestCommsFlowInitiatorTest.kt diff --git a/samples/network-verifier/build.gradle b/samples/network-verifier/build.gradle new file mode 100644 index 0000000000..f64efcc692 --- /dev/null +++ b/samples/network-verifier/build.gradle @@ -0,0 +1,49 @@ +apply plugin: 'kotlin' +apply plugin: 'java' +apply plugin: 'net.corda.plugins.cordapp' +apply plugin: 'net.corda.plugins.cordformation' + +dependencies { + cordaCompile project(":core") + cordaCompile project(":node-api") + cordaCompile project(path: ":node:capsule", configuration: 'runtimeArtifacts') + + testCompile project(":test-utils") + testCompile "junit:junit:$junit_version" +} + +task deployNodes(type: net.corda.plugins.Cordform, dependsOn: ['jar']) { + ext.rpcUsers = [['username': "default", 'password': "default", 'permissions': [ 'ALL' ]]] + + directory "./build/nodes" + node { + name "O=Notary Service,L=Zurich,C=CH" + notary = [validating : false] + p2pPort 10002 + rpcSettings { + port 10003 + adminPort 10004 + } + h2Port 20004 + } + node { + name "O=Bank A,L=London,C=GB" + p2pPort 10005 + cordapps = [] + rpcUsers = ext.rpcUsers + rpcSettings { + port 10007 + adminPort 10008 + } + } + node { + name "O=Bank B,L=New York,C=US" + p2pPort 10009 + cordapps = [] + rpcUsers = ext.rpcUsers + rpcSettings { + port 10011 + adminPort 10012 + } + } +} \ No newline at end of file diff --git a/samples/network-verifier/src/main/kotlin/net/corda/verification/TestCommsFlow.kt b/samples/network-verifier/src/main/kotlin/net/corda/verification/TestCommsFlow.kt new file mode 100644 index 0000000000..3437cce254 --- /dev/null +++ b/samples/network-verifier/src/main/kotlin/net/corda/verification/TestCommsFlow.kt @@ -0,0 +1,81 @@ +package net.corda.verification + +import co.paralleluniverse.fibers.Suspendable +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.Contract +import net.corda.core.contracts.ContractState +import net.corda.core.flows.* +import net.corda.core.identity.AbstractParty +import net.corda.core.identity.CordaX500Name +import net.corda.core.identity.Party +import net.corda.core.serialization.CordaSerializable +import net.corda.core.transactions.LedgerTransaction +import net.corda.core.transactions.TransactionBuilder +import net.corda.core.utilities.ProgressTracker +import net.corda.core.utilities.unwrap + + +@StartableByRPC +@InitiatingFlow +class TestCommsFlowInitiator(val x500Name: CordaX500Name? = null) : FlowLogic>() { + + object SENDING : ProgressTracker.Step("SENDING") + object RECIEVED_ALL : ProgressTracker.Step("RECIEVED_ALL") + object FINALIZING : ProgressTracker.Step("FINALIZING") + + override val progressTracker: ProgressTracker = ProgressTracker(SENDING, RECIEVED_ALL, FINALIZING) + + @Suspendable + override fun call(): List { + progressTracker.currentStep = SENDING + val responses = serviceHub.networkMapCache.allNodes.map { + it.legalIdentities.first() + }.filterNot { + it in serviceHub.myInfo.legalIdentities + }.filterNot { + it in serviceHub.networkMapCache.notaryIdentities + }.filter(::matchesX500) + .map { + val initiateFlow = initiateFlow(it) + initiateFlow.receive().unwrap { it } + }.toList().also { + progressTracker.currentStep = RECIEVED_ALL + } + val tx = TransactionBuilder(notary = serviceHub.networkMapCache.notaryIdentities.first()) + tx.addOutputState(CommsTestState(responses, serviceHub.myInfo.legalIdentities.first()), CommsTestContract::class.qualifiedName!!) + tx.addCommand(CommsTestCommand, serviceHub.myInfo.legalIdentities.first().owningKey) + val signedTx = serviceHub.signInitialTransaction(tx) + subFlow(FinalityFlow(signedTx)) + return responses + } + + fun matchesX500(it: Party): Boolean { + return x500Name?.equals(it.name) ?: true + } +} + +@InitiatedBy(TestCommsFlowInitiator::class) +class TestCommsFlowResponder(val otherSideSession: FlowSession) : FlowLogic() { + @Suspendable + override fun call() { + otherSideSession.send("Hello from: " + serviceHub.myInfo.legalIdentities.first().name.toString()) + } + +} + +@CordaSerializable +data class CommsTestState(val responses: List, val issuer: AbstractParty) : ContractState { + override val participants: List + get() = listOf(issuer) + +} + + +@CordaSerializable +object CommsTestCommand : CommandData + + +class CommsTestContract : Contract { + override fun verify(tx: LedgerTransaction) { + } +} \ No newline at end of file diff --git a/samples/network-verifier/src/main/kotlin/net/corda/verification/TestNotaryFlow.kt b/samples/network-verifier/src/main/kotlin/net/corda/verification/TestNotaryFlow.kt new file mode 100644 index 0000000000..91b8d4bbec --- /dev/null +++ b/samples/network-verifier/src/main/kotlin/net/corda/verification/TestNotaryFlow.kt @@ -0,0 +1,65 @@ +package net.corda.verification + +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.Contract +import net.corda.core.contracts.ContractState +import net.corda.core.flows.FinalityFlow +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.StartableByRPC +import net.corda.core.identity.AbstractParty +import net.corda.core.serialization.CordaSerializable +import net.corda.core.transactions.LedgerTransaction +import net.corda.core.transactions.TransactionBuilder +import net.corda.core.utilities.ProgressTracker + + +@StartableByRPC +class TestNotaryFlow : FlowLogic() { + + object ISSUING : ProgressTracker.Step("ISSUING") + object ISSUED : ProgressTracker.Step("ISSUED") + object DESTROYING : ProgressTracker.Step("DESTROYING") + object FINALIZED : ProgressTracker.Step("FINALIZED") + + override val progressTracker: ProgressTracker = ProgressTracker(ISSUING, ISSUED, DESTROYING, FINALIZED) + + + override fun call(): String { + val issueBuilder = TransactionBuilder() + val notary = serviceHub.networkMapCache.notaryIdentities.first() + issueBuilder.notary = notary; + val myIdentity = serviceHub.myInfo.legalIdentities.first() + issueBuilder.addOutputState(NotaryTestState(notary.name.toString(), myIdentity), NotaryTestContract::class.qualifiedName!!) + issueBuilder.addCommand(NotaryTestCommand, myIdentity.owningKey) + val signedTx = serviceHub.signInitialTransaction(issueBuilder) + val issueResult = subFlow(FinalityFlow(signedTx)) + progressTracker.currentStep = ISSUED + val destroyBuilder = TransactionBuilder() + destroyBuilder.notary = notary; + destroyBuilder.addInputState(issueResult.tx.outRefsOfType().first()) + destroyBuilder.addCommand(NotaryTestCommand, myIdentity.owningKey) + val signedDestroyT = serviceHub.signInitialTransaction(destroyBuilder) + val result = subFlow(FinalityFlow(signedDestroyT)) + progressTracker.currentStep = DESTROYING + progressTracker.currentStep = FINALIZED + return "notarised: " + result.notary.toString() + "::" + result.tx.id + } +} + + +@CordaSerializable +data class NotaryTestState(val id: String, val issuer: AbstractParty) : ContractState { + override val participants: List + get() = listOf(issuer) + +} + + +@CordaSerializable +object NotaryTestCommand : CommandData + + +class NotaryTestContract : Contract { + override fun verify(tx: LedgerTransaction) { + } +} \ No newline at end of file diff --git a/samples/network-verifier/src/test/kotlin/net/corda/configsample/TestCommsFlowInitiatorTest.kt b/samples/network-verifier/src/test/kotlin/net/corda/configsample/TestCommsFlowInitiatorTest.kt new file mode 100644 index 0000000000..d0974f0eba --- /dev/null +++ b/samples/network-verifier/src/test/kotlin/net/corda/configsample/TestCommsFlowInitiatorTest.kt @@ -0,0 +1,34 @@ +package net.corda.configsample + +import net.corda.testing.core.ALICE_NAME +import net.corda.testing.core.DUMMY_BANK_A_NAME +import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.core.TestIdentity +import net.corda.verification.TestCommsFlowInitiator +import org.junit.Assert +import org.junit.Test + +class TestCommsFlowInitiatorTest { + + val ALICE = TestIdentity(ALICE_NAME, 70) + val NOTARY = TestIdentity(DUMMY_NOTARY_NAME, 12) + val DUMMY_BANK_A = TestIdentity(DUMMY_BANK_A_NAME, 3) + + @Test + fun `should allow all node infos through if no x500 is passed`() { + val testCommsFlowInitiator = TestCommsFlowInitiator() + + Assert.assertTrue(testCommsFlowInitiator.matchesX500(ALICE.party)) + Assert.assertTrue(testCommsFlowInitiator.matchesX500(NOTARY.party)) + Assert.assertTrue(testCommsFlowInitiator.matchesX500(DUMMY_BANK_A.party)) + } + + @Test + fun `should allow only specified x500 if no x500 is passed`() { + val testCommsFlowInitiator = TestCommsFlowInitiator(ALICE_NAME) + + Assert.assertTrue(testCommsFlowInitiator.matchesX500(ALICE.party)) + Assert.assertFalse(testCommsFlowInitiator.matchesX500(NOTARY.party)) + Assert.assertFalse(testCommsFlowInitiator.matchesX500(DUMMY_BANK_A.party)) + } +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 9f1701e383..0cb65be579 100644 --- a/settings.gradle +++ b/settings.gradle @@ -58,5 +58,6 @@ include 'samples:simm-valuation-demo:contracts-states' include 'samples:notary-demo' include 'samples:bank-of-corda-demo' include 'samples:cordapp-configuration' +include 'samples:network-verifier' include 'serialization' include 'serialization-deterministic' From b8e6c47cfdbe2301e305d103e0e7c9844c195656 Mon Sep 17 00:00:00 2001 From: Shams Asari Date: Wed, 4 Jul 2018 15:39:22 +0100 Subject: [PATCH 5/9] Added missing JacksonSupport unit test for Instant (#3507) --- .../kotlin/net/corda/client/jackson/JacksonSupportTest.kt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/client/jackson/src/test/kotlin/net/corda/client/jackson/JacksonSupportTest.kt b/client/jackson/src/test/kotlin/net/corda/client/jackson/JacksonSupportTest.kt index 9a7c0a8dfb..374009264c 100644 --- a/client/jackson/src/test/kotlin/net/corda/client/jackson/JacksonSupportTest.kt +++ b/client/jackson/src/test/kotlin/net/corda/client/jackson/JacksonSupportTest.kt @@ -391,6 +391,11 @@ class JacksonSupportTest(@Suppress("unused") private val name: String, factory: testToStringSerialisation(UUID.randomUUID()) } + @Test + fun Instant() { + testToStringSerialisation(Instant.now()) + } + @Test fun `Date is treated as Instant`() { val date = Date() From d634cdcbac7bf86528e94a4e91b088bdd9943802 Mon Sep 17 00:00:00 2001 From: Chris Rankin Date: Wed, 4 Jul 2018 15:42:43 +0100 Subject: [PATCH 6/9] Clear some cut-and-paste cruft out of our Gradle files. (#3511) --- experimental/avalanche/build.gradle | 34 +++++--------------- experimental/behave/build.gradle | 41 +++++-------------------- experimental/build.gradle | 2 +- experimental/kryo-hook/build.gradle | 25 ++------------- experimental/quasar-hook/build.gradle | 25 ++------------- samples/irs-demo/build.gradle | 4 +-- tools/network-bootstrapper/build.gradle | 11 +------ 7 files changed, 22 insertions(+), 120 deletions(-) diff --git a/experimental/avalanche/build.gradle b/experimental/avalanche/build.gradle index ea6e2a4632..82cfd5135d 100644 --- a/experimental/avalanche/build.gradle +++ b/experimental/avalanche/build.gradle @@ -1,41 +1,23 @@ buildscript { - ext.kotlin_version = '1.2.40' - repositories { - mavenCentral() jcenter() } dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.3' + classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" } } -plugins { - id "org.jetbrains.kotlin.jvm" - id 'com.github.johnrengelman.shadow' version '2.0.3' - id 'java' - id 'application' -} -repositories { - mavenCentral() -} +apply plugin: 'kotlin' +apply plugin: 'application' +apply plugin: 'com.github.johnrengelman.shadow' + dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile group: 'info.picocli', name: 'picocli', version: '3.0.1' - testCompile group: 'junit', name: 'junit', version: '4.12' -} -compileKotlin { - kotlinOptions { - jvmTarget = "1.8" - } -} -compileTestKotlin { - kotlinOptions { - jvmTarget = "1.8" - } + compile "info.picocli:picocli:3.0.1" + testCompile "junit:junit:$junit_version" } + mainClassName = "net.corda.avalanche.MainKt" shadowJar { baseName = "avalanche" diff --git a/experimental/behave/build.gradle b/experimental/behave/build.gradle index 4ccc01426e..c5cba5eb8a 100644 --- a/experimental/behave/build.gradle +++ b/experimental/behave/build.gradle @@ -1,33 +1,14 @@ -buildscript { - ext.commonsio_version = '2.6' - ext.commonslogging_version = '1.2' - ext.cucumber_version = '1.2.5' - ext.crash_version = 'cce5a00f114343c1145c1d7756e1dd6df3ea984e' - ext.docker_client_version = '8.11.0' - - repositories { - maven { - jcenter() - url 'https://jitpack.io' - } - } - - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } +ext { + commonsio_version = '2.6' + cucumber_version = '1.2.5' + crash_version = 'cce5a00f114343c1145c1d7756e1dd6df3ea984e' + docker_client_version = '8.11.0' } group 'net.corda.behave' -apply plugin: 'java' apply plugin: 'kotlin' -sourceCompatibility = 1.8 - -repositories { - mavenCentral() -} - sourceSets { behave { java { @@ -63,6 +44,7 @@ dependencies { compile "org.slf4j:log4j-over-slf4j:$slf4j_version" compile "org.slf4j:jul-to-slf4j:$slf4j_version" + compile "org.slf4j:jcl-over-slf4j:$slf4j_version" compile "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version" compile "org.apache.logging.log4j:log4j-core:$log4j_version" @@ -70,10 +52,9 @@ dependencies { compile "net.sf.jopt-simple:jopt-simple:$jopt_simple_version" // FastClasspathScanner: classpath scanning - compile 'io.github.lukehutch:fast-classpath-scanner:2.12.3' + compile "io.github.lukehutch:fast-classpath-scanner:$fast_classpath_scanner_version" compile "commons-io:commons-io:$commonsio_version" - compile "commons-logging:commons-logging:$commonslogging_version" compile "com.spotify:docker-client:$docker_client_version" compile "io.reactivex:rxjava:$rxjava_version" @@ -93,14 +74,6 @@ dependencies { behaveCompile "info.cukes:cucumber-picocontainer:$cucumber_version" } -compileKotlin { - kotlinOptions.jvmTarget = "1.8" -} - -compileTestKotlin { - kotlinOptions.jvmTarget = "1.8" -} - test { testLogging.showStandardStreams = true } diff --git a/experimental/build.gradle b/experimental/build.gradle index c5a39773ee..2aa7d36615 100644 --- a/experimental/build.gradle +++ b/experimental/build.gradle @@ -24,7 +24,7 @@ dependencies { compile project(':finance') // ObjectWeb Asm: a library for synthesising and working with JVM bytecode. - compile "org.ow2.asm:asm:5.0.4" + compile "org.ow2.asm:asm:$asm_version" compile "com.google.guava:guava:$guava_version" diff --git a/experimental/kryo-hook/build.gradle b/experimental/kryo-hook/build.gradle index 2926bc00ae..040b2e5f80 100644 --- a/experimental/kryo-hook/build.gradle +++ b/experimental/kryo-hook/build.gradle @@ -1,26 +1,5 @@ -buildscript { - // For sharing constants between builds - Properties constants = new Properties() - file("$projectDir/../../constants.properties").withInputStream { constants.load(it) } - - ext.kotlin_version = constants.getProperty("kotlinVersion") - ext.javaassist_version = "3.12.1.GA" - - repositories { - mavenLocal() - mavenCentral() - jcenter() - } - - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -repositories { - mavenLocal() - mavenCentral() - jcenter() +ext { + javaassist_version = "3.12.1.GA" } apply plugin: 'kotlin' diff --git a/experimental/quasar-hook/build.gradle b/experimental/quasar-hook/build.gradle index 72e3a19fbf..c2387079a8 100644 --- a/experimental/quasar-hook/build.gradle +++ b/experimental/quasar-hook/build.gradle @@ -1,26 +1,5 @@ -buildscript { - // For sharing constants between builds - Properties constants = new Properties() - file("$projectDir/../../constants.properties").withInputStream { constants.load(it) } - - ext.kotlin_version = constants.getProperty("kotlinVersion") - ext.javaassist_version = "3.12.1.GA" - - repositories { - mavenLocal() - mavenCentral() - jcenter() - } - - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -repositories { - mavenLocal() - mavenCentral() - jcenter() +ext { + javaassist_version = "3.12.1.GA" } apply plugin: 'kotlin' diff --git a/samples/irs-demo/build.gradle b/samples/irs-demo/build.gradle index b116b7d8e9..f1fb1ef397 100644 --- a/samples/irs-demo/build.gradle +++ b/samples/irs-demo/build.gradle @@ -58,9 +58,7 @@ repositories { maven { url 'https://dl.bintray.com/palantir/releases' // docker-compose-rule is published on bintray } - repositories { - maven { url 'https://jitpack.io' } - } + maven { url 'https://jitpack.io' } } dependencies { diff --git a/tools/network-bootstrapper/build.gradle b/tools/network-bootstrapper/build.gradle index b49b5e87bc..ef2eab205d 100644 --- a/tools/network-bootstrapper/build.gradle +++ b/tools/network-bootstrapper/build.gradle @@ -11,19 +11,10 @@ buildscript { } dependencies { - classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version" - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1' + classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" } } -repositories { - mavenLocal() - mavenCentral() - jcenter() -} - - apply plugin: 'kotlin' apply plugin: 'idea' apply plugin: 'java' From 68d0826563ca0bc43ad934b09b09c43420701c1b Mon Sep 17 00:00:00 2001 From: Patrick Kuo Date: Wed, 4 Jul 2018 16:51:54 +0100 Subject: [PATCH 7/9] Custom config parser for more complex config structure (#3513) * custom config parser for more complex config structure * address PR issues --- .../internal/config/ConfigUtilities.kt | 18 ++++++++++- .../internal/config/ConfigParsingTest.kt | 31 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/ConfigUtilities.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/ConfigUtilities.kt index f3b78acd4e..b3ee7f06ee 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/ConfigUtilities.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/ConfigUtilities.kt @@ -25,6 +25,8 @@ import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KType +import kotlin.reflect.full.createInstance +import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor import kotlin.reflect.jvm.jvmErasure @@ -32,6 +34,17 @@ import kotlin.reflect.jvm.jvmErasure @Target(AnnotationTarget.PROPERTY) annotation class OldConfig(val value: String) +/** + * This annotation can be used to provide ConfigParser for the class, + * the [parseAs] method will use the provided parser instead of data class constructs to parse the object. + */ +@Target(AnnotationTarget.CLASS) +annotation class CustomConfigParser(val parser: KClass>) + +interface ConfigParser { + fun parse(config: Config): T +} + const val CUSTOM_NODE_PROPERTIES_ROOT = "custom" // TODO Move other config parsing to use parseAs and remove this @@ -40,7 +53,10 @@ operator fun Config.getValue(receiver: Any, metadata: KProperty<*>): T } fun Config.parseAs(clazz: KClass, onUnknownKeys: ((Set, logger: Logger) -> Unit) = UnknownConfigKeysPolicy.FAIL::handle, nestedPath: String? = null): T { - require(clazz.isData) { "Only Kotlin data classes can be parsed. Offending: ${clazz.qualifiedName}" } + // Use custom parser if provided, instead of treating the object as data class. + clazz.findAnnotation()?.let { return uncheckedCast(it.parser.createInstance().parse(this)) } + + require(clazz.isData) { "Only Kotlin data classes or class annotated with CustomConfigParser can be parsed. Offending: ${clazz.qualifiedName}" } val constructor = clazz.primaryConstructor!! val parameters = constructor.parameters val parameterNames = parameters.flatMap { param -> diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt index 688e6d53f9..07698b83c3 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt @@ -227,6 +227,36 @@ class ConfigParsingTest { } } + @Test + fun `parse with provided parser`() { + val type1Config = mapOf("type" to "1", "value" to "type 1 value") + val type2Config = mapOf("type" to "2", "value" to "type 2 value") + + val configuration = config("values" to listOf(type1Config, type2Config)) + val objects = configuration.parseAs() + + assertThat(objects.values).containsExactly(TestObject.Type1("type 1 value"), TestObject.Type2("type 2 value")) + } + + class TestParser : ConfigParser { + override fun parse(config: Config): TestObject { + val type = config.getInt("type") + return when (type) { + 1 -> config.parseAs(onUnknownKeys = UnknownConfigKeysPolicy.IGNORE::handle) + 2 -> config.parseAs(onUnknownKeys = UnknownConfigKeysPolicy.IGNORE::handle) + else -> throw IllegalArgumentException("Unsupported Object type : '$type'") + } + } + } + + data class TestObjects(val values: List) + + @CustomConfigParser(TestParser::class) + sealed class TestObject { + data class Type1(val value: String) : TestObject() + data class Type2(val value: String) : TestObject() + } + private inline fun , reified L : ListData, V : Any> testPropertyType( value1: V, value2: V, @@ -310,6 +340,7 @@ class ConfigParsingTest { require(positive > 0) { "$positive is not positive" } } } + data class OldData( @OldConfig("oldValue") val newValue: String) From 244167d3e906fe2e883447071ad5b1df813cf04c Mon Sep 17 00:00:00 2001 From: Shams Asari Date: Wed, 4 Jul 2018 17:17:27 +0100 Subject: [PATCH 8/9] Enabled warnings as errors (#3514) --- .idea/compiler.xml | 2 + build.gradle | 1 + .../corda/client/jfx/NodeMonitorModelTest.kt | 25 +------- .../client/jfx/model/NodeMonitorModel.kt | 2 +- .../client/jfx/model/TransactionDataModel.kt | 5 +- .../client/rpc/FlowsExecutionModeRpcTest.kt | 10 +-- .../node/services/KeyManagementService.kt | 4 ++ .../net/corda/core/schemas/PersistentTypes.kt | 2 +- .../core/transactions/WireTransaction.kt | 2 +- .../corda/core/contracts/ContractsDSLTests.kt | 9 ++- .../core/crypto/PartialMerkleTreeTest.kt | 3 +- .../net/corda/core/flows/AttachmentTests.kt | 4 +- .../internal/ResolveTransactionsFlowTest.kt | 3 +- .../core/internal/TopologicalSortTest.kt | 8 +-- .../core/transactions/TransactionTests.kt | 15 ++--- .../net/corda/docs/ClientRpcTutorial.kt | 2 + .../kotlin/net/corda/docs/FlowCookbook.kt | 2 +- .../net/corda/docs/LaunchSpaceshipFlow.kt | 2 + .../tutorial/tearoffs/TutorialTearOffs.kt | 4 +- .../behave/scenarios/helpers/Substeps.kt | 19 +++--- .../net/corda/behave/process/CommandTests.kt | 3 +- experimental/kryo-hook/build.gradle | 1 - experimental/quasar-hook/build.gradle | 1 - .../contracts/universal/PrettyPrint.kt | 61 +++++++++---------- .../contracts/universal/UniversalContract.kt | 31 +++++----- .../corda/finance/contracts/universal/IRS.kt | 41 +++++++------ .../kotlin/net/corda/node/AuthDBTests.kt | 16 ++--- .../registration/NodeRegistrationTest.kt | 4 +- .../messaging/MQSecurityAsNodeTest.kt | 4 +- .../services/messaging/MQSecurityAsRPCTest.kt | 2 +- .../services/messaging/MQSecurityTest.kt | 9 +-- .../node/services/config/NodeConfiguration.kt | 29 ++------- .../identity/InMemoryIdentityService.kt | 2 +- .../keys/E2ETestKeyManagementService.kt | 2 +- .../net/corda/node/services/keys/KMSUtils.kt | 3 +- .../keys/PersistentKeyManagementService.kt | 5 +- .../SingleThreadedStateMachineManager.kt | 21 +++---- .../statemachine/StaffedFlowHospital.kt | 7 +-- .../statemachine/StateMachineState.kt | 1 - .../interceptors/HospitalisingInterceptor.kt | 4 +- .../node/utilities/AppendOnlyPersistentMap.kt | 47 +++++++------- .../services/vault/VaultQueryJavaTests.java | 20 ++---- .../net/corda/node/CordaRPCOpsImplTest.kt | 10 +-- .../net/corda/node/internal/NodeTest.kt | 2 +- .../RoundTripObservableSerializerTests.kt | 11 ++-- .../RpcServerObservableSerializerTests.kt | 7 +-- .../events/NodeSchedulerServiceTest.kt | 33 +++------- .../messaging/ArtemisMessagingTest.kt | 4 +- .../persistence/DBCheckpointStorageTests.kt | 2 +- .../persistence/DBTransactionStorageTests.kt | 15 +++-- .../persistence/HibernateConfigurationTest.kt | 35 ++++++----- .../persistence/NodeAttachmentStorageTest.kt | 21 +++---- .../transactions/MaxTransactionSizeTests.kt | 22 ++++--- .../node/services/vault/VaultQueryTests.kt | 7 +-- .../node/services/vault/VaultWithCashTest.kt | 12 ++-- .../corda/node/utilities/ObservablesTests.kt | 5 +- .../attachmentdemo/AttachmentDemoTest.kt | 13 +--- .../corda/attachmentdemo/AttachmentDemo.kt | 3 +- .../net/corda/test/spring/SpringDriver.kt | 2 + .../internal/amqp/JavaGenericsTest.java | 8 +-- .../amqp/JavaPrivatePropertyTests.java | 9 ++- .../ContractAttachmentSerializerTest.kt | 5 +- .../internal/amqp/ErrorMessagesTests.kt | 18 +++--- .../internal/amqp/GenericsTests.kt | 10 +-- .../internal/amqp/PrivatePropertyTests.kt | 2 +- .../internal/amqp/RoundTripTests.kt | 20 +++--- .../internal/amqp/SerializationOutputTests.kt | 15 +++-- .../amqp/SerializationPropertyOrdering.kt | 2 +- .../node/internal/MockKeyManagementService.kt | 2 +- .../testing/node/internal/NodeBasedTest.kt | 6 +- .../testing/internal/InternalTestUtils.kt | 15 +++++ .../corda/demobench/views/NodeTerminalView.kt | 1 + .../bootstrapper/cli/CommandLineInterface.kt | 5 +- .../net/corda/bootstrapper/context/Context.kt | 7 +-- .../corda/bootstrapper/nodes/NodeFinder.kt | 7 +-- .../bootstrapper/nodes/NodeInstantiator.kt | 11 ++-- .../serialization/SerializationHelper.kt | 5 +- 77 files changed, 349 insertions(+), 441 deletions(-) diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 356d4cafaa..e1cb19e8be 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -127,6 +127,8 @@ + + diff --git a/build.gradle b/build.gradle index a960fb5c55..16451c7059 100644 --- a/build.gradle +++ b/build.gradle @@ -172,6 +172,7 @@ allprojects { jvmTarget = "1.8" javaParameters = true // Useful for reflection. freeCompilerArgs = ['-Xjvm-default=compatibility'] + allWarningsAsErrors = true } } diff --git a/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt b/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt index ab405af19b..8f5c1fe4dd 100644 --- a/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt +++ b/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt @@ -3,7 +3,6 @@ package net.corda.client.jfx import net.corda.client.jfx.model.NodeMonitorModel import net.corda.client.jfx.model.ProgressTrackingEvent import net.corda.core.context.InvocationOrigin -import net.corda.core.contracts.Amount import net.corda.core.contracts.ContractState import net.corda.core.crypto.isFulfilledBy import net.corda.core.crypto.keys @@ -22,12 +21,9 @@ import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.getOrThrow import net.corda.finance.DOLLARS -import net.corda.finance.USD -import net.corda.finance.flows.CashExitFlow import net.corda.finance.flows.CashIssueFlow import net.corda.finance.flows.CashPaymentFlow -import net.corda.node.services.Permissions.Companion.invokeRpc -import net.corda.node.services.Permissions.Companion.startFlow +import net.corda.node.services.Permissions.Companion.all import net.corda.testing.core.* import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.driver @@ -54,18 +50,7 @@ class NodeMonitorModelTest { private fun setup(runTest: () -> Unit) { driver(DriverParameters(extraCordappPackagesToScan = listOf("net.corda.finance"))) { - val cashUser = User("user1", "test", permissions = setOf( - startFlow(), - startFlow(), - startFlow(), - invokeRpc(CordaRPCOps::notaryIdentities), - invokeRpc("vaultTrackBy"), - invokeRpc("vaultQueryBy"), - invokeRpc(CordaRPCOps::internalVerifiedTransactionsFeed), - invokeRpc(CordaRPCOps::stateMachineRecordedTransactionMappingFeed), - invokeRpc(CordaRPCOps::stateMachinesFeed), - invokeRpc(CordaRPCOps::networkMapFeed)) - ) + val cashUser = User("user1", "test", permissions = setOf(all())) val aliceNodeHandle = startNode(providedName = ALICE_NAME, rpcUsers = listOf(cashUser)).getOrThrow() aliceNode = aliceNodeHandle.nodeInfo newNode = { nodeName -> startNode(providedName = nodeName).getOrThrow().nodeInfo } @@ -114,11 +99,7 @@ class NodeMonitorModelTest { @Test fun `cash issue works end to end`() = setup { - rpc.startFlow(::CashIssueFlow, - Amount(100, USD), - OpaqueBytes(ByteArray(1, { 1 })), - notaryParty - ) + rpc.startFlow(::CashIssueFlow, 100.DOLLARS, OpaqueBytes.of(1), notaryParty) vaultUpdates.expectEvents(isStrict = false) { sequence( diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt index 26d9bf09d5..eb8e78898f 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt @@ -101,12 +101,12 @@ class NodeMonitorModel : AutoCloseable { * TODO provide an unsubscribe mechanism */ fun register(nodeHostAndPort: NetworkHostAndPort, username: String, password: String) { - // `retryableStateMachineUpdatesSubject` will change it's upstream subscriber in case of RPC connection failure, this `Observable` should // never produce an error. // `stateMachineUpdatesSubject` will stay firmly subscribed to `retryableStateMachineUpdatesSubject` retryableStateMachineUpdatesSubject.subscribe(stateMachineUpdatesSubject) + @Suppress("DEPRECATION") // Proxy may change during re-connect, ensure that subject wiring accurately reacts to this activity. proxyObservable.addListener { _, _, wrapper -> if (wrapper != null) { diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt index 900ed8fd42..7d208748c8 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt @@ -48,7 +48,7 @@ data class PartiallyResolvedTransaction( return PartiallyResolvedTransaction( transaction = transaction, inputs = transaction.inputs.map { stateRef -> - val tx = inputTransactions.get(stateRef) + val tx = inputTransactions[stateRef] if (tx == null) { InputResolution.Unresolved(stateRef) } else { @@ -64,7 +64,7 @@ data class PartiallyResolvedTransaction( val outputCount = transaction.coreTransaction.inputs.size val stateRefs = (0 until outputCount).map { StateRef(transaction.id, it) } stateRefs.map { stateRef -> - val tx = inputTransactions.get(stateRef) + val tx = inputTransactions[stateRef] if (tx == null) { OutputResolution.Unresolved(stateRef) } else { @@ -84,6 +84,7 @@ class TransactionDataModel { private val collectedTransactions = transactions.recordInSequence().distinctBy { it.id } private val rpcProxy by observableValue(NodeMonitorModel::proxyObservable) + @Suppress("DEPRECATION") val partiallyResolvedTransactions = collectedTransactions.map { PartiallyResolvedTransaction.fromSignedTransaction(it, it.inputs.map { stateRef -> diff --git a/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt b/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt index 98bb322323..2d9cde9b38 100644 --- a/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt +++ b/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt @@ -54,14 +54,12 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract @Before fun setup() { - node = startNode(ALICE_NAME, rpcUsers = listOf(rpcUser)) - client = CordaRPCClient(node.internals.configuration.rpcOptions.address!!) + client = CordaRPCClient(node.internals.configuration.rpcOptions.address) } @Test fun `flows draining mode can be enabled and queried`() { - asALoggerUser { rpcOps -> val newValue = true rpcOps.setFlowsDrainingModeEnabled(true) @@ -74,7 +72,6 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract @Test fun `flows draining mode can be disabled and queried`() { - asALoggerUser { rpcOps -> rpcOps.setFlowsDrainingModeEnabled(true) val newValue = false @@ -88,7 +85,6 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract @Test fun `node starts with flows draining mode disabled`() { - asALoggerUser { rpcOps -> val defaultStartingMode = rpcOps.isFlowsDrainingModeEnabled() @@ -97,14 +93,12 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract } private fun login(username: String, password: String, externalTrace: Trace? = null, impersonatedActor: Actor? = null): CordaRPCConnection { - return client.start(username, password, externalTrace, impersonatedActor) } private fun asALoggerUser(action: (CordaRPCOps) -> Unit) { - login(rpcUser.username, rpcUser.password).use { action(it.proxy) } } -} \ No newline at end of file +} diff --git a/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt b/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt index 7b4801b112..14ba9b21c0 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt @@ -2,11 +2,15 @@ package net.corda.core.node.services import co.paralleluniverse.fibers.Suspendable import net.corda.core.DoNotImplement +import net.corda.core.crypto.CompositeKey import net.corda.core.crypto.DigitalSignature import net.corda.core.crypto.SignableData import net.corda.core.crypto.TransactionSignature import net.corda.core.identity.PartyAndCertificate +import java.security.KeyPair +import java.security.PrivateKey import java.security.PublicKey +import java.security.cert.X509Certificate /** * The KMS is responsible for storing and using private keys to sign things. An implementation of this may, for example, diff --git a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt index 6e6e7ea34f..a4f7391f40 100644 --- a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt +++ b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt @@ -122,7 +122,7 @@ object MappedSchemaValidator { fieldsFromOtherMappedSchema(schema) + methodsFromOtherMappedSchema(schema) /** Returns true if [javax.persistence] annotation expect [javax.persistence.Transient] is found. */ - private inline fun hasJpaAnnotation(annotations: Array) = + private fun hasJpaAnnotation(annotations: Array) = annotations.any { annotation -> annotation.toString().startsWith("@javax.persistence.") && annotation !is javax.persistence.Transient } class SchemaCrossReferenceReport(private val schema: String, private val entity: String, private val referencedSchema: String, diff --git a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt index 6f4a63b898..e3697f9d00 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt @@ -48,7 +48,7 @@ class WireTransaction(componentGroups: List, val privacySalt: Pr @DeleteForDJVM constructor(componentGroups: List) : this(componentGroups, PrivacySalt()) - @Deprecated("Required only in some unit-tests and for backwards compatibility purposes.", ReplaceWith("WireTransaction(val componentGroups: List, override val privacySalt: PrivacySalt)"), DeprecationLevel.WARNING) + @Deprecated("Required only for backwards compatibility purposes.", ReplaceWith("WireTransaction(val componentGroups: List, override val privacySalt: PrivacySalt)"), DeprecationLevel.WARNING) @DeleteForDJVM constructor(inputs: List, attachments: List, diff --git a/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt b/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt index bfb54e5e78..57320d7eb9 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt @@ -31,7 +31,8 @@ class ContractsDSLTests { } @RunWith(Parameterized::class) - class RequireSingleCommandTests(private val testFunction: (Collection>) -> CommandWithParties, description: String) { + class RequireSingleCommandTests(private val testFunction: (Collection>) -> CommandWithParties, + @Suppress("UNUSED_PARAMETER") description: String) { companion object { @JvmStatic @Parameterized.Parameters(name = "{1}") @@ -64,7 +65,8 @@ class ContractsDSLTests { } @RunWith(Parameterized::class) - class SelectWithSingleInputsTests(private val testFunction: (Collection>, PublicKey?, AbstractParty?) -> Iterable>, description: String) { + class SelectWithSingleInputsTests(private val testFunction: (Collection>, PublicKey?, AbstractParty?) -> Iterable>, + @Suppress("UNUSED_PARAMETER") description: String) { companion object { @JvmStatic @Parameterized.Parameters(name = "{1}") @@ -112,7 +114,8 @@ class ContractsDSLTests { } @RunWith(Parameterized::class) - class SelectWithMultipleInputsTests(private val testFunction: (Collection>, Collection?, Collection?) -> Iterable>, description: String) { + class SelectWithMultipleInputsTests(private val testFunction: (Collection>, Collection?, Collection?) -> Iterable>, + @Suppress("UNUSED_PARAMETER") description: String) { companion object { @JvmStatic @Parameterized.Parameters(name = "{1}") diff --git a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt index 3c7275a819..70648b07be 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt @@ -20,6 +20,7 @@ import net.corda.testing.dsl.LedgerDSL import net.corda.testing.dsl.TestLedgerDSLInterpreter import net.corda.testing.dsl.TestTransactionDSLInterpreter import net.corda.testing.internal.TEST_TX_TIME +import net.corda.testing.internal.createWireTransaction import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.ledger @@ -264,7 +265,7 @@ class PartialMerkleTreeTest { timeWindow: TimeWindow? = null, attachments: List = emptyList() ): WireTransaction { - return WireTransaction( + return createWireTransaction( inputs = testTx.inputs, attachments = attachments, outputs = testTx.outputs, diff --git a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt index 06f3907b21..6029897303 100644 --- a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt @@ -57,7 +57,7 @@ class AttachmentTests { bobNode.registerInitiatedFlow(FetchAttachmentsResponse::class.java) // Insert an attachment into node zero's store directly. val id = aliceNode.database.transaction { - aliceNode.attachments.importAttachment(fakeAttachment().inputStream()) + aliceNode.attachments.importAttachment(fakeAttachment().inputStream(), "test", null) } // Get node one to run a flow to fetch it and insert it. @@ -110,7 +110,7 @@ class AttachmentTests { val attachment = fakeAttachment() // Insert an attachment into node zero's store directly. val id = aliceNode.database.transaction { - aliceNode.attachments.importAttachment(attachment.inputStream()) + aliceNode.attachments.importAttachment(attachment.inputStream(), "test", null) } // Corrupt its store. diff --git a/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt b/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt index b652959156..8172bbc9be 100644 --- a/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt @@ -146,7 +146,7 @@ class ResolveTransactionsFlowTest { } // TODO: this operation should not require an explicit transaction val id = megaCorpNode.transaction { - megaCorpNode.services.attachments.importAttachment(makeJar()) + megaCorpNode.services.attachments.importAttachment(makeJar(), "test", null) } val stx2 = makeTransactions(withAttachment = id).second val p = TestFlow(stx2, megaCorp) @@ -201,6 +201,7 @@ class ResolveTransactionsFlowTest { } } + @Suppress("unused") @InitiatedBy(TestFlow::class) private class TestResponseFlow(val otherSideSession: FlowSession) : FlowLogic() { @Suspendable diff --git a/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt b/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt index 1c4f76cad9..6237a1a019 100644 --- a/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt @@ -21,10 +21,10 @@ import rx.Observable import java.util.* class TopologicalSortTest { - class DummyTransaction( + class DummyTransaction constructor( override val id: SecureHash, override val inputs: List, - val numberOfOutputs: Int, + @Suppress("CanBeParameter") private val numberOfOutputs: Int, override val notary: Party ) : CoreTransaction() { override val outputs: List> = (1..numberOfOutputs).map { @@ -78,7 +78,7 @@ class TopologicalSortTest { } // Swap two random items - transactions.combine(Generator.intRange(0, N - 1), Generator.intRange(0, N - 2)) { txs, i, j -> + transactions.combine(Generator.intRange(0, N - 1), Generator.intRange(0, N - 2)) { txs, i, _ -> val k = 0 // if (i == j) i + 1 else j val tmp = txs[i] txs[i] = txs[k] @@ -94,7 +94,7 @@ class TopologicalSortTest { } } - fun checkTopologicallyOrdered(txs: List) { + private fun checkTopologicallyOrdered(txs: List) { val outputs = HashSet() for (tx in txs) { if (!outputs.containsAll(tx.inputs)) { diff --git a/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt b/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt index cbda60638f..3f6f40bf51 100644 --- a/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt +++ b/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt @@ -8,6 +8,7 @@ import net.corda.core.crypto.CompositeKey import net.corda.core.identity.Party import net.corda.testing.contracts.DummyContract import net.corda.testing.core.* +import net.corda.testing.internal.createWireTransaction import net.corda.testing.internal.rigorousMock import org.junit.Rule import org.junit.Test @@ -53,7 +54,7 @@ class TransactionTests { val cpub = ck.public val c1 = CompositeKey.Builder().addKeys(apub, bpub).build(2) val compKey = CompositeKey.Builder().addKeys(c1, cpub).build(1) - val wtx = WireTransaction( + val wtx = createWireTransaction( inputs = listOf(StateRef(SecureHash.randomSHA256(), 0)), attachments = emptyList(), outputs = emptyList(), @@ -79,7 +80,7 @@ class TransactionTests { @Test fun `signed transaction missing signatures`() { - val wtx = WireTransaction( + val wtx = createWireTransaction( inputs = listOf(StateRef(SecureHash.randomSHA256(), 0)), attachments = emptyList(), outputs = emptyList(), @@ -119,8 +120,8 @@ class TransactionTests { }, DummyContract.PROGRAM_ID)) val id = SecureHash.randomSHA256() val timeWindow: TimeWindow? = null - val privacySalt: PrivacySalt = PrivacySalt() - val transaction: LedgerTransaction = LedgerTransaction( + val privacySalt = PrivacySalt() + val transaction = LedgerTransaction( inputs, outputs, commands, @@ -137,7 +138,7 @@ class TransactionTests { @Test fun `transaction cannot have duplicate inputs`() { val stateRef = StateRef(SecureHash.randomSHA256(), 0) - fun buildTransaction() = WireTransaction( + fun buildTransaction() = createWireTransaction( inputs = listOf(stateRef, stateRef), attachments = emptyList(), outputs = emptyList(), @@ -160,7 +161,7 @@ class TransactionTests { val attachments = emptyList() val id = SecureHash.randomSHA256() val timeWindow: TimeWindow? = null - val privacySalt: PrivacySalt = PrivacySalt() + val privacySalt = PrivacySalt() fun buildTransaction() = LedgerTransaction( inputs, outputs, @@ -178,7 +179,7 @@ class TransactionTests { @Test fun `transactions with identical contents must have different ids`() { val outputState = TransactionState(DummyContract.SingleOwnerState(0, ALICE), DummyContract.PROGRAM_ID, DUMMY_NOTARY) - fun buildTransaction() = WireTransaction( + fun buildTransaction() = createWireTransaction( inputs = emptyList(), attachments = emptyList(), outputs = listOf(outputState), diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt index 8cc5f3ab61..093b4bc8d0 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt @@ -40,6 +40,7 @@ enum class PrintOrVisualise { Visualise } +@Suppress("DEPRECATION") fun main(args: Array) { require(args.isNotEmpty()) { "Usage: [Print|Visualise]" } val printOrVisualise = PrintOrVisualise.valueOf(args[0]) @@ -99,6 +100,7 @@ fun main(args: Array) { } } // END 5 + Unit } } diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt index 40f7487946..c2b2046724 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt @@ -1,4 +1,4 @@ -@file:Suppress("UNUSED_VARIABLE", "unused") +@file:Suppress("UNUSED_VARIABLE", "unused", "DEPRECATION") package net.corda.docs diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt index e6826fa213..8e94e82b32 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt @@ -1,3 +1,5 @@ +@file:Suppress("DEPRECATION") + package net.corda.docs import co.paralleluniverse.fibers.Suspendable diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt index 0635c136f3..d4f67c02a0 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt @@ -1,3 +1,5 @@ +@file:Suppress("UNUSED_VARIABLE") + package net.corda.docs.tutorial.tearoffs import net.corda.core.contracts.Command @@ -42,4 +44,4 @@ fun main(args: Array) { } catch (e: FilteredTransactionVerificationException) { throw MerkleTreeException("Rate Fix Oracle: Couldn't verify partial Merkle tree.") } -} \ No newline at end of file +} diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt index 71f3dca79b..6af97417eb 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt @@ -2,22 +2,21 @@ package net.corda.behave.scenarios.helpers import net.corda.behave.scenarios.ScenarioState import net.corda.core.messaging.CordaRPCOps -import net.corda.core.utilities.contextLogger +import org.slf4j.Logger +import org.slf4j.LoggerFactory abstract class Substeps(protected val state: ScenarioState) { + protected val log: Logger = LoggerFactory.getLogger(javaClass) - protected val log = contextLogger() - - protected fun withNetwork(action: ScenarioState.() -> Unit) = - state.withNetwork(action) + protected fun withNetwork(action: ScenarioState.() -> Unit) = state.withNetwork(action) protected fun withClient(nodeName: String, action: ScenarioState.(CordaRPCOps) -> T): T { - return state.withClient(nodeName, { - return@withClient try { + return state.withClient(nodeName) { + try { action(state, it) } catch (ex: Exception) { - state.error(ex.message ?: "Failed to execute RPC call") + state.error(ex.message ?: "Failed to execute RPC call") } - }) + } } -} \ No newline at end of file +} diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt index 0d560b4b74..747c82cdae 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt @@ -5,7 +5,6 @@ import org.junit.Test import rx.observers.TestSubscriber class CommandTests { - @Test fun `successful command returns zero`() { val exitCode = Command(listOf("ls", "/")).run() @@ -21,7 +20,7 @@ class CommandTests { @Test fun `output stream for command can be observed`() { val subscriber = TestSubscriber() - val exitCode = Command(listOf("ls", "/")).use(subscriber) { _, output -> + val exitCode = Command(listOf("ls", "/")).use(subscriber) { _, _ -> subscriber.awaitTerminalEvent() subscriber.assertCompleted() subscriber.assertNoErrors() diff --git a/experimental/kryo-hook/build.gradle b/experimental/kryo-hook/build.gradle index 040b2e5f80..ab36a754b6 100644 --- a/experimental/kryo-hook/build.gradle +++ b/experimental/kryo-hook/build.gradle @@ -3,7 +3,6 @@ ext { } apply plugin: 'kotlin' -apply plugin: 'kotlin-kapt' apply plugin: 'idea' description 'A javaagent to allow hooking into Kryo' diff --git a/experimental/quasar-hook/build.gradle b/experimental/quasar-hook/build.gradle index c2387079a8..dfe49fa970 100644 --- a/experimental/quasar-hook/build.gradle +++ b/experimental/quasar-hook/build.gradle @@ -3,7 +3,6 @@ ext { } apply plugin: 'kotlin' -apply plugin: 'kotlin-kapt' apply plugin: 'idea' description 'A javaagent to allow hooking into the instrumentation by Quasar' diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt index 3632bfa6a7..9c043ffd48 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt @@ -2,12 +2,12 @@ package net.corda.finance.contracts.universal import net.corda.core.crypto.toStringShort import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import java.math.BigDecimal import java.security.PublicKey import java.time.Instant private class PrettyPrint(arr : Arrangement) { - val parties = involvedParties(arr) private val sb = StringBuilder() @@ -16,21 +16,21 @@ private class PrettyPrint(arr : Arrangement) { private var atStart = true private fun print(msg: String) { if (atStart) - repeat(indentLevel, { sb.append(' ') }) + repeat(indentLevel) { sb.append(' ') } sb.append(msg) atStart = false } private fun println(message: Any?) { if (atStart) - repeat(indentLevel, { sb.append(' ') }) + repeat(indentLevel) { sb.append(' ') } sb.appendln(message) atStart = true } private fun print(msg: Any?) { if (atStart) - repeat(indentLevel, { sb.append(' ') }) + repeat(indentLevel) { sb.append(' ') } sb.append(msg) atStart = false } @@ -45,8 +45,7 @@ private class PrettyPrint(arr : Arrangement) { val partyMap = mutableMapOf() val usedPartyNames = mutableSetOf() - fun createPartyName(party : Party) : String - { + fun createPartyName(party : Party): String { val parts = party.name.organisation.toLowerCase().split(' ') var camelName = parts.drop(1).fold(parts.first()) { @@ -69,38 +68,38 @@ private class PrettyPrint(arr : Arrangement) { } } - fun prettyPrint(per: Perceivable, x: Boolean? = null) { + fun prettyPrintBoolean(per: Perceivable) { when (per) { is Const -> print("\"${per.value}\"") is PerceivableOr -> { - prettyPrint(per.left) + prettyPrintBoolean(per.left) print(" or ") - prettyPrint(per.right) + prettyPrintBoolean(per.right) } is PerceivableAnd -> { - prettyPrint(per.left) + prettyPrintBoolean(per.left) print(" and ") - prettyPrint(per.right) + prettyPrintBoolean(per.right) } is TimePerceivable -> { when (per.cmp) { Comparison.GT, Comparison.GTE -> { print("after(") - prettyPrint(per.instant) + prettyPrintInstant(per.instant) print(")") } Comparison.LT, Comparison.LTE -> { print("before(") - prettyPrint(per.instant) + prettyPrintInstant(per.instant) print(")") } } } is PerceivableComparison<*> -> { when (per.type) { - BigDecimal::class.java -> prettyPrint(per.left as Perceivable) - Instant::class.java -> prettyPrint(per.left as Perceivable) - Boolean::class.java -> prettyPrint(per.left as Perceivable) + BigDecimal::class.java -> prettyPrintBigDecimal(uncheckedCast(per.left)) + Instant::class.java -> prettyPrintInstant(uncheckedCast(per.left)) + Boolean::class.java -> prettyPrintBoolean(uncheckedCast(per.left)) } when (per.cmp) { Comparison.GT -> print(" > ") @@ -109,9 +108,9 @@ private class PrettyPrint(arr : Arrangement) { Comparison.LTE -> print(" <= ") } when (per.type) { - BigDecimal::class.java -> prettyPrint(per.right as Perceivable) - Instant::class.java -> prettyPrint(per.right as Perceivable) - Boolean::class.java -> prettyPrint(per.right as Perceivable) + BigDecimal::class.java -> prettyPrintBigDecimal(uncheckedCast(per.right)) + Instant::class.java -> prettyPrintInstant(uncheckedCast(per.right)) + Boolean::class.java -> prettyPrintBoolean(uncheckedCast(per.right)) } } is TerminalEvent -> print("TerminalEvent(${partyMap[per.reference.owningKey]}, \"${per.source}\")") @@ -120,7 +119,7 @@ private class PrettyPrint(arr : Arrangement) { } } - fun prettyPrint(per: Perceivable, x: Instant? = null) { + fun prettyPrintInstant(per: Perceivable) { when (per) { is Const -> print("\"${per.value}\"") is StartDate -> print("startDate") @@ -129,34 +128,33 @@ private class PrettyPrint(arr : Arrangement) { } } - fun prettyPrint(per: Perceivable, x: BigDecimal? = null) { + fun prettyPrintBigDecimal(per: Perceivable) { when (per) { is PerceivableOperation -> { - prettyPrint(per.left) + prettyPrintBigDecimal(per.left) when (per.op) { Operation.PLUS -> print(" + ") Operation.MINUS -> print(" - ") Operation.DIV -> print(" / ") Operation.TIMES -> print(" * ") - else -> print(per.op) } - prettyPrint(per.right) + prettyPrintBigDecimal(per.right) } is UnaryPlus -> { print("(") - prettyPrint(per.arg) + prettyPrintBigDecimal(per.arg) print(".).plus()") } is Const -> print(per.value) is Interest -> { print("Interest(") - prettyPrint(per.amount) + prettyPrintBigDecimal(per.amount) print(", \"${per.dayCountConvention}\", ") - prettyPrint(per.amount) + prettyPrintBigDecimal(per.amount) print(", ") - prettyPrint(per.start) + prettyPrintInstant(per.start) print(", ") - prettyPrint(per.end) + prettyPrintInstant(per.end) print(")") } is CurrencyCross -> print("${per.foreign}/${per.domestic}") @@ -165,7 +163,6 @@ private class PrettyPrint(arr : Arrangement) { } fun prettyPrint(arr: Arrangement) { - when (arr) { is Zero -> println("zero") is RollOut -> { @@ -183,7 +180,7 @@ private class PrettyPrint(arr : Arrangement) { is Continuation -> println("next()") is Obligation -> { print("${partyMap[arr.from.owningKey]}.gives( ${partyMap[arr.to.owningKey]}, ") - prettyPrint(arr.amount) + prettyPrintBigDecimal(arr.amount) println(", ${arr.currency})") } is Actions -> { @@ -191,7 +188,7 @@ private class PrettyPrint(arr : Arrangement) { indent { for ((name, condition, arrangement) in arr.actions) { print("\"$name\".givenThat(") - prettyPrint(condition) + prettyPrintBoolean(condition) println(") {") indent { prettyPrint(arrangement) diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt index ef37f3114b..f73805b967 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt @@ -36,46 +36,45 @@ class UniversalContract : Contract { class Split(val ratio: BigDecimal) : Commands } - fun eval(@Suppress("UNUSED_PARAMETER") tx: LedgerTransaction, expr: Perceivable): Instant? = when (expr) { + fun evalInstant(expr: Perceivable): Instant? = when (expr) { is Const -> expr.value is StartDate -> null is EndDate -> null else -> throw Error("Unable to evaluate") } - fun eval(tx: LedgerTransaction, expr: Perceivable): Boolean = when (expr) { - is PerceivableAnd -> eval(tx, expr.left) && eval(tx, expr.right) - is PerceivableOr -> eval(tx, expr.left) || eval(tx, expr.right) + fun evalBoolean(tx: LedgerTransaction, expr: Perceivable): Boolean = when (expr) { + is PerceivableAnd -> evalBoolean(tx, expr.left) && evalBoolean(tx, expr.right) + is PerceivableOr -> evalBoolean(tx, expr.left) || evalBoolean(tx, expr.right) is Const -> expr.value is TimePerceivable -> when (expr.cmp) { - Comparison.LTE -> tx.timeWindow!!.fromTime!! <= eval(tx, expr.instant) - Comparison.GTE -> tx.timeWindow!!.untilTime!! >= eval(tx, expr.instant) + Comparison.LTE -> tx.timeWindow!!.fromTime!! <= evalInstant(expr.instant) + Comparison.GTE -> tx.timeWindow!!.untilTime!! >= evalInstant(expr.instant) else -> throw NotImplementedError("eval special") } is ActorPerceivable -> tx.commands.single().signers.contains(expr.actor.owningKey) else -> throw NotImplementedError("eval - Boolean - " + expr.javaClass.name) } - fun eval(tx: LedgerTransaction, expr: Perceivable): BigDecimal = + fun evalBigDecimal(tx: LedgerTransaction, expr: Perceivable): BigDecimal = when (expr) { is Const -> expr.value is UnaryPlus -> { - val x = eval(tx, expr.arg) + val x = evalBigDecimal(tx, expr.arg) if (x > BigDecimal.ZERO) x else BigDecimal.ZERO } is PerceivableOperation -> { - val l = eval(tx, expr.left) - val r = eval(tx, expr.right) + val l = evalBigDecimal(tx, expr.left) + val r = evalBigDecimal(tx, expr.right) when (expr.op) { Operation.DIV -> l / r Operation.MINUS -> l - r Operation.PLUS -> l + r Operation.TIMES -> l * r - else -> throw NotImplementedError("eval - amount - operation " + expr.op) } } is Fixing -> { @@ -83,8 +82,8 @@ class UniversalContract : Contract { 0.0.bd } is Interest -> { - val a = eval(tx, expr.amount) - val i = eval(tx, expr.interest) + val a = evalBigDecimal(tx, expr.amount) + val i = evalBigDecimal(tx, expr.interest) //TODO @@ -95,7 +94,7 @@ class UniversalContract : Contract { fun validateImmediateTransfers(tx: LedgerTransaction, arrangement: Arrangement): Arrangement = when (arrangement) { is Obligation -> { - val amount = eval(tx, arrangement.amount) + val amount = evalBigDecimal(tx, arrangement.amount) requireThat { "transferred quantity is non-negative" using (amount >= BigDecimal.ZERO) } Obligation(const(amount), arrangement.currency, arrangement.from, arrangement.to) } @@ -210,7 +209,7 @@ class UniversalContract : Contract { "action must have a time-window" using (tx.timeWindow != null) // "action must be authorized" by (cmd.signers.any { action.actors.any { party -> party.owningKey == it } }) // todo perhaps merge these two requirements? - "condition must be met" using (eval(tx, action.condition)) + "condition must be met" using evalBoolean(tx, action.condition) } // verify that any resulting transfers can be resolved @@ -287,7 +286,7 @@ class UniversalContract : Contract { perceivable.dayCountConvention, replaceFixing(tx, perceivable.interest, fixings, unusedFixings), perceivable.start, perceivable.end)) is Fixing -> { - val dt = eval(tx, perceivable.date) + val dt = evalInstant(perceivable.date) if (dt != null && fixings.containsKey(FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor))) { unusedFixings.remove(FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)) uncheckedCast(Const(fixings[FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)]!!)) diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt index 1205a64947..52a85cc5d2 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt @@ -14,13 +14,12 @@ class IRS { @Rule @JvmField val testSerialization = SerializationEnvironmentRule() - val TEST_TX_TIME_1: Instant get() = Instant.parse("2017-09-02T12:00:00.00Z") - val notional = 50.M - val currency = EUR - - val tradeDate: LocalDate = LocalDate.of(2016, 9, 1) + private val testTxTime1: Instant = Instant.parse("2017-09-02T12:00:00.00Z") + private val notional = 50.M + private val currency = EUR + private val tradeDate: LocalDate = LocalDate.of(2016, 9, 1) /* @@ -33,7 +32,7 @@ class IRS { */ - val contractInitial = arrange { + private val contractInitial = arrange { rollOut("2016-09-01".ld, "2018-09-01".ld, Frequency.Quarterly) { actions { (acmeCorp or highStreetBank) may { @@ -52,7 +51,8 @@ class IRS { } } } - val contractAfterFixingFirst = arrange { + + private val contractAfterFixingFirst = arrange { actions { (acmeCorp or highStreetBank) may { val floating = interest(notional, "act/365", 1.0.bd, "2016-09-01", "2016-12-01") @@ -83,15 +83,15 @@ class IRS { rollOut("2016-12-01".ld, "2018-09-01".ld, Frequency.Quarterly) { actions { (acmeCorp or highStreetBank) may { - val floating = interest(notional, "act/365", fix("LIBOR", start, Tenor("3M")), start, end) - val fixed = interest(notional, "act/365", 0.5.bd, start, end) + val nextFloating = interest(notional, "act/365", fix("LIBOR", start, Tenor("3M")), start, end) + val nextFixed = interest(notional, "act/365", 0.5.bd, start, end) "pay floating" anytime { - highStreetBank.owes(acmeCorp, floating - fixed, currency) + highStreetBank.owes(acmeCorp, nextFloating - nextFixed, currency) next() } "pay fixed" anytime { - highStreetBank.owes(acmeCorp, fixed - floating, currency) + highStreetBank.owes(acmeCorp, nextFixed - nextFloating, currency) next() } } @@ -102,7 +102,7 @@ class IRS { } } - val contractAfterExecutionFirst = arrange { + private val contractAfterExecutionFirst = arrange { rollOut("2016-12-01".ld, "2018-09-01".ld, Frequency.Quarterly) { actions { (acmeCorp or highStreetBank) may { @@ -122,19 +122,20 @@ class IRS { } } - val paymentFirst = arrange { highStreetBank.owes(acmeCorp, 250.K, EUR) } + private val paymentFirst = arrange { highStreetBank.owes(acmeCorp, 250.K, EUR) } - val stateInitial = UniversalContract.State(listOf(DUMMY_NOTARY), contractInitial) + private val stateInitial = UniversalContract.State(listOf(DUMMY_NOTARY), contractInitial) - val stateAfterFixingFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterFixingFirst) - val stateAfterExecutionFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterExecutionFirst) + private val stateAfterFixingFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterFixingFirst) + private val stateAfterExecutionFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterExecutionFirst) + + private val statePaymentFirst = UniversalContract.State(listOf(DUMMY_NOTARY), paymentFirst) - val statePaymentFirst = UniversalContract.State(listOf(DUMMY_NOTARY), paymentFirst) @Test fun issue() { transaction { output(UNIVERSAL_PROGRAM_ID, stateInitial) - timeWindow(TEST_TX_TIME_1) + timeWindow(testTxTime1) tweak { command(acmeCorp.owningKey, UniversalContract.Commands.Issue()) @@ -150,7 +151,7 @@ class IRS { transaction { input(UNIVERSAL_PROGRAM_ID, stateInitial) output(UNIVERSAL_PROGRAM_ID, stateAfterFixingFirst) - timeWindow(TEST_TX_TIME_1) + timeWindow(testTxTime1) tweak { command(highStreetBank.owningKey, UniversalContract.Commands.Action("some undefined name")) @@ -190,7 +191,7 @@ class IRS { input(UNIVERSAL_PROGRAM_ID, stateAfterFixingFirst) output(UNIVERSAL_PROGRAM_ID, stateAfterExecutionFirst) output(UNIVERSAL_PROGRAM_ID, statePaymentFirst) - timeWindow(TEST_TX_TIME_1) + timeWindow(testTxTime1) tweak { command(highStreetBank.owningKey, UniversalContract.Commands.Action("some undefined name")) diff --git a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt index 3750d76ef2..7f0972a175 100644 --- a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt @@ -47,6 +47,7 @@ class AuthDBTests : NodeBasedTest() { fun encFormats() = arrayOf(PasswordEncryption.NONE, PasswordEncryption.SHIRO_1_CRYPT) } + @Suppress("MemberVisibilityCanBePrivate") @Parameterized.Parameter lateinit var passwordEncryption: PasswordEncryption @@ -94,7 +95,7 @@ class AuthDBTests : NodeBasedTest() { ) node = startNode(ALICE_NAME, rpcUsers = emptyList(), configOverrides = securityConfig) - client = CordaRPCClient(node.internals.configuration.rpcOptions.address!!) + client = CordaRPCClient(node.internals.configuration.rpcOptions.address) } @Test @@ -227,9 +228,8 @@ private data class RoleAndPermissions(val role: String, val permissions: List = emptyList(), roleAndPermissions: List = emptyList()) : AutoCloseable { + val jdbcUrl = "jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1" companion object { const val DB_CREATE_SCHEMA = """ @@ -279,11 +279,7 @@ private class UsersDB : AutoCloseable { } } - constructor(name: String, - users: List = emptyList(), - roleAndPermissions: List = emptyList()) { - - jdbcUrl = "jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1" + init { dataSource = DataSourceFactory.createDataSource(Properties().apply { put("dataSourceClassName", "org.h2.jdbcx.JdbcDataSource") put("dataSource.url", jdbcUrl) @@ -291,11 +287,9 @@ private class UsersDB : AutoCloseable { session { it.execute(DB_CREATE_SCHEMA) } - require(users.map { it.username }.toSet().size == users.size) { "Duplicate username in input" } - users.forEach { insert(it) } roleAndPermissions.forEach { insert(it) } } diff --git a/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt b/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt index 1e751a1658..6f0246660d 100644 --- a/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt @@ -20,7 +20,6 @@ import net.corda.testing.core.singleIdentity import net.corda.testing.driver.PortAllocation import net.corda.testing.internal.DEV_ROOT_CA import net.corda.testing.node.NotarySpec -import net.corda.testing.node.internal.CompatibilityZoneParams import net.corda.testing.node.internal.SharedCompatibilityZoneParams import net.corda.testing.node.internal.internalDriver import net.corda.testing.node.internal.network.NetworkMapServer @@ -51,7 +50,6 @@ class NodeRegistrationTest { private val notaryName = CordaX500Name("NotaryService", "Zurich", "CH") private val aliceName = CordaX500Name("Alice", "London", "GB") private val genevieveName = CordaX500Name("Genevieve", "London", "GB") - private val log = contextLogger() } @Rule @@ -69,7 +67,7 @@ class NodeRegistrationTest { pollInterval = 1.seconds, hostAndPort = portAllocation.nextHostAndPort(), myHostNameValue = "localhost", - additionalServices = registrationHandler) + additionalServices = *arrayOf(registrationHandler)) serverHostAndPort = server.start() } diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt index 8bc80d99b7..6325ff723e 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt @@ -68,7 +68,7 @@ class MQSecurityAsNodeTest : P2PMQSecurityTest() { @Test fun `login to a non ssl port as a node user`() { - val attacker = clientTo(alice.internals.configuration.rpcOptions.address!!, sslConfiguration = null) + val attacker = clientTo(alice.internals.configuration.rpcOptions.address, sslConfiguration = null) assertThatExceptionOfType(ActiveMQSecurityException::class.java).isThrownBy { attacker.start(NODE_P2P_USER, NODE_P2P_USER, enableSSL = false) } @@ -76,7 +76,7 @@ class MQSecurityAsNodeTest : P2PMQSecurityTest() { @Test fun `login to a non ssl port as a peer user`() { - val attacker = clientTo(alice.internals.configuration.rpcOptions.address!!, sslConfiguration = null) + val attacker = clientTo(alice.internals.configuration.rpcOptions.address, sslConfiguration = null) assertThatExceptionOfType(ActiveMQSecurityException::class.java).isThrownBy { attacker.start(PEER_USER, PEER_USER, enableSSL = false) // Login as a peer } diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt index e06d21eee6..9eee5fd05d 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt @@ -8,7 +8,7 @@ import org.junit.Test */ class MQSecurityAsRPCTest : RPCMQSecurityTest() { override fun createAttacker(): SimpleMQClient { - return clientTo(alice.internals.configuration.rpcOptions.address!!) + return clientTo(alice.internals.configuration.rpcOptions.address) } @Test diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt index 44da2d4e7e..179fe0b7f0 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt @@ -29,6 +29,7 @@ import net.corda.testing.node.internal.NodeBasedTest import net.corda.testing.node.internal.startFlow import org.apache.activemq.artemis.api.core.ActiveMQNonExistentQueueException import org.apache.activemq.artemis.api.core.ActiveMQSecurityException +import org.apache.activemq.artemis.api.core.RoutingType import org.apache.activemq.artemis.api.core.SimpleString import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.After @@ -111,9 +112,9 @@ abstract class MQSecurityTest : NodeBasedTest() { } fun loginToRPCAndGetClientQueue(): String { - loginToRPC(alice.internals.configuration.rpcOptions.address!!, rpcUser) + loginToRPC(alice.internals.configuration.rpcOptions.address, rpcUser) val clientQueueQuery = SimpleString("${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.${rpcUser.username}.*") - val client = clientTo(alice.internals.configuration.rpcOptions.address!!) + val client = clientTo(alice.internals.configuration.rpcOptions.address) client.start(rpcUser.username, rpcUser.password, false) return client.session.addressQuery(clientQueueQuery).queueNames.single().toString() } @@ -126,7 +127,7 @@ abstract class MQSecurityTest : NodeBasedTest() { fun assertTempQueueCreationAttackFails(queue: String) { assertAttackFails(queue, "CREATE_NON_DURABLE_QUEUE") { - attacker.session.createTemporaryQueue(queue, queue) + attacker.session.createTemporaryQueue(queue, RoutingType.MULTICAST, queue) } // Double-check assertThatExceptionOfType(ActiveMQNonExistentQueueException::class.java).isThrownBy { @@ -143,7 +144,7 @@ abstract class MQSecurityTest : NodeBasedTest() { fun assertNonTempQueueCreationAttackFails(queue: String, durable: Boolean) { val permission = if (durable) "CREATE_DURABLE_QUEUE" else "CREATE_NON_DURABLE_QUEUE" assertAttackFails(queue, permission) { - attacker.session.createQueue(queue, queue, durable) + attacker.session.createQueue(queue, RoutingType.MULTICAST, queue, durable) } // Double-check assertThatExceptionOfType(ActiveMQNonExistentQueueException::class.java).isThrownBy { diff --git a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt index 46e889e06f..b4de9fbea4 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt @@ -4,11 +4,10 @@ import com.typesafe.config.Config import com.typesafe.config.ConfigException import net.corda.core.context.AuthServiceId import net.corda.core.identity.CordaX500Name -import net.corda.core.internal.div +import net.corda.core.internal.TimedFlow import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.core.utilities.seconds -import net.corda.node.internal.artemis.CertificateChainCheckPolicy import net.corda.node.services.config.rpc.NodeRpcOptions import net.corda.nodeapi.BrokerRpcSslOptions import net.corda.nodeapi.internal.config.NodeSSLConfiguration @@ -40,6 +39,7 @@ interface NodeConfiguration : NodeSSLConfiguration { val devModeOptions: DevModeOptions? val compatibilityZoneURL: URL? val networkServices: NetworkServicesConfig? + @Suppress("DEPRECATION") val certificateChainCheckPolicies: List val verifierType: VerifierType val flowTimeout: FlowTimeoutConfiguration @@ -179,6 +179,7 @@ data class NodeConfigurationImpl( override val messagingServerAddress: NetworkHostAndPort?, override val messagingServerExternal: Boolean = (messagingServerAddress != null), override val notary: NotaryConfig?, + @Suppress("DEPRECATION") @Deprecated("Do not configure") override val certificateChainCheckPolicies: List = emptyList(), override val devMode: Boolean = false, @@ -329,6 +330,7 @@ data class NodeConfigurationImpl( require(security == null || rpcUsers.isEmpty()) { "Cannot specify both 'rpcUsers' and 'security' in configuration" } + @Suppress("DEPRECATION") if(certificateChainCheckPolicies.isNotEmpty()) { logger.warn("""You are configuring certificateChainCheckPolicies. This is a setting that is not used, and will be removed in a future version. |Please contact the R3 team on the public slack to discuss your use case. @@ -383,18 +385,7 @@ enum class CertChainPolicyType { } @Deprecated("Do not use") -data class CertChainPolicyConfig(val role: String, private val policy: CertChainPolicyType, private val trustedAliases: Set) { - val certificateChainCheckPolicy: CertificateChainCheckPolicy - get() { - return when (policy) { - CertChainPolicyType.Any -> CertificateChainCheckPolicy.Any - CertChainPolicyType.RootMustMatch -> CertificateChainCheckPolicy.RootMustMatch - CertChainPolicyType.LeafMustMatch -> CertificateChainCheckPolicy.LeafMustMatch - CertChainPolicyType.MustContainOneOf -> CertificateChainCheckPolicy.MustContainOneOf(trustedAliases) - CertChainPolicyType.UsernameMustMatch -> CertificateChainCheckPolicy.UsernameMustMatchCommonName - } - } -} +data class CertChainPolicyConfig(val role: String, private val policy: CertChainPolicyType, private val trustedAliases: Set) // Supported types of authentication/authorization data providers enum class AuthDataSourceType { @@ -431,8 +422,6 @@ data class SecurityConfiguration(val authService: SecurityConfiguration.AuthServ } } - fun copyWithAdditionalUser(user: User) = AuthService(dataSource.copyWithAdditionalUser(user), id, options) - // Optional components: cache data class Options(val cache: Options.Cache?) { @@ -460,12 +449,6 @@ data class SecurityConfiguration(val authService: SecurityConfiguration.AuthServ AuthDataSourceType.DB -> require(users == null && connection != null) } } - - fun copyWithAdditionalUser(user: User): DataSource { - val extendedList = this.users?.toMutableList() ?: mutableListOf() - extendedList.add(user) - return DataSource(this.type, this.passwordEncryption, this.connection, listOf(*extendedList.toTypedArray())) - } } companion object { @@ -485,4 +468,4 @@ data class SecurityConfiguration(val authService: SecurityConfiguration.AuthServ id = AuthServiceId("NODE_CONFIG")) } } -} \ No newline at end of file +} diff --git a/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt b/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt index e7ab13fa4c..adcc86892a 100644 --- a/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt +++ b/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt @@ -24,7 +24,7 @@ import javax.annotation.concurrent.ThreadSafe */ // TODO There is duplicated logic between this and PersistentIdentityService @ThreadSafe -class InMemoryIdentityService(identities: List = emptyList(), +class InMemoryIdentityService(identities: List = emptyList(), override val trustRoot: X509Certificate) : SingletonSerializeAsToken(), IdentityService { companion object { private val log = contextLogger() diff --git a/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt b/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt index 0c0eb61778..d900d2c73b 100644 --- a/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt +++ b/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt @@ -53,7 +53,7 @@ class E2ETestKeyManagementService(val identityService: IdentityService, } override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate { - return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey), revocationEnabled) + return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey)) } private fun getSigner(publicKey: PublicKey): ContentSigner = getSigner(getSigningKeyPair(publicKey)) diff --git a/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt b/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt index 5bf1a3d043..851d0872a2 100644 --- a/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt +++ b/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt @@ -30,8 +30,7 @@ import java.time.Duration fun freshCertificate(identityService: IdentityService, subjectPublicKey: PublicKey, issuer: PartyAndCertificate, - issuerSigner: ContentSigner, - revocationEnabled: Boolean = false): PartyAndCertificate { + issuerSigner: ContentSigner): PartyAndCertificate { val issuerRole = CertRole.extract(issuer.certificate) require(issuerRole == CertRole.LEGAL_IDENTITY) { "Confidential identities can only be issued from well known identities, provided issuer ${issuer.name} has role $issuerRole" } val issuerCert = issuer.certificate diff --git a/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt b/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt index e2d7509bb9..c6d0aaaa86 100644 --- a/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt +++ b/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt @@ -87,8 +87,9 @@ class PersistentKeyManagementService(val identityService: IdentityService, return keyPair.public } - override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate = - freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey), revocationEnabled) + override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate { + return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey)) + } private fun getSigner(publicKey: PublicKey): ContentSigner = getSigner(getSigningKeyPair(publicKey)) diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt index 51ad2460c4..40d1c92b99 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt @@ -56,10 +56,10 @@ import kotlin.streams.toList @ThreadSafe class SingleThreadedStateMachineManager( val serviceHub: ServiceHubInternal, - val checkpointStorage: CheckpointStorage, + private val checkpointStorage: CheckpointStorage, val executor: ExecutorService, val database: CordaPersistence, - val secureRandom: SecureRandom, + private val secureRandom: SecureRandom, private val unfinishedFibers: ReusableLatch = ReusableLatch(), private val classloader: ClassLoader = SingleThreadedStateMachineManager::class.java.classLoader ) : StateMachineManager, StateMachineManagerInternal { @@ -135,7 +135,7 @@ class SingleThreadedStateMachineManager( } serviceHub.networkMapCache.nodeReady.then { resumeRestoredFlows(fibers) - flowMessaging.start { receivedMessage, deduplicationHandler -> + flowMessaging.start { _, deduplicationHandler -> executor.execute { deliverExternalEvent(deduplicationHandler.externalCause) } @@ -286,10 +286,10 @@ class SingleThreadedStateMachineManager( } private fun checkQuasarJavaAgentPresence() { - check(SuspendableHelper.isJavaAgentActive(), { + check(SuspendableHelper.isJavaAgentActive()) { """Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM. #See https://docs.corda.net/troubleshooting.html - 'Fiber classes not instrumented' for more details.""".trimMargin("#") - }) + } } private fun decrementLiveFibers() { @@ -304,8 +304,7 @@ class SingleThreadedStateMachineManager( return checkpointStorage.getAllCheckpoints().map { (id, serializedCheckpoint) -> // If a flow is added before start() then don't attempt to restore it mutex.locked { if (flows.containsKey(id)) return@map null } - val checkpoint = deserializeCheckpoint(serializedCheckpoint) - if (checkpoint == null) return@map null + val checkpoint = deserializeCheckpoint(serializedCheckpoint) ?: return@map null logger.debug { "Restored $checkpoint" } createFlowFromCheckpoint( id = id, @@ -524,12 +523,6 @@ class SingleThreadedStateMachineManager( isStartIdempotent: Boolean ): CordaFuture> { val flowId = StateMachineRunId.createRandom() - val deduplicationSeed = when (flowStart) { - FlowStart.Explicit -> flowId.uuid.toString() - is FlowStart.Initiated -> - "${flowStart.initiatingMessage.initiatorSessionId.toLong}-" + - "${flowStart.initiatingMessage.initiationEntropy}" - } // Before we construct the state machine state by freezing the FlowLogic we need to make sure that lazy properties // have access to the fiber (and thereby the service hub) @@ -541,7 +534,7 @@ class SingleThreadedStateMachineManager( val flowCorDappVersion = createSubFlowVersion(serviceHub.cordappProvider.getCordappForFlow(flowLogic), serviceHub.myInfo.platformVersion) - val initialCheckpoint = Checkpoint.create(invocationContext, flowStart, flowLogic.javaClass, frozenFlowLogic, ourIdentity, deduplicationSeed, flowCorDappVersion).getOrThrow() + val initialCheckpoint = Checkpoint.create(invocationContext, flowStart, flowLogic.javaClass, frozenFlowLogic, ourIdentity, flowCorDappVersion).getOrThrow() val startedFuture = openFuture() val initialState = StateMachineState( checkpoint = initialCheckpoint, diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt index 2779cee916..75493c1cfb 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt @@ -2,6 +2,7 @@ package net.corda.node.services.statemachine import net.corda.core.flows.StateMachineRunId import net.corda.core.internal.ThreadBox +import net.corda.core.internal.TimedFlow import net.corda.core.internal.bufferUntilSubscribed import net.corda.core.messaging.DataFeed import net.corda.core.utilities.contextLogger @@ -100,12 +101,6 @@ class StaffedFlowHospital { private data class ConsultationReport(val error: Throwable, val diagnosis: Diagnosis, val by: List) - /** - * The flow running in [flowFiber] has cleaned, possibly as a result of a flow hospital resume. - */ - // It's okay for flows to be cleaned... we fix them now! - fun flowCleaned(flowFiber: FlowFiber) = Unit - /** * The flow has been removed from the state machine. */ diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt index e4de7f953a..5684910f44 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt @@ -69,7 +69,6 @@ data class Checkpoint( flowLogicClass: Class>, frozenFlowLogic: SerializedBytes>, ourIdentity: Party, - deduplicationSeed: String, subFlowVersion: SubFlowVersion ): Try { return SubFlow.create(flowLogicClass, subFlowVersion).map { topLevelSubFlow -> diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt index db6cbed48b..93f78f3692 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt @@ -45,9 +45,7 @@ class HospitalisingInterceptor( when (nextState.checkpoint.errorState) { is ErrorState.Clean -> { - if (hospitalisedFlows.remove(fiber.id) != null) { - flowHospital.flowCleaned(fiber) - } + hospitalisedFlows.remove(fiber.id) } is ErrorState.Errored -> { val exceptionsToHandle = nextState.checkpoint.errorState.errors.map { it.exception } diff --git a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt index 945cc2135a..19db9ef18d 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt @@ -76,7 +76,7 @@ abstract class AppendOnlyPersistentMapBase( Transactional.Committed(value) } else { // Some database transactions, including us, writing, with readers seeing whatever is in the database and writers seeing the (in memory) value. - Transactional.InFlight(this, key, { loadValue(key) }).apply { alsoWrite(value) } + Transactional.InFlight(this, key, _readerValueLoader = { loadValue(key) }).apply { alsoWrite(value) } } } @@ -146,13 +146,13 @@ abstract class AppendOnlyPersistentMapBase( } // Helpers to know if transaction(s) are currently writing the given key. - protected fun weAreWriting(key: K): Boolean = pendingKeys.get(key)?.contains(contextTransaction) ?: false - protected fun anyoneWriting(key: K): Boolean = pendingKeys.get(key)?.isNotEmpty() ?: false + protected fun weAreWriting(key: K): Boolean = pendingKeys[key]?.contains(contextTransaction) ?: false + protected fun anyoneWriting(key: K): Boolean = pendingKeys[key]?.isNotEmpty() ?: false // Indicate this database transaction is a writer of this key. private fun addPendingKey(key: K, databaseTransaction: DatabaseTransaction): Boolean { var added = true - pendingKeys.compute(key) { k, oldSet -> + pendingKeys.compute(key) { _, oldSet -> if (oldSet == null) { val newSet = HashSet(0) newSet += databaseTransaction @@ -167,7 +167,7 @@ abstract class AppendOnlyPersistentMapBase( // Remove this database transaction as a writer of this key, because the transaction committed or rolled back. private fun removePendingKey(key: K, databaseTransaction: DatabaseTransaction) { - pendingKeys.compute(key) { k, oldSet -> + pendingKeys.compute(key) { _, oldSet -> if (oldSet == null) { oldSet } else { @@ -199,7 +199,7 @@ abstract class AppendOnlyPersistentMapBase( } // No one can see it. - class Missing() : Transactional() { + class Missing : Transactional() { override val value: T get() = throw NoSuchElementException("Not present") override val isPresent: Boolean @@ -228,7 +228,7 @@ abstract class AppendOnlyPersistentMapBase( fun alsoWrite(_value: T) { // Make the lazy loader the writers see actually just return the value that has been set. - writerValueLoader.set({ _value }) + writerValueLoader.set { _value } // We make all these vals so that the lambdas do not need a reference to this, and so the onCommit only has a weak ref to the value. // We want this so that the cache could evict the value (due to memory constraints etc) without the onCommit callback // retaining what could be a large memory footprint object. @@ -242,10 +242,9 @@ abstract class AppendOnlyPersistentMapBase( // and then stop saying the transaction is writing the key. tx.onCommit { if (strongComitted.compareAndSet(false, true)) { - val dereferencedKey = strongKey val dereferencedValue = weakValue.get() if (dereferencedValue != null) { - strongMap.cache.put(dereferencedKey, Committed(dereferencedValue)) + strongMap.cache.put(strongKey, Committed(dereferencedValue)) } } strongMap.removePendingKey(strongKey, tx) @@ -262,7 +261,7 @@ abstract class AppendOnlyPersistentMapBase( private fun loadAsWriter(): T { val _value = writerValueLoader.get()() if (writerValueLoader.get() == _writerValueLoader) { - writerValueLoader.set({ _value }) + writerValueLoader.set { _value } } return _value } @@ -272,7 +271,7 @@ abstract class AppendOnlyPersistentMapBase( private fun loadAsReader(): T? { val _value = readerValueLoader.get()() if (readerValueLoader.get() == _readerValueLoader) { - readerValueLoader.set({ _value }) + readerValueLoader.set { _value } } return _value } @@ -310,7 +309,7 @@ open class AppendOnlyPersistentMap( toPersistentEntity, persistentEntityClass) { //TODO determine cacheBound based on entity class later or with node config allowing tuning, or using some heuristic based on heap size - override val cache = NonInvalidatingCache>( + override val cache = NonInvalidatingCache( bound = cacheBound, loadFunction = { key: K -> // This gets called if a value is read and the cache has no Transactional for this key yet. @@ -321,10 +320,10 @@ open class AppendOnlyPersistentMap( // If someone is writing (but not us) // For those not writing, the value cannot be seen. // For those writing, they need to re-load the value from the database (which their database transaction CAN see). - Transactional.InFlight(this, key, { null }, { loadValue(key)!! }) + Transactional.InFlight(this, key, { null }, { loadValue(key)!! }) } else { // If no one is writing, then the value does not exist. - Transactional.Missing() + Transactional.Missing() } } else { // A value was found @@ -332,10 +331,10 @@ open class AppendOnlyPersistentMap( // If we are writing, it might not be globally visible, and was evicted from the cache. // For those not writing, they need to check the database again. // For those writing, they can see the value found. - Transactional.InFlight(this, key, { loadValue(key) }, { value }) + Transactional.InFlight(this, key, { loadValue(key) }, { value }) } else { // If no one is writing, then make it globally visible. - Transactional.Committed(value) + Transactional.Committed(value) } } }) @@ -354,26 +353,22 @@ class WeightBasedAppendOnlyPersistentMap( fromPersistentEntity, toPersistentEntity, persistentEntityClass) { - override val cache = NonInvalidatingWeightBasedCache>( + override val cache = NonInvalidatingWeightBasedCache( maxWeight = maxWeight, - weigher = object : Weigher> { - override fun weigh(key: K, value: Transactional): Int { - return weighingFunc(key, value) - } - }, + weigher = Weigher { key, value -> weighingFunc(key, value) }, loadFunction = { key: K -> val value: V? = loadValue(key) if (value == null) { if (anyoneWriting(key)) { - Transactional.InFlight(this, key, { null }, { loadValue(key)!! }) + Transactional.InFlight(this, key, { null }, { loadValue(key)!! }) } else { - Transactional.Missing() + Transactional.Missing() } } else { if (weAreWriting(key)) { - Transactional.InFlight(this, key, { loadValue(key) }, { value }) + Transactional.InFlight(this, key, { loadValue(key) }, { value }) } else { - Transactional.Committed(value) + Transactional.Committed(value) } } }) diff --git a/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java b/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java index 3c9b727313..359a162c39 100644 --- a/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java +++ b/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java @@ -35,9 +35,6 @@ import org.junit.Rule; import org.junit.Test; import rx.Observable; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CertificateException; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -69,7 +66,7 @@ public class VaultQueryJavaTests { private CordaPersistence database; @Before - public void setUp() throws CertificateException, InvalidAlgorithmParameterException { + public void setUp() { List cordappPackages = asList("net.corda.testing.internal.vault", "net.corda.finance.contracts.asset", CashSchemaV1.class.getPackage().getName()); IdentityService identitySvc = makeTestIdentityService(MEGA_CORP.getIdentity(), DUMMY_CASH_ISSUER_INFO.getIdentity(), DUMMY_NOTARY.getIdentity()); Pair databaseAndServices = makeTestDatabaseAndMockServices( @@ -85,14 +82,10 @@ public class VaultQueryJavaTests { } @After - public void cleanUp() throws IOException { + public void cleanUp() { database.close(); } - /** - * Sample Vault Query API tests - */ - /** * Static queryBy() tests */ @@ -103,6 +96,7 @@ public class VaultQueryJavaTests { FieldInfo currency = getField("currency", SampleCashSchemaV2.PersistentCashState.class); CriteriaExpression.AggregateFunctionExpression expression = sum(quantity, singletonList(currency), Sort.Direction.ASC); + @SuppressWarnings("unchecked") VaultCustomQueryCriteria criteria = new VaultCustomQueryCriteria(expression, Vault.StateStatus.UNCONSUMED, null); database.transaction(tx -> vaultService.queryBy(FungibleAsset.class, criteria)); @@ -115,13 +109,14 @@ public class VaultQueryJavaTests { FieldInfo stateRef = getField("stateRef", SampleCashSchemaV2.PersistentCashState.class); CriteriaExpression.AggregateFunctionExpression expression = sum(quantity, asList(currency, stateRef), Sort.Direction.ASC); + @SuppressWarnings("unchecked") VaultCustomQueryCriteria criteria = new VaultCustomQueryCriteria(expression, Vault.StateStatus.UNCONSUMED, null); database.transaction(tx -> vaultService.queryBy(FungibleAsset.class, criteria)); } @Test - public void unconsumedLinearStates() throws VaultQueryException { + public void unconsumedLinearStates() { database.transaction(tx -> { vaultFiller.fillWithSomeTestLinearStates(3); return tx; @@ -193,7 +188,7 @@ public class VaultQueryJavaTests { } @Test - public void consumedDealStatesPagedSorted() throws VaultQueryException { + public void consumedDealStatesPagedSorted() { List dealIds = asList("123", "456", "789"); @SuppressWarnings("unchecked") Triple, UniqueIdentifier, Vault> ids = @@ -304,7 +299,6 @@ public class VaultQueryJavaTests { DataFeed, Vault.Update> results = vaultService.trackBy(ContractState.class, criteria); Vault.Page snapshot = results.getSnapshot(); - Observable> updates = results.getUpdates(); // DOCEND VaultJavaQueryExample4 assertThat(snapshot.getStates()).hasSize(3); @@ -358,7 +352,6 @@ public class VaultQueryJavaTests { @SuppressWarnings("unchecked") public void aggregateFunctionsWithoutGroupClause() { database.transaction(tx -> { - Amount dollars100 = new Amount<>(100, Currency.getInstance("USD")); Amount dollars200 = new Amount<>(200, Currency.getInstance("USD")); Amount dollars300 = new Amount<>(300, Currency.getInstance("USD")); @@ -404,7 +397,6 @@ public class VaultQueryJavaTests { @SuppressWarnings("unchecked") public void aggregateFunctionsWithSingleGroupClause() { database.transaction(tx -> { - Amount dollars100 = new Amount<>(100, Currency.getInstance("USD")); Amount dollars200 = new Amount<>(200, Currency.getInstance("USD")); Amount dollars300 = new Amount<>(300, Currency.getInstance("USD")); diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index 1297bd97e6..fe97431308 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -24,7 +24,6 @@ import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap import net.corda.finance.DOLLARS import net.corda.finance.GBP -import net.corda.finance.USD import net.corda.finance.contracts.asset.Cash import net.corda.finance.flows.CashIssueFlow import net.corda.finance.flows.CashPaymentFlow @@ -157,6 +156,7 @@ class CordaRPCOpsImplTest { @Test fun `issue and move`() { + @Suppress("DEPRECATION") withPermissions(invokeRpc(CordaRPCOps::stateMachinesFeed), invokeRpc(CordaRPCOps::internalVerifiedTransactionsFeed), invokeRpc("vaultTrackBy"), @@ -168,11 +168,7 @@ class CordaRPCOpsImplTest { vaultTrackCash = rpc.vaultTrackBy().updates } - val result = rpc.startFlow(::CashIssueFlow, - 100.DOLLARS, - OpaqueBytes(ByteArray(1, { 1 })), - notary - ) + val result = rpc.startFlow(::CashIssueFlow, 100.DOLLARS, OpaqueBytes.of(1), notary) mockNet.runNetwork() @@ -247,7 +243,7 @@ class CordaRPCOpsImplTest { fun `cash command by user not permissioned for cash`() { withoutAnyPermissions { assertThatExceptionOfType(PermissionException::class.java).isThrownBy { - rpc.startFlow(::CashIssueFlow, Amount(100, USD), OpaqueBytes(ByteArray(1, { 1 })), notary) + rpc.startFlow(::CashIssueFlow, 100.DOLLARS, OpaqueBytes.of(1), notary) } } } diff --git a/node/src/test/kotlin/net/corda/node/internal/NodeTest.kt b/node/src/test/kotlin/net/corda/node/internal/NodeTest.kt index 76e2d0b7e4..777990b656 100644 --- a/node/src/test/kotlin/net/corda/node/internal/NodeTest.kt +++ b/node/src/test/kotlin/net/corda/node/internal/NodeTest.kt @@ -60,7 +60,7 @@ class NodeTest { fun `generateAndSaveNodeInfo works`() { val configuration = createConfig(ALICE_NAME) val platformVersion = 789 - configureDatabase(configuration.dataSourceProperties, configuration.database, { null }, { null }).use { database -> + configureDatabase(configuration.dataSourceProperties, configuration.database, { null }, { null }).use { val node = Node(configuration, rigorousMock().also { doReturn(platformVersion).whenever(it).platformVersion }, initialiseSerialization = false) diff --git a/node/src/test/kotlin/net/corda/node/internal/serialization/RoundTripObservableSerializerTests.kt b/node/src/test/kotlin/net/corda/node/internal/serialization/RoundTripObservableSerializerTests.kt index 2a16e8febf..0620f0f115 100644 --- a/node/src/test/kotlin/net/corda/node/internal/serialization/RoundTripObservableSerializerTests.kt +++ b/node/src/test/kotlin/net/corda/node/internal/serialization/RoundTripObservableSerializerTests.kt @@ -19,7 +19,6 @@ import org.apache.activemq.artemis.api.core.SimpleString import org.junit.Test import rx.Notification import rx.Observable -import rx.Subscription import rx.subjects.UnicastSubject import java.time.Instant import java.util.* @@ -38,7 +37,7 @@ class RoundTripObservableSerializerTests { .maximumSize(100) .build() - subMap.put(id, ObservableSubscription(mock())) + subMap.put(id, ObservableSubscription(mock())) return subMap } @@ -48,7 +47,7 @@ class RoundTripObservableSerializerTests { }) private fun createRpcObservableMap(): Cache>> { - val onObservableRemove = RemovalListener>> { key, value, cause -> + val onObservableRemove = RemovalListener>> { key, _, _ -> val observableId = key!! observablesToReap.locked { observables.add(observableId) } @@ -85,7 +84,7 @@ class RoundTripObservableSerializerTests { // What we're actually going to serialize then deserialize - val obs = Observable.create({ 12 }) + val obs = Observable.create { Math.random() } val serverSerializationContext = RpcServerObservableSerializer.createContext( serializationContext, serverObservableContext) @@ -95,6 +94,6 @@ class RoundTripObservableSerializerTests { val blob = SerializationOutput(serverSerializer).serialize(obs, serverSerializationContext) - val obs2 = DeserializationInput(clientSerializer).deserialize(blob, clientSerializationContext) + DeserializationInput(clientSerializer).deserialize(blob, clientSerializationContext) } -} \ No newline at end of file +} diff --git a/node/src/test/kotlin/net/corda/node/internal/serialization/RpcServerObservableSerializerTests.kt b/node/src/test/kotlin/net/corda/node/internal/serialization/RpcServerObservableSerializerTests.kt index 8d9e96391b..720d147eac 100644 --- a/node/src/test/kotlin/net/corda/node/internal/serialization/RpcServerObservableSerializerTests.kt +++ b/node/src/test/kotlin/net/corda/node/internal/serialization/RpcServerObservableSerializerTests.kt @@ -8,13 +8,12 @@ import net.corda.node.internal.serialization.testutils.TestObservableContext import net.corda.node.internal.serialization.testutils.serializationContext import net.corda.node.serialization.amqp.RpcServerObservableSerializer import net.corda.node.services.messaging.ObservableSubscription +import net.corda.serialization.internal.AllWhitelist import net.corda.serialization.internal.amqp.SerializationOutput import net.corda.serialization.internal.amqp.SerializerFactory -import net.corda.serialization.internal.AllWhitelist import org.apache.activemq.artemis.api.core.SimpleString import org.junit.Test import rx.Observable -import rx.Subscription import java.time.Instant import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit @@ -28,7 +27,7 @@ class RpcServerObservableSerializerTests { .maximumSize(100) .build() - subMap.put(Trace.InvocationId("test1", Instant.now()), ObservableSubscription(mock())) + subMap.put(Trace.InvocationId("test1", Instant.now()), ObservableSubscription(mock())) return subMap } @@ -72,7 +71,7 @@ class RpcServerObservableSerializerTests { register(RpcServerObservableSerializer()) } - val obs = Observable.create({ 12 }) + val obs = Observable.create { Math.random() } val newContext = RpcServerObservableSerializer.createContext(serializationContext, observable) try { diff --git a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt index ce52ebd50f..76ac89be69 100644 --- a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt @@ -1,21 +1,7 @@ package net.corda.node.services.events -import com.nhaarman.mockito_kotlin.any -import com.nhaarman.mockito_kotlin.argForWhich -import com.nhaarman.mockito_kotlin.doAnswer -import com.nhaarman.mockito_kotlin.doReturn -import com.nhaarman.mockito_kotlin.eq -import com.nhaarman.mockito_kotlin.same -import com.nhaarman.mockito_kotlin.timeout -import com.nhaarman.mockito_kotlin.verify -import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions -import com.nhaarman.mockito_kotlin.whenever -import junit.framework.Assert.fail -import net.corda.core.contracts.SchedulableState -import net.corda.core.contracts.ScheduledActivity -import net.corda.core.contracts.ScheduledStateRef -import net.corda.core.contracts.StateRef -import net.corda.core.contracts.TransactionState +import com.nhaarman.mockito_kotlin.* +import net.corda.core.contracts.* import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.flows.FlowLogicRef @@ -36,11 +22,7 @@ import net.corda.testing.internal.rigorousMock import net.corda.testing.internal.spectator import net.corda.testing.node.MockServices import net.corda.testing.node.TestClock -import org.junit.After -import org.junit.Before -import org.junit.Ignore -import org.junit.Rule -import org.junit.Test +import org.junit.* import org.junit.rules.TestWatcher import org.junit.runner.Description import org.slf4j.Logger @@ -51,6 +33,7 @@ import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.test.assertEquals +import kotlin.test.fail open class NodeSchedulerServiceTestBase { protected class Event(time: Instant) { @@ -87,7 +70,7 @@ open class NodeSchedulerServiceTestBase { doLookup(transactionStates).whenever(it).loadState(any()) } - protected val traces = Collections.synchronizedList(mutableListOf()) + private val traces = Collections.synchronizedList(mutableListOf()) @Before fun resetTraces() { @@ -98,7 +81,7 @@ open class NodeSchedulerServiceTestBase { doReturn(false).whenever(it).isTraceEnabled doAnswer { traces += it.getArgument(1) - }.whenever(it).trace(eq(NodeSchedulerService.schedulingAsNextFormat), any()) + }.whenever(it).trace(eq(NodeSchedulerService.schedulingAsNextFormat), any()) } protected fun assertWaitingFor(ssr: ScheduledStateRef) { @@ -273,7 +256,7 @@ class NodeSchedulerServiceTest : NodeSchedulerServiceTestBase() { class NodeSchedulerPersistenceTest : NodeSchedulerServiceTestBase() { private val databaseConfig: DatabaseConfig = DatabaseConfig() - fun createScheduler(db: CordaPersistence): NodeSchedulerService { + private fun createScheduler(db: CordaPersistence): NodeSchedulerService { return NodeSchedulerService( testClock, db, @@ -285,7 +268,7 @@ class NodeSchedulerPersistenceTest : NodeSchedulerServiceTestBase() { log = log).apply { start() } } - fun transactionStateMock(logicRef: FlowLogicRef, time: Instant): TransactionState<*> { + private fun transactionStateMock(logicRef: FlowLogicRef, time: Instant): TransactionState<*> { return rigorousMock>().also { doReturn(rigorousMock().also { doReturn(ScheduledActivity(logicRef, time)).whenever(it).nextScheduledActivity(any(), any()) diff --git a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTest.kt b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTest.kt index 98b066e343..2a8e7d3e4e 100644 --- a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTest.kt @@ -6,9 +6,8 @@ import net.corda.core.crypto.generateKeyPair import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.seconds import net.corda.node.internal.configureDatabase -import net.corda.node.services.config.CertChainPolicyConfig -import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.config.FlowTimeoutConfiguration +import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.config.configureWithDevSSLCertificate import net.corda.node.services.network.NetworkMapCacheImpl import net.corda.node.services.network.PersistentNetworkMapCache @@ -72,7 +71,6 @@ class ArtemisMessagingTest { doReturn("cordacadevpass").whenever(it).keyStorePassword doReturn(NetworkHostAndPort("0.0.0.0", serverPort)).whenever(it).p2pAddress doReturn(null).whenever(it).jmxMonitoringHttpPort - doReturn(emptyList()).whenever(it).certificateChainCheckPolicies doReturn(FlowTimeoutConfiguration(5.seconds, 3, backoffBase = 1.0)).whenever(it).flowTimeout } LogHelper.setLevel(PersistentUniquenessProvider::class) diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt b/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt index 903ffa6c01..bc02aa19f0 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/DBCheckpointStorageTests.kt @@ -190,7 +190,7 @@ class DBCheckpointStorageTests { override fun call() {} } val frozenLogic = logic.serialize(context = SerializationDefaults.CHECKPOINT_CONTEXT) - val checkpoint = Checkpoint.create(InvocationContext.shell(), FlowStart.Explicit, logic.javaClass, frozenLogic, ALICE, "", SubFlowVersion.CoreFlow(version)).getOrThrow() + val checkpoint = Checkpoint.create(InvocationContext.shell(), FlowStart.Explicit, logic.javaClass, frozenLogic, ALICE, SubFlowVersion.CoreFlow(version)).getOrThrow() return id to checkpoint.serialize(context = SerializationDefaults.CHECKPOINT_CONTEXT) } diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt b/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt index b14abfcfee..44703546e2 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt @@ -7,18 +7,14 @@ import net.corda.core.crypto.SignatureMetadata import net.corda.core.crypto.TransactionSignature import net.corda.core.toFuture import net.corda.core.transactions.SignedTransaction -import net.corda.core.transactions.WireTransaction import net.corda.node.internal.configureDatabase import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.transactions.PersistentUniquenessProvider import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.DatabaseConfig -import net.corda.testing.core.ALICE_NAME -import net.corda.testing.core.DUMMY_NOTARY_NAME -import net.corda.testing.core.SerializationEnvironmentRule -import net.corda.testing.core.TestIdentity -import net.corda.testing.core.dummyCommand +import net.corda.testing.core.* import net.corda.testing.internal.LogHelper +import net.corda.testing.internal.createWireTransaction import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import org.assertj.core.api.Assertions.assertThat import org.junit.After @@ -166,7 +162,7 @@ class DBTransactionStorageTests { } private fun newTransaction(): SignedTransaction { - val wtx = WireTransaction( + val wtx = createWireTransaction( inputs = listOf(StateRef(SecureHash.randomSHA256(), 0)), attachments = emptyList(), outputs = emptyList(), @@ -174,6 +170,9 @@ class DBTransactionStorageTests { notary = DUMMY_NOTARY, timeWindow = null ) - return SignedTransaction(wtx, listOf(TransactionSignature(ByteArray(1), ALICE_PUBKEY, SignatureMetadata(1, Crypto.findSignatureScheme(ALICE_PUBKEY).schemeNumberID)))) + return SignedTransaction( + wtx, + listOf(TransactionSignature(ByteArray(1), ALICE_PUBKEY, SignatureMetadata(1, Crypto.findSignatureScheme(ALICE_PUBKEY).schemeNumberID))) + ) } } diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/HibernateConfigurationTest.kt b/node/src/test/kotlin/net/corda/node/services/persistence/HibernateConfigurationTest.kt index 6b22d940fc..5f4264d536 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/HibernateConfigurationTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/HibernateConfigurationTest.kt @@ -4,7 +4,6 @@ import com.nhaarman.mockito_kotlin.* import net.corda.core.contracts.Amount import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateRef -import net.corda.core.contracts.TransactionState import net.corda.core.crypto.SecureHash import net.corda.core.crypto.generateKeyPair import net.corda.core.identity.AbstractParty @@ -29,23 +28,23 @@ import net.corda.finance.schemas.SampleCashSchemaV2 import net.corda.finance.schemas.SampleCashSchemaV3 import net.corda.finance.utils.sumCash import net.corda.node.internal.configureDatabase +import net.corda.node.services.api.IdentityServiceInternal +import net.corda.node.services.api.WritableTransactionStorage import net.corda.node.services.schema.ContractStateAndRef import net.corda.node.services.schema.HibernateObserver import net.corda.node.services.schema.NodeSchemaService -import net.corda.node.services.vault.VaultSchemaV1 -import net.corda.node.services.api.IdentityServiceInternal -import net.corda.node.services.api.WritableTransactionStorage import net.corda.node.services.vault.NodeVaultService +import net.corda.node.services.vault.VaultSchemaV1 import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.DatabaseConfig import net.corda.nodeapi.internal.persistence.HibernateConfiguration import net.corda.testing.core.* import net.corda.testing.internal.rigorousMock +import net.corda.testing.internal.vault.DummyLinearStateSchemaV1 +import net.corda.testing.internal.vault.DummyLinearStateSchemaV2 import net.corda.testing.internal.vault.VaultFiller import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties -import net.corda.testing.internal.vault.DummyLinearStateSchemaV1 -import net.corda.testing.internal.vault.DummyLinearStateSchemaV2 import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat import org.hibernate.SessionFactory @@ -74,18 +73,18 @@ class HibernateConfigurationTest { val testSerialization = SerializationEnvironmentRule() lateinit var services: MockServices private lateinit var vaultFiller: VaultFiller - lateinit var bankServices: MockServices - lateinit var issuerServices: MockServices - lateinit var notaryServices: MockServices + private lateinit var bankServices: MockServices + private lateinit var issuerServices: MockServices + private lateinit var notaryServices: MockServices lateinit var database: CordaPersistence val vault: VaultService get() = services.vaultService // Hibernate configuration objects lateinit var hibernateConfig: HibernateConfiguration - lateinit var hibernatePersister: HibernateObserver - lateinit var sessionFactory: SessionFactory - lateinit var entityManager: EntityManager - lateinit var criteriaBuilder: CriteriaBuilder + private lateinit var hibernatePersister: HibernateObserver + private lateinit var sessionFactory: SessionFactory + private lateinit var entityManager: EntityManager + private lateinit var criteriaBuilder: CriteriaBuilder // Identities used private lateinit var identity: Party @@ -93,7 +92,7 @@ class HibernateConfigurationTest { private lateinit var notary: Party // test States - lateinit var cashStates: List> + private lateinit var cashStates: List> @Before fun setUp() { @@ -690,7 +689,7 @@ class HibernateConfigurationTest { val queryResults = entityManager.createQuery(criteriaQuery).resultList queryResults.forEach { - val cashState = (services.loadState(toStateRef(it.stateRef!!)) as TransactionState).data + val cashState = services.loadState(toStateRef(it.stateRef!!)).data as Cash.State println("${it.stateRef} with owner: ${cashState.owner.owningKey.toBase58String()}") } @@ -774,7 +773,7 @@ class HibernateConfigurationTest { // execute query val queryResults = entityManager.createQuery(criteriaQuery).resultList queryResults.forEach { - val cashState = (services.loadState(toStateRef(it.stateRef!!)) as TransactionState).data + val cashState = services.loadState(toStateRef(it.stateRef!!)).data as Cash.State println("${it.stateRef} with owner ${cashState.owner.owningKey.toBase58String()} and participants ${cashState.participants.map { it.owningKey.toBase58String() }}") } @@ -913,6 +912,6 @@ class HibernateConfigurationTest { } private fun toStateRef(pStateRef: PersistentStateRef): StateRef { - return StateRef(SecureHash.parse(pStateRef.txId!!), pStateRef.index!!) + return StateRef(SecureHash.parse(pStateRef.txId), pStateRef.index) } -} \ No newline at end of file +} diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/NodeAttachmentStorageTest.kt b/node/src/test/kotlin/net/corda/node/services/persistence/NodeAttachmentStorageTest.kt index 8fa276c2a7..81796a540c 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/NodeAttachmentStorageTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/NodeAttachmentStorageTest.kt @@ -5,11 +5,7 @@ import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import net.corda.core.crypto.SecureHash import net.corda.core.crypto.sha256 -import net.corda.core.internal.read -import net.corda.core.internal.readAll -import net.corda.core.internal.readFully -import net.corda.core.internal.write -import net.corda.core.internal.writeLines +import net.corda.core.internal.* import net.corda.core.node.services.vault.AttachmentQueryCriteria import net.corda.core.node.services.vault.AttachmentSort import net.corda.core.node.services.vault.Builder @@ -59,7 +55,7 @@ class NodeAttachmentStorageTest { fun `insert and retrieve`() { val (testJar, expectedHash) = makeTestJar() - val id = testJar.read { storage.importAttachment(it) } + val id = testJar.read { storage.importAttachment(it, "test", null) } assertEquals(expectedHash, id) assertNull(storage.openAttachment(SecureHash.randomSHA256())) @@ -84,7 +80,7 @@ class NodeAttachmentStorageTest { val (testJar, expectedHash) = makeTestJar() val (jarB, hashB) = makeTestJar(listOf(Pair("file", "content"))) - val id = testJar.read { storage.importAttachment(it) } + val id = testJar.read { storage.importAttachment(it, "test", null) } assertEquals(expectedHash, id) @@ -99,7 +95,7 @@ class NodeAttachmentStorageTest { stream.close() - val idB = jarB.read { storage.importAttachment(it) } + val idB = jarB.read { storage.importAttachment(it, "test", null) } assertEquals(hashB, idB) storage.openAttachment(id)!!.openAsJAR().use { @@ -119,6 +115,7 @@ class NodeAttachmentStorageTest { val (jarB, hashB) = makeTestJar(listOf(Pair("file", "content"))) val (jarC, hashC) = makeTestJar(listOf(Pair("magic_file", "magic_content_puff"))) + @Suppress("DEPRECATION") jarA.read { storage.importAttachment(it) } jarB.read { storage.importAttachment(it, "uploaderB", "fileB.zip") } jarC.read { storage.importAttachment(it, "uploaderC", "fileC.zip") } @@ -186,11 +183,11 @@ class NodeAttachmentStorageTest { fun `duplicates not allowed`() { val (testJar, _) = makeTestJar() testJar.read { - storage.importAttachment(it) + storage.importAttachment(it, "test", null) } assertFailsWith { testJar.read { - storage.importAttachment(it) + storage.importAttachment(it, "test", null) } } } @@ -199,7 +196,7 @@ class NodeAttachmentStorageTest { fun `corrupt entry throws exception`() { val (testJar, _) = makeTestJar() val id = database.transaction { - val id = testJar.read { storage.importAttachment(it) } + val id = testJar.read { storage.importAttachment(it, "test", null) } // Corrupt the file in the store. val bytes = testJar.readAll() @@ -227,7 +224,7 @@ class NodeAttachmentStorageTest { path.writeLines(listOf("Hey", "there!")) path.read { assertFailsWith("either empty or not a JAR") { - storage.importAttachment(it) + storage.importAttachment(it, "test", null) } } } diff --git a/node/src/test/kotlin/net/corda/node/services/transactions/MaxTransactionSizeTests.kt b/node/src/test/kotlin/net/corda/node/services/transactions/MaxTransactionSizeTests.kt index 9195a5d468..14ff42b13e 100644 --- a/node/src/test/kotlin/net/corda/node/services/transactions/MaxTransactionSizeTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/transactions/MaxTransactionSizeTests.kt @@ -5,6 +5,7 @@ import net.corda.core.crypto.SecureHash import net.corda.core.flows.* import net.corda.core.identity.Party import net.corda.core.internal.InputStreamAndHash +import net.corda.core.node.services.AttachmentId import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.getOrThrow import net.corda.testing.common.internal.testNetworkParameters @@ -21,6 +22,7 @@ import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Test +import java.io.InputStream import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -57,10 +59,10 @@ class MaxTransactionSizeTests { val bigFile3 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 2) val bigFile4 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 3) val flow = aliceNode.transaction { - val hash1 = aliceNode.services.attachments.importAttachment(bigFile1.inputStream) - val hash2 = aliceNode.services.attachments.importAttachment(bigFile2.inputStream) - val hash3 = aliceNode.services.attachments.importAttachment(bigFile3.inputStream) - val hash4 = aliceNode.services.attachments.importAttachment(bigFile4.inputStream) + val hash1 = aliceNode.importAttachment(bigFile1.inputStream) + val hash2 = aliceNode.importAttachment(bigFile2.inputStream) + val hash3 = aliceNode.importAttachment(bigFile3.inputStream) + val hash4 = aliceNode.importAttachment(bigFile4.inputStream) assertEquals(hash1, bigFile1.sha256) SendLargeTransactionFlow(notary, bob, hash1, hash2, hash3, hash4) } @@ -80,10 +82,10 @@ class MaxTransactionSizeTests { val bigFile3 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 2) val bigFile4 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 3) val flow = aliceNode.transaction { - val hash1 = aliceNode.services.attachments.importAttachment(bigFile1.inputStream) - val hash2 = aliceNode.services.attachments.importAttachment(bigFile2.inputStream) - val hash3 = aliceNode.services.attachments.importAttachment(bigFile3.inputStream) - val hash4 = aliceNode.services.attachments.importAttachment(bigFile4.inputStream) + val hash1 = aliceNode.importAttachment(bigFile1.inputStream) + val hash2 = aliceNode.importAttachment(bigFile2.inputStream) + val hash3 = aliceNode.importAttachment(bigFile3.inputStream) + val hash4 = aliceNode.importAttachment(bigFile4.inputStream) assertEquals(hash1, bigFile1.sha256) SendLargeTransactionFlow(notary, bob, hash1, hash2, hash3, hash4, verify = false) } @@ -94,6 +96,10 @@ class MaxTransactionSizeTests { } } + private fun StartedMockNode.importAttachment(inputStream: InputStream): AttachmentId { + return services.attachments.importAttachment(inputStream, "test", null) + } + @StartableByRPC @InitiatingFlow class SendLargeTransactionFlow(private val notary: Party, diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt index 60a5628773..54e47d3f08 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt @@ -41,7 +41,6 @@ import org.junit.Test import org.junit.rules.ExpectedException import org.junit.rules.ExternalResource import java.time.Duration -import java.time.Instant import java.time.LocalDate import java.time.ZoneOffset import java.time.temporal.ChronoUnit @@ -103,7 +102,7 @@ open class VaultQueryTestRule : ExternalResource(), VaultQueryParties { override val bob = TestIdentity(BOB_NAME, 80) override val cashNotary = TestIdentity(CordaX500Name("Cash Notary Service", "Zurich", "CH"), 21) override val charlie = TestIdentity(CHARLIE_NAME, 90) - override val dummyCashIssuer = TestIdentity(CordaX500Name("Snake Oil Issuer", "London", "GB"), 10) + final override val dummyCashIssuer = TestIdentity(CordaX500Name("Snake Oil Issuer", "London", "GB"), 10) override val DUMMY_CASH_ISSUER = dummyCashIssuer.ref(1) override val dummyNotary = TestIdentity(DUMMY_NOTARY_NAME, 20) override val DUMMY_OBLIGATION_ISSUER = TestIdentity(CordaX500Name("Snake Oil Issuer", "London", "GB"), 10).party @@ -133,7 +132,7 @@ open class VaultQueryTestRule : ExternalResource(), VaultQueryParties { cordappPackages, makeTestIdentityService(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, dummyCashIssuer.identity, dummyNotary.identity), megaCorp, - moreKeys = DUMMY_NOTARY_KEY) + moreKeys = *arrayOf(DUMMY_NOTARY_KEY)) database = databaseAndServices.first services = databaseAndServices.second vaultFiller = VaultFiller(services, dummyNotary) @@ -151,7 +150,7 @@ open class VaultQueryTestRule : ExternalResource(), VaultQueryParties { } } -class VaultQueryRollbackRule(val vaultQueryParties: VaultQueryParties) : ExternalResource() { +class VaultQueryRollbackRule(private val vaultQueryParties: VaultQueryParties) : ExternalResource() { lateinit var transaction: DatabaseTransaction diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt index e7e3a50ea2..fe270603b5 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt @@ -64,7 +64,7 @@ class VaultWithCashTest { private val servicesKey = generateKeyPair() lateinit var services: MockServices private lateinit var vaultFiller: VaultFiller - lateinit var issuerServices: MockServices + private lateinit var issuerServices: MockServices val vaultService: VaultService get() = services.vaultService lateinit var database: CordaPersistence private lateinit var notaryServices: MockServices @@ -77,7 +77,7 @@ class VaultWithCashTest { cordappPackages, makeTestIdentityService(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, dummyCashIssuer.identity, dummyNotary.identity), TestIdentity(MEGA_CORP.name, servicesKey), - moreKeys = dummyNotary.keyPair) + moreKeys = *arrayOf(dummyNotary.keyPair)) database = databaseAndServices.first services = databaseAndServices.second vaultFiller = VaultFiller(services, dummyNotary) @@ -130,7 +130,7 @@ class VaultWithCashTest { database.transaction { // A tx that spends our money. val spendTXBuilder = TransactionBuilder(DUMMY_NOTARY) - Cash.generateSpend(services, spendTXBuilder, 80.DOLLARS, BOB) + Cash.generateSpend(services, spendTXBuilder, 80.DOLLARS, services.myInfo.legalIdentitiesAndCerts.single(), BOB) val spendPTX = services.signInitialTransaction(spendTXBuilder, freshKey) notaryServices.addSignature(spendPTX) } @@ -178,7 +178,7 @@ class VaultWithCashTest { val first = backgroundExecutor.fork { database.transaction { val txn1Builder = TransactionBuilder(DUMMY_NOTARY) - Cash.generateSpend(services, txn1Builder, 60.DOLLARS, BOB) + Cash.generateSpend(services, txn1Builder, 60.DOLLARS, services.myInfo.legalIdentitiesAndCerts.single(), BOB) val ptxn1 = notaryServices.signInitialTransaction(txn1Builder) val txn1 = services.addSignature(ptxn1, freshKey) println("txn1: ${txn1.id} spent ${((txn1.tx.outputs[0].data) as Cash.State).amount}") @@ -209,7 +209,7 @@ class VaultWithCashTest { val second = backgroundExecutor.fork { database.transaction { val txn2Builder = TransactionBuilder(DUMMY_NOTARY) - Cash.generateSpend(services, txn2Builder, 80.DOLLARS, BOB) + Cash.generateSpend(services, txn2Builder, 80.DOLLARS, services.myInfo.legalIdentitiesAndCerts.single(), BOB) val ptxn2 = notaryServices.signInitialTransaction(txn2Builder) val txn2 = services.addSignature(ptxn2, freshKey) println("txn2: ${txn2.id} spent ${((txn2.tx.outputs[0].data) as Cash.State).amount}") @@ -333,7 +333,7 @@ class VaultWithCashTest { database.transaction { // A tx that spends our money. val spendTXBuilder = TransactionBuilder(DUMMY_NOTARY) - Cash.generateSpend(services, spendTXBuilder, 80.DOLLARS, BOB) + Cash.generateSpend(services, spendTXBuilder, 80.DOLLARS, services.myInfo.legalIdentitiesAndCerts.single(), BOB) val spendPTX = notaryServices.signInitialTransaction(spendTXBuilder) val spendTX = services.addSignature(spendPTX, freshKey) services.recordTransactions(spendTX) diff --git a/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt b/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt index 6adbcd890a..d319c0b1d1 100644 --- a/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt +++ b/node/src/test/kotlin/net/corda/node/utilities/ObservablesTests.kt @@ -13,7 +13,6 @@ import rx.Observable import rx.subjects.PublishSubject import java.io.Closeable import java.util.* -import kotlin.test.fail class ObservablesTests { private fun isInDatabaseTransaction() = contextTransactionOrNull != null @@ -58,7 +57,7 @@ class ObservablesTests { assertThat(secondEvent.get()).isEqualTo(0 to false) } - class TestException : Exception("Synthetic exception for tests") {} + class TestException : Exception("Synthetic exception for tests") @Test fun `bufferUntilDatabaseCommit swallows if transaction rolled back`() { @@ -83,7 +82,6 @@ class ObservablesTests { assertThat(secondEvent.isDone).isFalse() throw TestException() } - fail("Should not have successfully completed transaction") } catch (e: TestException) { } assertThat(secondEvent.isDone).isFalse() @@ -115,7 +113,6 @@ class ObservablesTests { assertThat(secondEvent.isDone).isFalse() throw TestException() } - fail("Should not have successfully completed transaction") } catch (e: TestException) { } assertThat(secondEvent.isDone).isTrue() diff --git a/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt b/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt index 04f157429c..2d6c876139 100644 --- a/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt +++ b/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt @@ -1,10 +1,8 @@ package net.corda.attachmentdemo import net.corda.client.rpc.CordaRPCClient -import net.corda.core.messaging.CordaRPCOps import net.corda.core.utilities.getOrThrow -import net.corda.node.services.Permissions.Companion.invokeRpc -import net.corda.node.services.Permissions.Companion.startFlow +import net.corda.node.services.Permissions.Companion.all import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.core.DUMMY_BANK_B_NAME import net.corda.testing.driver.DriverParameters @@ -20,14 +18,7 @@ class AttachmentDemoTest { fun `attachment demo using a 10MB zip file`() { val numOfExpectedBytes = 10_000_000 driver(DriverParameters(isDebug = true, portAllocation = PortAllocation.Incremental(20000))) { - val demoUser = listOf(User("demo", "demo", setOf( - startFlow(), - invokeRpc(CordaRPCOps::attachmentExists), - invokeRpc(CordaRPCOps::uploadAttachment), - invokeRpc(CordaRPCOps::openAttachment), - invokeRpc(CordaRPCOps::wellKnownPartyFromX500Name), - invokeRpc(CordaRPCOps::internalVerifiedTransactionsFeed) - ))) + val demoUser = listOf(User("demo", "demo", setOf(all()))) val (nodeA, nodeB) = listOf( startNode(providedName = DUMMY_BANK_A_NAME, rpcUsers = demoUser, maximumHeapSize = "1g"), startNode(providedName = DUMMY_BANK_B_NAME, rpcUsers = demoUser, maximumHeapSize = "1g") diff --git a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt index ebbfdab4b6..052606583d 100644 --- a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt +++ b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt @@ -86,14 +86,12 @@ fun sender(rpc: CordaRPCOps, numOfClearBytes: Int = 1024) { // default size 1K. } private fun sender(rpc: CordaRPCOps, inputStream: InputStream, hash: SecureHash.SHA256, executor: ScheduledExecutorService) { - // Get the identity key of the other side (the recipient). val notaryFuture: CordaFuture = poll(executor, DUMMY_NOTARY_NAME.toString()) { rpc.wellKnownPartyFromX500Name(DUMMY_NOTARY_NAME) } val otherSideFuture: CordaFuture = poll(executor, DUMMY_BANK_B_NAME.toString()) { rpc.wellKnownPartyFromX500Name(DUMMY_BANK_B_NAME) } // Make sure we have the file in storage if (!rpc.attachmentExists(hash)) { inputStream.use { - val avail = inputStream.available() val id = rpc.uploadAttachment(it) require(hash == id) { "Id was '$id' instead of '$hash'" } } @@ -133,6 +131,7 @@ class AttachmentDemoFlow(private val otherSide: Party, } } +@Suppress("DEPRECATION") // DOCSTART 1 fun recipient(rpc: CordaRPCOps, webPort: Int) { println("Waiting to receive transaction ...") diff --git a/samples/irs-demo/src/integration-test/kotlin/net/corda/test/spring/SpringDriver.kt b/samples/irs-demo/src/integration-test/kotlin/net/corda/test/spring/SpringDriver.kt index 83e438f4fd..a8645bf341 100644 --- a/samples/irs-demo/src/integration-test/kotlin/net/corda/test/spring/SpringDriver.kt +++ b/samples/irs-demo/src/integration-test/kotlin/net/corda/test/spring/SpringDriver.kt @@ -1,3 +1,5 @@ +@file:Suppress("DEPRECATION") + package net.corda.test.spring import net.corda.core.concurrent.CordaFuture diff --git a/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaGenericsTest.java b/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaGenericsTest.java index d788948b98..40d3f1d311 100644 --- a/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaGenericsTest.java +++ b/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaGenericsTest.java @@ -13,7 +13,7 @@ public class JavaGenericsTest { private final Integer v; private Inner(Integer v) { this.v = v; } - public Integer getV() { return v; } + Integer getV() { return v; } } private static class A { @@ -25,7 +25,7 @@ public class JavaGenericsTest { @Test public void basicGeneric() throws NotSerializableException { - A a1 = new A(1); + A a1 = new A<>(1); SerializerFactory factory = testDefaultFactory(); @@ -66,7 +66,7 @@ public class JavaGenericsTest { @Test public void forceWildcard() throws NotSerializableException { - SerializedBytes bytes = forceWildcardSerialize(new A(new Inner(29))); + SerializedBytes bytes = forceWildcardSerialize(new A<>(new Inner(29))); Inner i = (Inner)forceWildcardDeserialize(bytes).getT(); assertEquals(29, i.getV()); } @@ -75,7 +75,7 @@ public class JavaGenericsTest { public void forceWildcardSharedFactory() throws NotSerializableException { SerializerFactory factory = testDefaultFactory(); - SerializedBytes bytes = forceWildcardSerializeFactory(new A(new Inner(29)), factory); + SerializedBytes bytes = forceWildcardSerializeFactory(new A<>(new Inner(29)), factory); Inner i = (Inner)forceWildcardDeserializeFactory(bytes, factory).getT(); assertEquals(29, i.getV()); diff --git a/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaPrivatePropertyTests.java b/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaPrivatePropertyTests.java index 72b8395b6b..e96763360d 100644 --- a/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaPrivatePropertyTests.java +++ b/serialization/src/test/java/net/corda/serialization/internal/amqp/JavaPrivatePropertyTests.java @@ -7,6 +7,7 @@ import java.io.NotSerializableException; import java.lang.reflect.Field; import java.util.Map; +import static net.corda.core.internal.InternalUtils.uncheckedCast; import static net.corda.serialization.internal.amqp.testutils.AMQPTestUtilsKt.testDefaultFactory; import static org.junit.Assert.*; @@ -30,6 +31,7 @@ public class JavaPrivatePropertyTests { B(Boolean b) { this.b = b; } + @SuppressWarnings("unused") public Boolean isB() { return this.b; } @@ -38,6 +40,7 @@ public class JavaPrivatePropertyTests { static class B2 { private Boolean b; + @SuppressWarnings("unused") public Boolean isB() { return this.b; } @@ -50,6 +53,7 @@ public class JavaPrivatePropertyTests { static class B3 { private Boolean b; + @SuppressWarnings("unused") // break the BEAN format explicitly (i.e. it's not isB) public Boolean isb() { return this.b; @@ -67,6 +71,7 @@ public class JavaPrivatePropertyTests { return this.a; } + @SuppressWarnings("unused") public Boolean isA() { return this.a > 0; } @@ -145,7 +150,7 @@ public class JavaPrivatePropertyTests { Field f = SerializerFactory.class.getDeclaredField("serializersByDescriptor"); f.setAccessible(true); - Map> serializersByDescriptor = (Map>) f.get(factory); + Map> serializersByDescriptor = uncheckedCast(f.get(factory)); assertEquals(1, serializersByDescriptor.size()); ObjectSerializer cSerializer = ((ObjectSerializer)serializersByDescriptor.values().toArray()[0]); @@ -172,7 +177,7 @@ public class JavaPrivatePropertyTests { // Field f = SerializerFactory.class.getDeclaredField("serializersByDescriptor"); f.setAccessible(true); - Map> serializersByDescriptor = (Map>) f.get(factory); + Map> serializersByDescriptor = uncheckedCast(f.get(factory)); assertEquals(1, serializersByDescriptor.size()); ObjectSerializer cSerializer = ((ObjectSerializer)serializersByDescriptor.values().toArray()[0]); diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/ContractAttachmentSerializerTest.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/ContractAttachmentSerializerTest.kt index 9bef17e21c..a4d17cc52e 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/ContractAttachmentSerializerTest.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/ContractAttachmentSerializerTest.kt @@ -17,7 +17,6 @@ import org.junit.Test import kotlin.test.assertEquals class ContractAttachmentSerializerTest { - @Rule @JvmField val testSerialization = SerializationEnvironmentRule() @@ -51,7 +50,7 @@ class ContractAttachmentSerializerTest { fun `write contract attachment and read it back using token context`() { val attachment = GeneratedAttachment("test".toByteArray()) - mockServices.attachments.importAttachment(attachment.open()) + mockServices.attachments.importAttachment(attachment.open(), "test", null) val contractAttachment = ContractAttachment(attachment, DummyContract.PROGRAM_ID) val serialized = contractAttachment.serialize(factory, contextWithToken) @@ -68,7 +67,7 @@ class ContractAttachmentSerializerTest { val largeAttachmentSize = 1024 * 1024 val attachment = GeneratedAttachment(ByteArray(largeAttachmentSize)) - mockServices.attachments.importAttachment(attachment.open()) + mockServices.attachments.importAttachment(attachment.open(), "test", null) val contractAttachment = ContractAttachment(attachment, DummyContract.PROGRAM_ID) val serialized = contractAttachment.serialize(factory, contextWithToken) diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/ErrorMessagesTests.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/ErrorMessagesTests.kt index 0d87de40a8..f1e053cc43 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/ErrorMessagesTests.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/ErrorMessagesTests.kt @@ -2,10 +2,9 @@ package net.corda.serialization.internal.amqp import net.corda.serialization.internal.amqp.testutils.TestSerializationOutput import net.corda.serialization.internal.amqp.testutils.deserialize -import net.corda.serialization.internal.amqp.testutils.serialize import net.corda.serialization.internal.amqp.testutils.testDefaultFactory import net.corda.serialization.internal.amqp.testutils.testName -import org.assertj.core.api.Assertions +import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Ignore import org.junit.Test import java.io.NotSerializableException @@ -28,7 +27,7 @@ class ErrorMessagesTests { val testname = "${javaClass.name}\$${testName()}" - Assertions.assertThatThrownBy { + assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(C(1)) }.isInstanceOf(NotSerializableException::class.java).hasMessage(errMsg("a", testname)) } @@ -43,7 +42,7 @@ class ErrorMessagesTests { val testname = "${javaClass.name}\$${testName()}" - Assertions.assertThatThrownBy { + assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(C(1, 2)) }.isInstanceOf(NotSerializableException::class.java).hasMessage(errMsg("b", testname)) } @@ -55,28 +54,27 @@ class ErrorMessagesTests { // despite b being private, the getter we've added is public and thus allows for the serialisation // of the object data class C(val a: Int, private val b: Int) { - public fun getB() = b + @Suppress("unused") + fun getB() = b } val sf = testDefaultFactory() - val testname = "${javaClass.name}\$${testName()}" - val bytes = TestSerializationOutput(VERBOSE, sf).serialize(C(1, 2)) - val c = DeserializationInput(sf).deserialize(bytes) + DeserializationInput(sf).deserialize(bytes) } // Java allows this to be set at the class level yet Kotlin doesn't for some reason @Ignore("Current behaviour allows for the serialization of objects with private members, this will be disallowed at some point in the future") @Test fun protectedProperty() { - data class C(protected val a: Int) + open class C(@Suppress("unused") protected val a: Int) val sf = testDefaultFactory() val testname = "${javaClass.name}\$${testName()}" - Assertions.assertThatThrownBy { + assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(C(1)) }.isInstanceOf(NotSerializableException::class.java).hasMessage(errMsg("a", testname)) } diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/GenericsTests.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/GenericsTests.kt index a99fefd455..af68f8d669 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/GenericsTests.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/GenericsTests.kt @@ -277,7 +277,7 @@ class GenericsTests { private fun fingerprintingDiffersStrip(state: Any) { class cl : ClassLoader() - val m = ClassLoader::class.java.getDeclaredMethod("findLoadedClass", *arrayOf>(String::class.java)) + val m = ClassLoader::class.java.getDeclaredMethod("findLoadedClass", String::class.java) m.isAccessible = true val factory1 = testDefaultFactory() @@ -295,16 +295,16 @@ class GenericsTests { // now deserialise those objects val factory3 = testDefaultFactory() factory3.register(net.corda.serialization.internal.amqp.custom.PublicKeySerializer) - val des1 = DeserializationInput(factory3).deserializeAndReturnEnvelope(ser1.obj) + DeserializationInput(factory3).deserializeAndReturnEnvelope(ser1.obj) val factory4 = SerializerFactory(AllWhitelist, cl()) factory4.register(net.corda.serialization.internal.amqp.custom.PublicKeySerializer) - val des2 = DeserializationInput(factory4).deserializeAndReturnEnvelope(ser2.obj) + DeserializationInput(factory4).deserializeAndReturnEnvelope(ser2.obj) } @Test fun fingerprintingDiffers() { - val state = TransactionState ( + val state = TransactionState( TestContractState(listOf(miniCorp.party)), "wibble", miniCorp.party, encumbrance = null, @@ -317,7 +317,7 @@ class GenericsTests { @Test fun fingerprintingDiffersList() { - val state = TransactionState ( + val state = TransactionState( TestContractState(listOf(miniCorp.party)), "wibble", miniCorp.party, encumbrance = null, diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/PrivatePropertyTests.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/PrivatePropertyTests.kt index ce6a0e9084..732f8cf313 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/PrivatePropertyTests.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/PrivatePropertyTests.kt @@ -97,7 +97,7 @@ class PrivatePropertyTests { @ConstructorForDeserialization constructor() : this(0, 0) - fun setA(a: Int, b: Int) { this.a = a } + fun setA(a: Int, @Suppress("UNUSED_PARAMETER") b: Int) { this.a = a } fun getA() = a } diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/RoundTripTests.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/RoundTripTests.kt index 575794be83..381032cfbd 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/RoundTripTests.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/RoundTripTests.kt @@ -4,7 +4,8 @@ import net.corda.core.serialization.ConstructorForDeserialization import net.corda.serialization.internal.amqp.testutils.deserialize import net.corda.serialization.internal.amqp.testutils.serialize import net.corda.serialization.internal.amqp.testutils.testDefaultFactoryNoEvolution -import org.assertj.core.api.Assertions +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Test class RoundTripTests { @@ -16,20 +17,15 @@ class RoundTripTests { val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) - Assertions.assertThatThrownBy { + assertThatThrownBy { newC.l.add("d") }.isInstanceOf(UnsupportedOperationException::class.java) } @Test fun mutableStillMutable() { - class C { - val l: MutableList - - @Suppress("Unused") - constructor (l: MutableList) { - this.l = l.toMutableList() - } + class C(l: MutableList) { + val l: MutableList = l.toMutableList() } val factory = testDefaultFactoryNoEvolution() @@ -37,6 +33,7 @@ class RoundTripTests { val newC = DeserializationInput(factory).deserialize(bytes) newC.l.add("d") + assertThat(newC.l).containsExactly("a", "b", "c", "d") } @Test @@ -52,6 +49,7 @@ class RoundTripTests { val newC = DeserializationInput(factory).deserialize(bytes) newC.l.add("d") + assertThat(newC.l).containsExactly("a", "b", "c", "d") } @Test @@ -61,6 +59,6 @@ class RoundTripTests { val factory = testDefaultFactoryNoEvolution() val bytes = SerializationOutput(factory).serialize(C(listOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) - val newC2 = newC.copy(l = (newC.l + "d")) + newC.copy(l = (newC.l + "d")) } -} \ No newline at end of file +} diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationOutputTests.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationOutputTests.kt index a4b73fb283..5a368b8304 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationOutputTests.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationOutputTests.kt @@ -888,6 +888,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi class GenericSubclass(param: OtherGeneric) : GenericSuperclass(param) { override fun equals(other: Any?): Boolean = other is GenericSubclass // This is a bit lame but we just want to check it doesn't throw exceptions + override fun hashCode(): Int = javaClass.hashCode() } @Test @@ -966,8 +967,10 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi assertSame(objCopy.a, objCopy.b) } - data class Spike private constructor(val a: String) { + class Spike private constructor(val a: String) { constructor() : this("a") + override fun equals(other: Any?): Boolean = other is Spike && other.a == this.a + override fun hashCode(): Int = a.hashCode() } @Test @@ -1028,7 +1031,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi serdes(obj, factory, factory2) } - data class ByteArrays(val a: ByteArray, val b: ByteArray) + class ByteArrays(val a: ByteArray, val b: ByteArray) @Test fun `test byte arrays not reference counted`() { @@ -1162,7 +1165,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi } // - // Example stacktrace that this test is tryint to reproduce + // Example stacktrace that this test is trying to reproduce // // java.lang.IllegalArgumentException: // net.corda.core.contracts.TransactionState -> @@ -1179,10 +1182,6 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi // @Test fun reproduceWrongNumberOfArguments() { - val field = SerializerFactory::class.java.getDeclaredField("serializersByType").apply { - this.isAccessible = true - } - data class C(val a: Amount) val factory = testDefaultFactoryNoEvolution() @@ -1337,7 +1336,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi val bytes = SerializationOutput(testDefaultFactory()).serialize(i) try { - val i2 = DeserializationInput(testDefaultFactory()).deserialize(bytes) + DeserializationInput(testDefaultFactory()).deserialize(bytes) } catch (e: NotSerializableException) { throw Error("Deserializing serialized \$C should not throw") } diff --git a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationPropertyOrdering.kt b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationPropertyOrdering.kt index 59f4f8fc1d..0e1f8788f3 100644 --- a/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationPropertyOrdering.kt +++ b/serialization/src/test/kotlin/net/corda/serialization/internal/amqp/SerializationPropertyOrdering.kt @@ -35,7 +35,7 @@ class SerializationPropertyOrdering { val u = User(l,l) val output = TestSerializationOutput(VERBOSE, sf).serializeAndReturnSchema(u) - val input = DeserializationInput(sf).deserialize(output.obj) + DeserializationInput(sf).deserialize(output.obj) } @Test diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt index fa835a2a49..53664ea9f1 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt @@ -34,7 +34,7 @@ class MockKeyManagementService(val identityService: IdentityService, override fun filterMyKeys(candidateKeys: Iterable): Iterable = candidateKeys.filter { it in this.keys } override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate { - return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey), revocationEnabled) + return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey)) } private fun getSigner(publicKey: PublicKey): ContentSigner = net.corda.node.services.keys.getSigner(getSigningKeyPair(publicKey)) diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/NodeBasedTest.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/NodeBasedTest.kt index 7fbd49e067..6eef21a1b3 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/NodeBasedTest.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/NodeBasedTest.kt @@ -67,10 +67,10 @@ abstract class NodeBasedTest(private val cordappPackages: List = emptyLi // Wait until ports are released val portNotBoundChecks = nodes.flatMap { listOf( - it.internals.configuration.p2pAddress.let { addressMustNotBeBoundFuture(shutdownExecutor, it) }, - it.internals.configuration.rpcOptions.address?.let { addressMustNotBeBoundFuture(shutdownExecutor, it) } + addressMustNotBeBoundFuture(shutdownExecutor, it.internals.configuration.p2pAddress), + addressMustNotBeBoundFuture(shutdownExecutor, it.internals.configuration.rpcOptions.address) ) - }.filterNotNull() + } nodes.clear() portNotBoundChecks.transpose().getOrThrow() } finally { diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestUtils.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestUtils.kt index 9a2386497a..5b4555e547 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestUtils.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestUtils.kt @@ -1,11 +1,14 @@ package net.corda.testing.internal +import net.corda.core.contracts.* import net.corda.core.crypto.Crypto import net.corda.core.crypto.Crypto.generateKeyPair +import net.corda.core.crypto.SecureHash import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.identity.PartyAndCertificate import net.corda.core.node.NodeInfo +import net.corda.core.transactions.WireTransaction import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.node.services.config.configureDevKeyAndTrustStores @@ -139,3 +142,15 @@ fun createNodeSslConfig(path: Path, name: CordaX500Name = CordaX500Name("MegaCor return sslConfig } + +/** This is the same as the deprecated [WireTransaction] c'tor but avoids the deprecation warning. */ +fun createWireTransaction(inputs: List, + attachments: List, + outputs: List>, + commands: List>, + notary: Party?, + timeWindow: TimeWindow?, + privacySalt: PrivacySalt = PrivacySalt()): WireTransaction { + val componentGroups = WireTransaction.createComponentGroups(inputs, outputs, commands, attachments, notary, timeWindow) + return WireTransaction(componentGroups, privacySalt) +} diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/views/NodeTerminalView.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/views/NodeTerminalView.kt index abd626159b..a63943bcc6 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/views/NodeTerminalView.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/views/NodeTerminalView.kt @@ -186,6 +186,7 @@ class NodeTerminalView : Fragment() { invoke = ::pollCashBalances ) + @Suppress("DEPRECATION") private fun initialise(config: NodeConfigWrapper, ops: CordaRPCOps) { try { val (txInit, txNext) = ops.internalVerifiedTransactionsFeed() diff --git a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/cli/CommandLineInterface.kt b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/cli/CommandLineInterface.kt index 1836f5e76a..8ea71b8a43 100644 --- a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/cli/CommandLineInterface.kt +++ b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/cli/CommandLineInterface.kt @@ -13,7 +13,6 @@ import java.io.File class CommandLineInterface { - fun run(parsedArgs: CliParser) { val baseDir = parsedArgs.baseDirectory val cacheDir = File(baseDir, Constants.BOOTSTRAPPER_DIR_NAME) @@ -37,7 +36,7 @@ class CommandLineInterface { .build().getOrThrow() persistContext(contextFile, objectMapper, context) } else { - val context = setupContextFromExisting(contextFile, objectMapper, networkName) + val context = setupContextFromExisting(contextFile, objectMapper) val (_, instantiator, _) = Backend.fromContext(context, cacheDir) val nodeAdder = NodeAdder(context, NodeInstantiator(instantiator, context)) parsedArgs.nodesToAdd.map { @@ -48,7 +47,7 @@ class CommandLineInterface { } - private fun setupContextFromExisting(contextFile: File, objectMapper: ObjectMapper, networkName: String): Context { + private fun setupContextFromExisting(contextFile: File, objectMapper: ObjectMapper): Context { return contextFile.let { if (it.exists()) { it.inputStream().use { diff --git a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/context/Context.kt b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/context/Context.kt index 8b72714c8d..ab689eb47f 100644 --- a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/context/Context.kt +++ b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/context/Context.kt @@ -23,7 +23,7 @@ class Context(val networkName: String, val backendType: Backend.BackendType, bac var extraParams = ConcurrentHashMap(backendOptions) private fun registerNode(name: String, nodeInstanceRequest: NodeInstanceRequest) { - nodes.computeIfAbsent(name, { _ -> ConcurrentHashSet() }).add(nodeInstanceRequest.toPersistable()) + nodes.computeIfAbsent(name) { ConcurrentHashSet() }.add(nodeInstanceRequest.toPersistable()) } fun registerNode(request: NodeInstanceRequest) { @@ -53,7 +53,7 @@ class Context(val networkName: String, val backendType: Backend.BackendType, bac nodeInstanceRequest.actualX500, nodeInstanceRequest.localImageId, nodeInstanceRequest.remoteImageName, - nodeInstanceRequest.nodeConfig.rpcOptions.address!!.port, + nodeInstanceRequest.nodeConfig.rpcOptions.address.port, nodeInstanceRequest.expectedFqName, "", "" @@ -62,8 +62,7 @@ class Context(val networkName: String, val backendType: Backend.BackendType, bac } } - fun NodeInstanceRequest.toPersistable(): PersistableNodeInstance { + private fun NodeInstanceRequest.toPersistable(): PersistableNodeInstance { return fromInstanceRequest(this) } } - diff --git a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeFinder.kt b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeFinder.kt index 9c2b75d94b..4de42a5224 100644 --- a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeFinder.kt +++ b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeFinder.kt @@ -2,12 +2,11 @@ package net.corda.bootstrapper.nodes import com.typesafe.config.ConfigFactory import net.corda.bootstrapper.Constants -import org.slf4j.LoggerFactory +import net.corda.core.utilities.contextLogger import java.io.File class NodeFinder(private val scratchDir: File) { - fun findNodes(): List { return scratchDir.walkBottomUp().filter { it.name == "node.conf" && !it.absolutePath.contains(Constants.BOOTSTRAPPER_DIR_NAME) }.map { try { @@ -17,7 +16,7 @@ class NodeFinder(private val scratchDir: File) { } }.filterNotNull() .filter { !it.first.hasPath("notary") } - .map { (nodeConfig, nodeConfigFile) -> + .map { (_, nodeConfigFile) -> LOG.info("We've found a node with name: ${nodeConfigFile.parentFile.name}") FoundNode(nodeConfigFile, nodeConfigFile.parentFile) }.toList() @@ -25,7 +24,7 @@ class NodeFinder(private val scratchDir: File) { } companion object { - val LOG = LoggerFactory.getLogger(NodeFinder::class.java) + val LOG = contextLogger() } } diff --git a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeInstantiator.kt b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeInstantiator.kt index 1c7f0ac6f6..9de81220a9 100644 --- a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeInstantiator.kt +++ b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/nodes/NodeInstantiator.kt @@ -39,40 +39,37 @@ class NodeInstantiator(val instantiator: Instantiator, } fun instantiateNodeInstance(request: Context.PersistableNodeInstance): CompletableFuture { - return instantiateNodeInstance(request.remoteImageName, request.rpcPort!!, request.instanceName, request.fqdn, request.instanceX500).thenApplyAsync { + return instantiateNodeInstance(request.remoteImageName, request.instanceName, request.fqdn, request.instanceX500).thenApplyAsync { InstanceInfo(request.groupName, request.instanceName, request.fqdn, it.first, it.second) } } fun instantiateNodeInstance(request: NodeInstanceRequest): CompletableFuture { - return instantiateNodeInstance(request.remoteImageName, request.nodeConfig.rpcOptions.address!!.port, request.nodeInstanceName, request.expectedFqName, request.actualX500) + return instantiateNodeInstance(request.remoteImageName, request.nodeInstanceName, request.expectedFqName, request.actualX500) .thenApplyAsync { (reachableName, portMapping) -> request.toNodeInstance(reachableName, portMapping) } } fun instantiateNotaryInstance(request: NodeInstanceRequest): CompletableFuture { - return instantiateNotaryInstance(request.remoteImageName, request.nodeConfig.rpcOptions.address!!.port, request.nodeInstanceName, request.expectedFqName) + return instantiateNotaryInstance(request.remoteImageName, request.nodeInstanceName, request.expectedFqName) .thenApplyAsync { (reachableName, portMapping) -> request.toNodeInstance(reachableName, portMapping) } } private fun instantiateNotaryInstance(remoteImageName: String, - rpcPort: Int, nodeInstanceName: String, expectedFqName: String): CompletableFuture>> { return instantiator.instantiateContainer( remoteImageName, listOf(Constants.NODE_P2P_PORT, Constants.NODE_RPC_PORT, Constants.NODE_SSHD_PORT), nodeInstanceName, - mapOf("OUR_NAME" to expectedFqName, - "OUR_PORT" to Constants.NODE_P2P_PORT.toString()) + mapOf("OUR_NAME" to expectedFqName, "OUR_PORT" to Constants.NODE_P2P_PORT.toString()) ) } private fun instantiateNodeInstance(remoteImageName: String, - rpcPort: Int, nodeInstanceName: String, expectedFqName: String, actualX500: String): CompletableFuture>> { diff --git a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/serialization/SerializationHelper.kt b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/serialization/SerializationHelper.kt index d3d867c461..8e350c8c14 100644 --- a/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/serialization/SerializationHelper.kt +++ b/tools/network-bootstrapper/src/main/kotlin/net/corda/bootstrapper/serialization/SerializationHelper.kt @@ -7,13 +7,12 @@ import net.corda.serialization.internal.AMQP_P2P_CONTEXT import net.corda.serialization.internal.AMQP_STORAGE_CONTEXT import net.corda.serialization.internal.SerializationFactoryImpl - class SerializationEngine { companion object { fun init() { synchronized(this) { if (nodeSerializationEnv == null) { - val classloader = this.javaClass.classLoader + val classloader = this::class.java.classLoader nodeSerializationEnv = SerializationEnvironmentImpl( SerializationFactoryImpl().apply { registerScheme(AMQPServerSerializationScheme(emptyList())) @@ -27,4 +26,4 @@ class SerializationEngine { } } } -} \ No newline at end of file +} From 0c8c9148827bdc91a138eef75c345d2840ad41c9 Mon Sep 17 00:00:00 2001 From: Shams Asari Date: Thu, 5 Jul 2018 12:40:36 +0100 Subject: [PATCH 9/9] Removing warnings --- .idea/compiler.xml | 7 ++ .../corda/bridge/smoketest/BridgeSmokeTest.kt | 23 ++-- .../bridge/services/ArtemisConnectionTest.kt | 2 - .../client/jfx/model/StateMachineDataModel.kt | 8 +- .../net/corda/core/messaging/CordaRPCOps.kt | 2 +- .../corda/docs/IntegrationTestingTutorial.kt | 4 +- .../java/net/corda/docs/FlowCookbookJava.java | 7 +- .../tutorial/contract/CommercialPaper.java | 8 +- .../net/corda/behave/network/Network.kt | 118 +----------------- .../main/kotlin/net/corda/behave/node/Node.kt | 30 ++--- .../corda/behave/scenarios/ScenarioState.kt | 2 +- .../behave/scenarios/helpers/Substeps.kt | 9 +- experimental/flow-hook/build.gradle | 1 - .../kotlin/net/corda/flowhook/FiberMonitor.kt | 1 - .../kotlin/net/corda/flowhook/FlowHook.kt | 3 +- .../net/corda/flowhook/FlowHookContainer.kt | 2 +- experimental/ha-testing/build.gradle | 1 - .../haTesting/LinearStateScenarioRunner.kt | 3 +- .../cash/selection/CashSelectionOracleImpl.kt | 4 +- .../selection/CashSelectionSQLServerImpl.kt | 5 +- .../kotlin/net/corda/launcher/Launcher.kt | 16 ++- .../node/services/MySQLNotaryServiceTests.kt | 2 +- .../services/persistence/RunOnceService.kt | 3 +- .../MultiThreadedStateMachineManager.kt | 23 ++-- .../persistence/RunOnceServiceTest.kt | 2 - .../persistence/SchemaMigrationTest.kt | 16 +-- .../LinearStateBatchNotariseContract.kt | 3 +- .../contracts/asset/OnLedgerAsset.kt | 50 +------- .../cash/selection/AbstractCashSelection.kt | 18 ++- .../perftestcordapp/flows/CashExitFlow.kt | 8 +- .../flows/CashIssueAndDoublePayment.kt | 9 +- .../flows/CashIssueAndDuplicatePayment.kt | 9 +- .../flows/CashIssueAndPaymentNoSelection.kt | 7 +- .../perftestcordapp/flows/CashIssueFlow.kt | 3 + .../perftestcordapp/flows/CashPaymentFlow.kt | 4 + .../flows/LinearStateBatchNotariseFlow.kt | 10 +- .../net/corda/testing/node/MockServices.kt | 10 +- .../node/internal/InternalMockNetwork.kt | 2 +- .../node/internal/InternalTestUtils.kt | 26 ++-- .../service/proxy/CordaRPCProxyClient.kt | 4 +- .../service/proxy/RPCProxyWebService.kt | 5 +- .../com/r3/corda/dbmigration/Launcher.kt | 6 +- .../corda/explorer/views/TransactionViewer.kt | 7 +- .../com/r3/corda/jmeter/BaseFlowSampler.kt | 14 +-- .../main/kotlin/net/corda/notarytest/Main.kt | 15 +-- 45 files changed, 168 insertions(+), 344 deletions(-) diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 6c83ad467d..1b1637872f 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -54,6 +54,12 @@ + + + + + + @@ -93,6 +99,7 @@ + diff --git a/bridge/bridgecapsule/src/smoke-test/kotlin/net/corda/bridge/smoketest/BridgeSmokeTest.kt b/bridge/bridgecapsule/src/smoke-test/kotlin/net/corda/bridge/smoketest/BridgeSmokeTest.kt index 5f3688b48b..7b58ad71e1 100644 --- a/bridge/bridgecapsule/src/smoke-test/kotlin/net/corda/bridge/smoketest/BridgeSmokeTest.kt +++ b/bridge/bridgecapsule/src/smoke-test/kotlin/net/corda/bridge/smoketest/BridgeSmokeTest.kt @@ -7,12 +7,10 @@ import net.corda.core.identity.CordaX500Name import net.corda.core.internal.* import net.corda.core.node.NetworkParameters import net.corda.core.node.NotaryInfo -import net.corda.core.node.services.AttachmentId import net.corda.core.serialization.SerializationDefaults import net.corda.core.serialization.serialize import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.contextLogger -import net.corda.node.services.config.CertChainPolicyConfig import net.corda.node.services.config.EnterpriseConfiguration import net.corda.node.services.config.MutualExclusionConfiguration import net.corda.node.services.config.NodeConfiguration @@ -102,7 +100,7 @@ class BridgeSmokeTest { bridgeJar.copyToDirectory(testDir) } - fun createNetworkParams(baseDirectory: Path) { + private fun createNetworkParams(baseDirectory: Path) { val dummyNotaryParty = TestIdentity(DUMMY_NOTARY_NAME) val notaryInfo = NotaryInfo(dummyNotaryParty.party, false) val copier = NetworkParametersCopier(NetworkParameters( @@ -112,18 +110,18 @@ class BridgeSmokeTest { maxMessageSize = 10485760, maxTransactionSize = 40000, epoch = 1, - whitelistedContractImplementations = emptyMap>() + whitelistedContractImplementations = emptyMap() ), overwriteFile = true) copier.install(baseDirectory) } - fun SSLConfiguration.createBridgeKeyStores(legalName: CordaX500Name, - rootCert: X509Certificate = DEV_ROOT_CA.certificate, - intermediateCa: CertificateAndKeyPair = DEV_INTERMEDIATE_CA) { + private fun SSLConfiguration.createBridgeKeyStores(legalName: CordaX500Name, + rootCert: X509Certificate = DEV_ROOT_CA.certificate, + intermediateCa: CertificateAndKeyPair = DEV_INTERMEDIATE_CA) { certificatesDirectory.createDirectories() if (!trustStoreFile.exists()) { - loadKeyStore(javaClass.classLoader.getResourceAsStream("certificates/${DEV_CA_TRUST_STORE_FILE}"), DEV_CA_TRUST_STORE_PASS).save(trustStoreFile, trustStorePassword) + loadKeyStore(javaClass.classLoader.getResourceAsStream("certificates/$DEV_CA_TRUST_STORE_FILE"), DEV_CA_TRUST_STORE_PASS).save(trustStoreFile, trustStorePassword) } val (nodeCaCert, nodeCaKeyPair) = createDevNodeCa(intermediateCa, legalName) @@ -189,13 +187,13 @@ class BridgeSmokeTest { } } - fun serverListening(host: String, port: Int): Boolean { + private fun serverListening(host: String, port: Int): Boolean { var s: Socket? = null - try { + return try { s = Socket(host, port) - return true + true } catch (e: Exception) { - return false + false } finally { try { s?.close() @@ -212,7 +210,6 @@ class BridgeSmokeTest { doReturn("cordacadevpass").whenever(it).keyStorePassword doReturn(NetworkHostAndPort("localhost", 11005)).whenever(it).p2pAddress doReturn(null).whenever(it).jmxMonitoringHttpPort - doReturn(emptyList()).whenever(it).certificateChainCheckPolicies doReturn(EnterpriseConfiguration(MutualExclusionConfiguration(false, "", 20000, 40000), externalBridge = true)).whenever(it).enterpriseConfiguration } val artemisServer = ArtemisMessagingServer(artemisConfig, NetworkHostAndPort("0.0.0.0", 11005), MAX_MESSAGE_SIZE) diff --git a/bridge/src/integration-test/kotlin/net/corda/bridge/services/ArtemisConnectionTest.kt b/bridge/src/integration-test/kotlin/net/corda/bridge/services/ArtemisConnectionTest.kt index 83ceb724a4..9844676da7 100644 --- a/bridge/src/integration-test/kotlin/net/corda/bridge/services/ArtemisConnectionTest.kt +++ b/bridge/src/integration-test/kotlin/net/corda/bridge/services/ArtemisConnectionTest.kt @@ -17,7 +17,6 @@ import net.corda.bridge.createBridgeKeyStores import net.corda.bridge.createNetworkParams import net.corda.bridge.services.artemis.BridgeArtemisConnectionServiceImpl import net.corda.core.utilities.NetworkHostAndPort -import net.corda.node.services.config.CertChainPolicyConfig import net.corda.node.services.config.EnterpriseConfiguration import net.corda.node.services.config.MutualExclusionConfiguration import net.corda.node.services.config.NodeConfiguration @@ -102,7 +101,6 @@ class ArtemisConnectionTest { doReturn("cordacadevpass").whenever(it).keyStorePassword doReturn(NetworkHostAndPort("localhost", 11005)).whenever(it).p2pAddress doReturn(null).whenever(it).jmxMonitoringHttpPort - doReturn(emptyList()).whenever(it).certificateChainCheckPolicies doReturn(EnterpriseConfiguration(MutualExclusionConfiguration(false, "", 20000, 40000), externalBridge = true)).whenever(it).enterpriseConfiguration } val artemisServer = ArtemisMessagingServer(artemisConfig, NetworkHostAndPort("0.0.0.0", 11005), MAX_MESSAGE_SIZE) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/StateMachineDataModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/StateMachineDataModel.kt index a400c74e41..e9bd23ba68 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/StateMachineDataModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/StateMachineDataModel.kt @@ -57,14 +57,16 @@ class StateMachineDataModel { private val progressTracking by observable(NodeMonitorModel::progressTracking) private val progressEvents = progressTracking.recordAsAssociation(ProgressTrackingEvent::stateMachineId) - val counter = Counter() + private val counter = Counter() private val stateMachineIndexMap = HashMap() private val stateMachineStatus = stateMachineUpdates.fold(FXCollections.observableArrayList>()) { list, update -> when (update) { is StateMachineUpdate.Added -> { counter.addSmm() - val flowInitiator= update.stateMachineInfo.initiator + // TODO Use invocationContext instead + @Suppress("DEPRECATION") + val flowInitiator = update.stateMachineInfo.initiator val added: SimpleObjectProperty = SimpleObjectProperty(StateMachineStatus.Added(update.id, update.stateMachineInfo.flowLogicClassName, flowInitiator)) list.add(added) @@ -83,7 +85,7 @@ class StateMachineDataModel { private val stateMachineDataList = stateMachineStatus.map { val smStatus = it.value as StateMachineStatus.Added val id = smStatus.id - val progress = SimpleObjectProperty(progressEvents.get(id)) + val progress = SimpleObjectProperty(progressEvents[id]) StateMachineData(id, smStatus.stateMachineName, smStatus.flowInitiator, Pair(it, EasyBind.map(progress) { ProgressStatus(it?.message) })) } diff --git a/core/src/main/kotlin/net/corda/core/messaging/CordaRPCOps.kt b/core/src/main/kotlin/net/corda/core/messaging/CordaRPCOps.kt index 12fbbc7f19..2c376a5d36 100644 --- a/core/src/main/kotlin/net/corda/core/messaging/CordaRPCOps.kt +++ b/core/src/main/kotlin/net/corda/core/messaging/CordaRPCOps.kt @@ -52,7 +52,7 @@ data class StateMachineInfo @JvmOverloads constructor( * An object representing information about the initiator of the flow. Note that this field is * superceded by the [invocationContext] property, which has more detail. */ - @Deprecated("There is more info available using 'context'") val initiator: FlowInitiator, + @Deprecated("There is more info available using 'invocationContext'") val initiator: FlowInitiator, /** A [DataFeed] of the current progress step as a human readable string, and updates to that string. */ val progressTrackerStepAndUpdates: DataFeed?, /** An [InvocationContext] describing why and by whom the flow was started. */ diff --git a/docs/source/example-code/src/integration-test/kotlin/net/corda/docs/IntegrationTestingTutorial.kt b/docs/source/example-code/src/integration-test/kotlin/net/corda/docs/IntegrationTestingTutorial.kt index 436b2707b5..2c9ed7cf88 100644 --- a/docs/source/example-code/src/integration-test/kotlin/net/corda/docs/IntegrationTestingTutorial.kt +++ b/docs/source/example-code/src/integration-test/kotlin/net/corda/docs/IntegrationTestingTutorial.kt @@ -136,7 +136,7 @@ class IntegrationTestingTutorial : IntegrationTest() { // move to Bob parallel( (1..numberOfStates).map { i -> - expect(match = { it.moved() == i * 100 }) { update: Vault.Update -> + expect(match = { it.moved() == i * 100 }) { _: Vault.Update -> } } ), @@ -154,7 +154,7 @@ class IntegrationTestingTutorial : IntegrationTest() { } } - fun Vault.Update.moved(): Int { + private fun Vault.Update.moved(): Int { val consumedSum = consumed.sumBy { it.state.data.amount.quantity.toInt() } val producedSum = produced.sumBy { it.state.data.amount.quantity.toInt() } return consumedSum - producedSum diff --git a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java index 5d33594b3a..aaca60ab22 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java @@ -40,6 +40,7 @@ import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; @@ -134,7 +135,7 @@ public class FlowCookbookJava { // We retrieve a notary from the network map. // DOCSTART 01 CordaX500Name notaryName = new CordaX500Name("Notary Service", "London", "GB"); - Party specificNotary = getServiceHub().getNetworkMapCache().getNotary(notaryName); + Party specificNotary = Objects.requireNonNull(getServiceHub().getNetworkMapCache().getNotary(notaryName)); // Alternatively, we can pick an arbitrary notary from the notary // list. However, it is always preferable to specify the notary // explicitly, as the notary list might change when new notaries are @@ -378,7 +379,7 @@ public class FlowCookbookJava { // Or we can add the output state as a ``TransactionState``, which already specifies // the output's contract and notary. // DOCSTART 51 - TransactionState txState = new TransactionState(ourOutputState, DummyContract.PROGRAM_ID, specificNotary); + TransactionState txState = new TransactionState<>(ourOutputState, DummyContract.PROGRAM_ID, specificNotary); // DOCEND 51 // Commands can be added as ``Command``s. @@ -662,7 +663,7 @@ public class FlowCookbookJava { } @Override - protected void checkTransaction(SignedTransaction stx) { + protected void checkTransaction(@NotNull SignedTransaction stx) { requireThat(require -> { // Any additional checking we see fit... DummyState outputState = (DummyState) stx.getTx().getOutputs().get(0).getData(); diff --git a/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java b/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java index 6d406ed5ae..249d9580dc 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java @@ -13,6 +13,7 @@ package net.corda.docs.java.tutorial.contract; import net.corda.core.contracts.*; import net.corda.core.transactions.LedgerTransaction; import net.corda.core.transactions.LedgerTransaction.InOutGroup; +import org.jetbrains.annotations.NotNull; import java.time.Instant; import java.util.Currency; @@ -22,6 +23,7 @@ import static net.corda.core.contracts.ContractsDSL.requireSingleCommand; import static net.corda.core.contracts.ContractsDSL.requireThat; import static net.corda.finance.utils.StateSumming.sumCashBy; +@SuppressWarnings("unused") public class CommercialPaper implements Contract { // DOCSTART 1 public static final String IOU_CONTRACT_ID = "com.example.contract.IOUContract"; @@ -29,7 +31,7 @@ public class CommercialPaper implements Contract { // DOCSTART 3 @Override - public void verify(LedgerTransaction tx) { + public void verify(@NotNull LedgerTransaction tx) { List> groups = tx.groupStates(State.class, State::withoutOwner); CommandWithParties cmd = requireSingleCommand(tx.getCommands(), Commands.class); // DOCEND 3 @@ -37,7 +39,7 @@ public class CommercialPaper implements Contract { // DOCSTART 4 TimeWindow timeWindow = tx.getTimeWindow(); - for (InOutGroup group : groups) { + for (InOutGroup group : groups) { List inputs = group.getInputs(); List outputs = group.getOutputs(); @@ -57,6 +59,7 @@ public class CommercialPaper implements Contract { Amount> received = sumCashBy(tx.getOutputStates(), input.getOwner()); if (timeWindow == null) throw new IllegalArgumentException("Redemptions must be timestamped"); Instant time = timeWindow.getFromTime(); + if (time == null) throw new IllegalArgumentException("Redemptions must have a from time"); requireThat(require -> { require.using("the paper must have matured", time.isAfter(input.getMaturityDate())); require.using("the received amount equals the face value", received == input.getFaceValue()); @@ -68,6 +71,7 @@ public class CommercialPaper implements Contract { State output = outputs.get(0); if (timeWindow == null) throw new IllegalArgumentException("Issuances must have a time-window"); Instant time = timeWindow.getUntilTime(); + if (time == null) throw new IllegalArgumentException("Issuances must have an until time"); requireThat(require -> { // Don't allow people to issue commercial paper under other entities identities. require.using("output states are issued by a command signer", cmd.getSigners().contains(output.getIssuance().getParty().getOwningKey())); diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt b/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt index 0946c70fdd..b00eeb6991 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt @@ -11,19 +11,19 @@ package net.corda.behave.network import net.corda.behave.database.DatabaseType -import net.corda.behave.file.* -import net.corda.behave.monitoring.PatternWatch +import net.corda.behave.file.LogSource +import net.corda.behave.file.currentDirectory +import net.corda.behave.file.stagingRoot +import net.corda.behave.file.tmpDirectory import net.corda.behave.node.Distribution import net.corda.behave.node.Node import net.corda.behave.node.configuration.NotaryType import net.corda.behave.process.Command import net.corda.behave.process.JarCommand import net.corda.core.CordaException -import net.corda.core.CordaRuntimeException import net.corda.core.internal.* import net.corda.core.utilities.contextLogger import net.corda.core.utilities.minutes -import net.corda.core.utilities.seconds import java.io.Closeable import java.nio.file.Files import java.nio.file.Path @@ -147,116 +147,8 @@ class Network private constructor( * using Local signing and "Auto Approval" mode */ private fun bootstrapDoorman() { - // TODO: rework how we use the Doorman/NMS (now these are a separate product / distribution) signalFailure("Bootstrapping a Corda Enterprise network using the Doorman is no longer supported; exiting ...") - return - - // WARNING!! Need to use the correct bootstrapper - // only if using OS nodes (need to choose the latest version) - val r3node = nodes.values - .find { it.config.distribution.type == Distribution.Type.CORDA_ENTERPRISE } ?: throw CordaRuntimeException("Missing R3 distribution node") - val distribution = r3node.config.distribution - - // Copy over reference configuration files used in bootstrapping - val source = doormanConfigDirectory - val doormanTargetDirectory = targetDirectory / "doorman" - source.toFile().copyRecursively(doormanTargetDirectory.toFile(), true) - - // Use master version of Bootstrapper - val doormanJar = Distribution.R3_MASTER.doormanJar - log.info("DoormanJar URL: $doormanJar\n") - - // 1. Create key stores for local signer - - // java -jar doorman-.jar --mode ROOT_KEYGEN - log.info("Doorman target directory: $doormanTargetDirectory") - runCommand(JarCommand(doormanJar, - arrayOf("--config-file", "$doormanConfigDirectory/node-init.conf", "--mode", "ROOT_KEYGEN", "--trust-store-password", "password"), - doormanTargetDirectory, timeout)) - - // java -jar doorman-.jar --mode CA_KEYGEN - runCommand(JarCommand(doormanJar, - arrayOf("--config-file", "$doormanConfigDirectory/node-init.conf", "--mode", "CA_KEYGEN"), - doormanTargetDirectory, timeout)) - - // 2. Start the doorman service for notary registration - doormanNMS = JarCommand(doormanJar, - arrayOf("--config-file", "$doormanConfigDirectory/node-init.conf"), - doormanTargetDirectory, timeout) - - val doormanCommand = runCommand(doormanNMS, noWait = true) - log.info("Waiting for DoormanNMS to be alive") - - PatternWatch(doormanCommand.output, "Network management web services started on").await(30.seconds) - log.info("DoormanNMS up and running") - - // Notary Nodes - val notaryNodes = nodes.values.filter { it.config.notary.notaryType != NotaryType.NONE } - notaryNodes.forEach { notaryNode -> - val notaryTargetDirectory = targetDirectory / notaryNode.config.name - log.info("Notary target directory: $notaryTargetDirectory") - - // 3. Create notary node and register with the doorman - runCommand(JarCommand(distribution.cordaJar, - arrayOf("--initial-registration", - "--base-directory", "$notaryTargetDirectory", - "--network-root-truststore", "../doorman/certificates/distribute-nodes/network-root-truststore.jks", - "--network-root-truststore-password", "password"), - notaryTargetDirectory, timeout)) - - // 4. Generate node info files for notary nodes - runCommand(JarCommand(distribution.cordaJar, - arrayOf("--just-generate-node-info", - "--base-directory", "$notaryTargetDirectory"), - notaryTargetDirectory, timeout)) - - // cp (or ln -s) nodeInfo* notary-node-info - val nodeInfoFile = notaryTargetDirectory.toFile().listFiles { _, filename -> filename.matches("nodeInfo-.+".toRegex()) }.firstOrNull() ?: throw CordaRuntimeException("Missing notary nodeInfo file") - - Files.copy(nodeInfoFile.toPath(), (notaryTargetDirectory / "notary-node-info"), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING) - } - - // exit Doorman process - doormanCommand.interrupt() - doormanCommand.waitFor() - - // 5. Add notary identities to the network parameters - - // 6. Load initial network parameters file for network map service - val networkParamsConfig = if (notaryNodes.isEmpty()) "network-parameters-without-notary.conf" else "network-parameters.conf" - val updateNetworkParams = JarCommand(doormanJar, - arrayOf("--config-file", "$doormanTargetDirectory/node.conf", "--set-network-parameters", "$doormanTargetDirectory/$networkParamsConfig"), - doormanTargetDirectory, timeout) - runCommand(updateNetworkParams) - - // 7. Start a fully configured Doorman / NMS - doormanNMS = JarCommand(doormanJar, - arrayOf("--config-file", "$doormanConfigDirectory/node.conf"), - doormanTargetDirectory, timeout) - - val doormanNMSCommand = runCommand(doormanNMS, noWait = true) - log.info("Waiting for DoormanNMS to be alive") - - PatternWatch(doormanNMSCommand.output, "Network management web services started on").await(30.seconds) - log.info("DoormanNMS up and running") - - // 8. Register other participant nodes - val partyNodes = nodes.values.filter { it.config.notary.notaryType == NotaryType.NONE } - partyNodes.forEach { partyNode -> - val partyTargetDirectory = targetDirectory / partyNode.config.name - log.info("Party target directory: $partyTargetDirectory") - - // 3. Create notary node and register with the doorman - runCommand(JarCommand(distribution.cordaJar, - arrayOf("--initial-registration", - "--network-root-truststore", "../doorman/certificates/distribute-nodes/network-root-truststore.jks", - "--network-root-truststore-password", "password", - "--base-directory", "$partyTargetDirectory"), - partyTargetDirectory, timeout)) - } - - isDoormanNMSRunning = true } private fun runCommand(command: Command, noWait: Boolean = false): Command { @@ -446,7 +338,7 @@ class Network private constructor( val rpcProxyPortNo = node.config.nodeInterface.rpcProxy val pid = Files.lines(tmpDirectory / "rpcProxy-pid-$rpcProxyPortNo").findFirst().get() // TODO: consider generic implementation to support non *nix platforms - Command(listOf("kill", "-9", "$pid")).run() + Command(listOf("kill", "-9", pid)).run() (tmpDirectory / "rpcProxy-pid-$rpcProxyPortNo").deleteIfExists() } catch (e: Exception) { diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/Node.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/Node.kt index f322d89d47..e0a6cb2614 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/Node.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/Node.kt @@ -14,7 +14,6 @@ import net.corda.behave.database.DatabaseConnection import net.corda.behave.database.DatabaseType import net.corda.behave.file.LogSource import net.corda.behave.file.currentDirectory -import net.corda.behave.file.stagingRoot import net.corda.behave.monitoring.PatternWatch import net.corda.behave.node.configuration.* import net.corda.behave.process.JarCommand @@ -31,8 +30,8 @@ import net.corda.core.internal.div import net.corda.core.internal.exists import net.corda.core.messaging.CordaRPCOps import net.corda.core.utilities.NetworkHostAndPort -import net.corda.core.utilities.minutes import net.corda.core.utilities.loggerFor +import net.corda.core.utilities.minutes import net.corda.core.utilities.seconds import org.apache.commons.io.FileUtils import java.net.InetAddress @@ -45,7 +44,7 @@ import java.util.concurrent.CountDownLatch */ class Node( val config: Configuration, - val rootDirectory: Path = currentDirectory, + private val rootDirectory: Path = currentDirectory, private val settings: ServiceSettings = ServiceSettings(), val rpcProxy: Boolean = false, val networkType: Distribution.Type @@ -77,18 +76,6 @@ class Node( private var haveDependenciesStopped = false - fun describe(): String { - val network = config.nodeInterface - val database = config.database - return """ - |Node Information: ${config.name} - | - P2P: ${network.host}:${network.p2pPort} - | - RPC: ${network.host}:${network.rpcPort} - | - SSH: ${network.host}:${network.sshPort} - | - DB: ${network.host}:${database.port} (${database.type}) - |""".trimMargin() - } - fun configure() { if (isConfigured) { return } isConfigured = true @@ -164,10 +151,6 @@ class Node( } } - val nodeInfoGenerationOutput: LogSource by lazy { - LogSource(logDirectory, "node-info-gen.log") - } - val logOutput: LogSource by lazy { val hostname = InetAddress.getLocalHost().hostName LogSource(logDirectory, "node-$hostname.*.log") @@ -387,10 +370,11 @@ class Node( val name = name ?: error("Node name not set") val directory = directory ?: error("Runtime directory not set") // TODO: rework how we use the Doorman/NMS (now these are a separate product / distribution) - val compatibilityZoneURL = null - if (networkType == Distribution.Type.CORDA_ENTERPRISE && System.getProperty("USE_NETWORK_SERVICES") != null) - "http://localhost:1300" // TODO: add additional USE_NETWORK_SERVICES_URL to specify location of existing operational environment to use. - else null + val compatibilityZoneURL = if (networkType == Distribution.Type.CORDA_ENTERPRISE && System.getProperty("USE_NETWORK_SERVICES") != null) { + "http://localhost:1300" // TODO: add additional USE_NETWORK_SERVICES_URL to specify location of existing operational environment to use. + } else { + null + } return Node( Configuration( name, diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt index 42581651d5..467e69bac2 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt @@ -72,7 +72,7 @@ class ScenarioState { inline fun withNetwork(action: ScenarioState.() -> T): T { ensureNetworkIsRunning() - return action() + return this.action() } inline fun withClient(nodeName: String, crossinline action: (CordaRPCOps) -> T): T { diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt index 5519ebcce5..5cd3e7e1e2 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt @@ -10,7 +10,6 @@ package net.corda.behave.scenarios.helpers -import net.corda.behave.logging.getLogger import net.corda.behave.scenarios.ScenarioState import net.corda.core.messaging.CordaRPCOps import org.slf4j.Logger @@ -32,12 +31,12 @@ abstract class Substeps(protected val state: ScenarioState) { } protected fun withClientProxy(nodeName: String, action: ScenarioState.(CordaRPCOps) -> T): T { - return state.withClientProxy(nodeName, { - return@withClientProxy try { + return state.withClientProxy(nodeName) { + try { action(state, it) } catch (ex: Exception) { - state.error(ex.message ?: "Failed to execute HTTP call") + state.error(ex.message ?: "Failed to execute HTTP call") } - }) + } } } diff --git a/experimental/flow-hook/build.gradle b/experimental/flow-hook/build.gradle index 84060b827c..ced3dbf488 100644 --- a/experimental/flow-hook/build.gradle +++ b/experimental/flow-hook/build.gradle @@ -34,7 +34,6 @@ repositories { } apply plugin: 'kotlin' -apply plugin: 'kotlin-kapt' apply plugin: 'idea' description 'A javaagent to allow hooking into Kryo' diff --git a/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FiberMonitor.kt b/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FiberMonitor.kt index 64bce119ea..b4b4f80ef2 100644 --- a/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FiberMonitor.kt +++ b/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FiberMonitor.kt @@ -114,7 +114,6 @@ object FiberMonitor { thread { while (true) { Thread.sleep(1000) - this } } } diff --git a/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHook.kt b/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHook.kt index 5ee9445482..d438fb4a1c 100644 --- a/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHook.kt +++ b/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHook.kt @@ -12,7 +12,7 @@ package net.corda.flowhook import java.lang.instrument.Instrumentation -@Suppress("UNUSED") +@Suppress("UNUSED", "UNUSED_PARAMETER") class FlowHookAgent { companion object { @JvmStatic @@ -22,4 +22,3 @@ class FlowHookAgent { } } } - diff --git a/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHookContainer.kt b/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHookContainer.kt index f69a7fcf10..257bc99f65 100644 --- a/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHookContainer.kt +++ b/experimental/flow-hook/src/main/kotlin/net/corda/flowhook/FlowHookContainer.kt @@ -21,7 +21,7 @@ import org.apache.activemq.artemis.core.io.buffer.TimedBuffer import java.sql.Connection import java.util.concurrent.TimeUnit -@Suppress("UNUSED") +@Suppress("UNUSED", "UNUSED_PARAMETER") object FlowHookContainer { @JvmStatic diff --git a/experimental/ha-testing/build.gradle b/experimental/ha-testing/build.gradle index e9d0621f08..42355015ce 100644 --- a/experimental/ha-testing/build.gradle +++ b/experimental/ha-testing/build.gradle @@ -34,7 +34,6 @@ repositories { } apply plugin: 'kotlin' -apply plugin: 'kotlin-kapt' apply plugin: 'idea' apply plugin: 'net.corda.plugins.cordapp' diff --git a/experimental/ha-testing/src/main/kotlin/net/corda/haTesting/LinearStateScenarioRunner.kt b/experimental/ha-testing/src/main/kotlin/net/corda/haTesting/LinearStateScenarioRunner.kt index 7328921004..efb39e6870 100644 --- a/experimental/ha-testing/src/main/kotlin/net/corda/haTesting/LinearStateScenarioRunner.kt +++ b/experimental/ha-testing/src/main/kotlin/net/corda/haTesting/LinearStateScenarioRunner.kt @@ -11,13 +11,11 @@ import java.util.concurrent.Callable // Responsible for executing test scenario for a single node executing `LinearStateBatchNotariseFlow` and verifying the results class LinearStateScenarioRunner(options: OptionSet) : AbstractScenarioRunner(options), Callable { - companion object { private val logger = contextLogger() } override fun call(): Boolean { - scenarioInitialized() try { @@ -42,6 +40,7 @@ class LinearStateScenarioRunner(options: OptionSet) : AbstractScenarioRunner(opt } } + @Suppress("UNUSED_PARAMETER") private fun verifyResultsAndStatesTally(results: MutableList, states: Vault.Page): Boolean { // Unfortunately, there is absolutely nothing in `LinearStateBatchNotariseFlow.Result` which can link it to the original transaction return true diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionOracleImpl.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionOracleImpl.kt index c9c68f1413..111b6045b7 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionOracleImpl.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionOracleImpl.kt @@ -27,8 +27,8 @@ class CashSelectionOracleImpl : AbstractCashSelection(maxRetries = 16, retrySlee private val log = contextLogger() } - override fun isCompatible(metaData: DatabaseMetaData): Boolean { - return metaData.driverName.startsWith(JDBC_DRIVER_NAME, ignoreCase = true) + override fun isCompatible(metadata: DatabaseMetaData): Boolean { + return metadata.driverName.startsWith(JDBC_DRIVER_NAME, ignoreCase = true) } override fun toString() = "${this::class.qualifiedName} for '$JDBC_DRIVER_NAME'" diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionSQLServerImpl.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionSQLServerImpl.kt index fa2578c4c8..6e3e76051e 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionSQLServerImpl.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionSQLServerImpl.kt @@ -16,7 +16,6 @@ import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.contextLogger -import net.corda.core.utilities.toBase58String import java.sql.Connection import java.sql.DatabaseMetaData import java.sql.ResultSet @@ -32,8 +31,8 @@ class CashSelectionSQLServerImpl : AbstractCashSelection(maxRetries = 16, retryS private val log = contextLogger() } - override fun isCompatible(metaData: DatabaseMetaData): Boolean { - return metaData.driverName.startsWith(JDBC_DRIVER_NAME, ignoreCase = true) + override fun isCompatible(metadata: DatabaseMetaData): Boolean { + return metadata.driverName.startsWith(JDBC_DRIVER_NAME, ignoreCase = true) } override fun toString() = "${this::class.qualifiedName} for '$JDBC_DRIVER_NAME'" diff --git a/launcher/src/main/kotlin/net/corda/launcher/Launcher.kt b/launcher/src/main/kotlin/net/corda/launcher/Launcher.kt index 445dee7f4c..4b21edb7de 100644 --- a/launcher/src/main/kotlin/net/corda/launcher/Launcher.kt +++ b/launcher/src/main/kotlin/net/corda/launcher/Launcher.kt @@ -8,7 +8,6 @@ import java.nio.file.Paths import kotlin.system.exitProcess fun main(args: Array) { - if (args.isEmpty()) { println("Usage: launcher [args]") exitProcess(0) @@ -54,15 +53,14 @@ fun main(args: Array) { @Suppress("unchecked") private fun fixBaseDirArg(args: Array, nodeBaseDirFromArgs: Path): Array { val baseDirIdx = args.indexOf("--base-directory") - if (baseDirIdx != -1){ - args[baseDirIdx+1] = nodeBaseDirFromArgs.toString() - return args + return if (baseDirIdx != -1) { + // Replace the arg that follows, i.e. --base-directory X + // TODO This will not work for --base-directory=X + args[baseDirIdx + 1] = nodeBaseDirFromArgs.toString() + args + } else { + args + listOf("--base-directory", nodeBaseDirFromArgs.toString()) } - - val argsWithBaseDir = args.copyOf(args.size + 2) - argsWithBaseDir[argsWithBaseDir.lastIndex - 1] = "--base-directory" - argsWithBaseDir[argsWithBaseDir.lastIndex] = nodeBaseDirFromArgs.toString() - return argsWithBaseDir as Array } private fun setupClassLoader(nodeBaseDir: Path): ClassLoader { diff --git a/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt index 63c72ca297..48113eed2a 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt @@ -257,7 +257,7 @@ class MySQLNotaryServiceTests : IntegrationTest() { } private fun createNotaryNode(): InternalMockNetwork.MockNode { - val dataStoreProperties = makeTestDataSourceProperties(configSupplier = { _, _ -> ConfigFactory.empty() }, fallBackConfigSupplier = ::inMemoryH2DataSourceConfig).apply { + val dataStoreProperties = makeInternalTestDataSourceProperties(configSupplier = { ConfigFactory.empty() }).apply { setProperty("autoCommit", "false") } return mockNet.createUnstartedNode( diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/RunOnceService.kt b/node/src/main/kotlin/net/corda/node/services/persistence/RunOnceService.kt index ab1ca72da1..f91d6d9191 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/RunOnceService.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/RunOnceService.kt @@ -16,6 +16,7 @@ import net.corda.node.utilities.AffinityExecutor import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX import org.hibernate.Session +import org.hibernate.query.NativeQuery import java.io.Serializable import java.sql.SQLTransientConnectionException import java.time.Duration @@ -132,7 +133,7 @@ class RunOnceService(private val database: CordaPersistence, private val machine private fun insertMutualExclusion(session: Session) { val query = session.createNativeQuery("INSERT INTO $TABLE VALUES ('X', :machineName, :pid, CURRENT_TIMESTAMP, :version)", MutualExclusion::class.java) - query.unwrap(org.hibernate.SQLQuery::class.java).addSynchronizedEntityClass(MutualExclusion::class.java) + query.unwrap(NativeQuery::class.java).addSynchronizedEntityClass(MutualExclusion::class.java) query.setParameter("pid", pid) query.setParameter("machineName", machineName) query.setParameter("version", 0) diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/MultiThreadedStateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/MultiThreadedStateMachineManager.kt index 2d3816fc8c..a3ab52e4e8 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/MultiThreadedStateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/MultiThreadedStateMachineManager.kt @@ -70,7 +70,7 @@ class MultiThreadedStateMachineManager( val checkpointStorage: CheckpointStorage, val executor: ExecutorService, val database: CordaPersistence, - val secureRandom: SecureRandom, + private val secureRandom: SecureRandom, private val unfinishedFibers: ReusableLatch = ReusableLatch(), private val classloader: ClassLoader = MultiThreadedStateMachineManager::class.java.classLoader ) : StateMachineManager, StateMachineManagerInternal { @@ -158,7 +158,7 @@ class MultiThreadedStateMachineManager( } serviceHub.networkMapCache.nodeReady.then { resumeRestoredFlows(fibers) - flowMessaging.start { receivedMessage, deduplicationHandler -> + flowMessaging.start { _, deduplicationHandler -> lifeCycle.requireState(State.STARTED, StateMachineStoppedException("Flow cannot be started. State machine is stopped.")) { deliverExternalEvent(deduplicationHandler.externalCause) } @@ -306,10 +306,10 @@ class MultiThreadedStateMachineManager( } private fun checkQuasarJavaAgentPresence() { - check(SuspendableHelper.isJavaAgentActive(), { + check(SuspendableHelper.isJavaAgentActive()) { """Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM. #See https://docs.corda.net/troubleshooting.html - 'Fiber classes not instrumented' for more details.""".trimMargin("#") - }) + } } private fun decrementLiveFibers() { @@ -324,8 +324,7 @@ class MultiThreadedStateMachineManager( return checkpointStorage.getAllCheckpoints().map { (id, serializedCheckpoint) -> // If a flow is added before start() then don't attempt to restore it if (concurrentBox.content.flows.containsKey(id)) return@map null - val checkpoint = deserializeCheckpoint(serializedCheckpoint) - if (checkpoint == null) return@map null + val checkpoint = deserializeCheckpoint(serializedCheckpoint) ?: return@map null createFlowFromCheckpoint( id = id, checkpoint = checkpoint, @@ -440,7 +439,7 @@ class MultiThreadedStateMachineManager( val flowId = sessionToFlow[recipientId] if (flowId == null) { deduplicationHandler.afterDatabaseTransaction() - if (sessionMessage.payload is EndSessionMessage) { + if (sessionMessage.payload === EndSessionMessage) { logger.debug { "Got ${EndSessionMessage::class.java.simpleName} for " + "unknown session $recipientId, discarding..." @@ -537,12 +536,6 @@ class MultiThreadedStateMachineManager( isStartIdempotent: Boolean ): CordaFuture> { val flowId = StateMachineRunId.createRandom() - val deduplicationSeed = when (flowStart) { - FlowStart.Explicit -> flowId.uuid.toString() - is FlowStart.Initiated -> - "${flowStart.initiatingMessage.initiatorSessionId.toLong}-" + - "${flowStart.initiatingMessage.initiationEntropy}" - } // Before we construct the state machine state by freezing the FlowLogic we need to make sure that lazy properties // have access to the fiber (and thereby the service hub) @@ -553,7 +546,7 @@ class MultiThreadedStateMachineManager( val frozenFlowLogic = (flowLogic as FlowLogic<*>).serialize(context = checkpointSerializationContext!!) val flowCorDappVersion = FlowStateMachineImpl.createSubFlowVersion(serviceHub.cordappProvider.getCordappForFlow(flowLogic), serviceHub.myInfo.platformVersion) - val initialCheckpoint = Checkpoint.create(invocationContext, flowStart, flowLogic.javaClass, frozenFlowLogic, ourIdentity, deduplicationSeed, flowCorDappVersion).getOrThrow() + val initialCheckpoint = Checkpoint.create(invocationContext, flowStart, flowLogic.javaClass, frozenFlowLogic, ourIdentity, flowCorDappVersion).getOrThrow() val startedFuture = openFuture() val initialState = StateMachineState( checkpoint = initialCheckpoint, @@ -721,7 +714,7 @@ class MultiThreadedStateMachineManager( private fun addAndStartFlow(id: StateMachineRunId, flow: Flow) { val checkpoint = flow.fiber.snapshot().checkpoint for (sessionId in getFlowSessionIds(checkpoint)) { - sessionToFlow.put(sessionId, id) + sessionToFlow[sessionId] = id } concurrentBox.concurrent { val oldFlow = flows.put(id, flow) diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/RunOnceServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/persistence/RunOnceServiceTest.kt index 68b0692549..d2c2e793f1 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/RunOnceServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/RunOnceServiceTest.kt @@ -246,7 +246,6 @@ class RunOnceServiceTest { assertEquals('X', result.id) assertEquals("machine1", result.machineName) assertEquals("123", result.pid) - assertTrue(result.timestamp is LocalDateTime) return result } @@ -256,7 +255,6 @@ class RunOnceServiceTest { assertEquals('X', result.id) assertEquals("machine2", result.machineName) assertEquals("789", result.pid) - assertTrue(result.timestamp is LocalDateTime) return result } } diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/SchemaMigrationTest.kt b/node/src/test/kotlin/net/corda/node/services/persistence/SchemaMigrationTest.kt index 3bc2203069..35ecb94c26 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/SchemaMigrationTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/SchemaMigrationTest.kt @@ -25,6 +25,7 @@ import net.corda.testing.node.MockServices import org.apache.commons.io.FileUtils import org.assertj.core.api.Assertions.assertThat import org.junit.Test +import java.lang.reflect.Method import java.math.BigInteger import java.net.URL import javax.persistence.* @@ -32,7 +33,6 @@ import java.net.URLClassLoader import java.nio.file.Files import java.nio.file.Path - class SchemaMigrationTest { @Test @@ -82,7 +82,7 @@ class SchemaMigrationTest { // check that the file was picked up val nrOfChangesOnDiscoveredFile = db.dataSource.connection.use { - it.createStatement().executeQuery("select count(*) from DATABASECHANGELOG where filename ='migration/${fileName}'").use { rs -> + it.createStatement().executeQuery("select count(*) from DATABASECHANGELOG where filename ='migration/$fileName'").use { rs -> rs.next() rs.getInt(1) } @@ -102,9 +102,11 @@ class SchemaMigrationTest { } //hacky way to add a folder to the classpath - fun addToClassPath(file: Path) = URLClassLoader::class.java.getDeclaredMethod("addURL", URL::class.java).apply { - isAccessible = true - invoke(ClassLoader.getSystemClassLoader(), file.toFile().toURL()) + private fun addToClassPath(file: Path): Method { + return URLClassLoader::class.java.getDeclaredMethod("addURL", URL::class.java).apply { + isAccessible = true + invoke(ClassLoader.getSystemClassLoader(), file.toUri().toURL()) + } } object DummyTestSchema @@ -116,9 +118,9 @@ class SchemaMigrationTest { @ElementCollection @Column(name = "participants") - @CollectionTable(name = "dummy_test_states_parts", joinColumns = arrayOf( + @CollectionTable(name = "dummy_test_states_parts", joinColumns = [ JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))) + JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")]) override var participants: MutableSet? = null, @Transient diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/LinearStateBatchNotariseContract.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/LinearStateBatchNotariseContract.kt index f1445d1e80..257fd86533 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/LinearStateBatchNotariseContract.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/LinearStateBatchNotariseContract.kt @@ -40,7 +40,6 @@ class LinearStateBatchNotariseContract : Contract { } override fun verify(tx: LedgerTransaction) { - val command = tx.commands.requireSingleCommand() - val timeWindow: TimeWindow? = tx.timeWindow + tx.commands.requireSingleCommand() } } diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/OnLedgerAsset.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/OnLedgerAsset.kt index 7abc6173fd..c494d05a94 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/OnLedgerAsset.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/OnLedgerAsset.kt @@ -230,27 +230,6 @@ abstract class OnLedgerAsset> : C return Pair(gathered, gatheredAmount) } - /** - * Generate an transaction exiting fungible assets from the ledger. - * - * @param tx transaction builder to add states and commands to. - * @param amountIssued the amount to be exited, represented as a quantity of issued currency. - * @param assetStates the asset states to take funds from. No checks are done about ownership of these states, it is - * the responsibility of the caller to check that they do not attempt to exit funds held by others. - * @return the public keys which must sign the transaction for it to be valid. - */ - @Throws(InsufficientBalanceException::class) - @JvmStatic - @Deprecated("Replaced with generateExit() which takes in a party to pay change to") - fun , T: Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, - assetStates: List>, - deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, - generateMoveCommand: () -> CommandData, - generateExitCommand: (Amount>) -> CommandData): Set { - val owner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) - return generateExit(tx, amountIssued, assetStates, owner, deriveState, generateMoveCommand, generateExitCommand) - } - /** * Generate an transaction exiting fungible assets from the ledger. * @@ -323,31 +302,6 @@ abstract class OnLedgerAsset> : C abstract fun extractCommands(commands: Collection>): Collection> - /** - * Generate an transaction exiting assets from the ledger. - * - * @param tx transaction builder to add states and commands to. - * @param amountIssued the amount to be exited, represented as a quantity of issued currency. - * @param assetStates the asset states to take funds from. No checks are done about ownership of these states, it is - * the responsibility of the caller to check that they do not exit funds held by others. - * @param payChangeTo party to pay any change to; this is normally a confidential identity of the calling - * party. - * @return the public keys which must sign the transaction for it to be valid. - */ - @Throws(InsufficientBalanceException::class) - @Deprecated("Replaced with generateExit() which takes in a party to pay change to") - fun generateExit(tx: TransactionBuilder, amountIssued: Amount>, - assetStates: List>): Set { - return generateExit( - tx, - amountIssued, - assetStates, - deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, - generateMoveCommand = { -> generateMoveCommand() }, - generateExitCommand = { amount -> generateExitCommand(amount) } - ) - } - /** * Generate an transaction exiting assets from the ledger. * @@ -367,8 +321,8 @@ abstract class OnLedgerAsset> : C assetStates, payChangeTo, deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, - generateMoveCommand = { -> generateMoveCommand() }, - generateExitCommand = { amount -> generateExitCommand(amount) } + generateMoveCommand = { generateMoveCommand() }, + generateExitCommand = { generateExitCommand(it) } ) } diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/cash/selection/AbstractCashSelection.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/cash/selection/AbstractCashSelection.kt index 98c8830545..ce357fc656 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/cash/selection/AbstractCashSelection.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/cash/selection/AbstractCashSelection.kt @@ -14,22 +14,18 @@ import co.paralleluniverse.fibers.Suspendable import net.corda.core.contracts.Amount import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateRef -import net.corda.core.contracts.TransactionState import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party import net.corda.core.node.ServiceHub import net.corda.core.node.services.StatesNotAvailableException -import net.corda.core.serialization.SerializationDefaults -import net.corda.core.serialization.deserialize import net.corda.core.utilities.* import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash +import net.corda.core.internal.uncheckedCast import java.sql.* import java.util.* import java.util.concurrent.atomic.AtomicReference -import java.util.concurrent.locks.ReentrantLock -import kotlin.concurrent.withLock /** * Pluggable interface to allow for different cash selection provider implementations @@ -41,17 +37,17 @@ import kotlin.concurrent.withLock abstract class AbstractCashSelection(private val maxRetries: Int = 8, private val retrySleep: Int = 100, private val retryCap: Int = 2000) { companion object { - val instance = AtomicReference() + private val instance = AtomicReference() fun getInstance(metadata: () -> java.sql.DatabaseMetaData): AbstractCashSelection { return instance.get() ?: { - val _metadata = metadata() + val metadataResult = metadata() val cashSelectionAlgos = ServiceLoader.load(AbstractCashSelection::class.java).toList() - val cashSelectionAlgo = cashSelectionAlgos.firstOrNull { it.isCompatible(_metadata) } + val cashSelectionAlgo = cashSelectionAlgos.firstOrNull { it.isCompatible(metadataResult) } cashSelectionAlgo?.let { instance.set(cashSelectionAlgo) cashSelectionAlgo - } ?: throw ClassNotFoundException("\nUnable to load compatible cash selection algorithm implementation for JDBC driver ($_metadata)." + + } ?: throw ClassNotFoundException("\nUnable to load compatible cash selection algorithm implementation for JDBC driver ($metadataResult)." + "\nPlease specify an implementation in META-INF/services/${AbstractCashSelection::class.java}") }.invoke() } @@ -84,7 +80,7 @@ abstract class AbstractCashSelection(private val maxRetries: Int = 8, private va abstract fun executeQuery(connection: Connection, amount: Amount, lockId: UUID, notary: Party?, onlyFromIssuerParties: Set, withIssuerRefs: Set, withResultSet: (ResultSet) -> Boolean): Boolean - override abstract fun toString(): String + abstract override fun toString(): String /** * Query to gather Cash states that are available and retry if they are temporarily unavailable. @@ -149,7 +145,7 @@ abstract class AbstractCashSelection(private val maxRetries: Int = 8, private va if (stateRefs.isNotEmpty()) { // TODO: future implementation to retrieve contract states from a Vault BLOB store - stateAndRefs.addAll(services.loadStates(stateRefs) as Collection>) + stateAndRefs.addAll(uncheckedCast(services.loadStates(stateRefs))) } val success = stateAndRefs.isNotEmpty() && totalPennies >= amount.quantity diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlow.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlow.kt index bae6312103..bbbec404f7 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlow.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlow.kt @@ -13,6 +13,9 @@ package com.r3.corda.enterprise.perftestcordapp.flows import co.paralleluniverse.fibers.Suspendable import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash import com.r3.corda.enterprise.perftestcordapp.contracts.asset.cash.selection.AbstractCashSelection +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.FINALISING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.SIGNING_TX import com.r3.corda.enterprise.perftestcordapp.issuedBy import net.corda.core.contracts.Amount import net.corda.core.contracts.InsufficientBalanceException @@ -60,10 +63,13 @@ class CashExitFlow(private val amount: Amount, .getInstance { serviceHub.jdbcSession().metaData } .unconsumedCashStatesForSpending(serviceHub, amount, setOf(issuer.party), builder.notary, builder.lockId, setOf(issuer.reference)) val signers = try { + val changeOwner = exitStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amount) Cash().generateExit( builder, amount.issuedBy(issuer), - exitStates) + exitStates, + changeOwner + ) } catch (e: InsufficientBalanceException) { throw CashException("Exiting more cash than exists", e) } diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDoublePayment.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDoublePayment.kt index 973ee10cd0..49863ee403 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDoublePayment.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDoublePayment.kt @@ -14,6 +14,10 @@ import co.paralleluniverse.fibers.Suspendable import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash import com.r3.corda.enterprise.perftestcordapp.contracts.asset.OnLedgerAsset import com.r3.corda.enterprise.perftestcordapp.contracts.asset.PartyAndAmount +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.FINALISING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_ID +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.confidential.SwapIdentitiesFlow import net.corda.core.contracts.* import net.corda.core.flows.FlowException @@ -23,6 +27,7 @@ import net.corda.core.flows.StartableByRPC import net.corda.core.identity.AbstractParty import net.corda.core.identity.AnonymousParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker @@ -54,7 +59,7 @@ class CashIssueAndDoublePayment(val amount: Amount, = txState.copy(data = txState.data.copy(amount = amt, owner = owner)) val issueResult = subFlow(CashIssueFlow(amount, issueRef, notary)) - val cashStateAndRef = serviceHub.loadStates(setOf(StateRef(issueResult.id, 0))).single() as StateAndRef + val cashStateAndRef: StateAndRef = uncheckedCast(serviceHub.loadStates(setOf(StateRef(issueResult.id, 0))).single()) progressTracker.currentStep = GENERATING_ID val txIdentities = if (anonymous) { @@ -86,7 +91,7 @@ class CashIssueAndDoublePayment(val amount: Amount, progressTracker.currentStep = FINALISING_TX val notarised1 = finaliseTx(tx1, setOf(recipient), "Unable to notarise spend first time") try { - val notarised2 = finaliseTx(tx2, setOf(recipient), "Unable to notarise spend second time") + finaliseTx(tx2, setOf(recipient), "Unable to notarise spend second time") } catch (expected: CashException) { val cause = expected.cause if (cause is NotaryException) { diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDuplicatePayment.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDuplicatePayment.kt index a40b547a13..33d039db19 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDuplicatePayment.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndDuplicatePayment.kt @@ -14,12 +14,17 @@ import co.paralleluniverse.fibers.Suspendable import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash import com.r3.corda.enterprise.perftestcordapp.contracts.asset.OnLedgerAsset import com.r3.corda.enterprise.perftestcordapp.contracts.asset.PartyAndAmount +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.FINALISING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_ID +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.confidential.SwapIdentitiesFlow import net.corda.core.contracts.* import net.corda.core.flows.StartableByRPC import net.corda.core.identity.AbstractParty import net.corda.core.identity.AnonymousParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker @@ -51,7 +56,7 @@ class CashIssueAndDuplicatePayment(val amount: Amount, = txState.copy(data = txState.data.copy(amount = amt, owner = owner)) val issueResult = subFlow(CashIssueFlow(amount, issueRef, notary)) - val cashStateAndRef = serviceHub.loadStates(setOf(StateRef(issueResult.id, 0))).single() as StateAndRef + val cashStateAndRef: StateAndRef = uncheckedCast(serviceHub.loadStates(setOf(StateRef(issueResult.id, 0))).single()) progressTracker.currentStep = GENERATING_ID val txIdentities = if (anonymous) { @@ -74,7 +79,7 @@ class CashIssueAndDuplicatePayment(val amount: Amount, val tx = serviceHub.signInitialTransaction(spendTx, keysForSigning) progressTracker.currentStep = FINALISING_TX - val notarised1 = finaliseTx(tx, setOf(recipient), "Unable to notarise spend first time") + finaliseTx(tx, setOf(recipient), "Unable to notarise spend first time") val notarised2 = finaliseTx(tx, setOf(recipient), "Unable to notarise spend second time") return Result(notarised2.id, recipient) diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelection.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelection.kt index 0a59903e1b..75ba4d6f55 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelection.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelection.kt @@ -14,12 +14,17 @@ import co.paralleluniverse.fibers.Suspendable import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash import com.r3.corda.enterprise.perftestcordapp.contracts.asset.OnLedgerAsset import com.r3.corda.enterprise.perftestcordapp.contracts.asset.PartyAndAmount +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.FINALISING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_ID +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.confidential.SwapIdentitiesFlow import net.corda.core.contracts.* import net.corda.core.flows.StartableByRPC import net.corda.core.identity.AbstractParty import net.corda.core.identity.AnonymousParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker @@ -51,7 +56,7 @@ class CashIssueAndPaymentNoSelection(val amount: Amount, progressTracker.currentStep = GENERATING_TX val issueResult = subFlow(CashIssueFlow(amount, issueRef, notary)) - val cashStateAndRef = serviceHub.loadStates(setOf(StateRef(issueResult.id, 0))).single() as StateAndRef + val cashStateAndRef: StateAndRef = uncheckedCast(serviceHub.loadStates(setOf(StateRef(issueResult.id, 0))).single()) progressTracker.currentStep = GENERATING_ID val txIdentities = if (anonymous) { diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlow.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlow.kt index 7c84ef1057..77e3dd4608 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlow.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlow.kt @@ -12,6 +12,9 @@ package com.r3.corda.enterprise.perftestcordapp.flows import co.paralleluniverse.fibers.Suspendable import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.FINALISING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.SIGNING_TX import com.r3.corda.enterprise.perftestcordapp.issuedBy import net.corda.core.contracts.Amount import net.corda.core.flows.StartableByRPC diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlow.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlow.kt index 6ced99f6d0..c5271ae07e 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlow.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlow.kt @@ -12,6 +12,10 @@ package com.r3.corda.enterprise.perftestcordapp.flows import co.paralleluniverse.fibers.Suspendable import com.r3.corda.enterprise.perftestcordapp.contracts.asset.Cash +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.FINALISING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_ID +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.GENERATING_TX +import com.r3.corda.enterprise.perftestcordapp.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.confidential.SwapIdentitiesFlow import net.corda.core.contracts.Amount import net.corda.core.contracts.InsufficientBalanceException diff --git a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/LinearStateBatchNotariseFlow.kt b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/LinearStateBatchNotariseFlow.kt index b24dcba032..9e231ce683 100644 --- a/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/LinearStateBatchNotariseFlow.kt +++ b/perftestcordapp/src/main/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/LinearStateBatchNotariseFlow.kt @@ -104,8 +104,7 @@ class LinearStateBatchNotariseFlow(private val notary: Party, } builder.addCommand(LinearStateBatchNotariseContract.Commands.Evolve(), us.owningKey) builder.setTimeWindow(TimeWindow.fromOnly(serviceHub.clock.instant())) - val tx = serviceHub.signInitialTransaction(builder, us.owningKey) - return tx + return serviceHub.signInitialTransaction(builder, us.owningKey) } @Suspendable @@ -117,17 +116,16 @@ class LinearStateBatchNotariseFlow(private val notary: Party, @Suspendable private fun assembleInitialTx(us: Party): SignedTransaction { val builder = TransactionBuilder(notary) - (0 until n).forEach { outputIndex -> + (0 until n).forEach { builder.addOutputState(TransactionState(LinearStateBatchNotariseContract.State(UniqueIdentifier(), us, serviceHub.clock.instant()), LinearStateBatchNotariseContract.CP_PROGRAM_ID, notary)) } builder.addCommand(LinearStateBatchNotariseContract.Commands.Create(), us.owningKey) builder.setTimeWindow(TimeWindow.fromOnly(serviceHub.clock.instant())) - val tx = serviceHub.signInitialTransaction(builder, us.owningKey) - return tx + return serviceHub.signInitialTransaction(builder, us.owningKey) } @Suspendable - protected fun finaliseTx(tx: SignedTransaction, message: String): SignedTransaction { + private fun finaliseTx(tx: SignedTransaction, message: String): SignedTransaction { try { return subFlow(FinalityFlow(tx)) } catch (e: NotaryException) { diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockServices.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockServices.kt index 6bbcc34532..c8416bb862 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockServices.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockServices.kt @@ -11,9 +11,6 @@ package net.corda.testing.node import com.google.common.collect.MutableClassToInstanceMap -import com.typesafe.config.Config -import com.typesafe.config.ConfigFactory -import com.typesafe.config.ConfigParseOptions import net.corda.core.contracts.ContractClassName import net.corda.core.contracts.StateRef import net.corda.core.cordapp.CordappProvider @@ -34,9 +31,6 @@ import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.internal.ServicesForResolutionImpl import net.corda.node.internal.configureDatabase import net.corda.node.internal.cordapp.CordappLoader -import net.corda.node.services.api.SchemaService -import net.corda.node.services.api.VaultServiceInternal -import net.corda.node.services.api.WritableTransactionStorage import net.corda.node.services.api.* import net.corda.node.services.identity.InMemoryIdentityService import net.corda.node.services.schema.HibernateObserver @@ -89,7 +83,7 @@ open class MockServices private constructor( */ @JvmStatic fun makeTestDataSourceProperties(nodeName: String = SecureHash.randomSHA256().toString()): Properties { - return makeTestDataSourceProperties(nodeName, null, ::databaseProviderDataSourceConfig, ::inMemoryH2DataSourceConfig) + return makeInternalTestDataSourceProperties(nodeName) } /** @@ -109,7 +103,7 @@ open class MockServices private constructor( networkParameters: NetworkParameters = testNetworkParameters(), vararg moreKeys: KeyPair): Pair { val cordappLoader = CordappLoader.createWithTestPackages(cordappPackages) - val dataSourceProps = makeTestDataSourceProperties(initialIdentity.name.organisation, SecureHash.randomSHA256().toString()) + val dataSourceProps = makeInternalTestDataSourceProperties(initialIdentity.name.organisation, SecureHash.randomSHA256().toString()) val schemaService = NodeSchemaService(cordappLoader.cordappSchemas) val database = configureDatabase(dataSourceProps, makeTestDatabaseProperties(initialIdentity.name.organisation), identityService::wellKnownPartyFromX500Name, identityService::wellKnownPartyFromAnonymous, schemaService) val mockService = database.transaction { diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt index 005962fa2c..6e5cb838c1 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt @@ -383,7 +383,7 @@ open class InternalMockNetwork(private val cordappPackages: List, val config = mockNodeConfiguration().also { doReturn(baseDirectory(id).createDirectories()).whenever(it).baseDirectory doReturn(parameters.legalName ?: CordaX500Name("Mock Company $id", "London", "GB")).whenever(it).myLegalName - doReturn(makeTestDataSourceProperties("node_$id","net_$networkId")).whenever(it).dataSourceProperties + doReturn(makeInternalTestDataSourceProperties("node_$id", "net_$networkId")).whenever(it).dataSourceProperties doReturn(makeTestDatabaseProperties("node_$id")).whenever(it).database doReturn(emptyList()).whenever(it).extraNetworkMapKeys parameters.configOverrides(it) diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt index fb819be221..fc556a0001 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt @@ -146,16 +146,16 @@ internal interface InternalMockMessagingService : MessagingService { * @param nodeName Reflects the "instance" of the in-memory database or database username/schema. * Defaults to a random string. Passed to [configSupplier] and [fallBackConfigSupplier] methods. * @param nodeNameExtension Provides additional name extension for [configSupplier] and [fallBackConfigSupplier]. - * @param configSupplier Returns [Config] with dataSourceProperties, invoked with [nodeName] and [nodeNameExtension] parameters. + * @param configSupplier Returns [Config] with dataSourceProperties, invoked with [nodeName]. * Defaults to configuration created when 'databaseProvider' system property is set. * @param fallBackConfigSupplier Returns [Config] with dataSourceProperties, invoked with [nodeName] and [nodeNameExtension] parameters. * Defaults to configuration of in-memory H2 instance. */ -fun makeTestDataSourceProperties(nodeName: String? = SecureHash.randomSHA256().toString(), - nodeNameExtension: String? = null, - configSupplier: (String?, String?) -> Config = ::databaseProviderDataSourceConfig, - fallBackConfigSupplier: (String?, String?) -> Config = ::inMemoryH2DataSourceConfig): Properties { - val config = configSupplier(nodeName, nodeNameExtension) +fun makeInternalTestDataSourceProperties(nodeName: String? = SecureHash.randomSHA256().toString(), + nodeNameExtension: String? = null, + configSupplier: (String?) -> Config = ::databaseProviderDataSourceConfig, + fallBackConfigSupplier: (String?, String?) -> Config = ::inMemoryH2DataSourceConfig): Properties { + val config = configSupplier(nodeName) .withFallback(fallBackConfigSupplier(nodeName, nodeNameExtension)) .resolve() @@ -175,8 +175,8 @@ fun makeTestDataSourceProperties(nodeName: String? = SecureHash.randomSHA256().t * @param configSupplier Returns [Config] with databaseProperties, invoked with [nodeName] parameter. */ fun makeTestDatabaseProperties(nodeName: String? = null, - configSupplier: (String?, String?) -> Config = ::databaseProviderDataSourceConfig): DatabaseConfig { - val config = configSupplier(nodeName, null) + configSupplier: (String?) -> Config = ::databaseProviderDataSourceConfig): DatabaseConfig { + val config = configSupplier(nodeName) val transactionIsolationLevel = if (config.hasPath(DatabaseConstants.TRANSACTION_ISOLATION_LEVEL)) TransactionIsolationLevel.valueOf(config.getString(DatabaseConstants.TRANSACTION_ISOLATION_LEVEL)) else TransactionIsolationLevel.READ_COMMITTED @@ -188,11 +188,9 @@ fun makeTestDatabaseProperties(nodeName: String? = null, * Reads database and dataSource configuration from a file denoted by 'databaseProvider' system property, * overwritten by system properties and defaults to H2 in memory db. * @param nodeName Reflects the "instance" of the database username/schema, the value will be used to replace ${custom.nodeOrganizationName} placeholder - * @param notUsed Not uses, required for API backward compatibility. * if the placeholder is present in config. */ -fun databaseProviderDataSourceConfig(nodeName: String? = null, notUsed: String? = null): Config { - +fun databaseProviderDataSourceConfig(nodeName: String? = null): Config { val parseOptions = ConfigParseOptions.defaults() val keys = listOf(DatabaseConstants.DATA_SOURCE_URL, DatabaseConstants.DATA_SOURCE_CLASSNAME, @@ -218,11 +216,11 @@ fun databaseProviderDataSourceConfig(nodeName: String? = null, notUsed: String? /** * Creates data source configuration for in memory H2 as it would be specified in reference.conf 'datasource' snippet. - * @param nodeName Reflects the "instance" of the database username/schema + * @param providedNodeName Reflects the "instance" of the database username/schema * @param postfix Additional postix added to database "instance" name to add uniqueness when running integration tests. */ -fun inMemoryH2DataSourceConfig(nodeName: String? = null, postfix: String? = null) : Config { - val nodeName = nodeName ?: SecureHash.randomSHA256().toString() +fun inMemoryH2DataSourceConfig(providedNodeName: String? = null, postfix: String? = null) : Config { + val nodeName = providedNodeName ?: SecureHash.randomSHA256().toString() val h2InstanceName = if (postfix != null) nodeName + "_" + postfix else nodeName return ConfigFactory.parseMap(mapOf( diff --git a/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/CordaRPCProxyClient.kt b/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/CordaRPCProxyClient.kt index fb2543db21..564eb2cb7f 100644 --- a/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/CordaRPCProxyClient.kt +++ b/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/CordaRPCProxyClient.kt @@ -12,6 +12,7 @@ import net.corda.core.identity.Party import net.corda.core.internal.concurrent.doneFuture import net.corda.core.internal.openHttpConnection import net.corda.core.internal.responseAs +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.* import net.corda.core.node.NodeInfo import net.corda.core.node.services.AttachmentId @@ -29,7 +30,6 @@ import java.time.Instant import javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM class CordaRPCProxyClient(private val targetHostAndPort: NetworkHostAndPort) : CordaRPCOps { - companion object { val log = contextLogger() } @@ -47,7 +47,7 @@ class CordaRPCProxyClient(private val targetHostAndPort: NetworkHostAndPort) : C log.info("Corda RPC Proxy client calling: $flowName with values: $argList") val response = doPost(targetHostAndPort, "start-flow", argList.serialize().bytes) val result = doneFuture(response) - return FlowHandleImpl(StateMachineRunId.createRandom(), result) as FlowHandle + return uncheckedCast(FlowHandleImpl(StateMachineRunId.createRandom(), result)) } override fun nodeInfo(): NodeInfo { diff --git a/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/RPCProxyWebService.kt b/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/RPCProxyWebService.kt index 0ce061abab..3a5fa1df14 100644 --- a/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/RPCProxyWebService.kt +++ b/testing/qa/behave/tools/rpc-proxy/src/main/kotlin/net/corda/behave/service/proxy/RPCProxyWebService.kt @@ -25,6 +25,7 @@ import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import javax.ws.rs.core.Response.status +@Suppress("UNUSED_PARAMETER") @Path(RPC_PROXY_PATH) class RPCProxyWebService(targetHostAndPort: NetworkHostAndPort) { @@ -108,7 +109,7 @@ class RPCProxyWebService(targetHostAndPort: NetworkHostAndPort) { fun vaultQuery(input: InputStream): Response { log.info("vaultQuery") val contractStateType = input.readBytes().deserialize() - val clazz = Class.forName(contractStateType) as Class + val clazz = Class.forName(contractStateType).asSubclass(ContractState::class.java) return use { log.info("Calling vaultQuery with: $clazz") it.vaultQuery(clazz) @@ -125,7 +126,7 @@ class RPCProxyWebService(targetHostAndPort: NetworkHostAndPort) { for (i in argsList.indices) { log.info("$i: ${argsList[i]}") } - val flowClass = Class.forName(argsList[0] as String) as Class> + val flowClass = Class.forName(argsList[0] as String).asSubclass(FlowLogic::class.java) val flowArgs = argsList.drop(1).toTypedArray() log.info("Calling flow: $flowClass with arguments: ${flowArgs.asList()}") rpcClient.startFlowDynamic(flowClass, *flowArgs).returnValue.getOrThrow() diff --git a/tools/dbmigration/src/main/kotlin/com/r3/corda/dbmigration/Launcher.kt b/tools/dbmigration/src/main/kotlin/com/r3/corda/dbmigration/Launcher.kt index 274bc3a584..99c9e384e1 100644 --- a/tools/dbmigration/src/main/kotlin/com/r3/corda/dbmigration/Launcher.kt +++ b/tools/dbmigration/src/main/kotlin/com/r3/corda/dbmigration/Launcher.kt @@ -176,7 +176,7 @@ private fun handleCommand(options: OptionSet, baseDirectory: Path, configFile: P options.has(DRY_RUN) -> { val writer = getMigrationOutput(baseDirectory, options) migrationLogger.info("Exporting the current db migrations ...") - runMigrationCommand { migration, dataSource -> + runMigrationCommand { migration, _ -> migration.generateMigrationScript(writer) } } @@ -240,7 +240,7 @@ private fun runWithDataSource(config: Configuration, baseDirectory: Path, classL val jarDirs = config.jarDirs.map { Paths.get(it) } for (jarDir in jarDirs) { if (!jarDir.exists()) { - errorAndExit("Could not find the configured JDBC driver directory: '${jarDir}'.") + errorAndExit("Could not find the configured JDBC driver directory: '$jarDir'.") } } @@ -252,7 +252,7 @@ private fun runWithDataSource(config: Configuration, baseDirectory: Path, classL errorAndExit("""Failed to create datasource. |Please check that the correct JDBC driver is installed in one of the following folders: |${(driversFolder + jarDirs).joinToString("\n\t - ", "\t - ")} - |Caused By ${e}""".trimMargin(), e) + |Caused By $e""".trimMargin(), e) } } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/TransactionViewer.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/TransactionViewer.kt index f52d6c3c7c..2c2003c2c7 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/TransactionViewer.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/TransactionViewer.kt @@ -248,7 +248,7 @@ class TransactionViewer : CordaView("Transactions") { } override fun computeValue(): SecureHash { return if (hashList.isEmpty()) SecureHash.zeroHash - else hashList.fold(hashList[0], { one, another -> one.hashConcat(another) }) + else hashList.fold(hashList[0], SecureHash::hashConcat) } } graphicProperty().bind(hashBinding.map { identicon(it, 30.0) }) @@ -325,7 +325,7 @@ class TransactionViewer : CordaView("Transactions") { } } is IOUState -> { - fun Pane.partyLabel(party: Party) = label(party.nameOrNull().let { PartyNameFormatter.short.format(it) } ?: "Anonymous") { + fun Pane.partyLabel(party: Party) = label(party.nameOrNull().let { PartyNameFormatter.short.format(it) }) { tooltip(party.owningKey.toBase58String()) } row { @@ -363,8 +363,7 @@ private fun calculateTotalEquiv(myIdentity: Party?, outputs: List): AmountDiff { val (reportingCurrency, exchange) = reportingCurrencyExchange fun List.sum(): Long { - val cashSum: Long = map { it as? Cash.State } - .filterNotNull() + val cashSum: Long = mapNotNull { it as? Cash.State } .filter { it.owner.owningKey.toKnownParty().value == myIdentity } .map { exchange(it.amount.withoutIssuer()).quantity } .sum() diff --git a/tools/jmeter/src/main/kotlin/com/r3/corda/jmeter/BaseFlowSampler.kt b/tools/jmeter/src/main/kotlin/com/r3/corda/jmeter/BaseFlowSampler.kt index dd53ca819a..b75cc4a49b 100644 --- a/tools/jmeter/src/main/kotlin/com/r3/corda/jmeter/BaseFlowSampler.kt +++ b/tools/jmeter/src/main/kotlin/com/r3/corda/jmeter/BaseFlowSampler.kt @@ -16,7 +16,7 @@ import net.corda.core.flows.FlowLogic import net.corda.core.internal.LazyPool import net.corda.core.messaging.CordaRPCOps import net.corda.core.utilities.NetworkHostAndPort -import net.corda.core.utilities.loggerFor +import net.corda.core.utilities.contextLogger import org.apache.jmeter.config.Argument import org.apache.jmeter.config.Arguments import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient @@ -27,7 +27,7 @@ import java.util.* /** * Do most of the work for firing flow start requests via RPC at a Corda node. */ -abstract class BaseFlowSampler() : AbstractJavaSamplerClient() { +abstract class BaseFlowSampler : AbstractJavaSamplerClient() { companion object { private data class RPCParams(val address: NetworkHostAndPort, val user: String, val password: String) private data class RPCClient(val rpcClient: CordaRPCClient, val rpcConnection: CordaRPCConnection, val ops: CordaRPCOps) @@ -40,7 +40,7 @@ abstract class BaseFlowSampler() : AbstractJavaSamplerClient() { val allArgs = setOf(label, host, port, username, password) - val log = loggerFor() + val log = contextLogger() private val rpcClientPools = Collections.synchronizedMap(mutableMapOf>()) } @@ -48,7 +48,7 @@ abstract class BaseFlowSampler() : AbstractJavaSamplerClient() { private var rpcParams: RPCParams? = null private var rpcPool: LazyPool? = null - var labelValue: String? = null + private var labelValue: String? = null override fun getDefaultParameters(): Arguments { // Add copies of all args, since they seem to be mutable. @@ -70,7 +70,7 @@ abstract class BaseFlowSampler() : AbstractJavaSamplerClient() { labelValue = null } rpcPool = rpcClientPools.computeIfAbsent(rpcParams) { - LazyPool { + LazyPool { val rpcClient = CordaRPCClient(it.address) val rpcConnection = rpcClient.start(it.user, it.password) val rpcProxy = rpcConnection.proxy @@ -98,14 +98,14 @@ abstract class BaseFlowSampler() : AbstractJavaSamplerClient() { try { val flowResult = handle.returnValue.get() result.sampleEnd() - return result.apply { + result.apply { isSuccessful = true additionalFlowResponseProcessing(context, this, flowResult) } } catch (e: Exception) { result.sampleEnd() e.printStackTrace() - return result.apply { + result.apply { isSuccessful = false additionalFlowResponseProcessing(context, this, e) } diff --git a/tools/notarytest/src/main/kotlin/net/corda/notarytest/Main.kt b/tools/notarytest/src/main/kotlin/net/corda/notarytest/Main.kt index 518d46a2c9..90e93a18bf 100644 --- a/tools/notarytest/src/main/kotlin/net/corda/notarytest/Main.kt +++ b/tools/notarytest/src/main/kotlin/net/corda/notarytest/Main.kt @@ -16,9 +16,6 @@ import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.startFlow import net.corda.core.utilities.NetworkHostAndPort import net.corda.notarytest.service.JDBCLoadTestFlow -import java.io.File -import java.io.PrintWriter -import java.time.Instant import java.util.concurrent.TimeUnit /** The number of test flows to run on each notary node */ @@ -43,7 +40,7 @@ fun main(args: Array) { CordaRPCClient(it).start(notaryDemoUser.username, notaryDemoUser.password).use { println(it.proxy.nodeInfo()) val totalTime = Stopwatch.createStarted() - val durations = run(it.proxy, 1) + run(it.proxy, 1) totalTime.stop() val totalTx = TEST_RUNS * TRANSACTION_COUNT @@ -65,13 +62,3 @@ private fun run(rpc: CordaRPCOps, inputStateCount: Int? = null): List { flowDuration } } - -private fun printCSV(node: NetworkHostAndPort, durations: List, testRuns: Int, batchSize: Int) { - val pw = PrintWriter(File("notarytest-${Instant.now()}-${node.host}${node.port}-${testRuns}x$batchSize.csv")) - val sb = StringBuilder() - sb.append("$testRuns, $batchSize") - sb.append('\n') - sb.append(durations.joinToString()) - pw.write(sb.toString()) - pw.close() -} \ No newline at end of file