Unification of VaultQuery And VaultService APIs (into single VaultService interface) to simplify node bootstrapping and usability. (#1677)

This commit is contained in:
josecoll 2017-09-27 13:33:23 +01:00 committed by GitHub
parent 06cf741c0d
commit 241f843555
34 changed files with 589 additions and 692 deletions

View File

@ -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

View File

@ -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

View File

@ -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 <StateAndRef> (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 <T : ContractState> _queryBy(criteria: QueryCriteria,
paging: PageSpecification,
sorting: Sort,
contractStateType: Class<out T>): Vault.Page<T>
/**
* 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 <T : ContractState> _trackBy(criteria: QueryCriteria,
paging: PageSpecification,
sorting: Sort,
contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>>
// DOCEND VaultQueryAPI
// Note: cannot apply @JvmOverloads to interfaces nor interface implementations
// Java Helpers
fun <T : ContractState> queryBy(contractStateType: Class<out T>): Vault.Page<T> {
return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification): Vault.Page<T> {
return _queryBy(criteria, paging, Sort(emptySet()), contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), sorting, contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, paging, sorting, contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, Sort(emptySet()), contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), sorting, contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, sorting, contractStateType)
}
}
inline fun <reified T : ContractState> VaultQueryService.queryBy(): Vault.Page<T> {
return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.queryBy(criteria: QueryCriteria): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.queryBy(criteria: QueryCriteria, paging: PageSpecification): Vault.Page<T> {
return _queryBy(criteria, paging, Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.queryBy(criteria: QueryCriteria, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), sorting, T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, paging, sorting, T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.trackBy(): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.trackBy(criteria: QueryCriteria): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.trackBy(criteria: QueryCriteria, paging: PageSpecification): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.trackBy(criteria: QueryCriteria, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), sorting, T::class.java)
}
inline fun <reified T : ContractState> VaultQueryService.trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, sorting, T::class.java)
}
class VaultQueryException(description: String) : FlowException(description)

View File

@ -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<Vault.Update<ContractState>>
/**
* Enable creation of observables of updates.
*/
val updatesPublisher: PublishSubject<Vault.Update<ContractState>>
/**
* 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<U>,
contractStateType: Class<out T>): List<StateAndRef<T>>
// 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 <StateAndRef> (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 <T : ContractState> _queryBy(criteria: QueryCriteria,
paging: PageSpecification,
sorting: Sort,
contractStateType: Class<out T>): Vault.Page<T>
/**
* 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 <T : ContractState> _trackBy(criteria: QueryCriteria,
paging: PageSpecification,
sorting: Sort,
contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>>
// DOCEND VaultQueryAPI
// Note: cannot apply @JvmOverloads to interfaces nor interface implementations
// Java Helpers
fun <T : ContractState> queryBy(contractStateType: Class<out T>): Vault.Page<T> {
return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification): Vault.Page<T> {
return _queryBy(criteria, paging, Sort(emptySet()), contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), sorting, contractStateType)
}
fun <T : ContractState> queryBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, paging, sorting, contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), Sort(emptySet()), contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, Sort(emptySet()), contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), sorting, contractStateType)
}
fun <T : ContractState> trackBy(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, sorting, contractStateType)
}
}
inline fun <reified T : ContractState> VaultService.queryBy(): Vault.Page<T> {
return _queryBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultService.queryBy(criteria: QueryCriteria): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultService.queryBy(criteria: QueryCriteria, paging: PageSpecification): Vault.Page<T> {
return _queryBy(criteria, paging, Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultService.queryBy(criteria: QueryCriteria, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, PageSpecification(), sorting, T::class.java)
}
inline fun <reified T : ContractState> VaultService.queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): Vault.Page<T> {
return _queryBy(criteria, paging, sorting, T::class.java)
}
inline fun <reified T : ContractState> VaultService.trackBy(): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(QueryCriteria.VaultQueryCriteria(), PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultService.trackBy(criteria: QueryCriteria): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultService.trackBy(criteria: QueryCriteria, paging: PageSpecification): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, paging, Sort(emptySet()), T::class.java)
}
inline fun <reified T : ContractState> VaultService.trackBy(criteria: QueryCriteria, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return _trackBy(criteria, PageSpecification(), sorting, T::class.java)
}
inline fun <reified T : ContractState> VaultService.trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort): DataFeed<Vault.Page<T>, Vault.Update<T>> {
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"

View File

@ -219,14 +219,14 @@ class ContractUpgradeFlowTest {
val stx = result.getOrThrow().stx
val anonymisedRecipient = result.get().recipient!!
val stateAndRef = stx.tx.outRef<Cash.State>(0)
val baseState = a.database.transaction { a.services.vaultQueryService.queryBy<ContractState>().states.single() }
val baseState = a.database.transaction { a.services.vaultService.queryBy<ContractState>().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<ContractState>().states.single() }
val firstState = a.database.transaction { a.services.vaultService.queryBy<ContractState>().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<Collection<AbstractParty>>(listOf(anonymisedRecipient), (firstState.state.data as CashV2.State).owners, "Upgraded cash belongs to the right owner.")

View File

@ -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 <http://projects.spring.io/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

View File

@ -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<DummyState> results = getServiceHub().getVaultQueryService().queryBy(DummyState.class, criteria);
Page<DummyState> results = getServiceHub().getVaultService().queryBy(DummyState.class, criteria);
List<StateAndRef<DummyState>> dummyStates = results.getStates();
// For a full list of the available ways of extracting states from

View File

@ -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<DummyState> = serviceHub.vaultQueryService.queryBy<DummyState>(criteria)
val results: Page<DummyState> = serviceHub.vaultService.queryBy<DummyState>(criteria)
val dummyStates: List<StateAndRef<DummyState>> = results.states
// For a full list of the available ways of extracting states from

View File

@ -129,7 +129,7 @@ class SubmitCompletionFlow(private val ref: StateRef, private val verdict: Workf
override fun call(): StateAndRef<TradeApprovalContract.State> {
// DOCSTART 1
val criteria = VaultQueryCriteria(stateRefs = listOf(ref))
val latestRecord = serviceHub.vaultQueryService.queryBy<TradeApprovalContract.State>(criteria).states.single()
val latestRecord = serviceHub.vaultService.queryBy<TradeApprovalContract.State>(criteria).states.single()
// DOCEND 1
// Check the protocol hasn't already been run

View File

@ -27,7 +27,7 @@ class WorkflowTransactionBuildTutorialTest {
// Helper method to locate the latest Vault version of a LinearState
private inline fun <reified T : LinearState> ServiceHub.latest(ref: UniqueIdentifier): StateAndRef<T> {
val linearHeads = vaultQueryService.queryBy<T>(QueryCriteria.LinearStateQueryCriteria(uuid = listOf(ref.id)))
val linearHeads = vaultService.queryBy<T>(QueryCriteria.LinearStateQueryCriteria(uuid = listOf(ref.id)))
return linearHeads.states.single()
}

View File

@ -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

View File

@ -59,7 +59,7 @@ fun CordaRPCOps.getCashBalance(currency: Currency): Amount<Currency> {
}
fun ServiceHub.getCashBalance(currency: Currency): Amount<Currency> {
val results = this.vaultQueryService.queryBy<FungibleAsset<*>>(generateCashSumCriteria(currency))
val results = this.vaultService.queryBy<FungibleAsset<*>>(generateCashSumCriteria(currency))
return rowsToAmount(currency, results)
}
@ -69,7 +69,7 @@ fun CordaRPCOps.getCashBalances(): Map<Currency, Amount<Currency>> {
}
fun ServiceHub.getCashBalances(): Map<Currency, Amount<Currency>> {
val sums = this.vaultQueryService.queryBy<FungibleAsset<*>>(generateCashSumsCriteria()).otherResults
val sums = this.vaultService.queryBy<FungibleAsset<*>>(generateCashSumsCriteria()).otherResults
return rowsToBalances(sums)
}

View File

@ -59,7 +59,7 @@ class CashExitFlow(private val amount: Amount<Currency>,
}
// 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<Cash.State>(VaultQueryCriteria(stateRefs = builder.inputStates()),
val inputStates = serviceHub.vaultService.queryBy<Cash.State>(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

View File

@ -71,7 +71,7 @@ class CashTests : TestDependencyInjectionBase() {
ownedBy = OUR_IDENTITY_1, issuedBy = MINI_CORP.ref(1), issuerServices = miniCorpServices)
}
database.transaction {
vaultStatesUnconsumed = miniCorpServices.vaultQueryService.queryBy<Cash.State>().states
vaultStatesUnconsumed = miniCorpServices.vaultService.queryBy<Cash.State>().states
}
resetTestSerialization()
}

View File

@ -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<Cash.State>(criteria)
val (_, vaultUpdatesBankClient) = notaryNode.services.vaultQueryService.trackBy<Cash.State>(criteria)
val (_, vaultUpdatesBoc) = bankOfCordaNode.services.vaultService.trackBy<Cash.State>(criteria)
val (_, vaultUpdatesBankClient) = notaryNode.services.vaultService.trackBy<Cash.State>(criteria)
val future = bankOfCordaNode.services.startFlow(CashPaymentFlow(expectedPayment,
payTo)).resultFuture

View File

@ -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.

View File

@ -56,7 +56,7 @@ class CordaRPCOpsImpl(
sorting: Sort,
contractStateType: Class<out T>): Vault.Page<T> {
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<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return database.transaction {
services.vaultQueryService._trackBy(criteria, paging, sorting, contractStateType)
services.vaultService._trackBy(criteria, paging, sorting, contractStateType)
}
}

View File

@ -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<HibernateVaultQueryImpl>()
}
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<LinearState> or queryBy<FungibleState<*>>
*/
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 <T : ContractState> _queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>): Vault.Page<T> {
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<StateAndRef<T>> = mutableListOf()
val statesMeta: MutableList<Vault.StateMetadata> = mutableListOf()
val otherResults: MutableList<Any> = 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<TransactionState<T>>(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 <T : ContractState> _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> {
return mutex.locked {
val snapshotResults = _queryBy(criteria, paging, sorting, contractStateType)
val updates: Observable<Vault.Update<T>> = 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<String, MutableSet<String>> {
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<String, MutableSet<String>>()
distinctTypes.forEach { type ->
val concreteType: Class<ContractState> = 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 <T : ContractState> deriveContractInterfaces(clazz: Class<T>): Set<Class<T>> {
val myInterfaces: MutableSet<Class<T>> = mutableSetOf()
clazz.interfaces.forEach {
if (!it.equals(ContractState::class.java)) {
myInterfaces.add(uncheckedCast(it))
myInterfaces.addAll(deriveContractInterfaces(uncheckedCast(it)))
}
}
return myInterfaces
}
}

View File

@ -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<NodeVaultService>()
@ -102,9 +106,6 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT
override val updates: Observable<Vault.Update<ContractState>>
get() = mutex.locked { _updatesInDbTx }
override val updatesPublisher: PublishSubject<Vault.Update<ContractState>>
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<StateAndRef<T>>()
@ -368,8 +369,6 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT
return claimedStates
}
@VisibleForTesting
internal fun isRelevant(state: ContractState, myKeys: Set<PublicKey>): 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<LinearState> or queryBy<FungibleState<*>>
*/
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 <T : ContractState> _queryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>): Vault.Page<T> {
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<StateAndRef<T>> = mutableListOf()
val statesMeta: MutableList<Vault.StateMetadata> = mutableListOf()
val otherResults: MutableList<Any> = 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<TransactionState<T>>(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 <T : ContractState> _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> {
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<Vault.Update<T>>
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<String, MutableSet<String>> {
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<String, MutableSet<String>>()
distinctTypes.forEach { type ->
@Suppress("UNCHECKED_CAST")
val concreteType = Class.forName(type) as Class<ContractState>
val contractInterfaces = deriveContractInterfaces(concreteType)
contractInterfaces.map {
val contractInterface = contractInterfaceToConcreteTypes.getOrPut(it.name, { mutableSetOf() })
contractInterface.add(concreteType.name)
}
}
return contractInterfaceToConcreteTypes
}
}
private fun <T : ContractState> deriveContractInterfaces(clazz: Class<T>): Set<Class<T>> {
val myInterfaces: MutableSet<Class<T>> = mutableSetOf()
clazz.interfaces.forEach {
if (!it.equals(ContractState::class.java)) {
@Suppress("UNCHECKED_CAST")
myInterfaces.add(it as Class<T>)
myInterfaces.addAll(deriveContractInterfaces(it))
}
}
return myInterfaces
}
}

View File

@ -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<LinearState> results = vaultQuerySvc.queryBy(LinearState.class);
Vault.Page<LinearState> 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<DummyLinearContract.State> results = vaultQuerySvc.queryBy(DummyLinearContract.State.class, criteria, sorting);
Vault.Page<DummyLinearContract.State> 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<Cash.State> results = vaultQuerySvc.queryBy(Cash.State.class, criteria);
Vault.Page<Cash.State> 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<LinearState> results = vaultQuerySvc.queryBy(LinearState.class, compositeCriteria2, pageSpec, sorting);
Vault.Page<LinearState> 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<ContractState> results = vaultQuerySvc.queryBy(Cash.State.class, criteria);
Vault.Page<ContractState> results = vaultService.queryBy(Cash.State.class, criteria);
// DOCEND VaultJavaQueryExample3
assertThat(results.getStates()).hasSize(2);
@ -279,7 +260,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase {
Set<Class<ContractState>> contractStateTypes = new HashSet(Collections.singletonList(Cash.State.class));
VaultQueryCriteria criteria = new VaultQueryCriteria(Vault.StateStatus.UNCONSUMED, contractStateTypes);
DataFeed<Vault.Page<ContractState>, Vault.Update<ContractState>> results = vaultQuerySvc.trackBy(ContractState.class, criteria);
DataFeed<Vault.Page<ContractState>, Vault.Update<ContractState>> results = vaultService.trackBy(ContractState.class, criteria);
Vault.Page<ContractState> snapshot = results.getSnapshot();
Observable<Vault.Update<ContractState>> 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.Page<ContractState>, Vault.Update<ContractState>> results = vaultQuerySvc.trackBy(ContractState.class, compositeCriteria, pageSpec, sorting);
DataFeed<Vault.Page<ContractState>, Vault.Update<ContractState>> results = vaultService.trackBy(ContractState.class, compositeCriteria, pageSpec, sorting);
Vault.Page<ContractState> 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<Cash.State> results = vaultQuerySvc.queryBy(Cash.State.class, criteria);
Vault.Page<Cash.State> 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<Cash.State> results = vaultQuerySvc.queryBy(Cash.State.class, criteria);
Vault.Page<Cash.State> 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<Cash.State> results = vaultQuerySvc.queryBy(Cash.State.class, sumCriteria);
Vault.Page<Cash.State> results = vaultService.queryBy(Cash.State.class, sumCriteria);
// DOCEND VaultJavaQueryExample23
assertThat(results.getOtherResults()).hasSize(12);

View File

@ -100,7 +100,7 @@ class CordaRPCOpsImplTest {
// Check the monitoring service wallet is empty
aliceNode.database.transaction {
assertFalse(aliceNode.services.vaultQueryService.queryBy<ContractState>().totalStatesAvailable > 0)
assertFalse(aliceNode.services.vaultService.queryBy<ContractState>().totalStatesAvailable > 0)
}
// Tell the monitoring service node to issue some cash

View File

@ -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)
}

View File

@ -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<ScheduledState>().states.single()
nodeA.services.vaultService.queryBy<ScheduledState>().states.single()
}
val stateFromB = nodeB.database.transaction {
nodeB.services.vaultQueryService.queryBy<ScheduledState>().states.single()
nodeB.services.vaultService.queryBy<ScheduledState>().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<StateAndRef<ScheduledState>> = nodeA.database.transaction {
queryStatesWithPaging(nodeA.services.vaultQueryService)
queryStatesWithPaging(nodeA.services.vaultService)
}
val statesFromB: List<StateAndRef<ScheduledState>> = 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<StateAndRef<ScheduledState>> {
private fun queryStatesWithPaging(vaultService: VaultService): List<StateAndRef<ScheduledState>> {
// DOCSTART VaultQueryExamplePaging
var pageNumber = DEFAULT_PAGE_NUM
val states = mutableListOf<StateAndRef<ScheduledState>>()
do {
val pageSpec = PageSpecification(pageSize = PAGE_SIZE, pageNumber = pageNumber)
val results = vaultQueryService.queryBy<ScheduledState>(VaultQueryCriteria(), pageSpec, SORTING)
val results = vaultService.queryBy<ScheduledState>(VaultQueryCriteria(), pageSpec, SORTING)
states.addAll(results.states)
pageNumber++
} while ((pageSpec.pageSize * (pageNumber)) <= results.totalStatesAvailable)

View File

@ -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
}

View File

@ -1024,9 +1024,9 @@ class FlowFrameworkTests {
override fun call(): List<StateAndRef<ContractState>> {
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<ContractState>().states
}

View File

@ -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<Cash.State>().states
val w1 = vaultService.queryBy<Cash.State>().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<SignedTransaction>) {
@ -107,11 +105,9 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() {
vaultService.notify(stx.tx)
}
}
override val vaultQueryService: VaultQueryService get() = originalVaultQuery
}
val w2 = services2.vaultQueryService.queryBy<Cash.State>().states
val w2 = services2.vaultService.queryBy<Cash.State>().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<Cash.State>().states
val w1 = vaultService.queryBy<Cash.State>().states
assertThat(w1).hasSize(3)
val states = vaultQuery.queryBy<Cash.State>(VaultQueryCriteria(stateRefs = listOf(w1[1].ref, w1[2].ref))).states
val states = vaultService.queryBy<Cash.State>(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<Cash.State>().states
val unconsumedStates = vaultService.queryBy<Cash.State>().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<Cash.State>(criteriaLocked).states).hasSize(2)
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(2)
// my softlocked states
val criteriaByLockId = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.SPECIFIED, listOf(softLockId)))
assertThat(vaultQuery.queryBy<Cash.State>(criteriaByLockId).states).hasSize(2)
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId).states).hasSize(2)
// excluding softlocked states
val unlockedStates1 = vaultQuery.queryBy<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states
val unlockedStates1 = vaultService.queryBy<Cash.State>(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<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states
vaultService.softLockRelease(softLockId, NonEmptySet.of(unconsumedStates[1].ref))
val unlockedStates2 = vaultService.queryBy<Cash.State>(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<Cash.State>(VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.UNLOCKED_ONLY))).states
vaultService.softLockRelease(softLockId)
val unlockedStates = vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId1).states).hasSize(3)
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId2).states).hasSize(3)
vaultService.softLockReserve(softLockId2, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId1).states
val lockStatesId1 = vaultService.queryBy<Cash.State>(criteriaByLockId1).states
println("SOFT LOCK #1 final states: $lockStatesId1")
assertThat(lockStatesId1.size).isIn(0, 3)
val lockStatesId2 = vaultQuery.queryBy<Cash.State>(criteriaByLockId2).states
val lockStatesId2 = vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId1).states).hasSize(1)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId1).states).hasSize(3)
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
}
// attempt to relock same states with LockId1
database.transaction {
vaultSvc.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultQuery.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId1).states).hasSize(1)
vaultService.softLockReserve(softLockId1, NonEmptySet.of(stateRefsToSoftLock.first()))
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaByLockId1).states).hasSize(3)
vaultService.softLockReserve(softLockId1, stateRefsToSoftLock.toNonEmptySet())
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
}
}
@ -321,15 +317,15 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() {
}
database.transaction {
val unconsumedStates = vaultQuery.queryBy<Cash.State>().states
val unconsumedStates = vaultService.queryBy<Cash.State>().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<Cash.State>(criteriaLocked).states).hasSize(1)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>().states
val unconsumedStates = vaultService.queryBy<Cash.State>().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<Cash.State>().states
val unconsumedStates = vaultService.queryBy<Cash.State>().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<Cash.State>(criteriaLocked).states).hasSize(0)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>().states
val unconsumedStates = vaultService.queryBy<Cash.State>().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<Cash.State>(criteriaLocked).states).hasSize(1)
assertThat(vaultService.queryBy<Cash.State>(criteriaLocked).states).hasSize(1)
}
}
@ -416,18 +412,18 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() {
}
database.transaction {
var unlockedStates = 30
val allStates = vaultQuery.queryBy<Cash.State>().states
val allStates = vaultService.queryBy<Cash.State>().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<Cash.State>(criteriaLocked).states
val lockedStates = vaultService.queryBy<Cash.State>(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<Cash.State>(criteriaLocked).states).hasSize(lockedCount)
assertThat(vaultService.queryBy<Cash.State>(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())
}
}

