diff --git a/core/src/main/kotlin/net/corda/core/node/CordaPluginRegistry.kt b/core/src/main/kotlin/net/corda/core/node/CordaPluginRegistry.kt index a74d36d3de..600f548a80 100644 --- a/core/src/main/kotlin/net/corda/core/node/CordaPluginRegistry.kt +++ b/core/src/main/kotlin/net/corda/core/node/CordaPluginRegistry.kt @@ -1,12 +1,6 @@ package net.corda.core.node -import net.corda.core.contracts.ContractState -import net.corda.core.messaging.CordaRPCOps -import net.corda.core.node.services.VaultQueryService -import net.corda.core.schemas.MappedSchema -import net.corda.core.schemas.QueryableState import net.corda.core.serialization.SerializationCustomization -import java.util.function.Function /** * Implement this interface on a class advertised in a META-INF/services/net.corda.core.node.CordaPluginRegistry file diff --git a/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt b/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt index f4c0f205cd..5d23e76dab 100644 --- a/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt +++ b/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt @@ -64,11 +64,10 @@ interface ServiceHub : ServicesForResolution { /** * 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. + * node in some way. Additionally you may query and track states that correspond to various criteria. */ val vaultService: VaultService - /** The vault query service lets you select and track states that correspond to various criteria. */ - val vaultQueryService: VaultQueryService + /** * 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 diff --git a/core/src/main/kotlin/net/corda/core/node/services/VaultQueryService.kt b/core/src/main/kotlin/net/corda/core/node/services/VaultQueryService.kt index deace9212f..e69de29bb2 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/VaultQueryService.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/VaultQueryService.kt @@ -1,142 +0,0 @@ -package net.corda.core.node.services - -import net.corda.core.contracts.ContractState -import net.corda.core.flows.FlowException -import net.corda.core.messaging.DataFeed -import net.corda.core.node.services.vault.PageSpecification -import net.corda.core.node.services.vault.QueryCriteria -import net.corda.core.node.services.vault.Sort - -/** - * The vault query service lets you select and track states that correspond to various criteria. - */ -interface VaultQueryService { - // DOCSTART VaultQueryAPI - /** - * Generic vault query function which takes a [QueryCriteria] object to define filters, - * optional [PageSpecification] and optional [Sort] modification criteria (default unsorted), - * and returns a [Vault.Page] object containing the following: - * 1. states as a List of (page number and size defined by [PageSpecification]) - * 2. states metadata as a List of [Vault.StateMetadata] held in the Vault States table. - * 3. total number of results available if [PageSpecification] supplied (otherwise returns -1) - * 4. status types used in this query: UNCONSUMED, CONSUMED, ALL - * 5. other results (aggregate functions with/without using value groups) - * - * @throws VaultQueryException if the query cannot be executed for any reason - * (missing criteria or parsing error, paging errors, unsupported query, underlying database error) - * - * Notes - * If no [PageSpecification] is provided, a maximum of [DEFAULT_PAGE_SIZE] results will be returned. - * API users must specify a [PageSpecification] if they are expecting more than [DEFAULT_PAGE_SIZE] results, - * otherwise a [VaultQueryException] will be thrown alerting to this condition. - * It is the responsibility of the API user to request further pages and/or specify a more suitable [PageSpecification]. - */ - @Throws(VaultQueryException::class) - fun _queryBy(criteria: QueryCriteria, - paging: PageSpecification, - sorting: Sort, - contractStateType: Class): Vault.Page - - /** - * Generic vault query function which takes a [QueryCriteria] object to define filters, - * optional [PageSpecification] and optional [Sort] modification criteria (default unsorted), - * and returns a [Vault.PageAndUpdates] object containing - * 1) a snapshot as a [Vault.Page] (described previously in [queryBy]) - * 2) an [Observable] of [Vault.Update] - * - * @throws VaultQueryException if the query cannot be executed for any reason - * - * Notes: the snapshot part of the query adheres to the same behaviour as the [queryBy] function. - * the [QueryCriteria] applies to both snapshot and deltas (streaming updates). - */ - @Throws(VaultQueryException::class) - fun _trackBy(criteria: QueryCriteria, - paging: PageSpecification, - sorting: Sort, - contractStateType: Class): DataFeed, Vault.Update> - // DOCEND VaultQueryAPI - - // Note: cannot apply @JvmOverloads to interfaces nor interface implementations - // Java Helpers - fun queryBy(contractStateType: Class): Vault.Page { - return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType) - } - - fun queryBy(contractStateType: Class, criteria: QueryCriteria): Vault.Page { - return _queryBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType) - } - - fun queryBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification): Vault.Page { - return _queryBy(criteria, paging, Sort(emptySet()), contractStateType) - } - - fun queryBy(contractStateType: Class, criteria: QueryCriteria, sorting: Sort): Vault.Page { - return _queryBy(criteria, PageSpecification(), sorting, contractStateType) - } - - fun queryBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page { - return _queryBy(criteria, paging, sorting, contractStateType) - } - - fun trackBy(contractStateType: Class): DataFeed, Vault.Update> { - return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType) - } - - fun trackBy(contractStateType: Class, criteria: QueryCriteria): DataFeed, Vault.Update> { - return _trackBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType) - } - - fun trackBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification): DataFeed, Vault.Update> { - return _trackBy(criteria, paging, Sort(emptySet()), contractStateType) - } - - fun trackBy(contractStateType: Class, criteria: QueryCriteria, sorting: Sort): DataFeed, Vault.Update> { - return _trackBy(criteria, PageSpecification(), sorting, contractStateType) - } - - fun trackBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed, Vault.Update> { - return _trackBy(criteria, paging, sorting, contractStateType) - } -} - -inline fun VaultQueryService.queryBy(): Vault.Page { - return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java) -} - -inline fun VaultQueryService.queryBy(criteria: QueryCriteria): Vault.Page { - return _queryBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java) -} - -inline fun VaultQueryService.queryBy(criteria: QueryCriteria, paging: PageSpecification): Vault.Page { - return _queryBy(criteria, paging, Sort(emptySet()), T::class.java) -} - -inline fun VaultQueryService.queryBy(criteria: QueryCriteria, sorting: Sort): Vault.Page { - return _queryBy(criteria, PageSpecification(), sorting, T::class.java) -} - -inline fun VaultQueryService.queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page { - return _queryBy(criteria, paging, sorting, T::class.java) -} - -inline fun VaultQueryService.trackBy(): DataFeed, Vault.Update> { - return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java) -} - -inline fun VaultQueryService.trackBy(criteria: QueryCriteria): DataFeed, Vault.Update> { - return _trackBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java) -} - -inline fun VaultQueryService.trackBy(criteria: QueryCriteria, paging: PageSpecification): DataFeed, Vault.Update> { - return _trackBy(criteria, paging, Sort(emptySet()), T::class.java) -} - -inline fun VaultQueryService.trackBy(criteria: QueryCriteria, sorting: Sort): DataFeed, Vault.Update> { - return _trackBy(criteria, PageSpecification(), sorting, T::class.java) -} - -inline fun VaultQueryService.trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed, Vault.Update> { - return _trackBy(criteria, paging, sorting, T::class.java) -} - -class VaultQueryException(description: String) : FlowException(description) \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/node/services/VaultService.kt b/core/src/main/kotlin/net/corda/core/node/services/VaultService.kt index a2353a7b99..a16243a7db 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/VaultService.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/VaultService.kt @@ -6,7 +6,10 @@ import net.corda.core.contracts.* import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowException import net.corda.core.identity.AbstractParty +import net.corda.core.messaging.DataFeed +import net.corda.core.node.services.vault.PageSpecification import net.corda.core.node.services.vault.QueryCriteria +import net.corda.core.node.services.vault.Sort import net.corda.core.serialization.CordaSerializable import net.corda.core.toFuture import net.corda.core.utilities.NonEmptySet @@ -166,11 +169,6 @@ interface VaultService { */ val updates: Observable> - /** - * Enable creation of observables of updates. - */ - val updatesPublisher: PublishSubject> - /** * Provide a [CordaFuture] for when a [StateRef] is consumed, which can be very useful in building tests. */ @@ -221,7 +219,7 @@ interface VaultService { // DOCEND SoftLockAPI /** - * Helper function to combine using [VaultQueryService] calls to determine spendable states and soft locking them. + * Helper function to determine spendable states and soft locking them. * Currently performance will be worse than for the hand optimised version in `Cash.unconsumedCashStatesForSpending` * However, this is fully generic and can operate with custom [FungibleAsset] states. * @param lockId The [FlowLogic.runId.uuid] of the current flow used to soft lock the states. @@ -241,8 +239,135 @@ interface VaultService { amount: Amount, contractStateType: Class): List> + // DOCSTART VaultQueryAPI + /** + * Generic vault query function which takes a [QueryCriteria] object to define filters, + * optional [PageSpecification] and optional [Sort] modification criteria (default unsorted), + * and returns a [Vault.Page] object containing the following: + * 1. states as a List of (page number and size defined by [PageSpecification]) + * 2. states metadata as a List of [Vault.StateMetadata] held in the Vault States table. + * 3. total number of results available if [PageSpecification] supplied (otherwise returns -1) + * 4. status types used in this query: UNCONSUMED, CONSUMED, ALL + * 5. other results (aggregate functions with/without using value groups) + * + * @throws VaultQueryException if the query cannot be executed for any reason + * (missing criteria or parsing error, paging errors, unsupported query, underlying database error) + * + * Notes + * If no [PageSpecification] is provided, a maximum of [DEFAULT_PAGE_SIZE] results will be returned. + * API users must specify a [PageSpecification] if they are expecting more than [DEFAULT_PAGE_SIZE] results, + * otherwise a [VaultQueryException] will be thrown alerting to this condition. + * It is the responsibility of the API user to request further pages and/or specify a more suitable [PageSpecification]. + */ + @Throws(VaultQueryException::class) + fun _queryBy(criteria: QueryCriteria, + paging: PageSpecification, + sorting: Sort, + contractStateType: Class): Vault.Page + + /** + * Generic vault query function which takes a [QueryCriteria] object to define filters, + * optional [PageSpecification] and optional [Sort] modification criteria (default unsorted), + * and returns a [Vault.PageAndUpdates] object containing + * 1) a snapshot as a [Vault.Page] (described previously in [queryBy]) + * 2) an [Observable] of [Vault.Update] + * + * @throws VaultQueryException if the query cannot be executed for any reason + * + * Notes: the snapshot part of the query adheres to the same behaviour as the [queryBy] function. + * the [QueryCriteria] applies to both snapshot and deltas (streaming updates). + */ + @Throws(VaultQueryException::class) + fun _trackBy(criteria: QueryCriteria, + paging: PageSpecification, + sorting: Sort, + contractStateType: Class): DataFeed, Vault.Update> + // DOCEND VaultQueryAPI + + // Note: cannot apply @JvmOverloads to interfaces nor interface implementations + // Java Helpers + fun queryBy(contractStateType: Class): Vault.Page { + return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType) + } + + fun queryBy(contractStateType: Class, criteria: QueryCriteria): Vault.Page { + return _queryBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType) + } + + fun queryBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification): Vault.Page { + return _queryBy(criteria, paging, Sort(emptySet()), contractStateType) + } + + fun queryBy(contractStateType: Class, criteria: QueryCriteria, sorting: Sort): Vault.Page { + return _queryBy(criteria, PageSpecification(), sorting, contractStateType) + } + + fun queryBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page { + return _queryBy(criteria, paging, sorting, contractStateType) + } + + fun trackBy(contractStateType: Class): DataFeed, Vault.Update> { + return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType) + } + + fun trackBy(contractStateType: Class, criteria: QueryCriteria): DataFeed, Vault.Update> { + return _trackBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType) + } + + fun trackBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification): DataFeed, Vault.Update> { + return _trackBy(criteria, paging, Sort(emptySet()), contractStateType) + } + + fun trackBy(contractStateType: Class, criteria: QueryCriteria, sorting: Sort): DataFeed, Vault.Update> { + return _trackBy(criteria, PageSpecification(), sorting, contractStateType) + } + + fun trackBy(contractStateType: Class, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed, Vault.Update> { + return _trackBy(criteria, paging, sorting, contractStateType) + } } +inline fun VaultService.queryBy(): Vault.Page { + return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java) +} + +inline fun VaultService.queryBy(criteria: QueryCriteria): Vault.Page { + return _queryBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java) +} + +inline fun VaultService.queryBy(criteria: QueryCriteria, paging: PageSpecification): Vault.Page { + return _queryBy(criteria, paging, Sort(emptySet()), T::class.java) +} + +inline fun VaultService.queryBy(criteria: QueryCriteria, sorting: Sort): Vault.Page { + return _queryBy(criteria, PageSpecification(), sorting, T::class.java) +} + +inline fun VaultService.queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page { + return _queryBy(criteria, paging, sorting, T::class.java) +} + +inline fun VaultService.trackBy(): DataFeed, Vault.Update> { + return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java) +} + +inline fun VaultService.trackBy(criteria: QueryCriteria): DataFeed, Vault.Update> { + return _trackBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java) +} + +inline fun VaultService.trackBy(criteria: QueryCriteria, paging: PageSpecification): DataFeed, Vault.Update> { + return _trackBy(criteria, paging, Sort(emptySet()), T::class.java) +} + +inline fun VaultService.trackBy(criteria: QueryCriteria, sorting: Sort): DataFeed, Vault.Update> { + return _trackBy(criteria, PageSpecification(), sorting, T::class.java) +} + +inline fun VaultService.trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed, Vault.Update> { + return _trackBy(criteria, paging, sorting, T::class.java) +} + +class VaultQueryException(description: String) : FlowException(description) class StatesNotAvailableException(override val message: String?, override val cause: Throwable? = null) : FlowException(message, cause) { override fun toString() = "Soft locking error: $message" 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 4ef934798b..aeca91feb4 100644 --- a/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt +++ b/core/src/test/kotlin/net/corda/core/flows/ContractUpgradeFlowTest.kt @@ -219,14 +219,14 @@ class ContractUpgradeFlowTest { val stx = result.getOrThrow().stx val anonymisedRecipient = result.get().recipient!! val stateAndRef = stx.tx.outRef(0) - val baseState = a.database.transaction { a.services.vaultQueryService.queryBy().states.single() } + val baseState = a.database.transaction { a.services.vaultService.queryBy().states.single() } assertTrue(baseState.state.data is Cash.State, "Contract state is old version.") // Starts contract upgrade flow. val upgradeResult = a.services.startFlow(ContractUpgradeFlow.Initiate(stateAndRef, CashV2::class.java)).resultFuture mockNet.runNetwork() upgradeResult.getOrThrow() // Get contract state from the vault. - val firstState = a.database.transaction { a.services.vaultQueryService.queryBy().states.single() } + val firstState = a.database.transaction { a.services.vaultService.queryBy().states.single() } assertTrue(firstState.state.data is CashV2.State, "Contract state is upgraded to the new version.") assertEquals(Amount(1000000, USD).`issued by`(chosenIdentity.ref(1)), (firstState.state.data as CashV2.State).amount, "Upgraded cash contain the correct amount.") assertEquals>(listOf(anonymisedRecipient), (firstState.state.data as CashV2.State).owners, "Upgraded cash belongs to the right owner.") diff --git a/docs/source/api-vault-query.rst b/docs/source/api-vault-query.rst index 9f19f1087a..0b9944948d 100644 --- a/docs/source/api-vault-query.rst +++ b/docs/source/api-vault-query.rst @@ -10,9 +10,9 @@ Corda provides a number of flexible query mechanisms for accessing the Vault: - custom JPA_/JPQL_ queries - custom 3rd party Data Access frameworks such as `Spring Data `_ -The majority of query requirements can be satisfied by using the Vault Query API, which is exposed via the ``VaultQueryService`` for use directly by flows: +The majority of query requirements can be satisfied by using the Vault Query API, which is exposed via the ``VaultService`` for use directly by flows: -.. literalinclude:: ../../core/src/main/kotlin/net/corda/core/node/services/VaultQueryService.kt +.. literalinclude:: ../../core/src/main/kotlin/net/corda/core/node/services/VaultService.kt :language: kotlin :start-after: DOCSTART VaultQueryAPI :end-before: DOCEND VaultQueryAPI diff --git a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java index bfa1b329d4..3777536aae 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java @@ -223,7 +223,7 @@ public class FlowCookbookJava { // For example, we would extract any unconsumed ``DummyState``s // from our vault as follows: VaultQueryCriteria criteria = new VaultQueryCriteria(Vault.StateStatus.UNCONSUMED); - Page results = getServiceHub().getVaultQueryService().queryBy(DummyState.class, criteria); + Page results = getServiceHub().getVaultService().queryBy(DummyState.class, criteria); List> dummyStates = results.getStates(); // For a full list of the available ways of extracting states from diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt index 3e720145bf..4b0864d714 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt @@ -206,7 +206,7 @@ object FlowCookbook { // For example, we would extract any unconsumed ``DummyState``s // from our vault as follows: val criteria: VaultQueryCriteria = VaultQueryCriteria() // default is UNCONSUMED - val results: Page = serviceHub.vaultQueryService.queryBy(criteria) + val results: Page = serviceHub.vaultService.queryBy(criteria) val dummyStates: List> = results.states // For a full list of the available ways of extracting states from diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt index 2532577f9a..9b31523586 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt @@ -129,7 +129,7 @@ class SubmitCompletionFlow(private val ref: StateRef, private val verdict: Workf override fun call(): StateAndRef { // DOCSTART 1 val criteria = VaultQueryCriteria(stateRefs = listOf(ref)) - val latestRecord = serviceHub.vaultQueryService.queryBy(criteria).states.single() + val latestRecord = serviceHub.vaultService.queryBy(criteria).states.single() // DOCEND 1 // Check the protocol hasn't already been run 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 d625c1483e..831e8db3fb 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 @@ -27,7 +27,7 @@ class WorkflowTransactionBuildTutorialTest { // Helper method to locate the latest Vault version of a LinearState private inline fun ServiceHub.latest(ref: UniqueIdentifier): StateAndRef { - val linearHeads = vaultQueryService.queryBy(QueryCriteria.LinearStateQueryCriteria(uuid = listOf(ref.id))) + val linearHeads = vaultService.queryBy(QueryCriteria.LinearStateQueryCriteria(uuid = listOf(ref.id))) return linearHeads.states.single() } diff --git a/docs/source/tutorial-building-transactions.rst b/docs/source/tutorial-building-transactions.rst index 18734ca89f..b8c25bf04a 100644 --- a/docs/source/tutorial-building-transactions.rst +++ b/docs/source/tutorial-building-transactions.rst @@ -87,7 +87,7 @@ One of the first steps to forming a transaction is gathering the set of input references. This process will clearly vary according to the nature of the business process being captured by the smart contract and the parameterised details of the request. However, it will generally involve -searching the Vault via the ``VaultQueryService`` interface on the +searching the Vault via the ``VaultService`` interface on the ``ServiceHub`` to locate the input states. To give a few more specific details consider two simplified real world @@ -161,7 +161,7 @@ in the right workflow state over the RPC interface. The RPC will then initiate the relevant flow using ``StateRef``, or ``linearId`` values as parameters to the flow to identify the states being operated upon. Thus code to gather the latest input state for a given ``StateRef`` would use -the ``VaultQueryService`` as follows: +the ``VaultService`` as follows: .. literalinclude:: example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt :language: kotlin diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt index 2e28208a6f..d96b5b5c09 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt @@ -59,7 +59,7 @@ fun CordaRPCOps.getCashBalance(currency: Currency): Amount { } fun ServiceHub.getCashBalance(currency: Currency): Amount { - val results = this.vaultQueryService.queryBy>(generateCashSumCriteria(currency)) + val results = this.vaultService.queryBy>(generateCashSumCriteria(currency)) return rowsToAmount(currency, results) } @@ -69,7 +69,7 @@ fun CordaRPCOps.getCashBalances(): Map> { } fun ServiceHub.getCashBalances(): Map> { - val sums = this.vaultQueryService.queryBy>(generateCashSumsCriteria()).otherResults + val sums = this.vaultService.queryBy>(generateCashSumsCriteria()).otherResults return rowsToBalances(sums) } diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt index 763f0d4cff..f0084fb169 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt @@ -59,7 +59,7 @@ class CashExitFlow(private val amount: Amount, } // Work out who the owners of the burnt states were (specify page size so we don't silently drop any if > DEFAULT_PAGE_SIZE) - val inputStates = serviceHub.vaultQueryService.queryBy(VaultQueryCriteria(stateRefs = builder.inputStates()), + val inputStates = serviceHub.vaultService.queryBy(VaultQueryCriteria(stateRefs = builder.inputStates()), PageSpecification(pageNumber = DEFAULT_PAGE_NUM, pageSize = builder.inputStates().size)).states // TODO: Is it safe to drop participants we don't know how to contact? Does not knowing how to contact them diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt index b9b7bd7091..f30507ec3f 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt @@ -71,7 +71,7 @@ class CashTests : TestDependencyInjectionBase() { ownedBy = OUR_IDENTITY_1, issuedBy = MINI_CORP.ref(1), issuerServices = miniCorpServices) } database.transaction { - vaultStatesUnconsumed = miniCorpServices.vaultQueryService.queryBy().states + vaultStatesUnconsumed = miniCorpServices.vaultService.queryBy().states } resetTestSerialization() } 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 5fe62e9d3c..5a26f1196f 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashPaymentFlowTests.kt @@ -10,14 +10,10 @@ 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.chooseIdentity -import net.corda.testing.expect -import net.corda.testing.expectEvents -import net.corda.testing.getDefaultNotary +import net.corda.testing.* import net.corda.testing.node.InMemoryMessagingNetwork.ServicePeerAllocationStrategy.RoundRobin import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetwork.MockNode -import net.corda.testing.setCordappPackages import org.junit.After import org.junit.Before import org.junit.Test @@ -61,8 +57,8 @@ class CashPaymentFlowTests { bankOfCordaNode.database.transaction { // Register for vault updates val criteria = QueryCriteria.VaultQueryCriteria(status = Vault.StateStatus.ALL) - val (_, vaultUpdatesBoc) = bankOfCordaNode.services.vaultQueryService.trackBy(criteria) - val (_, vaultUpdatesBankClient) = notaryNode.services.vaultQueryService.trackBy(criteria) + val (_, vaultUpdatesBoc) = bankOfCordaNode.services.vaultService.trackBy(criteria) + val (_, vaultUpdatesBankClient) = notaryNode.services.vaultService.trackBy(criteria) val future = bankOfCordaNode.services.startFlow(CashPaymentFlow(expectedPayment, payTo)).resultFuture diff --git a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt index 50e9ac4866..6ba72a75d6 100644 --- a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt @@ -35,8 +35,8 @@ import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.debug import net.corda.node.internal.classloading.requireAnnotation import net.corda.node.internal.cordapp.CordappLoader -import net.corda.node.services.ContractUpgradeHandler import net.corda.node.internal.cordapp.CordappProviderImpl +import net.corda.node.services.ContractUpgradeHandler import net.corda.node.services.FinalityHandler import net.corda.node.services.NotaryChangeHandler import net.corda.node.services.api.* @@ -63,7 +63,6 @@ import net.corda.node.services.statemachine.appName import net.corda.node.services.statemachine.flowVersionAndInitiatingClass import net.corda.node.services.transactions.* import net.corda.node.services.upgrade.ContractUpgradeServiceImpl -import net.corda.node.services.vault.HibernateVaultQueryImpl import net.corda.node.services.vault.NodeVaultService import net.corda.node.services.vault.VaultSoftLockManager import net.corda.node.utilities.* @@ -83,11 +82,9 @@ import java.security.cert.CertificateFactory import java.security.cert.X509Certificate import java.sql.Connection import java.time.Clock -import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService import java.util.concurrent.TimeUnit.SECONDS -import kotlin.collections.ArrayList import kotlin.collections.set import kotlin.reflect.KClass import net.corda.core.crypto.generateKeyPair as cryptoGenerateKeyPair @@ -389,7 +386,7 @@ abstract class AbstractNode(open val configuration: NodeConfiguration, network = makeMessagingService(legalIdentity) info = makeInfo(legalIdentity) - val tokenizableServices = mutableListOf(attachments, network, services.vaultService, services.vaultQueryService, + val tokenizableServices = mutableListOf(attachments, network, services.vaultService, services.keyManagementService, services.identityService, platformClock, services.schedulerService, services.auditService, services.monitoringService, services.networkMapCache, services.schemaService, services.transactionVerifierService, services.validatedTransactions, services.contractUpgradeService, @@ -692,11 +689,9 @@ abstract class AbstractNode(open val configuration: NodeConfiguration, override val transactionVerifierService by lazy { makeTransactionVerifierService() } override val schemaService by lazy { NodeSchemaService() } override val networkMapCache by lazy { PersistentNetworkMapCache(this) } - override val vaultService by lazy { NodeVaultService(this) } + override val vaultService by lazy { NodeVaultService(this, database.hibernateConfig) } override val contractUpgradeService by lazy { ContractUpgradeServiceImpl() } - override val vaultQueryService by lazy { - HibernateVaultQueryImpl(database.hibernateConfig, vaultService) - } + // Place the long term identity key in the KMS. Eventually, this is likely going to be separated again because // the KMS is meant for derived temporary keys used in transactions, and we're not supposed to sign things with // the identity key. But the infrastructure to make that easy isn't here yet. diff --git a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt index ae8afce323..c902e8964a 100644 --- a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt @@ -56,7 +56,7 @@ class CordaRPCOpsImpl( sorting: Sort, contractStateType: Class): Vault.Page { return database.transaction { - services.vaultQueryService._queryBy(criteria, paging, sorting, contractStateType) + services.vaultService._queryBy(criteria, paging, sorting, contractStateType) } } @@ -66,7 +66,7 @@ class CordaRPCOpsImpl( sorting: Sort, contractStateType: Class): DataFeed, Vault.Update> { return database.transaction { - services.vaultQueryService._trackBy(criteria, paging, sorting, contractStateType) + services.vaultService._trackBy(criteria, paging, sorting, contractStateType) } } diff --git a/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt b/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt index 3501c2db34..e69de29bb2 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt @@ -1,204 +0,0 @@ -package net.corda.node.services.vault - -import net.corda.core.contracts.ContractState -import net.corda.core.contracts.StateAndRef -import net.corda.core.contracts.StateRef -import net.corda.core.contracts.TransactionState -import net.corda.core.crypto.SecureHash -import net.corda.core.internal.ThreadBox -import net.corda.core.internal.bufferUntilSubscribed -import net.corda.core.internal.uncheckedCast -import net.corda.core.messaging.DataFeed -import net.corda.core.node.services.Vault -import net.corda.core.node.services.VaultQueryException -import net.corda.core.node.services.VaultQueryService -import net.corda.core.node.services.VaultService -import net.corda.core.node.services.vault.* -import net.corda.core.node.services.vault.QueryCriteria.VaultCustomQueryCriteria -import net.corda.core.serialization.SerializationDefaults.STORAGE_CONTEXT -import net.corda.core.serialization.SingletonSerializeAsToken -import net.corda.core.serialization.deserialize -import net.corda.core.utilities.debug -import net.corda.core.utilities.loggerFor -import net.corda.core.utilities.trace -import net.corda.node.services.persistence.HibernateConfiguration -import net.corda.node.utilities.DatabaseTransactionManager -import org.hibernate.Session -import rx.Observable -import java.lang.Exception -import java.util.* -import javax.persistence.Tuple - -class HibernateVaultQueryImpl(val hibernateConfig: HibernateConfiguration, - val vault: VaultService) : SingletonSerializeAsToken(), VaultQueryService { - companion object { - val log = loggerFor() - } - - private var sessionFactory = hibernateConfig.sessionFactoryForRegisteredSchemas() - private var criteriaBuilder = sessionFactory.criteriaBuilder - - /** - * Maintain a list of contract state interfaces to concrete types stored in the vault - * for usage in generic queries of type queryBy or queryBy> - */ - private val contractStateTypeMappings = bootstrapContractStateTypes() - - init { - vault.rawUpdates.subscribe { update -> - update.produced.forEach { - val concreteType = it.state.data.javaClass - log.trace { "State update of type: $concreteType" } - val seen = contractStateTypeMappings.any { it.value.contains(concreteType.name) } - if (!seen) { - val contractInterfaces = deriveContractInterfaces(concreteType) - contractInterfaces.map { - val contractInterface = contractStateTypeMappings.getOrPut(it.name, { mutableSetOf() }) - contractInterface.add(concreteType.name) - } - } - } - } - } - - @Throws(VaultQueryException::class) - override fun _queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class): Vault.Page { - log.info("Vault Query for contract type: $contractStateType, criteria: $criteria, pagination: $paging, sorting: $sorting") - - // refresh to include any schemas registered after initial VQ service initialisation - sessionFactory = hibernateConfig.sessionFactoryForRegisteredSchemas() - criteriaBuilder = sessionFactory.criteriaBuilder - - // calculate total results where a page specification has been defined - var totalStates = -1L - if (!paging.isDefault) { - val count = builder { VaultSchemaV1.VaultStates::recordedTime.count() } - val countCriteria = VaultCustomQueryCriteria(count, Vault.StateStatus.ALL) - val results = queryBy(contractStateType, criteria.and(countCriteria)) - totalStates = results.otherResults[0] as Long - } - - val session = getSession() - - session.use { - val criteriaQuery = criteriaBuilder.createQuery(Tuple::class.java) - val queryRootVaultStates = criteriaQuery.from(VaultSchemaV1.VaultStates::class.java) - - // TODO: revisit (use single instance of parser for all queries) - val criteriaParser = HibernateQueryCriteriaParser(contractStateType, contractStateTypeMappings, criteriaBuilder, criteriaQuery, queryRootVaultStates) - - try { - // parse criteria and build where predicates - criteriaParser.parse(criteria, sorting) - - // prepare query for execution - val query = session.createQuery(criteriaQuery) - - // pagination checks - if (!paging.isDefault) { - // pagination - if (paging.pageNumber < DEFAULT_PAGE_NUM) throw VaultQueryException("Page specification: invalid page number ${paging.pageNumber} [page numbers start from $DEFAULT_PAGE_NUM]") - if (paging.pageSize < 1) throw VaultQueryException("Page specification: invalid page size ${paging.pageSize} [must be a value between 1 and $MAX_PAGE_SIZE]") - } - - query.firstResult = (paging.pageNumber - 1) * paging.pageSize - query.maxResults = paging.pageSize + 1 // detection too many results - - // execution - val results = query.resultList - - // final pagination check (fail-fast on too many results when no pagination specified) - if (paging.isDefault && results.size > DEFAULT_PAGE_SIZE) - throw VaultQueryException("Please specify a `PageSpecification` as there are more results [${results.size}] than the default page size [$DEFAULT_PAGE_SIZE]") - - val statesAndRefs: MutableList> = mutableListOf() - val statesMeta: MutableList = mutableListOf() - val otherResults: MutableList = mutableListOf() - - results.asSequence() - .forEachIndexed { index, result -> - if (result[0] is VaultSchemaV1.VaultStates) { - if (!paging.isDefault && index == paging.pageSize) // skip last result if paged - return@forEachIndexed - val vaultState = result[0] as VaultSchemaV1.VaultStates - val stateRef = StateRef(SecureHash.parse(vaultState.stateRef!!.txId!!), vaultState.stateRef!!.index!!) - val state = vaultState.contractState.deserialize>(context = STORAGE_CONTEXT) - statesMeta.add(Vault.StateMetadata(stateRef, - vaultState.contractStateClassName, - vaultState.recordedTime, - vaultState.consumedTime, - vaultState.stateStatus, - vaultState.notary, - vaultState.lockId, - vaultState.lockUpdateTime)) - statesAndRefs.add(StateAndRef(state, stateRef)) - } - else { - // TODO: improve typing of returned other results - log.debug { "OtherResults: ${Arrays.toString(result.toArray())}" } - otherResults.addAll(result.toArray().asList()) - } - } - - return Vault.Page(states = statesAndRefs, statesMetadata = statesMeta, stateTypes = criteriaParser.stateTypes, totalStatesAvailable = totalStates, otherResults = otherResults) - } catch (e: Exception) { - log.error(e.message) - throw e.cause ?: e - } - } - } - - private val mutex = ThreadBox({ vault.updatesPublisher }) - - @Throws(VaultQueryException::class) - override fun _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class): DataFeed, Vault.Update> { - return mutex.locked { - val snapshotResults = _queryBy(criteria, paging, sorting, contractStateType) - val updates: Observable> = uncheckedCast(vault.updatesPublisher.bufferUntilSubscribed().filter { it.containsType(contractStateType, snapshotResults.stateTypes) }) - DataFeed(snapshotResults, updates) - } - } - - private fun getSession(): Session { - return sessionFactory.withOptions(). - connection(DatabaseTransactionManager.current().connection). - openSession() - } - - /** - * Derive list from existing vault states and then incrementally update using vault observables - */ - fun bootstrapContractStateTypes(): MutableMap> { - val criteria = criteriaBuilder.createQuery(String::class.java) - val vaultStates = criteria.from(VaultSchemaV1.VaultStates::class.java) - criteria.select(vaultStates.get("contractStateClassName")).distinct(true) - val session = getSession() - session.use { - val query = session.createQuery(criteria) - val results = query.resultList - val distinctTypes = results.map { it } - - val contractInterfaceToConcreteTypes = mutableMapOf>() - distinctTypes.forEach { type -> - val concreteType: Class = uncheckedCast(Class.forName(type)) - val contractInterfaces = deriveContractInterfaces(concreteType) - contractInterfaces.map { - val contractInterface = contractInterfaceToConcreteTypes.getOrPut(it.name, { mutableSetOf() }) - contractInterface.add(concreteType.name) - } - } - return contractInterfaceToConcreteTypes - } - } - - private fun deriveContractInterfaces(clazz: Class): Set> { - val myInterfaces: MutableSet> = mutableSetOf() - clazz.interfaces.forEach { - if (!it.equals(ContractState::class.java)) { - myInterfaces.add(uncheckedCast(it)) - myInterfaces.addAll(deriveContractInterfaces(uncheckedCast(it))) - } - } - return myInterfaces - } -} \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt index 196dca299f..15796f15eb 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt @@ -6,14 +6,15 @@ import net.corda.core.contracts.* import net.corda.core.crypto.SecureHash import net.corda.core.internal.ThreadBox import net.corda.core.internal.VisibleForTesting +import net.corda.core.internal.bufferUntilSubscribed import net.corda.core.internal.tee +import net.corda.core.messaging.DataFeed import net.corda.core.node.ServiceHub import net.corda.core.node.services.StatesNotAvailableException import net.corda.core.node.services.Vault +import net.corda.core.node.services.VaultQueryException import net.corda.core.node.services.VaultService -import net.corda.core.node.services.vault.QueryCriteria -import net.corda.core.node.services.vault.Sort -import net.corda.core.node.services.vault.SortAttribute +import net.corda.core.node.services.vault.* import net.corda.core.schemas.PersistentStateRef import net.corda.core.serialization.SerializationDefaults.STORAGE_CONTEXT import net.corda.core.serialization.SingletonSerializeAsToken @@ -23,15 +24,18 @@ import net.corda.core.transactions.CoreTransaction import net.corda.core.transactions.NotaryChangeWireTransaction import net.corda.core.transactions.WireTransaction import net.corda.core.utilities.* +import net.corda.node.services.persistence.HibernateConfiguration import net.corda.node.services.statemachine.FlowStateMachineImpl import net.corda.node.utilities.DatabaseTransactionManager import net.corda.node.utilities.bufferUntilDatabaseCommit import net.corda.node.utilities.wrapWithDatabaseTransaction +import org.hibernate.Session import rx.Observable import rx.subjects.PublishSubject import java.security.PublicKey import java.time.Instant import java.util.* +import javax.persistence.Tuple /** * Currently, the node vault service is a very simple RDBMS backed implementation. It will change significantly when @@ -43,7 +47,7 @@ import java.util.* * TODO: keep an audit trail with time stamps of previously unconsumed states "as of" a particular point in time. * TODO: have transaction storage do some caching. */ -class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsToken(), VaultService { +class NodeVaultService(private val services: ServiceHub, private val hibernateConfig: HibernateConfiguration) : SingletonSerializeAsToken(), VaultService { private companion object { val log = loggerFor() @@ -102,9 +106,6 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT override val updates: Observable> get() = mutex.locked { _updatesInDbTx } - override val updatesPublisher: PublishSubject> - get() = mutex.locked { _updatesPublisher } - /** * Splits the provided [txns] into batches of [WireTransaction] and [NotaryChangeWireTransaction]. * This is required because the batches get aggregated into single updates, and we want to be able to @@ -347,7 +348,7 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT val enrichedCriteria = QueryCriteria.VaultQueryCriteria( contractStateTypes = setOf(contractStateType), softLockingCondition = QueryCriteria.SoftLockingCondition(QueryCriteria.SoftLockingType.UNLOCKED_AND_SPECIFIED, listOf(lockId))) - val results = services.vaultQueryService.queryBy(contractStateType, enrichedCriteria.and(eligibleStatesQuery), sorter) + val results = queryBy(contractStateType, enrichedCriteria.and(eligibleStatesQuery), sorter) var claimedAmount = 0L val claimedStates = mutableListOf>() @@ -368,8 +369,6 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT return claimedStates } - - @VisibleForTesting internal fun isRelevant(state: ContractState, myKeys: Set): Boolean { val keysToCheck = when (state) { @@ -378,4 +377,172 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT } return keysToCheck.any { it in myKeys } } + + private var sessionFactory = hibernateConfig.sessionFactoryForRegisteredSchemas() + private var criteriaBuilder = sessionFactory.criteriaBuilder + + /** + * Maintain a list of contract state interfaces to concrete types stored in the vault + * for usage in generic queries of type queryBy or queryBy> + */ + private val contractStateTypeMappings = bootstrapContractStateTypes() + + init { + rawUpdates.subscribe { update -> + update.produced.forEach { + val concreteType = it.state.data.javaClass + log.trace { "State update of type: $concreteType" } + val seen = contractStateTypeMappings.any { it.value.contains(concreteType.name) } + if (!seen) { + val contractInterfaces = deriveContractInterfaces(concreteType) + contractInterfaces.map { + val contractInterface = contractStateTypeMappings.getOrPut(it.name, { mutableSetOf() }) + contractInterface.add(concreteType.name) + } + } + } + } + } + + @Throws(VaultQueryException::class) + override fun _queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class): Vault.Page { + log.info("Vault Query for contract type: $contractStateType, criteria: $criteria, pagination: $paging, sorting: $sorting") + + // refresh to include any schemas registered after initial VQ service initialisation + sessionFactory = hibernateConfig.sessionFactoryForRegisteredSchemas() + criteriaBuilder = sessionFactory.criteriaBuilder + + // calculate total results where a page specification has been defined + var totalStates = -1L + if (!paging.isDefault) { + val count = builder { VaultSchemaV1.VaultStates::recordedTime.count() } + val countCriteria = QueryCriteria.VaultCustomQueryCriteria(count, Vault.StateStatus.ALL) + val results = queryBy(contractStateType, criteria.and(countCriteria)) + totalStates = results.otherResults[0] as Long + } + + val session = getSession() + + session.use { + val criteriaQuery = criteriaBuilder.createQuery(Tuple::class.java) + val queryRootVaultStates = criteriaQuery.from(VaultSchemaV1.VaultStates::class.java) + + // TODO: revisit (use single instance of parser for all queries) + val criteriaParser = HibernateQueryCriteriaParser(contractStateType, contractStateTypeMappings, criteriaBuilder, criteriaQuery, queryRootVaultStates) + + try { + // parse criteria and build where predicates + criteriaParser.parse(criteria, sorting) + + // prepare query for execution + val query = session.createQuery(criteriaQuery) + + // pagination checks + if (!paging.isDefault) { + // pagination + if (paging.pageNumber < DEFAULT_PAGE_NUM) throw VaultQueryException("Page specification: invalid page number ${paging.pageNumber} [page numbers start from ${DEFAULT_PAGE_NUM}]") + if (paging.pageSize < 1) throw VaultQueryException("Page specification: invalid page size ${paging.pageSize} [must be a value between 1 and ${MAX_PAGE_SIZE}]") + } + + query.firstResult = (paging.pageNumber - 1) * paging.pageSize + query.maxResults = paging.pageSize + 1 // detection too many results + + // execution + val results = query.resultList + + // final pagination check (fail-fast on too many results when no pagination specified) + if (paging.isDefault && results.size > DEFAULT_PAGE_SIZE) + throw VaultQueryException("Please specify a `PageSpecification` as there are more results [${results.size}] than the default page size [${DEFAULT_PAGE_SIZE}]") + + val statesAndRefs: MutableList> = mutableListOf() + val statesMeta: MutableList = mutableListOf() + val otherResults: MutableList = mutableListOf() + + results.asSequence() + .forEachIndexed { index, result -> + if (result[0] is VaultSchemaV1.VaultStates) { + if (!paging.isDefault && index == paging.pageSize) // skip last result if paged + return@forEachIndexed + val vaultState = result[0] as VaultSchemaV1.VaultStates + val stateRef = StateRef(SecureHash.parse(vaultState.stateRef!!.txId!!), vaultState.stateRef!!.index!!) + val state = vaultState.contractState.deserialize>(context = STORAGE_CONTEXT) + statesMeta.add(Vault.StateMetadata(stateRef, + vaultState.contractStateClassName, + vaultState.recordedTime, + vaultState.consumedTime, + vaultState.stateStatus, + vaultState.notary, + vaultState.lockId, + vaultState.lockUpdateTime)) + statesAndRefs.add(StateAndRef(state, stateRef)) + } + else { + // TODO: improve typing of returned other results + log.debug { "OtherResults: ${Arrays.toString(result.toArray())}" } + otherResults.addAll(result.toArray().asList()) + } + } + + return Vault.Page(states = statesAndRefs, statesMetadata = statesMeta, stateTypes = criteriaParser.stateTypes, totalStatesAvailable = totalStates, otherResults = otherResults) + } catch (e: java.lang.Exception) { + log.error(e.message) + throw e.cause ?: e + } + } + } + + @Throws(VaultQueryException::class) + override fun _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class): DataFeed, Vault.Update> { + return mutex.locked { + val snapshotResults = _queryBy(criteria, paging, sorting, contractStateType) + @Suppress("UNCHECKED_CAST") + val updates = _updatesPublisher.bufferUntilSubscribed().filter { it.containsType(contractStateType, snapshotResults.stateTypes) } as Observable> + DataFeed(snapshotResults, updates) + } + } + + private fun getSession(): Session { + return sessionFactory.withOptions(). + connection(DatabaseTransactionManager.current().connection). + openSession() + } + + /** + * Derive list from existing vault states and then incrementally update using vault observables + */ + private fun bootstrapContractStateTypes(): MutableMap> { + val criteria = criteriaBuilder.createQuery(String::class.java) + val vaultStates = criteria.from(VaultSchemaV1.VaultStates::class.java) + criteria.select(vaultStates.get("contractStateClassName")).distinct(true) + val session = getSession() + session.use { + val query = session.createQuery(criteria) + val results = query.resultList + val distinctTypes = results.map { it } + + val contractInterfaceToConcreteTypes = mutableMapOf>() + distinctTypes.forEach { type -> + @Suppress("UNCHECKED_CAST") + val concreteType = Class.forName(type) as Class + val contractInterfaces = deriveContractInterfaces(concreteType) + contractInterfaces.map { + val contractInterface = contractInterfaceToConcreteTypes.getOrPut(it.name, { mutableSetOf() }) + contractInterface.add(concreteType.name) + } + } + return contractInterfaceToConcreteTypes + } + } + + private fun deriveContractInterfaces(clazz: Class): Set> { + val myInterfaces: MutableSet> = mutableSetOf() + clazz.interfaces.forEach { + if (!it.equals(ContractState::class.java)) { + @Suppress("UNCHECKED_CAST") + myInterfaces.add(it as Class) + myInterfaces.addAll(deriveContractInterfaces(it)) + } + } + return myInterfaces + } } diff --git a/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java b/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java index f963189d1f..6a38dde99a 100644 --- a/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java +++ b/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java @@ -1,63 +1,44 @@ package net.corda.node.services.vault; -import com.google.common.collect.ImmutableSet; -import kotlin.Pair; -import kotlin.Triple; +import com.google.common.collect.*; +import kotlin.*; import net.corda.core.contracts.*; -import net.corda.core.identity.AbstractParty; -import net.corda.core.messaging.DataFeed; -import net.corda.core.node.services.IdentityService; -import net.corda.core.node.services.Vault; -import net.corda.core.node.services.VaultQueryException; -import net.corda.core.node.services.VaultQueryService; +import net.corda.core.identity.*; +import net.corda.core.messaging.*; +import net.corda.core.node.services.*; import net.corda.core.node.services.vault.*; -import net.corda.core.node.services.vault.QueryCriteria.LinearStateQueryCriteria; -import net.corda.core.node.services.vault.QueryCriteria.VaultCustomQueryCriteria; -import net.corda.core.node.services.vault.QueryCriteria.VaultQueryCriteria; -import net.corda.core.schemas.MappedSchema; -import net.corda.core.utilities.EncodingUtils; -import net.corda.core.utilities.OpaqueBytes; -import net.corda.finance.contracts.DealState; -import net.corda.finance.contracts.asset.Cash; -import net.corda.finance.contracts.asset.CashUtilities; -import net.corda.finance.schemas.CashSchemaV1; -import net.corda.node.utilities.CordaPersistence; -import net.corda.node.utilities.DatabaseTransaction; -import net.corda.testing.TestConstants; -import net.corda.testing.TestDependencyInjectionBase; -import net.corda.testing.contracts.DummyLinearContract; -import net.corda.testing.contracts.VaultFiller; -import net.corda.testing.node.MockServices; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import net.corda.core.node.services.vault.QueryCriteria.*; +import net.corda.core.schemas.*; +import net.corda.core.utilities.*; +import net.corda.finance.contracts.*; +import net.corda.finance.contracts.asset.*; +import net.corda.finance.schemas.*; +import net.corda.node.utilities.*; +import net.corda.testing.*; +import net.corda.testing.contracts.*; +import net.corda.testing.node.*; +import org.junit.*; import rx.Observable; -import java.io.IOException; -import java.lang.reflect.Field; -import java.security.KeyPair; +import java.io.*; +import java.lang.reflect.*; +import java.security.*; import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; +import java.util.stream.*; -import static net.corda.core.node.services.vault.QueryCriteriaUtils.DEFAULT_PAGE_NUM; -import static net.corda.core.node.services.vault.QueryCriteriaUtils.MAX_PAGE_SIZE; -import static net.corda.core.utilities.ByteArrays.toHexString; -import static net.corda.finance.contracts.asset.CashUtilities.getDUMMY_CASH_ISSUER; -import static net.corda.finance.contracts.asset.CashUtilities.getDUMMY_CASH_ISSUER_KEY; +import static net.corda.core.node.services.vault.QueryCriteriaUtils.*; +import static net.corda.core.utilities.ByteArrays.*; +import static net.corda.finance.contracts.asset.CashUtilities.*; import static net.corda.testing.CoreTestUtils.*; -import static net.corda.testing.TestConstants.getDUMMY_NOTARY; -import static net.corda.testing.TestConstants.getDUMMY_NOTARY_KEY; -import static net.corda.testing.node.MockServices.makeTestDatabaseAndMockServices; -import static net.corda.testing.node.MockServices.makeTestIdentityService; -import static org.assertj.core.api.Assertions.assertThat; +import static net.corda.testing.TestConstants.*; +import static net.corda.testing.node.MockServices.*; +import static org.assertj.core.api.Assertions.*; public class VaultQueryJavaTests extends TestDependencyInjectionBase { private MockServices services; private MockServices issuerServices; - private VaultQueryService vaultQuerySvc; + private VaultService vaultService; private CordaPersistence database; @Before @@ -73,7 +54,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { issuerServices = new MockServices(getDUMMY_CASH_ISSUER_KEY(), getBOC_KEY()); database = databaseAndServices.getFirst(); services = databaseAndServices.getSecond(); - vaultQuerySvc = services.getVaultQueryService(); + vaultService = services.getVaultService(); } @After @@ -98,7 +79,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { }); database.transaction(tx -> { // DOCSTART VaultJavaQueryExample0 - Vault.Page results = vaultQuerySvc.queryBy(LinearState.class); + Vault.Page results = vaultService.queryBy(LinearState.class); // DOCEND VaultJavaQueryExample0 assertThat(results.getStates()).hasSize(3); @@ -121,7 +102,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { SortAttribute.Standard sortAttribute = new SortAttribute.Standard(Sort.CommonStateAttribute.STATE_REF_TXN_ID); Sort sorting = new Sort(Collections.singletonList(new Sort.SortColumn(sortAttribute, Sort.Direction.ASC))); VaultQueryCriteria criteria = new VaultQueryCriteria(Vault.StateStatus.UNCONSUMED, null, stateRefs); - Vault.Page results = vaultQuerySvc.queryBy(DummyLinearContract.State.class, criteria, sorting); + Vault.Page results = vaultService.queryBy(DummyLinearContract.State.class, criteria, sorting); assertThat(results.getStates()).hasSize(2); @@ -156,7 +137,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { database.transaction(tx -> { // DOCSTART VaultJavaQueryExample1 VaultQueryCriteria criteria = new VaultQueryCriteria(Vault.StateStatus.CONSUMED); - Vault.Page results = vaultQuerySvc.queryBy(Cash.State.class, criteria); + Vault.Page results = vaultService.queryBy(Cash.State.class, criteria); // DOCEND VaultJavaQueryExample1 assertThat(results.getStates()).hasSize(3); @@ -202,7 +183,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { PageSpecification pageSpec = new PageSpecification(DEFAULT_PAGE_NUM, MAX_PAGE_SIZE); Sort.SortColumn sortByUid = new Sort.SortColumn(new SortAttribute.Standard(Sort.LinearStateAttribute.UUID), Sort.Direction.DESC); Sort sorting = new Sort(ImmutableSet.of(sortByUid)); - Vault.Page results = vaultQuerySvc.queryBy(LinearState.class, compositeCriteria2, pageSpec, sorting); + Vault.Page results = vaultService.queryBy(LinearState.class, compositeCriteria2, pageSpec, sorting); // DOCEND VaultJavaQueryExample2 assertThat(results.getStates()).hasSize(4); @@ -243,7 +224,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { QueryCriteria criteria = generalCriteria.and(customCriteria1).and(customCriteria2); - Vault.Page results = vaultQuerySvc.queryBy(Cash.State.class, criteria); + Vault.Page results = vaultService.queryBy(Cash.State.class, criteria); // DOCEND VaultJavaQueryExample3 assertThat(results.getStates()).hasSize(2); @@ -279,7 +260,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { Set> contractStateTypes = new HashSet(Collections.singletonList(Cash.State.class)); VaultQueryCriteria criteria = new VaultQueryCriteria(Vault.StateStatus.UNCONSUMED, contractStateTypes); - DataFeed, Vault.Update> results = vaultQuerySvc.trackBy(ContractState.class, criteria); + DataFeed, Vault.Update> results = vaultService.trackBy(ContractState.class, criteria); Vault.Page snapshot = results.getSnapshot(); Observable> updates = results.getUpdates(); @@ -318,7 +299,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { PageSpecification pageSpec = new PageSpecification(DEFAULT_PAGE_NUM, MAX_PAGE_SIZE); Sort.SortColumn sortByUid = new Sort.SortColumn(new SortAttribute.Standard(Sort.LinearStateAttribute.UUID), Sort.Direction.DESC); Sort sorting = new Sort(ImmutableSet.of(sortByUid)); - DataFeed, Vault.Update> results = vaultQuerySvc.trackBy(ContractState.class, compositeCriteria, pageSpec, sorting); + DataFeed, Vault.Update> results = vaultService.trackBy(ContractState.class, compositeCriteria, pageSpec, sorting); Vault.Page snapshot = results.getSnapshot(); // DOCEND VaultJavaQueryExample5 @@ -364,7 +345,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { QueryCriteria avgCriteria = new VaultCustomQueryCriteria(Builder.avg(pennies)); QueryCriteria criteria = sumCriteria.and(countCriteria).and(maxCriteria).and(minCriteria).and(avgCriteria); - Vault.Page results = vaultQuerySvc.queryBy(Cash.State.class, criteria); + Vault.Page results = vaultService.queryBy(Cash.State.class, criteria); // DOCEND VaultJavaQueryExample21 assertThat(results.getOtherResults()).hasSize(5); @@ -413,7 +394,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { QueryCriteria avgCriteria = new VaultCustomQueryCriteria(Builder.avg(pennies, Collections.singletonList(currency))); QueryCriteria criteria = sumCriteria.and(countCriteria).and(maxCriteria).and(minCriteria).and(avgCriteria); - Vault.Page results = vaultQuerySvc.queryBy(Cash.State.class, criteria); + Vault.Page results = vaultService.queryBy(Cash.State.class, criteria); // DOCEND VaultJavaQueryExample22 assertThat(results.getOtherResults()).hasSize(27); @@ -480,7 +461,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase { QueryCriteria sumCriteria = new VaultCustomQueryCriteria(Builder.sum(pennies, Arrays.asList(issuerParty, currency), Sort.Direction.DESC)); - Vault.Page results = vaultQuerySvc.queryBy(Cash.State.class, sumCriteria); + Vault.Page results = vaultService.queryBy(Cash.State.class, sumCriteria); // DOCEND VaultJavaQueryExample23 assertThat(results.getOtherResults()).hasSize(12); diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index f713bf0f5e..ecd2e604d0 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -100,7 +100,7 @@ class CordaRPCOpsImplTest { // Check the monitoring service wallet is empty aliceNode.database.transaction { - assertFalse(aliceNode.services.vaultQueryService.queryBy().totalStatesAvailable > 0) + assertFalse(aliceNode.services.vaultService.queryBy().totalStatesAvailable > 0) } // Tell the monitoring service node to issue some cash diff --git a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt index 33202b4874..0b7466dddf 100644 --- a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt @@ -96,7 +96,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { overrideClock = testClock, keyManagement = kms, network = mockMessagingService), TestReference { - override val vaultService: VaultService = NodeVaultService(this) + override val vaultService: VaultService = NodeVaultService(this, database.hibernateConfig) override val testReference = this@NodeSchedulerServiceTest override val cordappProvider: CordappProviderImpl = CordappProviderImpl(CordappLoader.createWithTestPackages()).start(attachments) } 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 bfd6557377..072fd74a05 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 @@ -5,7 +5,7 @@ import net.corda.core.concurrent.CordaFuture import net.corda.core.contracts.* import net.corda.core.flows.* import net.corda.core.identity.Party -import net.corda.core.node.services.VaultQueryService +import net.corda.core.node.services.VaultService import net.corda.core.node.services.queryBy import net.corda.core.node.services.vault.DEFAULT_PAGE_NUM import net.corda.core.node.services.vault.PageSpecification @@ -128,10 +128,10 @@ class ScheduledFlowTests { nodeA.services.startFlow(InsertInitialStateFlow(nodeB.info.chooseIdentity())) mockNet.waitQuiescent() val stateFromA = nodeA.database.transaction { - nodeA.services.vaultQueryService.queryBy().states.single() + nodeA.services.vaultService.queryBy().states.single() } val stateFromB = nodeB.database.transaction { - nodeB.services.vaultQueryService.queryBy().states.single() + nodeB.services.vaultService.queryBy().states.single() } assertEquals(1, countScheduledFlows) assertEquals("Must be same copy on both nodes", stateFromA, stateFromB) @@ -153,10 +153,10 @@ class ScheduledFlowTests { // Convert the states into maps to make error reporting easier val statesFromA: List> = nodeA.database.transaction { - queryStatesWithPaging(nodeA.services.vaultQueryService) + queryStatesWithPaging(nodeA.services.vaultService) } val statesFromB: List> = nodeB.database.transaction { - queryStatesWithPaging(nodeB.services.vaultQueryService) + queryStatesWithPaging(nodeB.services.vaultService) } assertEquals("Expect all states to be present",2 * N, statesFromA.count()) statesFromA.forEach { ref -> @@ -179,13 +179,13 @@ class ScheduledFlowTests { * * @return states ordered by the transaction ID. */ - private fun queryStatesWithPaging(vaultQueryService: VaultQueryService): List> { + private fun queryStatesWithPaging(vaultService: VaultService): List> { // DOCSTART VaultQueryExamplePaging var pageNumber = DEFAULT_PAGE_NUM val states = mutableListOf>() do { val pageSpec = PageSpecification(pageSize = PAGE_SIZE, pageNumber = pageNumber) - val results = vaultQueryService.queryBy(VaultQueryCriteria(), pageSpec, SORTING) + val results = vaultService.queryBy(VaultQueryCriteria(), pageSpec, SORTING) states.addAll(results.states) pageNumber++ } while ((pageSpec.pageSize * (pageNumber)) <= results.totalStatesAvailable) diff --git a/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt b/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt index ec6a134f13..4ea017461d 100644 --- a/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageTests.kt @@ -51,7 +51,7 @@ class DBTransactionStorageTests : TestDependencyInjectionBase() { services = object : MockServices(BOB_KEY) { override val vaultService: VaultService get() { - val vaultService = NodeVaultService(this) + val vaultService = NodeVaultService(this, database.hibernateConfig) hibernatePersister = HibernateObserver(vaultService.rawUpdates, database.hibernateConfig) return vaultService } 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 43869643f7..a08230d9ff 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 @@ -1024,9 +1024,9 @@ class FlowFrameworkTests { override fun call(): List> { val otherPartySession = initiateFlow(otherParty) otherPartySession.send(stx) - // hold onto reference here to force checkpoint of vaultQueryService and thus + // hold onto reference here to force checkpoint of vaultService and thus // prove it is registered as a tokenizableService in the node - val vaultQuerySvc = serviceHub.vaultQueryService + val vaultQuerySvc = serviceHub.vaultService waitForLedgerCommit(stx.id) return vaultQuerySvc.queryBy().states } 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 b5c9dc19d7..2880435862 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 @@ -47,8 +47,7 @@ import kotlin.test.assertTrue class NodeVaultServiceTest : TestDependencyInjectionBase() { lateinit var services: MockServices lateinit var issuerServices: MockServices - val vaultSvc: VaultService get() = services.vaultService - val vaultQuery: VaultQueryService get() = services.vaultQueryService + val vaultService: VaultService get() = services.vaultService lateinit var database: CordaPersistence @Before @@ -94,11 +93,10 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 3, 3, Random(0L)) } database.transaction { - val w1 = vaultQuery.queryBy().states + val w1 = vaultService.queryBy().states assertThat(w1).hasSize(3) - val originalVault = vaultSvc - val originalVaultQuery = vaultQuery + val originalVault = vaultService val services2 = object : MockServices() { override val vaultService: NodeVaultService get() = originalVault as NodeVaultService override fun recordTransactions(notifyVault: Boolean, txs: Iterable) { @@ -107,11 +105,9 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { vaultService.notify(stx.tx) } } - - override val vaultQueryService: VaultQueryService get() = originalVaultQuery } - val w2 = services2.vaultQueryService.queryBy().states + val w2 = services2.vaultService.queryBy().states assertThat(w2).hasSize(3) } } @@ -122,10 +118,10 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 3, 3, Random(0L)) } database.transaction { - val w1 = vaultQuery.queryBy().states + val w1 = vaultService.queryBy().states assertThat(w1).hasSize(3) - val states = vaultQuery.queryBy(VaultQueryCriteria(stateRefs = listOf(w1[1].ref, w1[2].ref))).states + val states = vaultService.queryBy(VaultQueryCriteria(stateRefs = listOf(w1[1].ref, w1[2].ref))).states assertThat(states).hasSize(2) } } @@ -137,34 +133,34 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { } database.transaction { - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertThat(unconsumedStates).hasSize(3) val stateRefsToSoftLock = NonEmptySet.of(unconsumedStates[1].ref, unconsumedStates[2].ref) // soft lock two of the three states val softLockId = UUID.randomUUID() - vaultSvc.softLockReserve(softLockId, stateRefsToSoftLock) + vaultService.softLockReserve(softLockId, stateRefsToSoftLock) // all softlocked states val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY)) - assertThat(vaultQuery.queryBy(criteriaLocked).states).hasSize(2) + assertThat(vaultService.queryBy(criteriaLocked).states).hasSize(2) // my softlocked states val criteriaByLockId = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId))) - assertThat(vaultQuery.queryBy(criteriaByLockId).states).hasSize(2) + assertThat(vaultService.queryBy(criteriaByLockId).states).hasSize(2) // excluding softlocked states - val unlockedStates1 = vaultQuery.queryBy(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states + val unlockedStates1 = vaultService.queryBy(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states assertThat(unlockedStates1).hasSize(1) // soft lock release one of the states explicitly - vaultSvc.softLockRelease(softLockId, NonEmptySet.of(unconsumedStates[1].ref)) - val unlockedStates2 = vaultQuery.queryBy(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states + vaultService.softLockRelease(softLockId, NonEmptySet.of(unconsumedStates[1].ref)) + val unlockedStates2 = vaultService.queryBy(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states assertThat(unlockedStates2).hasSize(2) // soft lock release the rest by id - vaultSvc.softLockRelease(softLockId) - val unlockedStates = vaultQuery.queryBy(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states + vaultService.softLockRelease(softLockId) + val unlockedStates = vaultService.queryBy(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states assertThat(unlockedStates).hasSize(3) // should be back to original states @@ -195,8 +191,8 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { backgroundExecutor.submit { try { database.transaction { - vaultSvc.softLockReserve(softLockId1, stateRefsToSoftLock) - assertThat(vaultQuery.queryBy(criteriaByLockId1).states).hasSize(3) + vaultService.softLockReserve(softLockId1, stateRefsToSoftLock) + assertThat(vaultService.queryBy(criteriaByLockId1).states).hasSize(3) } println("SOFT LOCK STATES #1 succeeded") } catch(e: Throwable) { @@ -211,8 +207,8 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { try { Thread.sleep(100) // let 1st thread soft lock them 1st database.transaction { - vaultSvc.softLockReserve(softLockId2, stateRefsToSoftLock) - assertThat(vaultQuery.queryBy(criteriaByLockId2).states).hasSize(3) + vaultService.softLockReserve(softLockId2, stateRefsToSoftLock) + assertThat(vaultService.queryBy(criteriaByLockId2).states).hasSize(3) } println("SOFT LOCK STATES #2 succeeded") } catch(e: Throwable) { @@ -224,10 +220,10 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { countDown.await() database.transaction { - val lockStatesId1 = vaultQuery.queryBy(criteriaByLockId1).states + val lockStatesId1 = vaultService.queryBy(criteriaByLockId1).states println("SOFT LOCK #1 final states: $lockStatesId1") assertThat(lockStatesId1.size).isIn(0, 3) - val lockStatesId2 = vaultQuery.queryBy(criteriaByLockId2).states + val lockStatesId2 = vaultService.queryBy(criteriaByLockId2).states println("SOFT LOCK #2 final states: $lockStatesId2") assertThat(lockStatesId2.size).isIn(0, 3) } @@ -248,15 +244,15 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { // lock 1st state with LockId1 database.transaction { - vaultSvc.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first())) + vaultService.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first())) val criteriaByLockId1 = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId1))) - assertThat(vaultQuery.queryBy(criteriaByLockId1).states).hasSize(1) + assertThat(vaultService.queryBy(criteriaByLockId1).states).hasSize(1) } // attempt to lock all 3 states with LockId2 database.transaction { assertThatExceptionOfType(StatesNotAvailableException::class.java).isThrownBy( - { vaultSvc.softLockReserve(softLockId2, stateRefsToSoftLock.toNonEmptySet()) } + { vaultService.softLockReserve(softLockId2, stateRefsToSoftLock.toNonEmptySet()) } ).withMessageContaining("only 2 rows available").withNoCause() } } @@ -276,14 +272,14 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { // lock states with LockId1 database.transaction { - vaultSvc.softLockReserve(softLockId1, stateRefsToSoftLock) - assertThat(vaultQuery.queryBy(criteriaByLockId1).states).hasSize(3) + vaultService.softLockReserve(softLockId1, stateRefsToSoftLock) + assertThat(vaultService.queryBy(criteriaByLockId1).states).hasSize(3) } // attempt to relock same states with LockId1 database.transaction { - vaultSvc.softLockReserve(softLockId1, stateRefsToSoftLock) - assertThat(vaultQuery.queryBy(criteriaByLockId1).states).hasSize(3) + vaultService.softLockReserve(softLockId1, stateRefsToSoftLock) + assertThat(vaultService.queryBy(criteriaByLockId1).states).hasSize(3) } } @@ -303,14 +299,14 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { // lock states with LockId1 database.transaction { - vaultSvc.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first())) - assertThat(vaultQuery.queryBy(criteriaByLockId1).states).hasSize(1) + vaultService.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first())) + assertThat(vaultService.queryBy(criteriaByLockId1).states).hasSize(1) } // attempt to lock all states with LockId1 (including previously already locked one) database.transaction { - vaultSvc.softLockReserve(softLockId1, stateRefsToSoftLock.toNonEmptySet()) - assertThat(vaultQuery.queryBy(criteriaByLockId1).states).hasSize(3) + vaultService.softLockReserve(softLockId1, stateRefsToSoftLock.toNonEmptySet()) + assertThat(vaultService.queryBy(criteriaByLockId1).states).hasSize(3) } } @@ -321,15 +317,15 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { } database.transaction { - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertThat(unconsumedStates).hasSize(1) - val spendableStatesUSD = vaultSvc.unconsumedCashStatesForSpending(100.DOLLARS) + val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(100.DOLLARS) spendableStatesUSD.forEach(::println) assertThat(spendableStatesUSD).hasSize(1) assertThat(spendableStatesUSD[0].state.data.amount.quantity).isEqualTo(100L * 100) val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY)) - assertThat(vaultQuery.queryBy(criteriaLocked).states).hasSize(1) + assertThat(vaultService.queryBy(criteriaLocked).states).hasSize(1) } } @@ -340,7 +336,7 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 1, 1, Random(0L), issuedBy = (BOC.ref(1))) } database.transaction { - val spendableStatesUSD = vaultSvc.unconsumedCashStatesForSpending(200.DOLLARS, + val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(200.DOLLARS, onlyFromIssuerParties = setOf(DUMMY_CASH_ISSUER.party, BOC)) spendableStatesUSD.forEach(::println) assertThat(spendableStatesUSD).hasSize(2) @@ -359,10 +355,10 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 1, 1, Random(0L), issuedBy = (BOC.ref(3)), ref = OpaqueBytes.of(3)) } database.transaction { - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertThat(unconsumedStates).hasSize(4) - val spendableStatesUSD = vaultSvc.unconsumedCashStatesForSpending(200.DOLLARS, + val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(200.DOLLARS, onlyFromIssuerParties = setOf(BOC), withIssuerRefs = setOf(OpaqueBytes.of(1), OpaqueBytes.of(2))) assertThat(spendableStatesUSD).hasSize(2) assertThat(spendableStatesUSD[0].state.data.amount.token.issuer.party).isEqualTo(BOC) @@ -378,14 +374,14 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 1, 1, Random(0L)) } database.transaction { - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertThat(unconsumedStates).hasSize(1) - val spendableStatesUSD = vaultSvc.unconsumedCashStatesForSpending(110.DOLLARS) + val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(110.DOLLARS) spendableStatesUSD.forEach(::println) assertThat(spendableStatesUSD).hasSize(0) val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY)) - assertThat(vaultQuery.queryBy(criteriaLocked).states).hasSize(0) + assertThat(vaultService.queryBy(criteriaLocked).states).hasSize(0) } } @@ -395,15 +391,15 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 2, 2, Random(0L)) } database.transaction { - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertThat(unconsumedStates).hasSize(2) - val spendableStatesUSD = vaultSvc.unconsumedCashStatesForSpending(1.DOLLARS) + val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(1.DOLLARS) spendableStatesUSD.forEach(::println) assertThat(spendableStatesUSD).hasSize(1) assertThat(spendableStatesUSD[0].state.data.amount.quantity).isGreaterThanOrEqualTo(100L) val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY)) - assertThat(vaultQuery.queryBy(criteriaLocked).states).hasSize(1) + assertThat(vaultService.queryBy(criteriaLocked).states).hasSize(1) } } @@ -416,18 +412,18 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { } database.transaction { var unlockedStates = 30 - val allStates = vaultQuery.queryBy().states + val allStates = vaultService.queryBy().states assertThat(allStates).hasSize(unlockedStates) var lockedCount = 0 for (i in 1..5) { val lockId = UUID.randomUUID() - val spendableStatesUSD = vaultSvc.unconsumedCashStatesForSpending(20.DOLLARS, lockId = lockId) + val spendableStatesUSD = vaultService.unconsumedCashStatesForSpending(20.DOLLARS, lockId = lockId) spendableStatesUSD.forEach(::println) assertThat(spendableStatesUSD.size <= unlockedStates) unlockedStates -= spendableStatesUSD.size val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(lockId))) - val lockedStates = vaultQuery.queryBy(criteriaLocked).states + val lockedStates = vaultService.queryBy(criteriaLocked).states if (spendableStatesUSD.isNotEmpty()) { assertEquals(spendableStatesUSD.size, lockedStates.size) val lockedTotal = lockedStates.map { it.state.data }.sumCash() @@ -438,7 +434,7 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { } } val criteriaLocked = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY)) - assertThat(vaultQuery.queryBy(criteriaLocked).states).hasSize(lockedCount) + assertThat(vaultService.queryBy(criteriaLocked).states).hasSize(lockedCount) } } @@ -457,10 +453,10 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.recordTransactions(usefulTX) - vaultSvc.addNoteToTransaction(usefulTX.id, "USD Sample Note 1") - vaultSvc.addNoteToTransaction(usefulTX.id, "USD Sample Note 2") - vaultSvc.addNoteToTransaction(usefulTX.id, "USD Sample Note 3") - assertEquals(3, vaultSvc.getTransactionNotes(usefulTX.id).count()) + vaultService.addNoteToTransaction(usefulTX.id, "USD Sample Note 1") + vaultService.addNoteToTransaction(usefulTX.id, "USD Sample Note 2") + vaultService.addNoteToTransaction(usefulTX.id, "USD Sample Note 3") + assertEquals(3, vaultService.getTransactionNotes(usefulTX.id).count()) // Issue more Money (GBP) val anotherBuilder = TransactionBuilder(null).apply { @@ -470,8 +466,8 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() { services.recordTransactions(anotherTX) - vaultSvc.addNoteToTransaction(anotherTX.id, "GBP Sample Note 1") - assertEquals(1, vaultSvc.getTransactionNotes(anotherTX.id).count()) + vaultService.addNoteToTransaction(anotherTX.id, "GBP Sample Note 1") + assertEquals(1, vaultService.getTransactionNotes(anotherTX.id).count()) } } 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 b6aabe44c6..74c799fc57 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 @@ -48,8 +48,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { private lateinit var services: MockServices private lateinit var notaryServices: MockServices - private val vaultSvc: VaultService get() = services.vaultService - private val vaultQuerySvc: VaultQueryService get() = services.vaultQueryService + private val vaultService: VaultService get() = services.vaultService private val identitySvc: IdentityService = makeTestIdentityService() private lateinit var database: CordaPersistence @@ -146,7 +145,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { // DOCSTART VaultQueryExample1 - val result = vaultQuerySvc.queryBy() + val result = vaultService.queryBy() /** * Query result returns a [Vault.Page] which contains: @@ -173,7 +172,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria() // default is UNCONSUMED - val result = vaultQuerySvc.queryBy(criteria) + val result = vaultService.queryBy(criteria) assertThat(result.states).hasSize(16) assertThat(result.statesMetadata).hasSize(16) @@ -191,7 +190,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val paging = PageSpecification(DEFAULT_PAGE_NUM, 10) database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - val resultsBeforeConsume = vaultQuerySvc.queryBy(criteria, paging) + val resultsBeforeConsume = vaultService.queryBy(criteria, paging) assertThat(resultsBeforeConsume.states).hasSize(4) assertThat(resultsBeforeConsume.totalStatesAvailable).isEqualTo(4) } @@ -200,7 +199,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val consumedCriteria = VaultQueryCriteria(status = Vault.StateStatus.UNCONSUMED) - val resultsAfterConsume = vaultQuerySvc.queryBy(consumedCriteria, paging) + val resultsAfterConsume = vaultService.queryBy(consumedCriteria, paging) assertThat(resultsAfterConsume.states).hasSize(1) assertThat(resultsAfterConsume.totalStatesAvailable).isEqualTo(1) } @@ -214,7 +213,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.fillWithSomeTestDeals(listOf("123", "456", "789")) } database.transaction { - val result = vaultQuerySvc.queryBy() + val result = vaultService.queryBy() assertThat(result.states).hasSize(3) assertThat(result.statesMetadata).hasSize(3) @@ -230,7 +229,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria() // default is UNCONSUMED - val result = vaultQuerySvc.queryBy(criteria) + val result = vaultService.queryBy(criteria) assertThat(result.states).hasSize(3) assertThat(result.statesMetadata).hasSize(3) @@ -254,7 +253,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val sortAttribute = SortAttribute.Standard(Sort.CommonStateAttribute.STATE_REF) val criteria = VaultQueryCriteria() - val results = vaultQuerySvc.queryBy(criteria, Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC)))) + val results = vaultService.queryBy(criteria, Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC)))) // default StateRef sort is by index then txnId: // order by @@ -285,7 +284,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val sortBy = Sort(setOf(Sort.SortColumn(sortAttributeTxnId, Sort.Direction.ASC), Sort.SortColumn(sortAttributeIndex, Sort.Direction.ASC))) val criteria = VaultQueryCriteria() - val results = vaultQuerySvc.queryBy(criteria, sortBy) + val results = vaultService.queryBy(criteria, sortBy) results.statesMetadata.forEach { println(" ${it.ref}") @@ -309,7 +308,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { // DOCSTART VaultQueryExample2 val sortAttribute = SortAttribute.Standard(Sort.CommonStateAttribute.STATE_REF_TXN_ID) val criteria = VaultQueryCriteria(stateRefs = listOf(stateRefs.first(), stateRefs.last())) - val results = vaultQuerySvc.queryBy(criteria, Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC)))) + val results = vaultService.queryBy(criteria, Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC)))) // DOCEND VaultQueryExample2 assertThat(results.states).hasSize(2) @@ -331,7 +330,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { // default State.Status is UNCONSUMED // DOCSTART VaultQueryExample3 val criteria = VaultQueryCriteria(contractStateTypes = setOf(Cash.State::class.java, DealState::class.java)) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample3 assertThat(results.states).hasSize(6) } @@ -351,7 +350,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(5) } } @@ -367,7 +366,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val paging = PageSpecification(DEFAULT_PAGE_NUM, 10) database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - val resultsBeforeConsume = vaultQuerySvc.queryBy(criteria, paging) + val resultsBeforeConsume = vaultService.queryBy(criteria, paging) assertThat(resultsBeforeConsume.states).hasSize(4) assertThat(resultsBeforeConsume.totalStatesAvailable).isEqualTo(4) } @@ -376,7 +375,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val consumedCriteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) - val resultsAfterConsume = vaultQuerySvc.queryBy(consumedCriteria, paging) + val resultsAfterConsume = vaultService.queryBy(consumedCriteria, paging) assertThat(resultsAfterConsume.states).hasSize(3) assertThat(resultsAfterConsume.totalStatesAvailable).isEqualTo(3) } @@ -396,7 +395,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(17) } } @@ -409,7 +408,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) val paging = PageSpecification(DEFAULT_PAGE_NUM, 10) database.transaction { - val resultsBeforeConsume = vaultQuerySvc.queryBy(criteria, paging) + val resultsBeforeConsume = vaultService.queryBy(criteria, paging) assertThat(resultsBeforeConsume.states).hasSize(1) assertThat(resultsBeforeConsume.totalStatesAvailable).isEqualTo(1) } @@ -417,7 +416,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.consumeCash(50.DOLLARS, notary = DUMMY_NOTARY) // consumed 100 (spent), produced 50 (change) } database.transaction { - val resultsAfterConsume = vaultQuerySvc.queryBy(criteria, paging) + val resultsAfterConsume = vaultService.queryBy(criteria, paging) assertThat(resultsAfterConsume.states).hasSize(2) assertThat(resultsAfterConsume.totalStatesAvailable).isEqualTo(2) } @@ -433,7 +432,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample4 val criteria = VaultQueryCriteria(notary = listOf(CASH_NOTARY)) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample4 assertThat(results.states).hasSize(3) } @@ -450,7 +449,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = LinearStateQueryCriteria(participants = listOf(BIG_CORP)) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(3) } } @@ -467,7 +466,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample5 val criteria = LinearStateQueryCriteria(participants = listOf(BIG_CORP, MINI_CORP)) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample5 assertThat(results.states).hasSize(3) @@ -479,44 +478,44 @@ class VaultQueryTests : TestDependencyInjectionBase() { val (lockId1, lockId2) = database.transaction { val issuedStates = services.fillWithSomeTestCash(100.DOLLARS, notaryServices, CASH_NOTARY, 10, 10, Random(0L)).states.toList() - vaultSvc.softLockReserve(UUID.randomUUID(), NonEmptySet.of(issuedStates[1].ref, issuedStates[2].ref, issuedStates[3].ref)) + vaultService.softLockReserve(UUID.randomUUID(), NonEmptySet.of(issuedStates[1].ref, issuedStates[2].ref, issuedStates[3].ref)) val lockId1 = UUID.randomUUID() - vaultSvc.softLockReserve(lockId1, NonEmptySet.of(issuedStates[4].ref, issuedStates[5].ref)) + vaultService.softLockReserve(lockId1, NonEmptySet.of(issuedStates[4].ref, issuedStates[5].ref)) val lockId2 = UUID.randomUUID() - vaultSvc.softLockReserve(lockId2, NonEmptySet.of(issuedStates[6].ref)) + vaultService.softLockReserve(lockId2, NonEmptySet.of(issuedStates[6].ref)) Pair(lockId1, lockId2) } database.transaction { // excluding soft locked states val criteriaExclusive = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY)) - val resultsExclusive = vaultQuerySvc.queryBy(criteriaExclusive) + val resultsExclusive = vaultService.queryBy(criteriaExclusive) assertThat(resultsExclusive.states).hasSize(4) // only soft locked states val criteriaLockedOnly = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY)) - val resultsLockedOnly = vaultQuerySvc.queryBy(criteriaLockedOnly) + val resultsLockedOnly = vaultService.queryBy(criteriaLockedOnly) assertThat(resultsLockedOnly.states).hasSize(6) // soft locked states by single lock id val criteriaByLockId = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(lockId1))) - val resultsByLockId = vaultQuerySvc.queryBy(criteriaByLockId) + val resultsByLockId = vaultService.queryBy(criteriaByLockId) assertThat(resultsByLockId.states).hasSize(2) // soft locked states by multiple lock ids val criteriaByLockIds = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(lockId1, lockId2))) - val resultsByLockIds = vaultQuerySvc.queryBy(criteriaByLockIds) + val resultsByLockIds = vaultService.queryBy(criteriaByLockIds) assertThat(resultsByLockIds.states).hasSize(3) // unlocked and locked by `lockId2` val criteriaUnlockedAndByLockId = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_AND_SPECIFIED, listOf(lockId2))) - val resultsUnlockedAndByLockIds = vaultQuerySvc.queryBy(criteriaUnlockedAndByLockId) + val resultsUnlockedAndByLockIds = vaultService.queryBy(criteriaUnlockedAndByLockId) assertThat(resultsUnlockedAndByLockIds.states).hasSize(5) // missing lockId expectedEx.expect(IllegalArgumentException::class.java) expectedEx.expectMessage("Must specify one or more lockIds") val criteriaMissingLockId = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_AND_SPECIFIED)) - vaultQuerySvc.queryBy(criteriaMissingLockId) + vaultService.queryBy(criteriaMissingLockId) } } @@ -530,7 +529,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.equal(GBP.currencyCode) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -545,7 +544,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.notEqual(GBP.currencyCode) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -560,7 +559,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::pennies.greaterThan(1000L) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -575,7 +574,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::pennies.greaterThanOrEqual(1000L) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -590,7 +589,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::pennies.lessThan(1000L) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -605,7 +604,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::pennies.lessThanOrEqual(1000L) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -620,7 +619,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::pennies.between(500L, 1500L) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -636,7 +635,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val currencies = listOf(CHF.currencyCode, GBP.currencyCode) val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.`in`(currencies) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -652,7 +651,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val currencies = listOf(CHF.currencyCode, GBP.currencyCode) val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.notIn(currencies) } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -667,7 +666,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.like("%BP") } // GPB val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -682,7 +681,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.notLike("%BP") } // GPB val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -697,7 +696,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::issuerParty.isNull() } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(0) } } @@ -712,7 +711,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val logicalExpression = builder { CashSchemaV1.PersistentCashState::issuerParty.notNull() } val criteria = VaultCustomQueryCriteria(logicalExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(3) } } @@ -743,7 +742,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val avg = builder { CashSchemaV1.PersistentCashState::pennies.avg() } val avgCriteria = VaultCustomQueryCriteria(avg) - val results = vaultQuerySvc.queryBy>(sumCriteria + val results = vaultService.queryBy>(sumCriteria .and(countCriteria) .and(maxCriteria) .and(minCriteria) @@ -782,7 +781,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val avg = builder { CashSchemaV1.PersistentCashState::pennies.avg(groupByColumns = listOf(CashSchemaV1.PersistentCashState::currency)) } val avgCriteria = VaultCustomQueryCriteria(avg) - val results = vaultQuerySvc.queryBy>(sumCriteria + val results = vaultService.queryBy>(sumCriteria .and(maxCriteria) .and(minCriteria) .and(avgCriteria)) @@ -837,7 +836,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { orderBy = Sort.Direction.DESC) } - val results = vaultQuerySvc.queryBy>(VaultCustomQueryCriteria(sum)) + val results = vaultService.queryBy>(VaultCustomQueryCriteria(sum)) // DOCEND VaultQueryExample23 assertThat(results.otherResults).hasSize(12) @@ -871,15 +870,15 @@ class VaultQueryTests : TestDependencyInjectionBase() { // count fungible assets val count = builder { VaultSchemaV1.VaultStates::recordedTime.count() } val countCriteria = QueryCriteria.VaultCustomQueryCriteria(count) - val fungibleStateCount = vaultQuerySvc.queryBy>(countCriteria).otherResults.single() as Long + val fungibleStateCount = vaultService.queryBy>(countCriteria).otherResults.single() as Long assertThat(fungibleStateCount).isEqualTo(10L) // count linear states - val linearStateCount = vaultQuerySvc.queryBy(countCriteria).otherResults.single() as Long + val linearStateCount = vaultService.queryBy(countCriteria).otherResults.single() as Long assertThat(linearStateCount).isEqualTo(9L) // count deal states - val dealStateCount = vaultQuerySvc.queryBy(countCriteria).otherResults.single() as Long + val dealStateCount = vaultService.queryBy(countCriteria).otherResults.single() as Long assertThat(dealStateCount).isEqualTo(3L) } } @@ -900,15 +899,15 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // count fungible assets val countCriteria = QueryCriteria.VaultCustomQueryCriteria(count, Vault.StateStatus.ALL) - val fungibleStateCount = vaultQuerySvc.queryBy>(countCriteria).otherResults.single() as Long + val fungibleStateCount = vaultService.queryBy>(countCriteria).otherResults.single() as Long assertThat(fungibleStateCount).isEqualTo(10L) // count linear states - val linearStateCount = vaultQuerySvc.queryBy(countCriteria).otherResults.single() as Long + val linearStateCount = vaultService.queryBy(countCriteria).otherResults.single() as Long assertThat(linearStateCount).isEqualTo(9L) // count deal states - val dealStateCount = vaultQuerySvc.queryBy(countCriteria).otherResults.single() as Long + val dealStateCount = vaultService.queryBy(countCriteria).otherResults.single() as Long assertThat(dealStateCount).isEqualTo(3L) } val cashUpdates = @@ -924,30 +923,30 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // count fungible assets val countCriteriaUnconsumed = QueryCriteria.VaultCustomQueryCriteria(count, Vault.StateStatus.UNCONSUMED) - val fungibleStateCountUnconsumed = vaultQuerySvc.queryBy>(countCriteriaUnconsumed).otherResults.single() as Long + val fungibleStateCountUnconsumed = vaultService.queryBy>(countCriteriaUnconsumed).otherResults.single() as Long assertThat(fungibleStateCountUnconsumed.toInt()).isEqualTo(10 - cashUpdates.consumed.size + cashUpdates.produced.size) // count linear states - val linearStateCountUnconsumed = vaultQuerySvc.queryBy(countCriteriaUnconsumed).otherResults.single() as Long + val linearStateCountUnconsumed = vaultService.queryBy(countCriteriaUnconsumed).otherResults.single() as Long assertThat(linearStateCountUnconsumed).isEqualTo(5L) // count deal states - val dealStateCountUnconsumed = vaultQuerySvc.queryBy(countCriteriaUnconsumed).otherResults.single() as Long + val dealStateCountUnconsumed = vaultService.queryBy(countCriteriaUnconsumed).otherResults.single() as Long assertThat(dealStateCountUnconsumed).isEqualTo(2L) // CONSUMED states // count fungible assets val countCriteriaConsumed = QueryCriteria.VaultCustomQueryCriteria(count, Vault.StateStatus.CONSUMED) - val fungibleStateCountConsumed = vaultQuerySvc.queryBy>(countCriteriaConsumed).otherResults.single() as Long + val fungibleStateCountConsumed = vaultService.queryBy>(countCriteriaConsumed).otherResults.single() as Long assertThat(fungibleStateCountConsumed.toInt()).isEqualTo(cashUpdates.consumed.size) // count linear states - val linearStateCountConsumed = vaultQuerySvc.queryBy(countCriteriaConsumed).otherResults.single() as Long + val linearStateCountConsumed = vaultService.queryBy(countCriteriaConsumed).otherResults.single() as Long assertThat(linearStateCountConsumed).isEqualTo(4L) // count deal states - val dealStateCountConsumed = vaultQuerySvc.queryBy(countCriteriaConsumed).otherResults.single() as Long + val dealStateCountConsumed = vaultService.queryBy(countCriteriaConsumed).otherResults.single() as Long assertThat(dealStateCountConsumed).isEqualTo(1L) } } @@ -967,7 +966,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { QueryCriteria.TimeInstantType.RECORDED, ColumnPredicate.Between(start, end)) val criteria = VaultQueryCriteria(timeCondition = recordedBetweenExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample6 assertThat(results.states).hasSize(3) @@ -976,7 +975,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val recordedBetweenExpressionFuture = TimeCondition( QueryCriteria.TimeInstantType.RECORDED, ColumnPredicate.Between(startFuture, end)) val criteriaFuture = VaultQueryCriteria(timeCondition = recordedBetweenExpressionFuture) - assertThat(vaultQuerySvc.queryBy(criteriaFuture).states).isEmpty() + assertThat(vaultService.queryBy(criteriaFuture).states).isEmpty() } } @@ -996,7 +995,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { QueryCriteria.TimeInstantType.CONSUMED, ColumnPredicate.BinaryComparison(BinaryComparisonOperator.GREATER_THAN_OR_EQUAL, asOfDateTime)) val criteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED, timeCondition = consumedAfterExpression) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(3) } @@ -1012,7 +1011,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { // DOCSTART VaultQueryExample7 val pagingSpec = PageSpecification(DEFAULT_PAGE_NUM, 10) val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - val results = vaultQuerySvc.queryBy(criteria, paging = pagingSpec) + val results = vaultService.queryBy(criteria, paging = pagingSpec) // DOCEND VaultQueryExample7 assertThat(results.states).hasSize(10) assertThat(results.totalStatesAvailable).isEqualTo(100) @@ -1031,7 +1030,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val pagingSpec = PageSpecification(10, 10) val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - val results = vaultQuerySvc.queryBy(criteria, paging = pagingSpec) + val results = vaultService.queryBy(criteria, paging = pagingSpec) assertThat(results.states).hasSize(5) // should retrieve states 90..94 assertThat(results.totalStatesAvailable).isEqualTo(95) } @@ -1050,7 +1049,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val pagingSpec = PageSpecification(0, 10) val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - vaultQuerySvc.queryBy(criteria, paging = pagingSpec) + vaultService.queryBy(criteria, paging = pagingSpec) } } @@ -1067,7 +1066,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { @Suppress("EXPECTED_CONDITION") val pagingSpec = PageSpecification(DEFAULT_PAGE_NUM, @Suppress("INTEGER_OVERFLOW")MAX_PAGE_SIZE + 1) // overflow = -2147483648 val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - vaultQuerySvc.queryBy(criteria, paging = pagingSpec) + vaultService.queryBy(criteria, paging = pagingSpec) } } @@ -1082,7 +1081,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - vaultQuerySvc.queryBy(criteria) + vaultService.queryBy(criteria) } } @@ -1098,7 +1097,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val sortCol2 = Sort.SortColumn(SortAttribute.Standard(Sort.VaultStateAttribute.STATE_STATUS), Sort.Direction.ASC) val sortCol3 = Sort.SortColumn(SortAttribute.Standard(Sort.VaultStateAttribute.CONSUMED_TIME), Sort.Direction.DESC) val sorting = Sort(setOf(sortCol1, sortCol2, sortCol3)) - val result = vaultQuerySvc.queryBy(VaultQueryCriteria(status = Vault.StateStatus.ALL), sorting = sorting) + val result = vaultService.queryBy(VaultQueryCriteria(status = Vault.StateStatus.ALL), sorting = sorting) val states = result.states val metadata = result.statesMetadata @@ -1123,7 +1122,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.fillWithSomeTestLinearStates(10) } database.transaction { - val results = vaultQuerySvc.queryBy>() + val results = vaultService.queryBy>() assertThat(results.states).hasSize(4) } } @@ -1142,7 +1141,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) assertThat(results.states).hasSize(2) } } @@ -1154,7 +1153,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.fillWithSomeTestLinearStates(10) } database.transaction { - val results = vaultQuerySvc.queryBy() + val results = vaultService.queryBy() assertThat(results.states).hasSize(3) } } @@ -1169,7 +1168,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } // should now have x2 CONSUMED + x2 UNCONSUMED (one spent + one change) database.transaction { - val results = vaultQuerySvc.queryBy(FungibleAssetQueryCriteria()) + val results = vaultService.queryBy(FungibleAssetQueryCriteria()) assertThat(results.statesMetadata).hasSize(2) assertThat(results.states).hasSize(2) } @@ -1192,7 +1191,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -1205,7 +1204,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.fillWithSomeTestDeals(listOf("123", "456", "789")) } database.transaction { - val results = vaultQuerySvc.queryBy() + val results = vaultService.queryBy() assertThat(results.states).hasSize(13) } } @@ -1224,7 +1223,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(3) } } @@ -1241,7 +1240,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { // DOCSTART VaultQueryExample8 val linearIds = issuedStates.states.map { it.state.data.linearId }.toList() val criteria = LinearStateQueryCriteria(linearId = listOf(linearIds.first(), linearIds.last())) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample8 assertThat(results.states).hasSize(2) } @@ -1259,7 +1258,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val linearIds = listOf(linearState1.states.first().state.data.linearId, linearState3.states.first().state.data.linearId) val criteria = LinearStateQueryCriteria(linearId = linearIds) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -1276,7 +1275,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val externalIds = listOf(linearState1.states.first().state.data.linearId.externalId!!, linearState3.states.first().state.data.linearId.externalId!!) val criteria = LinearStateQueryCriteria(externalId = externalIds) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(2) } } @@ -1297,7 +1296,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { // DOCSTART VaultQueryExample9 val linearStateCriteria = LinearStateQueryCriteria(linearId = listOf(linearId), status = Vault.StateStatus.ALL) val vaultCriteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - val results = vaultQuerySvc.queryBy(linearStateCriteria and vaultCriteria) + val results = vaultService.queryBy(linearStateCriteria and vaultCriteria) // DOCEND VaultQueryExample9 assertThat(results.states).hasSize(4) } @@ -1320,7 +1319,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val vaultCriteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) val sorting = Sort(setOf(Sort.SortColumn(SortAttribute.Standard(Sort.LinearStateAttribute.UUID), Sort.Direction.DESC))) - val results = vaultQuerySvc.queryBy(linearStateCriteria.and(vaultCriteria), sorting = sorting) + val results = vaultService.queryBy(linearStateCriteria.and(vaultCriteria), sorting = sorting) results.states.forEach { println("${it.state.data.linearId.id}") } assertThat(results.states).hasSize(8) } @@ -1337,7 +1336,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val vaultCriteria = VaultQueryCriteria() val sorting = Sort(setOf(Sort.SortColumn(SortAttribute.Standard(Sort.LinearStateAttribute.EXTERNAL_ID), Sort.Direction.DESC))) - val results = vaultQuerySvc.queryBy((vaultCriteria), sorting = sorting) + val results = vaultService.queryBy((vaultCriteria), sorting = sorting) results.states.forEach { println(it.state.data.linearString) } assertThat(results.states).hasSize(6) } @@ -1358,7 +1357,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val sorting = Sort(setOf(Sort.SortColumn(SortAttribute.Standard(Sort.LinearStateAttribute.EXTERNAL_ID), Sort.Direction.DESC))) - val results = vaultQuerySvc.queryBy(compositeCriteria, sorting = sorting) + val results = vaultService.queryBy(compositeCriteria, sorting = sorting) assertThat(results.statesMetadata).hasSize(4) assertThat(results.states).hasSize(4) } @@ -1375,7 +1374,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val vaultCriteria = VaultQueryCriteria() val sorting = Sort(setOf(Sort.SortColumn(SortAttribute.Custom(DummyLinearStateSchemaV1.PersistentDummyLinearState::class.java, "linearString"), Sort.Direction.DESC))) - val results = vaultQuerySvc.queryBy((vaultCriteria), sorting = sorting) + val results = vaultService.queryBy((vaultCriteria), sorting = sorting) results.states.forEach { println(it.state.data.linearString) } assertThat(results.states).hasSize(6) } @@ -1397,7 +1396,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val linearStateCriteria = LinearStateQueryCriteria(linearId = txns.states.map { it.state.data.linearId }, status = Vault.StateStatus.CONSUMED) val vaultCriteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) val sorting = Sort(setOf(Sort.SortColumn(SortAttribute.Standard(Sort.LinearStateAttribute.UUID), Sort.Direction.DESC))) - val results = vaultQuerySvc.queryBy(linearStateCriteria.and(vaultCriteria), sorting = sorting) + val results = vaultService.queryBy(linearStateCriteria.and(vaultCriteria), sorting = sorting) assertThat(results.states).hasSize(3) } } @@ -1411,7 +1410,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.fillWithSomeTestDeals(listOf("123", "456", "789")) } database.transaction { - val results = vaultQuerySvc.queryBy() + val results = vaultService.queryBy() assertThat(results.states).hasSize(3) } } @@ -1424,7 +1423,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample10 val criteria = LinearStateQueryCriteria(externalId = listOf("456", "789")) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample10 assertThat(results.states).hasSize(2) @@ -1439,11 +1438,11 @@ class VaultQueryTests : TestDependencyInjectionBase() { services.fillWithSomeTestDeals(listOf("123", "789")) } database.transaction { - val all = vaultQuerySvc.queryBy() + val all = vaultService.queryBy() all.states.forEach { println(it.state) } val criteria = LinearStateQueryCriteria(externalId = listOf("456")) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) assertThat(results.states).hasSize(1) } } @@ -1459,7 +1458,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample11 val criteria = LinearStateQueryCriteria(participants = parties) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample11 assertThat(results.states).hasSize(1) @@ -1481,7 +1480,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val criteria = FungibleAssetQueryCriteria(issuer = listOf(BOC), issuerRef = listOf(BOC.ref(1).reference, BOC.ref(2).reference)) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) assertThat(results.states).hasSize(2) } } @@ -1509,7 +1508,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = FungibleAssetQueryCriteria(issuer = listOf(gbpCashIssuer.party, usdCashIssuer.party)) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) assertThat(results.states).hasSize(2) } } @@ -1523,7 +1522,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val criteria = FungibleAssetQueryCriteria(owner = listOf(MEGA_CORP)) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) assertThat(results.states).hasSize(1) // can only be 1 owner of a node (MEGA_CORP in this MockServices setup) } } @@ -1540,7 +1539,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample5.2 val criteria = FungibleAssetQueryCriteria(owner = listOf(MEGA_CORP, BOC)) - val results = vaultQuerySvc.queryBy(criteria) + val results = vaultService.queryBy(criteria) // DOCEND VaultQueryExample5.2 assertThat(results.states).hasSize(2) // can only be 1 owner of a node (MEGA_CORP in this MockServices setup) @@ -1560,7 +1559,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { // DOCSTART VaultQueryExample12 val ccyIndex = builder { CashSchemaV1.PersistentCashState::currency.equal(USD.currencyCode) } val criteria = VaultCustomQueryCriteria(ccyIndex) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) // DOCEND VaultQueryExample12 assertThat(results.states).hasSize(3) @@ -1580,7 +1579,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val ccyIndex = builder { CashSchemaV1.PersistentCashState::currency.equal(USD.currencyCode) } val ccyCriteria = VaultCustomQueryCriteria(ccyIndex) - val results = vaultQuerySvc.queryBy>(sumCriteria.and(ccyCriteria)) + val results = vaultService.queryBy>(sumCriteria.and(ccyCriteria)) assertThat(results.otherResults).hasSize(2) assertThat(results.otherResults[0]).isEqualTo(30000L) @@ -1601,7 +1600,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { val ccyIndex = builder { CashSchemaV1.PersistentCashState::pennies.sum(groupByColumns = listOf(CashSchemaV1.PersistentCashState::currency)) } val criteria = VaultCustomQueryCriteria(ccyIndex) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) assertThat(results.otherResults).hasSize(6) assertThat(results.otherResults[0]).isEqualTo(110000L) @@ -1624,7 +1623,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample13 val fungibleAssetCriteria = FungibleAssetQueryCriteria(quantity = builder { greaterThan(2500L) }) - val results = vaultQuerySvc.queryBy(fungibleAssetCriteria) + val results = vaultService.queryBy(fungibleAssetCriteria) // DOCEND VaultQueryExample13 assertThat(results.states).hasSize(4) // POUNDS, SWISS_FRANCS @@ -1642,7 +1641,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { database.transaction { // DOCSTART VaultQueryExample14 val criteria = FungibleAssetQueryCriteria(issuer = listOf(BOC)) - val results = vaultQuerySvc.queryBy>(criteria) + val results = vaultService.queryBy>(criteria) // DOCEND VaultQueryExample14 assertThat(results.states).hasSize(1) @@ -1661,7 +1660,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val ccyIndex = builder { CashSchemaV1.PersistentCashState::currency.equal(GBP.currencyCode) } val customCriteria = VaultCustomQueryCriteria(ccyIndex) val fungibleAssetCriteria = FungibleAssetQueryCriteria(quantity = builder { greaterThan(5000L) }) - val results = vaultQuerySvc.queryBy(fungibleAssetCriteria.and(customCriteria)) + val results = vaultService.queryBy(fungibleAssetCriteria.and(customCriteria)) assertThat(results.states).hasSize(1) // POUNDS > 50 } @@ -1700,7 +1699,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val ccyIndex = builder { CommercialPaperSchemaV1.PersistentCommercialPaperState::currency.equal(USD.currencyCode) } val criteria1 = QueryCriteria.VaultCustomQueryCriteria(ccyIndex) - val result = vaultQuerySvc.queryBy(criteria1) + val result = vaultService.queryBy(criteria1) Assertions.assertThat(result.states).hasSize(1) Assertions.assertThat(result.statesMetadata).hasSize(1) @@ -1746,7 +1745,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val criteria2 = QueryCriteria.VaultCustomQueryCriteria(maturityIndex) val criteria3 = QueryCriteria.VaultCustomQueryCriteria(faceValueIndex) - vaultQuerySvc.queryBy(criteria1.and(criteria3).and(criteria2)) + vaultService.queryBy(criteria1.and(criteria3).and(criteria2)) } Assertions.assertThat(result.states).hasSize(1) Assertions.assertThat(result.statesMetadata).hasSize(1) @@ -1766,7 +1765,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val criteria = VaultCustomQueryCriteria(logicalExpression) assertThatThrownBy { - vaultQuerySvc.queryBy(criteria) + vaultService.queryBy(criteria) }.isInstanceOf(VaultQueryException::class.java).hasMessageContaining("Please register the entity") } } @@ -1794,7 +1793,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val customCriteria2 = VaultCustomQueryCriteria(quantityIndex) val criteria = generalCriteria.and(customCriteria1.and(customCriteria2)) - vaultQuerySvc.queryBy(criteria) + vaultService.queryBy(criteria) } // DOCEND VaultQueryExample20 @@ -1819,7 +1818,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val recordedBetweenExpression = TimeCondition(TimeInstantType.RECORDED, builder { between(start, end) }) val basicCriteria = VaultQueryCriteria(timeCondition = recordedBetweenExpression) - val results = vaultQuerySvc.queryBy(basicCriteria) + val results = vaultService.queryBy(basicCriteria) assertThat(results.states).hasSize(1) } @@ -1837,7 +1836,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val externalIdCondition = builder { VaultSchemaV1.VaultLinearStates::externalId.equal("TEST2") } val externalIdCustomCriteria = VaultCustomQueryCriteria(externalIdCondition) - val results = vaultQuerySvc.queryBy(externalIdCustomCriteria) + val results = vaultService.queryBy(externalIdCustomCriteria) assertThat(results.states).hasSize(1) } @@ -1866,7 +1865,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val basicCriteria = VaultQueryCriteria(timeCondition = recordedBetweenExpression) val criteria = basicCriteria.and(customCriteria) - vaultQuerySvc.queryBy(criteria) + vaultService.queryBy(criteria) } assertThat(results.states).hasSize(1) @@ -1894,7 +1893,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val uuidCustomCriteria = VaultCustomQueryCriteria(uuidCondition) val criteria = externalIdCustomCriteria or uuidCustomCriteria - vaultQuerySvc.queryBy(criteria) + vaultService.queryBy(criteria) } assertThat(results.statesMetadata).hasSize(2) assertThat(results.states).hasSize(2) @@ -1911,7 +1910,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val linearStateCriteria = LinearStateQueryCriteria(participants = listOf(ALICE)) - val results = vaultQuerySvc.queryBy(linearStateCriteria) + val results = vaultService.queryBy(linearStateCriteria) assertThat(results.states).hasSize(1) assertThat(results.states[0].state.data.linearId.externalId).isEqualTo("TEST1") @@ -1931,7 +1930,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { } database.transaction { val linearStateCriteria = LinearStateQueryCriteria(participants = listOf(ALICE, BOB, CHARLIE)) - val results = vaultQuerySvc.queryBy(linearStateCriteria) + val results = vaultService.queryBy(linearStateCriteria) assertThat(results.states).hasSize(1) assertThat(results.states[0].state.data.linearId.externalId).isEqualTo("TEST1") @@ -1952,7 +1951,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val externalIdCondition = VaultSchemaV1.VaultLinearStates::externalId.isNull() val externalIdCustomCriteria = VaultCustomQueryCriteria(externalIdCondition) - vaultQuerySvc.queryBy(externalIdCustomCriteria) + vaultService.queryBy(externalIdCustomCriteria) } assertThat(results.states).hasSize(1) } @@ -1972,7 +1971,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val externalIdCondition = VaultSchemaV1.VaultLinearStates::externalId.notNull() val externalIdCustomCriteria = VaultCustomQueryCriteria(externalIdCondition) - vaultQuerySvc.queryBy(externalIdCustomCriteria) + vaultService.queryBy(externalIdCustomCriteria) } assertThat(results.states).hasSize(2) } @@ -2001,7 +2000,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val sorter = Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC))) // Execute query - val results = services.vaultQueryService.queryBy>(baseCriteria and enrichedCriteria, sorter).states + val results = services.vaultService.queryBy>(baseCriteria and enrichedCriteria, sorter).states assertThat(results).hasSize(4) } } @@ -2015,7 +2014,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val updates = database.transaction { // DOCSTART VaultQueryExample15 - vaultQuerySvc.trackBy().updates // UNCONSUMED default + vaultService.trackBy().updates // UNCONSUMED default // DOCEND VaultQueryExample15 } val (linearStates, dealStates) = @@ -2057,7 +2056,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val updates = database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.CONSUMED) - vaultQuerySvc.trackBy(criteria).updates + vaultService.trackBy(criteria).updates } val (linearStates, dealStates) = database.transaction { @@ -2103,7 +2102,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val updates = database.transaction { val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL) - vaultQuerySvc.trackBy(criteria).updates + vaultService.trackBy(criteria).updates } val (linearStates, dealStates) = database.transaction { @@ -2158,7 +2157,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val updates = database.transaction { // DOCSTART VaultQueryExample16 - val (snapshot, updates) = vaultQuerySvc.trackBy() + val (snapshot, updates) = vaultService.trackBy() // DOCEND VaultQueryExample16 assertThat(snapshot.states).hasSize(0) updates @@ -2207,7 +2206,7 @@ class VaultQueryTests : TestDependencyInjectionBase() { val updates = database.transaction { // DOCSTART VaultQueryExample17 - val (snapshot, updates) = vaultQuerySvc.trackBy() + val (snapshot, updates) = vaultService.trackBy() // DOCEND VaultQueryExample17 assertThat(snapshot.states).hasSize(0) updates diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt index 9c969f0950..a1450132a5 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultWithCashTest.kt @@ -1,11 +1,10 @@ -package net.corda.node.services.vault +package net.corda.node.services.vaultService import net.corda.core.contracts.ContractState import net.corda.core.contracts.LinearState import net.corda.core.contracts.UniqueIdentifier import net.corda.core.identity.AnonymousParty import net.corda.core.node.services.Vault -import net.corda.core.node.services.VaultQueryService import net.corda.core.node.services.VaultService import net.corda.core.node.services.queryBy import net.corda.core.node.services.vault.QueryCriteria @@ -37,8 +36,7 @@ import kotlin.test.assertEquals class VaultWithCashTest : TestDependencyInjectionBase() { lateinit var services: MockServices lateinit var issuerServices: MockServices - val vault: VaultService get() = services.vaultService - val vaultQuery: VaultQueryService get() = services.vaultQueryService + val vaultService: VaultService get() = services.vaultService lateinit var database: CordaPersistence lateinit var notaryServices: MockServices @@ -69,7 +67,7 @@ class VaultWithCashTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.DOLLARS, issuerServices, DUMMY_NOTARY, 3, 3, Random(0L), issuedBy = DUMMY_CASH_ISSUER) } database.transaction { - val w = vaultQuery.queryBy().states + val w = vaultService.queryBy().states assertEquals(3, w.size) val state = w[0].state.data @@ -141,8 +139,8 @@ class VaultWithCashTest : TestDependencyInjectionBase() { println("Cash balance: ${services.getCashBalance(USD)}") } database.transaction { - assertThat(vaultQuery.queryBy().states).hasSize(10) - assertThat(vaultQuery.queryBy(criteriaLocked).states).hasSize(0) + assertThat(vaultService.queryBy().states).hasSize(10) + assertThat(vaultService.queryBy(criteriaLocked).states).hasSize(0) } val backgroundExecutor = Executors.newFixedThreadPool(2) @@ -157,9 +155,9 @@ class VaultWithCashTest : TestDependencyInjectionBase() { val ptxn1 = notaryServices.signInitialTransaction(txn1Builder) val txn1 = services.addSignature(ptxn1, freshKey) println("txn1: ${txn1.id} spent ${((txn1.tx.outputs[0].data) as Cash.State).amount}") - val unconsumedStates1 = vaultQuery.queryBy() - val consumedStates1 = vaultQuery.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)) - val lockedStates1 = vaultQuery.queryBy(criteriaLocked).states + val unconsumedStates1 = vaultService.queryBy() + val consumedStates1 = vaultService.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)) + val lockedStates1 = vaultService.queryBy(criteriaLocked).states println("""txn1 states: UNCONSUMED: ${unconsumedStates1.totalStatesAvailable} : $unconsumedStates1, CONSUMED: ${consumedStates1.totalStatesAvailable} : $consumedStates1, @@ -167,9 +165,9 @@ class VaultWithCashTest : TestDependencyInjectionBase() { """) services.recordTransactions(txn1) println("txn1: Cash balance: ${services.getCashBalance(USD)}") - val unconsumedStates2 = vaultQuery.queryBy() - val consumedStates2 = vaultQuery.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)) - val lockedStates2 = vaultQuery.queryBy(criteriaLocked).states + val unconsumedStates2 = vaultService.queryBy() + val consumedStates2 = vaultService.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)) + val lockedStates2 = vaultService.queryBy(criteriaLocked).states println("""txn1 states: UNCONSUMED: ${unconsumedStates2.totalStatesAvailable} : $unconsumedStates2, CONSUMED: ${consumedStates2.totalStatesAvailable} : $consumedStates2, @@ -193,9 +191,9 @@ class VaultWithCashTest : TestDependencyInjectionBase() { val ptxn2 = notaryServices.signInitialTransaction(txn2Builder) val txn2 = services.addSignature(ptxn2, freshKey) println("txn2: ${txn2.id} spent ${((txn2.tx.outputs[0].data) as Cash.State).amount}") - val unconsumedStates1 = vaultQuery.queryBy() - val consumedStates1 = vaultQuery.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)) - val lockedStates1 = vaultQuery.queryBy(criteriaLocked).states + val unconsumedStates1 = vaultService.queryBy() + val consumedStates1 = vaultService.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)) + val lockedStates1 = vaultService.queryBy(criteriaLocked).states println("""txn2 states: UNCONSUMED: ${unconsumedStates1.totalStatesAvailable} : $unconsumedStates1, CONSUMED: ${consumedStates1.totalStatesAvailable} : $consumedStates1, @@ -203,9 +201,9 @@ class VaultWithCashTest : TestDependencyInjectionBase() { """) services.recordTransactions(txn2) println("txn2: Cash balance: ${services.getCashBalance(USD)}") - val unconsumedStates2 = vaultQuery.queryBy() - val consumedStates2 = vaultQuery.queryBy() - val lockedStates2 = vaultQuery.queryBy(criteriaLocked).states + val unconsumedStates2 = vaultService.queryBy() + val consumedStates2 = vaultService.queryBy() + val lockedStates2 = vaultService.queryBy(criteriaLocked).states println("""txn2 states: UNCONSUMED: ${unconsumedStates2.totalStatesAvailable} : $unconsumedStates2, CONSUMED: ${consumedStates2.totalStatesAvailable} : $consumedStates2, @@ -269,7 +267,7 @@ class VaultWithCashTest : TestDependencyInjectionBase() { dummyIssue } database.transaction { - assertThat(vaultQuery.queryBy().states).hasSize(1) + assertThat(vaultService.queryBy().states).hasSize(1) // Move the same state val dummyMoveBuilder = TransactionBuilder(notary = DUMMY_NOTARY) @@ -284,7 +282,7 @@ class VaultWithCashTest : TestDependencyInjectionBase() { services.recordTransactions(dummyMove) } database.transaction { - assertThat(vaultQuery.queryBy().states).hasSize(1) + assertThat(vaultService.queryBy().states).hasSize(1) } } @@ -298,14 +296,14 @@ class VaultWithCashTest : TestDependencyInjectionBase() { services.fillWithSomeTestCash(100.POUNDS, issuerServices, DUMMY_NOTARY, 1, 1, Random(0L)) } database.transaction { - val cash = vaultQuery.queryBy().states + val cash = vaultService.queryBy().states cash.forEach { println(it.state.data.amount) } } database.transaction { services.fillWithSomeTestDeals(listOf("123", "456", "789")) } database.transaction { - val deals = vaultQuery.queryBy().states + val deals = vaultService.queryBy().states deals.forEach { println(it.state.data.linearId.externalId!!) } } @@ -318,10 +316,10 @@ class VaultWithCashTest : TestDependencyInjectionBase() { services.recordTransactions(spendTX) } database.transaction { - val consumedStates = vaultQuery.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states + val consumedStates = vaultService.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states assertEquals(3, consumedStates.count()) - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertEquals(7, unconsumedStates.count()) } } @@ -336,13 +334,13 @@ class VaultWithCashTest : TestDependencyInjectionBase() { } val deals = database.transaction { - vaultQuery.queryBy().states + vaultService.queryBy().states } database.transaction { services.fillWithSomeTestLinearStates(3) } database.transaction { - val linearStates = vaultQuery.queryBy().states + val linearStates = vaultService.queryBy().states linearStates.forEach { println(it.state.data.linearId) } // Create a txn consuming different contract types @@ -359,10 +357,10 @@ class VaultWithCashTest : TestDependencyInjectionBase() { services.recordTransactions(dummyMove) } database.transaction { - val consumedStates = vaultQuery.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states + val consumedStates = vaultService.queryBy(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states assertEquals(2, consumedStates.count()) - val unconsumedStates = vaultQuery.queryBy().states + val unconsumedStates = vaultService.queryBy().states assertEquals(6, unconsumedStates.count()) } } 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 687ccbe857..af7aae480e 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 @@ -97,7 +97,7 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten val swaps = node1.database.transaction { - node1.services.vaultQueryService.queryBy().states + node1.services.vaultService.queryBy().states } val theDealRef: StateAndRef = swaps.single() diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmFlow.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmFlow.kt index 56c7001682..eb1198a881 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmFlow.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmFlow.kt @@ -80,7 +80,7 @@ object SimmFlow { notary = serviceHub.networkMapCache.notaryIdentities.first() // TODO We should pass the notary as a parameter to the flow, not leave it to random choice. val criteria = LinearStateQueryCriteria(participants = listOf(otherParty)) - val trades = serviceHub.vaultQueryService.queryBy(criteria).states + val trades = serviceHub.vaultService.queryBy(criteria).states val portfolio = Portfolio(trades, valuationDate) otherPartySession = initiateFlow(otherParty) @@ -89,7 +89,7 @@ object SimmFlow { } else { updatePortfolio(portfolio, existing) } - val portfolioStateRef = serviceHub.vaultQueryService.queryBy(criteria).states.first() + val portfolioStateRef = serviceHub.vaultService.queryBy(criteria).states.first() val state = updateValuation(portfolioStateRef) logger.info("SimmFlow done") @@ -126,7 +126,7 @@ object SimmFlow { private fun updateValuation(stateRef: StateAndRef): RevisionedState { logger.info("Agreeing valuations") val state = stateRef.state.data - val portfolio = serviceHub.vaultQueryService.queryBy(VaultQueryCriteria(stateRefs = state.portfolio)).states.toPortfolio() + val portfolio = serviceHub.vaultService.queryBy(VaultQueryCriteria(stateRefs = state.portfolio)).states.toPortfolio() val valuer = serviceHub.identityService.wellKnownPartyFromAnonymous(state.valuer) require(valuer != null) { "Valuer party must be known to this node" } @@ -211,7 +211,7 @@ object SimmFlow { @Suspendable override fun call() { val criteria = LinearStateQueryCriteria(participants = listOf(replyToSession.counterparty)) - val trades = serviceHub.vaultQueryService.queryBy(criteria).states + val trades = serviceHub.vaultService.queryBy(criteria).states val portfolio = Portfolio(trades) logger.info("SimmFlow receiver started") offer = replyToSession.receive().unwrap { it } @@ -220,7 +220,7 @@ object SimmFlow { } else { updatePortfolio(portfolio) } - val portfolioStateRef = serviceHub.vaultQueryService.queryBy(criteria).states.first() + val portfolioStateRef = serviceHub.vaultService.queryBy(criteria).states.first() updateValuation(portfolioStateRef) } @@ -327,7 +327,7 @@ object SimmFlow { @Suspendable private fun updateValuation(stateRef: StateAndRef) { - val portfolio = serviceHub.vaultQueryService.queryBy(VaultQueryCriteria(stateRefs = stateRef.state.data.portfolio)).states.toPortfolio() + val portfolio = serviceHub.vaultService.queryBy(VaultQueryCriteria(stateRefs = stateRef.state.data.portfolio)).states.toPortfolio() val valuer = serviceHub.identityService.wellKnownPartyFromAnonymous(stateRef.state.data.valuer) ?: throw IllegalStateException("Unknown valuer party ${stateRef.state.data.valuer}") val valuation = agreeValuation(portfolio, offer.valuationDate, valuer) subFlow(object : StateRevisionFlow.Receiver(replyToSession) { diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmRevaluation.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmRevaluation.kt index 8f607163ef..599e9d4345 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmRevaluation.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/SimmRevaluation.kt @@ -20,7 +20,7 @@ object SimmRevaluation { class Initiator(private val curStateRef: StateRef, private val valuationDate: LocalDate) : FlowLogic() { @Suspendable override fun call() { - val stateAndRef = serviceHub.vaultQueryService.queryBy(VaultQueryCriteria(stateRefs = listOf(curStateRef))).states.single() + val stateAndRef = serviceHub.vaultService.queryBy(VaultQueryCriteria(stateRefs = listOf(curStateRef))).states.single() val curState = stateAndRef.state.data if (ourIdentity == curState.participants[0]) { val otherParty = serviceHub.identityService.wellKnownPartyFromAnonymous(curState.participants[1]) diff --git a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/SellerFlow.kt b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/SellerFlow.kt index 890885227f..2a08170192 100644 --- a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/SellerFlow.kt +++ b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/SellerFlow.kt @@ -40,7 +40,7 @@ class SellerFlow(private val otherParty: Party, progressTracker.currentStep = SELF_ISSUING val cpOwner = serviceHub.keyManagementService.freshKeyAndCert(ourIdentityAndCert, false) - val commercialPaper = serviceHub.vaultQueryService.queryBy(CommercialPaper.State::class.java).states.first() + val commercialPaper = serviceHub.vaultService.queryBy(CommercialPaper.State::class.java).states.first() progressTracker.currentStep = TRADING diff --git a/testing/node-driver/src/main/kotlin/net/corda/node/testing/MockServiceHubInternal.kt b/testing/node-driver/src/main/kotlin/net/corda/node/testing/MockServiceHubInternal.kt index b29cd52654..e3e54de6d4 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/node/testing/MockServiceHubInternal.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/node/testing/MockServiceHubInternal.kt @@ -35,7 +35,6 @@ open class MockServiceHubInternal( override val database: CordaPersistence, override val configuration: NodeConfiguration, val customVault: VaultService? = null, - val customVaultQuery: VaultQueryService? = null, val keyManagement: KeyManagementService? = null, val network: MessagingService? = null, val identity: IdentityService? = MOCK_IDENTITY_SERVICE, @@ -50,8 +49,6 @@ open class MockServiceHubInternal( val customTransactionVerifierService: TransactionVerifierService? = InMemoryTransactionVerifierService(2), override val cordappProvider: CordappProvider = CordappProviderImpl(CordappLoader.createDefault(Paths.get("."))).start(attachments) ) : ServiceHubInternal { - override val vaultQueryService: VaultQueryService - get() = customVaultQuery ?: throw UnsupportedOperationException() override val transactionVerifierService: TransactionVerifierService get() = customTransactionVerifierService ?: throw UnsupportedOperationException() override val vaultService: VaultService 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 73dc1f883d..7338a6c68f 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 @@ -24,7 +24,6 @@ import net.corda.node.services.persistence.InMemoryStateMachineRecordedTransacti import net.corda.node.services.schema.HibernateObserver import net.corda.node.services.schema.NodeSchemaService import net.corda.node.services.transactions.InMemoryTransactionVerifierService -import net.corda.node.services.vault.HibernateVaultQueryImpl import net.corda.node.services.vault.NodeVaultService import net.corda.node.utilities.CordaPersistence import net.corda.node.utilities.configureDatabase @@ -117,8 +116,6 @@ open class MockServices(cordappPackages: List = emptyList(), vararg val (vaultService as NodeVaultService).notifyAll(txs.map { it.tx }) } - override val vaultQueryService: VaultQueryService = HibernateVaultQueryImpl(database.hibernateConfig, vaultService) - override fun jdbcSession(): Connection = database.createSession() } } @@ -149,7 +146,6 @@ open class MockServices(cordappPackages: List = emptyList(), vararg val override val vaultService: VaultService get() = throw UnsupportedOperationException() override val contractUpgradeService: ContractUpgradeService get() = throw UnsupportedOperationException() - override val vaultQueryService: VaultQueryService get() = throw UnsupportedOperationException() override val networkMapCache: NetworkMapCache get() = throw UnsupportedOperationException() override val clock: Clock get() = Clock.systemUTC() override val myInfo: NodeInfo get() { @@ -163,7 +159,7 @@ open class MockServices(cordappPackages: List = emptyList(), vararg val lateinit var hibernatePersister: HibernateObserver fun makeVaultService(hibernateConfig: HibernateConfiguration = HibernateConfiguration( { NodeSchemaService() }, makeTestDatabaseProperties(), { identityService })): VaultService { - val vaultService = NodeVaultService(this) + val vaultService = NodeVaultService(this, hibernateConfig) hibernatePersister = HibernateObserver(vaultService.rawUpdates, hibernateConfig) return vaultService }