Change references to 'wallet' with 'vault'

This commit is contained in:
Ross Nicoll
2016-09-19 11:32:38 +01:00
parent ae4513c8eb
commit ebda724f14
38 changed files with 252 additions and 250 deletions

View File

@ -30,10 +30,10 @@ class APIServerImpl(val node: AbstractNode) : APIServer {
// something we can't later implement against a persistent store (i.e. need to pick / build a query engine)
if (query is StatesQuery.Selection) {
if (query.criteria is StatesQuery.Criteria.AllDeals) {
val states = node.services.walletService.linearHeads
val states = node.services.vaultService.linearHeads
return states.values.map { it.ref }
} else if (query.criteria is StatesQuery.Criteria.Deal) {
val states = node.services.walletService.linearHeadsOfType<DealState>().filterValues {
val states = node.services.vaultService.linearHeadsOfType<DealState>().filterValues {
it.state.data.ref == query.criteria.ref
}
return states.values.map { it.ref }
@ -43,7 +43,7 @@ class APIServerImpl(val node: AbstractNode) : APIServer {
}
override fun fetchStates(states: List<StateRef>): Map<StateRef, TransactionState<ContractState>?> {
return node.services.walletService.statesForRefs(states)
return node.services.vaultService.statesForRefs(states)
}
override fun fetchTransactions(txs: List<SecureHash>): Map<SecureHash, SignedTransaction?> {

View File

@ -43,8 +43,8 @@ import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.node.services.transactions.NotaryService
import com.r3corda.node.services.transactions.SimpleNotaryService
import com.r3corda.node.services.transactions.ValidatingNotaryService
import com.r3corda.node.services.wallet.CashBalanceAsMetricsObserver
import com.r3corda.node.services.wallet.NodeWalletService
import com.r3corda.node.services.vault.CashBalanceAsMetricsObserver
import com.r3corda.node.services.vault.NodeVaultService
import com.r3corda.node.utilities.*
import org.slf4j.Logger
import java.nio.file.FileAlreadyExistsException
@ -94,7 +94,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
override val networkService: MessagingServiceInternal get() = net
override val networkMapCache: NetworkMapCache get() = netMapCache
override val storageService: TxWritableStorageService get() = storage
override val walletService: WalletService get() = wallet
override val vaultService: VaultService get() = vault
override val keyManagementService: KeyManagementService get() = keyManagement
override val identityService: IdentityService get() = identity
override val schedulerService: SchedulerService get() = scheduler
@ -121,7 +121,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
lateinit var storage: TxWritableStorageService
lateinit var checkpointStorage: CheckpointStorage
lateinit var smm: StateMachineManager
lateinit var wallet: WalletService
lateinit var vault: VaultService
lateinit var keyManagement: KeyManagementService
var inNodeNetworkMapService: NetworkMapService? = null
var inNodeWalletMonitorService: WalletMonitorService? = null
@ -167,7 +167,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
checkpointStorage = storageServices.second
netMapCache = InMemoryNetworkMapCache()
net = makeMessagingService()
wallet = makeWalletService()
vault = makeVaultService()
identity = makeIdentityService()
@ -180,7 +180,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
protocolLogicFactory = initialiseProtocolLogicFactory()
val tokenizableServices = mutableListOf(storage, net, wallet, keyManagement, identity, platformClock, scheduler)
val tokenizableServices = mutableListOf(storage, net, vault, keyManagement, identity, platformClock, scheduler)
customServices.clear()
customServices.addAll(buildPluginServices(tokenizableServices))
@ -211,7 +211,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
// TODO: this model might change but for now it provides some de-coupling
// Add SMM observers
ANSIProgressObserver(smm)
// Add wallet observers
// Add vault observers
CashBalanceAsMetricsObserver(services)
ScheduledActivityObserver(services)
}
@ -372,7 +372,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
}
// TODO: sort out ordering of open & protected modifiers of functions in this class.
protected open fun makeWalletService(): WalletService = NodeWalletService(services)
protected open fun makeVaultService(): VaultService = NodeVaultService(services)
protected open fun makeWalletMonitorService(): WalletMonitorService = WalletMonitorService(services, smm)

View File

@ -39,14 +39,14 @@ abstract class ServiceHubInternal : ServiceHub {
/**
* Given a list of [SignedTransaction]s, writes them to the given storage for validated transactions and then
* sends them to the wallet for further processing. This is intended for implementations to call from
* sends them to the vault for further processing. This is intended for implementations to call from
* [recordTransactions].
*
* @param txs The transactions to record.
*/
internal fun recordTransactionsInternal(writableStorageService: TxWritableStorageService, txs: Iterable<SignedTransaction>) {
txs.forEach { writableStorageService.validatedTransactions.addTransaction(it) }
walletService.notifyAll(txs.map { it.tx })
vaultService.notifyAll(txs.map { it.tx })
}
/**

View File

@ -20,7 +20,7 @@ import javax.annotation.concurrent.ThreadSafe
/**
* A first pass of a simple [SchedulerService] that works with [MutableClock]s for testing, demonstrations and simulations
* that also encompasses the [Wallet] observer for processing transactions.
* that also encompasses the [Vault] observer for processing transactions.
*
* This will observe transactions as they are stored and schedule and unschedule activities based on the States consumed
* or produced.
@ -50,7 +50,7 @@ class NodeSchedulerService(private val services: ServiceHubInternal,
// to somewhere.
private class InnerState {
// TODO: This has no persistence, and we don't consider initialising from non-empty map if we add persistence.
// If we were to rebuild the wallet at start up by replaying transactions and re-calculating, then
// If we were to rebuild the vault at start up by replaying transactions and re-calculating, then
// persistence here would be unnecessary.
var scheduledStates = HashMap<StateRef, ScheduledStateRef>()
var earliestState: ScheduledStateRef? = null

View File

@ -8,21 +8,21 @@ import com.r3corda.core.protocols.ProtocolLogicRefFactory
import com.r3corda.node.services.api.ServiceHubInternal
/**
* This observes the wallet and schedules and unschedules activities appropriately based on state production and
* This observes the vault and schedules and unschedules activities appropriately based on state production and
* consumption.
*/
class ScheduledActivityObserver(val services: ServiceHubInternal) {
init {
// TODO: Need to consider failure scenarios. This needs to run if the TX is successfully recorded
services.walletService.updates.subscribe { update ->
services.vaultService.updates.subscribe { update ->
update.consumed.forEach { services.schedulerService.unscheduleStateActivity(it) }
update.produced.forEach { scheduleStateActivity(it, services.protocolLogicRefFactory) }
}
// In the short term, to get restart-able IRS demo, re-initialise from wallet state
// In the short term, to get restart-able IRS demo, re-initialise from vault state
// TODO: there's a race condition here. We need to move persistence into the scheduler but that is a bigger
// change so I want to revisit as a distinct branch/PR.
for (state in services.walletService.currentWallet.statesOfType<SchedulableState>()) {
for (state in services.vaultService.currentVault.statesOfType<SchedulableState>()) {
scheduleStateActivity(state, services.protocolLogicRefFactory)
}
}

View File

@ -8,7 +8,7 @@ import com.r3corda.core.crypto.Party
import com.r3corda.core.crypto.toStringShort
import com.r3corda.core.messaging.MessageRecipients
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.node.services.Wallet
import com.r3corda.core.node.services.Vault
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.core.serialization.serialize
import com.r3corda.core.transactions.LedgerTransaction
@ -60,7 +60,7 @@ class WalletMonitorService(services: ServiceHubInternal, val smm: StateMachineMa
// Notify listeners on state changes
services.storageService.validatedTransactions.updates.subscribe { tx -> notifyTransaction(tx.tx.toLedgerTransaction(services)) }
services.walletService.updates.subscribe { update -> notifyWalletUpdate(update) }
services.vaultService.updates.subscribe { update -> notifyVaultUpdate(update) }
smm.changes.subscribe { change ->
val fiberId: Long = change.third
val logic: ProtocolLogic<*> = change.first
@ -81,7 +81,7 @@ class WalletMonitorService(services: ServiceHubInternal, val smm: StateMachineMa
}
@VisibleForTesting
internal fun notifyWalletUpdate(update: Wallet.Update)
internal fun notifyVaultUpdate(update: Vault.Update)
= notifyEvent(ServiceToClientEvent.OutputState(Instant.now(), update.consumed, update.produced))
@VisibleForTesting
@ -135,7 +135,7 @@ class WalletMonitorService(services: ServiceHubInternal, val smm: StateMachineMa
fun processRegisterRequest(req: RegisterRequest) {
try {
listeners.add(RegisteredListener(req.replyToRecipient, req.sessionID))
val stateMessage = StateSnapshotMessage(services.walletService.currentWallet.states.toList(),
val stateMessage = StateSnapshotMessage(services.vaultService.currentVault.states.toList(),
smm.allStateMachines.map { it.javaClass.name })
net.send(net.createMessage(STATE_TOPIC, DEFAULT_SESSION_ID, stateMessage.serialize().bits), req.replyToRecipient)
@ -158,7 +158,7 @@ class WalletMonitorService(services: ServiceHubInternal, val smm: StateMachineMa
try {
Cash().generateSpend(builder, req.amount.withoutIssuer(), req.recipient.owningKey,
// TODO: Move cash state filtering by issuer down to the contract itself
services.walletService.currentWallet.statesOfType<Cash.State>().filter { it.state.data.amount.token == req.amount.token },
services.vaultService.currentVault.statesOfType<Cash.State>().filter { it.state.data.amount.token == req.amount.token },
setOf(req.amount.token.issuer.party))
.forEach {
val key = services.keyManagementService.keys[it] ?: throw IllegalStateException("Could not find signing key for ${it.toStringShort()}")
@ -182,11 +182,11 @@ class WalletMonitorService(services: ServiceHubInternal, val smm: StateMachineMa
try {
val issuer = PartyAndReference(services.storageService.myLegalIdentity, req.issueRef)
Cash().generateExit(builder, req.amount.issuedBy(issuer),
services.walletService.currentWallet.statesOfType<Cash.State>().filter { it.state.data.owner == issuer.party.owningKey })
services.vaultService.currentVault.statesOfType<Cash.State>().filter { it.state.data.owner == issuer.party.owningKey })
builder.signWith(services.storageService.myLegalIdentityKey)
// Work out who the owners of the burnt states were
val inputStatesNullable = services.walletService.statesForRefs(builder.inputStates())
val inputStatesNullable = services.vaultService.statesForRefs(builder.inputStates())
val inputStates = inputStatesNullable.values.filterNotNull().map { it.data }
if (inputStatesNullable.size != inputStates.size) {
val unresolvedStateRefs = inputStatesNullable.filter { it.value == null }.map { it.key }

View File

@ -1,19 +1,19 @@
package com.r3corda.node.services.wallet
package com.r3corda.node.services.vault
import com.codahale.metrics.Gauge
import com.r3corda.contracts.asset.cashBalances
import com.r3corda.core.node.services.Wallet
import com.r3corda.core.node.services.Vault
import com.r3corda.node.services.api.ServiceHubInternal
import java.util.*
/**
* This class observes the wallet and reflect current cash balances as exposed metrics in the monitoring service.
* This class observes the vault and reflect current cash balances as exposed metrics in the monitoring service.
*/
class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal) {
init {
// TODO: Need to consider failure scenarios. This needs to run if the TX is successfully recorded
serviceHubInternal.walletService.updates.subscribe { update ->
exportCashBalancesViaMetrics(serviceHubInternal.walletService.currentWallet)
serviceHubInternal.vaultService.updates.subscribe { update ->
exportCashBalancesViaMetrics(serviceHubInternal.vaultService.currentVault)
}
}
@ -24,16 +24,16 @@ class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal) {
private val balanceMetrics = HashMap<Currency, BalanceMetric>()
private fun exportCashBalancesViaMetrics(wallet: Wallet) {
private fun exportCashBalancesViaMetrics(vault: Vault) {
// This is just for demo purposes. We probably shouldn't expose balances via JMX in a real node as that might
// be commercially sensitive info that the sysadmins aren't even meant to know.
//
// Note: exported as pennies.
val m = serviceHubInternal.monitoringService.metrics
for ((key, value) in wallet.cashBalances) {
for ((key, value) in vault.cashBalances) {
val metric = balanceMetrics.getOrPut(key) {
val newMetric = BalanceMetric()
m.register("WalletBalances.${key}Pennies", newMetric)
m.register("VaultBalances.${key}Pennies", newMetric)
newMetric
}
metric.pennies = value.quantity

View File

@ -1,11 +1,11 @@
package com.r3corda.node.services.wallet
package com.r3corda.node.services.vault
import com.google.common.collect.Sets
import com.r3corda.core.contracts.*
import com.r3corda.core.crypto.SecureHash
import com.r3corda.core.node.ServiceHub
import com.r3corda.core.node.services.Wallet
import com.r3corda.core.node.services.WalletService
import com.r3corda.core.node.services.Vault
import com.r3corda.core.node.services.VaultService
import com.r3corda.core.serialization.SingletonSerializeAsToken
import com.r3corda.core.transactions.WireTransaction
import com.r3corda.core.utilities.loggerFor
@ -21,8 +21,8 @@ import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Currently, the node wallet service is a very simple RDBMS backed implementation. It will change significantly when
* we add further functionality as the design for the wallet and wallet service matures.
* Currently, the node vault service is a very simple RDBMS backed implementation. It will change significantly when
* we add further functionality as the design for the vault and vault service matures.
*
* This class needs database transactions to be in-flight during method calls and init, and will throw exceptions if
* this is not the case.
@ -31,10 +31,10 @@ import kotlin.concurrent.withLock
* 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 NodeWalletService(private val services: ServiceHub) : SingletonSerializeAsToken(), WalletService {
class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsToken(), VaultService {
private companion object {
val log = loggerFor<NodeWalletService>()
val log = loggerFor<NodeVaultService>()
}
private object StatesSetTable : JDBCHashedTable("vault_unconsumed_states") {
@ -53,11 +53,11 @@ class NodeWalletService(private val services: ServiceHub) : SingletonSerializeAs
protected val mutex = ReentrantLock()
override val currentWallet: Wallet get() = mutex.withLock { Wallet(allUnconsumedStates()) }
override val currentVault: Vault get() = mutex.withLock { Vault(allUnconsumedStates()) }
private val _updatesPublisher = PublishSubject.create<Wallet.Update>()
private val _updatesPublisher = PublishSubject.create<Vault.Update>()
override val updates: Observable<Wallet.Update>
override val updates: Observable<Vault.Update>
get() = _updatesPublisher
/**
@ -66,21 +66,21 @@ class NodeWalletService(private val services: ServiceHub) : SingletonSerializeAs
* TODO: Represent this using an actual JDBCHashMap or look at vault design further.
*/
override val linearHeads: Map<UniqueIdentifier, StateAndRef<LinearState>>
get() = currentWallet.states.filterStatesOfType<LinearState>().associateBy { it.state.data.linearId }.mapValues { it.value }
get() = currentVault.states.filterStatesOfType<LinearState>().associateBy { it.state.data.linearId }.mapValues { it.value }
override fun notifyAll(txns: Iterable<WireTransaction>): Wallet {
override fun notifyAll(txns: Iterable<WireTransaction>): Vault {
val ourKeys = services.keyManagementService.keys.keys
val netDelta = txns.fold(Wallet.NoUpdate) { netDelta, txn -> netDelta + makeUpdate(txn, netDelta, ourKeys) }
if (netDelta != Wallet.NoUpdate) {
val netDelta = txns.fold(Vault.NoUpdate) { netDelta, txn -> netDelta + makeUpdate(txn, netDelta, ourKeys) }
if (netDelta != Vault.NoUpdate) {
mutex.withLock {
recordUpdate(netDelta)
}
_updatesPublisher.onNext(netDelta)
}
return currentWallet
return currentVault
}
private fun makeUpdate(tx: WireTransaction, netDelta: Wallet.Update, ourKeys: Set<PublicKey>): Wallet.Update {
private fun makeUpdate(tx: WireTransaction, netDelta: Vault.Update, ourKeys: Set<PublicKey>): Vault.Update {
val ourNewStates = tx.outputs.
filter { isRelevant(it.data, ourKeys) }.
map { tx.outRef<ContractState>(it.data) }
@ -95,26 +95,26 @@ class NodeWalletService(private val services: ServiceHub) : SingletonSerializeAs
// Is transaction irrelevant?
if (consumed.isEmpty() && ourNewStates.isEmpty()) {
log.trace { "tx ${tx.id} was irrelevant to this wallet, ignoring" }
return Wallet.NoUpdate
log.trace { "tx ${tx.id} was irrelevant to this vault, ignoring" }
return Vault.NoUpdate
}
return Wallet.Update(consumed, ourNewStates.toHashSet())
return Vault.Update(consumed, ourNewStates.toHashSet())
}
private fun isRelevant(state: ContractState, ourKeys: Set<PublicKey>): Boolean {
return if (state is OwnableState) {
state.owner in ourKeys
} else if (state is LinearState) {
// It's potentially of interest to the wallet
// It's potentially of interest to the vault
state.isRelevant(ourKeys)
} else {
false
}
}
private fun recordUpdate(update: Wallet.Update): Wallet.Update {
if (update != Wallet.NoUpdate) {
private fun recordUpdate(update: Vault.Update): Vault.Update {
if (update != Vault.NoUpdate) {
val producedStateRefs = update.produced.map { it.ref }
val consumedStateRefs = update.consumed
log.trace { "Removing $consumedStateRefs consumed contract states and adding $producedStateRefs produced contract states to the database." }

View File

@ -11,7 +11,7 @@ import com.r3corda.core.messaging.SingleMessageRecipient
import com.r3corda.core.node.ServiceHub
import com.r3corda.core.node.services.ServiceType
import com.r3corda.core.node.services.TransactionStorage
import com.r3corda.core.node.services.Wallet
import com.r3corda.core.node.services.Vault
import com.r3corda.core.transactions.SignedTransaction
import com.r3corda.core.transactions.WireTransaction
import com.r3corda.core.utilities.DUMMY_NOTARY
@ -370,7 +370,7 @@ class TwoPartyTradeProtocolTests {
private fun LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.fillUpForBuyer(
withError: Boolean,
owner: PublicKey = BOB_PUBKEY): Pair<Wallet, List<WireTransaction>> {
owner: PublicKey = BOB_PUBKEY): Pair<Vault, List<WireTransaction>> {
val issuer = DUMMY_CASH_ISSUER
// Bob (Buyer) has some cash he got from the Bank of Elbonia, Alice (Seller) has some commercial paper she
// wants to sell to Bob.
@ -407,15 +407,15 @@ class TwoPartyTradeProtocolTests {
this.verifies()
}
val wallet = Wallet(listOf("bob cash 1".outputStateAndRef(), "bob cash 2".outputStateAndRef()))
return Pair(wallet, listOf(eb1, bc1, bc2))
val vault = Vault(listOf("bob cash 1".outputStateAndRef(), "bob cash 2".outputStateAndRef()))
return Pair(vault, listOf(eb1, bc1, bc2))
}
private fun LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.fillUpForSeller(
withError: Boolean,
owner: PublicKey,
amount: Amount<Issued<Currency>>,
attachmentID: SecureHash?): Pair<Wallet, List<WireTransaction>> {
attachmentID: SecureHash?): Pair<Vault, List<WireTransaction>> {
val ap = transaction {
output("alice's paper") {
CommercialPaper.State(MEGA_CORP.ref(1, 2, 3), owner, amount, TEST_TX_TIME + 7.days)
@ -432,8 +432,8 @@ class TwoPartyTradeProtocolTests {
}
}
val wallet = Wallet(listOf("alice's paper".outputStateAndRef()))
return Pair(wallet, listOf(ap))
val vault = Vault(listOf("alice's paper".outputStateAndRef()))
return Pair(vault, listOf(ap))
}
class RecordingTransactionStorage(val delegate: TransactionStorage) : TransactionStorage {

View File

@ -14,14 +14,14 @@ import com.r3corda.testing.node.MockNetworkMapCache
import com.r3corda.node.services.network.NetworkMapService
import com.r3corda.node.services.persistence.DataVending
import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.core.testing.InMemoryWalletService
import com.r3corda.core.testing.InMemoryVaultService
import com.r3corda.testing.node.MockStorageService
import com.r3corda.testing.MOCK_IDENTITY_SERVICE
import java.time.Clock
@Suppress("LeakingThis")
open class MockServiceHubInternal(
customWallet: WalletService? = null,
customVault: VaultService? = null,
val keyManagement: KeyManagementService? = null,
val net: MessagingServiceInternal? = null,
val identity: IdentityService? = MOCK_IDENTITY_SERVICE,
@ -32,7 +32,7 @@ open class MockServiceHubInternal(
val overrideClock: Clock? = NodeClock(),
val protocolFactory: ProtocolLogicRefFactory? = ProtocolLogicRefFactory()
) : ServiceHubInternal() {
override val walletService: WalletService = customWallet ?: InMemoryWalletService(this)
override val vaultService: VaultService = customVault ?: InMemoryVaultService(this)
override val keyManagementService: KeyManagementService
get() = keyManagement ?: throw UnsupportedOperationException()
override val identityService: IdentityService

View File

@ -17,7 +17,7 @@ import com.r3corda.node.services.events.NodeSchedulerService
import com.r3corda.testing.node.InMemoryMessagingNetwork
import com.r3corda.node.services.persistence.PerFileCheckpointStorage
import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.node.services.wallet.NodeWalletService
import com.r3corda.node.services.vault.NodeVaultService
import com.r3corda.node.utilities.AddOrRemove
import com.r3corda.node.utilities.AffinityExecutor
import com.r3corda.node.utilities.configureDatabase

View File

@ -3,11 +3,11 @@ package com.r3corda.node.services
import com.r3corda.contracts.testing.fillWithSomeTestCash
import com.r3corda.core.contracts.DOLLARS
import com.r3corda.core.node.services.TxWritableStorageService
import com.r3corda.core.node.services.WalletService
import com.r3corda.core.node.services.VaultService
import com.r3corda.core.transactions.SignedTransaction
import com.r3corda.core.utilities.DUMMY_NOTARY
import com.r3corda.core.utilities.LogHelper
import com.r3corda.node.services.wallet.NodeWalletService
import com.r3corda.node.services.vault.NodeVaultService
import com.r3corda.node.utilities.configureDatabase
import com.r3corda.node.utilities.databaseTransaction
import com.r3corda.testing.node.MockServices
@ -19,42 +19,42 @@ import org.junit.Test
import java.io.Closeable
import java.util.*
class NodeWalletServiceTest {
class NodeVaultServiceTest {
lateinit var dataSource: Closeable
@Before
fun setUp() {
LogHelper.setLevel(NodeWalletService::class)
LogHelper.setLevel(NodeVaultService::class)
dataSource = configureDatabase(makeTestDataSourceProperties()).first
}
@After
fun tearDown() {
dataSource.close()
LogHelper.reset(NodeWalletService::class)
LogHelper.reset(NodeVaultService::class)
}
@Test
fun `states not local to instance`() {
databaseTransaction {
val services1 = object : MockServices() {
override val walletService: WalletService = NodeWalletService(this)
override val vaultService: VaultService = NodeVaultService(this)
override fun recordTransactions(txs: Iterable<SignedTransaction>) {
for (stx in txs) {
storageService.validatedTransactions.addTransaction(stx)
walletService.notify(stx.tx)
vaultService.notify(stx.tx)
}
}
}
services1.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L))
val w1 = services1.walletService.currentWallet
val w1 = services1.vaultService.currentVault
assertThat(w1.states).hasSize(3)
val originalStorage = services1.storageService
val services2 = object : MockServices() {
override val walletService: WalletService = NodeWalletService(this)
override val vaultService: VaultService = NodeVaultService(this)
// We need to be able to find the same transactions as before, too.
override val storageService: TxWritableStorageService get() = originalStorage
@ -62,12 +62,12 @@ class NodeWalletServiceTest {
override fun recordTransactions(txs: Iterable<SignedTransaction>) {
for (stx in txs) {
storageService.validatedTransactions.addTransaction(stx)
walletService.notify(stx.tx)
vaultService.notify(stx.tx)
}
}
}
val w2 = services2.walletService.currentWallet
val w2 = services2.vaultService.currentVault
assertThat(w2.states).hasSize(3)
}
}

View File

@ -5,12 +5,12 @@ import com.r3corda.contracts.asset.DUMMY_CASH_ISSUER
import com.r3corda.contracts.asset.cashBalances
import com.r3corda.contracts.testing.fillWithSomeTestCash
import com.r3corda.core.contracts.*
import com.r3corda.core.node.services.WalletService
import com.r3corda.core.node.services.VaultService
import com.r3corda.core.transactions.SignedTransaction
import com.r3corda.core.utilities.DUMMY_NOTARY
import com.r3corda.core.utilities.DUMMY_NOTARY_KEY
import com.r3corda.core.utilities.LogHelper
import com.r3corda.node.services.wallet.NodeWalletService
import com.r3corda.node.services.vault.NodeVaultService
import com.r3corda.node.utilities.configureDatabase
import com.r3corda.node.utilities.databaseTransaction
import com.r3corda.testing.*
@ -27,25 +27,25 @@ import kotlin.test.assertNull
// TODO: Move this to the cash contract tests once mock services are further split up.
class WalletWithCashTest {
class VaultWithCashTest {
lateinit var services: MockServices
val wallet: WalletService get() = services.walletService
val vault: VaultService get() = services.vaultService
lateinit var dataSource: Closeable
@Before
fun setUp() {
LogHelper.setLevel(NodeWalletService::class)
LogHelper.setLevel(NodeVaultService::class)
dataSource = configureDatabase(makeTestDataSourceProperties()).first
databaseTransaction {
services = object : MockServices() {
override val walletService: WalletService = NodeWalletService(this)
override val vaultService: VaultService = NodeVaultService(this)
override fun recordTransactions(txs: Iterable<SignedTransaction>) {
for (stx in txs) {
storageService.validatedTransactions.addTransaction(stx)
}
// Refactored to use notifyAll() as we have no other unit test for that method with multiple transactions.
walletService.notifyAll(txs.map { it.tx })
vaultService.notifyAll(txs.map { it.tx })
}
}
}
@ -53,7 +53,7 @@ class WalletWithCashTest {
@After
fun tearDown() {
LogHelper.reset(NodeWalletService::class)
LogHelper.reset(NodeVaultService::class)
dataSource.close()
}
@ -63,7 +63,7 @@ class WalletWithCashTest {
// Fix the PRNG so that we get the same splits every time.
services.fillWithSomeTestCash(100.DOLLARS, DUMMY_NOTARY, 3, 3, Random(0L))
val w = wallet.currentWallet
val w = vault.currentVault
assertEquals(3, w.states.toList().size)
val state = w.states.toList()[0].state.data as Cash.State
@ -100,14 +100,14 @@ class WalletWithCashTest {
signWith(DUMMY_NOTARY_KEY)
}.toSignedTransaction()
assertNull(wallet.currentWallet.cashBalances[USD])
assertNull(vault.currentVault.cashBalances[USD])
services.recordTransactions(usefulTX)
assertEquals(100.DOLLARS, wallet.currentWallet.cashBalances[USD])
assertEquals(100.DOLLARS, vault.currentVault.cashBalances[USD])
services.recordTransactions(irrelevantTX)
assertEquals(100.DOLLARS, wallet.currentWallet.cashBalances[USD])
assertEquals(100.DOLLARS, vault.currentVault.cashBalances[USD])
services.recordTransactions(spendTX)
assertEquals(20.DOLLARS, wallet.currentWallet.cashBalances[USD])
assertEquals(20.DOLLARS, vault.currentVault.cashBalances[USD])
// TODO: Flesh out these tests as needed.
}
@ -151,7 +151,7 @@ class WalletWithCashTest {
dummyIssue.toLedgerTransaction(services).verify()
services.recordTransactions(dummyIssue)
assertEquals(1, wallet.currentWallet.states.toList().size)
assertEquals(1, vault.currentVault.states.toList().size)
// Move the same state
val dummyMove = TransactionType.General.Builder(notary = DUMMY_NOTARY).apply {
@ -163,7 +163,7 @@ class WalletWithCashTest {
dummyIssue.toLedgerTransaction(services).verify()
services.recordTransactions(dummyMove)
assertEquals(1, wallet.currentWallet.states.toList().size)
assertEquals(1, vault.currentVault.states.toList().size)
}
}
}

View File

@ -6,7 +6,7 @@ import com.r3corda.core.contracts.*
import com.r3corda.core.crypto.SecureHash
import com.r3corda.core.crypto.newSecureRandom
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.node.services.Wallet
import com.r3corda.core.node.services.Vault
import com.r3corda.core.random63BitValue
import com.r3corda.core.serialization.OpaqueBytes
import com.r3corda.core.serialization.deserialize
@ -77,8 +77,8 @@ class WalletMonitorServiceTests {
val (monitorServiceNode, registerNode) = network.createTwoNodes()
val sessionID = authenticate(monitorServiceNode, registerNode)
var receivePsm = receiveWalletUpdate(registerNode, sessionID)
var expected = Wallet.Update(emptySet(), emptySet())
monitorServiceNode.inNodeWalletMonitorService!!.notifyWalletUpdate(expected)
var expected = Vault.Update(emptySet(), emptySet())
monitorServiceNode.inNodeWalletMonitorService!!.notifyVaultUpdate(expected)
network.runNetwork()
var actual = receivePsm.get(1, TimeUnit.SECONDS)
assertEquals(expected.consumed, actual.consumed)
@ -89,8 +89,8 @@ class WalletMonitorServiceTests {
val consumed = setOf(StateRef(SecureHash.randomSHA256(), 0))
val producedState = TransactionState(DummyContract.SingleOwnerState(newSecureRandom().nextInt(), DUMMY_PUBKEY_1), DUMMY_NOTARY)
val produced = setOf(StateAndRef(producedState, StateRef(SecureHash.randomSHA256(), 0)))
expected = Wallet.Update(consumed, produced)
monitorServiceNode.inNodeWalletMonitorService!!.notifyWalletUpdate(expected)
expected = Vault.Update(consumed, produced)
monitorServiceNode.inNodeWalletMonitorService!!.notifyVaultUpdate(expected)
network.runNetwork()
actual = receivePsm.get(1, TimeUnit.SECONDS)
assertEquals(expected.produced, actual.produced)
@ -110,7 +110,7 @@ class WalletMonitorServiceTests {
}
// Check the monitoring service wallet is empty
assertFalse(monitorServiceNode.services.walletService.currentWallet.states.iterator().hasNext())
assertFalse(monitorServiceNode.services.vaultService.currentVault.states.iterator().hasNext())
// Tell the monitoring service node to issue some cash
val recipient = monitorServiceNode.services.storageService.myLegalIdentity

View File

@ -25,8 +25,8 @@ class DataVendingServiceTests {
@Test
fun `notify of transaction`() {
val (walletServiceNode, registerNode) = network.createTwoNodes()
val beneficiary = walletServiceNode.services.storageService.myLegalIdentityKey.public
val (vaultServiceNode, registerNode) = network.createTwoNodes()
val beneficiary = vaultServiceNode.services.storageService.myLegalIdentityKey.public
val deposit = registerNode.services.storageService.myLegalIdentity.ref(1)
network.runNetwork()
@ -37,13 +37,13 @@ class DataVendingServiceTests {
// Complete the cash transaction, and then manually relay it
ptx.signWith(registerNode.services.storageService.myLegalIdentityKey)
val tx = ptx.toSignedTransaction()
assertEquals(0, walletServiceNode.services.walletService.currentWallet.states.toList().size)
assertEquals(0, vaultServiceNode.services.vaultService.currentVault.states.toList().size)
DataVending.Service.notify(registerNode.net, registerNode.services.storageService.myLegalIdentity,
walletServiceNode.info, tx)
vaultServiceNode.info, tx)
network.runNetwork()
// Check the transaction is in the receiving node
val actual = walletServiceNode.services.walletService.currentWallet.states.singleOrNull()
val actual = vaultServiceNode.services.vaultService.currentVault.states.singleOrNull()
val expected = tx.tx.outRef<Cash.State>(0)
assertEquals(expected, actual)
@ -54,8 +54,8 @@ class DataVendingServiceTests {
*/
@Test
fun `notify failure`() {
val (walletServiceNode, registerNode) = network.createTwoNodes()
val beneficiary = walletServiceNode.services.storageService.myLegalIdentityKey.public
val (vaultServiceNode, registerNode) = network.createTwoNodes()
val beneficiary = vaultServiceNode.services.storageService.myLegalIdentityKey.public
val deposit = MEGA_CORP.ref(1)
network.runNetwork()
@ -66,12 +66,12 @@ class DataVendingServiceTests {
// The transaction tries issuing MEGA_CORP cash, but we aren't the issuer, so it's invalid
ptx.signWith(registerNode.services.storageService.myLegalIdentityKey)
val tx = ptx.toSignedTransaction(false)
assertEquals(0, walletServiceNode.services.walletService.currentWallet.states.toList().size)
assertEquals(0, vaultServiceNode.services.vaultService.currentVault.states.toList().size)
DataVending.Service.notify(registerNode.net, registerNode.services.storageService.myLegalIdentity,
walletServiceNode.info, tx)
vaultServiceNode.info, tx)
network.runNetwork()
// Check the transaction is not in the receiving node
assertEquals(0, walletServiceNode.services.walletService.currentWallet.states.toList().size)
assertEquals(0, vaultServiceNode.services.vaultService.currentVault.states.toList().size)
}
}