View File

@ -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<ContractState>()
val result = vaultService.queryBy<ContractState>()
/**
* 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<ContractState>(criteria)
val result = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging)
val resultsBeforeConsume = vaultService.queryBy<ContractState>(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<ContractState>(consumedCriteria, paging)
val resultsAfterConsume = vaultService.queryBy<ContractState>(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<Cash.State>()
val result = vaultService.queryBy<Cash.State>()
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<Cash.State>(criteria)
val result = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria, Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC))))
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria, sortBy)
val results = vaultService.queryBy<Cash.State>(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<DummyLinearContract.State>(criteria, Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.ASC))))
val results = vaultService.queryBy<DummyLinearContract.State>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging)
val resultsBeforeConsume = vaultService.queryBy<ContractState>(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<ContractState>(consumedCriteria, paging)
val resultsAfterConsume = vaultService.queryBy<ContractState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging)
val resultsBeforeConsume = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging)
val resultsAfterConsume = vaultService.queryBy<ContractState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteriaExclusive)
val resultsExclusive = vaultService.queryBy<ContractState>(criteriaExclusive)
assertThat(resultsExclusive.states).hasSize(4)
// only soft locked states
val criteriaLockedOnly = VaultQueryCriteria(softLockingCondition = SoftLockingCondition(SoftLockingType.LOCKED_ONLY))
val resultsLockedOnly = vaultQuerySvc.queryBy<ContractState>(criteriaLockedOnly)
val resultsLockedOnly = vaultService.queryBy<ContractState>(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<ContractState>(criteriaByLockId)
val resultsByLockId = vaultService.queryBy<ContractState>(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<ContractState>(criteriaByLockIds)
val resultsByLockIds = vaultService.queryBy<ContractState>(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<ContractState>(criteriaUnlockedAndByLockId)
val resultsUnlockedAndByLockIds = vaultService.queryBy<ContractState>(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<ContractState>(criteriaMissingLockId)
vaultService.queryBy<ContractState>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<FungibleAsset<*>>(sumCriteria
val results = vaultService.queryBy<FungibleAsset<*>>(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<FungibleAsset<*>>(sumCriteria
val results = vaultService.queryBy<FungibleAsset<*>>(sumCriteria
.and(maxCriteria)
.and(minCriteria)
.and(avgCriteria))
@ -837,7 +836,7 @@ class VaultQueryTests : TestDependencyInjectionBase() {
orderBy = Sort.Direction.DESC)
}
val results = vaultQuerySvc.queryBy<FungibleAsset<*>>(VaultCustomQueryCriteria(sum))
val results = vaultService.queryBy<FungibleAsset<*>>(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<FungibleAsset<*>>(countCriteria).otherResults.single() as Long
val fungibleStateCount = vaultService.queryBy<FungibleAsset<*>>(countCriteria).otherResults.single() as Long
assertThat(fungibleStateCount).isEqualTo(10L)
// count linear states
val linearStateCount = vaultQuerySvc.queryBy<LinearState>(countCriteria).otherResults.single() as Long
val linearStateCount = vaultService.queryBy<LinearState>(countCriteria).otherResults.single() as Long
assertThat(linearStateCount).isEqualTo(9L)
// count deal states
val dealStateCount = vaultQuerySvc.queryBy<DealState>(countCriteria).otherResults.single() as Long
val dealStateCount = vaultService.queryBy<DealState>(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<FungibleAsset<*>>(countCriteria).otherResults.single() as Long
val fungibleStateCount = vaultService.queryBy<FungibleAsset<*>>(countCriteria).otherResults.single() as Long
assertThat(fungibleStateCount).isEqualTo(10L)
// count linear states
val linearStateCount = vaultQuerySvc.queryBy<LinearState>(countCriteria).otherResults.single() as Long
val linearStateCount = vaultService.queryBy<LinearState>(countCriteria).otherResults.single() as Long
assertThat(linearStateCount).isEqualTo(9L)
// count deal states
val dealStateCount = vaultQuerySvc.queryBy<DealState>(countCriteria).otherResults.single() as Long
val dealStateCount = vaultService.queryBy<DealState>(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<FungibleAsset<*>>(countCriteriaUnconsumed).otherResults.single() as Long
val fungibleStateCountUnconsumed = vaultService.queryBy<FungibleAsset<*>>(countCriteriaUnconsumed).otherResults.single() as Long
assertThat(fungibleStateCountUnconsumed.toInt()).isEqualTo(10 - cashUpdates.consumed.size + cashUpdates.produced.size)
// count linear states
val linearStateCountUnconsumed = vaultQuerySvc.queryBy<LinearState>(countCriteriaUnconsumed).otherResults.single() as Long
val linearStateCountUnconsumed = vaultService.queryBy<LinearState>(countCriteriaUnconsumed).otherResults.single() as Long
assertThat(linearStateCountUnconsumed).isEqualTo(5L)
// count deal states
val dealStateCountUnconsumed = vaultQuerySvc.queryBy<DealState>(countCriteriaUnconsumed).otherResults.single() as Long
val dealStateCountUnconsumed = vaultService.queryBy<DealState>(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<FungibleAsset<*>>(countCriteriaConsumed).otherResults.single() as Long
val fungibleStateCountConsumed = vaultService.queryBy<FungibleAsset<*>>(countCriteriaConsumed).otherResults.single() as Long
assertThat(fungibleStateCountConsumed.toInt()).isEqualTo(cashUpdates.consumed.size)
// count linear states
val linearStateCountConsumed = vaultQuerySvc.queryBy<LinearState>(countCriteriaConsumed).otherResults.single() as Long
val linearStateCountConsumed = vaultService.queryBy<LinearState>(countCriteriaConsumed).otherResults.single() as Long
assertThat(linearStateCountConsumed).isEqualTo(4L)
// count deal states
val dealStateCountConsumed = vaultQuerySvc.queryBy<DealState>(countCriteriaConsumed).otherResults.single() as Long
val dealStateCountConsumed = vaultService.queryBy<DealState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteriaFuture).states).isEmpty()
assertThat(vaultService.queryBy<ContractState>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging = pagingSpec)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging = pagingSpec)
val results = vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging = pagingSpec)
vaultService.queryBy<ContractState>(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<ContractState>(criteria, paging = pagingSpec)
vaultService.queryBy<ContractState>(criteria, paging = pagingSpec)
}
}
@ -1082,7 +1081,7 @@ class VaultQueryTests : TestDependencyInjectionBase() {
}
database.transaction {
val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL)
vaultQuerySvc.queryBy<ContractState>(criteria)
vaultService.queryBy<ContractState>(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<ContractState>(VaultQueryCriteria(status = Vault.StateStatus.ALL), sorting = sorting)
val result = vaultService.queryBy<ContractState>(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<FungibleAsset<*>>()
val results = vaultService.queryBy<FungibleAsset<*>>()
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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(criteria)
assertThat(results.states).hasSize(2)
}
}
@ -1154,7 +1153,7 @@ class VaultQueryTests : TestDependencyInjectionBase() {
services.fillWithSomeTestLinearStates(10)
}
database.transaction {
val results = vaultQuerySvc.queryBy<Cash.State>()
val results = vaultService.queryBy<Cash.State>()
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<Cash.State>(FungibleAssetQueryCriteria())
val results = vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
val results = vaultService.queryBy<Cash.State>(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<LinearState>()
val results = vaultService.queryBy<LinearState>()
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<LinearState>(criteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(criteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(criteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(criteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(linearStateCriteria and vaultCriteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(linearStateCriteria.and(vaultCriteria), sorting = sorting)
val results = vaultService.queryBy<LinearState>(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<DummyLinearContract.State>((vaultCriteria), sorting = sorting)
val results = vaultService.queryBy<DummyLinearContract.State>((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<LinearState>(compositeCriteria, sorting = sorting)
val results = vaultService.queryBy<LinearState>(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<DummyLinearContract.State>((vaultCriteria), sorting = sorting)
val results = vaultService.queryBy<DummyLinearContract.State>((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<LinearState>(linearStateCriteria.and(vaultCriteria), sorting = sorting)
val results = vaultService.queryBy<LinearState>(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<DealState>()
val results = vaultService.queryBy<DealState>()
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<DealState>(criteria)
val results = vaultService.queryBy<DealState>(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<DealState>()
val all = vaultService.queryBy<DealState>()
all.states.forEach { println(it.state) }
val criteria = LinearStateQueryCriteria(externalId = listOf("456"))
val results = vaultQuerySvc.queryBy<DealState>(criteria)
val results = vaultService.queryBy<DealState>(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<DealState>(criteria)
val results = vaultService.queryBy<DealState>(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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(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<ContractState>(criteria)
val results = vaultService.queryBy<ContractState>(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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(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<FungibleAsset<*>>(sumCriteria.and(ccyCriteria))
val results = vaultService.queryBy<FungibleAsset<*>>(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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(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<Cash.State>(fungibleAssetCriteria)
val results = vaultService.queryBy<Cash.State>(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<FungibleAsset<*>>(criteria)
val results = vaultService.queryBy<FungibleAsset<*>>(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<Cash.State>(fungibleAssetCriteria.and(customCriteria))
val results = vaultService.queryBy<Cash.State>(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<CommercialPaper.State>(criteria1)
val result = vaultService.queryBy<CommercialPaper.State>(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<CommercialPaper.State>(criteria1.and(criteria3).and(criteria2))
vaultService.queryBy<CommercialPaper.State>(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<Cash.State>(criteria)
vaultService.queryBy<Cash.State>(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<Cash.State>(criteria)
vaultService.queryBy<Cash.State>(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<LinearState>(basicCriteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(externalIdCustomCriteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(criteria)
vaultService.queryBy<LinearState>(criteria)
}
assertThat(results.states).hasSize(1)
@ -1894,7 +1893,7 @@ class VaultQueryTests : TestDependencyInjectionBase() {
val uuidCustomCriteria = VaultCustomQueryCriteria(uuidCondition)
val criteria = externalIdCustomCriteria or uuidCustomCriteria
vaultQuerySvc.queryBy<LinearState>(criteria)
vaultService.queryBy<LinearState>(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<LinearState>(linearStateCriteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(linearStateCriteria)
val results = vaultService.queryBy<LinearState>(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<LinearState>(externalIdCustomCriteria)
vaultService.queryBy<LinearState>(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<LinearState>(externalIdCustomCriteria)
vaultService.queryBy<LinearState>(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<FungibleAsset<*>>(baseCriteria and enrichedCriteria, sorter).states
val results = services.vaultService.queryBy<FungibleAsset<*>>(baseCriteria and enrichedCriteria, sorter).states
assertThat(results).hasSize(4)
}
}
@ -2015,7 +2014,7 @@ class VaultQueryTests : TestDependencyInjectionBase() {
val updates =
database.transaction {
// DOCSTART VaultQueryExample15
vaultQuerySvc.trackBy<Cash.State>().updates // UNCONSUMED default
vaultService.trackBy<Cash.State>().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<Cash.State>(criteria).updates
vaultService.trackBy<Cash.State>(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<Cash.State>(criteria).updates
vaultService.trackBy<Cash.State>(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<LinearState>()
val (snapshot, updates) = vaultService.trackBy<LinearState>()
// 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<DealState>()
val (snapshot, updates) = vaultService.trackBy<DealState>()
// DOCEND VaultQueryExample17
assertThat(snapshot.states).hasSize(0)
updates

View File

@ -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<Cash.State>().states
val w = vaultService.queryBy<Cash.State>().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<Cash.State>().states).hasSize(10)
assertThat(vaultQuery.queryBy<Cash.State>(criteriaLocked).states).hasSize(0)
assertThat(vaultService.queryBy<Cash.State>().states).hasSize(10)
assertThat(vaultService.queryBy<Cash.State>(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<Cash.State>()
val consumedStates1 = vaultQuery.queryBy<Cash.State>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED))
val lockedStates1 = vaultQuery.queryBy<Cash.State>(criteriaLocked).states
val unconsumedStates1 = vaultService.queryBy<Cash.State>()
val consumedStates1 = vaultService.queryBy<Cash.State>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED))
val lockedStates1 = vaultService.queryBy<Cash.State>(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<Cash.State>()
val consumedStates2 = vaultQuery.queryBy<Cash.State>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED))
val lockedStates2 = vaultQuery.queryBy<Cash.State>(criteriaLocked).states
val unconsumedStates2 = vaultService.queryBy<Cash.State>()
val consumedStates2 = vaultService.queryBy<Cash.State>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED))
val lockedStates2 = vaultService.queryBy<Cash.State>(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<Cash.State>()
val consumedStates1 = vaultQuery.queryBy<Cash.State>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED))
val lockedStates1 = vaultQuery.queryBy<Cash.State>(criteriaLocked).states
val unconsumedStates1 = vaultService.queryBy<Cash.State>()
val consumedStates1 = vaultService.queryBy<Cash.State>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED))
val lockedStates1 = vaultService.queryBy<Cash.State>(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<Cash.State>()
val consumedStates2 = vaultQuery.queryBy<Cash.State>()
val lockedStates2 = vaultQuery.queryBy<Cash.State>(criteriaLocked).states
val unconsumedStates2 = vaultService.queryBy<Cash.State>()
val consumedStates2 = vaultService.queryBy<Cash.State>()
val lockedStates2 = vaultService.queryBy<Cash.State>(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<DummyLinearContract.State>().states).hasSize(1)
assertThat(vaultService.queryBy<DummyLinearContract.State>().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<DummyLinearContract.State>().states).hasSize(1)
assertThat(vaultService.queryBy<DummyLinearContract.State>().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<Cash.State>().states
val cash = vaultService.queryBy<Cash.State>().states
cash.forEach { println(it.state.data.amount) }
}
database.transaction {
services.fillWithSomeTestDeals(listOf("123", "456", "789"))
}
database.transaction {
val deals = vaultQuery.queryBy<DummyDealContract.State>().states
val deals = vaultService.queryBy<DummyDealContract.State>().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<ContractState>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states
val consumedStates = vaultService.queryBy<ContractState>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states
assertEquals(3, consumedStates.count())
val unconsumedStates = vaultQuery.queryBy<ContractState>().states
val unconsumedStates = vaultService.queryBy<ContractState>().states
assertEquals(7, unconsumedStates.count())
}
}
@ -336,13 +334,13 @@ class VaultWithCashTest : TestDependencyInjectionBase() {
}
val deals =
database.transaction {
vaultQuery.queryBy<DummyDealContract.State>().states
vaultService.queryBy<DummyDealContract.State>().states
}
database.transaction {
services.fillWithSomeTestLinearStates(3)
}
database.transaction {
val linearStates = vaultQuery.queryBy<DummyLinearContract.State>().states
val linearStates = vaultService.queryBy<DummyLinearContract.State>().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<ContractState>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states
val consumedStates = vaultService.queryBy<ContractState>(VaultQueryCriteria(status = Vault.StateStatus.CONSUMED)).states
assertEquals(2, consumedStates.count())
val unconsumedStates = vaultQuery.queryBy<ContractState>().states
val unconsumedStates = vaultService.queryBy<ContractState>().states
assertEquals(6, unconsumedStates.count())
}
}

View File

@ -97,7 +97,7 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten
val swaps =
node1.database.transaction {
node1.services.vaultQueryService.queryBy<InterestRateSwap.State>().states
node1.services.vaultService.queryBy<InterestRateSwap.State>().states
}
val theDealRef: StateAndRef<InterestRateSwap.State> = swaps.single()

View File

@ -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<IRSState>(criteria).states
val trades = serviceHub.vaultService.queryBy<IRSState>(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<PortfolioState>(criteria).states.first()
val portfolioStateRef = serviceHub.vaultService.queryBy<PortfolioState>(criteria).states.first()
val state = updateValuation(portfolioStateRef)
logger.info("SimmFlow done")
@ -126,7 +126,7 @@ object SimmFlow {
private fun updateValuation(stateRef: StateAndRef<PortfolioState>): RevisionedState<PortfolioState.Update> {
logger.info("Agreeing valuations")
val state = stateRef.state.data
val portfolio = serviceHub.vaultQueryService.queryBy<IRSState>(VaultQueryCriteria(stateRefs = state.portfolio)).states.toPortfolio()
val portfolio = serviceHub.vaultService.queryBy<IRSState>(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<IRSState>(criteria).states
val trades = serviceHub.vaultService.queryBy<IRSState>(criteria).states
val portfolio = Portfolio(trades)
logger.info("SimmFlow receiver started")
offer = replyToSession.receive<OfferMessage>().unwrap { it }
@ -220,7 +220,7 @@ object SimmFlow {
} else {
updatePortfolio(portfolio)
}
val portfolioStateRef = serviceHub.vaultQueryService.queryBy<PortfolioState>(criteria).states.first()
val portfolioStateRef = serviceHub.vaultService.queryBy<PortfolioState>(criteria).states.first()
updateValuation(portfolioStateRef)
}
@ -327,7 +327,7 @@ object SimmFlow {
@Suspendable
private fun updateValuation(stateRef: StateAndRef<PortfolioState>) {
val portfolio = serviceHub.vaultQueryService.queryBy<IRSState>(VaultQueryCriteria(stateRefs = stateRef.state.data.portfolio)).states.toPortfolio()
val portfolio = serviceHub.vaultService.queryBy<IRSState>(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<PortfolioState.Update>(replyToSession) {

View File

@ -20,7 +20,7 @@ object SimmRevaluation {
class Initiator(private val curStateRef: StateRef, private val valuationDate: LocalDate) : FlowLogic<Unit>() {
@Suspendable
override fun call() {
val stateAndRef = serviceHub.vaultQueryService.queryBy<PortfolioState>(VaultQueryCriteria(stateRefs = listOf(curStateRef))).states.single()
val stateAndRef = serviceHub.vaultService.queryBy<PortfolioState>(VaultQueryCriteria(stateRefs = listOf(curStateRef))).states.single()
val curState = stateAndRef.state.data
if (ourIdentity == curState.participants[0]) {
val otherParty = serviceHub.identityService.wellKnownPartyFromAnonymous(curState.participants[1])

View File

@ -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

View File

@ -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

View File

@ -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<String> = 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<String> = 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<String> = 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
}