From d77290831c9784edf2d2ae5ee7c1d1ce1cd247a5 Mon Sep 17 00:00:00 2001 From: Anthony Keenan Date: Wed, 28 Feb 2018 15:59:56 +0000 Subject: [PATCH] CORDA-1035 - Testing api KDoc Updates (#2670) * [CORDA-1035] Testing api KDoc Updates (#2584) * Testing api KDoc Updates * Update after code review * Update api-current * Revert changes to compiler.xml * Made comment changes from review * Fixing merge conflict * Don't expose net.corda.node through test API (first pass) * Fixing merge conflicts * Update api-current * Addressing review commits * Fix exposure of internal implementation of MessageHandlerRegistration * Make InProcess expose ServiceHub instead of internal StartedNodeServices * Move InternalMockMessaginService interface to internal namespace * Move MOCK_VERSION_INFO to internal namespace to avoid exposing VersionInfo * Don't expose WritableTransactionStorage via testing api * Create public VerifierType enum * Update api-current and modify check-api-changes to check for net.corda.node exposures * Fix merge conflicts * Fixing another merge conflict * Fix accidentally broken unit tests * Make getInternalServices a property * Fix failing unit tests * Add todo to check-api-changes * Fix rpc sender thread busy looping * Fix tests * Fixing tests * Address mike's comments * Fixing tests * Make random port allocation internal * Update api * Update api --- .ci/api-current.txt | 290 ++++++++++-------- .ci/check-api-changes.sh | 4 + .../corda/client/jfx/NodeMonitorModelTest.kt | 1 + .../client/rpc/CordaRPCJavaClientTest.java | 4 +- .../client/rpc/FlowsExecutionModeRpcTest.kt | 2 +- .../confidential/IdentitySyncFlowTests.kt | 12 +- .../confidential/SwapIdentitiesFlowTests.kt | 6 +- .../net/corda/core/flows/FlowsInJavaTest.java | 5 +- .../core/crypto/PartialMerkleTreeTest.kt | 2 +- .../net/corda/core/flows/AttachmentTests.kt | 16 +- .../core/flows/CollectSignaturesFlowTests.kt | 10 +- .../core/flows/ContractUpgradeFlowTest.kt | 21 +- .../net/corda/core/flows/FinalityFlowTests.kt | 25 +- .../corda/core/flows/ReceiveAllFlowTests.kt | 9 +- .../internal/ResolveTransactionsFlowTest.kt | 14 +- .../AttachmentSerializationTest.kt | 10 +- .../TransactionSerializationTests.kt | 1 + docs/packages.md | 42 ++- .../corda/docs/IntegrationTestingTutorial.kt | 4 +- .../corda/docs/FxTransactionBuildTutorial.kt | 4 +- .../tutorial/contract/TutorialContract.kt | 4 +- .../mocknetwork/TutorialMockNetwork.kt | 52 ++-- .../tutorial/testdsl/CommercialPaperTest.java | 37 ++- .../net/corda/docs/CustomVaultQueryTest.kt | 18 +- .../docs/FxTransactionBuildTutorialTest.kt | 32 +- .../WorkflowTransactionBuildTutorialTest.kt | 39 ++- .../docs/tutorial/testdsl/TutorialTestDSL.kt | 2 + docs/source/flow-testing.rst | 12 +- .../finance/contracts/CommercialPaperTests.kt | 5 +- .../contracts/asset/ObligationTests.kt | 1 + .../cash/selection/CashSelectionH2ImplTest.kt | 11 +- .../corda/finance/flows/CashExitFlowTests.kt | 7 +- .../corda/finance/flows/CashIssueFlowTests.kt | 5 +- .../finance/flows/CashPaymentFlowTests.kt | 16 +- .../corda/node/CordappScanningDriverTest.kt | 4 +- .../net/corda/node/NodePerformanceTests.kt | 6 +- .../draining/P2PFlowsDrainingModeTest.kt | 4 +- .../node/services/BFTNotaryServiceTests.kt | 20 +- .../node/services/DistributedServiceTests.kt | 5 +- .../node/services/RaftNotaryServiceTests.kt | 16 +- .../node/services/network/NetworkMapTest.kt | 3 +- .../services/network/NodeInfoWatcherTest.kt | 2 +- .../network/PersistentNetworkMapCacheTest.kt | 4 +- .../net/corda/node/services/rpc/RpcSslTest.kt | 5 +- .../statemachine/FlowVersioningTest.kt | 6 +- .../statemachine/LargeTransactionsTest.kt | 3 +- .../services/messaging/MQSecurityTest.kt | 8 +- .../services/messaging/P2PMQSecurityTest.kt | 6 +- .../services/messaging/P2PMessagingTest.kt | 29 +- .../services/messaging/RPCMQSecurityTest.kt | 6 +- .../test/node/NodeStatePersistenceTests.kt | 11 +- .../net/corda/node/CordaRPCOpsImplTest.kt | 3 +- .../node/internal/NetworkParametersTest.kt | 18 +- .../node/messaging/InMemoryMessagingTests.kt | 6 +- .../node/messaging/TwoPartyTradeFlowTests.kt | 9 +- .../ScheduledFlowsDrainingModeTest.kt | 6 +- .../corda/node/services/NotaryChangeTests.kt | 14 +- .../services/events/ScheduledFlowTests.kt | 12 +- .../messaging/ArtemisMessagingTest.kt | 2 +- .../services/network/NetworkMapCacheTest.kt | 6 +- .../persistence/HibernateConfigurationTest.kt | 3 +- .../node/services/rpc/ArtemisRpcTests.kt | 3 +- .../services/schema/NodeSchemaServiceTest.kt | 9 +- .../statemachine/FlowFrameworkTests.kt | 27 +- .../transactions/MaxTransactionSizeTests.kt | 47 ++- .../transactions/NotaryServiceTests.kt | 73 ++--- .../ValidatingNotaryServiceTests.kt | 23 +- .../services/vault/NodeVaultServiceTest.kt | 15 +- .../node/services/vault/VaultQueryTests.kt | 1 + .../vault/VaultSoftLockManagerTest.kt | 14 +- .../corda/irs/api/NodeInterestRatesTest.kt | 2 +- .../kotlin/net/corda/irs/contract/IRSTests.kt | 3 +- .../kotlin/net/corda/irs/IRSDemoTest.kt | 5 +- .../net/corda/netmap/NetworkMapVisualiser.kt | 9 +- .../net/corda/netmap/VisualiserViewModel.kt | 4 +- .../corda/netmap/simulation/IRSSimulation.kt | 12 +- .../net/corda/netmap/simulation/Simulation.kt | 5 +- .../net/corda/traderdemo/TraderDemoTest.kt | 6 +- .../traderdemo/TransactionGraphSearchTests.kt | 2 +- .../net/corda/testing/driver/DriverTests.kt | 3 +- .../testing/node/FlowStackSnapshotTest.kt | 2 +- .../kotlin/net/corda/testing/driver/Driver.kt | 95 ++++-- .../net/corda/testing/driver/DriverDSL.kt | 15 +- .../testing/driver/internal/DriverInternal.kt | 15 +- .../testing/node/InMemoryMessagingNetwork.kt | 114 ++++--- .../net/corda/testing/node/MockNetwork.kt | 177 +++++++---- .../net/corda/testing/node/MockServices.kt | 108 ++----- .../net/corda/testing/node/NodeTestUtils.kt | 22 +- .../net/corda/testing/node/NotarySpec.kt | 17 +- .../kotlin/net/corda/testing/node/User.kt | 8 +- .../testing/node/internal/DriverDSLImpl.kt | 2 +- .../testing/node/internal/InMemoryMessage.kt | 15 + .../node/internal/InternalMockNetwork.kt | 37 ++- .../node/internal/InternalTestUtils.kt | 19 +- .../node/internal/MockKeyManagementService.kt | 57 ++++ .../node/internal/MockTransactionStorage.kt | 38 +++ .../testing/node/internal/NodeBasedTest.kt | 1 - .../corda/testing/contracts/DummyContract.kt | 15 + .../net/corda/testing/contracts/DummyState.kt | 4 +- .../kotlin/net/corda/testing/core/Expect.kt | 3 + .../testing/core/SerializationTestHelpers.kt | 13 +- .../net/corda/testing/core/TestConstants.kt | 13 +- .../net/corda/testing/core/TestUtils.kt | 17 +- .../testing/dsl/TransactionDSLInterpreter.kt | 3 + .../FlowStackSnapshot.kt | 2 +- .../InternalSerializationTestHelpers.kt | 11 +- .../testing/internal/InternalTestConstants.kt | 5 + .../testing/internal/InternalTestUtils.kt | 16 + .../testing/internal/vault/VaultFiller.kt | 2 + .../testing/services/MockAttachmentStorage.kt | 27 +- ...ices.statemachine.FlowStackSnapshotFactory | 2 +- .../views/cordapps/cash/NewTransaction.kt | 4 +- tools/scripts/upgrade-test-packages.ps1 | 2 +- tools/scripts/upgrade-test-packages.sh | 1 - .../net/corda/verifier/VerifierTests.kt | 2 +- 115 files changed, 1220 insertions(+), 867 deletions(-) create mode 100644 testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InMemoryMessage.kt create mode 100644 testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt create mode 100644 testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockTransactionStorage.kt rename testing/test-utils/src/main/kotlin/net/corda/testing/{services => internal}/FlowStackSnapshot.kt (99%) diff --git a/.ci/api-current.txt b/.ci/api-current.txt index 5d9b37ed50..5e526faca8 100644 --- a/.ci/api-current.txt +++ b/.ci/api-current.txt @@ -634,6 +634,7 @@ public static final class net.corda.core.contracts.UniqueIdentifier$Companion ex ## @net.corda.core.serialization.CordaSerializable @net.corda.core.DoNotImplement public final class net.corda.core.contracts.WhitelistedByZoneAttachmentConstraint extends java.lang.Object implements net.corda.core.contracts.AttachmentConstraint public boolean isSatisfiedBy(net.corda.core.contracts.Attachment) + public static final net.corda.core.contracts.WhitelistedByZoneAttachmentConstraint INSTANCE ## @net.corda.core.DoNotImplement public interface net.corda.core.cordapp.Cordapp @org.jetbrains.annotations.NotNull public abstract List getContractClassNames() @@ -1320,6 +1321,39 @@ public @interface net.corda.core.flows.InitiatedBy public @interface net.corda.core.flows.InitiatingFlow public abstract int version() ## +@net.corda.core.serialization.CordaSerializable public final class net.corda.core.flows.NotarisationPayload extends java.lang.Object + public (Object, net.corda.core.flows.NotarisationRequestSignature) + @org.jetbrains.annotations.NotNull public final Object component1() + @org.jetbrains.annotations.NotNull public final net.corda.core.flows.NotarisationRequestSignature component2() + @org.jetbrains.annotations.NotNull public final net.corda.core.flows.NotarisationPayload copy(Object, net.corda.core.flows.NotarisationRequestSignature) + public boolean equals(Object) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.CoreTransaction getCoreTransaction() + @org.jetbrains.annotations.NotNull public final net.corda.core.flows.NotarisationRequestSignature getRequestSignature() + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.SignedTransaction getSignedTransaction() + @org.jetbrains.annotations.NotNull public final Object getTransaction() + public int hashCode() + public String toString() +## +@net.corda.core.serialization.CordaSerializable public final class net.corda.core.flows.NotarisationRequest extends java.lang.Object + public (List, net.corda.core.crypto.SecureHash) + @org.jetbrains.annotations.NotNull public final List getStatesToConsume() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash getTransactionId() + public final void verifySignature(net.corda.core.flows.NotarisationRequestSignature, net.corda.core.identity.Party) + public static final net.corda.core.flows.NotarisationRequest$Companion Companion +## +public static final class net.corda.core.flows.NotarisationRequest$Companion extends java.lang.Object +## +@net.corda.core.serialization.CordaSerializable public final class net.corda.core.flows.NotarisationRequestSignature extends java.lang.Object + public (net.corda.core.crypto.DigitalSignature$WithKey, int) + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.DigitalSignature$WithKey component1() + public final int component2() + @org.jetbrains.annotations.NotNull public final net.corda.core.flows.NotarisationRequestSignature copy(net.corda.core.crypto.DigitalSignature$WithKey, int) + public boolean equals(Object) + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.DigitalSignature$WithKey getDigitalSignature() + public final int getPlatformVersion() + public int hashCode() + public String toString() +## @net.corda.core.flows.InitiatingFlow public final class net.corda.core.flows.NotaryChangeFlow extends net.corda.core.flows.AbstractStateReplacementFlow$Instigator public (net.corda.core.contracts.StateAndRef, net.corda.core.identity.Party, net.corda.core.utilities.ProgressTracker) @org.jetbrains.annotations.NotNull protected net.corda.core.flows.AbstractStateReplacementFlow$UpgradeTx assembleTx() @@ -1346,6 +1380,15 @@ public @interface net.corda.core.flows.InitiatingFlow public int hashCode() @org.jetbrains.annotations.NotNull public String toString() ## +@net.corda.core.serialization.CordaSerializable public static final class net.corda.core.flows.NotaryError$RequestSignatureInvalid extends net.corda.core.flows.NotaryError + public (Throwable) + @org.jetbrains.annotations.NotNull public final Throwable component1() + @org.jetbrains.annotations.NotNull public final net.corda.core.flows.NotaryError$RequestSignatureInvalid copy(Throwable) + public boolean equals(Object) + @org.jetbrains.annotations.NotNull public final Throwable getCause() + public int hashCode() + @org.jetbrains.annotations.NotNull public String toString() +## @net.corda.core.serialization.CordaSerializable public static final class net.corda.core.flows.NotaryError$TimeWindowInvalid extends net.corda.core.flows.NotaryError public (java.time.Instant, net.corda.core.contracts.TimeWindow) @org.jetbrains.annotations.NotNull public final java.time.Instant component1() @@ -1384,6 +1427,7 @@ public final class net.corda.core.flows.NotaryFlow extends java.lang.Object public (net.corda.core.transactions.SignedTransaction) public (net.corda.core.transactions.SignedTransaction, net.corda.core.utilities.ProgressTracker) @co.paralleluniverse.fibers.Suspendable @org.jetbrains.annotations.NotNull public List call() + @org.jetbrains.annotations.NotNull protected final net.corda.core.identity.Party checkTransaction() @org.jetbrains.annotations.NotNull public net.corda.core.utilities.ProgressTracker getProgressTracker() @co.paralleluniverse.fibers.Suspendable @org.jetbrains.annotations.NotNull protected final net.corda.core.utilities.UntrustworthyData notarise(net.corda.core.identity.Party) @org.jetbrains.annotations.NotNull protected final List validateResponse(net.corda.core.utilities.UntrustworthyData, net.corda.core.identity.Party) @@ -1844,6 +1888,8 @@ public @interface net.corda.core.messaging.RPCReturnsObservables @org.jetbrains.annotations.NotNull public abstract net.corda.core.cordapp.CordappProvider getCordappProvider() @org.jetbrains.annotations.NotNull public abstract net.corda.core.node.services.IdentityService getIdentityService() @org.jetbrains.annotations.NotNull public abstract net.corda.core.node.NetworkParameters getNetworkParameters() + @org.jetbrains.annotations.NotNull public abstract net.corda.core.contracts.TransactionState loadState(net.corda.core.contracts.StateRef) + @org.jetbrains.annotations.NotNull public abstract Set loadStates(Set) ## public final class net.corda.core.node.StatesToRecord extends java.lang.Enum protected (String, int) @@ -2935,6 +2981,72 @@ public static final class net.corda.core.serialization.SingletonSerializationTok @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash getId() @org.jetbrains.annotations.NotNull public final String getReason() ## +@net.corda.core.serialization.CordaSerializable @net.corda.core.DoNotImplement public final class net.corda.core.transactions.ContractUpgradeFilteredTransaction extends net.corda.core.transactions.CoreTransaction + public (List, net.corda.core.identity.Party, net.corda.core.crypto.SecureHash) + @org.jetbrains.annotations.NotNull public final List component1() + @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party component2() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash component3() + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.ContractUpgradeFilteredTransaction copy(List, net.corda.core.identity.Party, net.corda.core.crypto.SecureHash) + public boolean equals(Object) + @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash getId() + @org.jetbrains.annotations.NotNull public List getInputs() + @org.jetbrains.annotations.NotNull public net.corda.core.identity.Party getNotary() + @org.jetbrains.annotations.NotNull public List getOutputs() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash getRest() + public int hashCode() + public String toString() +## +@net.corda.core.DoNotImplement public final class net.corda.core.transactions.ContractUpgradeLedgerTransaction extends net.corda.core.transactions.FullTransaction implements net.corda.core.transactions.TransactionWithSignatures + public (List, net.corda.core.identity.Party, net.corda.core.contracts.ContractAttachment, net.corda.core.contracts.ContractAttachment, net.corda.core.crypto.SecureHash, net.corda.core.contracts.PrivacySalt, List, net.corda.core.node.NetworkParameters) + public void checkSignaturesAreValid() + @org.jetbrains.annotations.NotNull public final List component1() + @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party component2() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.ContractAttachment component3() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.ContractAttachment component4() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash component5() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.PrivacySalt component6() + @org.jetbrains.annotations.NotNull public final List component7() + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.ContractUpgradeLedgerTransaction copy(List, net.corda.core.identity.Party, net.corda.core.contracts.ContractAttachment, net.corda.core.contracts.ContractAttachment, net.corda.core.crypto.SecureHash, net.corda.core.contracts.PrivacySalt, List, net.corda.core.node.NetworkParameters) + public boolean equals(Object) + @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash getId() + @org.jetbrains.annotations.NotNull public List getInputs() + @org.jetbrains.annotations.NotNull public List getKeyDescriptions(Set) + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.ContractAttachment getLegacyContractAttachment() + @org.jetbrains.annotations.NotNull public Set getMissingSigners() + @org.jetbrains.annotations.NotNull public net.corda.core.identity.Party getNotary() + @org.jetbrains.annotations.NotNull public List getOutputs() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.PrivacySalt getPrivacySalt() + @org.jetbrains.annotations.NotNull public Set getRequiredSigningKeys() + @org.jetbrains.annotations.NotNull public List getSigs() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.ContractAttachment getUpgradedContractAttachment() + public int hashCode() + public String toString() + public void verifyRequiredSignatures() + public void verifySignaturesExcept(Collection) +## +@net.corda.core.serialization.CordaSerializable @net.corda.core.DoNotImplement public final class net.corda.core.transactions.ContractUpgradeWireTransaction extends net.corda.core.transactions.CoreTransaction + public (List, net.corda.core.identity.Party, net.corda.core.crypto.SecureHash, String, net.corda.core.crypto.SecureHash, net.corda.core.contracts.PrivacySalt) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.ContractUpgradeFilteredTransaction buildFilteredTransaction() + @org.jetbrains.annotations.NotNull public final List component1() + @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party component2() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash component3() + @org.jetbrains.annotations.NotNull public final String component4() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash component5() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.PrivacySalt component6() + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.ContractUpgradeWireTransaction copy(List, net.corda.core.identity.Party, net.corda.core.crypto.SecureHash, String, net.corda.core.crypto.SecureHash, net.corda.core.contracts.PrivacySalt) + public boolean equals(Object) + @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash getId() + @org.jetbrains.annotations.NotNull public List getInputs() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash getLegacyContractAttachmentId() + @org.jetbrains.annotations.NotNull public net.corda.core.identity.Party getNotary() + @org.jetbrains.annotations.NotNull public List getOutputs() + @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.PrivacySalt getPrivacySalt() + @org.jetbrains.annotations.NotNull public final String getUpgradeContractClassName() + @org.jetbrains.annotations.NotNull public final net.corda.core.crypto.SecureHash getUpgradedContractAttachmentId() + public int hashCode() + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.ContractUpgradeLedgerTransaction resolve(net.corda.core.node.ServicesForResolution, List) + public String toString() +## @net.corda.core.serialization.CordaSerializable @net.corda.core.DoNotImplement public abstract class net.corda.core.transactions.CoreTransaction extends net.corda.core.transactions.BaseTransaction public () @org.jetbrains.annotations.NotNull public abstract List getInputs() @@ -2981,6 +3093,7 @@ public static final class net.corda.core.transactions.FilteredTransaction$Compan ## @net.corda.core.serialization.CordaSerializable @net.corda.core.DoNotImplement public final class net.corda.core.transactions.LedgerTransaction extends net.corda.core.transactions.FullTransaction public (List, List, List, List, net.corda.core.crypto.SecureHash, net.corda.core.identity.Party, net.corda.core.contracts.TimeWindow, net.corda.core.contracts.PrivacySalt) + public (List, List, List, List, net.corda.core.crypto.SecureHash, net.corda.core.identity.Party, net.corda.core.contracts.TimeWindow, net.corda.core.contracts.PrivacySalt, net.corda.core.node.NetworkParameters) @org.jetbrains.annotations.NotNull public final List commandsOfType(Class) @org.jetbrains.annotations.NotNull public final List component1() @org.jetbrains.annotations.NotNull public final List component2() @@ -2991,6 +3104,7 @@ public static final class net.corda.core.transactions.FilteredTransaction$Compan @org.jetbrains.annotations.Nullable public final net.corda.core.contracts.TimeWindow component7() @org.jetbrains.annotations.NotNull public final net.corda.core.contracts.PrivacySalt component8() @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.LedgerTransaction copy(List, List, List, List, net.corda.core.crypto.SecureHash, net.corda.core.identity.Party, net.corda.core.contracts.TimeWindow, net.corda.core.contracts.PrivacySalt) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.LedgerTransaction copy(List, List, List, List, net.corda.core.crypto.SecureHash, net.corda.core.identity.Party, net.corda.core.contracts.TimeWindow, net.corda.core.contracts.PrivacySalt, net.corda.core.node.NetworkParameters) public boolean equals(Object) @org.jetbrains.annotations.NotNull public final List filterCommands(Class, function.Predicate) @org.jetbrains.annotations.NotNull public final List filterInRefs(Class, function.Predicate) @@ -3075,6 +3189,7 @@ public static final class net.corda.core.transactions.LedgerTransaction$InOutGro @org.jetbrains.annotations.NotNull public List getOutputs() public int hashCode() @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.NotaryChangeLedgerTransaction resolve(net.corda.core.node.ServiceHub, List) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.NotaryChangeLedgerTransaction resolve(net.corda.core.node.ServicesForResolution, List) public String toString() ## @net.corda.core.serialization.CordaSerializable @net.corda.core.DoNotImplement public final class net.corda.core.transactions.SignedTransaction extends java.lang.Object implements net.corda.core.transactions.TransactionWithSignatures @@ -3086,6 +3201,7 @@ public static final class net.corda.core.transactions.LedgerTransaction$InOutGro @org.jetbrains.annotations.NotNull public final List component2() @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.SignedTransaction copy(net.corda.core.serialization.SerializedBytes, List) public boolean equals(Object) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.CoreTransaction getCoreTransaction() @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash getId() @org.jetbrains.annotations.NotNull public final List getInputs() @org.jetbrains.annotations.NotNull public ArrayList getKeyDescriptions(Set) @@ -3100,7 +3216,10 @@ public static final class net.corda.core.transactions.LedgerTransaction$InOutGro @kotlin.Deprecated public final boolean isNotaryChangeTransaction() @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.SignedTransaction plus(Collection) @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.SignedTransaction plus(net.corda.core.crypto.TransactionSignature) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.BaseTransaction resolveBaseTransaction(net.corda.core.node.ServicesForResolution) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.ContractUpgradeLedgerTransaction resolveContractUpgradeTransaction(net.corda.core.node.ServicesForResolution) @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.NotaryChangeLedgerTransaction resolveNotaryChangeTransaction(net.corda.core.node.ServiceHub) + @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.NotaryChangeLedgerTransaction resolveNotaryChangeTransaction(net.corda.core.node.ServicesForResolution) @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.TransactionWithSignatures resolveTransactionWithSignatures(net.corda.core.node.ServicesForResolution) @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.LedgerTransaction toLedgerTransaction(net.corda.core.node.ServiceHub) @org.jetbrains.annotations.NotNull public final net.corda.core.transactions.LedgerTransaction toLedgerTransaction(net.corda.core.node.ServiceHub, boolean) @@ -3660,7 +3779,7 @@ public final class net.corda.testing.driver.Driver extends java.lang.Object @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture getDefaultNotaryNode() @org.jetbrains.annotations.NotNull public abstract List getNotaryHandles() @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture startNode(net.corda.testing.driver.NodeParameters) - @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture startNode(net.corda.testing.driver.NodeParameters, net.corda.core.identity.CordaX500Name, List, net.corda.node.services.config.VerifierType, Map, Boolean, String) + @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture startNode(net.corda.testing.driver.NodeParameters, net.corda.core.identity.CordaX500Name, List, net.corda.testing.driver.VerifierType, Map, Boolean, String) @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture startWebserver(net.corda.testing.driver.NodeHandle) @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture startWebserver(net.corda.testing.driver.NodeHandle, String) ## @@ -3709,8 +3828,9 @@ public final class net.corda.testing.driver.DriverParameters extends java.lang.O @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.DriverParameters withWaitForAllNodesToFinish(boolean) ## @net.corda.core.DoNotImplement public interface net.corda.testing.driver.InProcess extends net.corda.testing.driver.NodeHandle - @org.jetbrains.annotations.NotNull public abstract net.corda.node.services.api.StartedNodeServices getServices() + @org.jetbrains.annotations.NotNull public abstract net.corda.core.node.ServiceHub getServices() @org.jetbrains.annotations.NotNull public abstract rx.Observable registerInitiatedFlow(Class) + @org.jetbrains.annotations.NotNull public abstract net.corda.core.concurrent.CordaFuture startFlow(net.corda.core.flows.FlowLogic) ## public final class net.corda.testing.driver.JmxPolicy extends java.lang.Object public () @@ -3735,29 +3855,29 @@ public final class net.corda.testing.driver.JmxPolicy extends java.lang.Object ## public final class net.corda.testing.driver.NodeParameters extends java.lang.Object public () - public (net.corda.core.identity.CordaX500Name, List, net.corda.node.services.config.VerifierType, Map, Boolean, String) + public (net.corda.core.identity.CordaX500Name, List, net.corda.testing.driver.VerifierType, Map, Boolean, String) @org.jetbrains.annotations.Nullable public final net.corda.core.identity.CordaX500Name component1() @org.jetbrains.annotations.NotNull public final List component2() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.config.VerifierType component3() + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.VerifierType component3() @org.jetbrains.annotations.NotNull public final Map component4() @org.jetbrains.annotations.Nullable public final Boolean component5() @org.jetbrains.annotations.NotNull public final String component6() - @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters copy(net.corda.core.identity.CordaX500Name, List, net.corda.node.services.config.VerifierType, Map, Boolean, String) + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters copy(net.corda.core.identity.CordaX500Name, List, net.corda.testing.driver.VerifierType, Map, Boolean, String) public boolean equals(Object) @org.jetbrains.annotations.NotNull public final Map getCustomOverrides() @org.jetbrains.annotations.NotNull public final String getMaximumHeapSize() @org.jetbrains.annotations.Nullable public final net.corda.core.identity.CordaX500Name getProvidedName() @org.jetbrains.annotations.NotNull public final List getRpcUsers() @org.jetbrains.annotations.Nullable public final Boolean getStartInSameProcess() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.config.VerifierType getVerifierType() + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.VerifierType getVerifierType() public int hashCode() public String toString() - @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withCustomerOverrides(Map) + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withCustomOverrides(Map) @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withMaximumHeapSize(String) @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withProvidedName(net.corda.core.identity.CordaX500Name) @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withRpcUsers(List) @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withStartInSameProcess(Boolean) - @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withVerifierType(net.corda.node.services.config.VerifierType) + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.NodeParameters withVerifierType(net.corda.testing.driver.VerifierType) ## public final class net.corda.testing.driver.NotaryHandle extends java.lang.Object public (net.corda.core.identity.Party, boolean, net.corda.core.concurrent.CordaFuture) @@ -3776,6 +3896,7 @@ public final class net.corda.testing.driver.NotaryHandle extends java.lang.Objec @org.jetbrains.annotations.NotNull public abstract Process getProcess() ## @net.corda.core.DoNotImplement public abstract class net.corda.testing.driver.PortAllocation extends java.lang.Object + public () @org.jetbrains.annotations.NotNull public final net.corda.core.utilities.NetworkHostAndPort nextHostAndPort() public abstract int nextPort() ## @@ -3784,9 +3905,10 @@ public static final class net.corda.testing.driver.PortAllocation$Incremental ex @org.jetbrains.annotations.NotNull public final concurrent.atomic.AtomicInteger getPortCounter() public int nextPort() ## -public static final class net.corda.testing.driver.PortAllocation$RandomFree extends net.corda.testing.driver.PortAllocation - public int nextPort() - public static final net.corda.testing.driver.PortAllocation$RandomFree INSTANCE +public final class net.corda.testing.driver.VerifierType extends java.lang.Enum + protected (String, int) + public static net.corda.testing.driver.VerifierType valueOf(String) + public static net.corda.testing.driver.VerifierType[] values() ## public final class net.corda.testing.driver.WebserverHandle extends java.lang.Object public (net.corda.core.utilities.NetworkHostAndPort, Process) @@ -3813,7 +3935,7 @@ public static final class net.corda.testing.node.ClusterSpec$Raft extends net.co public String toString() ## @javax.annotation.concurrent.ThreadSafe public final class net.corda.testing.node.InMemoryMessagingNetwork extends net.corda.core.serialization.SingletonSerializeAsToken - @org.jetbrains.annotations.NotNull public synchronized final List getEndpoints() + @org.jetbrains.annotations.NotNull public synchronized final List getEndpointsExternal() @org.jetbrains.annotations.NotNull public final rx.Observable getReceivedMessages() @org.jetbrains.annotations.NotNull public final rx.Observable getSentMessages() @org.jetbrains.annotations.Nullable public final net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer pumpSend(boolean) @@ -3822,41 +3944,32 @@ public static final class net.corda.testing.node.ClusterSpec$Raft extends net.co ## public static final class net.corda.testing.node.InMemoryMessagingNetwork$Companion extends java.lang.Object ## -public static final class net.corda.testing.node.InMemoryMessagingNetwork$InMemoryMessage extends java.lang.Object implements net.corda.node.services.messaging.Message - public (String, net.corda.core.utilities.ByteSequence, String, java.time.Instant) - @org.jetbrains.annotations.NotNull public final String component1() - @org.jetbrains.annotations.NotNull public final net.corda.core.utilities.ByteSequence component2() - @org.jetbrains.annotations.NotNull public final String component3() - @org.jetbrains.annotations.NotNull public final java.time.Instant component4() - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$InMemoryMessage copy(String, net.corda.core.utilities.ByteSequence, String, java.time.Instant) +@net.corda.core.serialization.CordaSerializable public static final class net.corda.testing.node.InMemoryMessagingNetwork$DistributedServiceHandle extends java.lang.Object implements net.corda.core.messaging.MessageRecipientGroup + public (net.corda.core.identity.Party) + @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party component1() + @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$DistributedServiceHandle copy(net.corda.core.identity.Party) public boolean equals(Object) - @org.jetbrains.annotations.NotNull public net.corda.core.utilities.ByteSequence getData() - @org.jetbrains.annotations.NotNull public java.time.Instant getDebugTimestamp() - @org.jetbrains.annotations.NotNull public String getTopic() - @org.jetbrains.annotations.NotNull public String getUniqueMessageId() + @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party getParty() public int hashCode() @org.jetbrains.annotations.NotNull public String toString() ## -public final class net.corda.testing.node.InMemoryMessagingNetwork$InMemoryMessaging$Handler extends java.lang.Object implements net.corda.node.services.messaging.MessageHandlerRegistration - public (net.corda.testing.node.InMemoryMessagingNetwork$InMemoryMessaging, String, kotlin.jvm.functions.Function2) - @org.jetbrains.annotations.NotNull public final kotlin.jvm.functions.Function2 getCallback() - @org.jetbrains.annotations.NotNull public final String getTopicSession() -## public static interface net.corda.testing.node.InMemoryMessagingNetwork$LatencyCalculator @org.jetbrains.annotations.NotNull public abstract java.time.Duration between(net.corda.core.messaging.SingleMessageRecipient, net.corda.core.messaging.SingleMessageRecipient) ## @net.corda.core.serialization.CordaSerializable public static final class net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer extends java.lang.Object - public (net.corda.testing.node.InMemoryMessagingNetwork$PeerHandle, net.corda.node.services.messaging.Message, net.corda.core.messaging.MessageRecipients) - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$PeerHandle component1() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.messaging.Message component2() - @org.jetbrains.annotations.NotNull public final net.corda.core.messaging.MessageRecipients component3() - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer copy(net.corda.testing.node.InMemoryMessagingNetwork$PeerHandle, net.corda.node.services.messaging.Message, net.corda.core.messaging.MessageRecipients) - public boolean equals(Object) - @org.jetbrains.annotations.NotNull public final net.corda.node.services.messaging.Message getMessage() + @org.jetbrains.annotations.NotNull public final net.corda.core.utilities.ByteSequence getMessageData() @org.jetbrains.annotations.NotNull public final net.corda.core.messaging.MessageRecipients getRecipients() @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$PeerHandle getSender() - public int hashCode() @org.jetbrains.annotations.NotNull public String toString() + public static final net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer$Companion Companion +## +public static final class net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer$Companion extends java.lang.Object +## +public static final class net.corda.testing.node.InMemoryMessagingNetwork$MockMessagingService extends java.lang.Object + @org.jetbrains.annotations.Nullable public final net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer pumpReceive(boolean) + public static final net.corda.testing.node.InMemoryMessagingNetwork$MockMessagingService$Companion Companion +## +public static final class net.corda.testing.node.InMemoryMessagingNetwork$MockMessagingService$Companion extends java.lang.Object ## @net.corda.core.serialization.CordaSerializable public static final class net.corda.testing.node.InMemoryMessagingNetwork$PeerHandle extends java.lang.Object implements net.corda.core.messaging.SingleMessageRecipient public (int, net.corda.core.identity.CordaX500Name) @@ -3864,57 +3977,23 @@ public static interface net.corda.testing.node.InMemoryMessagingNetwork$LatencyC @org.jetbrains.annotations.NotNull public final net.corda.core.identity.CordaX500Name component2() @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$PeerHandle copy(int, net.corda.core.identity.CordaX500Name) public boolean equals(Object) - @org.jetbrains.annotations.NotNull public final net.corda.core.identity.CordaX500Name getDescription() public final int getId() - public int hashCode() - @org.jetbrains.annotations.NotNull public String toString() -## -@net.corda.core.serialization.CordaSerializable public static final class net.corda.testing.node.InMemoryMessagingNetwork$ServiceHandle extends java.lang.Object implements net.corda.core.messaging.MessageRecipientGroup - public (net.corda.core.identity.Party) - @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party component1() - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$ServiceHandle copy(net.corda.core.identity.Party) - public boolean equals(Object) - @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party getParty() + @org.jetbrains.annotations.NotNull public final net.corda.core.identity.CordaX500Name getName() public int hashCode() @org.jetbrains.annotations.NotNull public String toString() ## @net.corda.core.DoNotImplement public abstract static class net.corda.testing.node.InMemoryMessagingNetwork$ServicePeerAllocationStrategy extends java.lang.Object - public abstract Object pickNext(net.corda.testing.node.InMemoryMessagingNetwork$ServiceHandle, List) + public abstract Object pickNext(net.corda.testing.node.InMemoryMessagingNetwork$DistributedServiceHandle, List) ## public static final class net.corda.testing.node.InMemoryMessagingNetwork$ServicePeerAllocationStrategy$Random extends net.corda.testing.node.InMemoryMessagingNetwork$ServicePeerAllocationStrategy public () public (SplittableRandom) @org.jetbrains.annotations.NotNull public final SplittableRandom getRandom() - public Object pickNext(net.corda.testing.node.InMemoryMessagingNetwork$ServiceHandle, List) + public Object pickNext(net.corda.testing.node.InMemoryMessagingNetwork$DistributedServiceHandle, List) ## public static final class net.corda.testing.node.InMemoryMessagingNetwork$ServicePeerAllocationStrategy$RoundRobin extends net.corda.testing.node.InMemoryMessagingNetwork$ServicePeerAllocationStrategy public () - public Object pickNext(net.corda.testing.node.InMemoryMessagingNetwork$ServiceHandle, List) -## -@net.corda.core.DoNotImplement public static interface net.corda.testing.node.InMemoryMessagingNetwork$TestMessagingService extends net.corda.node.services.messaging.MessagingService - @org.jetbrains.annotations.Nullable public abstract net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer pumpReceive(boolean) - public abstract void stop() -## -public class net.corda.testing.node.MessagingServiceSpy extends java.lang.Object implements net.corda.node.services.messaging.MessagingService - public (net.corda.node.services.messaging.MessagingService) - @org.jetbrains.annotations.NotNull public net.corda.node.services.messaging.MessageHandlerRegistration addMessageHandler(String, kotlin.jvm.functions.Function2) - public void cancelRedelivery(long) - @org.jetbrains.annotations.NotNull public net.corda.node.services.messaging.Message createMessage(String, byte[], String) - @org.jetbrains.annotations.NotNull public net.corda.core.messaging.MessageRecipients getAddressOfParty(net.corda.core.node.services.PartyInfo) - @org.jetbrains.annotations.NotNull public final net.corda.node.services.messaging.MessagingService getMessagingService() - @org.jetbrains.annotations.NotNull public net.corda.core.messaging.SingleMessageRecipient getMyAddress() - public void removeMessageHandler(net.corda.node.services.messaging.MessageHandlerRegistration) - @co.paralleluniverse.fibers.Suspendable public void send(List) - @co.paralleluniverse.fibers.Suspendable public void send(net.corda.node.services.messaging.Message, net.corda.core.messaging.MessageRecipients, Long, Object, Map) -## -public final class net.corda.testing.node.MockKeyManagementService extends net.corda.core.serialization.SingletonSerializeAsToken implements net.corda.core.node.services.KeyManagementService - @org.jetbrains.annotations.NotNull public Iterable filterMyKeys(Iterable) - @org.jetbrains.annotations.NotNull public java.security.PublicKey freshKey() - @org.jetbrains.annotations.NotNull public net.corda.core.identity.PartyAndCertificate freshKeyAndCert(net.corda.core.identity.PartyAndCertificate, boolean) - @org.jetbrains.annotations.NotNull public final net.corda.core.node.services.IdentityService getIdentityService() - @org.jetbrains.annotations.NotNull public Set getKeys() - @org.jetbrains.annotations.NotNull public net.corda.core.crypto.TransactionSignature sign(net.corda.core.crypto.SignableData, java.security.PublicKey) - @org.jetbrains.annotations.NotNull public net.corda.core.crypto.DigitalSignature$WithKey sign(byte[], java.security.PublicKey) + public Object pickNext(net.corda.testing.node.InMemoryMessagingNetwork$DistributedServiceHandle, List) ## public class net.corda.testing.node.MockNetwork extends java.lang.Object public (List) @@ -3926,7 +4005,6 @@ public class net.corda.testing.node.MockNetwork extends java.lang.Object @org.jetbrains.annotations.NotNull public final net.corda.testing.node.StartedMockNode createNode(net.corda.core.identity.CordaX500Name, Integer) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.StartedMockNode createNode(net.corda.core.identity.CordaX500Name, Integer, java.math.BigInteger) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.StartedMockNode createNode(net.corda.core.identity.CordaX500Name, Integer, java.math.BigInteger, kotlin.jvm.functions.Function1) - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.StartedMockNode createNode(net.corda.core.identity.CordaX500Name, Integer, java.math.BigInteger, kotlin.jvm.functions.Function1, net.corda.node.VersionInfo) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.StartedMockNode createNode(net.corda.testing.node.MockNodeParameters) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.StartedMockNode createPartyNode(net.corda.core.identity.CordaX500Name) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.UnstartedMockNode createUnstartedNode() @@ -3934,7 +4012,6 @@ public class net.corda.testing.node.MockNetwork extends java.lang.Object @org.jetbrains.annotations.NotNull public final net.corda.testing.node.UnstartedMockNode createUnstartedNode(net.corda.core.identity.CordaX500Name, Integer) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.UnstartedMockNode createUnstartedNode(net.corda.core.identity.CordaX500Name, Integer, java.math.BigInteger) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.UnstartedMockNode createUnstartedNode(net.corda.core.identity.CordaX500Name, Integer, java.math.BigInteger, kotlin.jvm.functions.Function1) - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.UnstartedMockNode createUnstartedNode(net.corda.core.identity.CordaX500Name, Integer, java.math.BigInteger, kotlin.jvm.functions.Function1, net.corda.node.VersionInfo) @org.jetbrains.annotations.NotNull public final net.corda.testing.node.UnstartedMockNode createUnstartedNode(net.corda.testing.node.MockNodeParameters) @org.jetbrains.annotations.NotNull public final List getCordappPackages() @org.jetbrains.annotations.NotNull public final net.corda.core.identity.Party getDefaultNotaryIdentity() @@ -3990,19 +4067,17 @@ public final class net.corda.testing.node.MockNetworkParameters extends java.lan ## public final class net.corda.testing.node.MockNodeParameters extends java.lang.Object public () - public (Integer, net.corda.core.identity.CordaX500Name, java.math.BigInteger, kotlin.jvm.functions.Function1, net.corda.node.VersionInfo) + public (Integer, net.corda.core.identity.CordaX500Name, java.math.BigInteger, kotlin.jvm.functions.Function1) @org.jetbrains.annotations.Nullable public final Integer component1() @org.jetbrains.annotations.Nullable public final net.corda.core.identity.CordaX500Name component2() @org.jetbrains.annotations.NotNull public final java.math.BigInteger component3() @org.jetbrains.annotations.NotNull public final kotlin.jvm.functions.Function1 component4() - @org.jetbrains.annotations.NotNull public final net.corda.node.VersionInfo component5() - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.MockNodeParameters copy(Integer, net.corda.core.identity.CordaX500Name, java.math.BigInteger, kotlin.jvm.functions.Function1, net.corda.node.VersionInfo) + @org.jetbrains.annotations.NotNull public final net.corda.testing.node.MockNodeParameters copy(Integer, net.corda.core.identity.CordaX500Name, java.math.BigInteger, kotlin.jvm.functions.Function1) public boolean equals(Object) @org.jetbrains.annotations.NotNull public final kotlin.jvm.functions.Function1 getConfigOverrides() @org.jetbrains.annotations.NotNull public final java.math.BigInteger getEntropyRoot() @org.jetbrains.annotations.Nullable public final Integer getForcedID() @org.jetbrains.annotations.Nullable public final net.corda.core.identity.CordaX500Name getLegalName() - @org.jetbrains.annotations.NotNull public final net.corda.node.VersionInfo getVersion() public int hashCode() public String toString() @org.jetbrains.annotations.NotNull public final net.corda.testing.node.MockNodeParameters withConfigOverrides(kotlin.jvm.functions.Function1) @@ -4029,15 +4104,14 @@ public class net.corda.testing.node.MockServices extends java.lang.Object implem @org.jetbrains.annotations.NotNull public java.time.Clock getClock() @org.jetbrains.annotations.NotNull public net.corda.core.node.services.ContractUpgradeService getContractUpgradeService() @org.jetbrains.annotations.NotNull public net.corda.core.cordapp.CordappProvider getCordappProvider() - @org.jetbrains.annotations.NotNull public final com.google.common.collect.MutableClassToInstanceMap getCordappServices() @org.jetbrains.annotations.NotNull public net.corda.core.node.services.IdentityService getIdentityService() @org.jetbrains.annotations.NotNull public net.corda.core.node.services.KeyManagementService getKeyManagementService() - @org.jetbrains.annotations.NotNull public static final net.corda.node.VersionInfo getMOCK_VERSION_INFO() @org.jetbrains.annotations.NotNull public net.corda.core.node.NodeInfo getMyInfo() @org.jetbrains.annotations.NotNull public net.corda.core.node.services.NetworkMapCache getNetworkMapCache() @org.jetbrains.annotations.NotNull public net.corda.core.node.NetworkParameters getNetworkParameters() + @org.jetbrains.annotations.NotNull protected final net.corda.core.node.ServicesForResolution getServicesForResolution() @org.jetbrains.annotations.NotNull public net.corda.core.node.services.TransactionVerifierService getTransactionVerifierService() - @org.jetbrains.annotations.NotNull public net.corda.node.services.api.WritableTransactionStorage getValidatedTransactions() + @org.jetbrains.annotations.NotNull public net.corda.core.node.services.TransactionStorage getValidatedTransactions() @org.jetbrains.annotations.NotNull public net.corda.core.node.services.VaultService getVaultService() @org.jetbrains.annotations.NotNull public java.sql.Connection jdbcSession() @org.jetbrains.annotations.NotNull public net.corda.core.contracts.TransactionState loadState(net.corda.core.contracts.StateRef) @@ -4054,11 +4128,10 @@ public class net.corda.testing.node.MockServices extends java.lang.Object implem public static final net.corda.testing.node.MockServices$Companion Companion ## public static final class net.corda.testing.node.MockServices$Companion extends java.lang.Object - @org.jetbrains.annotations.NotNull public final net.corda.node.VersionInfo getMOCK_VERSION_INFO() @kotlin.jvm.JvmStatic @org.jetbrains.annotations.NotNull public final Properties makeTestDataSourceProperties(String) ## public static final class net.corda.testing.node.MockServices$Companion$makeTestDatabaseAndMockServices$mockService$1$1 extends net.corda.testing.node.MockServices - @org.jetbrains.annotations.NotNull public net.corda.node.services.api.VaultServiceInternal getVaultService() + @org.jetbrains.annotations.NotNull public net.corda.core.node.services.VaultService getVaultService() @org.jetbrains.annotations.NotNull public java.sql.Connection jdbcSession() public void recordTransactions(net.corda.core.node.StatesToRecord, Iterable) ## @@ -4102,37 +4175,28 @@ public static final class net.corda.testing.node.MockServicesKt$createMockCordaS @org.jetbrains.annotations.NotNull public net.corda.core.messaging.FlowProgressHandle startTrackedFlow(net.corda.core.flows.FlowLogic) @org.jetbrains.annotations.NotNull public net.corda.core.contracts.StateAndRef toStateAndRef(net.corda.core.contracts.StateRef) ## -public class net.corda.testing.node.MockTransactionStorage extends net.corda.core.serialization.SingletonSerializeAsToken implements net.corda.node.services.api.WritableTransactionStorage - public () - public boolean addTransaction(net.corda.core.transactions.SignedTransaction) - @org.jetbrains.annotations.Nullable public net.corda.core.transactions.SignedTransaction getTransaction(net.corda.core.crypto.SecureHash) - @org.jetbrains.annotations.NotNull public rx.Observable getUpdates() - @org.jetbrains.annotations.NotNull public net.corda.core.messaging.DataFeed track() -## public final class net.corda.testing.node.NodeTestUtils extends java.lang.Object @org.jetbrains.annotations.NotNull public static final net.corda.testing.dsl.LedgerDSL ledger(net.corda.core.node.ServiceHub, kotlin.jvm.functions.Function1) @org.jetbrains.annotations.NotNull public static final net.corda.testing.dsl.LedgerDSL ledger(net.corda.core.node.ServiceHub, net.corda.core.identity.Party, kotlin.jvm.functions.Function1) - @org.jetbrains.annotations.NotNull public static final net.corda.core.context.InvocationContext newContext(net.corda.node.services.api.StartedNodeServices) - @org.jetbrains.annotations.NotNull public static final net.corda.core.concurrent.CordaFuture startFlow(net.corda.node.services.api.StartedNodeServices, net.corda.core.flows.FlowLogic) @org.jetbrains.annotations.NotNull public static final net.corda.core.context.Actor testActor(net.corda.core.identity.CordaX500Name) @org.jetbrains.annotations.NotNull public static final net.corda.core.context.InvocationContext testContext(net.corda.core.identity.CordaX500Name) @org.jetbrains.annotations.NotNull public static final net.corda.testing.dsl.LedgerDSL transaction(net.corda.core.node.ServiceHub, kotlin.jvm.functions.Function1) @org.jetbrains.annotations.NotNull public static final net.corda.testing.dsl.LedgerDSL transaction(net.corda.core.node.ServiceHub, net.corda.core.identity.Party, kotlin.jvm.functions.Function1) ## public final class net.corda.testing.node.NotarySpec extends java.lang.Object - public (net.corda.core.identity.CordaX500Name, boolean, List, net.corda.node.services.config.VerifierType, net.corda.testing.node.ClusterSpec) + public (net.corda.core.identity.CordaX500Name, boolean, List, net.corda.testing.driver.VerifierType, net.corda.testing.node.ClusterSpec) @org.jetbrains.annotations.NotNull public final net.corda.core.identity.CordaX500Name component1() public final boolean component2() @org.jetbrains.annotations.NotNull public final List component3() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.config.VerifierType component4() + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.VerifierType component4() @org.jetbrains.annotations.Nullable public final net.corda.testing.node.ClusterSpec component5() - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.NotarySpec copy(net.corda.core.identity.CordaX500Name, boolean, List, net.corda.node.services.config.VerifierType, net.corda.testing.node.ClusterSpec) + @org.jetbrains.annotations.NotNull public final net.corda.testing.node.NotarySpec copy(net.corda.core.identity.CordaX500Name, boolean, List, net.corda.testing.driver.VerifierType, net.corda.testing.node.ClusterSpec) public boolean equals(Object) @org.jetbrains.annotations.Nullable public final net.corda.testing.node.ClusterSpec getCluster() @org.jetbrains.annotations.NotNull public final net.corda.core.identity.CordaX500Name getName() @org.jetbrains.annotations.NotNull public final List getRpcUsers() public final boolean getValidating() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.config.VerifierType getVerifierType() + @org.jetbrains.annotations.NotNull public final net.corda.testing.driver.VerifierType getVerifierType() public int hashCode() public String toString() ## @@ -4140,11 +4204,10 @@ public final class net.corda.testing.node.StartedMockNode extends java.lang.Obje @org.jetbrains.annotations.NotNull public final List findStateMachines(Class) public final int getId() @org.jetbrains.annotations.NotNull public final net.corda.core.node.NodeInfo getInfo() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.messaging.MessagingService getNetwork() - @org.jetbrains.annotations.NotNull public final net.corda.node.services.api.StartedNodeServices getServices() + @org.jetbrains.annotations.NotNull public final net.corda.core.node.ServiceHub getServices() @org.jetbrains.annotations.Nullable public final net.corda.testing.node.InMemoryMessagingNetwork$MessageTransfer pumpReceive(boolean) @org.jetbrains.annotations.NotNull public final rx.Observable registerInitiatedFlow(Class) - public final void setMessagingServiceSpy(net.corda.testing.node.MessagingServiceSpy) + @org.jetbrains.annotations.NotNull public final net.corda.core.concurrent.CordaFuture startFlow(net.corda.core.flows.FlowLogic) public final void stop() public final Object transaction(kotlin.jvm.functions.Function0) public static final net.corda.testing.node.StartedMockNode$Companion Companion @@ -4394,9 +4457,6 @@ public final class net.corda.testing.core.ExpectKt extends java.lang.Object ## public static final class net.corda.testing.core.ExpectKt$expectEvents$1$lock$1 extends java.lang.Object ## -@net.corda.core.DoNotImplement public interface net.corda.testing.core.GlobalSerializationEnvironment extends net.corda.core.serialization.internal.SerializationEnvironment - public abstract void unset() -## public final class net.corda.testing.core.SerializationEnvironmentRule extends java.lang.Object implements org.junit.rules.TestRule public () public (boolean) @@ -4421,7 +4481,6 @@ public final class net.corda.testing.core.TestConstants extends java.lang.Object @kotlin.jvm.JvmField @org.jetbrains.annotations.NotNull public static final net.corda.core.identity.CordaX500Name DUMMY_BANK_C_NAME @kotlin.jvm.JvmField @org.jetbrains.annotations.NotNull public static final net.corda.core.identity.CordaX500Name DUMMY_NOTARY_NAME public static final int MAX_MESSAGE_SIZE = 10485760 - @kotlin.jvm.JvmField public static final java.time.Instant TEST_TX_TIME ## public final class net.corda.testing.core.TestIdentity extends java.lang.Object public (net.corda.core.identity.CordaX500Name) @@ -4438,8 +4497,6 @@ public static final class net.corda.testing.core.TestIdentity$Companion extends @org.jetbrains.annotations.NotNull public final net.corda.testing.core.TestIdentity fresh(String) ## public final class net.corda.testing.core.TestUtils extends java.lang.Object - @org.jetbrains.annotations.NotNull public static final net.corda.core.identity.Party chooseIdentity(net.corda.core.node.NodeInfo) - @org.jetbrains.annotations.NotNull public static final net.corda.core.identity.PartyAndCertificate chooseIdentityAndCert(net.corda.core.node.NodeInfo) @org.jetbrains.annotations.NotNull public static final net.corda.core.utilities.NetworkHostAndPort freeLocalHostAndPort() public static final int freePort() @org.jetbrains.annotations.NotNull public static final net.corda.core.contracts.StateRef generateStateRef() @@ -4634,23 +4691,10 @@ public final class net.corda.testing.http.HttpUtils extends java.lang.Object public final void putJson(java.net.URL, String) public static final net.corda.testing.http.HttpUtils INSTANCE ## -public final class net.corda.testing.services.FlowStackSnapshotFactoryImpl extends java.lang.Object implements net.corda.node.services.statemachine.FlowStackSnapshotFactory - public () - @co.paralleluniverse.fibers.Suspendable @org.jetbrains.annotations.NotNull public net.corda.core.flows.FlowStackSnapshot getFlowStackSnapshot(Class) - public void persistAsJsonFile(Class, java.nio.file.Path, net.corda.core.flows.StateMachineRunId) -## -public static final class net.corda.testing.services.FlowStackSnapshotFactoryImpl$ThreadLocalIndex$Companion extends java.lang.Object - @org.jetbrains.annotations.NotNull public final ThreadLocal getCurrentIndex() -## -public static final class net.corda.testing.services.FlowStackSnapshotFactoryImpl$ThreadLocalIndex$Companion$currentIndex$1 extends java.lang.ThreadLocal - @org.jetbrains.annotations.NotNull protected Integer initialValue() -## -public final class net.corda.testing.services.FlowStackSnapshotKt extends java.lang.Object -## public final class net.corda.testing.services.MockAttachmentStorage extends net.corda.core.serialization.SingletonSerializeAsToken implements net.corda.core.node.services.AttachmentStorage public () @org.jetbrains.annotations.NotNull public final kotlin.Pair getAttachmentIdAndBytes(java.io.InputStream) - @org.jetbrains.annotations.NotNull public final HashMap getFiles() + @org.jetbrains.annotations.NotNull public final Map getFiles() public boolean hasAttachment(net.corda.core.crypto.SecureHash) @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash importAttachment(java.io.InputStream) @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash importAttachment(java.io.InputStream, String, String) @@ -4658,8 +4702,4 @@ public final class net.corda.testing.services.MockAttachmentStorage extends net. @org.jetbrains.annotations.NotNull public net.corda.core.crypto.SecureHash importOrGetAttachment(java.io.InputStream) @org.jetbrains.annotations.Nullable public net.corda.core.contracts.Attachment openAttachment(net.corda.core.crypto.SecureHash) @org.jetbrains.annotations.NotNull public List queryAttachments(net.corda.core.node.services.vault.AttachmentQueryCriteria, net.corda.core.node.services.vault.AttachmentSort) - public static final net.corda.testing.services.MockAttachmentStorage$Companion Companion -## -public static final class net.corda.testing.services.MockAttachmentStorage$Companion extends java.lang.Object - public final byte[] getBytes(java.io.InputStream) ## diff --git a/.ci/check-api-changes.sh b/.ci/check-api-changes.sh index 5896f6ebbf..d991c4e7cf 100755 --- a/.ci/check-api-changes.sh +++ b/.ci/check-api-changes.sh @@ -46,16 +46,20 @@ EOF #Get a list of any methods that expose classes in .internal. namespaces, and any classes which extend/implement #an internal class +#TODO: check that only classes in a whitelist are part of the API rather than look for specific invalid cases going forward newInternalExposures=$(echo "$userDiffContents" | grep "^+" | grep "\.internal\." ) +newNodeExposures=$(echo "$userDiffContents" | grep "^+" | grep "net.corda.node" ) internalCount=`grep -v "^$" < flowHandle = rpcProxy.startFlowDynamic(CashIssueFlow.class, DOLLARS(123), OpaqueBytes.of((byte)0), - TestUtils.chooseIdentity(node.getInfo())); + InternalTestUtilsKt.chooseIdentity(node.getInfo())); System.out.println("Started issuing cash, waiting on result"); flowHandle.getReturnValue().get(); 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 26108f4328..41c45553b1 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 @@ -11,9 +11,9 @@ import net.corda.node.internal.StartedNode import net.corda.node.services.Permissions import net.corda.node.services.Permissions.Companion.invokeRpc import net.corda.testing.core.ALICE_NAME -import net.corda.testing.core.chooseIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.driver +import net.corda.testing.internal.chooseIdentity import net.corda.testing.node.User import net.corda.testing.node.internal.NodeBasedTest import org.assertj.core.api.Assertions.assertThat diff --git a/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt b/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt index 84b95c31bc..bb57ede626 100644 --- a/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt +++ b/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt @@ -19,7 +19,7 @@ import net.corda.testing.core.BOB_NAME import net.corda.testing.core.CHARLIE_NAME import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -57,13 +57,13 @@ class IdentitySyncFlowTests { // Alice issues then pays some cash to a new confidential identity that Bob doesn't know about val anonymous = true val ref = OpaqueBytes.of(0x01) - val issueFlow = aliceNode.services.startFlow(CashIssueAndPaymentFlow(1000.DOLLARS, ref, alice, anonymous, notary)) + val issueFlow = aliceNode.services.startFlow(CashIssueAndPaymentFlow(1000.DOLLARS, ref, alice, anonymous, notary)).resultFuture val issueTx = issueFlow.getOrThrow().stx val confidentialIdentity = issueTx.tx.outputs.map { it.data }.filterIsInstance().single().owner assertNull(bobNode.database.transaction { bobNode.services.identityService.wellKnownPartyFromAnonymous(confidentialIdentity) }) // Run the flow to sync up the identities - aliceNode.services.startFlow(Initiator(bob, issueTx.tx)).getOrThrow() + aliceNode.services.startFlow(Initiator(bob, issueTx.tx)).resultFuture.getOrThrow() val expected = aliceNode.database.transaction { aliceNode.services.identityService.wellKnownPartyFromAnonymous(confidentialIdentity) } @@ -88,7 +88,7 @@ class IdentitySyncFlowTests { val anonymous = true val ref = OpaqueBytes.of(0x01) val issueFlow = charlieNode.services.startFlow(CashIssueAndPaymentFlow(1000.DOLLARS, ref, charlie, anonymous, notary)) - val issueTx = issueFlow.getOrThrow().stx + val issueTx = issueFlow.resultFuture.getOrThrow().stx val confidentialIdentity = issueTx.tx.outputs.map { it.data }.filterIsInstance().single().owner val confidentialIdentCert = charlieNode.services.identityService.certificateFromKey(confidentialIdentity.owningKey)!! @@ -97,11 +97,11 @@ class IdentitySyncFlowTests { assertNotNull(aliceNode.database.transaction { aliceNode.services.identityService.wellKnownPartyFromAnonymous(confidentialIdentity) }) // Generate a payment from Charlie to Alice, including the confidential state - val payTx = charlieNode.services.startFlow(CashPaymentFlow(1000.DOLLARS, alice, anonymous)).getOrThrow().stx + val payTx = charlieNode.services.startFlow(CashPaymentFlow(1000.DOLLARS, alice, anonymous)).resultFuture.getOrThrow().stx // Run the flow to sync up the identities, and confirm Charlie's confidential identity doesn't leak assertNull(bobNode.database.transaction { bobNode.services.identityService.wellKnownPartyFromAnonymous(confidentialIdentity) }) - aliceNode.services.startFlow(Initiator(bob, payTx.tx)).getOrThrow() + aliceNode.services.startFlow(Initiator(bob, payTx.tx)).resultFuture.getOrThrow() assertNull(bobNode.database.transaction { bobNode.services.identityService.wellKnownPartyFromAnonymous(confidentialIdentity) }) } diff --git a/confidential-identities/src/test/kotlin/net/corda/confidential/SwapIdentitiesFlowTests.kt b/confidential-identities/src/test/kotlin/net/corda/confidential/SwapIdentitiesFlowTests.kt index 111b8e4ac6..91ab305ab6 100644 --- a/confidential-identities/src/test/kotlin/net/corda/confidential/SwapIdentitiesFlowTests.kt +++ b/confidential-identities/src/test/kotlin/net/corda/confidential/SwapIdentitiesFlowTests.kt @@ -4,8 +4,8 @@ import net.corda.core.identity.* import net.corda.core.utilities.getOrThrow import net.corda.testing.core.* import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.startFlow import org.junit.Before -import net.corda.testing.node.startFlow import org.junit.Test import kotlin.test.* @@ -27,7 +27,7 @@ class SwapIdentitiesFlowTests { val bob = bobNode.services.myInfo.singleIdentity() // Run the flows - val requesterFlow = aliceNode.services.startFlow(SwapIdentitiesFlow(bob)) + val requesterFlow = aliceNode.services.startFlow(SwapIdentitiesFlow(bob)).resultFuture // Get the results val actual: Map = requesterFlow.getOrThrow().toMap() @@ -62,7 +62,7 @@ class SwapIdentitiesFlowTests { val charlieNode = mockNet.createPartyNode(CHARLIE_NAME) val bob: Party = bobNode.services.myInfo.singleIdentity() val notBob = charlieNode.database.transaction { - charlieNode.services.keyManagementService.freshKeyAndCert(charlieNode.services.myInfo.chooseIdentityAndCert(), false) + charlieNode.services.keyManagementService.freshKeyAndCert(charlieNode.services.myInfo.singleIdentityAndCert(), false) } val sigData = SwapIdentitiesFlow.buildDataToSign(notBob) val signature = charlieNode.services.keyManagementService.sign(sigData, notBob.owningKey) diff --git a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java index d7a1d863d7..f98b11141d 100644 --- a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java +++ b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java @@ -17,7 +17,6 @@ import static java.util.Collections.emptyList; import static net.corda.testing.core.TestUtils.singleIdentity; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.Assert.fail; -import static net.corda.testing.node.NodeTestUtils.startFlow; public class FlowsInJavaTest { private final MockNetwork mockNet = new MockNetwork(emptyList()); @@ -40,7 +39,7 @@ public class FlowsInJavaTest { @Test public void suspendableActionInsideUnwrap() throws Exception { bobNode.registerInitiatedFlow(SendHelloAndThenReceive.class); - Future result = startFlow(aliceNode.getServices(), new SendInUnwrapFlow(bob)); + Future result = aliceNode.startFlow(new SendInUnwrapFlow(bob)); mockNet.runNetwork(); assertThat(result.get()).isEqualTo("Hello"); } @@ -56,7 +55,7 @@ public class FlowsInJavaTest { private void primitiveReceiveTypeTest(Class receiveType) throws InterruptedException { PrimitiveReceiveFlow flow = new PrimitiveReceiveFlow(bob, receiveType); - Future result = startFlow(aliceNode.getServices(), flow); + Future result = aliceNode.startFlow(flow); mockNet.runNetwork(); try { result.get(); 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 88df92acf3..3c7275a819 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt @@ -15,11 +15,11 @@ import net.corda.finance.contracts.asset.Cash import net.corda.node.services.api.IdentityServiceInternal import net.corda.testing.core.DUMMY_NOTARY_NAME import net.corda.testing.core.SerializationEnvironmentRule -import net.corda.testing.core.TEST_TX_TIME import net.corda.testing.core.TestIdentity 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.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.ledger 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 608d7c894e..d7bf7ce049 100644 --- a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt @@ -13,9 +13,9 @@ import net.corda.node.services.persistence.NodeAttachmentService import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.singleIdentity -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -65,7 +65,7 @@ class AttachmentTests { mockNet.runNetwork() val bobFlow = bobNode.startAttachmentFlow(setOf(id), alice) mockNet.runNetwork() - assertEquals(0, bobFlow.getOrThrow().fromDisk.size) + assertEquals(0, bobFlow.resultFuture.getOrThrow().fromDisk.size) // Verify it was inserted into node one's store. val attachment = bobNode.database.transaction { @@ -77,7 +77,7 @@ class AttachmentTests { // Shut down node zero and ensure node one can still resolve the attachment. aliceNode.dispose() - val response: FetchDataFlow.Result = bobNode.startAttachmentFlow(setOf(id), alice).getOrThrow() + val response: FetchDataFlow.Result = bobNode.startAttachmentFlow(setOf(id), alice).resultFuture.getOrThrow() assertEquals(attachment, response.fromDisk[0]) } @@ -92,19 +92,19 @@ class AttachmentTests { val alice = aliceNode.info.singleIdentity() val bobFlow = bobNode.startAttachmentFlow(setOf(hash), alice) mockNet.runNetwork() - val e = assertFailsWith { bobFlow.getOrThrow() } + val e = assertFailsWith { bobFlow.resultFuture.getOrThrow() } assertEquals(hash, e.requested) } @Test fun maliciousResponse() { // Make a node that doesn't do sanity checking at load time. - val aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME), nodeFactory = { args -> + val aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME), nodeFactory = { args -> object : InternalMockNetwork.MockNode(args) { override fun start() = super.start().apply { attachments.checkAttachmentsOnLoad = false } } }) - val bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) + val bobNode = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME)) val alice = aliceNode.info.singleIdentity() aliceNode.registerInitiatedFlow(FetchAttachmentsResponse::class.java) bobNode.registerInitiatedFlow(FetchAttachmentsResponse::class.java) @@ -127,7 +127,7 @@ class AttachmentTests { mockNet.runNetwork() val bobFlow = bobNode.startAttachmentFlow(setOf(id), alice) mockNet.runNetwork() - assertFailsWith { bobFlow.getOrThrow() } + assertFailsWith { bobFlow.resultFuture.getOrThrow() } } private fun StartedNode<*>.startAttachmentFlow(hashes: Set, otherSide: Party) = services.startFlow(InitiatingFetchAttachmentsFlow(otherSide, hashes)) diff --git a/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt b/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt index e2c24061a3..9e862af098 100644 --- a/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt @@ -18,7 +18,7 @@ import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -116,7 +116,7 @@ class CollectSignaturesFlowTests { val state = DummyContract.MultiOwnerState(magicNumber, parties) val flow = aliceNode.services.startFlow(TestFlow.Initiator(state, notary)) mockNet.runNetwork() - val result = flow.getOrThrow() + val result = flow.resultFuture.getOrThrow() result.verifyRequiredSignatures() println(result.tx) println(result.sigs) @@ -128,7 +128,7 @@ class CollectSignaturesFlowTests { val ptx = aliceNode.services.signInitialTransaction(onePartyDummyContract) val flow = aliceNode.services.startFlow(CollectSignaturesFlow(ptx, emptySet())) mockNet.runNetwork() - val result = flow.getOrThrow() + val result = flow.resultFuture.getOrThrow() result.verifyRequiredSignatures() println(result.tx) println(result.sigs) @@ -142,7 +142,7 @@ class CollectSignaturesFlowTests { val flow = aliceNode.services.startFlow(CollectSignaturesFlow(ptx, emptySet())) mockNet.runNetwork() assertFailsWith("The Initiator of CollectSignaturesFlow must have signed the transaction.") { - flow.getOrThrow() + flow.resultFuture.getOrThrow() } } @@ -156,7 +156,7 @@ class CollectSignaturesFlowTests { val signedByBoth = bobNode.services.addSignature(signedByA) val flow = aliceNode.services.startFlow(CollectSignaturesFlow(signedByBoth, emptySet())) mockNet.runNetwork() - val result = flow.getOrThrow() + val result = flow.resultFuture.getOrThrow() println(result.tx) println(result.sigs) } diff --git a/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt b/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt index 3278c93e93..69288a9a8e 100644 --- a/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt +++ b/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt @@ -28,7 +28,6 @@ import net.corda.testing.core.singleIdentity import net.corda.testing.node.User import net.corda.testing.node.internal.* import net.corda.testing.node.internal.InternalMockNetwork.MockNode -import net.corda.testing.node.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -81,25 +80,25 @@ class ContractUpgradeFlowTest { // The request is expected to be rejected because party B hasn't authorised the upgrade yet. val rejectedFuture = aliceNode.services.startFlow(ContractUpgradeFlow.Initiate(atx!!.tx.outRef(0), DummyContractV2::class.java)) mockNet.runNetwork() - assertFailsWith(UnexpectedFlowEndException::class) { rejectedFuture.getOrThrow() } + assertFailsWith(UnexpectedFlowEndException::class) { rejectedFuture.resultFuture.getOrThrow() } // Party B authorise the contract state upgrade, and immediately deauthorise the same. - bobNode.services.startFlow(ContractUpgradeFlow.Authorise(btx!!.tx.outRef(0), DummyContractV2::class.java)).getOrThrow() - bobNode.services.startFlow(ContractUpgradeFlow.Deauthorise(btx.tx.outRef(0).ref)).getOrThrow() + bobNode.services.startFlow(ContractUpgradeFlow.Authorise(btx!!.tx.outRef(0), DummyContractV2::class.java)).resultFuture.getOrThrow() + bobNode.services.startFlow(ContractUpgradeFlow.Deauthorise(btx.tx.outRef(0).ref)).resultFuture.getOrThrow() // The request is expected to be rejected because party B has subsequently deauthorised and a previously authorised upgrade. val deauthorisedFuture = aliceNode.services.startFlow(ContractUpgradeFlow.Initiate(atx.tx.outRef(0), DummyContractV2::class.java)) mockNet.runNetwork() - assertFailsWith(UnexpectedFlowEndException::class) { deauthorisedFuture.getOrThrow() } + assertFailsWith(UnexpectedFlowEndException::class) { deauthorisedFuture.resultFuture.getOrThrow() } // Party B authorise the contract state upgrade - bobNode.services.startFlow(ContractUpgradeFlow.Authorise(btx.tx.outRef(0), DummyContractV2::class.java)).getOrThrow() + bobNode.services.startFlow(ContractUpgradeFlow.Authorise(btx.tx.outRef(0), DummyContractV2::class.java)).resultFuture.getOrThrow() // Party A initiates contract upgrade flow, expected to succeed this time. val resultFuture = aliceNode.services.startFlow(ContractUpgradeFlow.Initiate(atx.tx.outRef(0), DummyContractV2::class.java)) mockNet.runNetwork() - val result = resultFuture.getOrThrow() + val result = resultFuture.resultFuture.getOrThrow() fun check(node: StartedNode) { val upgradeTx = node.database.transaction { @@ -201,15 +200,15 @@ class ContractUpgradeFlowTest { val chosenIdentity = alice val result = aliceNode.services.startFlow(CashIssueFlow(Amount(1000, USD), OpaqueBytes.of(1), notary)) mockNet.runNetwork() - val stx = result.getOrThrow().stx - val anonymisedRecipient = result.get().recipient!! + val stx = result.resultFuture.getOrThrow().stx + val anonymisedRecipient = result.resultFuture.get().recipient!! val stateAndRef = stx.tx.outRef(0) val baseState = aliceNode.database.transaction { aliceNode.services.vaultService.queryBy().states.single() } assertTrue(baseState.state.data is Cash.State, "Contract state is old version.") // Starts contract upgrade flow. val upgradeResult = aliceNode.services.startFlow(ContractUpgradeFlow.Initiate(stateAndRef, CashV2::class.java)) mockNet.runNetwork() - upgradeResult.getOrThrow() + upgradeResult.resultFuture.getOrThrow() // Get contract state from the vault. val upgradedStateFromVault = aliceNode.database.transaction { aliceNode.services.vaultService.queryBy().states.single() } assertEquals(Amount(1000000, USD).`issued by`(chosenIdentity.ref(1)), upgradedStateFromVault.state.data.amount, "Upgraded cash contain the correct amount.") @@ -225,7 +224,7 @@ class ContractUpgradeFlowTest { .addCommand(CashV2.Move(), alice.owningKey) ) - aliceNode.services.startFlow(FinalityFlow(spendUpgradedTx)).apply { + aliceNode.services.startFlow(FinalityFlow(spendUpgradedTx)).resultFuture.apply { mockNet.runNetwork() get() } diff --git a/core/src/test/kotlin/net/corda/core/flows/FinalityFlowTests.kt b/core/src/test/kotlin/net/corda/core/flows/FinalityFlowTests.kt index 15d0f42b03..e19385799c 100644 --- a/core/src/test/kotlin/net/corda/core/flows/FinalityFlowTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/FinalityFlowTests.kt @@ -6,10 +6,9 @@ import net.corda.core.utilities.getOrThrow import net.corda.finance.POUNDS import net.corda.finance.contracts.asset.Cash import net.corda.finance.issuedBy -import net.corda.node.services.api.StartedNodeServices import net.corda.testing.core.* import net.corda.testing.node.MockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.StartedMockNode import org.junit.After import org.junit.Before import org.junit.Test @@ -22,8 +21,8 @@ class FinalityFlowTests { } private lateinit var mockNet: MockNetwork - private lateinit var aliceServices: StartedNodeServices - private lateinit var bobServices: StartedNodeServices + private lateinit var aliceNode: StartedMockNode + private lateinit var bobNode: StartedMockNode private lateinit var alice: Party private lateinit var bob: Party private lateinit var notary: Party @@ -31,10 +30,8 @@ class FinalityFlowTests { @Before fun setup() { mockNet = MockNetwork(cordappPackages = listOf("net.corda.finance.contracts.asset")) - val aliceNode = mockNet.createPartyNode(ALICE_NAME) - val bobNode = mockNet.createPartyNode(BOB_NAME) - aliceServices = aliceNode.services - bobServices = bobNode.services + aliceNode = mockNet.createPartyNode(ALICE_NAME) + bobNode = mockNet.createPartyNode(BOB_NAME) alice = aliceNode.info.singleIdentity() bob = bobNode.info.singleIdentity() notary = mockNet.defaultNotaryIdentity @@ -50,13 +47,13 @@ class FinalityFlowTests { val amount = 1000.POUNDS.issuedBy(alice.ref(0)) val builder = TransactionBuilder(notary) Cash().generateIssue(builder, amount, bob, notary) - val stx = aliceServices.signInitialTransaction(builder) - val flow = aliceServices.startFlow(FinalityFlow(stx)) + val stx = aliceNode.services.signInitialTransaction(builder) + val flow = aliceNode.startFlow(FinalityFlow(stx)) mockNet.runNetwork() val notarisedTx = flow.getOrThrow() notarisedTx.verifyRequiredSignatures() - val transactionSeenByB = bobServices.database.transaction { - bobServices.validatedTransactions.getTransaction(notarisedTx.id) + val transactionSeenByB = bobNode.transaction { + bobNode.services.validatedTransactions.getTransaction(notarisedTx.id) } assertEquals(notarisedTx, transactionSeenByB) } @@ -67,8 +64,8 @@ class FinalityFlowTests { val fakeIdentity = CHARLIE // Charlie isn't part of this network, so node A won't recognise them val builder = TransactionBuilder(notary) Cash().generateIssue(builder, amount, fakeIdentity, notary) - val stx = aliceServices.signInitialTransaction(builder) - val flow = aliceServices.startFlow(FinalityFlow(stx)) + val stx = aliceNode.services.signInitialTransaction(builder) + val flow = aliceNode.startFlow(FinalityFlow(stx)) mockNet.runNetwork() assertFailsWith { flow.getOrThrow() diff --git a/core/src/test/kotlin/net/corda/core/flows/ReceiveAllFlowTests.kt b/core/src/test/kotlin/net/corda/core/flows/ReceiveAllFlowTests.kt index 18fdf82f64..93f2f0f471 100644 --- a/core/src/test/kotlin/net/corda/core/flows/ReceiveAllFlowTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/ReceiveAllFlowTests.kt @@ -7,7 +7,7 @@ import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.startFlow import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Test @@ -22,7 +22,6 @@ class ReceiveMultipleFlowTests { @Test fun showcase_flows_as_closures() { - val answer = 10.0 val message = "Hello Ivan" @@ -52,7 +51,7 @@ class ReceiveMultipleFlowTests { val flow = nodes[0].services.startFlow(initiatingFlow) mockNet.runNetwork() - val receivedAnswer = flow.getOrThrow() + val receivedAnswer = flow.resultFuture.getOrThrow() assertThat(receivedAnswer).isEqualTo(answer) } @@ -64,7 +63,7 @@ class ReceiveMultipleFlowTests { nodes[2].registerAnswer(AlgorithmDefinition::class, stringValue) val flow = nodes[0].services.startFlow(ParallelAlgorithmMap(nodes[1].info.singleIdentity(), nodes[2].info.singleIdentity())) mockNet.runNetwork() - val result = flow.getOrThrow() + val result = flow.resultFuture.getOrThrow() assertThat(result).isEqualTo(doubleValue * stringValue.length) } @@ -76,7 +75,7 @@ class ReceiveMultipleFlowTests { nodes[2].registerAnswer(ParallelAlgorithmList::class, value2) val flow = nodes[0].services.startFlow(ParallelAlgorithmList(nodes[1].info.singleIdentity(), nodes[2].info.singleIdentity())) mockNet.runNetwork() - val data = flow.getOrThrow() + val data = flow.resultFuture.getOrThrow() assertThat(data[0]).isEqualTo(value1) assertThat(data[1]).isEqualTo(value2) assertThat(data.fold(1.0) { a, b -> a * b }).isEqualTo(value1 * value2) 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 f6d9432f6a..b340601f12 100644 --- a/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt @@ -13,7 +13,7 @@ import net.corda.testing.contracts.DummyContract import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -62,7 +62,7 @@ class ResolveTransactionsFlowTest { val p = TestFlow(setOf(stx2.id), megaCorp) val future = miniCorpNode.services.startFlow(p) mockNet.runNetwork() - val results = future.getOrThrow() + val results = future.resultFuture.getOrThrow() assertEquals(listOf(stx1.id, stx2.id), results.map { it.id }) miniCorpNode.database.transaction { assertEquals(stx1, miniCorpNode.services.validatedTransactions.getTransaction(stx1.id)) @@ -77,7 +77,7 @@ class ResolveTransactionsFlowTest { val p = TestFlow(setOf(stx.id), megaCorp) val future = miniCorpNode.services.startFlow(p) mockNet.runNetwork() - assertFailsWith(SignedTransaction.SignaturesMissingException::class) { future.getOrThrow() } + assertFailsWith(SignedTransaction.SignaturesMissingException::class) { future.resultFuture.getOrThrow() } } @Test @@ -86,7 +86,7 @@ class ResolveTransactionsFlowTest { val p = TestFlow(stx2, megaCorp) val future = miniCorpNode.services.startFlow(p) mockNet.runNetwork() - future.getOrThrow() + future.resultFuture.getOrThrow() miniCorpNode.database.transaction { assertEquals(stx1, miniCorpNode.services.validatedTransactions.getTransaction(stx1.id)) // But stx2 wasn't inserted, just stx1. @@ -111,7 +111,7 @@ class ResolveTransactionsFlowTest { val p = TestFlow(setOf(cursor.id), megaCorp, 40) val future = miniCorpNode.services.startFlow(p) mockNet.runNetwork() - assertFailsWith { future.getOrThrow() } + assertFailsWith { future.resultFuture.getOrThrow() } } @Test @@ -135,7 +135,7 @@ class ResolveTransactionsFlowTest { val p = TestFlow(setOf(stx3.id), megaCorp) val future = miniCorpNode.services.startFlow(p) mockNet.runNetwork() - future.getOrThrow() + future.resultFuture.getOrThrow() } @Test @@ -157,7 +157,7 @@ class ResolveTransactionsFlowTest { val p = TestFlow(stx2, megaCorp) val future = miniCorpNode.services.startFlow(p) mockNet.runNetwork() - future.getOrThrow() + future.resultFuture.getOrThrow() // TODO: this operation should not require an explicit transaction miniCorpNode.database.transaction { diff --git a/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt b/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt index 88acc9a8c2..7770f5af8a 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt @@ -18,10 +18,10 @@ import net.corda.node.services.persistence.NodeAttachmentService import net.corda.nodeapi.internal.persistence.currentDBSession import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME -import net.corda.testing.node.MockNodeParameters import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -71,8 +71,8 @@ class AttachmentSerializationTest { @Before fun setUp() { mockNet = InternalMockNetwork(emptyList()) - server = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - client = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) + server = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) + client = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME)) client.internals.disableDBCloseOnStop() // Otherwise the in-memory database may disappear (taking the checkpoint with it) while we reboot the client. mockNet.runNetwork() serverIdentity = server.info.singleIdentity() @@ -160,7 +160,7 @@ class AttachmentSerializationTest { private fun rebootClientAndGetAttachmentContent(checkAttachmentsOnLoad: Boolean = true): String { client.dispose() - client = mockNet.createNode(MockNodeParameters(client.internals.id, client.internals.configuration.myLegalName), { args -> + client = mockNet.createNode(InternalMockNodeParameters(client.internals.id, client.internals.configuration.myLegalName), nodeFactory = { args -> object : InternalMockNetwork.MockNode(args) { override fun start() = super.start().apply { attachments.checkAttachmentsOnLoad = checkAttachmentsOnLoad } } diff --git a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt index d7894ed1ee..cfb4c681a3 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt @@ -9,6 +9,7 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.seconds import net.corda.finance.POUNDS import net.corda.testing.core.* +import net.corda.testing.internal.TEST_TX_TIME import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import org.junit.Before diff --git a/docs/packages.md b/docs/packages.md index 2be38afd1e..a1c257ac91 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -106,38 +106,68 @@ Various types for common financial concepts like day roll conventions, fixes, et WARNING: NOT API STABLE. -# net.corda.finance.contracts.asset +# Package net.corda.finance.contracts.asset Cash states, obligations and commodities. WARNING: NOT API STABLE. -# net.corda.finance.contracts.asset.cash.selection +# Package net.corda.finance.contracts.asset.cash.selection Provisional support for pluggable cash selectors, needed for different database backends. WARNING: NOT API STABLE. -# net.corda.finance.contracts.math +# Package net.corda.finance.contracts.math Splines and interpolation. WARNING: NOT API STABLE. -# net.corda.finance.flows +# Package net.corda.finance.flows Cash payments and issuances. Two party "delivery vs payment" atomic asset swaps. WARNING: NOT API STABLE. -# net.corda.finance.plugin +# Package net.corda.finance.plugin JSON/Jackson plugin for business calendars. WARNING: NOT API STABLE. -# net.corda.finance.schemas +# Package net.corda.finance.schemas JPA (Java Persistence Architecture) schemas for the financial state types. +WARNING: NOT API STABLE. + +# Package net.corda.testing.core + +Generic test utilities for contracts and flows + +# Package net.corda.testing.node + +Test utilites to help running nodes programmatically for tests + +# Package net.corda.testing.driver + +Test utilites to help running nodes programmatically for tests + +# Package net.corda.testing.dsl + +A simple DSL for building pseudo-transactions (not the same as the wire protocol) for testing purposes + +# Package net.corda.testing.contracts + +Dummy state and contracts for testing purposes + +# Package net.corda.testing.services + +Mock service implementations for testing purposes + +# Package net.corda.testing.http + +A small set of utilities for working with http calls. + WARNING: NOT API STABLE. \ No newline at end of file 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 62cac9978e..375a13c3b6 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 @@ -73,7 +73,7 @@ class IntegrationTestingTutorial { (1..10).map { i -> aliceProxy.startFlow(::CashPaymentFlow, i.DOLLARS, - bob.nodeInfo.chooseIdentity(), + bob.nodeInfo.singleIdentity(), true ).returnValue }.transpose().getOrThrow() @@ -95,7 +95,7 @@ class IntegrationTestingTutorial { // START 5 for (i in 1..10) { - bobProxy.startFlow(::CashPaymentFlow, i.DOLLARS, alice.nodeInfo.chooseIdentity()).returnValue.getOrThrow() + bobProxy.startFlow(::CashPaymentFlow, i.DOLLARS, alice.nodeInfo.singleIdentity()).returnValue.getOrThrow() } aliceVaultUpdates.expectEvents { diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/FxTransactionBuildTutorial.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/FxTransactionBuildTutorial.kt index 73893bae56..ee2547687f 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/FxTransactionBuildTutorial.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/FxTransactionBuildTutorial.kt @@ -16,7 +16,7 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.unwrap import net.corda.finance.contracts.asset.Cash import net.corda.finance.schemas.CashSchemaV1 -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import java.util.* @CordaSerializable @@ -74,7 +74,7 @@ private fun prepareOurInputsAndOutputs(serviceHub: ServiceHub, lockId: UUID, req val outputs = if (residual > 0L) { // Build an output state for the residual change back to us val residualAmount = Amount(residual, sellAmount.token) - val residualOutput = Cash.State(residualAmount, serviceHub.myInfo.chooseIdentity()) + val residualOutput = Cash.State(residualAmount, serviceHub.myInfo.singleIdentity()) listOf(transferedFundsOutput, residualOutput) } else { listOf(transferedFundsOutput) diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/contract/TutorialContract.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/contract/TutorialContract.kt index a3cd0a656f..78946fbd67 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/contract/TutorialContract.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/contract/TutorialContract.kt @@ -10,7 +10,7 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.finance.contracts.asset.Cash import net.corda.finance.utils.sumCashBy -import net.corda.testing.core.chooseIdentityAndCert +import net.corda.testing.core.singleIdentityAndCert import java.time.Instant import java.util.* @@ -112,7 +112,7 @@ class CommercialPaper : Contract { services = services, tx = tx, amount = paper.state.data.faceValue.withoutIssuer(), - ourIdentity = services.myInfo.chooseIdentityAndCert(), + ourIdentity = services.myInfo.singleIdentityAndCert(), to = paper.state.data.owner ) tx.addInputState(paper) diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt index add59fa45b..939d241942 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt @@ -73,32 +73,32 @@ class TutorialMockNetwork { mockNet.stopNodes() } - @Test - fun `fail if initiated doesn't send back 1 on first result`() { +// @Test +// fun `fail if initiated doesn't send back 1 on first result`() { - // DOCSTART 1 - // modify message if it's 1 - nodeB.setMessagingServiceSpy(object : MessagingServiceSpy(nodeB.network) { + // DOCSTART 1 + // TODO: Fix this test - accessing the MessagingService directly exposes internal interfaces +// nodeB.setMessagingServiceSpy(object : MessagingServiceSpy(nodeB.network) { +// override fun send(message: Message, target: MessageRecipients, retryId: Long?, sequenceKey: Any, additionalHeaders: Map) { +// val messageData = message.data.deserialize() as? ExistingSessionMessage +// val payload = messageData?.payload +// +// if (payload is DataSessionMessage && payload.payload.deserialize() == 1) { +// val alteredMessageData = messageData.copy(payload = payload.copy(99.serialize())).serialize().bytes +// messagingService.send(InMemoryMessagingNetwork.InMemoryMessage(message.topic, OpaqueBytes(alteredMessageData), message.uniqueMessageId), target, retryId) +// } else { +// messagingService.send(message, target, retryId) +// } +// } +// }) + // DOCEND 1 - override fun send(message: Message, target: MessageRecipients, retryId: Long?, sequenceKey: Any, additionalHeaders: Map) { - val messageData = message.data.deserialize() as? ExistingSessionMessage - val payload = messageData?.payload - if (payload is DataSessionMessage && payload.payload.deserialize() == 1) { - val alteredMessageData = messageData.copy(payload = payload.copy(99.serialize())).serialize().bytes - messagingService.send(InMemoryMessagingNetwork.InMemoryMessage(message.topic, OpaqueBytes(alteredMessageData), message.uniqueMessageId), target, retryId) - } else { - messagingService.send(message, target, retryId) - } - } - }) - // DOCEND 1 - - val initiatingReceiveFlow = nodeA.services.startFlow(FlowA(nodeB.info.legalIdentities.first())) - - mockNet.runNetwork() - - expectedEx.expect(IllegalArgumentException::class.java) - expectedEx.expectMessage("Expected to receive 1") - initiatingReceiveFlow.getOrThrow() - } +// val initiatingReceiveFlow = nodeA.startFlow(FlowA(nodeB.info.legalIdentities.first())) +// +// mockNet.runNetwork() +// +// expectedEx.expect(IllegalArgumentException::class.java) +// expectedEx.expectMessage("Expected to receive 1") +// initiatingReceiveFlow.getOrThrow() +// } } \ No newline at end of file diff --git a/docs/source/example-code/src/test/java/net/corda/docs/java/tutorial/testdsl/CommercialPaperTest.java b/docs/source/example-code/src/test/java/net/corda/docs/java/tutorial/testdsl/CommercialPaperTest.java index ff5e91b4ed..7952b07fbe 100644 --- a/docs/source/example-code/src/test/java/net/corda/docs/java/tutorial/testdsl/CommercialPaperTest.java +++ b/docs/source/example-code/src/test/java/net/corda/docs/java/tutorial/testdsl/CommercialPaperTest.java @@ -12,15 +12,15 @@ import net.corda.testing.node.MockServices; import org.junit.Before; import org.junit.Test; -import java.security.PublicKey; +import java.time.Instant; import java.time.temporal.ChronoUnit; import static java.util.Collections.singletonList; -import static net.corda.core.crypto.Crypto.generateKeyPair; import static net.corda.finance.Currencies.DOLLARS; import static net.corda.finance.Currencies.issuedBy; import static net.corda.finance.contracts.JavaCommercialPaper.JCP_PROGRAM_ID; -import static net.corda.testing.core.TestConstants.*; +import static net.corda.testing.core.TestConstants.ALICE_NAME; +import static net.corda.testing.core.TestConstants.BOB_NAME; import static net.corda.testing.node.MockServicesKt.makeTestIdentityService; import static net.corda.testing.node.NodeTestUtils.ledger; import static net.corda.testing.node.NodeTestUtils.transaction; @@ -31,21 +31,26 @@ public class CommercialPaperTest { private static final TestIdentity bob = new TestIdentity(BOB_NAME, 80L); private static final TestIdentity megaCorp = new TestIdentity(new CordaX500Name("MegaCorp", "London", "GB")); private final byte[] defaultRef = {123}; + private static final Instant TEST_TX_TIME = Instant.parse("2015-04-17T12:00:00.00Z"); + private MockServices ledgerServices; - // DOCSTART 11 - private final MockServices ledgerServices = new MockServices( - // A list of packages to scan for cordapps - singletonList("net.corda.finance.contracts"), - // The identity represented by this set of mock services. Defaults to a test identity. - // You can also use the alternative parameter initialIdentityName which accepts a - // [CordaX500Name] - megaCorp, - // An implementation of [IdentityService], which contains a list of all identities known - // to the node. Use [makeTestIdentityService] which returns an implementation of - // [InMemoryIdentityService] with the given identities - makeTestIdentityService(megaCorp.getIdentity()) + @Before + public void setUp() { + // DOCSTART 11 + ledgerServices = new MockServices( + // A list of packages to scan for cordapps + singletonList("net.corda.finance.contracts"), + // The identity represented by this set of mock services. Defaults to a test identity. + // You can also use the alternative parameter initialIdentityName which accepts a + // [CordaX500Name] + megaCorp, + // An implementation of [IdentityService], which contains a list of all identities known + // to the node. Use [makeTestIdentityService] which returns an implementation of + // [InMemoryIdentityService] with the given identities + makeTestIdentityService(megaCorp.getIdentity()) ); - // DOCEND 11 + // DOCEND 11 + } @SuppressWarnings("unused") // DOCSTART 12 diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt index 6867695965..36a807f5ce 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt @@ -7,10 +7,9 @@ import net.corda.core.utilities.getOrThrow import net.corda.finance.* import net.corda.finance.contracts.getCashBalances import net.corda.finance.flows.CashIssueFlow -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import net.corda.testing.node.startFlow import org.junit.After import org.junit.Assert import org.junit.Before @@ -56,20 +55,17 @@ class CustomVaultQueryTest { private fun issueCashForCurrency(amountToIssue: Amount) { // Use NodeA as issuer and create some dollars - val flowHandle1 = nodeA.services.startFlow(CashIssueFlow(amountToIssue, + nodeA.startFlow(CashIssueFlow(amountToIssue, OpaqueBytes.of(0x01), - notary)) - // Wait for the flow to stop and print - flowHandle1.getOrThrow() + notary)).getOrThrow() } private fun topUpCurrencies() { - val flowHandle1 = nodeA.services.startFlow(TopupIssuerFlow.TopupIssuanceRequester( - nodeA.info.chooseIdentity(), + nodeA.startFlow(TopupIssuerFlow.TopupIssuanceRequester( + nodeA.info.singleIdentity(), OpaqueBytes.of(0x01), - nodeA.info.chooseIdentity(), - notary)) - flowHandle1.getOrThrow() + nodeA.info.singleIdentity(), + notary)).getOrThrow() } private fun getBalances(): Pair>, Map>> { diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt index 67a4c919f7..bc24f58acc 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt @@ -7,10 +7,9 @@ import net.corda.core.utilities.getOrThrow import net.corda.finance.* import net.corda.finance.contracts.getCashBalances import net.corda.finance.flows.CashIssueFlow -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import net.corda.testing.node.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -38,34 +37,29 @@ class FxTransactionBuildTutorialTest { @Test fun `Run ForeignExchangeFlow to completion`() { - // Use NodeA as issuer and create some dollars - val flowHandle1 = nodeA.services.startFlow(CashIssueFlow(DOLLARS(1000), + // Use NodeA as issuer and create some dollars and wait for the flow to stop + nodeA.startFlow(CashIssueFlow(DOLLARS(1000), OpaqueBytes.of(0x01), - notary)) - // Wait for the flow to stop and print - flowHandle1.getOrThrow() + notary)).getOrThrow() printBalances() - // Using NodeB as Issuer create some pounds. - val flowHandle2 = nodeB.services.startFlow(CashIssueFlow(POUNDS(1000), + // Using NodeB as Issuer create some pounds and wait for the flow to stop + nodeB.startFlow(CashIssueFlow(POUNDS(1000), OpaqueBytes.of(0x01), - notary)) - // Wait for flow to come to an end and print - flowHandle2.getOrThrow() + notary)).getOrThrow() printBalances() // Setup some futures on the vaults to await the arrival of the exchanged funds at both nodes val nodeAVaultUpdate = nodeA.services.vaultService.updates.toFuture() val nodeBVaultUpdate = nodeB.services.vaultService.updates.toFuture() - // Now run the actual Fx exchange - val doIt = nodeA.services.startFlow(ForeignExchangeFlow("trade1", - POUNDS(100).issuedBy(nodeB.info.chooseIdentity().ref(0x01)), - DOLLARS(200).issuedBy(nodeA.info.chooseIdentity().ref(0x01)), - nodeB.info.chooseIdentity(), - weAreBaseCurrencySeller = false)) + // Now run the actual Fx exchange and wait for the flow to finish + nodeA.startFlow(ForeignExchangeFlow("trade1", + POUNDS(100).issuedBy(nodeB.info.singleIdentity().ref(0x01)), + DOLLARS(200).issuedBy(nodeA.info.singleIdentity().ref(0x01)), + nodeB.info.singleIdentity(), + weAreBaseCurrencySeller = false)).getOrThrow() // wait for the flow to finish and the vault updates to be done - doIt.getOrThrow() // Get the balances when the vault updates nodeAVaultUpdate.get() val balancesA = nodeA.transaction { diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt index 7f751e577a..e7d28fb72e 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/WorkflowTransactionBuildTutorialTest.kt @@ -9,11 +9,10 @@ import net.corda.core.node.services.queryBy import net.corda.core.node.services.vault.QueryCriteria import net.corda.core.toFuture import net.corda.core.utilities.getOrThrow -import net.corda.node.services.api.StartedNodeServices import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.node.MockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.StartedMockNode import org.junit.After import org.junit.Before import org.junit.Test @@ -21,8 +20,8 @@ import kotlin.test.assertEquals class WorkflowTransactionBuildTutorialTest { private lateinit var mockNet: MockNetwork - private lateinit var aliceServices: StartedNodeServices - private lateinit var bobServices: StartedNodeServices + private lateinit var aliceNode: StartedMockNode + private lateinit var bobNode: StartedMockNode private lateinit var alice: Party private lateinit var bob: Party @@ -35,11 +34,9 @@ class WorkflowTransactionBuildTutorialTest { @Before fun setup() { mockNet = MockNetwork(threadPerNode = true, cordappPackages = listOf("net.corda.docs")) - val aliceNode = mockNet.createPartyNode(ALICE_NAME) - val bobNode = mockNet.createPartyNode(BOB_NAME) + aliceNode = mockNet.createPartyNode(ALICE_NAME) + bobNode = mockNet.createPartyNode(BOB_NAME) aliceNode.registerInitiatedFlow(RecordCompletionFlow::class.java) - aliceServices = aliceNode.services - bobServices = bobNode.services alice = aliceNode.services.myInfo.identityFromX500Name(ALICE_NAME) bob = bobNode.services.myInfo.identityFromX500Name(BOB_NAME) } @@ -52,20 +49,20 @@ class WorkflowTransactionBuildTutorialTest { @Test fun `Run workflow to completion`() { // Setup a vault subscriber to wait for successful upload of the proposal to NodeB - val nodeBVaultUpdate = bobServices.vaultService.updates.toFuture() + val nodeBVaultUpdate = bobNode.services.vaultService.updates.toFuture() // Kick of the proposal flow - val flow1 = aliceServices.startFlow(SubmitTradeApprovalFlow("1234", bob)) + val flow1 = aliceNode.startFlow(SubmitTradeApprovalFlow("1234", bob)) // Wait for the flow to finish val proposalRef = flow1.getOrThrow() val proposalLinearId = proposalRef.state.data.linearId // Wait for NodeB to include it's copy in the vault nodeBVaultUpdate.get() // Fetch the latest copy of the state from both nodes - val latestFromA = aliceServices.database.transaction { - aliceServices.latest(proposalLinearId) + val latestFromA = aliceNode.transaction { + aliceNode.services.latest(proposalLinearId) } - val latestFromB = bobServices.database.transaction { - bobServices.latest(proposalLinearId) + val latestFromB = bobNode.transaction { + bobNode.services.latest(proposalLinearId) } // Confirm the state as as expected assertEquals(WorkflowState.NEW, proposalRef.state.data.state) @@ -75,21 +72,21 @@ class WorkflowTransactionBuildTutorialTest { assertEquals(proposalRef, latestFromA) assertEquals(proposalRef, latestFromB) // Setup a vault subscriber to pause until the final update is in NodeA and NodeB - val nodeAVaultUpdate = aliceServices.vaultService.updates.toFuture() - val secondNodeBVaultUpdate = bobServices.vaultService.updates.toFuture() + val nodeAVaultUpdate = aliceNode.services.vaultService.updates.toFuture() + val secondNodeBVaultUpdate = bobNode.services.vaultService.updates.toFuture() // Run the manual completion flow from NodeB - val flow2 = bobServices.startFlow(SubmitCompletionFlow(latestFromB.ref, WorkflowState.APPROVED)) + val flow2 = bobNode.startFlow(SubmitCompletionFlow(latestFromB.ref, WorkflowState.APPROVED)) // wait for the flow to end val completedRef = flow2.getOrThrow() // wait for the vault updates to stabilise nodeAVaultUpdate.get() secondNodeBVaultUpdate.get() // Fetch the latest copies from the vault - val finalFromA = aliceServices.database.transaction { - aliceServices.latest(proposalLinearId) + val finalFromA = aliceNode.transaction { + aliceNode.services.latest(proposalLinearId) } - val finalFromB = bobServices.database.transaction { - bobServices.latest(proposalLinearId) + val finalFromB = bobNode.transaction { + bobNode.services.latest(proposalLinearId) } // Confirm the state is as expected assertEquals(WorkflowState.APPROVED, completedRef.state.data.state) diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt index e6539a910b..15e3f2feb7 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt @@ -17,6 +17,7 @@ import net.corda.testing.node.makeTestIdentityService import net.corda.testing.node.transaction import org.junit.Rule import org.junit.Test +import java.time.Instant class CommercialPaperTest { private companion object { @@ -25,6 +26,7 @@ class CommercialPaperTest { val bigCorp = TestIdentity((CordaX500Name("BigCorp", "New York", "GB"))) val dummyNotary = TestIdentity(DUMMY_NOTARY_NAME, 20) val megaCorp = TestIdentity(CordaX500Name("MegaCorp", "London", "GB")) + val TEST_TX_TIME: Instant = Instant.parse("2015-04-17T12:00:00.00Z") } @Rule diff --git a/docs/source/flow-testing.rst b/docs/source/flow-testing.rst index 8e131b94ff..df7844dd44 100644 --- a/docs/source/flow-testing.rst +++ b/docs/source/flow-testing.rst @@ -65,14 +65,14 @@ With regards to initiated flows (see :doc:`flow-state-machines` for information full node automatically registers them by scanning the CorDapp jars. In a unit test environment this is not possible so ``MockNode`` has the ``registerInitiatedFlow`` method to manually register an initiated flow. -MockNetwork message manipulation --------------------------------- -The MockNetwork has the ability to manipulate message streams. You can use this to test your flows behaviour on corrupted, -or malicious data received. +.. MockNetwork message manipulation +.. -------------------------------- +.. The MockNetwork has the ability to manipulate message streams. You can use this to test your flows behaviour on corrupted, + or malicious data received. -Message modification example in ``TutorialMockNetwork.kt``: +.. Message modification example in ``TutorialMockNetwork.kt``: -.. literalinclude:: ../../docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt +.. .. literalinclude:: ../../docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt :language: kotlin :start-after: DOCSTART 1 :end-before: DOCEND 1 diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/CommercialPaperTests.kt b/finance/src/test/kotlin/net/corda/finance/contracts/CommercialPaperTests.kt index 43ebe167fd..93793659df 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/CommercialPaperTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/CommercialPaperTests.kt @@ -18,6 +18,7 @@ import net.corda.testing.core.* import net.corda.testing.dsl.EnforceVerifyOrFail import net.corda.testing.dsl.TransactionDSL import net.corda.testing.dsl.TransactionDSLInterpreter +import net.corda.testing.internal.TEST_TX_TIME import net.corda.testing.internal.vault.VaultFiller import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices.Companion.makeTestDatabaseAndMockServices @@ -270,7 +271,7 @@ class CommercialPaperTestsGeneric { // MegaCorpâ„¢ issues $10,000 of commercial paper, to mature in 30 days, owned initially by itself. val faceValue = 10000.DOLLARS `issued by` dummyCashIssuer.ref(1) - val issuance = megaCorpServices.myInfo.chooseIdentity().ref(1) + val issuance = megaCorpServices.myInfo.singleIdentity().ref(1) val issueBuilder = CommercialPaper().generateIssue(issuance, faceValue, TEST_TX_TIME + 30.days, dummyNotary.party) issueBuilder.setTimeWindow(TEST_TX_TIME, 30.seconds) val issuePtx = megaCorpServices.signInitialTransaction(issueBuilder) @@ -300,7 +301,7 @@ class CommercialPaperTestsGeneric { fun makeRedeemTX(time: Instant): Pair { val builder = TransactionBuilder(dummyNotary.party) builder.setTimeWindow(time, 30.seconds) - CommercialPaper().generateRedeem(builder, moveTX.tx.outRef(1), megaCorpServices, megaCorpServices.myInfo.chooseIdentityAndCert()) + CommercialPaper().generateRedeem(builder, moveTX.tx.outRef(1), megaCorpServices, megaCorpServices.myInfo.singleIdentityAndCert()) val ptx = aliceServices.signInitialTransaction(builder) val ptx2 = megaCorpServices.addSignature(ptx) val stx = notaryServices.addSignature(ptx2) diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt index fa32531bfd..e6d8d6417e 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt @@ -23,6 +23,7 @@ import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyState import net.corda.testing.core.* import net.corda.testing.dsl.* +import net.corda.testing.internal.TEST_TX_TIME import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.ledger diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionH2ImplTest.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionH2ImplTest.kt index 79feb44f34..435ee7d4a5 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionH2ImplTest.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionH2ImplTest.kt @@ -10,7 +10,6 @@ import net.corda.finance.flows.CashIssueFlow import net.corda.finance.flows.CashPaymentFlow import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNodeParameters -import net.corda.testing.node.startFlow import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.After import org.junit.Test @@ -31,10 +30,10 @@ class CashSelectionH2ImplTest { // spend operation below. // Issuing Integer.MAX_VALUE will not cause an exception since PersistentCashState.pennies is a long nCopies(2, Integer.MAX_VALUE).map { issueAmount -> - node.services.startFlow(CashIssueFlow(issueAmount.POUNDS, OpaqueBytes.of(1), mockNet.defaultNotaryIdentity)) + node.startFlow(CashIssueFlow(issueAmount.POUNDS, OpaqueBytes.of(1), mockNet.defaultNotaryIdentity)) }.transpose().getOrThrow() // The spend must be more than the size of a single cash state to force the accumulator onto the second state. - node.services.startFlow(CashPaymentFlow((Integer.MAX_VALUE + 1L).POUNDS, node.info.legalIdentities[0])).getOrThrow() + node.startFlow(CashPaymentFlow((Integer.MAX_VALUE + 1L).POUNDS, node.info.legalIdentities[0])).getOrThrow() } @Test @@ -46,9 +45,9 @@ class CashSelectionH2ImplTest { val notary = mockNet.defaultNotaryIdentity // Start more cash spends than we have connections. If spend leaks a connection on retry, we will run out of connections. - val flow1 = bankA.services.startFlow(CashPaymentFlow(amount = 100.DOLLARS, anonymous = false, recipient = notary)) - val flow2 = bankA.services.startFlow(CashPaymentFlow(amount = 100.DOLLARS, anonymous = false, recipient = notary)) - val flow3 = bankA.services.startFlow(CashPaymentFlow(amount = 100.DOLLARS, anonymous = false, recipient = notary)) + val flow1 = bankA.startFlow(CashPaymentFlow(amount = 100.DOLLARS, anonymous = false, recipient = notary)) + val flow2 = bankA.startFlow(CashPaymentFlow(amount = 100.DOLLARS, anonymous = false, recipient = notary)) + val flow3 = bankA.startFlow(CashPaymentFlow(amount = 100.DOLLARS, anonymous = false, recipient = notary)) assertThatThrownBy { flow1.getOrThrow() }.isInstanceOf(CashException::class.java) assertThatThrownBy { flow2.getOrThrow() }.isInstanceOf(CashException::class.java) diff --git a/finance/src/test/kotlin/net/corda/finance/flows/CashExitFlowTests.kt b/finance/src/test/kotlin/net/corda/finance/flows/CashExitFlowTests.kt index 40ba1deffc..541dcc7d4c 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashExitFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashExitFlowTests.kt @@ -10,7 +10,6 @@ import net.corda.testing.core.BOC_NAME import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import net.corda.testing.node.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -32,7 +31,7 @@ class CashExitFlowTests { bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) bankOfCorda = bankOfCordaNode.info.identityFromX500Name(BOC_NAME) notary = mockNet.defaultNotaryIdentity - val future = bankOfCordaNode.services.startFlow(CashIssueFlow(initialBalance, ref, notary)) + val future = bankOfCordaNode.startFlow(CashIssueFlow(initialBalance, ref, notary)) mockNet.runNetwork() future.getOrThrow() } @@ -45,7 +44,7 @@ class CashExitFlowTests { @Test fun `exit some cash`() { val exitAmount = 500.DOLLARS - val future = bankOfCordaNode.services.startFlow(CashExitFlow(exitAmount, ref)) + val future = bankOfCordaNode.startFlow(CashExitFlow(exitAmount, ref)) mockNet.runNetwork() val exitTx = future.getOrThrow().stx.tx val expected = (initialBalance - exitAmount).`issued by`(bankOfCorda.ref(ref)) @@ -58,7 +57,7 @@ class CashExitFlowTests { @Test fun `exit zero cash`() { val expected = 0.DOLLARS - val future = bankOfCordaNode.services.startFlow(CashExitFlow(expected, ref)) + val future = bankOfCordaNode.startFlow(CashExitFlow(expected, ref)) mockNet.runNetwork() assertFailsWith { future.getOrThrow() diff --git a/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt b/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt index cd6522d901..080212bc3e 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt @@ -10,7 +10,6 @@ import net.corda.testing.core.BOC_NAME import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import net.corda.testing.node.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -40,7 +39,7 @@ class CashIssueFlowTests { fun `issue some cash`() { val expected = 500.DOLLARS val ref = OpaqueBytes.of(0x01) - val future = bankOfCordaNode.services.startFlow(CashIssueFlow(expected, ref, notary)) + val future = bankOfCordaNode.startFlow(CashIssueFlow(expected, ref, notary)) mockNet.runNetwork() val issueTx = future.getOrThrow().stx val output = issueTx.tx.outputsOfType().single() @@ -51,7 +50,7 @@ class CashIssueFlowTests { fun `issue zero cash`() { val expected = 0.DOLLARS val ref = OpaqueBytes.of(0x01) - val future = bankOfCordaNode.services.startFlow(CashIssueFlow(expected, ref, notary)) + val future = bankOfCordaNode.startFlow(CashIssueFlow(expected, ref, notary)) mockNet.runNetwork() assertFailsWith { future.getOrThrow() diff --git a/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt b/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt index 3c7139a891..9d5c737fe7 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt @@ -13,7 +13,7 @@ import net.corda.testing.core.* import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import net.corda.testing.node.startFlow + import org.junit.After import org.junit.Before import org.junit.Test @@ -34,7 +34,7 @@ class CashPaymentFlowTests { bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) bankOfCorda = bankOfCordaNode.info.identityFromX500Name(BOC_NAME) aliceNode = mockNet.createPartyNode(ALICE_NAME) - val future = bankOfCordaNode.services.startFlow(CashIssueFlow(initialBalance, ref, mockNet.defaultNotaryIdentity)) + val future = bankOfCordaNode.startFlow(CashIssueFlow(initialBalance, ref, mockNet.defaultNotaryIdentity)) future.getOrThrow() } @@ -45,7 +45,7 @@ class CashPaymentFlowTests { @Test fun `pay some cash`() { - val payTo = aliceNode.info.chooseIdentity() + val payTo = aliceNode.info.singleIdentity() val expectedPayment = 500.DOLLARS val expectedChange = 1500.DOLLARS @@ -55,7 +55,7 @@ class CashPaymentFlowTests { val (_, vaultUpdatesBoc) = bankOfCordaNode.services.vaultService.trackBy(criteria) val (_, vaultUpdatesBankClient) = aliceNode.services.vaultService.trackBy(criteria) - val future = bankOfCordaNode.services.startFlow(CashPaymentFlow(expectedPayment, payTo)) + val future = bankOfCordaNode.startFlow(CashPaymentFlow(expectedPayment, payTo)) mockNet.runNetwork() future.getOrThrow() @@ -84,9 +84,9 @@ class CashPaymentFlowTests { @Test fun `pay more than we have`() { - val payTo = aliceNode.info.chooseIdentity() + val payTo = aliceNode.info.singleIdentity() val expected = 4000.DOLLARS - val future = bankOfCordaNode.services.startFlow(CashPaymentFlow(expected, + val future = bankOfCordaNode.startFlow(CashPaymentFlow(expected, payTo)) mockNet.runNetwork() assertFailsWith { @@ -96,9 +96,9 @@ class CashPaymentFlowTests { @Test fun `pay zero cash`() { - val payTo = aliceNode.info.chooseIdentity() + val payTo = aliceNode.info.singleIdentity() val expected = 0.DOLLARS - val future = bankOfCordaNode.services.startFlow(CashPaymentFlow(expected, + val future = bankOfCordaNode.startFlow(CashPaymentFlow(expected, payTo)) mockNet.runNetwork() assertFailsWith { diff --git a/node/src/integration-test/kotlin/net/corda/node/CordappScanningDriverTest.kt b/node/src/integration-test/kotlin/net/corda/node/CordappScanningDriverTest.kt index fad710317b..0d5c9deb52 100644 --- a/node/src/integration-test/kotlin/net/corda/node/CordappScanningDriverTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/CordappScanningDriverTest.kt @@ -11,7 +11,7 @@ import net.corda.core.utilities.unwrap import net.corda.node.services.Permissions.Companion.startFlow import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.driver import net.corda.testing.node.User import org.assertj.core.api.Assertions.assertThat @@ -29,7 +29,7 @@ class CordappScanningDriverTest { val initiatedFlowClass = CordaRPCClient(alice.rpcAddress) .start(user.username, user.password) .proxy - .startFlow(::ReceiveFlow, bob.nodeInfo.chooseIdentity()) + .startFlow(::ReceiveFlow, bob.nodeInfo.singleIdentity()) .returnValue assertThat(initiatedFlowClass.getOrThrow()).isEqualTo(SendSubClassFlow::class.java.name) } diff --git a/node/src/integration-test/kotlin/net/corda/node/NodePerformanceTests.kt b/node/src/integration-test/kotlin/net/corda/node/NodePerformanceTests.kt index 215f907976..09412296b5 100644 --- a/node/src/integration-test/kotlin/net/corda/node/NodePerformanceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/NodePerformanceTests.kt @@ -19,9 +19,9 @@ import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.InProcess import net.corda.testing.node.User import net.corda.testing.driver.driver +import net.corda.testing.driver.internal.internalServices import net.corda.testing.internal.performance.div import net.corda.testing.node.NotarySpec -import net.corda.testing.node.internal.InternalDriverDSL import net.corda.testing.node.internal.internalDriver import net.corda.testing.node.internal.performance.startPublishingFixedRateInjector import net.corda.testing.node.internal.performance.startReporter @@ -81,7 +81,7 @@ class NodePerformanceTests { internalDriver(startNodesInProcess = true) { val a = startNode(rpcUsers = listOf(User("A", "A", setOf(startFlow())))).get() a as InProcess - val metricRegistry = startReporter(this.shutdownManager, a.services.monitoringService.metrics) + val metricRegistry = startReporter(this.shutdownManager, a.internalServices.monitoringService.metrics) CordaRPCClient(a.rpcAddress).use("A", "A") { connection -> startPublishingFixedRateInjector(metricRegistry, 8, 5.minutes, 2000L / TimeUnit.SECONDS) { connection.proxy.startFlow(::EmptyFlow).returnValue.get() @@ -99,7 +99,7 @@ class NodePerformanceTests { extraCordappPackagesToScan = listOf("net.corda.finance") ) { val notary = defaultNotaryNode.getOrThrow() as InProcess - val metricRegistry = startReporter(this.shutdownManager, notary.services.monitoringService.metrics) + val metricRegistry = startReporter(this.shutdownManager, notary.internalServices.monitoringService.metrics) CordaRPCClient(notary.rpcAddress).use("A", "A") { connection -> println("ISSUING") val doneFutures = (1..100).toList().parallelStream().map { diff --git a/node/src/integration-test/kotlin/net/corda/node/modes/draining/P2PFlowsDrainingModeTest.kt b/node/src/integration-test/kotlin/net/corda/node/modes/draining/P2PFlowsDrainingModeTest.kt index 7afdae9343..645f32f081 100644 --- a/node/src/integration-test/kotlin/net/corda/node/modes/draining/P2PFlowsDrainingModeTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/modes/draining/P2PFlowsDrainingModeTest.kt @@ -9,7 +9,7 @@ import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.loggerFor import net.corda.core.utilities.unwrap import net.corda.node.services.Permissions -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver @@ -51,7 +51,7 @@ class P2PFlowsDrainingModeTest { driver(DriverParameters(isDebug = true, startNodesInProcess = false, portAllocation = portAllocation)) { val initiatedNode = startNode().getOrThrow() val initiating = startNode(rpcUsers = users).getOrThrow().rpc - val counterParty = initiatedNode.nodeInfo.chooseIdentity() + val counterParty = initiatedNode.nodeInfo.singleIdentity() val initiated = initiatedNode.rpc initiated.setFlowsDrainingModeEnabled(true) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt index 8f7869f98f..7570469451 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/BFTNotaryServiceTests.kt @@ -26,14 +26,14 @@ import net.corda.node.services.transactions.minCorrectReplicas import net.corda.nodeapi.internal.DevIdentityGenerator import net.corda.nodeapi.internal.network.NetworkParametersCopier import net.corda.core.node.NotaryInfo -import net.corda.testing.core.chooseIdentity import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.contracts.DummyContract +import net.corda.testing.core.singleIdentity import net.corda.testing.core.dummyCommand -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test @@ -69,7 +69,7 @@ class BFTNotaryServiceTests { val clusterAddresses = replicaIds.map { NetworkHostAndPort("localhost", 11000 + it * 10) } val nodes = replicaIds.map { replicaId -> - mockNet.createUnstartedNode(MockNodeParameters(configOverrides = { + mockNet.createUnstartedNode(InternalMockNodeParameters(configOverrides = { val notary = NotaryConfig(validating = false, bftSMaRt = BFTSMaRtConfiguration(replicaId, clusterAddresses, exposeRaces = exposeRaces)) doReturn(notary).whenever(it).notary })) @@ -89,10 +89,10 @@ class BFTNotaryServiceTests { startBftClusterAndNode(minClusterSize(1), exposeRaces = true) // This true adds a sleep to expose the race. val f = node.run { val trivialTx = signInitialTransaction(notary) { - addOutputState(DummyContract.SingleOwnerState(owner = info.chooseIdentity()), DummyContract.PROGRAM_ID, AlwaysAcceptAttachmentConstraint) + addOutputState(DummyContract.SingleOwnerState(owner = info.singleIdentity()), DummyContract.PROGRAM_ID, AlwaysAcceptAttachmentConstraint) } // Create a new consensus while the redundant replica is sleeping: - services.startFlow(NotaryFlow.Client(trivialTx)) + services.startFlow(NotaryFlow.Client(trivialTx)).resultFuture } mockNet.runNetwork() f.getOrThrow() @@ -113,7 +113,7 @@ class BFTNotaryServiceTests { startBftClusterAndNode(clusterSize) node.run { val issueTx = signInitialTransaction(notary) { - addOutputState(DummyContract.SingleOwnerState(owner = info.chooseIdentity()), DummyContract.PROGRAM_ID, AlwaysAcceptAttachmentConstraint) + addOutputState(DummyContract.SingleOwnerState(owner = info.singleIdentity()), DummyContract.PROGRAM_ID, AlwaysAcceptAttachmentConstraint) } database.transaction { services.recordTransactions(issueTx) @@ -127,7 +127,7 @@ class BFTNotaryServiceTests { val flows = spendTxs.map { NotaryFlow.Client(it) } val stateMachines = flows.map { services.startFlow(it) } mockNet.runNetwork() - val results = stateMachines.map { Try.on { it.getOrThrow() } } + val results = stateMachines.map { Try.on { it.resultFuture.getOrThrow() } } val successfulIndex = results.mapIndexedNotNull { index, result -> if (result is Try.Success) { val signers = result.value.map { it.by } @@ -148,7 +148,7 @@ class BFTNotaryServiceTests { assertEquals(StateRef(issueTx.id, 0), stateRef) assertEquals(spendTxs[successfulIndex].id, consumingTx.id) assertEquals(0, consumingTx.inputIndex) - assertEquals(info.chooseIdentity(), consumingTx.requestingParty) + assertEquals(info.singleIdentity(), consumingTx.requestingParty) } } } @@ -157,7 +157,7 @@ class BFTNotaryServiceTests { private fun StartedNode.signInitialTransaction(notary: Party, block: TransactionBuilder.() -> Any?): SignedTransaction { return services.signInitialTransaction( TransactionBuilder(notary).apply { - addCommand(dummyCommand(services.myInfo.chooseIdentity().owningKey)) + addCommand(dummyCommand(services.myInfo.singleIdentity().owningKey)) block() } ) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt index a172e5459d..ad3733499b 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt @@ -70,8 +70,9 @@ class DistributedServiceTests { } aliceProxy = connectRpc(alice) val rpcClientsToNotaries = notaryNodes.map(::connectRpc) + notaryStateMachines = Observable.from(rpcClientsToNotaries.map { proxy -> - proxy.stateMachinesFeed().updates.map { Pair(proxy.nodeInfo().chooseIdentity(), it) } + proxy.stateMachinesFeed().updates.map { Pair(proxy.nodeInfo().legalIdentitiesAndCerts.first().party, it) } }).flatMap { it.onErrorResumeNext(Observable.empty()) }.bufferUntilSubscribed() testBlock() @@ -162,6 +163,6 @@ class DistributedServiceTests { } private fun paySelf(amount: Amount) { - aliceProxy.startFlow(::CashPaymentFlow, amount, alice.nodeInfo.chooseIdentity()).returnValue.getOrThrow() + aliceProxy.startFlow(::CashPaymentFlow, amount, alice.nodeInfo.singleIdentity()).returnValue.getOrThrow() } } \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt index 09f8733f1b..d656b9022e 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/RaftNotaryServiceTests.kt @@ -11,7 +11,7 @@ import net.corda.core.internal.concurrent.map import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.getOrThrow import net.corda.testing.core.DUMMY_BANK_A_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.contracts.DummyContract import net.corda.testing.driver.driver import net.corda.testing.core.dummyCommand @@ -20,7 +20,7 @@ import net.corda.testing.driver.InProcess import net.corda.testing.driver.internal.InProcessImpl import net.corda.testing.node.ClusterSpec import net.corda.testing.node.NotarySpec -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.startFlow import org.junit.Test import java.util.* import kotlin.test.assertEquals @@ -41,20 +41,20 @@ class RaftNotaryServiceTests { val firstTxBuilder = TransactionBuilder(defaultNotaryIdentity) .addInputState(inputState) - .addCommand(dummyCommand(bankA.services.myInfo.chooseIdentity().owningKey)) + .addCommand(dummyCommand(bankA.services.myInfo.singleIdentity().owningKey)) val firstSpendTx = bankA.services.signInitialTransaction(firstTxBuilder) - val firstSpend = bankA.services.startFlow(NotaryFlow.Client(firstSpendTx)) + val firstSpend = bankA.startFlow(NotaryFlow.Client(firstSpendTx)) firstSpend.getOrThrow() val secondSpendBuilder = TransactionBuilder(defaultNotaryIdentity).withItems(inputState).run { - val dummyState = DummyContract.SingleOwnerState(0, bankA.services.myInfo.chooseIdentity()) + val dummyState = DummyContract.SingleOwnerState(0, bankA.services.myInfo.singleIdentity()) addOutputState(dummyState, DummyContract.PROGRAM_ID) - addCommand(dummyCommand(bankA.services.myInfo.chooseIdentity().owningKey)) + addCommand(dummyCommand(bankA.services.myInfo.singleIdentity().owningKey)) this } val secondSpendTx = bankA.services.signInitialTransaction(secondSpendBuilder) - val secondSpend = bankA.services.startFlow(NotaryFlow.Client(secondSpendTx)) + val secondSpend = bankA.startFlow(NotaryFlow.Client(secondSpendTx)) val ex = assertFailsWith(NotaryException::class) { secondSpend.getOrThrow() } val error = ex.error as NotaryError.Conflict @@ -65,7 +65,7 @@ class RaftNotaryServiceTests { private fun issueState(nodeHandle: InProcess, notary: Party): StateAndRef<*> { return (nodeHandle as InProcessImpl).database.transaction { - val builder = DummyContract.generateInitial(Random().nextInt(), notary, nodeHandle.services.myInfo.chooseIdentity().ref(0)) + val builder = DummyContract.generateInitial(Random().nextInt(), notary, nodeHandle.services.myInfo.singleIdentity().ref(0)) val stx = nodeHandle.services.signInitialTransaction(builder) nodeHandle.services.recordTransactions(stx) StateAndRef(builder.outputStates().first(), StateRef(stx.id, 0)) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/network/NetworkMapTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/network/NetworkMapTest.kt index a8c0f5d99b..a156141766 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/network/NetworkMapTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/network/NetworkMapTest.kt @@ -16,6 +16,7 @@ import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.driver.NodeHandle import net.corda.testing.driver.PortAllocation +import net.corda.testing.driver.internal.RandomFree import net.corda.testing.node.internal.CompatibilityZoneParams import net.corda.testing.node.internal.internalDriver import net.corda.testing.node.internal.network.NetworkMapServer @@ -35,7 +36,7 @@ class NetworkMapTest { val testSerialization = SerializationEnvironmentRule(true) private val cacheTimeout = 1.seconds - private val portAllocation = PortAllocation.RandomFree + private val portAllocation = RandomFree private lateinit var networkMapServer: NetworkMapServer private lateinit var compatibilityZone: CompatibilityZoneParams diff --git a/node/src/integration-test/kotlin/net/corda/node/services/network/NodeInfoWatcherTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/network/NodeInfoWatcherTest.kt index 2d54eca863..07ad4bf3a3 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/network/NodeInfoWatcherTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/network/NodeInfoWatcherTest.kt @@ -12,7 +12,7 @@ import net.corda.nodeapi.internal.network.NodeInfoFilesCopier import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.internal.createNodeInfoAndSigned -import net.corda.testing.node.MockKeyManagementService +import net.corda.testing.node.internal.MockKeyManagementService import net.corda.testing.node.makeTestIdentityService import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.contentOf diff --git a/node/src/integration-test/kotlin/net/corda/node/services/network/PersistentNetworkMapCacheTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/network/PersistentNetworkMapCacheTest.kt index 8f7790b0e2..68103c2c7a 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/network/PersistentNetworkMapCacheTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/network/PersistentNetworkMapCacheTest.kt @@ -32,7 +32,7 @@ class PersistentNetworkMapCacheTest : NodeBasedTest() { val nodes = startNodesWithPort(partiesList) nodes.forEach { infos.add(it.info) - addressesMap[it.info.chooseIdentity().name] = it.info.addresses[0] + addressesMap[it.info.singleIdentity().name] = it.info.addresses[0] it.dispose() // We want them to communicate with NetworkMapService to save data to cache. } } @@ -81,7 +81,7 @@ class PersistentNetworkMapCacheTest : NodeBasedTest() { val alice = startNodesWithPort(listOf(ALICE))[0] val netCache = alice.services.networkMapCache alice.database.transaction { - val res = netCache.getNodeByLegalIdentity(alice.info.chooseIdentity()) + val res = netCache.getNodeByLegalIdentity(alice.info.singleIdentity()) assertEquals(alice.info, res) val res2 = netCache.getNodeByLegalName(DUMMY_REGULATOR.name) assertEquals(infos.singleOrNull { DUMMY_REGULATOR.name in it.legalIdentities.map { it.name } }, res2) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt index 8ccab804c9..253f49aa0e 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt @@ -10,6 +10,7 @@ import net.corda.node.testsupport.withKeyStores import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver +import net.corda.testing.driver.internal.RandomFree import net.corda.testing.internal.useSslRpcOverrides import net.corda.testing.node.User import org.assertj.core.api.Assertions.assertThat @@ -33,7 +34,7 @@ class RpcSslTest { withKeyStores(server, client) { nodeSslOptions, clientSslOptions -> var successful = false - driver(DriverParameters(isDebug = true, startNodesInProcess = true, portAllocation = PortAllocation.RandomFree)) { + driver(DriverParameters(isDebug = true, startNodesInProcess = true, portAllocation = RandomFree)) { startNode(rpcUsers = listOf(user), customOverrides = nodeSslOptions.useSslRpcOverrides()).getOrThrow().use { node -> createCordaRPCClientWithSsl(node.rpcAddress, sslConfiguration = clientSslOptions).start(user.username, user.password).use { connection -> connection.proxy.apply { @@ -52,7 +53,7 @@ class RpcSslTest { fun rpc_client_not_using_ssl() { val user = User("mark", "dadada", setOf(all())) var successful = false - driver(DriverParameters(isDebug = true, startNodesInProcess = true, portAllocation = PortAllocation.RandomFree)) { + driver(DriverParameters(isDebug = true, startNodesInProcess = true, portAllocation = RandomFree)) { startNode(rpcUsers = listOf(user)).getOrThrow().use { node -> CordaRPCClient(node.rpcAddress).start(user.username, user.password).use { connection -> connection.proxy.apply { diff --git a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt index 4322161a16..1b7e5a7f96 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt @@ -7,11 +7,11 @@ import net.corda.core.flows.InitiatingFlow import net.corda.core.identity.Party import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.NodeBasedTest -import net.corda.testing.node.startFlow import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME +import net.corda.testing.node.internal.startFlow import org.assertj.core.api.Assertions.assertThat import org.junit.Test @@ -22,7 +22,7 @@ class FlowVersioningTest : NodeBasedTest() { val bob = startNode(BOB_NAME, platformVersion = 3) bob.internals.installCoreFlow(PretendInitiatingCoreFlow::class, ::PretendInitiatedCoreFlow) val (alicePlatformVersionAccordingToBob, bobPlatformVersionAccordingToAlice) = alice.services.startFlow( - PretendInitiatingCoreFlow(bob.info.chooseIdentity())).getOrThrow() + PretendInitiatingCoreFlow(bob.info.singleIdentity())).resultFuture.getOrThrow() assertThat(alicePlatformVersionAccordingToBob).isEqualTo(2) assertThat(bobPlatformVersionAccordingToAlice).isEqualTo(3) } diff --git a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt index aa007be6d7..b0d40d62cb 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt @@ -17,6 +17,7 @@ import net.corda.testing.core.* import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver +import net.corda.testing.driver.internal.RandomFree import net.corda.testing.node.User import org.junit.Test import kotlin.test.assertEquals @@ -78,7 +79,7 @@ class LargeTransactionsTest { startNodesInProcess = true, extraCordappPackagesToScan = listOf("net.corda.testing.contracts"), networkParameters = testNetworkParameters(maxTransactionSize = 13.MB.toInt()), - portAllocation = PortAllocation.RandomFree)) { + portAllocation = RandomFree)) { val rpcUser = User("admin", "admin", setOf("ALL")) val (alice, _) = listOf(ALICE_NAME, BOB_NAME).map { startNode(providedName = it, rpcUsers = listOf(rpcUser)) }.transpose().getOrThrow() CordaRPCClient(alice.rpcAddress).use(rpcUser.username, rpcUser.password) { 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 cacf677ed7..44da2d4e7e 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 @@ -23,10 +23,10 @@ import net.corda.nodeapi.internal.config.SSLConfiguration import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.node.User -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.configureTestSSL import net.corda.testing.node.internal.NodeBasedTest -import net.corda.testing.node.startFlow +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.SimpleString @@ -189,9 +189,9 @@ abstract class MQSecurityTest : NodeBasedTest() { protected fun startBobAndCommunicateWithAlice(): Party { val bob = startNode(BOB_NAME) bob.registerInitiatedFlow(ReceiveFlow::class.java) - val bobParty = bob.info.chooseIdentity() + val bobParty = bob.info.singleIdentity() // Perform a protocol exchange to force the peer queue to be created - alice.services.startFlow(SendFlow(bobParty, 0)).getOrThrow() + alice.services.startFlow(SendFlow(bobParty, 0)).resultFuture.getOrThrow() return bobParty } diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMQSecurityTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMQSecurityTest.kt index df8970ff65..223324938b 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMQSecurityTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMQSecurityTest.kt @@ -6,7 +6,7 @@ import net.corda.nodeapi.RPCApi import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.P2P_PREFIX import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.PEERS_PREFIX import net.corda.testing.core.BOB_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import org.junit.Test /** @@ -16,7 +16,7 @@ import org.junit.Test abstract class P2PMQSecurityTest : MQSecurityTest() { @Test fun `consume message from P2P queue`() { - assertConsumeAttackFails("$P2P_PREFIX${alice.info.chooseIdentity().owningKey.toStringShort()}") + assertConsumeAttackFails("$P2P_PREFIX${alice.info.singleIdentity().owningKey.toStringShort()}") } @Test @@ -34,7 +34,7 @@ abstract class P2PMQSecurityTest : MQSecurityTest() { @Test fun `create queue for peer which has not been communicated with`() { val bob = startNode(BOB_NAME) - assertAllQueueCreationAttacksFail("$PEERS_PREFIX${bob.info.chooseIdentity().owningKey.toStringShort()}") + assertAllQueueCreationAttacksFail("$PEERS_PREFIX${bob.info.singleIdentity().owningKey.toStringShort()}") } @Test diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt index fb25de28ff..b1729281b1 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt @@ -16,11 +16,12 @@ import net.corda.node.services.messaging.MessagingService import net.corda.node.services.messaging.ReceivedMessage import net.corda.node.services.messaging.send import net.corda.testing.core.ALICE_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverDSL import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.InProcess import net.corda.testing.driver.driver +import net.corda.testing.driver.internal.internalServices import net.corda.testing.node.ClusterSpec import net.corda.testing.node.NotarySpec import org.assertj.core.api.Assertions.assertThat @@ -50,7 +51,7 @@ class P2PMessagingTest { val alice = startAlice() val serviceAddress = alice.services.networkMapCache.run { val notaryParty = notaryIdentities.randomOrNull()!! - alice.services.networkService.getAddressOfParty(getPartyInfo(notaryParty)!!) + alice.internalServices.networkService.getAddressOfParty(getPartyInfo(notaryParty)!!) } val responseMessage = "response" @@ -76,7 +77,7 @@ class P2PMessagingTest { val alice = startAlice() val serviceAddress = alice.services.networkMapCache.run { val notaryParty = notaryIdentities.randomOrNull()!! - alice.services.networkService.getAddressOfParty(getPartyInfo(notaryParty)!!) + alice.internalServices.networkService.getAddressOfParty(getPartyInfo(notaryParty)!!) } val responseMessage = "response" @@ -99,7 +100,7 @@ class P2PMessagingTest { val aliceRestarted = startAlice() val responseFuture = openFuture() - aliceRestarted.services.networkService.runOnNextMessage("test.response") { + aliceRestarted.internalServices.networkService.runOnNextMessage("test.response") { responseFuture.set(it.data.deserialize()) } val response = responseFuture.getOrThrow() @@ -142,8 +143,8 @@ class P2PMessagingTest { ) distributedServiceNodes.forEach { - val nodeName = it.services.myInfo.chooseIdentity().name - it.services.networkService.addMessageHandler("test.request") { netMessage, _ -> + val nodeName = it.services.myInfo.legalIdentitiesAndCerts.first().name + it.internalServices.networkService.addMessageHandler("test.request") { netMessage, _ -> crashingNodes.requestsReceived.incrementAndGet() crashingNodes.firstRequestReceived.countDown() // The node which receives the first request will ignore all requests @@ -155,8 +156,8 @@ class P2PMessagingTest { } else { println("sending response") val request = netMessage.data.deserialize() - val response = it.services.networkService.createMessage("test.response", responseMessage.serialize().bytes) - it.services.networkService.send(response, request.replyTo) + val response = it.internalServices.networkService.createMessage("test.response", responseMessage.serialize().bytes) + it.internalServices.networkService.send(response, request.replyTo) } } } @@ -169,7 +170,7 @@ class P2PMessagingTest { node.respondWith(node.services.myInfo) } val serviceAddress = originatingNode.services.networkMapCache.run { - originatingNode.services.networkService.getAddressOfParty(getPartyInfo(getNotary(serviceName)!!)!!) + originatingNode.internalServices.networkService.getAddressOfParty(getPartyInfo(getNotary(serviceName)!!)!!) } val participatingNodes = HashSet() // Try several times so that we can be fairly sure that any node not participating is not due to Artemis' selection @@ -185,19 +186,19 @@ class P2PMessagingTest { } private fun InProcess.respondWith(message: Any) { - services.networkService.addMessageHandler("test.request") { netMessage, _ -> + internalServices.networkService.addMessageHandler("test.request") { netMessage, _ -> val request = netMessage.data.deserialize() - val response = services.networkService.createMessage("test.response", message.serialize().bytes) - services.networkService.send(response, request.replyTo) + val response = internalServices.networkService.createMessage("test.response", message.serialize().bytes) + internalServices.networkService.send(response, request.replyTo) } } private fun InProcess.receiveFrom(target: MessageRecipients, retryId: Long? = null): CordaFuture { val response = openFuture() - services.networkService.runOnNextMessage("test.response") { netMessage -> + internalServices.networkService.runOnNextMessage("test.response") { netMessage -> response.set(netMessage.data.deserialize()) } - services.networkService.send("test.request", TestRequest(replyTo = services.networkService.myAddress), target, retryId = retryId) + internalServices.networkService.send("test.request", TestRequest(replyTo = internalServices.networkService.myAddress), target, retryId = retryId) return response } diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/RPCMQSecurityTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/RPCMQSecurityTest.kt index b9535b670b..9e0e7bbf09 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/RPCMQSecurityTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/RPCMQSecurityTest.kt @@ -7,7 +7,7 @@ import net.corda.nodeapi.RPCApi import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.P2P_PREFIX import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.PEERS_PREFIX import net.corda.testing.core.BOB_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import org.junit.Test /** @@ -17,7 +17,7 @@ import org.junit.Test abstract class RPCMQSecurityTest : MQSecurityTest() { @Test fun `consume message from P2P queue`() { - assertConsumeAttackFailsNonexistent("$P2P_PREFIX${alice.info.chooseIdentity().owningKey.toStringShort()}") + assertConsumeAttackFailsNonexistent("$P2P_PREFIX${alice.info.singleIdentity().owningKey.toStringShort()}") } @Test @@ -35,7 +35,7 @@ abstract class RPCMQSecurityTest : MQSecurityTest() { @Test fun `create queue for peer which has not been communicated with`() { val bob = startNode(BOB_NAME) - assertConsumeAttackFailsNonexistent("$PEERS_PREFIX${bob.info.chooseIdentity().owningKey.toBase58String()}") + assertConsumeAttackFailsNonexistent("$PEERS_PREFIX${bob.info.singleIdentity().owningKey.toBase58String()}") } @Test diff --git a/node/src/integration-test/kotlin/net/corda/test/node/NodeStatePersistenceTests.kt b/node/src/integration-test/kotlin/net/corda/test/node/NodeStatePersistenceTests.kt index d22c318d05..18d0b2748d 100644 --- a/node/src/integration-test/kotlin/net/corda/test/node/NodeStatePersistenceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/test/node/NodeStatePersistenceTests.kt @@ -21,10 +21,11 @@ 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.testing.node.User -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver +import net.corda.testing.driver.internal.RandomFree import org.junit.Assume.assumeFalse import org.junit.Test import java.lang.management.ManagementFactory @@ -43,10 +44,10 @@ class NodeStatePersistenceTests { val user = User("mark", "dadada", setOf(startFlow(), invokeRpc("vaultQuery"))) val message = Message("Hello world!") - val stateAndRef: StateAndRef? = driver(DriverParameters(isDebug = true, startNodesInProcess = isQuasarAgentSpecified(), portAllocation = PortAllocation.RandomFree)) { + val stateAndRef: StateAndRef? = driver(DriverParameters(isDebug = true, startNodesInProcess = isQuasarAgentSpecified(), portAllocation = RandomFree)) { val nodeName = { val nodeHandle = startNode(rpcUsers = listOf(user)).getOrThrow() - val nodeName = nodeHandle.nodeInfo.chooseIdentity().name + val nodeName = nodeHandle.nodeInfo.singleIdentity().name // Ensure the notary node has finished starting up, before starting a flow that needs a notary defaultNotaryNode.getOrThrow() CordaRPCClient(nodeHandle.rpcAddress).start(user.username, user.password).use { @@ -77,10 +78,10 @@ class NodeStatePersistenceTests { val user = User("mark", "dadada", setOf(startFlow(), invokeRpc("vaultQuery"))) val message = Message("Hello world!") - val stateAndRef: StateAndRef? = driver(DriverParameters(isDebug = true, startNodesInProcess = isQuasarAgentSpecified(), portAllocation = PortAllocation.RandomFree)) { + val stateAndRef: StateAndRef? = driver(DriverParameters(isDebug = true, startNodesInProcess = isQuasarAgentSpecified(), portAllocation = RandomFree)) { val nodeName = { val nodeHandle = startNode(rpcUsers = listOf(user)).getOrThrow() - val nodeName = nodeHandle.nodeInfo.chooseIdentity().name + val nodeName = nodeHandle.nodeInfo.singleIdentity().name // Ensure the notary node has finished starting up, before starting a flow that needs a notary defaultNotaryNode.getOrThrow() CordaRPCClient(nodeHandle.rpcAddress).start(user.username, user.password).use { diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index 75ce1850d3..99bfc70399 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -40,6 +40,7 @@ import net.corda.testing.core.sequence import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode +import net.corda.testing.node.internal.InternalMockNodeParameters import net.corda.testing.node.testActor import org.apache.commons.io.IOUtils import org.assertj.core.api.Assertions.assertThatExceptionOfType @@ -80,7 +81,7 @@ class CordaRPCOpsImplTest { @Before fun setup() { mockNet = InternalMockNetwork(cordappPackages = listOf("net.corda.finance.contracts.asset")) - aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) + aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) rpc = SecureCordaRPCOps(aliceNode.services, aliceNode.smm, aliceNode.database, aliceNode.services) CURRENT_RPC_CONTEXT.set(RpcAuthContext(InvocationContext.rpc(testActor()), buildSubject("TEST_USER", emptySet()))) diff --git a/node/src/test/kotlin/net/corda/node/internal/NetworkParametersTest.kt b/node/src/test/kotlin/net/corda/node/internal/NetworkParametersTest.kt index 5ee95ed7e7..1042a6d49e 100644 --- a/node/src/test/kotlin/net/corda/node/internal/NetworkParametersTest.kt +++ b/node/src/test/kotlin/net/corda/node/internal/NetworkParametersTest.kt @@ -13,9 +13,13 @@ import net.corda.core.node.NotaryInfo import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.DUMMY_NOTARY_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.node.* +import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.MOCK_VERSION_INFO +import net.corda.testing.node.internal.startFlow import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.After @@ -24,7 +28,7 @@ import java.nio.file.Path import kotlin.test.assertFails class NetworkParametersTest { - private val mockNet = MockNetwork( + private val mockNet = InternalMockNetwork( emptyList(), MockNetworkParameters(networkSendManuallyPumped = true), notarySpecs = listOf(MockNetworkNotarySpec(DUMMY_NOTARY_NAME))) @@ -37,7 +41,7 @@ class NetworkParametersTest { // Minimum Platform Version tests @Test fun `node shutdowns when on lower platform version than network`() { - val alice = mockNet.createUnstartedNode(MockNodeParameters(legalName = ALICE_NAME, forcedID = 100, version = MockServices.MOCK_VERSION_INFO.copy(platformVersion = 1))) + val alice = mockNet.createUnstartedNode(InternalMockNodeParameters(legalName = ALICE_NAME, forcedID = 100, version = MOCK_VERSION_INFO.copy(platformVersion = 1))) val aliceDirectory = mockNet.baseDirectory(100) val netParams = testNetworkParameters( notaries = listOf(NotaryInfo(mockNet.defaultNotaryIdentity, true)), @@ -48,7 +52,7 @@ class NetworkParametersTest { @Test fun `node works fine when on higher platform version`() { - val alice = mockNet.createUnstartedNode(MockNodeParameters(legalName = ALICE_NAME, forcedID = 100, version = MockServices.MOCK_VERSION_INFO.copy(platformVersion = 2))) + val alice = mockNet.createUnstartedNode(InternalMockNodeParameters(legalName = ALICE_NAME, forcedID = 100, version = MOCK_VERSION_INFO.copy(platformVersion = 2))) val aliceDirectory = mockNet.baseDirectory(100) val netParams = testNetworkParameters( notaries = listOf(NotaryInfo(mockNet.defaultNotaryIdentity, true)), @@ -60,14 +64,14 @@ class NetworkParametersTest { // Notaries tests @Test fun `choosing notary not specified in network parameters will fail`() { - val fakeNotary = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME, configOverrides = { + val fakeNotary = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME, configOverrides = { val notary = NotaryConfig(false) doReturn(notary).whenever(it).notary})) - val fakeNotaryId = fakeNotary.info.chooseIdentity() + val fakeNotaryId = fakeNotary.info.singleIdentity() val alice = mockNet.createPartyNode(ALICE_NAME) assertThat(alice.services.networkMapCache.notaryIdentities).doesNotContain(fakeNotaryId) assertFails { - alice.services.startFlow(CashIssueFlow(500.DOLLARS, OpaqueBytes.of(0x01), fakeNotaryId)).getOrThrow() + alice.services.startFlow(CashIssueFlow(500.DOLLARS, OpaqueBytes.of(0x01), fakeNotaryId)).resultFuture.getOrThrow() } } diff --git a/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt b/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt index 6981ac1b2f..7998a9df32 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt @@ -4,7 +4,7 @@ import net.corda.core.messaging.AllPossibleRecipients import net.corda.node.services.messaging.Message import net.corda.node.services.messaging.TopicStringValidator import net.corda.testing.internal.rigorousMock -import net.corda.testing.node.MockNetwork +import net.corda.testing.node.internal.InternalMockNetwork import org.junit.After import org.junit.Before import org.junit.Test @@ -14,11 +14,11 @@ import kotlin.test.assertFails import kotlin.test.assertTrue class InMemoryMessagingTests { - lateinit var mockNet: MockNetwork + lateinit var mockNet: InternalMockNetwork @Before fun setUp() { - mockNet = MockNetwork(emptyList()) + mockNet = InternalMockNetwork(emptyList()) } @After diff --git a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt index 5395c0453d..4bd1dddbc0 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt @@ -45,11 +45,14 @@ import net.corda.testing.internal.LogHelper 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.rigorousMock import net.corda.testing.internal.vault.VaultFiller import net.corda.testing.node.* import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.InternalMockNodeParameters import net.corda.testing.node.internal.pumpReceive +import net.corda.testing.node.internal.startFlow import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before @@ -278,7 +281,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) { // ... bring the node back up ... the act of constructing the SMM will re-register the message handlers // that Bob was waiting on before the reboot occurred. - bobNode = mockNet.createNode(MockNodeParameters(bobAddr.id, BOB_NAME)) + bobNode = mockNet.createNode(InternalMockNodeParameters(bobAddr.id, BOB_NAME)) // Find the future representing the result of this state machine again. val bobFuture = bobNode.smm.findStateMachines(BuyerAcceptor::class.java).single().second @@ -312,7 +315,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) { // of gets and puts. private fun makeNodeWithTracking(name: CordaX500Name): StartedNode { // Create a node in the mock network ... - return mockNet.createNode(MockNodeParameters(legalName = name), nodeFactory = { args -> + return mockNet.createNode(InternalMockNodeParameters(legalName = name), nodeFactory = { args -> object : InternalMockNetwork.MockNode(args) { // That constructs a recording tx storage override fun makeTransactionStorage(database: CordaPersistence, transactionCacheSizeBytes: Long): WritableTransactionStorage { @@ -537,7 +540,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) { val buyerFlows: Observable> = buyerNode.registerInitiatedFlow(BuyerAcceptor::class.java) val firstBuyerFiber = buyerFlows.toFuture().map { it.stateMachine } val seller = SellerInitiator(buyer, notary, assetToSell, 1000.DOLLARS, anonymous) - val sellerResult = sellerNode.services.startFlow(seller) + val sellerResult = sellerNode.services.startFlow(seller).resultFuture return RunResult(firstBuyerFiber, sellerResult, seller.stateMachine.id) } diff --git a/node/src/test/kotlin/net/corda/node/modes/draining/ScheduledFlowsDrainingModeTest.kt b/node/src/test/kotlin/net/corda/node/modes/draining/ScheduledFlowsDrainingModeTest.kt index 589fcdd832..7e030e8000 100644 --- a/node/src/test/kotlin/net/corda/node/modes/draining/ScheduledFlowsDrainingModeTest.kt +++ b/node/src/test/kotlin/net/corda/node/modes/draining/ScheduledFlowsDrainingModeTest.kt @@ -16,8 +16,8 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.dummyCommand import net.corda.testing.core.singleIdentity -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.InternalMockNodeParameters import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before @@ -48,8 +48,8 @@ class ScheduledFlowsDrainingModeTest { @Before fun setup() { mockNet = InternalMockNetwork(cordappPackages = listOf("net.corda.testing.contracts"), threadPerNode = true) - aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) + aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) + bobNode = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME)) notary = mockNet.defaultNotaryIdentity alice = aliceNode.info.singleIdentity() bob = bobNode.info.singleIdentity() diff --git a/node/src/test/kotlin/net/corda/node/services/NotaryChangeTests.kt b/node/src/test/kotlin/net/corda/node/services/NotaryChangeTests.kt index 9851246573..6ac3f82c7e 100644 --- a/node/src/test/kotlin/net/corda/node/services/NotaryChangeTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/NotaryChangeTests.kt @@ -66,7 +66,7 @@ class NotaryChangeTests { val state = issueMultiPartyState(clientNodeA, clientNodeB, oldNotaryNode, oldNotaryParty) val newNotary = newNotaryParty val flow = NotaryChangeFlow(state, newNotary) - val future = clientNodeA.services.startFlow(flow) + val future = clientNodeA.startFlow(flow) mockNet.runNetwork() @@ -82,7 +82,7 @@ class NotaryChangeTests { val state = issueMultiPartyState(clientNodeA, clientNodeB, oldNotaryNode, oldNotaryParty) val newEvilNotary = getTestPartyAndCertificate(CordaX500Name(organisation = "Evil R3", locality = "London", country = "GB"), generateKeyPair().public) val flow = NotaryChangeFlow(state, newEvilNotary.party) - val future = clientNodeA.services.startFlow(flow) + val future = clientNodeA.startFlow(flow) mockNet.runNetwork() @@ -98,7 +98,7 @@ class NotaryChangeTests { val state = StateAndRef(issueTx.outputs.first(), StateRef(issueTx.id, 0)) val newNotary = newNotaryParty val flow = NotaryChangeFlow(state, newNotary) - val future = clientNodeA.services.startFlow(flow) + val future = clientNodeA.startFlow(flow) mockNet.runNetwork() val newState = future.getOrThrow() assertEquals(newState.state.notary, newNotary) @@ -143,18 +143,18 @@ class NotaryChangeTests { private fun changeNotary(movedState: StateAndRef, node: StartedMockNode, newNotary: Party): StateAndRef { val flow = NotaryChangeFlow(movedState, newNotary) - val future = node.services.startFlow(flow) + val future = node.startFlow(flow) mockNet.runNetwork() return future.getOrThrow() } private fun moveState(state: StateAndRef, fromNode: StartedMockNode, toNode: StartedMockNode): StateAndRef { - val tx = DummyContract.move(state, toNode.info.chooseIdentity()) + val tx = DummyContract.move(state, toNode.info.singleIdentity()) val stx = fromNode.services.signInitialTransaction(tx) val notaryFlow = NotaryFlow.Client(stx) - val future = fromNode.services.startFlow(notaryFlow) + val future = fromNode.startFlow(notaryFlow) mockNet.runNetwork() val notarySignature = future.getOrThrow() @@ -200,7 +200,7 @@ fun issueState(services: ServiceHub, nodeIdentity: Party, notaryIdentity: Party) } fun issueMultiPartyState(nodeA: StartedMockNode, nodeB: StartedMockNode, notaryNode: StartedMockNode, notaryIdentity: Party): StateAndRef { - val participants = listOf(nodeA.info.chooseIdentity(), nodeB.info.chooseIdentity()) + val participants = listOf(nodeA.info.singleIdentity(), nodeB.info.singleIdentity()) val state = TransactionState( DummyContract.MultiOwnerState(0, participants), DummyContract.PROGRAM_ID, notaryIdentity) diff --git a/node/src/test/kotlin/net/corda/node/services/events/ScheduledFlowTests.kt b/node/src/test/kotlin/net/corda/node/services/events/ScheduledFlowTests.kt index 96a3b63a87..5aea06bcfb 100644 --- a/node/src/test/kotlin/net/corda/node/services/events/ScheduledFlowTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/events/ScheduledFlowTests.kt @@ -25,10 +25,10 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.dummyCommand import net.corda.testing.core.singleIdentity -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Assert.* import org.junit.Before @@ -104,8 +104,8 @@ class ScheduledFlowTests { @Before fun setup() { mockNet = InternalMockNetwork(cordappPackages = listOf("net.corda.testing.contracts"), threadPerNode = true) - aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) + aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) + bobNode = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME)) notary = mockNet.defaultNotaryIdentity alice = aliceNode.info.singleIdentity() bob = bobNode.info.singleIdentity() @@ -144,8 +144,8 @@ class ScheduledFlowTests { val N = 100 val futures = mutableListOf>() for (i in 0 until N) { - futures.add(aliceNode.services.startFlow(InsertInitialStateFlow(bob, notary))) - futures.add(bobNode.services.startFlow(InsertInitialStateFlow(alice, notary))) + futures.add(aliceNode.services.startFlow(InsertInitialStateFlow(bob, notary)).resultFuture) + futures.add(bobNode.services.startFlow(InsertInitialStateFlow(alice, notary)).resultFuture) } mockNet.waitQuiescent() 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 0ea623a398..08e3af6ef9 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 @@ -17,8 +17,8 @@ import net.corda.nodeapi.internal.persistence.DatabaseConfig import net.corda.testing.core.* import net.corda.testing.internal.LogHelper import net.corda.testing.internal.rigorousMock -import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties +import net.corda.testing.node.internal.MOCK_VERSION_INFO import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.After diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt index 03bb1a1667..031945431f 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt @@ -6,9 +6,9 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.node.services.api.NetworkMapCacheInternal import net.corda.testing.core.getTestPartyAndCertificate -import net.corda.testing.node.MockNodeParameters import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.InternalMockNodeParameters import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Test @@ -28,12 +28,12 @@ class NetworkMapCacheTest { @Test fun `key collision`() { val entropy = BigInteger.valueOf(24012017L) - val aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME, entropyRoot = entropy)) + val aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME, entropyRoot = entropy)) val alice = aliceNode.info.singleIdentity() // Node A currently knows only about itself, so this returns node A assertEquals(aliceNode.services.networkMapCache.getNodesByLegalIdentityKey(alice.owningKey).singleOrNull(), aliceNode.info) - val bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME, entropyRoot = entropy)) + val bobNode = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME, entropyRoot = entropy)) val bob = bobNode.info.singleIdentity() assertEquals(alice, bob) 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 ef7f1f76c7..f10e35724e 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 @@ -34,6 +34,7 @@ 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.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.DatabaseConfig @@ -121,7 +122,7 @@ class HibernateConfigurationTest { override val vaultService = NodeVaultService(Clock.systemUTC(), keyManagementService, servicesForResolution, hibernateConfig) override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable) { for (stx in txs) { - validatedTransactions.addTransaction(stx) + (validatedTransactions as WritableTransactionStorage).addTransaction(stx) } // Refactored to use notifyAll() as we have no other unit test for that method with multiple transactions. vaultService.notifyAll(statesToRecord, txs.map { it.tx }) diff --git a/node/src/test/kotlin/net/corda/node/services/rpc/ArtemisRpcTests.kt b/node/src/test/kotlin/net/corda/node/services/rpc/ArtemisRpcTests.kt index 1898743c8b..47a31bf0de 100644 --- a/node/src/test/kotlin/net/corda/node/services/rpc/ArtemisRpcTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/rpc/ArtemisRpcTests.kt @@ -19,6 +19,7 @@ import net.corda.nodeapi.internal.config.SSLConfiguration import net.corda.nodeapi.internal.config.User import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.driver.PortAllocation +import net.corda.testing.driver.internal.RandomFree import org.apache.activemq.artemis.api.core.ActiveMQConnectionTimedOutException import org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl @@ -31,7 +32,7 @@ import java.nio.file.Path import kotlin.reflect.KClass class ArtemisRpcTests { - private val ports: PortAllocation = PortAllocation.RandomFree + private val ports: PortAllocation = RandomFree private val user = User("mark", "dadada", setOf(all())) private val users = listOf(user) diff --git a/node/src/test/kotlin/net/corda/node/services/schema/NodeSchemaServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/schema/NodeSchemaServiceTest.kt index aa31cf7dd8..a14cd60e5c 100644 --- a/node/src/test/kotlin/net/corda/node/services/schema/NodeSchemaServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/schema/NodeSchemaServiceTest.kt @@ -12,11 +12,10 @@ import net.corda.node.services.api.ServiceHubInternal import net.corda.node.services.schema.NodeSchemaService.NodeCoreV1 import net.corda.node.services.schema.NodeSchemaService.NodeNotaryV1 import net.corda.testing.driver.DriverParameters -import net.corda.testing.driver.InProcess import net.corda.testing.driver.driver import net.corda.testing.driver.internal.InProcessImpl import net.corda.testing.internal.vault.DummyLinearStateSchemaV1 -import net.corda.testing.node.MockNetwork +import net.corda.testing.node.internal.InternalMockNetwork import org.hibernate.annotations.Cascade import org.hibernate.annotations.CascadeType import org.junit.Ignore @@ -32,7 +31,7 @@ class NodeSchemaServiceTest { */ @Test fun `registering custom schemas for testing with MockNode`() { - val mockNet = MockNetwork(cordappPackages = listOf(DummyLinearStateSchemaV1::class.packageName)) + val mockNet = InternalMockNetwork(cordappPackages = listOf(DummyLinearStateSchemaV1::class.packageName)) val mockNode = mockNet.createNode() val schemaService = mockNode.services.schemaService assertTrue(schemaService.schemaOptions.containsKey(DummyLinearStateSchemaV1)) @@ -41,7 +40,7 @@ class NodeSchemaServiceTest { @Test fun `check node runs with minimal core schema set`() { - val mockNet = MockNetwork(cordappPackages = emptyList()) + val mockNet = InternalMockNetwork(cordappPackages = emptyList()) val mockNode = mockNet.createNode() val schemaService = mockNode.services.schemaService @@ -53,7 +52,7 @@ class NodeSchemaServiceTest { @Test fun `check node runs inclusive of notary node schema set`() { - val mockNet = MockNetwork(cordappPackages = emptyList()) + val mockNet = InternalMockNetwork(cordappPackages = emptyList()) val mockNotaryNode = mockNet.notaryNodes.first() val schemaService = mockNotaryNode.services.schemaService diff --git a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt index 9797fca399..55d7073e5b 100644 --- a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt @@ -34,11 +34,8 @@ import net.corda.testing.core.* import net.corda.testing.internal.LogHelper import net.corda.testing.node.InMemoryMessagingNetwork.MessageTransfer import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin -import net.corda.testing.node.MockNodeParameters -import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.* import net.corda.testing.node.internal.InternalMockNetwork.MockNode -import net.corda.testing.node.internal.pumpReceive -import net.corda.testing.node.internal.startFlow import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType @@ -80,8 +77,8 @@ class FlowFrameworkTests { cordappPackages = listOf("net.corda.finance.contracts", "net.corda.testing.contracts"), servicePeerAllocationStrategy = RoundRobin() ) - aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) + aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) + bobNode = mockNet.createNode(InternalMockNodeParameters(legalName = BOB_NAME)) receivedSessionMessagesObservable().forEach { receivedSessionMessages += it } @@ -166,7 +163,7 @@ class FlowFrameworkTests { var sentCount = 0 mockNet.messagingNetwork.sentMessages.toSessionTransfers().filter { it.isPayloadTransfer }.forEach { sentCount++ } - val charlieNode = mockNet.createNode(MockNodeParameters(legalName = CHARLIE_NAME)) + val charlieNode = mockNet.createNode(InternalMockNodeParameters(legalName = CHARLIE_NAME)) val secondFlow = charlieNode.registerFlowFactory(PingPongFlow::class) { PingPongFlow(it, payload2) } mockNet.runNetwork() val charlie = charlieNode.info.singleIdentity() @@ -185,7 +182,7 @@ class FlowFrameworkTests { assertEquals(1, bobNode.checkpointStorage.checkpoints().size) // confirm checkpoint bobNode.services.networkMapCache.clearNetworkMapCache() } - val node2b = mockNet.createNode(MockNodeParameters(bobNode.internals.id)) + val node2b = mockNet.createNode(InternalMockNodeParameters(bobNode.internals.id)) bobNode.internals.manuallyCloseDB() val (firstAgain, fut1) = node2b.getSingleFlow() // Run the network which will also fire up the second flow. First message should get deduped. So message data stays in sync. @@ -212,7 +209,7 @@ class FlowFrameworkTests { @Test fun `sending to multiple parties`() { - val charlieNode = mockNet.createNode(MockNodeParameters(legalName = CHARLIE_NAME)) + val charlieNode = mockNet.createNode(InternalMockNodeParameters(legalName = CHARLIE_NAME)) val charlie = charlieNode.info.singleIdentity() bobNode.registerFlowFactory(SendFlow::class) { InitiatedReceiveFlow(it).nonTerminating() } charlieNode.registerFlowFactory(SendFlow::class) { InitiatedReceiveFlow(it).nonTerminating() } @@ -244,7 +241,7 @@ class FlowFrameworkTests { @Test fun `receiving from multiple parties`() { - val charlieNode = mockNet.createNode(MockNodeParameters(legalName = CHARLIE_NAME)) + val charlieNode = mockNet.createNode(InternalMockNodeParameters(legalName = CHARLIE_NAME)) val charlie = charlieNode.info.singleIdentity() val bobPayload = "Test 1" val charliePayload = "Test 2" @@ -400,7 +397,7 @@ class FlowFrameworkTests { @Test fun `FlowException propagated in invocation chain`() { - val charlieNode = mockNet.createNode(MockNodeParameters(legalName = CHARLIE_NAME)) + val charlieNode = mockNet.createNode(InternalMockNodeParameters(legalName = CHARLIE_NAME)) val charlie = charlieNode.info.singleIdentity() charlieNode.registerFlowFactory(ReceiveFlow::class) { ExceptionFlow { MyFlowException("Chain") } } @@ -414,7 +411,7 @@ class FlowFrameworkTests { @Test fun `FlowException thrown and there is a 3rd unrelated party flow`() { - val charlieNode = mockNet.createNode(MockNodeParameters(legalName = CHARLIE_NAME)) + val charlieNode = mockNet.createNode(InternalMockNodeParameters(legalName = CHARLIE_NAME)) val charlie = charlieNode.info.singleIdentity() // Bob will send its payload and then block waiting for the receive from Alice. Meanwhile Alice will move @@ -662,7 +659,7 @@ class FlowFrameworkTests { private inline fun > StartedNode.restartAndGetRestoredFlow() = internals.run { disableDBCloseOnStop() // Handover DB to new node copy stop() - val newNode = mockNet.createNode(MockNodeParameters(id, configuration.myLegalName)) + val newNode = mockNet.createNode(InternalMockNodeParameters(id, configuration.myLegalName)) newNode.internals.acceptableLiveFiberCountOnStop = 1 manuallyCloseDB() mockNet.runNetwork() @@ -723,9 +720,9 @@ class FlowFrameworkTests { } private fun Observable.toSessionTransfers(): Observable { - return filter { it.message.topic == StateMachineManagerImpl.sessionTopic }.map { + return filter { it.getMessage().topic == StateMachineManagerImpl.sessionTopic }.map { val from = it.sender.id - val message = it.message.data.deserialize() + val message = it.messageData.deserialize() SessionTransfer(from, sanitise(message), it.recipients) } } 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 6b06f8a50c..cf90d50f59 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 @@ -7,7 +7,6 @@ import net.corda.core.identity.Party import net.corda.core.internal.InputStreamAndHash import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.getOrThrow -import net.corda.node.services.api.StartedNodeServices import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyState @@ -15,9 +14,9 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.dummyCommand import net.corda.testing.core.singleIdentity +import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNodeParameters -import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.StartedMockNode import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before @@ -26,22 +25,20 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith class MaxTransactionSizeTests { - private lateinit var mockNet: InternalMockNetwork - private lateinit var notaryServices: StartedNodeServices - private lateinit var aliceServices: StartedNodeServices + private lateinit var mockNet: MockNetwork + private lateinit var notaryNode: StartedMockNode + private lateinit var aliceNode: StartedMockNode + private lateinit var bobNode: StartedMockNode private lateinit var notary: Party private lateinit var alice: Party private lateinit var bob: Party @Before fun setup() { - mockNet = InternalMockNetwork( - listOf("net.corda.testing.contracts", "net.corda.node.services.transactions"), - networkParameters = testNetworkParameters(maxTransactionSize = 3_000_000)) - val aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - val bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) - notaryServices = mockNet.defaultNotaryNode.services - aliceServices = aliceNode.services + mockNet = MockNetwork(listOf("net.corda.testing.contracts", "net.corda.node.services.transactions"), networkParameters = testNetworkParameters(maxTransactionSize = 3_000_000)) + aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) + bobNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)) + notaryNode = mockNet.defaultNotaryNode notary = mockNet.defaultNotaryIdentity alice = aliceNode.info.singleIdentity() bob = bobNode.info.singleIdentity() @@ -59,16 +56,16 @@ class MaxTransactionSizeTests { val bigFile2 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 1) val bigFile3 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 2) val bigFile4 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 3) - val flow = aliceServices.database.transaction { - val hash1 = aliceServices.attachments.importAttachment(bigFile1.inputStream) - val hash2 = aliceServices.attachments.importAttachment(bigFile2.inputStream) - val hash3 = aliceServices.attachments.importAttachment(bigFile3.inputStream) - val hash4 = aliceServices.attachments.importAttachment(bigFile4.inputStream) + 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) assertEquals(hash1, bigFile1.sha256) SendLargeTransactionFlow(notary, bob, hash1, hash2, hash3, hash4) } val exception = assertFailsWith { - val future = aliceServices.startFlow(flow) + val future = aliceNode.startFlow(flow) mockNet.runNetwork() future.getOrThrow() } @@ -82,16 +79,16 @@ class MaxTransactionSizeTests { val bigFile2 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 1) val bigFile3 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 2) val bigFile4 = InputStreamAndHash.createInMemoryTestZip(1024 * 1024, 3) - val flow = aliceServices.database.transaction { - val hash1 = aliceServices.attachments.importAttachment(bigFile1.inputStream) - val hash2 = aliceServices.attachments.importAttachment(bigFile2.inputStream) - val hash3 = aliceServices.attachments.importAttachment(bigFile3.inputStream) - val hash4 = aliceServices.attachments.importAttachment(bigFile4.inputStream) + 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) assertEquals(hash1, bigFile1.sha256) SendLargeTransactionFlow(notary, bob, hash1, hash2, hash3, hash4, verify = false) } val ex = assertFailsWith { - val future = aliceServices.startFlow(flow) + val future = aliceNode.startFlow(flow) mockNet.runNetwork() future.getOrThrow() } diff --git a/node/src/test/kotlin/net/corda/node/services/transactions/NotaryServiceTests.kt b/node/src/test/kotlin/net/corda/node/services/transactions/NotaryServiceTests.kt index d37c5a3259..39ce8f8fe8 100644 --- a/node/src/test/kotlin/net/corda/node/services/transactions/NotaryServiceTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/transactions/NotaryServiceTests.kt @@ -7,13 +7,8 @@ import net.corda.core.crypto.Crypto import net.corda.core.crypto.SecureHash import net.corda.core.crypto.TransactionSignature import net.corda.core.crypto.sign -import net.corda.core.flows.NotaryError -import net.corda.core.flows.NotaryException -import net.corda.core.flows.NotaryFlow +import net.corda.core.flows.* import net.corda.core.identity.Party -import net.corda.core.flows.NotarisationPayload -import net.corda.core.flows.NotarisationRequest -import net.corda.core.flows.NotarisationRequestSignature import net.corda.core.internal.generateSignature import net.corda.core.messaging.MessageRecipients import net.corda.core.node.ServiceHub @@ -24,14 +19,14 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.seconds -import net.corda.node.services.api.StartedNodeServices +import net.corda.node.internal.StartedNode import net.corda.node.services.messaging.Message import net.corda.node.services.statemachine.InitialSessionMessage import net.corda.testing.contracts.DummyContract import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.dummyCommand import net.corda.testing.core.singleIdentity -import net.corda.testing.node.* +import net.corda.testing.node.internal.* import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before @@ -43,21 +38,19 @@ import kotlin.test.assertFailsWith import kotlin.test.assertTrue class NotaryServiceTests { - private lateinit var mockNet: MockNetwork - private lateinit var notaryServices: StartedNodeServices - private lateinit var aliceNode: StartedMockNode - private lateinit var aliceServices: StartedNodeServices + private lateinit var mockNet: InternalMockNetwork + private lateinit var notaryServices: ServiceHub + private lateinit var aliceNode: StartedNode private lateinit var notary: Party private lateinit var alice: Party @Before fun setup() { - mockNet = MockNetwork(cordappPackages = listOf("net.corda.testing.contracts")) - aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - aliceServices = aliceNode.services + mockNet = InternalMockNetwork(cordappPackages = listOf("net.corda.testing.contracts")) + aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) notaryServices = mockNet.defaultNotaryNode.services //TODO get rid of that notary = mockNet.defaultNotaryIdentity - alice = aliceServices.myInfo.singleIdentity() + alice = aliceNode.services.myInfo.singleIdentity() } @After @@ -68,12 +61,12 @@ class NotaryServiceTests { @Test fun `should sign a unique transaction with a valid time-window`() { val stx = run { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) .setTimeWindow(Instant.now(), 30.seconds) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val future = runNotaryClient(stx) @@ -84,11 +77,11 @@ class NotaryServiceTests { @Test fun `should sign a unique transaction without a time-window`() { val stx = run { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val future = runNotaryClient(stx) @@ -99,12 +92,12 @@ class NotaryServiceTests { @Test fun `should report error for transaction with an invalid time-window`() { val stx = run { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) .setTimeWindow(Instant.now().plusSeconds(3600), 30.seconds) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val future = runNotaryClient(stx) @@ -116,17 +109,17 @@ class NotaryServiceTests { @Test fun `should sign identical transaction multiple times (notarisation is idempotent)`() { val stx = run { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val firstAttempt = NotaryFlow.Client(stx) val secondAttempt = NotaryFlow.Client(stx) - val f1 = aliceServices.startFlow(firstAttempt) - val f2 = aliceServices.startFlow(secondAttempt) + val f1 = aliceNode.services.startFlow(firstAttempt).resultFuture + val f2 = aliceNode.services.startFlow(secondAttempt).resultFuture mockNet.runNetwork() @@ -144,29 +137,29 @@ class NotaryServiceTests { @Test fun `should report conflict when inputs are reused across transactions`() { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val stx = run { val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val stx2 = run { val tx = TransactionBuilder(notary) .addInputState(inputState) - .addInputState(issueState(aliceServices, alice)) + .addInputState(issueState(aliceNode.services, alice)) .addCommand(dummyCommand(alice.owningKey)) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val firstSpend = NotaryFlow.Client(stx) val secondSpend = NotaryFlow.Client(stx2) // Double spend the inputState in a second transaction. - aliceServices.startFlow(firstSpend) - val future = aliceServices.startFlow(secondSpend) + aliceNode.services.startFlow(firstSpend) + val future = aliceNode.services.startFlow(secondSpend) mockNet.runNetwork() - val ex = assertFailsWith(NotaryException::class) { future.getOrThrow() } + val ex = assertFailsWith(NotaryException::class) { future.resultFuture.getOrThrow() } val notaryError = ex.error as NotaryError.Conflict assertEquals(notaryError.txId, stx2.id) notaryError.conflict.verified() @@ -178,7 +171,7 @@ class NotaryServiceTests { val transaction = originalPayload.signedTransaction val randomKeyPair = Crypto.generateKeyPair() val bytesToSign = NotarisationRequest(transaction.inputs, transaction.id).serialize().bytes - val modifiedSignature = NotarisationRequestSignature(randomKeyPair.sign(bytesToSign), aliceServices.myInfo.platformVersion) + val modifiedSignature = NotarisationRequestSignature(randomKeyPair.sign(bytesToSign), aliceNode.services.myInfo.platformVersion) originalPayload.copy(requestSignature = modifiedSignature) } } @@ -189,7 +182,7 @@ class NotaryServiceTests { val transaction = originalPayload.signedTransaction val wrongInputs = listOf(StateRef(SecureHash.randomSHA256(), 0)) val request = NotarisationRequest(wrongInputs, transaction.id) - val modifiedSignature = request.generateSignature(aliceServices) + val modifiedSignature = request.generateSignature(aliceNode.services) originalPayload.copy(requestSignature = modifiedSignature) } } @@ -200,7 +193,7 @@ class NotaryServiceTests { val transaction = originalPayload.signedTransaction val wrongTransactionId = SecureHash.randomSHA256() val request = NotarisationRequest(transaction.inputs, wrongTransactionId) - val modifiedSignature = request.generateSignature(aliceServices) + val modifiedSignature = request.generateSignature(aliceNode.services) originalPayload.copy(requestSignature = modifiedSignature) } } @@ -214,7 +207,7 @@ class NotaryServiceTests { if (payload is NotarisationPayload) { val alteredPayload = payloadModifier(payload) val alteredMessageData = messageData.copy(firstPayload = alteredPayload.serialize()) - val alteredMessage = InMemoryMessagingNetwork.InMemoryMessage(message.topic, OpaqueBytes(alteredMessageData.serialize().bytes), message.uniqueMessageId) + val alteredMessage = InMemoryMessage(message.topic, OpaqueBytes(alteredMessageData.serialize().bytes), message.uniqueMessageId) messagingService.send(alteredMessage, target, retryId) } else { @@ -224,11 +217,11 @@ class NotaryServiceTests { }) val stx = run { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val future = runNotaryClient(stx) @@ -238,7 +231,7 @@ class NotaryServiceTests { private fun runNotaryClient(stx: SignedTransaction): CordaFuture> { val flow = NotaryFlow.Client(stx) - val future = aliceServices.startFlow(flow) + val future = aliceNode.services.startFlow(flow).resultFuture mockNet.runNetwork() return future } diff --git a/node/src/test/kotlin/net/corda/node/services/transactions/ValidatingNotaryServiceTests.kt b/node/src/test/kotlin/net/corda/node/services/transactions/ValidatingNotaryServiceTests.kt index f7dd12b0cc..bc79857f21 100644 --- a/node/src/test/kotlin/net/corda/node/services/transactions/ValidatingNotaryServiceTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/transactions/ValidatingNotaryServiceTests.kt @@ -22,7 +22,7 @@ import net.corda.testing.core.dummyCommand import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNodeParameters -import net.corda.testing.node.startFlow +import net.corda.testing.node.StartedMockNode import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before @@ -33,17 +33,16 @@ import kotlin.test.assertFailsWith class ValidatingNotaryServiceTests { private lateinit var mockNet: MockNetwork - private lateinit var notaryServices: StartedNodeServices - private lateinit var aliceServices: StartedNodeServices + private lateinit var notaryNode: StartedMockNode + private lateinit var aliceNode: StartedMockNode private lateinit var notary: Party private lateinit var alice: Party @Before fun setup() { mockNet = MockNetwork(cordappPackages = listOf("net.corda.testing.contracts")) - val aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) - notaryServices = mockNet.defaultNotaryNode.services - aliceServices = aliceNode.services + aliceNode = mockNet.createNode(MockNodeParameters(legalName = ALICE_NAME)) + notaryNode = mockNet.defaultNotaryNode notary = mockNet.defaultNotaryIdentity alice = aliceNode.info.singleIdentity() } @@ -56,11 +55,11 @@ class ValidatingNotaryServiceTests { @Test fun `should report error for invalid transaction dependency`() { val stx = run { - val inputState = issueInvalidState(aliceServices, alice, notary) + val inputState = issueInvalidState(aliceNode.services, alice, notary) val tx = TransactionBuilder(notary) .addInputState(inputState) .addCommand(dummyCommand(alice.owningKey)) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val future = runClient(stx) @@ -74,11 +73,11 @@ class ValidatingNotaryServiceTests { fun `should report error for missing signatures`() { val expectedMissingKey = generateKeyPair().public val stx = run { - val inputState = issueState(aliceServices, alice) + val inputState = issueState(aliceNode.services, alice) val command = Command(DummyContract.Commands.Move(), expectedMissingKey) val tx = TransactionBuilder(notary).withItems(inputState, command) - aliceServices.signInitialTransaction(tx) + aliceNode.services.signInitialTransaction(tx) } val ex = assertFailsWith(NotaryException::class) { @@ -94,7 +93,7 @@ class ValidatingNotaryServiceTests { private fun runClient(stx: SignedTransaction): CordaFuture> { val flow = NotaryFlow.Client(stx) - val future = aliceServices.startFlow(flow) + val future = aliceNode.startFlow(flow) mockNet.runNetwork() return future } @@ -102,7 +101,7 @@ class ValidatingNotaryServiceTests { private fun issueState(serviceHub: ServiceHub, identity: Party): StateAndRef<*> { val tx = DummyContract.generateInitial(Random().nextInt(), notary, identity.ref(0)) val signedByNode = serviceHub.signInitialTransaction(tx) - val stx = notaryServices.addSignature(signedByNode, notary.owningKey) + val stx = notaryNode.services.addSignature(signedByNode, notary.owningKey) serviceHub.recordTransactions(stx) return StateAndRef(tx.outputStates().first(), StateRef(stx.id, 0)) } diff --git a/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt index d9aa1248af..9bdcd1f24c 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/NodeVaultServiceTest.kt @@ -29,6 +29,7 @@ import net.corda.finance.contracts.getCashBalance import net.corda.finance.schemas.CashSchemaV1 import net.corda.finance.utils.sumCash import net.corda.node.services.api.IdentityServiceInternal +import net.corda.node.services.api.WritableTransactionStorage import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.testing.core.* import net.corda.testing.internal.LogHelper @@ -141,7 +142,7 @@ class NodeVaultServiceTest { override val vaultService: NodeVaultService get() = originalVault override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable) { for (stx in txs) { - validatedTransactions.addTransaction(stx) + (validatedTransactions as WritableTransactionStorage).addTransaction(stx) vaultService.notify(statesToRecord, stx.tx) } } @@ -553,7 +554,7 @@ class NodeVaultServiceTest { // ensure transaction contract state is persisted in DBStorage val signedIssuedTx = services.signInitialTransaction(issueBuilder) - services.validatedTransactions.addTransaction(signedIssuedTx) + (services.validatedTransactions as WritableTransactionStorage).addTransaction(signedIssuedTx) database.transaction { vaultService.notify(StatesToRecord.ONLY_RELEVANT, issueTx) } val expectedIssueUpdate = Vault.Update(emptySet(), setOf(cashState), null) @@ -569,7 +570,7 @@ class NodeVaultServiceTest { // ensure transaction contract state is persisted in DBStorage val signedMoveTx = services.signInitialTransaction(issueBuilder) - services.validatedTransactions.addTransaction(signedMoveTx) + (services.validatedTransactions as WritableTransactionStorage).addTransaction(signedMoveTx) val observedUpdates = vaultSubscriber.onNextEvents assertEquals(observedUpdates, listOf(expectedIssueUpdate, expectedMoveUpdate)) @@ -599,7 +600,7 @@ class NodeVaultServiceTest { } val issueStx = bocServices.signInitialTransaction(issueTxBuilder) // We need to record the issue transaction so inputs can be resolved for the notary change transaction - services.validatedTransactions.addTransaction(issueStx) + (services.validatedTransactions as WritableTransactionStorage).addTransaction(issueStx) val initialCashState = StateAndRef(issueStx.tx.outputs.single(), StateRef(issueStx.id, 0)) @@ -614,7 +615,7 @@ class NodeVaultServiceTest { } // ensure transaction contract state is persisted in DBStorage - services.validatedTransactions.addTransaction(SignedTransaction(changeNotaryTx, listOf(NullKeys.NULL_SIGNATURE))) + (services.validatedTransactions as WritableTransactionStorage).addTransaction(SignedTransaction(changeNotaryTx, listOf(NullKeys.NULL_SIGNATURE))) // Move cash val moveTxBuilder = database.transaction { @@ -626,7 +627,7 @@ class NodeVaultServiceTest { // ensure transaction contract state is persisted in DBStorage val signedMoveTx = services.signInitialTransaction(moveTxBuilder) - services.validatedTransactions.addTransaction(signedMoveTx) + (services.validatedTransactions as WritableTransactionStorage).addTransaction(signedMoveTx) database.transaction { service.notify(StatesToRecord.ONLY_RELEVANT, moveTx) @@ -660,7 +661,7 @@ class NodeVaultServiceTest { // ensure transaction contract state is persisted in DBStorage val signedTxb = services.signInitialTransaction(txb) - services.validatedTransactions.addTransaction(signedTxb) + (services.validatedTransactions as WritableTransactionStorage).addTransaction(signedTxb) // Check that it was ignored as irrelevant. assertEquals(currentCashStates, countCash()) 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 04e0b34c37..9f8663c47d 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 @@ -26,6 +26,7 @@ import net.corda.node.internal.configureDatabase import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.DatabaseConfig import net.corda.testing.core.* +import net.corda.testing.internal.TEST_TX_TIME import net.corda.testing.internal.rigorousMock import net.corda.testing.internal.vault.DUMMY_LINEAR_CONTRACT_PROGRAM_ID import net.corda.testing.internal.vault.DummyLinearContract diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultSoftLockManagerTest.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultSoftLockManagerTest.kt index 1ec7772bea..dea24d1d7d 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultSoftLockManagerTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultSoftLockManagerTest.kt @@ -26,11 +26,11 @@ import net.corda.core.utilities.unwrap import net.corda.node.internal.InitiatedFlowFactory import net.corda.node.services.api.VaultServiceInternal import net.corda.nodeapi.internal.persistence.HibernateConfiguration -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.rigorousMock -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.startFlow +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Test import java.util.* @@ -50,7 +50,7 @@ class NodePair(private val mockNet: InternalMockNetwork) { @InitiatingFlow abstract class AbstractClientLogic(nodePair: NodePair) : FlowLogic() { - protected val server = nodePair.server.info.chooseIdentity() + protected val server = nodePair.server.info.singleIdentity() protected abstract fun callImpl(): T @Suspendable override fun call() = callImpl().also { @@ -71,7 +71,7 @@ class NodePair(private val mockNet: InternalMockNetwork) { while (!serverRunning.get()) mockNet.runNetwork(1) if (rebootClient) { client.dispose() - client = mockNet.createNode(MockNodeParameters(client.internals.id)) + client = mockNet.createNode(InternalMockNodeParameters(client.internals.id)) } return uncheckedCast(client.smm.allStateMachines.single().stateMachine) } @@ -115,11 +115,11 @@ class VaultSoftLockManagerTest { private abstract class ParticipantState(override val participants: List) : ContractState private class PlainOldState(participants: List) : ParticipantState(participants) { - constructor(nodePair: NodePair) : this(listOf(nodePair.client.info.chooseIdentity())) + constructor(nodePair: NodePair) : this(listOf(nodePair.client.info.singleIdentity())) } private class FungibleAssetImpl(participants: List) : ParticipantState(participants), FungibleAsset { - constructor(nodePair: NodePair) : this(listOf(nodePair.client.info.chooseIdentity())) + constructor(nodePair: NodePair) : this(listOf(nodePair.client.info.singleIdentity())) override val owner get() = participants[0] override fun withNewOwner(newOwner: AbstractParty) = throw UnsupportedOperationException() diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/NodeInterestRatesTest.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/NodeInterestRatesTest.kt index 81bc7e254a..c586129494 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/NodeInterestRatesTest.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/NodeInterestRatesTest.kt @@ -227,7 +227,7 @@ class NodeInterestRatesTest { val flow = FilteredRatesFlow(tx, oracle, fixOf, BigDecimal("0.675"), BigDecimal("0.1")) LogHelper.setLevel("rates") mockNet.runNetwork() - val future = aliceNode.services.startFlow(flow) + val future = aliceNode.startFlow(flow) mockNet.runNetwork() future.getOrThrow() // We should now have a valid fix of our tx from the oracle. diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt index 9dd8a7debf..490f587303 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt @@ -26,7 +26,6 @@ import net.corda.finance.contracts.Tenor import net.corda.node.services.api.IdentityServiceInternal import net.corda.testing.core.DUMMY_NOTARY_NAME import net.corda.testing.core.SerializationEnvironmentRule -import net.corda.testing.core.TEST_TX_TIME import net.corda.testing.core.TestIdentity import net.corda.testing.dsl.* import net.corda.testing.internal.rigorousMock @@ -36,10 +35,12 @@ import net.corda.testing.node.transaction import org.junit.Rule import org.junit.Test import java.math.BigDecimal +import java.time.Instant import java.time.LocalDate import java.util.* import kotlin.test.assertEquals +private val TEST_TX_TIME = Instant.parse("2015-04-17T12:00:00.00Z") private val DUMMY_PARTY = Party(CordaX500Name("Dummy", "Madrid", "ES"), generateKeyPair().public) private val dummyNotary = TestIdentity(DUMMY_NOTARY_NAME, 20) private val megaCorp = TestIdentity(CordaX500Name("MegaCorp", "London", "GB")) diff --git a/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt b/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt index 70fdb57b7a..11450c4939 100644 --- a/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt +++ b/samples/irs-demo/src/integration-test/kotlin/net/corda/irs/IRSDemoTest.kt @@ -22,12 +22,11 @@ import net.corda.core.utilities.seconds import net.corda.finance.plugin.registerFinanceJSONMappers import net.corda.irs.contract.InterestRateSwap import net.corda.irs.web.IrsDemoWebApplication -import net.corda.node.services.config.NodeConfiguration import net.corda.test.spring.springDriver import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.core.DUMMY_BANK_B_NAME import net.corda.testing.core.DUMMY_NOTARY_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.http.HttpApi import net.corda.testing.node.NotarySpec @@ -85,7 +84,7 @@ class IRSDemoTest { val numBDeals = getTradeCount(nodeBApi) runUploadRates(controllerApi) - runTrade(nodeAApi, controller.nodeInfo.chooseIdentity()) + runTrade(nodeAApi, controller.nodeInfo.singleIdentity()) assertThat(getTradeCount(nodeAApi)).isEqualTo(numADeals + 1) assertThat(getTradeCount(nodeBApi)).isEqualTo(numBDeals + 1) diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt index 9d370c22f6..161264eb36 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt @@ -16,9 +16,8 @@ import net.corda.core.utilities.ProgressTracker import net.corda.netmap.VisualiserViewModel.Style import net.corda.netmap.simulation.IRSSimulation import net.corda.node.services.statemachine.* -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.node.InMemoryMessagingNetwork -import net.corda.testing.node.MockNetwork import net.corda.testing.node.internal.InternalMockNetwork import rx.Scheduler import rx.schedulers.Schedulers @@ -222,7 +221,7 @@ class NetworkMapVisualiser : Application() { // Flow done; schedule it for removal in a few seconds. We batch them up to make nicer // animations. updateProgressTrackerWidget(change) - println("Flow done for ${node.started!!.info.chooseIdentity().name}") + println("Flow done for ${node.started!!.info.singleIdentity().name}") viewModel.doneTrackers += tracker } else { // Subflow is done; ignore it. @@ -230,7 +229,7 @@ class NetworkMapVisualiser : Application() { } else if (!viewModel.trackerBoxes.containsKey(tracker)) { // New flow started up; add. val extraLabel = viewModel.simulation.extraNodeLabels[node] - val label = node.started!!.info.chooseIdentity().name.organisation.let { if (extraLabel != null) "$it: $extraLabel" else it } + val label = node.started!!.info.singleIdentity().name.organisation.let { if (extraLabel != null) "$it: $extraLabel" else it } val widget = view.buildProgressTrackerWidget(label, tracker.topLevelTracker) println("Added: $tracker, $widget") viewModel.trackerBoxes[tracker] = widget @@ -341,7 +340,7 @@ class NetworkMapVisualiser : Application() { private fun transferIsInteresting(transfer: InMemoryMessagingNetwork.MessageTransfer): Boolean { // Loopback messages are boring. if (transfer.sender == transfer.recipients) return false - val message = transfer.message.data.deserialize() + val message = transfer.messageData.deserialize() return when (message) { is InitialSessionMessage -> message.firstPayload != null is ExistingSessionMessage -> when (message.payload) { diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt index 5ba0385023..385a677319 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt @@ -12,7 +12,7 @@ import net.corda.core.utilities.ProgressTracker import net.corda.finance.utils.ScreenCoordinate import net.corda.netmap.simulation.IRSSimulation import net.corda.netmap.simulation.place -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.node.internal.InternalMockNetwork import java.util.* @@ -88,7 +88,7 @@ class VisualiserViewModel { try { return node.place.coordinate.project(view.mapImage.fitWidth, view.mapImage.fitHeight, 64.3209, 29.8406, -23.2031, 33.0469) } catch (e: Exception) { - throw Exception("Cannot project ${node.started!!.info.chooseIdentity()}", e) + throw Exception("Cannot project ${node.started!!.info.singleIdentity()}", e) } } diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt index aed3705c38..1ad0942057 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt @@ -21,10 +21,10 @@ import net.corda.finance.flows.TwoPartyDealFlow.Instigator import net.corda.finance.plugin.registerFinanceJSONMappers import net.corda.irs.contract.InterestRateSwap import net.corda.irs.flows.FixingFlow -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.node.InMemoryMessagingNetwork +import net.corda.testing.node.internal.startFlow import net.corda.testing.node.makeTestIdentityService -import net.corda.testing.node.startFlow import rx.Observable import java.time.LocalDate import java.util.* @@ -133,8 +133,8 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten .reader() .readText() .replace("oracleXXX", RatesOracleNode.RATES_SERVICE_NAME.toString())) - irs.fixedLeg.fixedRatePayer = node1.info.chooseIdentity() - irs.floatingLeg.floatingRatePayer = node2.info.chooseIdentity() + irs.fixedLeg.fixedRatePayer = node1.info.singleIdentity() + irs.floatingLeg.floatingRatePayer = node2.info.singleIdentity() node1.registerInitiatedFlow(FixingFlow.Fixer::class.java) node2.registerInitiatedFlow(FixingFlow.Fixer::class.java) @InitiatingFlow @@ -158,9 +158,9 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten showConsensusFor(listOf(node1.internals, node2.internals, regulators[0])) val instigator = StartDealFlow( - node2.info.chooseIdentity(), + node2.info.singleIdentity(), AutoOffer(mockNet.defaultNotaryIdentity, irs)) // TODO Pass notary as parameter to Simulation. - val instigatorTxFuture = node1.services.startFlow(instigator) + val instigatorTxFuture = node1.services.startFlow(instigator).resultFuture return allOf(instigatorTxFuture.toCompletableFuture(), acceptorTxFuture).thenCompose { instigatorTxFuture.toCompletableFuture() } } diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt index 4b0a828e9f..0a465ca3c8 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt @@ -15,6 +15,7 @@ import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import net.corda.testing.node.TestClock import net.corda.testing.node.internal.InternalMockNetwork +import net.corda.testing.node.internal.InternalMockNodeParameters import net.corda.testing.node.internal.MockNodeArgs import rx.Observable import rx.subjects.PublishSubject @@ -40,7 +41,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) { private companion object { val defaultParams // The get() is necessary so that entropyRoot isn't shared. - get() = MockNodeParameters(configOverrides = { + get() = InternalMockNodeParameters(configOverrides = { doReturn(makeTestDataSourceProperties(it.myLegalName.organisation)).whenever(it).dataSourceProperties }) val DUMMY_REGULATOR = TestIdentity(CordaX500Name("Regulator A", "Paris", "FR"), 100).party @@ -141,7 +142,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, } // Keep going until one of the nodes has something to do, or we have checked every node. - val endpoints = mockNet.messagingNetwork.endpoints + val endpoints = mockNet.messagingNetwork.endpointsExternal var countDown = endpoints.size while (countDown > 0) { val handledMessage = endpoints[pumpCursor].pumpReceive(false) diff --git a/samples/trader-demo/src/integration-test/kotlin/net/corda/traderdemo/TraderDemoTest.kt b/samples/trader-demo/src/integration-test/kotlin/net/corda/traderdemo/TraderDemoTest.kt index e23d801e76..938e4243f5 100644 --- a/samples/trader-demo/src/integration-test/kotlin/net/corda/traderdemo/TraderDemoTest.kt +++ b/samples/trader-demo/src/integration-test/kotlin/net/corda/traderdemo/TraderDemoTest.kt @@ -11,7 +11,7 @@ import net.corda.node.services.Permissions.Companion.startFlow import net.corda.testing.core.BOC_NAME import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.core.DUMMY_BANK_B_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.InProcess import net.corda.testing.driver.driver @@ -57,8 +57,8 @@ class TraderDemoTest { val expectedBCash = clientB.cashCount + 1 val expectedPaper = listOf(clientA.commercialPaperCount + 1, clientB.commercialPaperCount) - clientBank.runIssuer(amount = 100.DOLLARS, buyerName = nodeA.services.myInfo.chooseIdentity().name, sellerName = nodeB.services.myInfo.chooseIdentity().name) - clientB.runSeller(buyerName = nodeA.services.myInfo.chooseIdentity().name, amount = 5.DOLLARS) + clientBank.runIssuer(amount = 100.DOLLARS, buyerName = nodeA.services.myInfo.singleIdentity().name, sellerName = nodeB.services.myInfo.singleIdentity().name) + clientB.runSeller(buyerName = nodeA.services.myInfo.singleIdentity().name, amount = 5.DOLLARS) assertThat(clientA.cashCount).isGreaterThan(originalACash) assertThat(clientB.cashCount).isEqualTo(expectedBCash) diff --git a/samples/trader-demo/src/test/kotlin/net/corda/traderdemo/TransactionGraphSearchTests.kt b/samples/trader-demo/src/test/kotlin/net/corda/traderdemo/TransactionGraphSearchTests.kt index b501cb7d52..74d8b78c25 100644 --- a/samples/trader-demo/src/test/kotlin/net/corda/traderdemo/TransactionGraphSearchTests.kt +++ b/samples/trader-demo/src/test/kotlin/net/corda/traderdemo/TransactionGraphSearchTests.kt @@ -14,7 +14,7 @@ import net.corda.testing.core.TestIdentity import net.corda.testing.core.dummyCommand import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices -import net.corda.testing.node.MockTransactionStorage +import net.corda.testing.node.internal.MockTransactionStorage import org.junit.Rule import org.junit.Test import kotlin.test.assertEquals diff --git a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/driver/DriverTests.kt b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/driver/DriverTests.kt index 4e39ac8297..1a34f17ece 100644 --- a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/driver/DriverTests.kt +++ b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/driver/DriverTests.kt @@ -17,6 +17,7 @@ import net.corda.testing.node.internal.internalDriver import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.core.DUMMY_BANK_B_NAME import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.driver.internal.RandomFree import net.corda.testing.http.HttpApi import net.corda.testing.node.NotarySpec import org.assertj.core.api.Assertions.* @@ -71,7 +72,7 @@ class DriverTests { @Test fun `random free port allocation`() { - val nodeHandle = driver(DriverParameters(portAllocation = PortAllocation.RandomFree)) { + val nodeHandle = driver(DriverParameters(portAllocation = RandomFree)) { val nodeInfo = startNode(providedName = DUMMY_BANK_A_NAME) nodeMustBeUp(nodeInfo) } diff --git a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt index f92952f609..309a298844 100644 --- a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt +++ b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt @@ -291,7 +291,7 @@ class FlowStackSnapshotTest { val mockNet = MockNetwork(emptyList(), threadPerNode = true) val node = mockNet.createPartyNode() node.registerInitiatedFlow(DummyFlow::class.java) - node.services.startFlow(FlowStackSnapshotSerializationTestingFlow()).get() + node.startFlow(FlowStackSnapshotSerializationTestingFlow()).get() val thrown = try { // Due to the [MockNetwork] implementation, the easiest way to trigger object serialization process is at // the network stopping stage. diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt index 2f200a55f6..5380130245 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt @@ -10,20 +10,21 @@ import net.corda.core.identity.Party import net.corda.core.messaging.CordaRPCOps import net.corda.core.node.NetworkParameters import net.corda.core.node.NodeInfo +import net.corda.core.node.ServiceHub import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.getOrThrow import net.corda.node.internal.Node -import net.corda.node.services.api.StartedNodeServices -import net.corda.node.services.config.VerifierType import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.driver.PortAllocation.Incremental +import net.corda.testing.driver.internal.internalServices import net.corda.testing.node.NotarySpec import net.corda.testing.node.User import net.corda.testing.node.internal.DriverDSLImpl import net.corda.testing.node.internal.genericDriver import net.corda.testing.node.internal.getTimestampAsDirectoryName +import net.corda.testing.node.internal.newContext import rx.Observable -import java.net.InetSocketAddress -import java.net.ServerSocket import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.atomic.AtomicInteger @@ -33,18 +34,27 @@ import java.util.concurrent.atomic.AtomicInteger */ data class NotaryHandle(val identity: Party, val validating: Boolean, val nodeHandles: CordaFuture>) +/** + * A base interface which represents a node as part of the [driver] dsl, extended by [InProcess] and [OutOfProcess] + */ @DoNotImplement interface NodeHandle : AutoCloseable { + /** Get the [NodeInfo] for this node */ val nodeInfo: NodeInfo /** * Interface to the node's RPC system. The first RPC user will be used to login if are any, otherwise a default one * will be added and that will be used. */ val rpc: CordaRPCOps + /** Get the p2p address for this node **/ val p2pAddress: NetworkHostAndPort + /** Get the rpc address for this node **/ val rpcAddress: NetworkHostAndPort + /** Get a [List] of [User]'s for this node **/ val rpcUsers: List + /** The location of the node's base directory **/ val baseDirectory: Path + /** * Stops the referenced node. */ @@ -52,46 +62,79 @@ interface NodeHandle : AutoCloseable { } +/** Interface which represents an out of process node and exposes its process handle. **/ @DoNotImplement interface OutOfProcess : NodeHandle { + /** The process in which this node is running **/ val process: Process } +/** Interface which represents an in process node and exposes available services. **/ @DoNotImplement interface InProcess : NodeHandle { - val services: StartedNodeServices + /** Services which are available to this node **/ + val services: ServiceHub + /** * Register a flow that is initiated by another flow */ fun > registerInitiatedFlow(initiatedFlowClass: Class): Observable + + /** + * Starts an already constructed flow. Note that you must be on the server thread to call this method. + * @param context indicates who started the flow, see: [InvocationContext]. + */ + fun startFlow(logic: FlowLogic): CordaFuture = internalServices.startFlow(logic, internalServices.newContext()).getOrThrow().resultFuture } +/** + * Class which represents a handle to a webserver process and its [NetworkHostAndPort] for testing purposes. + * + * @property listenAddress The [NetworkHostAndPort] for communicating with this webserver. + * @property process The [Process] in which the websever is running + * */ +@Deprecated("The webserver is for testing purposes only and will be removed soon") data class WebserverHandle( val listenAddress: NetworkHostAndPort, val process: Process ) +/** + * An abstract helper class which is used within the driver to allocate unused ports for testing. Use either + * the [Incremental] or [RandomFree] concrete implementations. + */ @DoNotImplement -sealed class PortAllocation { +abstract class PortAllocation { + /** Get the next available port **/ abstract fun nextPort(): Int + + /** Get the next available port via [nextPort] and then return a [NetworkHostAndPort] **/ fun nextHostAndPort() = NetworkHostAndPort("localhost", nextPort()) + /** + * An implementation of [PortAllocation] which allocates ports sequentially + */ class Incremental(startingPort: Int) : PortAllocation() { + /** The backing [AtomicInteger] used to keep track of the currently allocated port */ val portCounter = AtomicInteger(startingPort) - override fun nextPort() = portCounter.andIncrement - } - object RandomFree : PortAllocation() { - override fun nextPort(): Int { - return ServerSocket().use { - it.bind(InetSocketAddress(0)) - it.localPort - } - } + override fun nextPort() = portCounter.andIncrement } } -/** Helper builder for configuring a [Node] from Java. */ +/** + * Helper builder for configuring a [Node] from Java. + * + * @property providedName Optional name of the node, which will be its legal name in [Party]. Defaults to something + * random. Note that this must be unique as the driver uses it as a primary key! + * @property rpcUsers List of users who are authorised to use the RPC system. Defaults to a single user with + * all permissions. + * @property verifierType The type of transaction verifier to use. See: [VerifierType] + * @property customOverrides A map of custom node configuration overrides. + * @property startInSameProcess Determines if the node should be started inside the same process the Driver is running + * in. If null the Driver-level value will be used. + * @property maximumHeapSize The maximum JVM heap size to use for the node. + */ @Suppress("unused") data class NodeParameters( val providedName: CordaX500Name? = null, @@ -104,12 +147,14 @@ data class NodeParameters( fun withProvidedName(providedName: CordaX500Name?): NodeParameters = copy(providedName = providedName) fun withRpcUsers(rpcUsers: List): NodeParameters = copy(rpcUsers = rpcUsers) fun withVerifierType(verifierType: VerifierType): NodeParameters = copy(verifierType = verifierType) - fun withCustomerOverrides(customOverrides: Map): NodeParameters = copy(customOverrides = customOverrides) + fun withCustomOverrides(customOverrides: Map): NodeParameters = copy(customOverrides = customOverrides) fun withStartInSameProcess(startInSameProcess: Boolean?): NodeParameters = copy(startInSameProcess = startInSameProcess) fun withMaximumHeapSize(maximumHeapSize: String): NodeParameters = copy(maximumHeapSize = maximumHeapSize) } /** + * A class containing configuration information for Jolokia JMX, to be used when creating a node via the [driver] + * * @property startJmxHttpServer Indicates whether the spawned nodes should start with a Jolokia JMX agent to enable remote * JMX monitoring using HTTP/JSON * @property jmxHttpServerPortAllocation The port allocation strategy to use for remote Jolokia/JMX monitoring over HTTP. @@ -162,24 +207,28 @@ fun driver(defaultParameters: DriverParameters = DriverParameters(), dsl: Dr /** * Builder for configuring a [driver]. + * * @property isDebug Indicates whether the spawned nodes should start in jdwt debug mode and have debug level logging. * @property driverDirectory The base directory node directories go into, defaults to "build//". The node - * directories themselves are "//", where legalName defaults to "-" - * and may be specified in [DriverDSL.startNode]. + * directories themselves are "//", where legalName defaults to "-" + * and may be specified in [DriverDSL.startNode]. * @property portAllocation The port allocation strategy to use for the messaging and the web server addresses. Defaults - * to incremental. + * to incremental. * @property debugPortAllocation The port allocation strategy to use for jvm debugging. Defaults to incremental. * @property systemProperties A Map of extra system properties which will be given to each new node. Defaults to empty. * @property useTestClock If true the test clock will be used in Node. * @property startNodesInProcess Provides the default behaviour of whether new nodes should start inside this process or * not. Note that this may be overridden in [DriverDSL.startNode]. * @property waitForAllNodesToFinish If true, the nodes will not shut down automatically after executing the code in the - * driver DSL block. It will wait for them to be shut down externally instead. + * driver DSL block. It will wait for them to be shut down externally instead. * @property notarySpecs The notaries advertised for this network. These nodes will be started automatically and will be - * available from [DriverDSL.notaryHandles]. Defaults to a simple validating notary. + * available from [DriverDSL.notaryHandles], and will be added automatically to the network parameters. + * Defaults to a simple validating notary. + * @property extraCordappPackagesToScan A [List] of additional cordapp packages to scan for any cordapp code, e.g. + * contract verification code, flows and services. The calling package is automatically added. * @property jmxPolicy Used to specify whether to expose JMX metrics via Jolokia HHTP/JSON. * @property networkParameters The network parameters to be used by all the nodes. [NetworkParameters.notaries] must be - * empty as notaries are defined by [notarySpecs]. + * empty as notaries are defined by [notarySpecs]. */ @Suppress("unused") data class DriverParameters( diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt index 2cf3be566e..6ef75b3327 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt @@ -6,11 +6,18 @@ import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.internal.concurrent.map import net.corda.node.internal.Node -import net.corda.node.services.config.VerifierType import net.corda.testing.node.User import net.corda.testing.node.NotarySpec import java.nio.file.Path +enum class VerifierType { + InMemory, + OutOfProcess +} + +/** + * Underlying interface for the driver DSL. Do not instantiate directly, instead use the [driver] function. + * */ @DoNotImplement interface DriverDSL { /** Returns a list of [NotaryHandle]s matching the list of [NotarySpec]s passed into [driver]. */ @@ -53,10 +60,14 @@ interface DriverDSL { * when called from Java code. * @param providedName Optional name of the node, which will be its legal name in [Party]. Defaults to something * random. Note that this must be unique as the driver uses it as a primary key! - * @param verifierType The type of transaction verifier to use. See: [VerifierType] * @param rpcUsers List of users who are authorised to use the RPC system. Defaults to empty list. + * @param verifierType The type of transaction verifier to use. See: [VerifierType]. + * @param customOverrides A map of custom node configuration overrides. * @param startInSameProcess Determines if the node should be started inside the same process the Driver is running * in. If null the Driver-level value will be used. + * @param maximumHeapSize The maximum JVM heap size to use for the node as a [String]. By default a number is interpreted + * as being in bytes. Append the letter 'k' or 'K' to the value to indicate Kilobytes, 'm' or 'M' to indicate + * megabytes, and 'g' or 'G' to indicate gigabytes. The default value is "200m" = 200 megabytes. * @return A [CordaFuture] on the [NodeHandle] to the node. The future will complete when the node is available. */ fun startNode( diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/internal/DriverInternal.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/internal/DriverInternal.kt index 972677dd4d..20623ef743 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/internal/DriverInternal.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/internal/DriverInternal.kt @@ -12,10 +12,12 @@ import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.testing.driver.InProcess import net.corda.testing.driver.NodeHandle import net.corda.testing.driver.OutOfProcess +import net.corda.testing.driver.PortAllocation import net.corda.testing.node.User import rx.Observable +import java.net.InetSocketAddress +import java.net.ServerSocket import java.nio.file.Path -import java.sql.Connection interface NodeHandleInternal : NodeHandle { val configuration: NodeConfiguration @@ -73,3 +75,14 @@ data class InProcessImpl( override fun close() = stop() override fun > registerInitiatedFlow(initiatedFlowClass: Class): Observable = node.registerInitiatedFlow(initiatedFlowClass) } + +val InProcess.internalServices: StartedNodeServices get() = services as StartedNodeServices + +object RandomFree : PortAllocation() { + override fun nextPort(): Int { + return ServerSocket().use { + it.bind(InetSocketAddress(0)) + it.localPort + } + } +} \ No newline at end of file diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt index 70613b3253..adbd5175dd 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt @@ -1,6 +1,5 @@ package net.corda.testing.node -import net.corda.core.CordaInternal import net.corda.core.DoNotImplement import net.corda.core.crypto.CompositeKey import net.corda.core.identity.CordaX500Name @@ -25,7 +24,8 @@ import net.corda.node.services.messaging.MessagingService import net.corda.node.services.messaging.ReceivedMessage import net.corda.node.utilities.AffinityExecutor import net.corda.nodeapi.internal.persistence.CordaPersistence -import net.corda.testing.node.InMemoryMessagingNetwork.TestMessagingService +import net.corda.testing.node.internal.InMemoryMessage +import net.corda.testing.node.internal.InternalMockMessagingService import org.apache.activemq.artemis.utils.ReusableLatch import org.slf4j.LoggerFactory import rx.Observable @@ -39,8 +39,8 @@ import kotlin.concurrent.schedule import kotlin.concurrent.thread /** - * An in-memory network allows you to manufacture [TestMessagingService]s for a set of participants. Each - * [TestMessagingService] maintains a queue of messages it has received, and a background thread that dispatches + * An in-memory network allows you to manufacture [InternalMockMessagingService]s for a set of participants. Each + * [InternalMockMessagingService] maintains a queue of messages it has received, and a background thread that dispatches * messages one by one to registered handlers. Alternatively, a messaging system may be manually pumped, in which * case no thread is created and a caller is expected to force delivery one at a time (this is useful for unit * testing). @@ -69,8 +69,16 @@ class InMemoryMessagingNetwork private constructor( private var counter = 0 // -1 means stopped. private val handleEndpointMap = HashMap() + /** A class which represents a message being transferred from sender to recipients, within the [InMemoryMessageNetwork]. **/ @CordaSerializable - data class MessageTransfer(val sender: PeerHandle, val message: Message, val recipients: MessageRecipients) { + class MessageTransfer private constructor(val sender: PeerHandle, internal val message: Message, val recipients: MessageRecipients) { + companion object { + internal fun createMessageTransfer(sender: PeerHandle, message: Message, recipients: MessageRecipients): MessageTransfer { + return MessageTransfer(sender, message, recipients) + } + } + /** Data contained in this message transfer **/ + val messageData: ByteSequence get() = message.data override fun toString() = "${message.topic} from '$sender' to '$recipients'" } @@ -79,7 +87,7 @@ class InMemoryMessagingNetwork private constructor( private val messageSendQueue = LinkedBlockingQueue() private val _sentMessages = PublishSubject.create() @Suppress("unused") // Used by the visualiser tool. - /** A stream of (sender, message, recipients) triples */ + /** A stream of (sender, message, recipients) triples containing messages once they have been sent by [pumpSend]. */ val sentMessages: Observable get() = _sentMessages @@ -92,16 +100,18 @@ class InMemoryMessagingNetwork private constructor( private val _receivedMessages = PublishSubject.create() // Holds the mapping from services to peers advertising the service. - private val serviceToPeersMapping = HashMap>() + private val serviceToPeersMapping = HashMap>() // Holds the mapping from node's X.500 name to PeerHandle. private val peersMapping = HashMap() @Suppress("unused") // Used by the visualiser tool. - /** A stream of (sender, message, recipients) triples */ + /** A stream of (sender, message, recipients) triples containing messages once they have been received. */ val receivedMessages: Observable get() = _receivedMessages + internal val endpoints: List @Synchronized get() = handleEndpointMap.values.toList() + /** Get a [List] of all the [MockMessagingService] endpoints **/ + val endpointsExternal: List @Synchronized get() = handleEndpointMap.values.map{ MockMessagingService.createMockMessagingService(it) }.toList() - val endpoints: List @Synchronized get() = handleEndpointMap.values.toList() /** * Creates a node at the given address: useful if you want to recreate a node to simulate a restart. * @@ -119,11 +129,11 @@ class InMemoryMessagingNetwork private constructor( notaryService: PartyAndCertificate?, description: CordaX500Name = CordaX500Name(organisation = "In memory node $id", locality = "London", country = "UK"), database: CordaPersistence) - : TestMessagingService { + : InternalMockMessagingService { val peerHandle = PeerHandle(id, description) - peersMapping[peerHandle.description] = peerHandle // Assume that the same name - the same entity in MockNetwork. + peersMapping[peerHandle.name] = peerHandle // Assume that the same name - the same entity in MockNetwork. notaryService?.let { if (it.owningKey !is CompositeKey) peersMapping[it.name] = peerHandle } - val serviceHandles = notaryService?.let { listOf(ServiceHandle(it.party)) } + val serviceHandles = notaryService?.let { listOf(DistributedServiceHandle(it.party)) } ?: emptyList() //TODO only notary can be distributed? synchronized(this) { val node = InMemoryMessaging(manuallyPumped, peerHandle, executor, database) @@ -135,7 +145,8 @@ class InMemoryMessagingNetwork private constructor( } } - interface LatencyCalculator { // XXX: Used? + /** Implement this interface in order to inject artificial latency between sender/recipient pairs. */ + interface LatencyCalculator { fun between(sender: SingleMessageRecipient, receiver: SingleMessageRecipient): Duration } @@ -147,7 +158,7 @@ class InMemoryMessagingNetwork private constructor( @Synchronized private fun msgSend(from: InMemoryMessaging, message: Message, recipients: MessageRecipients) { messagesInFlight.countUp() - messageSendQueue += MessageTransfer(from.myAddress, message, recipients) + messageSendQueue += MessageTransfer.createMessageTransfer(from.myAddress, message, recipients) } @Synchronized @@ -159,12 +170,15 @@ class InMemoryMessagingNetwork private constructor( private fun getQueueForPeerHandle(recipients: PeerHandle) = messageReceiveQueues.getOrPut(recipients) { LinkedBlockingQueue() } @Synchronized - private fun getQueuesForServiceHandle(recipients: ServiceHandle): List> { + private fun getQueuesForServiceHandle(recipients: DistributedServiceHandle): List> { return serviceToPeersMapping[recipients]!!.map { messageReceiveQueues.getOrPut(it) { LinkedBlockingQueue() } } } + /** + * Stop all nodes within the network and clear any buffered messages + */ fun stop() { val nodes = synchronized(this) { counter = -1 @@ -179,15 +193,26 @@ class InMemoryMessagingNetwork private constructor( timer.cancel() } + /** + * A class which represents information about an entity on the [InMemoryMessagingNetwork]. + * + * @property id An integer giving the node an ID on the [InMemoryMessagingNetwork]. + * @property name The node's [CordaX500Name]. + */ @CordaSerializable - data class PeerHandle(val id: Int, val description: CordaX500Name) : SingleMessageRecipient { - override fun toString() = description.toString() + data class PeerHandle(val id: Int, val name: CordaX500Name) : SingleMessageRecipient { + override fun toString() = name.toString() override fun equals(other: Any?) = other is PeerHandle && other.id == id override fun hashCode() = id.hashCode() } + /** + * A class which represents information about nodes offering the same distributed service on the [InMemoryMessagingNetwork]. + * + * @property party The [Party] offering the service. + */ @CordaSerializable - data class ServiceHandle(val party: Party) : MessageRecipientGroup { + data class DistributedServiceHandle(val party: Party) : MessageRecipientGroup { override fun toString() = "Service($party)" } @@ -197,16 +222,16 @@ class InMemoryMessagingNetwork private constructor( */ @DoNotImplement sealed class ServicePeerAllocationStrategy { - abstract fun pickNext(service: ServiceHandle, pickFrom: List): A + abstract fun pickNext(service: DistributedServiceHandle, pickFrom: List): A class Random(val random: SplittableRandom = SplittableRandom()) : ServicePeerAllocationStrategy() { - override fun pickNext(service: ServiceHandle, pickFrom: List): A { + override fun pickNext(service: DistributedServiceHandle, pickFrom: List): A { return pickFrom[random.nextInt(pickFrom.size)] } } class RoundRobin : ServicePeerAllocationStrategy() { - private val previousPicks = HashMap() - override fun pickNext(service: ServiceHandle, pickFrom: List): A { + private val previousPicks = HashMap() + override fun pickNext(service: DistributedServiceHandle, pickFrom: List): A { val nextIndex = previousPicks.compute(service) { _, previous -> (previous?.plus(1) ?: 0) % pickFrom.size }!! @@ -215,7 +240,12 @@ class InMemoryMessagingNetwork private constructor( } } - // If block is set to true this function will only return once a message has been pushed onto the recipients' queues + /** + * Send the next queued message to the requested recipient(s) within the network + * + * @param block If set to true this function will only return once a message has been pushed onto the recipients' + * queues. This is only relevant if a [latencyCalculator] is being used to simulate latency in the network. + */ fun pumpSend(block: Boolean): MessageTransfer? { val transfer = (if (block) messageSendQueue.take() else messageSendQueue.poll()) ?: return null @@ -241,7 +271,7 @@ class InMemoryMessagingNetwork private constructor( private fun pumpSendInternal(transfer: MessageTransfer) { when (transfer.recipients) { is PeerHandle -> getQueueForPeerHandle(transfer.recipients).add(transfer) - is ServiceHandle -> { + is DistributedServiceHandle -> { val queues = getQueuesForServiceHandle(transfer.recipients) val queue = servicePeerAllocationStrategy.pickNext(transfer.recipients, queues) queue.add(transfer) @@ -257,13 +287,6 @@ class InMemoryMessagingNetwork private constructor( _sentMessages.onNext(transfer) } - data class InMemoryMessage(override val topic: String, - override val data: ByteSequence, - override val uniqueMessageId: String, - override val debugTimestamp: Instant = Instant.now()) : Message { - override fun toString() = "$topic#${String(data.bytes)}" - } - private data class InMemoryReceivedMessage(override val topic: String, override val data: ByteSequence, override val platformVersion: Int, @@ -272,21 +295,31 @@ class InMemoryMessagingNetwork private constructor( override val peer: CordaX500Name) : ReceivedMessage /** - * A [TestMessagingService] that provides a [MessagingService] abstraction that also contains the ability to + * A class that provides an abstraction over the nodes' messaging service that also contains the ability to * receive messages from the queue for testing purposes. */ - @DoNotImplement - interface TestMessagingService : MessagingService { - fun pumpReceive(block: Boolean): InMemoryMessagingNetwork.MessageTransfer? - fun stop() + class MockMessagingService private constructor(private val messagingService: InternalMockMessagingService) { + companion object { + internal fun createMockMessagingService(messagingService: InternalMockMessagingService): MockMessagingService { + return MockMessagingService(messagingService) + } + } + /** + * Delivers a single message from the internal queue. If there are no messages waiting to be delivered and block + * is true, waits until one has been provided on a different thread via send. If block is false, the return + * result indicates whether a message was delivered or not. + * + * @return the message that was processed, if any in this round. + */ + fun pumpReceive(block: Boolean): InMemoryMessagingNetwork.MessageTransfer? = messagingService.pumpReceive(block) } @ThreadSafe private inner class InMemoryMessaging(private val manuallyPumped: Boolean, private val peerHandle: PeerHandle, private val executor: AffinityExecutor, - private val database: CordaPersistence) : SingletonSerializeAsToken(), TestMessagingService { - inner class Handler(val topicSession: String, val callback: (ReceivedMessage, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration + private val database: CordaPersistence) : SingletonSerializeAsToken(), InternalMockMessagingService { + private inner class Handler(val topicSession: String, val callback: (ReceivedMessage, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration @Volatile private var running = true @@ -316,7 +349,7 @@ class InMemoryMessagingNetwork private constructor( return when (partyInfo) { is PartyInfo.SingleNode -> peersMapping[partyInfo.party.name] ?: throw IllegalArgumentException("No StartedMockNode for party ${partyInfo.party.name}") - is PartyInfo.DistributedNode -> ServiceHandle(partyInfo.party) + is PartyInfo.DistributedNode -> DistributedServiceHandle(partyInfo.party) } } @@ -454,6 +487,7 @@ class InMemoryMessagingNetwork private constructor( 1, message.uniqueMessageId, message.debugTimestamp, - sender.description) + sender.name) } } + diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockNetwork.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockNetwork.kt index bbcbf9f2cc..06da18f552 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockNetwork.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/MockNetwork.kt @@ -8,36 +8,38 @@ import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.node.NetworkParameters import net.corda.core.node.NodeInfo -import net.corda.node.VersionInfo +import net.corda.core.node.ServiceHub +import net.corda.core.utilities.getOrThrow import net.corda.node.internal.StartedNode -import net.corda.node.services.api.StartedNodeServices import net.corda.node.services.config.NodeConfiguration -import net.corda.node.services.messaging.MessagingService import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.node.internal.InternalMockMessagingService import net.corda.testing.node.internal.InternalMockNetwork -import net.corda.testing.node.internal.setMessagingServiceSpy +import net.corda.testing.node.internal.InternalMockNodeParameters +import net.corda.testing.node.internal.newContext import rx.Observable import java.math.BigInteger import java.nio.file.Path /** - * Extend this class in order to intercept and modify messages passing through the [MessagingService] when using the [InMemoryMessagingNetwork]. - */ -open class MessagingServiceSpy(val messagingService: MessagingService) : MessagingService by messagingService - -/** - * @param entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value, + * Immutable builder for configuring a [StartedMockNode] or an [UnstartedMockNode] via [MockNetwork.createNode] and + * [MockNetwork.createUnstartedNode]. Kotlin users can also use the named parameters overloads of those methods which + * are more convenient. + * + * @property forcedID Override the ID to use for the node. By default node ID's are generated sequentially in a + * [MockNetwork]. Specifying the same ID is required if a node is restarted. + * @property legalName The [CordaX500Name] name to use for the node. + * @property entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value, * but can be overridden to cause nodes to have stable or colliding identity/service keys. - * @param configOverrides add/override behaviour of the [NodeConfiguration] mock object. + * @property configOverrides Add/override behaviour of the [NodeConfiguration] mock object. */ @Suppress("unused") data class MockNodeParameters( val forcedID: Int? = null, val legalName: CordaX500Name? = null, val entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()), - val configOverrides: (NodeConfiguration) -> Any? = {}, - val version: VersionInfo = MockServices.MOCK_VERSION_INFO) { + val configOverrides: (NodeConfiguration) -> Any? = {}) { fun withForcedID(forcedID: Int?): MockNodeParameters = copy(forcedID = forcedID) fun withLegalName(legalName: CordaX500Name?): MockNodeParameters = copy(legalName = legalName) fun withEntropyRoot(entropyRoot: BigInteger): MockNodeParameters = copy(entropyRoot = entropyRoot) @@ -76,7 +78,13 @@ data class MockNetworkParameters( fun withNetworkParameters(networkParameters: NetworkParameters): MockNetworkParameters = copy(networkParameters = networkParameters) } -/** Represents a node configuration for injection via [MockNetworkParameters] */ +/** + * The spec for a notary which will used by the [MockNetwork] to automatically start a notary node. This notary will + * become part of the network parameters used by all the nodes. + * + * @property name The name of the notary node. + * @property validating Boolean for whether the notary is validating or non-validating. + */ data class MockNetworkNotarySpec(val name: CordaX500Name, val validating: Boolean = true) { constructor(name: CordaX500Name) : this(name, validating = true) } @@ -89,9 +97,15 @@ class UnstartedMockNode private constructor(private val node: InternalMockNetwor } } + /** An identifier for the node. By default this is allocated sequentially in a [MockNetwork] **/ val id get() : Int = node.id - /** Start the node **/ - fun start() = StartedMockNode.create(node.start()) + + /** + * Start the node + * + * @return A [StartedMockNode] object. + */ + fun start(): StartedMockNode = StartedMockNode.create(node.start()) } /** A class that represents a started mock node for testing. */ @@ -102,25 +116,34 @@ class StartedMockNode private constructor(private val node: StartedNode> registerInitiatedFlow(initiatedFlowClass: Class): Observable = node.registerInitiatedFlow(initiatedFlowClass) + /** The [ServiceHub] for the underlying node. **/ + val services get(): ServiceHub = node.services + /** An identifier for the node. By default this is allocated sequentially in a [MockNetwork]. **/ + val id get(): Int = node.internals.id + /** The [NodeInfo] for the underlying node. **/ + val info get(): NodeInfo = node.services.myInfo /** - * Attach a [MessagingServiceSpy] to the [InternalMockNetwork.MockNode] allowing - * interception and modification of messages. + * Starts an already constructed flow. Note that you must be on the server thread to call this method. + * @param context indicates who started the flow, see: [InvocationContext]. */ - fun setMessagingServiceSpy(messagingServiceSpy: MessagingServiceSpy) = node.setMessagingServiceSpy(messagingServiceSpy) + fun startFlow(logic: FlowLogic): CordaFuture = node.services.startFlow(logic, node.services.newContext()).getOrThrow().resultFuture - /** Stop the node **/ + /** Register a flow that is initiated by another flow .**/ + fun > registerInitiatedFlow(initiatedFlowClass: Class): Observable = node.registerInitiatedFlow(initiatedFlowClass) + + /** Stop the node. **/ fun stop() = node.internals.stop() - /** Receive a message from the queue. */ + /** + * Delivers a single message from the internal queue. If there are no messages waiting to be delivered and block + * is true, waits until one has been provided on a different thread via send. If block is false, the return + * result indicates whether a message was delivered or not. + * + * @return the message that was processed, if any in this round. + */ fun pumpReceive(block: Boolean = false): InMemoryMessagingNetwork.MessageTransfer? { - return (services.networkService as InMemoryMessagingNetwork.TestMessagingService).pumpReceive(block) + return (node.network as InternalMockMessagingService).pumpReceive(block) } /** Returns the currently live flows of type [flowClass], and their corresponding result future. */ @@ -128,6 +151,7 @@ class StartedMockNode private constructor(private val node: StartedNode transaction(statement: () -> T): T { @@ -158,6 +182,21 @@ class StartedMockNode private constructor(private val node: StartedNode, parameters: MockNetworkParameters = MockNetworkParameters()) : this(cordappPackages, defaultParameters = parameters) - private val internalMockNetwork = InternalMockNetwork( - cordappPackages, - defaultParameters, - networkSendManuallyPumped, - threadPerNode, - servicePeerAllocationStrategy, - notarySpecs, - networkParameters) - /** Which node will be used as the primary notary during transaction builds. */ - val defaultNotaryNode get() : StartedMockNode = StartedMockNode.create(internalMockNetwork.defaultNotaryNode) - /** The [Party] of the [defaultNotaryNode] */ - val defaultNotaryIdentity get() : Party = internalMockNetwork.defaultNotaryIdentity - /** A list of all notary nodes in the network that have been started. */ - val notaryNodes get() : List = internalMockNetwork.notaryNodes.map { StartedMockNode.create(it) } + + private val internalMockNetwork: InternalMockNetwork = InternalMockNetwork(cordappPackages, defaultParameters, networkSendManuallyPumped, threadPerNode, servicePeerAllocationStrategy, notarySpecs, networkParameters) + /** In a mock network, nodes have an incrementing integer ID. Real networks do not have this. Returns the next ID that will be used. */ - val nextNodeId get() : Int = internalMockNetwork.nextNodeId + val nextNodeId get(): Int = internalMockNetwork.nextNodeId + + /** + * Returns the single notary node on the network. Throws an exception if there are none or more than one. + * @see notaryNodes + */ + val defaultNotaryNode get(): StartedMockNode = StartedMockNode.create(internalMockNetwork.defaultNotaryNode) + + /** + * Return the identity of the default notary node. + * @see defaultNotaryNode + */ + val defaultNotaryIdentity get(): Party = internalMockNetwork.defaultNotaryIdentity + + /** + * Returns the list of notary nodes started by the network. + */ + val notaryNodes get(): List = internalMockNetwork.notaryNodes.map { StartedMockNode.create(it) } /** Create a started node with the given identity. **/ fun createPartyNode(legalName: CordaX500Name? = null): StartedMockNode = StartedMockNode.create(internalMockNetwork.createPartyNode(legalName)) /** Create a started node with the given parameters. **/ - fun createNode(parameters: MockNodeParameters = MockNodeParameters()): StartedMockNode = StartedMockNode.create(internalMockNetwork.createNode(parameters)) + fun createNode(parameters: MockNodeParameters = MockNodeParameters()): StartedMockNode = StartedMockNode.create(internalMockNetwork.createNode(InternalMockNodeParameters(parameters))) - /** Create a started node with the given parameters. - * @param legalName the node's legal name. - * @param forcedID a unique identifier for the node. - * @param entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value, + /** + * Create a started node with the given parameters. + * + * @param legalName The node's legal name. + * @param forcedID A unique identifier for the node. + * @param entropyRoot The initial entropy value to use when generating keys. Defaults to an (insecure) random value, * but can be overridden to cause nodes to have stable or colliding identity/service keys. - * @param configOverrides add/override behaviour of the [NodeConfiguration] mock object. - * @param version the mock node's platform, release, revision and vendor versions. + * @param configOverrides Add/override behaviour of the [NodeConfiguration] mock object. + * @param version The mock node's platform, release, revision and vendor versions. */ @JvmOverloads fun createNode(legalName: CordaX500Name? = null, forcedID: Int? = null, entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()), - configOverrides: (NodeConfiguration) -> Any? = {}, - version: VersionInfo = MockServices.MOCK_VERSION_INFO): StartedMockNode { - val parameters = MockNodeParameters(forcedID, legalName, entropyRoot, configOverrides, version) - return StartedMockNode.create(internalMockNetwork.createNode(parameters)) + configOverrides: (NodeConfiguration) -> Any? = {}): StartedMockNode { + val parameters = MockNodeParameters(forcedID, legalName, entropyRoot, configOverrides) + return StartedMockNode.create(internalMockNetwork.createNode(InternalMockNodeParameters(parameters))) } /** Create an unstarted node with the given parameters. **/ - fun createUnstartedNode(parameters: MockNodeParameters = MockNodeParameters()): UnstartedMockNode = UnstartedMockNode.create(internalMockNetwork.createUnstartedNode(parameters)) + fun createUnstartedNode(parameters: MockNodeParameters = MockNodeParameters()): UnstartedMockNode = UnstartedMockNode.create(internalMockNetwork.createUnstartedNode(InternalMockNodeParameters(parameters))) - /** Create an unstarted node with the given parameters. - * @param legalName the node's legal name. - * @param forcedID a unique identifier for the node. - * @param entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value, + /** + * Create an unstarted node with the given parameters. + * + * @param legalName The node's legal name. + * @param forcedID A unique identifier for the node. + * @param entropyRoot The initial entropy value to use when generating keys. Defaults to an (insecure) random value, * but can be overridden to cause nodes to have stable or colliding identity/service keys. - * @param configOverrides add/override behaviour of the [NodeConfiguration] mock object. - * @param version the mock node's platform, release, revision and vendor versions. + * @param configOverrides Add/override behaviour of the [NodeConfiguration] mock object. + * @param version The mock node's platform, release, revision and vendor versions. */ @JvmOverloads fun createUnstartedNode(legalName: CordaX500Name? = null, forcedID: Int? = null, entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()), - configOverrides: (NodeConfiguration) -> Any? = {}, - version: VersionInfo = MockServices.MOCK_VERSION_INFO): UnstartedMockNode { - val parameters = MockNodeParameters(forcedID, legalName, entropyRoot, configOverrides, version) - return UnstartedMockNode.create(internalMockNetwork.createUnstartedNode(parameters)) + configOverrides: (NodeConfiguration) -> Any? = {}): UnstartedMockNode { + val parameters = MockNodeParameters(forcedID, legalName, entropyRoot, configOverrides) + return UnstartedMockNode.create(internalMockNetwork.createUnstartedNode(InternalMockNodeParameters(parameters))) } /** Start all nodes that aren't already started. **/ 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 61099fff21..e7cfd31adc 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 @@ -10,13 +10,11 @@ import net.corda.core.crypto.* import net.corda.core.flows.FlowLogic import net.corda.core.identity.CordaX500Name import net.corda.core.identity.PartyAndCertificate -import net.corda.core.messaging.DataFeed import net.corda.core.messaging.FlowHandle import net.corda.core.messaging.FlowProgressHandle import net.corda.core.node.* import net.corda.core.node.services.* import net.corda.core.serialization.SerializeAsToken -import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.VersionInfo @@ -27,8 +25,6 @@ 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.identity.InMemoryIdentityService -import net.corda.node.services.keys.freshCertificate -import net.corda.node.services.keys.getSigner import net.corda.node.services.schema.HibernateObserver import net.corda.node.services.schema.NodeSchemaService import net.corda.node.services.transactions.InMemoryTransactionVerifierService @@ -40,17 +36,17 @@ import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.TestIdentity import net.corda.testing.internal.DEV_ROOT_CA import net.corda.testing.internal.MockCordappProvider +import net.corda.testing.node.internal.MockKeyManagementService +import net.corda.testing.node.internal.MockTransactionStorage import net.corda.testing.services.MockAttachmentStorage -import org.bouncycastle.operator.ContentSigner -import rx.Observable -import rx.subjects.PublishSubject import java.security.KeyPair -import java.security.PrivateKey -import java.security.PublicKey import java.sql.Connection import java.time.Clock import java.util.* +/** + * Returns a simple [InMemoryIdentityService] containing the supplied [identities]. + */ fun makeTestIdentityService(vararg identities: PartyAndCertificate) = InMemoryIdentityService(identities, DEV_ROOT_CA.certificate) /** @@ -64,16 +60,13 @@ fun makeTestIdentityService(vararg identities: PartyAndCertificate) = InMemoryId */ open class MockServices private constructor( cordappLoader: CordappLoader, - override val validatedTransactions: WritableTransactionStorage, + override val validatedTransactions: TransactionStorage, override val identityService: IdentityService, override val networkParameters: NetworkParameters, private val initialIdentity: TestIdentity, private val moreKeys: Array ) : ServiceHub { companion object { - @JvmStatic - val MOCK_VERSION_INFO = VersionInfo(1, "Mock release", "Mock revision", "Mock Vendor") - /** * Make properties appropriate for creating a DataSource for unit tests. * @@ -93,10 +86,11 @@ open class MockServices private constructor( /** * Makes database and mock services appropriate for unit tests. * - * @param moreKeys a list of additional [KeyPair] instances to be used by [MockServices]. - * @param identityService an instance of [IdentityService], see [makeTestIdentityService]. - * @param initialIdentity the first (typically sole) identity the services will represent. - * @return a pair where the first element is the instance of [CordaPersistence] and the second is [MockServices]. + * @param cordappPackages A [List] of cordapp packages to scan for any cordapp code, e.g. contract verification code, flows and services. + * @param identityService An instance of [IdentityService], see [makeTestIdentityService]. + * @param initialIdentity The first (typically sole) identity the services will represent. + * @param moreKeys A list of additional [KeyPair] instances to be used by [MockServices]. + * @return A pair where the first element is the instance of [CordaPersistence] and the second is [MockServices]. */ @JvmStatic @JvmOverloads @@ -111,12 +105,12 @@ open class MockServices private constructor( val database = configureDatabase(dataSourceProps, DatabaseConfig(), identityService, schemaService) val mockService = database.transaction { object : MockServices(cordappLoader, identityService, networkParameters, initialIdentity, moreKeys) { - override val vaultService: VaultServiceInternal = makeVaultService(database.hibernateConfig, schemaService) + override val vaultService: VaultService = makeVaultService(database.hibernateConfig, schemaService) override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable) { super.recordTransactions(statesToRecord, txs) // Refactored to use notifyAll() as we have no other unit test for that method with multiple transactions. - vaultService.notifyAll(statesToRecord, txs.map { it.coreTransaction }) + (vaultService as VaultServiceInternal).notifyAll(statesToRecord, txs.map { it.coreTransaction }) } override fun jdbcSession(): Connection = database.createSession() @@ -212,10 +206,9 @@ open class MockServices private constructor( */ constructor() : this(listOf(getCallerPackage()), CordaX500Name("TestIdentity", "", "GB"), makeTestIdentityService()) - override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable) { txs.forEach { - validatedTransactions.addTransaction(it) + (validatedTransactions as WritableTransactionStorage).addTransaction(it) } } @@ -241,7 +234,10 @@ open class MockServices private constructor( return vaultService } - val cordappServices: MutableClassToInstanceMap = MutableClassToInstanceMap.create() + // This needs to be internal as MutableClassToInstanceMap is a guava type and shouldn't be part of our public API + /** A map of available [CordaService] implementations */ + internal val cordappServices: MutableClassToInstanceMap = MutableClassToInstanceMap.create() + override fun cordaService(type: Class): T { require(type.isAnnotationPresent(CordaService::class.java)) { "${type.name} is not a Corda service" } return cordappServices.getInstance(type) @@ -252,6 +248,7 @@ open class MockServices private constructor( override fun registerUnloadHandler(runOnStop: () -> Unit) = throw UnsupportedOperationException() + /** Add the given package name to the list of packages which will be scanned for cordapp contract verification code */ fun addMockCordapp(contractClassName: ContractClassName) { mockCordappProvider.addMockCordapp(contractClassName, attachments) } @@ -260,70 +257,9 @@ open class MockServices private constructor( override fun loadStates(stateRefs: Set) = servicesForResolution.loadStates(stateRefs) } -class MockKeyManagementService(val identityService: IdentityService, - vararg initialKeys: KeyPair) : SingletonSerializeAsToken(), KeyManagementService { - private val keyStore: MutableMap = initialKeys.associateByTo(HashMap(), { it.public }, { it.private }) - - override val keys: Set get() = keyStore.keys - - private val nextKeys = LinkedList() - - override fun freshKey(): PublicKey { - val k = nextKeys.poll() ?: generateKeyPair() - keyStore[k.public] = k.private - return k.public - } - - 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) - } - - private fun getSigner(publicKey: PublicKey): ContentSigner = getSigner(getSigningKeyPair(publicKey)) - - private fun getSigningKeyPair(publicKey: PublicKey): KeyPair { - val pk = publicKey.keys.firstOrNull { keyStore.containsKey(it) } - ?: throw IllegalArgumentException("Public key not found: ${publicKey.toStringShort()}") - return KeyPair(pk, keyStore[pk]!!) - } - - override fun sign(bytes: ByteArray, publicKey: PublicKey): DigitalSignature.WithKey { - val keyPair = getSigningKeyPair(publicKey) - return keyPair.sign(bytes) - } - - override fun sign(signableData: SignableData, publicKey: PublicKey): TransactionSignature { - val keyPair = getSigningKeyPair(publicKey) - return keyPair.sign(signableData) - } -} - -open class MockTransactionStorage : WritableTransactionStorage, SingletonSerializeAsToken() { - override fun track(): DataFeed, SignedTransaction> { - return DataFeed(txns.values.toList(), _updatesPublisher) - } - - private val txns = HashMap() - - private val _updatesPublisher = PublishSubject.create() - - override val updates: Observable - get() = _updatesPublisher - - private fun notify(transaction: SignedTransaction) = _updatesPublisher.onNext(transaction) - - override fun addTransaction(transaction: SignedTransaction): Boolean { - val recorded = txns.putIfAbsent(transaction.id, transaction) == null - if (recorded) { - notify(transaction) - } - return recorded - } - - override fun getTransaction(id: SecureHash): SignedTransaction? = txns[id] -} - +/** + * Function which can be used to create a mock [CordaService] for use within testing, such as an Oracle. + */ fun createMockCordaService(serviceHub: MockServices, serviceConstructor: (AppServiceHub) -> T): T { class MockAppServiceHubImpl(val serviceHub: MockServices, serviceConstructor: (AppServiceHub) -> T) : AppServiceHub, ServiceHub by serviceHub { val serviceInstance: T = serviceConstructor(this) diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt index e156a1a847..6418205ee1 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt @@ -2,22 +2,16 @@ package net.corda.testing.node -import net.corda.core.concurrent.CordaFuture import net.corda.core.context.Actor import net.corda.core.context.AuthServiceId import net.corda.core.context.InvocationContext -import net.corda.core.context.InvocationOrigin -import net.corda.core.flows.FlowLogic import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.node.ServiceHub import net.corda.core.serialization.internal.effectiveSerializationEnv import net.corda.core.transactions.TransactionBuilder -import net.corda.core.utilities.getOrThrow -import net.corda.node.services.api.StartedNodeServices import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.core.TestIdentity -import net.corda.testing.core.chooseIdentity import net.corda.testing.dsl.* /** @@ -56,18 +50,8 @@ fun ServiceHub.transaction( TransactionDSL(TestTransactionDSLInterpreter(interpreter, TransactionBuilder(notary)), notary).script() } +/** Creates a new [Actor] for use in testing with the given [owningLegalIdentity]. */ fun testActor(owningLegalIdentity: CordaX500Name = CordaX500Name("Test Company Inc.", "London", "GB")) = Actor(Actor.Id("Only For Testing"), AuthServiceId("TEST"), owningLegalIdentity) -fun testContext(owningLegalIdentity: CordaX500Name = CordaX500Name("Test Company Inc.", "London", "GB")) = InvocationContext.rpc(testActor(owningLegalIdentity)) - -/** - * Starts an already constructed flow. Note that you must be on the server thread to call this method. [InvocationContext] - * has origin [InvocationOrigin.RPC] and actor with id "Only For Testing". - */ -fun StartedNodeServices.newContext() = testContext(myInfo.chooseIdentity().name) - -/** - * Starts an already constructed flow. Note that you must be on the server thread to call this method. [InvocationContext] - * has origin [Origin.RPC] and actor with id "Only For Testing". - */ -fun StartedNodeServices.startFlow(logic: FlowLogic): CordaFuture = startFlow(logic, newContext()).getOrThrow().resultFuture +/** Creates a new [InvocationContext] for use in testing with the given [owningLegalIdentity]. */ +fun testContext(owningLegalIdentity: CordaX500Name = CordaX500Name("Test Company Inc.", "London", "GB")) = InvocationContext.rpc(testActor(owningLegalIdentity)) \ No newline at end of file diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NotarySpec.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NotarySpec.kt index 348de42338..afde454e63 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NotarySpec.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NotarySpec.kt @@ -2,8 +2,18 @@ package net.corda.testing.node import net.corda.core.DoNotImplement import net.corda.core.identity.CordaX500Name -import net.corda.node.services.config.VerifierType +import net.corda.testing.driver.VerifierType +/** + * A notary spec for describing a notary which will be started automatically by the driver and which will be part of + * the network parameters used by all the nodes. + * + * @property name The name of the notary. If this is a notary cluster then each node member will be assigned a name based on this name. + * @property validating Boolean for whether the notary is validating or non-validating. + * @property rpcUsers A list of users able to instigate RPC for this node or cluster of nodes. + * @property verifierType How the notary will verify transactions. + * @property cluster [ClusterSpec] if this is a distributed cluster notary. If null then this is a single-node notary. + */ data class NotarySpec( val name: CordaX500Name, val validating: Boolean = true, @@ -12,10 +22,15 @@ data class NotarySpec( val cluster: ClusterSpec? = null ) +/** + * Abstract class specifying information about the consensus algorithm used for a cluster of nodes. + */ @DoNotImplement abstract class ClusterSpec { + /** The number of nodes within the cluster. **/ abstract val clusterSize: Int + /** A class representing the configuration of a raft consensus algorithm used for a cluster of nodes. **/ data class Raft( override val clusterSize: Int ) : ClusterSpec() { diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/User.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/User.kt index a60ea9fc26..fb8a1228d3 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/User.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/User.kt @@ -1,6 +1,12 @@ package net.corda.testing.node -/** Object encapsulating a node rpc user and their associated permissions for use when testing */ +/** + * Object encapsulating a node rpc user and their associated permissions for use when testing using the [driver] + * + * @property username The rpc user's username + * @property password The rpc user's password + * @property permissions A [List] of [String] detailing the [User]'s permissions + * */ data class User( val username: String, val password: String, diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt index e965855215..a15516debc 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt @@ -44,12 +44,12 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.driver.* +import net.corda.testing.driver.VerifierType import net.corda.testing.driver.internal.InProcessImpl import net.corda.testing.driver.internal.NodeHandleInternal import net.corda.testing.driver.internal.OutOfProcessImpl import net.corda.testing.internal.setGlobalSerialization import net.corda.testing.node.ClusterSpec -import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO import net.corda.testing.node.NotarySpec import net.corda.testing.node.User import net.corda.testing.node.internal.DriverDSLImpl.ClusterType.NON_VALIDATING_RAFT diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InMemoryMessage.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InMemoryMessage.kt new file mode 100644 index 0000000000..6ccf99c703 --- /dev/null +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InMemoryMessage.kt @@ -0,0 +1,15 @@ +package net.corda.testing.node.internal + +import net.corda.core.utilities.ByteSequence +import net.corda.node.services.messaging.Message +import java.time.Instant + +/** + * An implementation of [Message] for in memory messaging by the test [InMemoryMessagingNetwork]. + */ +data class InMemoryMessage(override val topic: String, + override val data: ByteSequence, + override val uniqueMessageId: String, + override val debugTimestamp: Instant = Instant.now()) : Message { + override fun toString() = "$topic#${String(data.bytes)}" +} \ No newline at end of file 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 df4b43ee1e..a663ed2b49 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 @@ -51,7 +51,6 @@ import net.corda.testing.internal.rigorousMock import net.corda.testing.internal.setGlobalSerialization import net.corda.testing.internal.testThreadFactory import net.corda.testing.node.* -import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import org.apache.activemq.artemis.utils.ReusableLatch import org.apache.sshd.common.util.security.SecurityUtils @@ -64,8 +63,10 @@ import java.time.Clock import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger +val MOCK_VERSION_INFO = VersionInfo(1, "Mock release", "Mock revision", "Mock Vendor") + fun StartedNode.pumpReceive(block: Boolean = false): InMemoryMessagingNetwork.MessageTransfer? { - return (network as InMemoryMessagingNetwork.TestMessagingService).pumpReceive(block) + return (network as InternalMockMessagingService).pumpReceive(block) } data class MockNodeArgs( @@ -76,6 +77,19 @@ data class MockNodeArgs( val version: VersionInfo = MOCK_VERSION_INFO ) +data class InternalMockNodeParameters( + val forcedID: Int? = null, + val legalName: CordaX500Name? = null, + val entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()), + val configOverrides: (NodeConfiguration) -> Any? = {}, + val version: VersionInfo = MOCK_VERSION_INFO) { + constructor(mockNodeParameters: MockNodeParameters) : this( + mockNodeParameters.forcedID, + mockNodeParameters.legalName, + mockNodeParameters.entropyRoot, + mockNodeParameters.configOverrides) +} + open class InternalMockNetwork(private val cordappPackages: List, defaultParameters: MockNetworkParameters = MockNetworkParameters(), val networkSendManuallyPumped: Boolean = defaultParameters.networkSendManuallyPumped, @@ -194,7 +208,7 @@ open class InternalMockNetwork(private val cordappPackages: List, @VisibleForTesting internal open fun createNotaries(): List> { return notarySpecs.map { (name, validating) -> - createNode(MockNodeParameters(legalName = name, configOverrides = { + createNode(InternalMockNodeParameters(legalName = name, configOverrides = { doReturn(NotaryConfig(validating)).whenever(it).notary })) } @@ -332,24 +346,24 @@ open class InternalMockNetwork(private val cordappPackages: List, } } - fun createUnstartedNode(parameters: MockNodeParameters = MockNodeParameters()): MockNode { + fun createUnstartedNode(parameters: InternalMockNodeParameters = InternalMockNodeParameters()): MockNode { return createUnstartedNode(parameters, defaultFactory) } - fun createUnstartedNode(parameters: MockNodeParameters = MockNodeParameters(), nodeFactory: (MockNodeArgs) -> N): N { + fun createUnstartedNode(parameters: InternalMockNodeParameters = InternalMockNodeParameters(), nodeFactory: (MockNodeArgs) -> N): N { return createNodeImpl(parameters, nodeFactory, false) } - fun createNode(parameters: MockNodeParameters = MockNodeParameters()): StartedNode { + fun createNode(parameters: InternalMockNodeParameters = InternalMockNodeParameters()): StartedNode { return createNode(parameters, defaultFactory) } /** Like the other [createNode] but takes a [nodeFactory] and propagates its [MockNode] subtype. */ - fun createNode(parameters: MockNodeParameters = MockNodeParameters(), nodeFactory: (MockNodeArgs) -> N): StartedNode { + fun createNode(parameters: InternalMockNodeParameters = InternalMockNodeParameters(), nodeFactory: (MockNodeArgs) -> N): StartedNode { return uncheckedCast(createNodeImpl(parameters, nodeFactory, true).started)!! } - private fun createNodeImpl(parameters: MockNodeParameters, nodeFactory: (MockNodeArgs) -> N, start: Boolean): N { + private fun createNodeImpl(parameters: InternalMockNodeParameters, nodeFactory: (MockNodeArgs) -> N, start: Boolean): N { val id = parameters.forcedID ?: nextNodeId++ val config = mockNodeConfiguration().also { doReturn(baseDirectory(id).createDirectories()).whenever(it).baseDirectory @@ -389,16 +403,15 @@ open class InternalMockNetwork(private val cordappPackages: List, } @JvmOverloads - fun createPartyNode(legalName: CordaX500Name? = null): StartedNode { - return createNode(MockNodeParameters(legalName = legalName)) + return createNode(InternalMockNodeParameters(legalName = legalName)) } @Suppress("unused") // This is used from the network visualiser tool. fun addressToNode(msgRecipient: MessageRecipients): MockNode { return when (msgRecipient) { is SingleMessageRecipient -> nodes.single { it.started!!.network.myAddress == msgRecipient } - is InMemoryMessagingNetwork.ServiceHandle -> { + is InMemoryMessagingNetwork.DistributedServiceHandle -> { nodes.firstOrNull { it.started!!.info.isLegalIdentity(msgRecipient.party) } ?: throw IllegalArgumentException("Couldn't find node advertising service with owning party name: ${msgRecipient.party.name} ") } @@ -428,6 +441,8 @@ open class InternalMockNetwork(private val cordappPackages: List, } +open class MessagingServiceSpy(val messagingService: MessagingService) : MessagingService by messagingService + /** * Attach a [MessagingServiceSpy] to the [InternalMockNetwork.MockNode] allowing interception and modification of messages. */ 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 5041dbde90..3d30e72712 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 @@ -2,6 +2,7 @@ package net.corda.testing.node.internal import net.corda.core.CordaException import net.corda.core.concurrent.CordaFuture +import net.corda.core.context.InvocationContext import net.corda.core.flows.FlowLogic import net.corda.core.internal.FlowStateMachine import net.corda.core.internal.concurrent.openFuture @@ -11,7 +12,11 @@ import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.millis import net.corda.core.utilities.seconds import net.corda.node.services.api.StartedNodeServices -import net.corda.testing.node.newContext +import net.corda.node.services.messaging.Message +import net.corda.node.services.messaging.MessagingService +import net.corda.testing.internal.chooseIdentity +import net.corda.testing.node.InMemoryMessagingNetwork +import net.corda.testing.node.testContext import org.slf4j.LoggerFactory import java.net.Socket import java.net.SocketException @@ -97,3 +102,15 @@ class ListenProcessDeathException(hostAndPort: NetworkHostAndPort, listenProcess CordaException("The process that was expected to listen on $hostAndPort has died with status: ${listenProcess.exitValue()}") fun StartedNodeServices.startFlow(logic: FlowLogic): FlowStateMachine = startFlow(logic, newContext()).getOrThrow() + +fun StartedNodeServices.newContext(): InvocationContext = testContext(myInfo.chooseIdentity().name) + +fun InMemoryMessagingNetwork.MessageTransfer.getMessage(): Message = message + +internal interface InternalMockMessagingService : MessagingService { + fun pumpReceive(block: Boolean): InMemoryMessagingNetwork.MessageTransfer? + + fun stop() +} + + 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 new file mode 100644 index 0000000000..fa835a2a49 --- /dev/null +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt @@ -0,0 +1,57 @@ +package net.corda.testing.node.internal + +import net.corda.core.crypto.* +import net.corda.core.identity.PartyAndCertificate +import net.corda.core.node.services.IdentityService +import net.corda.core.node.services.KeyManagementService +import net.corda.core.serialization.SingletonSerializeAsToken +import net.corda.node.services.keys.freshCertificate +import org.bouncycastle.operator.ContentSigner +import java.security.KeyPair +import java.security.PrivateKey +import java.security.PublicKey +import java.util.* + +/** + * A class which provides an implementation of [KeyManagementService] which is used in [MockServices] + * + * @property identityService The [IdentityService] which contains the given identities. + */ +class MockKeyManagementService(val identityService: IdentityService, + vararg initialKeys: KeyPair) : SingletonSerializeAsToken(), KeyManagementService { + private val keyStore: MutableMap = initialKeys.associateByTo(HashMap(), { it.public }, { it.private }) + + override val keys: Set get() = keyStore.keys + + private val nextKeys = LinkedList() + + override fun freshKey(): PublicKey { + val k = nextKeys.poll() ?: generateKeyPair() + keyStore[k.public] = k.private + return k.public + } + + 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) + } + + private fun getSigner(publicKey: PublicKey): ContentSigner = net.corda.node.services.keys.getSigner(getSigningKeyPair(publicKey)) + + private fun getSigningKeyPair(publicKey: PublicKey): KeyPair { + val pk = publicKey.keys.firstOrNull { keyStore.containsKey(it) } + ?: throw IllegalArgumentException("Public key not found: ${publicKey.toStringShort()}") + return KeyPair(pk, keyStore[pk]!!) + } + + override fun sign(bytes: ByteArray, publicKey: PublicKey): DigitalSignature.WithKey { + val keyPair = getSigningKeyPair(publicKey) + return keyPair.sign(bytes) + } + + override fun sign(signableData: SignableData, publicKey: PublicKey): TransactionSignature { + val keyPair = getSigningKeyPair(publicKey) + return keyPair.sign(signableData) + } +} \ No newline at end of file diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockTransactionStorage.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockTransactionStorage.kt new file mode 100644 index 0000000000..d18766c4f1 --- /dev/null +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockTransactionStorage.kt @@ -0,0 +1,38 @@ +package net.corda.testing.node.internal + +import net.corda.core.crypto.SecureHash +import net.corda.core.messaging.DataFeed +import net.corda.core.serialization.SingletonSerializeAsToken +import net.corda.core.transactions.SignedTransaction +import net.corda.node.services.api.WritableTransactionStorage +import rx.Observable +import rx.subjects.PublishSubject +import java.util.HashMap + +/** + * A class which provides an implementation of [WritableTransactionStorage] which is used in [MockServices] + */ +open class MockTransactionStorage : WritableTransactionStorage, SingletonSerializeAsToken() { + override fun track(): DataFeed, SignedTransaction> { + return DataFeed(txns.values.toList(), _updatesPublisher) + } + + private val txns = HashMap() + + private val _updatesPublisher = PublishSubject.create() + + override val updates: Observable + get() = _updatesPublisher + + private fun notify(transaction: SignedTransaction) = _updatesPublisher.onNext(transaction) + + override fun addTransaction(transaction: SignedTransaction): Boolean { + val recorded = txns.putIfAbsent(transaction.id, transaction) == null + if (recorded) { + notify(transaction) + } + return recorded + } + + override fun getTransaction(id: SecureHash): SignedTransaction? = txns[id] +} \ No newline at end of file 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 dd8237450b..8c8f0962fe 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 @@ -19,7 +19,6 @@ import net.corda.testing.node.User import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.getFreeLocalPorts import net.corda.testing.internal.testThreadFactory -import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO import org.apache.logging.log4j.Level import org.junit.After import org.junit.Before diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContract.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContract.kt index 3355b1fdf0..7a335b9968 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContract.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContract.kt @@ -9,12 +9,16 @@ import net.corda.core.transactions.TransactionBuilder // The dummy contract doesn't do anything useful. It exists for testing purposes, but has to be serializable +/** + * Dummy contract for testing purposes. Doesn't do anything useful. + */ data class DummyContract(val blank: Any? = null) : Contract { val PROGRAM_ID = "net.corda.testing.contracts.DummyContract" @DoNotImplement // State is effectively a sealed class. interface State : ContractState { + /** Some information that the state represents for test purposes. **/ val magicNumber: Int } @@ -47,6 +51,11 @@ data class DummyContract(val blank: Any? = null) : Contract { companion object { const val PROGRAM_ID: ContractClassName = "net.corda.testing.contracts.DummyContract" + /** + * Returns a [TransactionBuilder] with the given notary, a list of owners and an output state of type + * [SingleOwnerState] or [MultipleOwnerState] (depending on the number of owner parameters passed) containing + * the given magicNumber. + */ @JvmStatic fun generateInitial(magicNumber: Int, notary: Party, owner: PartyAndReference, vararg otherOwners: PartyAndReference): TransactionBuilder { val owners = listOf(owner) + otherOwners @@ -59,9 +68,15 @@ data class DummyContract(val blank: Any? = null) : Contract { } } + /** + * An overload of move for just one input state. + */ @JvmStatic fun move(prior: StateAndRef, newOwner: AbstractParty) = move(listOf(prior), newOwner) + /** + * Returns a [TransactionBuilder] that takes the given input states and transfers them to the newOwner. + */ @JvmStatic fun move(priors: List>, newOwner: AbstractParty): TransactionBuilder { require(priors.isNotEmpty()) diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyState.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyState.kt index e1047cb2e3..8502739712 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyState.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyState.kt @@ -6,6 +6,8 @@ import net.corda.core.identity.AbstractParty /** * Dummy state for use in testing. Not part of any contract, not even the [DummyContract]. */ -data class DummyState(val magicNumber: Int = 0) : ContractState { +data class DummyState( + /** Some information that the state represents for test purposes. **/ + val magicNumber: Int = 0) : ContractState { override val participants: List get() = emptyList() } diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt index 2125954fcd..2d1ea449c8 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt @@ -190,6 +190,9 @@ fun S.genericExpectEvents( finishFuture.getOrThrow() } +/** + * Part of the Expectation DSL + */ @DoNotImplement sealed class ExpectCompose { internal class Single(val expect: Expect) : ExpectCompose() diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/SerializationTestHelpers.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/SerializationTestHelpers.kt index 2feefc269b..2cebaecec3 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/SerializationTestHelpers.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/SerializationTestHelpers.kt @@ -28,7 +28,11 @@ import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService import java.util.concurrent.Executors -/** @param inheritable whether new threads inherit the environment, use sparingly. */ +/** + * A test serialization rule implementation for use in tests + * + * @param inheritable whether new threads inherit the environment, use sparingly. + */ class SerializationEnvironmentRule(private val inheritable: Boolean = false) : TestRule { companion object { init { @@ -71,10 +75,3 @@ class SerializationEnvironmentRule(private val inheritable: Boolean = false) : T } } } - -@DoNotImplement -interface GlobalSerializationEnvironment : SerializationEnvironment { - /** Unset this environment. */ - fun unset() -} - diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt index 6cbecab924..e11c081e59 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt @@ -10,28 +10,35 @@ import net.corda.nodeapi.internal.crypto.CertificateAndKeyPair import java.security.PublicKey import java.time.Instant -// A dummy time at which we will be pretending test transactions are created. -@JvmField -val TEST_TX_TIME = Instant.parse("2015-04-17T12:00:00.00Z") +/** A test notary name **/ @JvmField val DUMMY_NOTARY_NAME = CordaX500Name("Notary Service", "Zurich", "CH") +/** A test node name **/ @JvmField val DUMMY_BANK_A_NAME = CordaX500Name("Bank A", "London", "GB") +/** A test node name **/ @JvmField val DUMMY_BANK_B_NAME = CordaX500Name("Bank B", "New York", "US") +/** A test node name **/ @JvmField val DUMMY_BANK_C_NAME = CordaX500Name("Bank C", "Tokyo", "JP") +/** A test node name **/ @JvmField val BOC_NAME = CordaX500Name("BankOfCorda", "London", "GB") +/** A test node name **/ @JvmField val ALICE_NAME = CordaX500Name("Alice Corp", "Madrid", "ES") +/** A test node name **/ @JvmField val BOB_NAME = CordaX500Name("Bob Plc", "Rome", "IT") +/** A test node name **/ @JvmField val CHARLIE_NAME = CordaX500Name("Charlie Ltd", "Athens", "GR") +/** Generates a dummy command that doesn't do anything useful for use in tests **/ fun dummyCommand(vararg signers: PublicKey = arrayOf(generateKeyPair().public)) = Command(DummyCommandData, signers.toList()) +/** Trivial implementation of [TypeOnlyCommandData] for test purposes */ object DummyCommandData : TypeOnlyCommandData() /** Maximum artemis message size. 10 MiB maximum allowed file size for attachments, including message headers. */ diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestUtils.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestUtils.kt index 5229cde993..8d0f6047d6 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestUtils.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestUtils.kt @@ -18,7 +18,6 @@ import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.internal.createDevNodeCa import net.corda.nodeapi.internal.crypto.CertificateAndKeyPair import net.corda.nodeapi.internal.crypto.CertificateType -import net.corda.nodeapi.internal.crypto.X509CertificateFactory import net.corda.nodeapi.internal.crypto.X509Utilities import net.corda.testing.internal.DEV_INTERMEDIATE_CA import net.corda.testing.internal.DEV_ROOT_CA @@ -46,7 +45,8 @@ import java.util.concurrent.atomic.AtomicInteger * - The Int.DOLLARS syntax doesn't work from Java. Use the DOLLARS(int) function instead. */ -fun generateStateRef() = StateRef(SecureHash.randomSHA256(), 0) +/** Returns a fake state reference for testing purposes **/ +fun generateStateRef(): StateRef = StateRef(SecureHash.randomSHA256(), 0) private val freePortCounter = AtomicInteger(30000) /** @@ -100,6 +100,10 @@ fun getTestPartyAndCertificate(name: CordaX500Name, publicKey: PublicKey): Party return getTestPartyAndCertificate(Party(name, publicKey)) } +/** + * A class that encapsulates a test identity containing a [CordaX500Name] and a [KeyPair], alongside a range + * of utility methods for use during testing. + */ class TestIdentity(val name: CordaX500Name, val keyPair: KeyPair) { companion object { /** @@ -122,16 +126,11 @@ class TestIdentity(val name: CordaX500Name, val keyPair: KeyPair) { val publicKey: PublicKey get() = keyPair.public val party: Party = Party(name, publicKey) val identity: PartyAndCertificate by lazy { getTestPartyAndCertificate(party) } // Often not needed. + + /** Returns a [PartyAndReference] for this identity and the given reference */ fun ref(vararg bytes: Byte): PartyAndReference = party.ref(*bytes) } -/** - * Until we have proper handling of multiple identities per node, for tests we use the first identity as special one. - * TODO: Should be removed after multiple identities are introduced. - */ -fun NodeInfo.chooseIdentityAndCert(): PartyAndCertificate = legalIdentitiesAndCerts.first() - -fun NodeInfo.chooseIdentity(): Party = chooseIdentityAndCert().party /** * Extract a single identity from the node info. Throws an error if the node has multiple identities. */ diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TransactionDSLInterpreter.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TransactionDSLInterpreter.kt index 61e7ea1c9a..8bb0b6c492 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TransactionDSLInterpreter.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TransactionDSLInterpreter.kt @@ -76,6 +76,9 @@ interface TransactionDSLInterpreter : Verifies, OutputStateLookup { fun _attachment(contractClassName: ContractClassName) } +/** + * Underlying class for the transaction DSL. Do not instantiate directly, instead use the [transaction] function. + * */ class TransactionDSL(interpreter: T, private val notary: Party) : TransactionDSLInterpreter by interpreter { /** * Looks up the output label and adds the found state as an input. diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/services/FlowStackSnapshot.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt similarity index 99% rename from testing/test-utils/src/main/kotlin/net/corda/testing/services/FlowStackSnapshot.kt rename to testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt index 279f45e58f..6491d7e452 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/services/FlowStackSnapshot.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt @@ -1,4 +1,4 @@ -package net.corda.testing.services +package net.corda.testing.internal import co.paralleluniverse.fibers.Fiber import co.paralleluniverse.fibers.Instrumented diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalSerializationTestHelpers.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalSerializationTestHelpers.kt index aaa9e3a15d..5c706e686c 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalSerializationTestHelpers.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalSerializationTestHelpers.kt @@ -3,12 +3,12 @@ package net.corda.testing.internal import com.nhaarman.mockito_kotlin.doNothing import com.nhaarman.mockito_kotlin.whenever import net.corda.client.rpc.internal.KryoClientSerializationScheme +import net.corda.core.DoNotImplement import net.corda.core.serialization.internal.* import net.corda.node.serialization.KryoServerSerializationScheme import net.corda.nodeapi.internal.serialization.* import net.corda.nodeapi.internal.serialization.amqp.AMQPClientSerializationScheme import net.corda.nodeapi.internal.serialization.amqp.AMQPServerSerializationScheme -import net.corda.testing.core.GlobalSerializationEnvironment import net.corda.testing.core.SerializationEnvironmentRule import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService @@ -67,4 +67,11 @@ fun setGlobalSerialization(armed: Boolean): GlobalSerializationEnvironment { doNothing().whenever(it).unset() } } -} \ No newline at end of file +} + +@DoNotImplement +interface GlobalSerializationEnvironment : SerializationEnvironment { + /** Unset this environment. */ + fun unset() +} + diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt index d9165951a8..418bce072b 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt @@ -1,7 +1,12 @@ package net.corda.testing.internal import net.corda.nodeapi.internal.crypto.CertificateAndKeyPair +import java.time.Instant val DEV_INTERMEDIATE_CA: CertificateAndKeyPair by lazy { net.corda.nodeapi.internal.DEV_INTERMEDIATE_CA } val DEV_ROOT_CA: CertificateAndKeyPair by lazy { net.corda.nodeapi.internal.DEV_ROOT_CA } + +/** A dummy time at which we will be pretending test transactions are created. **/ +@JvmField +val TEST_TX_TIME = Instant.parse("2015-04-17T12:00:00.00Z") \ No newline at end of file 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 be8cd9a435..fd064cc6cf 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 @@ -4,6 +4,9 @@ import com.nhaarman.mockito_kotlin.doAnswer import net.corda.core.crypto.Crypto import net.corda.core.crypto.Crypto.generateKeyPair 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.utilities.NetworkHostAndPort import net.corda.core.utilities.loggerFor import net.corda.node.services.config.SslOptions @@ -136,3 +139,16 @@ fun SslOptions.noSslRpcOverrides(rpcAdminAddress: NetworkHostAndPort): Map>() + private val _files = HashMap>() + /** A map of the currently stored files by their [SecureHash] */ + val files: Map> get() = _files override fun importAttachment(jar: InputStream): AttachmentId = importAttachment(jar, UNKNOWN_UPLOADER, null) @@ -56,23 +52,22 @@ class MockAttachmentStorage : AttachmentStorage, SingletonSerializeAsToken() { fun importContractAttachment(contractClassNames: List, uploader: String, jar: InputStream): AttachmentId = importAttachmentInternal(jar, uploader, null, contractClassNames) - fun getAttachmentIdAndBytes(jar: InputStream): Pair = getBytes(jar).let { bytes -> Pair(bytes.sha256(), bytes) } + fun getAttachmentIdAndBytes(jar: InputStream): Pair = jar.readBytes().let { bytes -> Pair(bytes.sha256(), bytes) } - private class MockAttachment(dataLoader: () -> ByteArray, override val id: SecureHash): AbstractAttachment(dataLoader) + private class MockAttachment(dataLoader: () -> ByteArray, override val id: SecureHash) : AbstractAttachment(dataLoader) private fun importAttachmentInternal(jar: InputStream, uploader: String, filename: String?, contractClassNames: List? = null): AttachmentId { // JIS makes read()/readBytes() return bytes of the current file, but we want to hash the entire container here. require(jar !is JarInputStream) - val bytes = getBytes(jar) + val bytes = jar.readBytes() val sha256 = bytes.sha256() if (sha256 !in files.keys) { val baseAttachment = MockAttachment({ bytes }, sha256) val attachment = if (contractClassNames == null || contractClassNames.isEmpty()) baseAttachment else ContractAttachment(baseAttachment, contractClassNames.first(), contractClassNames.toSet(), uploader) - files[sha256] = Pair(attachment, bytes) + _files[sha256] = Pair(attachment, bytes) } return sha256 } - -} +} \ No newline at end of file diff --git a/testing/test-utils/src/main/resources/META-INF/services/net.corda.node.services.statemachine.FlowStackSnapshotFactory b/testing/test-utils/src/main/resources/META-INF/services/net.corda.node.services.statemachine.FlowStackSnapshotFactory index adc561e159..dcba0cd619 100644 --- a/testing/test-utils/src/main/resources/META-INF/services/net.corda.node.services.statemachine.FlowStackSnapshotFactory +++ b/testing/test-utils/src/main/resources/META-INF/services/net.corda.node.services.statemachine.FlowStackSnapshotFactory @@ -1 +1 @@ -net.corda.testing.services.FlowStackSnapshotFactoryImpl \ No newline at end of file +net.corda.testing.internal.FlowStackSnapshotFactoryImpl \ No newline at end of file diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt index d8431707f4..04f344817b 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt @@ -39,7 +39,7 @@ import net.corda.finance.flows.CashIssueAndPaymentFlow import net.corda.finance.flows.CashIssueAndPaymentFlow.IssueAndPaymentRequest import net.corda.finance.flows.CashPaymentFlow import net.corda.finance.flows.CashPaymentFlow.PaymentRequest -import net.corda.testing.core.chooseIdentityAndCert +import net.corda.testing.core.singleIdentityAndCert import org.controlsfx.dialog.ExceptionDialog import tornadofx.* import java.math.BigDecimal @@ -181,7 +181,7 @@ class NewTransaction : Fragment() { partyBLabel.textProperty().bind(transactionTypeCB.valueProperty().map { it?.partyNameB?.let { "$it : " } }) partyBChoiceBox.apply { visibleProperty().bind(transactionTypeCB.valueProperty().map { it?.partyNameB }.isNotNull()) - items = FXCollections.observableList(parties.map { it.chooseIdentityAndCert() }).sorted() + items = FXCollections.observableList(parties.map { it.singleIdentityAndCert() }).sorted() converter = stringConverter { it?.let { PartyNameFormatter.short.format(it.name) } ?: "" } } // Issuer diff --git a/tools/scripts/upgrade-test-packages.ps1 b/tools/scripts/upgrade-test-packages.ps1 index 79028809a2..034857a750 100644 --- a/tools/scripts/upgrade-test-packages.ps1 +++ b/tools/scripts/upgrade-test-packages.ps1 @@ -1,4 +1,4 @@ Get-ChildItem $args[0] -Include *.kt, *.java -Recurse | Foreach-Object { - (Get-Content $_.FullName) -replace 'net.corda.testing.(\*|generateStateRef|freeLocalHostAndPort|getFreeLocalPorts|getTestPartyAndCertificate|TestIdentity|chooseIdentity|singleIdentity|TEST_TX_TIME|DUMMY_NOTARY_NAME|DUMMY_BANK_A_NAME|DUMMY_BANK_B_NAME|DUMMY_BANK_C_NAME|BOC_NAME|ALICE_NAME|BOB_NAME|CHARLIE_NAME|DEV_INTERMEDIATE_CA|DEV_ROOT_CA|dummyCommand|DummyCommandData|MAX_MESSAGE_SIZE|SerializationEnvironmentRule|setGlobalSerialization|expect|sequence|parallel|replicate|genericExpectEvents)', 'net.corda.testing.core.$1' -replace 'net.corda.testing.FlowStackSnapshotFactoryImpl', 'net.corda.testing.services.FlowStackSnapshotFactoryImpl' -join "`r`n" | Set-Content -NoNewline -Force $_.FullName + (Get-Content $_.FullName) -replace 'net.corda.testing.(\*|generateStateRef|freeLocalHostAndPort|getFreeLocalPorts|getTestPartyAndCertificate|TestIdentity|chooseIdentity|singleIdentity|TEST_TX_TIME|DUMMY_NOTARY_NAME|DUMMY_BANK_A_NAME|DUMMY_BANK_B_NAME|DUMMY_BANK_C_NAME|BOC_NAME|ALICE_NAME|BOB_NAME|CHARLIE_NAME|DEV_INTERMEDIATE_CA|DEV_ROOT_CA|dummyCommand|DummyCommandData|MAX_MESSAGE_SIZE|SerializationEnvironmentRule|setGlobalSerialization|expect|sequence|parallel|replicate|genericExpectEvents)', 'net.corda.testing.core.$1' -join "`r`n" | Set-Content -NoNewline -Force $_.FullName } \ No newline at end of file diff --git a/tools/scripts/upgrade-test-packages.sh b/tools/scripts/upgrade-test-packages.sh index 1631126a11..466219c410 100644 --- a/tools/scripts/upgrade-test-packages.sh +++ b/tools/scripts/upgrade-test-packages.sh @@ -2,5 +2,4 @@ find $1 -type f \( -iname \*.kt -o -iname \*.java \) -exec sed -i " s/net.corda.testing.\(\*\|generateStateRef\|freeLocalHostAndPort\|getFreeLocalPorts\|getTestPartyAndCertificate\|TestIdentity\|chooseIdentity\|singleIdentity\|TEST_TX_TIME\|DUMMY_NOTARY_NAME\|DUMMY_BANK_A_NAME\|DUMMY_BANK_B_NAME\|DUMMY_BANK_C_NAME\|BOC_NAME\|ALICE_NAME\|BOB_NAME\|CHARLIE_NAME\|DEV_INTERMEDIATE_CA\|DEV_ROOT_CA\|dummyCommand\|DummyCommandData\|MAX_MESSAGE_SIZE\|SerializationEnvironmentRule\|setGlobalSerialization\|expect\|sequence\|parallel\|replicate\|genericExpectEvents\)/net.corda.testing.core.\1/g -s/net.corda.testing.FlowStackSnapshotFactoryImpl/net.corda.testing.services.FlowStackSnapshotFactoryImpl/g " '{}' \; \ No newline at end of file diff --git a/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierTests.kt b/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierTests.kt index 16b3d138a2..7cc31918e7 100644 --- a/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierTests.kt +++ b/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierTests.kt @@ -11,10 +11,10 @@ import net.corda.core.utilities.getOrThrow import net.corda.finance.DOLLARS import net.corda.finance.flows.CashIssueFlow import net.corda.finance.flows.CashPaymentFlow -import net.corda.node.services.config.VerifierType 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.driver.VerifierType import net.corda.testing.driver.internal.NodeHandleInternal import net.corda.testing.node.NotarySpec import org.junit.Ignore