diff --git a/.ci/api-current.txt b/.ci/api-current.txt index 831f9d431b..e512fab22b 100644 --- a/.ci/api-current.txt +++ b/.ci/api-current.txt @@ -1913,6 +1913,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) @@ -3015,6 +3017,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() @@ -3157,6 +3225,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 @@ -3168,6 +3237,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) @@ -3182,7 +3252,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) @@ -3747,7 +3820,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) ## @@ -3799,8 +3872,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 () @@ -3825,15 +3899,15 @@ 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, String) + public (net.corda.core.identity.CordaX500Name, List, net.corda.testing.driver.VerifierType, Map, Boolean, String, 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.Nullable public final String component7() - @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, 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, String) public boolean equals(Object) @org.jetbrains.annotations.NotNull public final Map getCustomOverrides() @org.jetbrains.annotations.Nullable public final String getLogLevel() @@ -3841,16 +3915,16 @@ public final class net.corda.testing.driver.NodeParameters extends java.lang.Obj @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 withLogLevel(String) @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) @@ -3869,6 +3943,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() ## @@ -3877,9 +3952,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) @@ -3906,7 +3982,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) @@ -3915,29 +3991,15 @@ 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, net.corda.node.services.statemachine.DeduplicationId, java.time.Instant, String) - @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 net.corda.node.services.statemachine.DeduplicationId component3() - @org.jetbrains.annotations.NotNull public final java.time.Instant component4() - @org.jetbrains.annotations.Nullable public final String component5() - @org.jetbrains.annotations.NotNull public final net.corda.testing.node.InMemoryMessagingNetwork$InMemoryMessage copy(String, net.corda.core.utilities.ByteSequence, net.corda.node.services.statemachine.DeduplicationId, java.time.Instant, String) +@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 Map getAdditionalHeaders() - @org.jetbrains.annotations.NotNull public net.corda.core.utilities.ByteSequence getData() - @org.jetbrains.annotations.NotNull public java.time.Instant getDebugTimestamp() - @org.jetbrains.annotations.Nullable public String getSenderUUID() - @org.jetbrains.annotations.NotNull public String getTopic() - @org.jetbrains.annotations.NotNull public net.corda.node.services.statemachine.DeduplicationId 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.Function3) - @org.jetbrains.annotations.NotNull public final kotlin.jvm.functions.Function3 getCallback() - @org.jetbrains.annotations.NotNull public final String getTopicSession() -## public static final class net.corda.testing.node.InMemoryMessagingNetwork$InMemoryMessaging$pumpReceiveInternal$1$1$acknowledgeHandle$1 extends java.lang.Object implements net.corda.node.services.messaging.AcknowledgeHandle public void acknowledge() public void persistDeduplicationId() @@ -3946,17 +4008,19 @@ public static interface net.corda.testing.node.InMemoryMessagingNetwork$LatencyC @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) @@ -3964,57 +4028,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.Function3) - public void cancelRedelivery(long) - @org.jetbrains.annotations.NotNull public net.corda.node.services.messaging.Message createMessage(String, byte[], net.corda.node.services.statemachine.DeduplicationId, Map) - @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) -## -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) @@ -4026,7 +4056,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() @@ -4034,7 +4063,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() @@ -4090,19 +4118,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) @@ -4130,15 +4156,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 final 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) @@ -4156,12 +4181,11 @@ 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, String, kotlin.jvm.functions.Function2) @kotlin.jvm.JvmStatic @org.jetbrains.annotations.NotNull public final net.corda.nodeapi.internal.persistence.DatabaseConfig makeTestDatabaseProperties(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) ## @@ -4208,38 +4232,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() - @org.jetbrains.annotations.NotNull public net.corda.core.concurrent.CordaFuture trackTransaction(net.corda.core.crypto.SecureHash) -## 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() ## @@ -4247,11 +4261,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 @@ -4501,9 +4514,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) @@ -4528,7 +4538,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) @@ -4545,8 +4554,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() @@ -4761,23 +4768,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) @@ -4785,8 +4779,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 5cb0945efa..d6789b3f02 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 @@ -10,13 +10,17 @@ import net.corda.node.internal.Node 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.* +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.core.DUMMY_NOTARY_NAME import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.driver import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.toDatabaseSchemaName import net.corda.testing.internal.toDatabaseSchemaNames +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 c171ee62c8..8e2cf20db4 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 052fce7b59..0bb65bb89b 100644 --- a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java +++ b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java @@ -15,7 +15,6 @@ import java.util.concurrent.Future; import static java.util.Collections.emptyList; import static net.corda.testing.core.TestUtils.singleIdentity; -import static net.corda.testing.node.NodeTestUtils.startFlow; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.Assert.fail; @@ -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 4f692580e9..bdd3d6ff2f 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 173af51a61..66eaaf8fe1 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 @@ -87,7 +87,7 @@ class IntegrationTestingTutorial : IntegrationTest() { (1..numberOfStates).map { i -> aliceProxy.startFlow(::CashPaymentFlow, i.DOLLARS, - bob.nodeInfo.chooseIdentity(), + bob.nodeInfo.singleIdentity(), true ).returnValue }.transpose().getOrThrow() @@ -109,7 +109,7 @@ class IntegrationTestingTutorial : IntegrationTest() { // START 5 for (i in 1..numberOfStates) { - 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 520304ee2f..80a42a12a2 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) { - - override fun send(message: Message, target: MessageRecipients, retryId: Long?, sequenceKey: Any) { - 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) - } - } - }) + // 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 - 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 0fe590c86a..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,24 +12,26 @@ import net.corda.testing.node.MockServices; import org.junit.Before; import org.junit.Test; +import java.time.Instant; import java.time.temporal.ChronoUnit; import static java.util.Collections.singletonList; 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; public class CommercialPaperTest { - private static final TestIdentity alice = new TestIdentity(ALICE_NAME, 70L); private static final TestIdentity bigCorp = new TestIdentity(new CordaX500Name("BigCorp", "New York", "GB")); 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; @Before 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 42d7db3d2a..4197ffc96e 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 @@ -22,6 +22,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 { @@ -30,6 +31,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 78b42d486c..36c1fd2585 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 f6c4d1b0dc..642c8b3e6c 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 ed54572be9..7d4ed7687c 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 c17e9af8d3..6498c4cc23 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 @@ -42,7 +41,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() @@ -53,7 +52,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 d1c52b7b7c..8b9ba26423 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt @@ -9,12 +9,10 @@ import net.corda.core.utilities.getOrThrow import net.corda.finance.DOLLARS import net.corda.finance.`issued by` import net.corda.finance.contracts.asset.Cash -import net.corda.node.internal.StartedNode import net.corda.testing.core.* import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin -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.MockNetwork +import net.corda.testing.node.StartedMockNode import org.junit.After import org.junit.Before import org.junit.Test @@ -22,20 +20,20 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith class CashPaymentFlowTests { - private lateinit var mockNet: InternalMockNetwork + private lateinit var mockNet: MockNetwork private val initialBalance = 2000.DOLLARS private val ref = OpaqueBytes.of(0x01) - private lateinit var bankOfCordaNode: StartedNode + private lateinit var bankOfCordaNode: StartedMockNode private lateinit var bankOfCorda: Party - private lateinit var aliceNode: StartedNode + private lateinit var aliceNode: StartedMockNode @Before fun start() { - mockNet = InternalMockNetwork(servicePeerAllocationStrategy = RoundRobin(), cordappPackages = listOf("net.corda.finance.contracts.asset", "net.corda.finance.schemas")) + mockNet = MockNetwork(servicePeerAllocationStrategy = RoundRobin(), cordappPackages = listOf("net.corda.finance.contracts.asset", "net.corda.finance.schemas")) 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() } @@ -46,17 +44,17 @@ 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 - bankOfCordaNode.database.transaction { + bankOfCordaNode.transaction { // Register for vault updates val criteria = QueryCriteria.VaultQueryCriteria(status = Vault.StateStatus.ALL) 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() @@ -85,9 +83,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 { @@ -97,9 +95,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 acef73f6fd..b4e6ea3b01 100644 --- a/node/src/integration-test/kotlin/net/corda/node/CordappScanningDriverTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/CordappScanningDriverTest.kt @@ -12,7 +12,7 @@ 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.DUMMY_NOTARY_NAME -import net.corda.testing.core.chooseIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.driver import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas @@ -40,7 +40,7 @@ class CordappScanningDriverTest : IntegrationTest() { 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/modes/draining/P2PFlowsDrainingModeTest.kt b/node/src/integration-test/kotlin/net/corda/node/modes/draining/P2PFlowsDrainingModeTest.kt index c93cbb898f..789cbd71d9 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 @@ -13,7 +13,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 @@ -56,7 +56,7 @@ class P2PFlowsDrainingModeTest { driver(DriverParameters(isDebug = true, startNodesInProcess = true, 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 4af4227678..1a441a860f 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 @@ -28,14 +28,14 @@ import net.corda.nodeapi.internal.DevIdentityGenerator import net.corda.nodeapi.internal.network.NetworkParametersCopier import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.contracts.DummyContract -import net.corda.testing.core.chooseIdentity import net.corda.testing.core.dummyCommand +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas -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.ClassRule @@ -78,7 +78,7 @@ class BFTNotaryServiceTests : IntegrationTest() { 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 })) @@ -98,10 +98,10 @@ class BFTNotaryServiceTests : IntegrationTest() { 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() @@ -122,7 +122,7 @@ class BFTNotaryServiceTests : IntegrationTest() { 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) @@ -136,7 +136,7 @@ class BFTNotaryServiceTests : IntegrationTest() { 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 } @@ -157,7 +157,7 @@ class BFTNotaryServiceTests : IntegrationTest() { 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) } } } @@ -166,7 +166,7 @@ class BFTNotaryServiceTests : IntegrationTest() { 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 a749674516..15be72b872 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 @@ -79,8 +79,9 @@ class DistributedServiceTests : IntegrationTest() { } 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() @@ -171,6 +172,6 @@ class DistributedServiceTests : IntegrationTest() { } 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/MySQLNotaryServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt index 60317e1ccf..8486cb67e7 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/MySQLNotaryServiceTests.kt @@ -20,15 +20,15 @@ import net.corda.nodeapi.internal.DevIdentityGenerator import net.corda.nodeapi.internal.network.NetworkParametersCopier import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.contracts.DummyContract -import net.corda.testing.core.chooseIdentity import net.corda.testing.core.dummyCommand +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import net.corda.testing.node.inMemoryH2DataSourceConfig 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.ClassRule @@ -77,22 +77,22 @@ class MySQLNotaryServiceTests : IntegrationTest() { val firstTxBuilder = TransactionBuilder(notaryParty) .addInputState(inputState) - .addCommand(dummyCommand(node.services.myInfo.chooseIdentity().owningKey)) + .addCommand(dummyCommand(node.services.myInfo.singleIdentity().owningKey)) val firstSpendTx = node.services.signInitialTransaction(firstTxBuilder) - val firstSpend = node.services.startFlow(NotaryFlow.Client(firstSpendTx)) + val firstSpend = node.services.startFlow(NotaryFlow.Client(firstSpendTx)).resultFuture mockNet.runNetwork() firstSpend.getOrThrow() val secondSpendBuilder = TransactionBuilder(notaryParty).withItems(inputState).run { - val dummyState = DummyContract.SingleOwnerState(0, node.info.chooseIdentity()) + val dummyState = DummyContract.SingleOwnerState(0, node.info.singleIdentity()) addOutputState(dummyState, DummyContract.PROGRAM_ID) - addCommand(dummyCommand(node.services.myInfo.chooseIdentity().owningKey)) + addCommand(dummyCommand(node.services.myInfo.singleIdentity().owningKey)) this } val secondSpendTx = node.services.signInitialTransaction(secondSpendBuilder) - val secondSpend = node.services.startFlow(NotaryFlow.Client(secondSpendTx)) + val secondSpend = node.services.startFlow(NotaryFlow.Client(secondSpendTx)).resultFuture mockNet.runNetwork() @@ -107,14 +107,14 @@ class MySQLNotaryServiceTests : IntegrationTest() { val txBuilder = TransactionBuilder(notaryParty) .addInputState(inputState) - .addCommand(dummyCommand(node.services.myInfo.chooseIdentity().owningKey)) + .addCommand(dummyCommand(node.services.myInfo.singleIdentity().owningKey)) val spendTx = node.services.signInitialTransaction(txBuilder) - val notarise = node.services.startFlow(NotaryFlow.Client(spendTx)) + val notarise = node.services.startFlow(NotaryFlow.Client(spendTx)).resultFuture mockNet.runNetwork() val signature = notarise.get().single() - val notariseRetry = node.services.startFlow(NotaryFlow.Client(spendTx)) + val notariseRetry = node.services.startFlow(NotaryFlow.Client(spendTx)).resultFuture mockNet.runNetwork() val signatureRetry = notariseRetry.get().single() @@ -132,7 +132,7 @@ class MySQLNotaryServiceTests : IntegrationTest() { setProperty("autoCommit", "false") } return mockNet.createUnstartedNode( - MockNodeParameters( + InternalMockNodeParameters( legalName = notaryName, entropyRoot = BigInteger.valueOf(60L), configOverrides = { @@ -145,7 +145,7 @@ class MySQLNotaryServiceTests : IntegrationTest() { private fun issueState(node: StartedNode, notary: Party): StateAndRef<*> { return node.database.transaction { - val builder = DummyContract.generateInitial(Random().nextInt(), notary, node.info.chooseIdentity().ref(0)) + val builder = DummyContract.generateInitial(Random().nextInt(), notary, node.info.singleIdentity().ref(0)) val stx = node.services.signInitialTransaction(builder) node.services.recordTransactions(stx) StateAndRef(builder.outputStates().first(), StateRef(stx.id, 0)) 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 2a2d18f68c..d8d828cf12 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 @@ -12,8 +12,8 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.getOrThrow import net.corda.testing.contracts.DummyContract import net.corda.testing.core.DUMMY_BANK_A_NAME -import net.corda.testing.core.chooseIdentity import net.corda.testing.core.dummyCommand +import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.driver import net.corda.testing.driver.internal.InProcessImpl @@ -22,7 +22,6 @@ import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.toDatabaseSchemaName import net.corda.testing.node.ClusterSpec import net.corda.testing.node.NotarySpec -import net.corda.testing.node.startFlow import org.junit.ClassRule import org.junit.Test import java.util.* @@ -49,20 +48,20 @@ class RaftNotaryServiceTests : IntegrationTest() { 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 @@ -73,7 +72,7 @@ class RaftNotaryServiceTests : IntegrationTest() { private fun issueState(nodeHandle: InProcessImpl, notary: Party): StateAndRef<*> { return nodeHandle.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 5a1cf8e40d..13b3812dd8 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 @@ -11,14 +11,14 @@ import net.corda.core.node.NodeInfo import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.seconds import net.corda.nodeapi.internal.network.NETWORK_PARAMS_FILE_NAME -import net.corda.testing.common.internal.testNetworkParameters import net.corda.nodeapi.internal.network.SignedNetworkParameters +import net.corda.testing.common.internal.testNetworkParameters 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.SerializationEnvironmentRule import net.corda.testing.driver.NodeHandle -import net.corda.testing.driver.PortAllocation +import net.corda.testing.driver.internal.RandomFree import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.toDatabaseSchemaName @@ -43,7 +43,7 @@ class NetworkMapTest : IntegrationTest() { 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 554a3829aa..98750f583e 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 @@ -38,7 +38,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. } } @@ -87,7 +87,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 45facffba8..6b18a1408c 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 @@ -12,9 +12,12 @@ import net.corda.testing.core.BOB_NAME import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.core.DUMMY_NOTARY_NAME import net.corda.testing.driver.DriverParameters -import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver -import net.corda.testing.internal.* +import net.corda.testing.driver.internal.RandomFree +import net.corda.testing.internal.IntegrationTest +import net.corda.testing.internal.IntegrationTestSchemas +import net.corda.testing.internal.toDatabaseSchemaName +import net.corda.testing.internal.useSslRpcOverrides import net.corda.testing.node.User import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule @@ -44,7 +47,7 @@ class RpcSslTest : IntegrationTest() { 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 { @@ -63,7 +66,7 @@ class RpcSslTest : IntegrationTest() { 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 9c054b068d..8171cae2fa 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 @@ -9,11 +9,11 @@ import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.toDatabaseSchemaName -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.ClassRule import org.junit.Test @@ -30,7 +30,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 783d793690..0476daef62 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 @@ -15,11 +15,11 @@ import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyState 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.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.toDatabaseSchemaName +import net.corda.testing.driver.internal.RandomFree import net.corda.testing.node.User import org.junit.ClassRule import org.junit.Test @@ -85,7 +85,7 @@ class LargeTransactionsTest : IntegrationTest() { 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 ce006792c5..454f735740 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 @@ -22,13 +22,13 @@ import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.NOTIFICATI 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.core.chooseIdentity import net.corda.testing.internal.IntegrationTestSchemas +import net.corda.testing.node.User +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.configureTestSSL import net.corda.testing.internal.toDatabaseSchemaName -import net.corda.testing.node.User 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 @@ -192,9 +192,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 a886b70d73..d75583b3d2 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,13 +16,14 @@ 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.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.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas +import net.corda.testing.internal.chooseIdentity import net.corda.testing.internal.toDatabaseSchemaName import net.corda.testing.node.ClusterSpec import net.corda.testing.node.NotarySpec @@ -57,7 +58,7 @@ class P2PMessagingTest : IntegrationTest() { 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" @@ -83,7 +84,7 @@ class P2PMessagingTest : IntegrationTest() { 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" @@ -106,7 +107,7 @@ class P2PMessagingTest : IntegrationTest() { 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() @@ -153,7 +154,7 @@ class P2PMessagingTest : IntegrationTest() { distributedServiceNodes.forEach { val nodeName = it.services.myInfo.chooseIdentity().name - it.services.networkService.addMessageHandler("test.request") { netMessage, _, handler -> + it.internalServices.networkService.addMessageHandler("test.request") { netMessage, _, handler -> crashingNodes.requestsReceived.incrementAndGet() crashingNodes.firstRequestReceived.countDown() // The node which receives the first request will ignore all requests @@ -165,8 +166,8 @@ class P2PMessagingTest : IntegrationTest() { } 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) } handler.acknowledge() } @@ -180,7 +181,7 @@ class P2PMessagingTest : IntegrationTest() { 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 @@ -196,20 +197,20 @@ class P2PMessagingTest : IntegrationTest() { } private fun InProcess.respondWith(message: Any) { - services.networkService.addMessageHandler("test.request") { netMessage, _, handle -> + internalServices.networkService.addMessageHandler("test.request") { netMessage, _, handle -> 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) handle.acknowledge() } } 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 eec2be291e..abdffb2720 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 @@ -22,8 +22,8 @@ import net.corda.node.services.Permissions.Companion.invokeRpc import net.corda.node.services.Permissions.Companion.startFlow 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.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.toDatabaseSchemaName @@ -52,10 +52,10 @@ class NodeStatePersistenceTests : IntegrationTest() { 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 { @@ -86,10 +86,10 @@ class NodeStatePersistenceTests : IntegrationTest() { 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 eeb6674fb1..70f97c40bc 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -42,6 +42,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.assertThat @@ -83,7 +84,7 @@ class CordaRPCOpsImplTest { @Before fun setup() { mockNet = InternalMockNetwork(cordappPackages = listOf("net.corda.finance.contracts.asset", "net.corda.finance.schemas")) - 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 7eedfc2fec..d250ddf7b1 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 15de453b0d..372982e2b2 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 90b7d4082a..a96f4abc6a 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 @@ -20,8 +20,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 @@ -52,8 +52,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 e09a95bc70..43dd68dc18 100644 --- a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTest.kt @@ -6,29 +6,20 @@ import com.nhaarman.mockito_kotlin.whenever import net.corda.core.crypto.generateKeyPair import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.internal.configureDatabase -import net.corda.node.services.config.CertChainPolicyConfig -import net.corda.node.services.config.EnterpriseConfiguration -import net.corda.node.services.config.MutualExclusionConfiguration -import net.corda.node.services.config.NodeConfiguration -import net.corda.node.services.config.configureWithDevSSLCertificate +import net.corda.node.services.config.* import net.corda.node.services.network.NetworkMapCacheImpl import net.corda.node.services.network.PersistentNetworkMapCache import net.corda.node.services.transactions.PersistentUniquenessProvider import net.corda.node.utilities.AffinityExecutor.ServiceAffinityExecutor import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.DatabaseConfig -import net.corda.testing.core.ALICE_NAME -import net.corda.testing.core.MAX_MESSAGE_SIZE -import net.corda.testing.core.SerializationEnvironmentRule -import net.corda.testing.core.freeLocalHostAndPort -import net.corda.testing.core.freePort +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.apache.activemq.artemis.api.core.Message.HDR_VALIDATED_USER import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.activemq.artemis.api.core.client.ClientMessage 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 af0f64ed01..b474cfa9d7 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 @@ -9,6 +9,7 @@ import net.corda.testing.core.getTestPartyAndCertificate 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 org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Test @@ -28,12 +29,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 d246e6dd7f..a705f3c52c 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 @@ -122,7 +123,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 8a501ee659..6f96c870e7 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 @@ -15,7 +15,7 @@ import net.corda.testing.driver.DriverParameters 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 @@ -31,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)) @@ -40,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 @@ -52,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 fdbfdef589..e4512c01af 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 @@ -35,11 +35,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 @@ -51,7 +48,6 @@ import rx.Notification import rx.Observable import java.time.Instant import java.util.* -import java.util.concurrent.ExecutionException import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -78,8 +74,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 } @@ -175,7 +171,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() @@ -193,7 +189,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. @@ -219,7 +215,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() } @@ -250,7 +246,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" @@ -408,7 +404,7 @@ class FlowFrameworkTests { @Test fun `FlowException only propagated to parent`() { - 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") } } @@ -421,7 +417,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 @@ -649,7 +645,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() @@ -709,9 +705,9 @@ class FlowFrameworkTests { } private fun Observable.toSessionTransfers(): Observable { - return filter { it.message.topic == FlowMessagingImpl.sessionTopic }.map { + return filter { it.getMessage().topic == FlowMessagingImpl.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 52a421a515..94af05d27a 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 @@ -17,19 +16,19 @@ 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 -import org.junit.Ignore import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class MaxTransactionSizeTests { 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 bobNode: StartedMockNode private lateinit var notary: Party private lateinit var alice: Party private lateinit var bob: Party @@ -37,10 +36,9 @@ class MaxTransactionSizeTests { @Before fun setup() { mockNet = MockNetwork(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 + 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() @@ -58,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() } @@ -81,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) } 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 a769783cf1..8007538ca8 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 @@ -19,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 @@ -38,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 @@ -63,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) @@ -79,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) @@ -94,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) @@ -111,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() @@ -139,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() @@ -173,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) } } @@ -184,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) } } @@ -195,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) } } @@ -209,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 { @@ -219,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) @@ -233,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 b17e75314f..cfeb6962aa 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.* import net.corda.testing.node.MockServices 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/perftestcordapp/src/integrationTest/kotlin/com/r3/corda/enterprise/perftestcordapp/NodePerformanceTests.kt b/perftestcordapp/src/integrationTest/kotlin/com/r3/corda/enterprise/perftestcordapp/NodePerformanceTests.kt index 6b63ff7c3e..60ff5179da 100644 --- a/perftestcordapp/src/integrationTest/kotlin/com/r3/corda/enterprise/perftestcordapp/NodePerformanceTests.kt +++ b/perftestcordapp/src/integrationTest/kotlin/com/r3/corda/enterprise/perftestcordapp/NodePerformanceTests.kt @@ -19,6 +19,7 @@ import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.InProcess import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver +import net.corda.testing.driver.internal.internalServices import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas import net.corda.testing.internal.performance.div @@ -92,7 +93,7 @@ class NodePerformanceTests : IntegrationTest() { driver(DriverParameters(startNodesInProcess = true)) { val a = startNode(rpcUsers = listOf(User("A", "A", setOf(startFlow())))).get() a as InProcess - val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, a.services.monitoringService.metrics) + val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, a.internalServices.monitoringService.metrics) CordaRPCClient(a.rpcAddress).use("A", "A") { connection -> startPublishingFixedRateInjector( metricRegistry = metricRegistry, @@ -112,7 +113,7 @@ class NodePerformanceTests : IntegrationTest() { driver(DriverParameters( startNodesInProcess = true, extraCordappPackagesToScan = listOf("net.corda.finance"))) { val a = startNode(rpcUsers = listOf(User("A", "A", setOf(startFlow())))).get() a as InProcess - val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, a.services.monitoringService.metrics) + val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, a.internalServices.monitoringService.metrics) CordaRPCClient(a.rpcAddress).use("A", "A") { connection -> startPublishingFixedRateInjector( metricRegistry = metricRegistry, @@ -137,7 +138,7 @@ class NodePerformanceTests : IntegrationTest() { portAllocation = PortAllocation.Incremental(20000) )) { val notary = defaultNotaryNode.getOrThrow() as InProcess - val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, notary.services.monitoringService.metrics) + val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, notary.internalServices.monitoringService.metrics) CordaRPCClient(notary.rpcAddress).use("A", "A") { connection -> startPublishingFixedRateInjector( metricRegistry = metricRegistry, @@ -163,7 +164,7 @@ class NodePerformanceTests : IntegrationTest() { val aliceFuture = startNode(providedName = ALICE_NAME, rpcUsers = listOf(user), startInSameProcess = true) val alice = aliceFuture.getOrThrow() as InProcess defaultNotaryNode.getOrThrow() - val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, alice.services.monitoringService.metrics) + val metricRegistry = startReporter((this as InternalDriverDSL).shutdownManager, alice.internalServices.monitoringService.metrics) CordaRPCClient(alice.rpcAddress).use("A", "A") { connection -> startPublishingFixedRateInjector( metricRegistry = metricRegistry, diff --git a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/CommercialPaperTests.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/CommercialPaperTests.kt index e967e99c7e..f280e1c1c4 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/CommercialPaperTests.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/CommercialPaperTests.kt @@ -20,6 +20,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.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.ledger diff --git a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashSelectionH2Test.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashSelectionH2Test.kt index 6e8a3c5ecb..0a49dd8a9b 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashSelectionH2Test.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashSelectionH2Test.kt @@ -10,7 +10,6 @@ import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.getOrThrow 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 @@ -33,10 +32,10 @@ class CashSelectionH2Test { // 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 @@ -48,9 +47,9 @@ class CashSelectionH2Test { 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/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashTests.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashTests.kt index 9498154bf4..4ef010d847 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashTests.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/contracts/asset/CashTests.kt @@ -62,7 +62,7 @@ fun ServiceHub.fillWithSomeTestCash(howMuch: Amount, ref: OpaqueBytes = OpaqueBytes(ByteArray(1, { 1 })), ownedBy: AbstractParty? = null, issuedBy: PartyAndReference = DUMMY_CASH_ISSUER): Vault { - val myKey = ownedBy?.owningKey ?: myInfo.chooseIdentity().owningKey + val myKey = ownedBy?.owningKey ?: myInfo.singleIdentity().owningKey val anonParty = AnonymousParty(myKey) // We will allocate one state to one transaction, for simplicities sake. diff --git a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlowTests.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlowTests.kt index 50c439c99a..3b4ed5eccd 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashExitFlowTests.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/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/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentFlowTests.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentFlowTests.kt index 6d0c32e2dd..4cd16076d1 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentFlowTests.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentFlowTests.kt @@ -13,7 +13,7 @@ import net.corda.node.internal.StartedNode import net.corda.testing.core.* import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin 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 @@ -33,7 +33,7 @@ class CashIssueAndPaymentFlowTests { cordappPackages = listOf("com.r3.corda.enterprise.perftestcordapp.contracts.asset", "com.r3.corda.enterprise.perftestcordapp.schemas")) bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) aliceNode = mockNet.createPartyNode(ALICE_NAME) - bankOfCorda = bankOfCordaNode.info.chooseIdentity() + bankOfCorda = bankOfCordaNode.info.singleIdentity() mockNet.runNetwork() notary = mockNet.defaultNotaryIdentity } @@ -45,7 +45,7 @@ class CashIssueAndPaymentFlowTests { @Test fun `issue and pay some cash`() { - val payTo = aliceNode.info.chooseIdentity() + val payTo = aliceNode.info.singleIdentity() val expectedPayment = 500.DOLLARS bankOfCordaNode.database.transaction { @@ -54,7 +54,7 @@ class CashIssueAndPaymentFlowTests { val (_, vaultUpdatesBoc) = bankOfCordaNode.services.vaultService.trackBy(criteria) val (_, vaultUpdatesBankClient) = aliceNode.services.vaultService.trackBy(criteria) - val future = bankOfCordaNode.services.startFlow(CashIssueAndPaymentFlow(expectedPayment, OpaqueBytes.of(1), payTo, false, notary)) + val future = bankOfCordaNode.services.startFlow(CashIssueAndPaymentFlow(expectedPayment, OpaqueBytes.of(1), payTo, false, notary)).resultFuture mockNet.runNetwork() future.getOrThrow() diff --git a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelectionFlowTest.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelectionFlowTest.kt index 7207975eac..cd7225d0f4 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelectionFlowTest.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueAndPaymentNoSelectionFlowTest.kt @@ -15,7 +15,7 @@ import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStra import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode 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 @@ -44,7 +44,7 @@ class CashIssueAndPayNoSelectionTests(private val anonymous: Boolean) { cordappPackages = listOf("com.r3.corda.enterprise.perftestcordapp.contracts.asset", "com.r3.corda.enterprise.perftestcordapp.schemas")) bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) aliceNode = mockNet.createPartyNode(ALICE_NAME) - bankOfCorda = bankOfCordaNode.info.chooseIdentity() + bankOfCorda = bankOfCordaNode.info.singleIdentity() mockNet.runNetwork() notary = mockNet.defaultNotaryIdentity } @@ -56,7 +56,7 @@ class CashIssueAndPayNoSelectionTests(private val anonymous: Boolean) { @Test fun `issue and pay some cash`() { - val payTo = aliceNode.info.chooseIdentity() + val payTo = aliceNode.info.singleIdentity() val expectedPayment = 500.DOLLARS bankOfCordaNode.database.transaction { @@ -68,7 +68,7 @@ class CashIssueAndPayNoSelectionTests(private val anonymous: Boolean) { = aliceNode.services.vaultService.trackBy(criteria) val future = bankOfCordaNode.services.startFlow(CashIssueAndPaymentNoSelection( - expectedPayment, OpaqueBytes.of(1), payTo, anonymous, notary)) + expectedPayment, OpaqueBytes.of(1), payTo, anonymous, notary)).resultFuture mockNet.runNetwork() future.getOrThrow() diff --git a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlowTests.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlowTests.kt index 29751c0acd..4c5a6ea0a3 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashIssueFlowTests.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/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 @@ -42,7 +41,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() @@ -53,7 +52,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/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlowTests.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlowTests.kt index be49181d35..37e9235808 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlowTests.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/CashPaymentFlowTests.kt @@ -13,7 +13,7 @@ import net.corda.node.internal.StartedNode import net.corda.testing.core.* import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin 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 @@ -35,9 +35,9 @@ class CashPaymentFlowTests { cordappPackages = listOf("com.r3.corda.enterprise.perftestcordapp.contracts.asset", "com.r3.corda.enterprise.perftestcordapp.schemas")) bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) aliceNode = mockNet.createPartyNode(ALICE_NAME) - bankOfCorda = bankOfCordaNode.info.chooseIdentity() + bankOfCorda = bankOfCordaNode.info.singleIdentity() mockNet.runNetwork() - val future = bankOfCordaNode.services.startFlow(CashIssueFlow(initialBalance, ref, mockNet.defaultNotaryIdentity)) + val future = bankOfCordaNode.services.startFlow(CashIssueFlow(initialBalance, ref, mockNet.defaultNotaryIdentity)).resultFuture future.getOrThrow() } @@ -48,7 +48,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 @@ -59,7 +59,7 @@ class CashPaymentFlowTests { val (_, vaultUpdatesBankClient) = aliceNode.services.vaultService.trackBy(criteria) val future = bankOfCordaNode.services.startFlow(CashPaymentFlow(expectedPayment, - payTo)) + payTo)).resultFuture mockNet.runNetwork() future.getOrThrow() @@ -88,10 +88,10 @@ 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, - payTo)) + payTo)).resultFuture mockNet.runNetwork() assertFailsWith { future.getOrThrow() @@ -100,10 +100,10 @@ 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, - payTo)) + payTo)).resultFuture mockNet.runNetwork() assertFailsWith { future.getOrThrow() diff --git a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/TwoPartyTradeFlowTest.kt b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/TwoPartyTradeFlowTest.kt index d8e6c2afc5..31566345a6 100644 --- a/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/TwoPartyTradeFlowTest.kt +++ b/perftestcordapp/src/test/kotlin/com/r3/corda/enterprise/perftestcordapp/flows/TwoPartyTradeFlowTest.kt @@ -51,10 +51,13 @@ import net.corda.testing.dsl.LedgerDSL import net.corda.testing.dsl.TestLedgerDSLInterpreter import net.corda.testing.dsl.TestTransactionDSLInterpreter import net.corda.testing.internal.LogHelper +import net.corda.testing.internal.TEST_TX_TIME import net.corda.testing.internal.rigorousMock 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 @@ -292,7 +295,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 @@ -327,7 +330,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) { 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 { @@ -552,7 +555,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/samples/irs-demo/README.md b/samples/irs-demo/README.md index 22b3364c4a..a3e5060a98 100644 --- a/samples/irs-demo/README.md +++ b/samples/irs-demo/README.md @@ -1,14 +1,14 @@ # IRS Demo -This demo brings up three nodes: Bank A, Bank B and a node that simultaneously runs a notary, a network map and an -interest rates oracle. The two banks agree on an interest rate swap, and then do regular fixings of the deal as the +This demo brings up three nodes: Bank A, Bank B and a node that simultaneously runs a notary, a network map and an +interest rates oracle. The two banks agree on an interest rate swap, and then do regular fixings of the deal as the time on a simulated clock passes. -Functionality is split into two parts - CordApp which provides actual distributed ledger backend and Spring Boot +Functionality is split into two parts - CordApp which provides actual distributed ledger backend and Spring Boot webapp which provides REST API and web frontend. Application communicate using Corda RPC protocol. To run from the command line in Unix: -1. Run ``./gradlew samples:irs-demo:cordapp:deployNodes`` to install configs and a command line tool under +1. Run ``./gradlew samples:irs-demo:cordapp:deployNodes`` to install configs and a command line tool under ``samples/irs-demo/cordapp/build`` 2. Run ``./gradlew samples:irs-demo:web:deployWebapps`` to install configs and tools for running webservers 3. Move to the ``samples/irs-demo/`` directory @@ -18,22 +18,22 @@ To run from the command line in Unix: To run from the command line in Windows: -1. Run ``gradlew.bat samples:irs-demo:cordapp:deployNodes`` to install configs and a command line tool under +1. Run ``gradlew.bat samples:irs-demo:cordapp:deployNodes`` to install configs and a command line tool under ``samples\irs-demo\build`` 2. Run ``gradlew.bat samples:irs-demo:web:deployWebapps`` to install configs and tools for running webservers 3. Run ``cd samples\irs-demo`` to change current working directory 4. Run ``cordapp\build\nodes\runnodes.bat`` to open up several 3 terminals for each nodes -5. Run ``web\build\webapps\webapps.bat`` to open up several 3 terminals for each nodes' webservers +5. Run ``web\build\webapps\runwebapps.bat`` to open up several 3 terminals for each nodes' webservers -This demo also has a web app. To use this, run nodes and then navigate to http://localhost:10007/ and +This demo also has a web app. To use this, run nodes and then navigate to http://localhost:10007/ and http://localhost:10010/ to see each node's view of the ledger. -To use the web app, click the "Create Deal" button, fill in the form, then click the "Submit" button. You can then use -the time controls at the top left of the home page to run the fixings. Click any individual trade in the blotter to +To use the web app, click the "Create Deal" button, fill in the form, then click the "Submit" button. You can then use +the time controls at the top left of the home page to run the fixings. Click any individual trade in the blotter to view it. -*Note:* The IRS web UI currently has a bug when changing the clock time where it may show no numbers or apply fixings -inconsistently. The issues will be addressed in a future milestone release. Meanwhile, you can take a look at a simpler +*Note:* The IRS web UI currently has a bug when changing the clock time where it may show no numbers or apply fixings +inconsistently. The issues will be addressed in a future milestone release. Meanwhile, you can take a look at a simpler oracle example here: https://github.com/corda/oracle-example. ## Running the system test @@ -52,9 +52,8 @@ Having this done, the system test can be run by running the Gradle task ``:sampl ### Other -In order to run the the test by other means that the Gradle task - two more system properties are expected - -``CORDAPP_DOCKER_COMPOSE`` and ``WEB_DOCKER_COMPOSE`` which should specify full path docker-compose file for IRS cordapp - and web frontend respectively. Those can be obtained by running ``:samples:irs-demo:cordapp:prepareDockerNodes`` and +In order to run the the test by other means that the Gradle task - two more system properties are expected - +``CORDAPP_DOCKER_COMPOSE`` and ``WEB_DOCKER_COMPOSE`` which should specify full path docker-compose file for IRS cordapp + and web frontend respectively. Those can be obtained by running ``:samples:irs-demo:cordapp:prepareDockerNodes`` and ``web:generateDockerCompose`` Gradle tasks. ``systemTest`` task simply executes those two and set proper system properties up. - \ No newline at end of file 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 839b2b229d..f0ed63f05a 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 76d1af97a4..551d3b5230 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 @@ -26,7 +26,7 @@ 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.internal.IntegrationTest @@ -92,7 +92,7 @@ class IRSDemoTest : IntegrationTest() { 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/irs-demo/web/src/test/resources/scripts/runwebapps.bat b/samples/irs-demo/web/src/test/resources/scripts/runwebapps.bat index c92810b5ef..cb90978f70 100755 --- a/samples/irs-demo/web/src/test/resources/scripts/runwebapps.bat +++ b/samples/irs-demo/web/src/test/resources/scripts/runwebapps.bat @@ -1,3 +1,4 @@ -cmd /C start java -Dspring.profiles.active=NotaryService -jar #JAR_PATH# -cmd /C start java -Dspring.profiles.active=BankA -jar #JAR_PATH# -cmd /C start java -Dspring.profiles.active=BankB -jar #JAR_PATH# \ No newline at end of file +SET scriptpath=%~dp0 +cmd /C start java -Dspring.profiles.active=NotaryService -jar %scriptpath%#JAR_PATH# +cmd /C start java -Dspring.profiles.active=BankA -jar %scriptpath%#JAR_PATH# +cmd /C start java -Dspring.profiles.active=BankB -jar %scriptpath%#JAR_PATH# 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 768d06bcc6..3a8c2fccec 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 @@ -9,6 +9,10 @@ import net.corda.finance.flows.CashPaymentFlow import net.corda.node.services.Permissions.Companion.all import net.corda.node.services.Permissions.Companion.startFlow import net.corda.testing.core.* +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.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.InProcess import net.corda.testing.driver.driver @@ -63,8 +67,8 @@ class TraderDemoTest : IntegrationTest() { 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 51f12643cb..35631ef5be 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 @@ -14,6 +14,7 @@ import net.corda.testing.common.internal.ProjectStructure.projectRootDir 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.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas @@ -79,7 +80,7 @@ class DriverTests : IntegrationTest() { @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 aaa54796e0..c4e277db8f 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 @@ -2,6 +2,7 @@ package net.corda.testing.driver +import net.corda.core.CordaInternal import net.corda.core.DoNotImplement import net.corda.core.concurrent.CordaFuture import net.corda.core.flows.FlowLogic @@ -10,17 +11,19 @@ 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.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 @@ -33,18 +36,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 +64,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, @@ -105,13 +150,15 @@ 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) fun withLogLevel(logLevel: String?): NodeParameters = copy(logLevel = logLevel) } /** + * 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. @@ -164,24 +211,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 parmeters to be used by all the nodes. [NetworkParameters.notaries] must be - * empty as notaries are defined by [notarySpecs]. + * @property networkParameters The network parameters to be used by all the nodes. [NetworkParameters.notaries] must be + * 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 a885289b2b..69cfab4404 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,8 +12,11 @@ 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 interface NodeHandleInternal : NodeHandle { @@ -72,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 4fdeb91e63..ca19473cc7 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 @@ -27,7 +27,8 @@ import net.corda.node.services.messaging.ReceivedMessage import net.corda.node.services.statemachine.DeduplicationId 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 @@ -41,8 +42,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). @@ -71,8 +72,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'" } @@ -81,7 +90,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 @@ -94,16 +103,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. * @@ -121,11 +132,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) @@ -137,7 +148,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 } @@ -149,7 +161,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 @@ -161,12 +173,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 @@ -181,15 +196,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)" } @@ -199,16 +225,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 }!! @@ -217,7 +243,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 @@ -243,7 +274,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) @@ -259,17 +290,6 @@ class InMemoryMessagingNetwork private constructor( _sentMessages.onNext(transfer) } - data class InMemoryMessage(override val topic: String, - override val data: ByteSequence, - override val uniqueMessageId: DeduplicationId, - override val debugTimestamp: Instant = Instant.now(), - override val senderUUID: String? = null) : Message { - - override val additionalHeaders: Map = emptyMap() - - override fun toString() = "$topic#${String(data.bytes)}" - } - private data class InMemoryReceivedMessage(override val topic: String, override val data: ByteSequence, override val platformVersion: Int, @@ -283,21 +303,31 @@ class InMemoryMessagingNetwork private constructor( } /** - * 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: MessageHandler) : MessageHandlerRegistration + private val database: CordaPersistence) : SingletonSerializeAsToken(), InternalMockMessagingService { + private inner class Handler(val topicSession: String, val callback: MessageHandler) : MessageHandlerRegistration @Volatile private var running = true @@ -327,7 +357,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) } } @@ -471,6 +501,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 d550695bc5..05c9ca5d30 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) @@ -77,7 +79,13 @@ data class MockNetworkParameters( fun withNotarySpecs(notarySpecs: List): MockNetworkParameters = copy(notarySpecs = notarySpecs) } -/** 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) } @@ -90,9 +98,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. */ @@ -103,30 +117,44 @@ 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. */ fun > findStateMachines(flowClass: Class): List>> = node.smm.findStateMachines(flowClass) + /** + * Executes given statement in the scope of transaction. + * + * @param statement to be executed in the scope of this transaction. + */ fun transaction(statement: () -> T): T { return node.database.transaction { statement() @@ -154,6 +182,23 @@ class StartedMockNode private constructor(private val node: StartedNode = internalMockNetwork.notaryNodes.map { StartedMockNode.create(it) } /** 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 + /** + * 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, + * @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, + * @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 7d56559cbf..69958cf7cf 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 @@ -4,28 +4,20 @@ import com.google.common.collect.MutableClassToInstanceMap import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigParseOptions -import net.corda.core.concurrent.CordaFuture import net.corda.core.contracts.ContractClassName -import net.corda.core.contracts.ContractState -import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateRef import net.corda.core.cordapp.CordappProvider -import net.corda.core.crypto.* +import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.identity.CordaX500Name import net.corda.core.identity.PartyAndCertificate -import net.corda.core.internal.concurrent.doneFuture -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.toFuture import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.NetworkHostAndPort -import net.corda.node.VersionInfo import net.corda.node.internal.ServicesForResolutionImpl import net.corda.node.internal.configureDatabase import net.corda.node.internal.cordapp.CordappLoader @@ -35,8 +27,6 @@ import net.corda.node.services.api.WritableTransactionStorage import net.corda.node.services.config.configOf import net.corda.node.services.config.parseToDbSchemaFriendlyName 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 @@ -56,17 +46,17 @@ import net.corda.testing.database.DatabaseConstants.SCHEMA import net.corda.testing.database.DatabaseConstants.TRANSACTION_ISOLATION_LEVEL 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) /** @@ -80,16 +70,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, final 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. * @@ -128,10 +115,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 @@ -146,12 +134,12 @@ open class MockServices private constructor( val database = configureDatabase(dataSourceProps, makeTestDatabaseProperties(initialIdentity.name.organisation), 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() @@ -247,10 +235,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) } } @@ -276,7 +263,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) @@ -287,6 +277,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) } @@ -295,74 +286,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 trackTransaction(id: SecureHash): CordaFuture { - return txns[id]?.let { doneFuture(it) } ?: _updatesPublisher.filter { it.id == id }.toFuture() - } - - 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 dcf47f96b3..5264ceba92 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 @@ -16,8 +16,8 @@ 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.* +import net.corda.testing.internal.chooseIdentity /** * Creates and tests a ledger built by the passed in dsl. @@ -55,17 +55,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) +/** 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)) - -/** - * Creates a new [InvocationContext] for testing purposes. - */ -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 \ 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 5e13e35abe..ab58590894 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..52132ebc92 --- /dev/null +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InMemoryMessage.kt @@ -0,0 +1,20 @@ +package net.corda.testing.node.internal + +import net.corda.core.utilities.ByteSequence +import net.corda.node.services.messaging.Message +import net.corda.node.services.statemachine.DeduplicationId +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: DeduplicationId, + override val debugTimestamp: Instant = Instant.now(), + override val senderUUID: String? = null) : Message { + + override val additionalHeaders: Map = emptyMap() + + 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 effa894298..36ad785e32 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 @@ -50,7 +50,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 net.corda.testing.node.MockServices.Companion.makeTestDatabaseProperties import org.apache.activemq.artemis.utils.ReusableLatch @@ -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 })) } @@ -329,24 +343,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 @@ -387,16 +401,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} ") } @@ -426,6 +439,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 92f51f191e..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 @@ -3,7 +3,6 @@ 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.context.InvocationOrigin import net.corda.core.flows.FlowLogic import net.corda.core.internal.FlowStateMachine import net.corda.core.internal.concurrent.openFuture @@ -13,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 @@ -99,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..843789f5d5 --- /dev/null +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockKeyManagementService.kt @@ -0,0 +1,58 @@ +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 net.corda.node.services.keys.getSigner +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 = 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..f2d515ca46 --- /dev/null +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/MockTransactionStorage.kt @@ -0,0 +1,45 @@ +package net.corda.testing.node.internal + +import net.corda.core.concurrent.CordaFuture +import net.corda.core.crypto.SecureHash +import net.corda.core.internal.concurrent.doneFuture +import net.corda.core.messaging.DataFeed +import net.corda.core.serialization.SingletonSerializeAsToken +import net.corda.core.toFuture +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 trackTransaction(id: SecureHash): CordaFuture { + return txns[id]?.let { doneFuture(it) } ?: _updatesPublisher.filter { it.id == id }.toFuture() + } + + 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 b90411b706..23a8e45f7d 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 @@ -20,7 +20,6 @@ import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.core.getFreeLocalPorts import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.testThreadFactory -import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO import net.corda.testing.node.User import org.apache.logging.log4j.Level import org.junit.After 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 f78678801a..a6564cd6f1 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 @@ -84,6 +84,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,7 +53,7 @@ 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) @@ -64,14 +61,14 @@ class MockAttachmentStorage : AttachmentStorage, SingletonSerializeAsToken() { // 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/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/iou/NewTransaction.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/iou/NewTransaction.kt index fde1d620b7..9c0fa8d254 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/iou/NewTransaction.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/iou/NewTransaction.kt @@ -32,7 +32,7 @@ import net.corda.explorer.model.MembershipListModel import net.corda.explorer.views.bigDecimalFormatter import net.corda.explorer.views.stringConverter import net.corda.sample.businessnetwork.iou.IOUFlow -import net.corda.testing.core.chooseIdentityAndCert +import net.corda.testing.core.singleIdentityAndCert import org.controlsfx.dialog.ExceptionDialog import tornadofx.* @@ -60,7 +60,7 @@ class NewTransaction : Fragment() { } partyBChoiceBox.apply { - items = FXCollections.observableList(parties.map { it.chooseIdentityAndCert() }).filtered { elementsFromServer.contains(it.party) }.sorted() + items = FXCollections.observableList(parties.map { it.singleIdentityAndCert() }).filtered { elementsFromServer.contains(it.party) }.sorted() } newTransactionDialog(window).showAndWait().ifPresent { request -> 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 abb0444f34..df3ff53ac0 100644 --- a/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierTests.kt +++ b/verifier/src/integration-test/kotlin/net/corda/verifier/VerifierTests.kt @@ -11,11 +11,11 @@ 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.DriverParameters +import net.corda.testing.driver.VerifierType import net.corda.testing.driver.internal.NodeHandleInternal import net.corda.testing.internal.IntegrationTest import net.corda.testing.internal.IntegrationTestSchemas