public class MockServices implements ServiceHub
An implementation of interface ServiceHub
that is designed for in-memory unit tests of contract validation logic. It has
enough functionality to do tests of code that queries the vault, inserts to the vault, and constructs/checks
transactions. However it isn't enough to test flows and other aspects of an app that require a network. For that
you should investigate class MockNetwork
.
There are a variety of constructors that can be used to supply enough data to simulate a node. Each mock service hub must have at least an identity of its own. The other components have defaults that work in most situations.
interface ServiceHub
,
class MockNetwork
@JvmOverloads public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull IdentityService identityService, @NotNull java.security.KeyPair... moreKeys)
Create a mock interface ServiceHub
that looks for app code in the given package names, uses the provided identity service
(you can get one from makeTestIdentityService
) and represents the given identity.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull java.security.KeyPair... moreKeys)
Create a mock interface ServiceHub
that looks for app code in the given package names, uses the provided identity service
(you can get one from makeTestIdentityService
) and represents the given identity.
interface ServiceHub
,
makeTestIdentityService
public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull IdentityService identityService, @NotNull NetworkParameters networkParameters, @NotNull java.security.KeyPair... moreKeys)
public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull IdentityService identityService, @NotNull NetworkParameters networkParameters, @NotNull java.security.KeyPair[] moreKeys, @NotNull KeyManagementService keyManagementService)
@JvmOverloads public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull CordaX500Name initialIdentityName, @NotNull IdentityService identityService, @NotNull java.security.KeyPair key, @NotNull java.security.KeyPair... moreKeys)
Create a mock interface ServiceHub
that looks for app code in the given package names, uses the provided identity service
(you can get one from makeTestIdentityService
) and represents the given identity.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull CordaX500Name initialIdentityName, @NotNull java.security.KeyPair key, @NotNull java.security.KeyPair... moreKeys)
Create a mock interface ServiceHub
that looks for app code in the given package names, uses the provided identity service
(you can get one from makeTestIdentityService
) and represents the given identity.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull CordaX500Name initialIdentityName, @NotNull IdentityService identityService)
Create a mock interface ServiceHub
that can't load CorDapp code, which uses the provided identity service
(you can get one from makeTestIdentityService
) and which represents the given identity.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages, @NotNull CordaX500Name initialIdentityName)
Create a mock interface ServiceHub
that can't load CorDapp code, which uses the provided identity service
(you can get one from makeTestIdentityService
) and which represents the given identity.
interface ServiceHub
,
makeTestIdentityService
public MockServices(@NotNull java.lang.Iterable<java.lang.String> cordappPackages)
Create a mock interface ServiceHub
that can't load CorDapp code, and which uses a default service identity.
interface ServiceHub
@JvmOverloads public MockServices(@NotNull CordaX500Name initialIdentityName, @NotNull IdentityService identityService, @NotNull java.security.KeyPair key, @NotNull java.security.KeyPair... moreKeys)
Create a mock interface ServiceHub
which uses the package of the caller to find CorDapp code. It uses the provided identity service
(you can get one from makeTestIdentityService
) and which represents the given identity.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull CordaX500Name initialIdentityName, @NotNull java.security.KeyPair key, @NotNull java.security.KeyPair... moreKeys)
Create a mock interface ServiceHub
which uses the package of the caller to find CorDapp code. It uses the provided identity service
(you can get one from makeTestIdentityService
) and which represents the given identity.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull CordaX500Name initialIdentityName, @NotNull IdentityService identityService)
Create a mock interface ServiceHub
which uses the package of the caller to find CorDapp code. It uses the provided identity service
(you can get one from makeTestIdentityService
) and which represents the given identity. It has no keys.
interface ServiceHub
,
makeTestIdentityService
@JvmOverloads public MockServices(@NotNull CordaX500Name initialIdentityName)
Create a mock interface ServiceHub
which uses the package of the caller to find CorDapp code. It uses the provided identity service
(you can get one from makeTestIdentityService
) and which represents the given identity. It has no keys.
interface ServiceHub
,
makeTestIdentityService
public MockServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull CordaX500Name initialIdentityName, @NotNull IdentityService identityService, @NotNull NetworkParameters networkParameters)
public MockServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull CordaX500Name initialIdentityName, @NotNull IdentityService identityService, @NotNull NetworkParameters networkParameters, @NotNull java.security.KeyPair key)
public MockServices(@NotNull NonExistentClass firstIdentity, @NotNull NonExistentClass... moreIdentities)
A helper constructor that requires at least one test identity to be registered, and which takes the package of the caller as the package in which to find app code. This is the most convenient constructor and the one that is normally worth using. The first identity is the identity of this service hub, the rest are identities that it is aware of.
public MockServices(@NotNull NonExistentClass firstIdentity, @NotNull NetworkParameters networkParameters, @NotNull NonExistentClass... moreIdentities)
public MockServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull NonExistentClass firstIdentity, @NotNull NonExistentClass... moreIdentities)
public MockServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull NonExistentClass firstIdentity, @NotNull NetworkParameters networkParameters, @NotNull NonExistentClass... moreIdentities)
public MockServices()
Create a mock interface ServiceHub
which uses the package of the caller to find CorDapp code. It uses a default service
identity.
interface ServiceHub
@NotNull public java.lang.ClassLoader getCordappClassloader()
Returns the classloader containing all jar deployed in the 'cordapps' folder.
public void recordTransactions(@NotNull StatesToRecord statesToRecord, @NotNull java.lang.Iterable<net.corda.core.transactions.SignedTransaction> txs)
Stores the given class SignedTransaction
s in the local transaction storage and then sends them to the vault for
further processing if statesToRecord
is not StatesToRecord.NONE.
This is expected to be run within a database transaction.
statesToRecord
- how the vault should treat the output states of the transaction.txs
- The transactions to record.class SignedTransaction
,
statesToRecord
@NotNull public NetworkParameters getNetworkParameters()
Returns the network parameters the node is operating under.
@NotNull public MockAttachmentStorage getAttachments()
Provides access to storage of arbitrary JAR files (which may contain only data, no code).
@NotNull public VaultService getVaultService()
The vault service lets you observe, soft lock and add notes to states that involve you or are relevant to your node in some way. Additionally you may query and track states that correspond to various criteria.
@NotNull public ContractUpgradeService getContractUpgradeService()
The interface ContractUpgradeService
is responsible for securely upgrading contract state objects according to
a specified and mutually agreed (amongst participants) contract version.
@NotNull public NetworkMapCache getNetworkMapCache()
A network map contains lists of nodes on the network along with information about their identity keys, services they provide and host names or IP addresses where they can be connected to. The cache wraps around a map fetched from an authoritative service, and adds easy lookup of the data stored within it. Generally it would be initialised with a specified network map service, which it fetches data from and then subscribes to updates of.
@NotNull public TestClock getClock()
A Clock representing the node's current time. This should be used in preference to directly accessing the clock so the current time can be controlled during unit testing.
@NotNull public NodeInfo getMyInfo()
The class NodeInfo
object corresponding to our own entry in the network map.
class NodeInfo
@NotNull public net.corda.core.node.services.TransactionVerifierService getTransactionVerifierService()
INTERNAL. DO NOT USE.
@NotNull public CordappProvider getCordappProvider()
Provides access to anything relating to cordapps including contract attachment resolution and app context
@NotNull public NetworkParametersService getNetworkParametersService()
Provides access to historical network parameters that are used in transaction resolution.
public void setNetworkParametersService(@NotNull NetworkParametersService p)
Provides access to historical network parameters that are used in transaction resolution.
@NotNull public DiagnosticsService getDiagnosticsService()
The interface DiagnosticsService
provides diagnostic level information about the node, including the current version of the node, and the
CorDapps currently installed on the node. Note that this information should be used to provide diagnostics only, and no functional
decisions should be made based on this.
interface DiagnosticsService
@NotNull protected ServicesForResolution getServicesForResolution()
@NotNull public <T extends SerializeAsToken> T cordaService(@NotNull java.lang.Class<T> type)
Return the singleton instance of the given Corda service type. This is a class that is annotated with
annotationclass CordaService
and will have automatically been registered by the node.
IllegalArgumentException
- If type
is not annotated with annotationclass CordaService
or if the instance is not found.annotationclass CordaService
@NotNull public java.sql.Connection jdbcSession()
Exposes a JDBC connection (session) object using the currently configured database.
Applications can use this to execute arbitrary SQL queries (native, direct, prepared, callable)
against its Node database tables (including custom contract tables defined by extending
interface QueryableState
).
When used within a flow, this session automatically forms part of the enclosing flow transaction boundary, and thus queryable data will include everything committed as of the last checkpoint.
We want to make sure users have a restricted access to administrative functions, this function will return a RestrictedConnection instance. The following methods are blocked:
abort(executor: Executor?)
clearWarnings()
close()
commit()
setSavepoint()
setSavepoint(name : String?)
releaseSavepoint(savepoint: Savepoint?)
rollback()
rollback(savepoint: Savepoint?)
setCatalog(catalog : String?)
setTransactionIsolation(level: Int)
setTypeMap(map: MutableMap
setHoldability(holdability: Int)
setSchema(schema: String?)
setNetworkTimeout(executor: Executor?, milliseconds: Int)
setAutoCommit(autoCommit: Boolean)
setReadOnly(readOnly: Boolean)
IllegalStateException
- if called outside of a transaction.interface QueryableState
,
RestrictedConnectionpublic <T> T withEntityManager(@NotNull kotlin.jvm.functions.Function1<? super javax.persistence.EntityManager,? extends T> block)
Exposes the Java Persistence API (JPA) to flows via a restricted EntityManager. This method can be used to persist and query entities which inherit from MappedSchema. This is particularly useful if off-ledger data needs to be kept in conjunction with on-ledger state data.
NOTE: Suspendable flow operations such as send, receive, subFlow and sleep, cannot be called within the lambda.
block
- a lambda function with access to an EntityManager.
We want to make sure users have a restricted access to administrative functions. The following methods are blocked:
close()
unwrap(cls: Class?)
getDelegate(): Any
getMetamodel()
joinTransaction()
lock(entity: Any?, lockMode: LockModeType?)
lock(entity: Any?, lockMode: LockModeType?, properties: MutableMap
setProperty(propertyName: String?, value: Any?)
getTransaction returns a RestrictedEntityTransaction to prevent unsafe manipulation of a flow's underlying database transaction. The following methods are blocked:
begin()
commit()
rollback()
public void withEntityManager(@NotNull java.util.function.Consumer<javax.persistence.EntityManager> block)
Exposes the Java Persistence API (JPA) to flows via a restricted EntityManager. This method can be used to persist and query entities which inherit from MappedSchema. This is particularly useful if off-ledger data needs to be kept in conjunction with on-ledger state data.
NOTE: Suspendable flow operations such as send, receive, subFlow and sleep, cannot be called within the lambda.
block
- a lambda function with access to an EntityManager.
We want to make sure users have a restricted access to administrative functions. The following methods are blocked:
close()
unwrap(cls: Class?)
getDelegate(): Any
getMetamodel()
joinTransaction()
lock(entity: Any?, lockMode: LockModeType?)
lock(entity: Any?, lockMode: LockModeType?, properties: MutableMap
setProperty(propertyName: String?, value: Any?)
getTransaction returns a RestrictedEntityTransaction to prevent unsafe manipulation of a flow's underlying database transaction. The following methods are blocked:
begin()
commit()
rollback()
@NotNull public java.lang.Void registerUnloadHandler(@NotNull kotlin.jvm.functions.Function0<kotlin.Unit> runOnStop)
Allows the registration of a callback that may inform services when the app is shutting down.
The intent is to allow the cleaning up of resources - e.g. releasing ports.
You should not rely on this to clean up executing flows - that's what quasar is for.
Please note that the shutdown handler is not guaranteed to be called. In production the node process may crash, be killed by the operating system and other forms of fatal termination may occur that result in this code never running. So you should use this functionality only for unit/integration testing or for code that can optimise this shutdown e.g. by cleaning up things that would otherwise trigger a slow recovery process next time the node starts.
public void addMockCordapp(@NotNull java.lang.String contractClassName)
Add the given package name to the list of packages which will be scanned for cordapp contract verification code
@NotNull public TransactionState<?> loadState(@NotNull StateRef stateRef)
Given a class StateRef
loads the referenced transaction and looks up the specified output interface ContractState
.
WARNING Do not use this method unless you really only want a single state - any batch loading should
go through loadStates
as repeatedly calling loadState
can lead to repeat deserialsiation work and
severe performance degradation.
TransactionResolutionException
- if stateRef
points to a non-existent transaction.class StateRef
,
interface ContractState
,
loadStates
,
loadState
@NotNull public java.util.Set<net.corda.core.contracts.StateAndRef> loadStates(@NotNull java.util.Set<net.corda.core.contracts.StateRef> stateRefs)
Given a Set of class StateRef
's loads the referenced transaction and looks up the specified output interface ContractState
.
TransactionResolutionException
- if stateRef points to a non-existent transaction.class StateRef
,
interface ContractState
@NotNull public Attachment loadContractAttachment(@NotNull StateRef stateRef)
Returns a dummy Attachment, in context of signature constrains non-downgrade rule this default to contract class version 1
.
@NotNull public TransactionStorage getValidatedTransactions()
A map of hash-
>tx where tx has been signature/contract validated and the states are known to be correct.The signatures aren't technically needed after that point, but we keep them around so that we can relaythe transaction data to other nodes that need it.
@NotNull public IdentityService getIdentityService()
An identity service maintains a directory of parties by their associated distinguished name/public keys and thus
supports lookup of a party given its key, or name. The service also manages the certificates linking confidentialidentities back to the well known identity (i.e. the identity in the network map) of a party.
@NotNull public KeyManagementService getKeyManagementService()
The key management service is responsible for storing and using private keys to sign things. An implementation of this may, for example, call out to a hardware security module that enforces various auditing and frequency-of-use requirements.
You don't normally need to use this directly. If you have a class TransactionBuilder
and wish to sign it to
get a class SignedTransaction
, look at signInitialTransaction.
class TransactionBuilder
,
class SignedTransaction
@JvmStatic @NotNull public static java.util.Properties makeTestDataSourceProperties(@NotNull java.lang.String nodeName)
Make properties appropriate for creating a DataSource for unit tests.
nodeName
- Reflects the "instance" of the in-memory database. Defaults to a random string.@JvmStatic @JvmOverloads @NotNull public static kotlin.Pair<net.corda.nodeapi.internal.persistence.CordaPersistence,net.corda.testing.node.MockServices> makeTestDatabaseAndMockServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull IdentityService identityService, @NotNull NonExistentClass initialIdentity, @NotNull NetworkParameters networkParameters, @NotNull java.security.KeyPair... moreKeys)
Makes database and mock services appropriate for unit tests.
cordappPackages
- A List of cordapp packages to scan for any cordapp code, e.g. contract verification code, flows and services.identityService
- An instance of interface IdentityService
, see makeTestIdentityService
.initialIdentity
- The first (typically sole) identity the services will represent.moreKeys
- A list of additional KeyPair instances to be used by class MockServices
.class MockServices
.@JvmStatic @JvmOverloads @NotNull public static kotlin.Pair<net.corda.nodeapi.internal.persistence.CordaPersistence,net.corda.testing.node.MockServices> makeTestDatabaseAndMockServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull IdentityService identityService, @NotNull NonExistentClass initialIdentity, @NotNull java.security.KeyPair... moreKeys)
Makes database and mock services appropriate for unit tests.
cordappPackages
- A List of cordapp packages to scan for any cordapp code, e.g. contract verification code, flows and services.identityService
- An instance of interface IdentityService
, see makeTestIdentityService
.initialIdentity
- The first (typically sole) identity the services will represent.moreKeys
- A list of additional KeyPair instances to be used by class MockServices
.class MockServices
.@JvmStatic @JvmOverloads @NotNull public static kotlin.Pair<net.corda.nodeapi.internal.persistence.CordaPersistence,net.corda.testing.node.MockServices> makeTestDatabaseAndPersistentServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull NetworkParameters networkParameters, @NotNull java.util.Set<java.security.KeyPair> moreKeys, @NotNull java.util.Set<net.corda.core.identity.PartyAndCertificate> moreIdentities, @NotNull net.corda.testing.internal.TestingNamedCacheFactory cacheFactory)
Makes database and persistent services appropriate for unit tests which require persistence across the vault, identity service and key managment service.
cordappPackages
- A List of cordapp packages to scan for any cordapp code, e.g. contract verification code, flows and services.initialIdentity
- The first (typically sole) identity the services will represent.moreKeys
- A list of additional KeyPair instances to be used by class MockServices
.moreIdentities
- A list of additional KeyPair instances to be used by class MockServices
.cacheFactory
- A custom cache factory to be used by the created interface IdentityService
class MockServices
.@JvmStatic @JvmOverloads @NotNull public static kotlin.Pair<net.corda.nodeapi.internal.persistence.CordaPersistence,net.corda.testing.node.MockServices> makeTestDatabaseAndPersistentServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull NetworkParameters networkParameters, @NotNull java.util.Set<java.security.KeyPair> moreKeys, @NotNull java.util.Set<net.corda.core.identity.PartyAndCertificate> moreIdentities)
Makes database and persistent services appropriate for unit tests which require persistence across the vault, identity service and key managment service.
cordappPackages
- A List of cordapp packages to scan for any cordapp code, e.g. contract verification code, flows and services.initialIdentity
- The first (typically sole) identity the services will represent.moreKeys
- A list of additional KeyPair instances to be used by class MockServices
.moreIdentities
- A list of additional KeyPair instances to be used by class MockServices
.class MockServices
.@JvmStatic @JvmOverloads @NotNull public static kotlin.Pair<net.corda.nodeapi.internal.persistence.CordaPersistence,net.corda.testing.node.MockServices> makeTestDatabaseAndPersistentServices(@NotNull java.util.List<java.lang.String> cordappPackages, @NotNull NonExistentClass initialIdentity, @NotNull java.util.Set<java.security.KeyPair> moreKeys, @NotNull java.util.Set<net.corda.core.identity.PartyAndCertificate> moreIdentities)
Makes database and persistent services appropriate for unit tests which require persistence across the vault, identity service and key managment service.
cordappPackages
- A List of cordapp packages to scan for any cordapp code, e.g. contract verification code, flows and services.initialIdentity
- The first (typically sole) identity the services will represent.moreKeys
- A list of additional KeyPair instances to be used by class MockServices
.moreIdentities
- A list of additional KeyPair instances to be used by class MockServices
.class MockServices
.