CORDA-654 MockServices no longer has hard-coded identities (#2192)

* Resurrect a test
* Fix a broken test
* Pass in the initial identity
* Make IdentityService easier to mock
This commit is contained in:
Andrzej Cichocki 2017-12-07 11:55:18 +00:00 committed by GitHub
parent eb3b816d90
commit c36bea3af5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 168 additions and 120 deletions

View File

@ -1,13 +1,14 @@
package net.corda.core.contracts package net.corda.core.contracts
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.cordapp.CordappProvider
import net.corda.core.crypto.SecureHash import net.corda.core.crypto.SecureHash
import net.corda.core.internal.UpgradeCommand import net.corda.core.internal.UpgradeCommand
import net.corda.testing.ALICE import net.corda.core.node.ServicesForResolution
import net.corda.testing.DUMMY_NOTARY import net.corda.testing.*
import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyContractV2 import net.corda.testing.contracts.DummyContractV2
import net.corda.testing.node.MockServices
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
@ -23,7 +24,9 @@ class DummyContractV2Tests {
@Test @Test
fun `upgrade from v1`() { fun `upgrade from v1`() {
val services = MockServices() val services = rigorousMock<ServicesForResolution>().also {
doReturn(rigorousMock<CordappProvider>()).whenever(it).cordappProvider
}
val contractUpgrade = DummyContractV2() val contractUpgrade = DummyContractV2()
val v1State = TransactionState(DummyContract.SingleOwnerState(0, ALICE), DummyContract.PROGRAM_ID, DUMMY_NOTARY, constraint = AlwaysAcceptAttachmentConstraint) val v1State = TransactionState(DummyContract.SingleOwnerState(0, ALICE), DummyContract.PROGRAM_ID, DUMMY_NOTARY, constraint = AlwaysAcceptAttachmentConstraint)
val v1Ref = StateRef(SecureHash.randomSHA256(), 0) val v1Ref = StateRef(SecureHash.randomSHA256(), 0)

View File

@ -129,7 +129,7 @@ class CollectSignaturesFlowTests {
@Test @Test
fun `fails when not signed by initiator`() { fun `fails when not signed by initiator`() {
val onePartyDummyContract = DummyContract.generateInitial(1337, notary, alice.ref(1)) val onePartyDummyContract = DummyContract.generateInitial(1337, notary, alice.ref(1))
val miniCorpServices = MockServices(listOf("net.corda.testing.contracts"), MINI_CORP.name, MINI_CORP_KEY) val miniCorpServices = MockServices(listOf("net.corda.testing.contracts"), rigorousMock(), MINI_CORP.name, MINI_CORP_KEY)
val ptx = miniCorpServices.signInitialTransaction(onePartyDummyContract) val ptx = miniCorpServices.signInitialTransaction(onePartyDummyContract)
val flow = aliceNode.services.startFlow(CollectSignaturesFlow(ptx, emptySet())) val flow = aliceNode.services.startFlow(CollectSignaturesFlow(ptx, emptySet()))
mockNet.runNetwork() mockNet.runNetwork()

View File

@ -49,9 +49,8 @@ class TransactionSerializationTests {
val inputState = StateAndRef(TransactionState(TestCash.State(depositRef, 100.POUNDS, MEGA_CORP), TEST_CASH_PROGRAM_ID, DUMMY_NOTARY), fakeStateRef) val inputState = StateAndRef(TransactionState(TestCash.State(depositRef, 100.POUNDS, MEGA_CORP), TEST_CASH_PROGRAM_ID, DUMMY_NOTARY), fakeStateRef)
val outputState = TransactionState(TestCash.State(depositRef, 600.POUNDS, MEGA_CORP), TEST_CASH_PROGRAM_ID, DUMMY_NOTARY) val outputState = TransactionState(TestCash.State(depositRef, 600.POUNDS, MEGA_CORP), TEST_CASH_PROGRAM_ID, DUMMY_NOTARY)
val changeState = TransactionState(TestCash.State(depositRef, 400.POUNDS, MEGA_CORP), TEST_CASH_PROGRAM_ID, DUMMY_NOTARY) val changeState = TransactionState(TestCash.State(depositRef, 400.POUNDS, MEGA_CORP), TEST_CASH_PROGRAM_ID, DUMMY_NOTARY)
val megaCorpServices = MockServices(listOf("net.corda.core.serialization"), rigorousMock(), MEGA_CORP.name, MEGA_CORP_KEY)
val megaCorpServices = MockServices(listOf("net.corda.core.serialization"), MEGA_CORP.name, MEGA_CORP_KEY) val notaryServices = MockServices(listOf("net.corda.core.serialization"), rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
val notaryServices = MockServices(listOf("net.corda.core.serialization"), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
lateinit var tx: TransactionBuilder lateinit var tx: TransactionBuilder
@Before @Before
@ -95,7 +94,7 @@ class TransactionSerializationTests {
Command(TestCash.Commands.Move(), DUMMY_KEY_2.public)) Command(TestCash.Commands.Move(), DUMMY_KEY_2.public))
val ptx2 = notaryServices.signInitialTransaction(tx2) val ptx2 = notaryServices.signInitialTransaction(tx2)
val dummyServices = MockServices(DUMMY_KEY_2) val dummyServices = MockServices(rigorousMock(), MEGA_CORP.name, DUMMY_KEY_2)
val stx2 = dummyServices.addSignature(ptx2) val stx2 = dummyServices.addSignature(ptx2)
stx.copy(sigs = stx2.sigs).verifyRequiredSignatures() stx.copy(sigs = stx2.sigs).verifyRequiredSignatures()

View File

@ -1,14 +1,15 @@
package net.corda.core.transactions package net.corda.core.transactions
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.* import net.corda.core.contracts.*
import net.corda.core.crypto.generateKeyPair
import net.corda.core.identity.AbstractParty import net.corda.core.identity.AbstractParty
import net.corda.core.identity.Party import net.corda.core.identity.Party
import net.corda.testing.DUMMY_NOTARY import net.corda.node.services.api.IdentityServiceInternal
import net.corda.testing.SerializationEnvironmentRule import net.corda.testing.*
import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyContract
import net.corda.testing.dummyCommand
import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices
import net.corda.testing.singleIdentity
import org.junit.Before import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@ -21,7 +22,10 @@ class LedgerTransactionQueryTests {
@Rule @Rule
@JvmField @JvmField
val testSerialization = SerializationEnvironmentRule() val testSerialization = SerializationEnvironmentRule()
private val services: MockServices = MockServices() private val keyPair = generateKeyPair()
private val services = MockServices(rigorousMock<IdentityServiceInternal>().also {
doReturn(null).whenever(it).partyFromKey(keyPair.public)
}, MEGA_CORP.name, keyPair)
private val identity: Party = services.myInfo.singleIdentity() private val identity: Party = services.myInfo.singleIdentity()
@Before @Before

View File

@ -17,7 +17,6 @@ import net.corda.testing.contracts.VaultFiller
import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices
import net.corda.testing.node.MockServices.Companion.makeTestDatabaseAndMockServices import net.corda.testing.node.MockServices.Companion.makeTestDatabaseAndMockServices
import net.corda.testing.node.makeTestIdentityService import net.corda.testing.node.makeTestIdentityService
import org.junit.Ignore
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
@ -224,19 +223,16 @@ class CommercialPaperTestsGeneric {
private lateinit var aliceServices: MockServices private lateinit var aliceServices: MockServices
private lateinit var aliceVaultService: VaultService private lateinit var aliceVaultService: VaultService
private lateinit var alicesVault: Vault<ContractState> private lateinit var alicesVault: Vault<ContractState>
private val notaryServices = MockServices(rigorousMock(), MEGA_CORP.name, DUMMY_NOTARY_KEY)
private val notaryServices = MockServices(DUMMY_NOTARY_KEY) private val issuerServices = MockServices(listOf("net.corda.finance.contracts"), rigorousMock(), MEGA_CORP.name, DUMMY_CASH_ISSUER_KEY)
private val issuerServices = MockServices(DUMMY_CASH_ISSUER_KEY)
private lateinit var moveTX: SignedTransaction private lateinit var moveTX: SignedTransaction
@Test
// @Test fun `issue move and then redeem`() {
@Ignore
fun `issue move and then redeem`() = withTestSerialization {
val aliceDatabaseAndServices = makeTestDatabaseAndMockServices( val aliceDatabaseAndServices = makeTestDatabaseAndMockServices(
listOf(ALICE_KEY), listOf(ALICE_KEY),
makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)), makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)),
initialIdentityName = MEGA_CORP.name) listOf("net.corda.finance.contracts"),
MEGA_CORP.name)
val databaseAlice = aliceDatabaseAndServices.first val databaseAlice = aliceDatabaseAndServices.first
aliceServices = aliceDatabaseAndServices.second aliceServices = aliceDatabaseAndServices.second
aliceVaultService = aliceServices.vaultService aliceVaultService = aliceServices.vaultService
@ -248,7 +244,8 @@ class CommercialPaperTestsGeneric {
val bigCorpDatabaseAndServices = makeTestDatabaseAndMockServices( val bigCorpDatabaseAndServices = makeTestDatabaseAndMockServices(
listOf(BIG_CORP_KEY), listOf(BIG_CORP_KEY),
makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)), makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)),
initialIdentityName = MEGA_CORP.name) listOf("net.corda.finance.contracts"),
MEGA_CORP.name)
val databaseBigCorp = bigCorpDatabaseAndServices.first val databaseBigCorp = bigCorpDatabaseAndServices.first
bigCorpServices = bigCorpDatabaseAndServices.second bigCorpServices = bigCorpDatabaseAndServices.second
bigCorpVaultService = bigCorpServices.vaultService bigCorpVaultService = bigCorpServices.vaultService

View File

@ -1,5 +1,6 @@
package net.corda.finance.contracts.asset package net.corda.finance.contracts.asset
import com.nhaarman.mockito_kotlin.*
import net.corda.core.contracts.* import net.corda.core.contracts.*
import net.corda.core.crypto.SecureHash import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.generateKeyPair import net.corda.core.crypto.generateKeyPair
@ -18,6 +19,7 @@ import net.corda.finance.utils.sumCash
import net.corda.finance.utils.sumCashBy import net.corda.finance.utils.sumCashBy
import net.corda.finance.utils.sumCashOrNull import net.corda.finance.utils.sumCashOrNull
import net.corda.finance.utils.sumCashOrZero import net.corda.finance.utils.sumCashOrZero
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.node.services.vault.NodeVaultService import net.corda.node.services.vault.NodeVaultService
import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.testing.* import net.corda.testing.*
@ -67,9 +69,11 @@ class CashTests {
@Before @Before
fun setUp() { fun setUp() {
LogHelper.setLevel(NodeVaultService::class) LogHelper.setLevel(NodeVaultService::class)
megaCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), MEGA_CORP.name, MEGA_CORP_KEY) megaCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock(), MEGA_CORP.name, MEGA_CORP_KEY)
miniCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), MINI_CORP.name, MINI_CORP_KEY) miniCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock<IdentityServiceInternal>().also {
val notaryServices = MockServices(listOf("net.corda.finance.contracts.asset"), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY) doNothing().whenever(it).justVerifyAndRegisterIdentity(argThat { name == MINI_CORP.name })
}, MINI_CORP.name, MINI_CORP_KEY)
val notaryServices = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
val databaseAndServices = makeTestDatabaseAndMockServices( val databaseAndServices = makeTestDatabaseAndMockServices(
listOf(generateKeyPair()), listOf(generateKeyPair()),
makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)), makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)),
@ -774,8 +778,9 @@ class CashTests {
// Double spend. // Double spend.
@Test @Test
fun chainCashDoubleSpendFailsWith() { fun chainCashDoubleSpendFailsWith() {
val mockService = MockServices(listOf("net.corda.finance.contracts.asset"), MEGA_CORP.name, MEGA_CORP_KEY) val mockService = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock<IdentityServiceInternal>().also {
doReturn(MEGA_CORP).whenever(it).partyFromKey(MEGA_CORP_PUBKEY)
}, MEGA_CORP.name, MEGA_CORP_KEY)
ledger(mockService) { ledger(mockService) {
unverifiedTransaction { unverifiedTransaction {
attachment(Cash.PROGRAM_ID) attachment(Cash.PROGRAM_ID)

View File

@ -1,5 +1,7 @@
package net.corda.finance.contracts.asset package net.corda.finance.contracts.asset
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.* import net.corda.core.contracts.*
import net.corda.core.crypto.NullKeys.NULL_PARTY import net.corda.core.crypto.NullKeys.NULL_PARTY
import net.corda.core.crypto.SecureHash import net.corda.core.crypto.SecureHash
@ -15,6 +17,7 @@ import net.corda.finance.*
import net.corda.finance.contracts.Commodity import net.corda.finance.contracts.Commodity
import net.corda.finance.contracts.NetType import net.corda.finance.contracts.NetType
import net.corda.finance.contracts.asset.Obligation.Lifecycle import net.corda.finance.contracts.asset.Obligation.Lifecycle
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.testing.* import net.corda.testing.*
import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyState import net.corda.testing.contracts.DummyState
@ -51,9 +54,13 @@ class ObligationTests {
beneficiary = CHARLIE beneficiary = CHARLIE
) )
private val outState = inState.copy(beneficiary = AnonymousParty(BOB_PUBKEY)) private val outState = inState.copy(beneficiary = AnonymousParty(BOB_PUBKEY))
private val miniCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), MINI_CORP.name, MINI_CORP_KEY) private val miniCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock(), MINI_CORP.name, MINI_CORP_KEY)
private val notaryServices = MockServices(DUMMY_NOTARY_KEY) private val notaryServices = MockServices(rigorousMock(), MEGA_CORP.name, DUMMY_NOTARY_KEY)
private val mockService = MockServices(listOf("net.corda.finance.contracts.asset")) private val mockService = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock<IdentityServiceInternal>().also {
doReturn(null).whenever(it).partyFromKey(ALICE_PUBKEY)
doReturn(null).whenever(it).partyFromKey(BOB_PUBKEY)
doReturn(MEGA_CORP).whenever(it).partyFromKey(MEGA_CORP_PUBKEY)
}, MEGA_CORP.name)
private fun cashObligationTestRoots( private fun cashObligationTestRoots(
group: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter> group: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>

View File

@ -2,7 +2,7 @@ package net.corda.nodeapi.internal.serialization
import net.corda.core.contracts.ContractAttachment import net.corda.core.contracts.ContractAttachment
import net.corda.core.serialization.* import net.corda.core.serialization.*
import net.corda.testing.SerializationEnvironmentRule import net.corda.testing.*
import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyContract
import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
@ -22,9 +22,7 @@ class ContractAttachmentSerializerTest {
private lateinit var factory: SerializationFactory private lateinit var factory: SerializationFactory
private lateinit var context: SerializationContext private lateinit var context: SerializationContext
private lateinit var contextWithToken: SerializationContext private lateinit var contextWithToken: SerializationContext
private val mockServices = MockServices(rigorousMock(), MEGA_CORP.name)
private val mockServices = MockServices()
@Before @Before
fun setup() { fun setup() {
factory = testSerialization.env.serializationFactory factory = testSerialization.env.serializationFactory

View File

@ -46,6 +46,7 @@ import net.corda.node.services.config.NotaryConfig
import net.corda.node.services.config.configureWithDevSSLCertificate import net.corda.node.services.config.configureWithDevSSLCertificate
import net.corda.node.services.events.NodeSchedulerService import net.corda.node.services.events.NodeSchedulerService
import net.corda.node.services.events.ScheduledActivityObserver import net.corda.node.services.events.ScheduledActivityObserver
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.node.services.identity.PersistentIdentityService import net.corda.node.services.identity.PersistentIdentityService
import net.corda.node.services.keys.PersistentKeyManagementService import net.corda.node.services.keys.PersistentKeyManagementService
import net.corda.node.services.messaging.MessagingService import net.corda.node.services.messaging.MessagingService
@ -497,7 +498,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration,
* Builds node internal, advertised, and plugin services. * Builds node internal, advertised, and plugin services.
* Returns a list of tokenizable services to be added to the serialisation context. * Returns a list of tokenizable services to be added to the serialisation context.
*/ */
private fun makeServices(keyPairs: Set<KeyPair>, schemaService: SchemaService, transactionStorage: WritableTransactionStorage, database: CordaPersistence, info: NodeInfo, identityService: IdentityService): MutableList<Any> { private fun makeServices(keyPairs: Set<KeyPair>, schemaService: SchemaService, transactionStorage: WritableTransactionStorage, database: CordaPersistence, info: NodeInfo, identityService: IdentityServiceInternal): MutableList<Any> {
checkpointStorage = DBCheckpointStorage() checkpointStorage = DBCheckpointStorage()
val metrics = MetricRegistry() val metrics = MetricRegistry()
attachments = NodeAttachmentService(metrics) attachments = NodeAttachmentService(metrics)
@ -591,7 +592,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration,
} }
} }
protected open fun makeKeyManagementService(identityService: IdentityService, keyPairs: Set<KeyPair>): KeyManagementService { protected open fun makeKeyManagementService(identityService: IdentityServiceInternal, keyPairs: Set<KeyPair>): KeyManagementService {
return PersistentKeyManagementService(identityService, keyPairs) return PersistentKeyManagementService(identityService, keyPairs)
} }

View File

@ -0,0 +1,11 @@
package net.corda.node.services.api
import net.corda.core.identity.PartyAndCertificate
import net.corda.core.node.services.IdentityService
interface IdentityServiceInternal : IdentityService {
/** This method exists so it can be mocked with doNothing, rather than having to make up a possibly invalid return value. */
fun justVerifyAndRegisterIdentity(identity: PartyAndCertificate) {
verifyAndRegisterIdentity(identity)
}
}

View File

@ -5,11 +5,11 @@ import net.corda.core.crypto.toStringShort
import net.corda.core.identity.* import net.corda.core.identity.*
import net.corda.core.internal.cert import net.corda.core.internal.cert
import net.corda.core.internal.toX509CertHolder import net.corda.core.internal.toX509CertHolder
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.UnknownAnonymousPartyException import net.corda.core.node.services.UnknownAnonymousPartyException
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.utilities.contextLogger import net.corda.core.utilities.contextLogger
import net.corda.core.utilities.trace import net.corda.core.utilities.trace
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.nodeapi.internal.crypto.X509CertificateFactory import net.corda.nodeapi.internal.crypto.X509CertificateFactory
import org.bouncycastle.cert.X509CertificateHolder import org.bouncycastle.cert.X509CertificateHolder
import java.security.InvalidAlgorithmParameterException import java.security.InvalidAlgorithmParameterException
@ -25,7 +25,7 @@ import javax.annotation.concurrent.ThreadSafe
*/ */
@ThreadSafe @ThreadSafe
class InMemoryIdentityService(identities: Iterable<PartyAndCertificate>, class InMemoryIdentityService(identities: Iterable<PartyAndCertificate>,
trustRoot: X509CertificateHolder) : SingletonSerializeAsToken(), IdentityService { trustRoot: X509CertificateHolder) : SingletonSerializeAsToken(), IdentityServiceInternal {
companion object { companion object {
private val log = contextLogger() private val log = contextLogger()
} }

View File

@ -6,12 +6,12 @@ import net.corda.core.crypto.toStringShort
import net.corda.core.identity.* import net.corda.core.identity.*
import net.corda.core.internal.cert import net.corda.core.internal.cert
import net.corda.core.internal.toX509CertHolder import net.corda.core.internal.toX509CertHolder
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.UnknownAnonymousPartyException import net.corda.core.node.services.UnknownAnonymousPartyException
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.utilities.MAX_HASH_HEX_SIZE import net.corda.core.utilities.MAX_HASH_HEX_SIZE
import net.corda.core.utilities.contextLogger import net.corda.core.utilities.contextLogger
import net.corda.core.utilities.debug import net.corda.core.utilities.debug
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.node.utilities.AppendOnlyPersistentMap import net.corda.node.utilities.AppendOnlyPersistentMap
import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX
import net.corda.nodeapi.internal.crypto.X509CertificateFactory import net.corda.nodeapi.internal.crypto.X509CertificateFactory
@ -27,7 +27,7 @@ import javax.persistence.Lob
@ThreadSafe @ThreadSafe
class PersistentIdentityService(override val trustRoot: X509Certificate, class PersistentIdentityService(override val trustRoot: X509Certificate,
vararg caCertificates: X509Certificate) : SingletonSerializeAsToken(), IdentityService { vararg caCertificates: X509Certificate) : SingletonSerializeAsToken(), IdentityServiceInternal {
constructor(trustRoot: X509CertificateHolder) : this(trustRoot.cert) constructor(trustRoot: X509CertificateHolder) : this(trustRoot.cert)
companion object { companion object {

View File

@ -3,9 +3,9 @@ package net.corda.node.services.keys
import net.corda.core.crypto.* import net.corda.core.crypto.*
import net.corda.core.identity.PartyAndCertificate import net.corda.core.identity.PartyAndCertificate
import net.corda.core.internal.ThreadBox import net.corda.core.internal.ThreadBox
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.KeyManagementService import net.corda.core.node.services.KeyManagementService
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.node.services.api.IdentityServiceInternal
import org.bouncycastle.operator.ContentSigner import org.bouncycastle.operator.ContentSigner
import java.security.KeyPair import java.security.KeyPair
import java.security.PrivateKey import java.security.PrivateKey
@ -25,7 +25,7 @@ import javax.annotation.concurrent.ThreadSafe
* etc. * etc.
*/ */
@ThreadSafe @ThreadSafe
class E2ETestKeyManagementService(val identityService: IdentityService, class E2ETestKeyManagementService(val identityService: IdentityServiceInternal,
initialKeys: Set<KeyPair>) : SingletonSerializeAsToken(), KeyManagementService { initialKeys: Set<KeyPair>) : SingletonSerializeAsToken(), KeyManagementService {
private class InnerState { private class InnerState {
val keys = HashMap<PublicKey, PrivateKey>() val keys = HashMap<PublicKey, PrivateKey>()

View File

@ -4,8 +4,8 @@ import net.corda.core.crypto.Crypto
import net.corda.core.identity.PartyAndCertificate import net.corda.core.identity.PartyAndCertificate
import net.corda.core.internal.cert import net.corda.core.internal.cert
import net.corda.core.internal.toX509CertHolder import net.corda.core.internal.toX509CertHolder
import net.corda.core.node.services.IdentityService
import net.corda.core.utilities.days import net.corda.core.utilities.days
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.nodeapi.internal.crypto.CertificateType import net.corda.nodeapi.internal.crypto.CertificateType
import net.corda.nodeapi.internal.crypto.ContentSignerBuilder import net.corda.nodeapi.internal.crypto.ContentSignerBuilder
import net.corda.nodeapi.internal.crypto.X509CertificateFactory import net.corda.nodeapi.internal.crypto.X509CertificateFactory
@ -28,7 +28,7 @@ import java.time.Duration
* @param revocationEnabled whether to check revocation status of certificates in the certificate path. * @param revocationEnabled whether to check revocation status of certificates in the certificate path.
* @return X.509 certificate and path to the trust root. * @return X.509 certificate and path to the trust root.
*/ */
fun freshCertificate(identityService: IdentityService, fun freshCertificate(identityService: IdentityServiceInternal,
subjectPublicKey: PublicKey, subjectPublicKey: PublicKey,
issuer: PartyAndCertificate, issuer: PartyAndCertificate,
issuerSigner: ContentSigner, issuerSigner: ContentSigner,
@ -39,7 +39,7 @@ fun freshCertificate(identityService: IdentityService,
issuerSigner, issuer.name, subjectPublicKey, window) issuerSigner, issuer.name, subjectPublicKey, window)
val ourCertPath = X509CertificateFactory().delegate.generateCertPath(listOf(ourCertificate.cert) + issuer.certPath.certificates) val ourCertPath = X509CertificateFactory().delegate.generateCertPath(listOf(ourCertificate.cert) + issuer.certPath.certificates)
val anonymisedIdentity = PartyAndCertificate(ourCertPath) val anonymisedIdentity = PartyAndCertificate(ourCertPath)
identityService.verifyAndRegisterIdentity(anonymisedIdentity) identityService.justVerifyAndRegisterIdentity(anonymisedIdentity)
return anonymisedIdentity return anonymisedIdentity
} }

View File

@ -2,10 +2,10 @@ package net.corda.node.services.keys
import net.corda.core.crypto.* import net.corda.core.crypto.*
import net.corda.core.identity.PartyAndCertificate import net.corda.core.identity.PartyAndCertificate
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.KeyManagementService import net.corda.core.node.services.KeyManagementService
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.utilities.MAX_HASH_HEX_SIZE import net.corda.core.utilities.MAX_HASH_HEX_SIZE
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.node.utilities.AppendOnlyPersistentMap import net.corda.node.utilities.AppendOnlyPersistentMap
import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX
import org.bouncycastle.operator.ContentSigner import org.bouncycastle.operator.ContentSigner
@ -24,7 +24,7 @@ import javax.persistence.Lob
* *
* This class needs database transactions to be in-flight during method calls and init. * This class needs database transactions to be in-flight during method calls and init.
*/ */
class PersistentKeyManagementService(val identityService: IdentityService, class PersistentKeyManagementService(val identityService: IdentityServiceInternal,
initialKeys: Set<KeyPair>) : SingletonSerializeAsToken(), KeyManagementService { initialKeys: Set<KeyPair>) : SingletonSerializeAsToken(), KeyManagementService {
@Entity @Entity

View File

@ -4,9 +4,9 @@ import com.google.common.collect.ImmutableSet;
import kotlin.Pair; import kotlin.Pair;
import kotlin.Triple; import kotlin.Triple;
import net.corda.core.contracts.*; import net.corda.core.contracts.*;
import net.corda.core.crypto.CryptoUtils;
import net.corda.core.identity.AbstractParty; import net.corda.core.identity.AbstractParty;
import net.corda.core.messaging.DataFeed; 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.Vault;
import net.corda.core.node.services.VaultQueryException; import net.corda.core.node.services.VaultQueryException;
import net.corda.core.node.services.VaultService; import net.corda.core.node.services.VaultService;
@ -14,11 +14,11 @@ import net.corda.core.node.services.vault.*;
import net.corda.core.node.services.vault.QueryCriteria.LinearStateQueryCriteria; 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.VaultCustomQueryCriteria;
import net.corda.core.node.services.vault.QueryCriteria.VaultQueryCriteria; import net.corda.core.node.services.vault.QueryCriteria.VaultQueryCriteria;
import net.corda.core.utilities.EncodingUtils;
import net.corda.core.utilities.OpaqueBytes; import net.corda.core.utilities.OpaqueBytes;
import net.corda.finance.contracts.DealState; import net.corda.finance.contracts.DealState;
import net.corda.finance.contracts.asset.Cash; import net.corda.finance.contracts.asset.Cash;
import net.corda.finance.schemas.CashSchemaV1; import net.corda.finance.schemas.CashSchemaV1;
import net.corda.node.services.api.IdentityServiceInternal;
import net.corda.nodeapi.internal.persistence.CordaPersistence; import net.corda.nodeapi.internal.persistence.CordaPersistence;
import net.corda.nodeapi.internal.persistence.DatabaseTransaction; import net.corda.nodeapi.internal.persistence.DatabaseTransaction;
import net.corda.testing.SerializationEnvironmentRule; import net.corda.testing.SerializationEnvironmentRule;
@ -61,13 +61,13 @@ public class VaultQueryJavaTests {
@Before @Before
public void setUp() throws CertificateException, InvalidAlgorithmParameterException { public void setUp() throws CertificateException, InvalidAlgorithmParameterException {
List<String> cordappPackages = Arrays.asList("net.corda.testing.contracts", "net.corda.finance.contracts.asset", CashSchemaV1.class.getPackage().getName()); List<String> cordappPackages = Arrays.asList("net.corda.testing.contracts", "net.corda.finance.contracts.asset", CashSchemaV1.class.getPackage().getName());
IdentityService identitySvc = makeTestIdentityService(Arrays.asList(getMEGA_CORP_IDENTITY(), getDUMMY_CASH_ISSUER_IDENTITY(), getDUMMY_NOTARY_IDENTITY())); IdentityServiceInternal identitySvc = makeTestIdentityService(Arrays.asList(getMEGA_CORP_IDENTITY(), getDUMMY_CASH_ISSUER_IDENTITY(), getDUMMY_NOTARY_IDENTITY()));
Pair<CordaPersistence, MockServices> databaseAndServices = makeTestDatabaseAndMockServices( Pair<CordaPersistence, MockServices> databaseAndServices = makeTestDatabaseAndMockServices(
Arrays.asList(getMEGA_CORP_KEY(), getDUMMY_NOTARY_KEY()), Arrays.asList(getMEGA_CORP_KEY(), getDUMMY_NOTARY_KEY()),
identitySvc, identitySvc,
cordappPackages, cordappPackages,
getMEGA_CORP().getName()); getMEGA_CORP().getName());
issuerServices = new MockServices(cordappPackages, getDUMMY_CASH_ISSUER_NAME(), getDUMMY_CASH_ISSUER_KEY(), getBOC_KEY()); issuerServices = new MockServices(cordappPackages, rigorousMock(IdentityServiceInternal.class), getDUMMY_CASH_ISSUER_NAME(), getDUMMY_CASH_ISSUER_KEY(), getBOC_KEY());
database = databaseAndServices.getFirst(); database = databaseAndServices.getFirst();
MockServices services = databaseAndServices.getSecond(); MockServices services = databaseAndServices.getSecond();
vaultFiller = new VaultFiller(services, getDUMMY_NOTARY(), getDUMMY_NOTARY_KEY()); vaultFiller = new VaultFiller(services, getDUMMY_NOTARY(), getDUMMY_NOTARY_KEY());
@ -449,30 +449,28 @@ public class VaultQueryJavaTests {
// DOCSTART VaultJavaQueryExample23 // DOCSTART VaultJavaQueryExample23
Field pennies = CashSchemaV1.PersistentCashState.class.getDeclaredField("pennies"); Field pennies = CashSchemaV1.PersistentCashState.class.getDeclaredField("pennies");
Field currency = CashSchemaV1.PersistentCashState.class.getDeclaredField("currency"); Field currency = CashSchemaV1.PersistentCashState.class.getDeclaredField("currency");
Field issuerParty = CashSchemaV1.PersistentCashState.class.getDeclaredField("issuerParty"); Field issuerPartyHash = CashSchemaV1.PersistentCashState.class.getDeclaredField("issuerPartyHash");
QueryCriteria sumCriteria = new VaultCustomQueryCriteria(Builder.sum(pennies, Arrays.asList(issuerPartyHash, currency), Sort.Direction.DESC));
QueryCriteria sumCriteria = new VaultCustomQueryCriteria(Builder.sum(pennies, Arrays.asList(issuerParty, currency), Sort.Direction.DESC));
Vault.Page<Cash.State> results = vaultService.queryBy(Cash.State.class, sumCriteria); Vault.Page<Cash.State> results = vaultService.queryBy(Cash.State.class, sumCriteria);
// DOCEND VaultJavaQueryExample23 // DOCEND VaultJavaQueryExample23
assertThat(results.getOtherResults()).hasSize(12); assertThat(results.getOtherResults()).hasSize(12);
assertThat(results.getOtherResults().get(0)).isEqualTo(400L); assertThat(results.getOtherResults().get(0)).isEqualTo(400L);
assertThat(results.getOtherResults().get(1)).isEqualTo(EncodingUtils.toBase58String(getBOC_PUBKEY())); assertThat(results.getOtherResults().get(1)).isEqualTo(CryptoUtils.toStringShort(getBOC_PUBKEY()));
assertThat(results.getOtherResults().get(2)).isEqualTo("GBP"); assertThat(results.getOtherResults().get(2)).isEqualTo("GBP");
assertThat(results.getOtherResults().get(3)).isEqualTo(300L); assertThat(results.getOtherResults().get(3)).isEqualTo(300L);
assertThat(results.getOtherResults().get(4)).isEqualTo(EncodingUtils.toBase58String(getDUMMY_CASH_ISSUER().getParty().getOwningKey())); assertThat(results.getOtherResults().get(4)).isEqualTo(CryptoUtils.toStringShort(getDUMMY_CASH_ISSUER().getParty().getOwningKey()));
assertThat(results.getOtherResults().get(5)).isEqualTo("GBP"); assertThat(results.getOtherResults().get(5)).isEqualTo("GBP");
assertThat(results.getOtherResults().get(6)).isEqualTo(200L); assertThat(results.getOtherResults().get(6)).isEqualTo(200L);
assertThat(results.getOtherResults().get(7)).isEqualTo(EncodingUtils.toBase58String(getBOC_PUBKEY())); assertThat(results.getOtherResults().get(7)).isEqualTo(CryptoUtils.toStringShort(getBOC_PUBKEY()));
assertThat(results.getOtherResults().get(8)).isEqualTo("USD"); assertThat(results.getOtherResults().get(8)).isEqualTo("USD");
assertThat(results.getOtherResults().get(9)).isEqualTo(100L); assertThat(results.getOtherResults().get(9)).isEqualTo(100L);
assertThat(results.getOtherResults().get(10)).isEqualTo(EncodingUtils.toBase58String(getDUMMY_CASH_ISSUER().getParty().getOwningKey())); assertThat(results.getOtherResults().get(10)).isEqualTo(CryptoUtils.toStringShort(getDUMMY_CASH_ISSUER().getParty().getOwningKey()));
assertThat(results.getOtherResults().get(11)).isEqualTo("USD"); assertThat(results.getOtherResults().get(11)).isEqualTo("USD");
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
e.printStackTrace(); throw new RuntimeException(e);
} }
return tx; return tx;
}); });

View File

@ -1,6 +1,8 @@
package net.corda.node.messaging package net.corda.node.messaging
import co.paralleluniverse.fibers.Suspendable import co.paralleluniverse.fibers.Suspendable
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.concurrent.CordaFuture import net.corda.core.concurrent.CordaFuture
import net.corda.core.contracts.* import net.corda.core.contracts.*
import net.corda.core.crypto.* import net.corda.core.crypto.*
@ -34,6 +36,7 @@ import net.corda.finance.flows.TwoPartyTradeFlow.Buyer
import net.corda.finance.flows.TwoPartyTradeFlow.Seller import net.corda.finance.flows.TwoPartyTradeFlow.Seller
import net.corda.node.internal.StartedNode import net.corda.node.internal.StartedNode
import net.corda.node.services.api.WritableTransactionStorage import net.corda.node.services.api.WritableTransactionStorage
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.node.services.persistence.DBTransactionStorage import net.corda.node.services.persistence.DBTransactionStorage
import net.corda.node.services.persistence.checkpoints import net.corda.node.services.persistence.checkpoints
import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.CordaPersistence
@ -90,13 +93,15 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
// we run in the unit test thread exclusively to speed things up, ensure deterministic results and // we run in the unit test thread exclusively to speed things up, ensure deterministic results and
// allow interruption half way through. // allow interruption half way through.
mockNet = MockNetwork(threadPerNode = true, cordappPackages = cordappPackages) mockNet = MockNetwork(threadPerNode = true, cordappPackages = cordappPackages)
ledger(MockServices(cordappPackages)) { val ledgerIdentityService = rigorousMock<IdentityServiceInternal>()
ledger(MockServices(cordappPackages, ledgerIdentityService, MEGA_CORP.name)) {
val notaryNode = mockNet.defaultNotaryNode val notaryNode = mockNet.defaultNotaryNode
val aliceNode = mockNet.createPartyNode(ALICE_NAME) val aliceNode = mockNet.createPartyNode(ALICE_NAME)
val bobNode = mockNet.createPartyNode(BOB_NAME) val bobNode = mockNet.createPartyNode(BOB_NAME)
val bankNode = mockNet.createPartyNode(BOC_NAME) val bankNode = mockNet.createPartyNode(BOC_NAME)
val alice = aliceNode.info.singleIdentity() val alice = aliceNode.info.singleIdentity()
val bank = bankNode.info.singleIdentity() val bank = bankNode.info.singleIdentity()
doReturn(null).whenever(ledgerIdentityService).partyFromKey(bank.owningKey)
val bob = bobNode.info.singleIdentity() val bob = bobNode.info.singleIdentity()
val notary = mockNet.defaultNotaryIdentity val notary = mockNet.defaultNotaryIdentity
val cashIssuer = bank.ref(1) val cashIssuer = bank.ref(1)
@ -140,13 +145,15 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
@Test(expected = InsufficientBalanceException::class) @Test(expected = InsufficientBalanceException::class)
fun `trade cash for commercial paper fails using soft locking`() { fun `trade cash for commercial paper fails using soft locking`() {
mockNet = MockNetwork(threadPerNode = true, cordappPackages = cordappPackages) mockNet = MockNetwork(threadPerNode = true, cordappPackages = cordappPackages)
ledger(MockServices(cordappPackages)) { val ledgerIdentityService = rigorousMock<IdentityServiceInternal>()
ledger(MockServices(cordappPackages, ledgerIdentityService, MEGA_CORP.name)) {
val notaryNode = mockNet.defaultNotaryNode val notaryNode = mockNet.defaultNotaryNode
val aliceNode = mockNet.createPartyNode(ALICE_NAME) val aliceNode = mockNet.createPartyNode(ALICE_NAME)
val bobNode = mockNet.createPartyNode(BOB_NAME) val bobNode = mockNet.createPartyNode(BOB_NAME)
val bankNode = mockNet.createPartyNode(BOC_NAME) val bankNode = mockNet.createPartyNode(BOC_NAME)
val alice = aliceNode.info.singleIdentity() val alice = aliceNode.info.singleIdentity()
val bank = bankNode.info.singleIdentity() val bank = bankNode.info.singleIdentity()
doReturn(null).whenever(ledgerIdentityService).partyFromKey(bank.owningKey)
val bob = bobNode.info.singleIdentity() val bob = bobNode.info.singleIdentity()
val issuer = bank.ref(1) val issuer = bank.ref(1)
val notary = mockNet.defaultNotaryIdentity val notary = mockNet.defaultNotaryIdentity
@ -196,7 +203,8 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
@Test @Test
fun `shutdown and restore`() { fun `shutdown and restore`() {
mockNet = MockNetwork(cordappPackages = cordappPackages) mockNet = MockNetwork(cordappPackages = cordappPackages)
ledger(MockServices(cordappPackages)) { val ledgerIdentityService = rigorousMock<IdentityServiceInternal>()
ledger(MockServices(cordappPackages, ledgerIdentityService, MEGA_CORP.name)) {
val notaryNode = mockNet.defaultNotaryNode val notaryNode = mockNet.defaultNotaryNode
val aliceNode = mockNet.createPartyNode(ALICE_NAME) val aliceNode = mockNet.createPartyNode(ALICE_NAME)
var bobNode = mockNet.createPartyNode(BOB_NAME) var bobNode = mockNet.createPartyNode(BOB_NAME)
@ -210,6 +218,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
val notary = mockNet.defaultNotaryIdentity val notary = mockNet.defaultNotaryIdentity
val alice = aliceNode.info.singleIdentity() val alice = aliceNode.info.singleIdentity()
val bank = bankNode.info.singleIdentity() val bank = bankNode.info.singleIdentity()
doReturn(null).whenever(ledgerIdentityService).partyFromKey(bank.owningKey)
val bob = bobNode.info.singleIdentity() val bob = bobNode.info.singleIdentity()
val issuer = bank.ref(1, 2, 3) val issuer = bank.ref(1, 2, 3)
@ -491,16 +500,18 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
@Test @Test
fun `dependency with error on buyer side`() { fun `dependency with error on buyer side`() {
mockNet = MockNetwork(cordappPackages = cordappPackages) mockNet = MockNetwork(cordappPackages = cordappPackages)
ledger(MockServices(cordappPackages)) { val ledgerIdentityService = rigorousMock<IdentityServiceInternal>()
runWithError(true, false, "at least one cash input") ledger(MockServices(cordappPackages, ledgerIdentityService, MEGA_CORP.name)) {
runWithError(ledgerIdentityService, true, false, "at least one cash input")
} }
} }
@Test @Test
fun `dependency with error on seller side`() { fun `dependency with error on seller side`() {
mockNet = MockNetwork(cordappPackages = cordappPackages) mockNet = MockNetwork(cordappPackages = cordappPackages)
ledger(MockServices(cordappPackages)) { val ledgerIdentityService = rigorousMock<IdentityServiceInternal>()
runWithError(false, true, "Issuances have a time-window") ledger(MockServices(cordappPackages, ledgerIdentityService, MEGA_CORP.name)) {
runWithError(ledgerIdentityService, false, true, "Issuances have a time-window")
} }
} }
@ -562,6 +573,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
data class TestTx(val notaryIdentity: Party, val price: Amount<Currency>, val anonymous: Boolean) data class TestTx(val notaryIdentity: Party, val price: Amount<Currency>, val anonymous: Boolean)
private fun LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.runWithError( private fun LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.runWithError(
ledgerIdentityService: IdentityServiceInternal,
bobError: Boolean, bobError: Boolean,
aliceError: Boolean, aliceError: Boolean,
expectedMessageSubstring: String expectedMessageSubstring: String
@ -575,6 +587,7 @@ class TwoPartyTradeFlowTests(private val anonymous: Boolean) {
val alice = aliceNode.info.singleIdentity() val alice = aliceNode.info.singleIdentity()
val bob = bobNode.info.singleIdentity() val bob = bobNode.info.singleIdentity()
val bank = bankNode.info.singleIdentity() val bank = bankNode.info.singleIdentity()
doReturn(null).whenever(ledgerIdentityService).partyFromKey(bank.owningKey)
val issuer = bank.ref(1, 2, 3) val issuer = bank.ref(1, 2, 3)
val bobsBadCash = bobNode.database.transaction { val bobsBadCash = bobNode.database.transaction {

View File

@ -1,8 +1,6 @@
package net.corda.node.services.persistence package net.corda.node.services.persistence
import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.*
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.Amount import net.corda.core.contracts.Amount
import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateAndRef
import net.corda.core.contracts.StateRef import net.corda.core.contracts.StateRef
@ -35,6 +33,7 @@ import net.corda.node.services.schema.HibernateObserver
import net.corda.node.services.schema.NodeSchemaService import net.corda.node.services.schema.NodeSchemaService
import net.corda.node.services.vault.VaultSchemaV1 import net.corda.node.services.vault.VaultSchemaV1
import net.corda.node.internal.configureDatabase import net.corda.node.internal.configureDatabase
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.nodeapi.internal.persistence.DatabaseConfig import net.corda.nodeapi.internal.persistence.DatabaseConfig
import net.corda.nodeapi.internal.persistence.HibernateConfiguration import net.corda.nodeapi.internal.persistence.HibernateConfiguration
@ -85,9 +84,9 @@ class HibernateConfigurationTest {
@Before @Before
fun setUp() { fun setUp() {
val cordappPackages = listOf("net.corda.testing.contracts", "net.corda.finance.contracts.asset") val cordappPackages = listOf("net.corda.testing.contracts", "net.corda.finance.contracts.asset")
bankServices = MockServices(cordappPackages, BOC.name, BOC_KEY) bankServices = MockServices(cordappPackages, rigorousMock(), BOC.name, BOC_KEY)
issuerServices = MockServices(cordappPackages, DUMMY_CASH_ISSUER_NAME, DUMMY_CASH_ISSUER_KEY) issuerServices = MockServices(cordappPackages, rigorousMock(), DUMMY_CASH_ISSUER_NAME, DUMMY_CASH_ISSUER_KEY)
notaryServices = MockServices(cordappPackages, DUMMY_NOTARY.name, DUMMY_NOTARY_KEY) notaryServices = MockServices(cordappPackages, rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
notary = notaryServices.myInfo.singleIdentity() notary = notaryServices.myInfo.singleIdentity()
val dataSourceProps = makeTestDataSourceProperties() val dataSourceProps = makeTestDataSourceProperties()
val identityService = rigorousMock<IdentityService>().also { mock -> val identityService = rigorousMock<IdentityService>().also { mock ->
@ -102,7 +101,9 @@ class HibernateConfigurationTest {
database.transaction { database.transaction {
hibernateConfig = database.hibernateConfig hibernateConfig = database.hibernateConfig
// `consumeCash` expects we can self-notarise transactions // `consumeCash` expects we can self-notarise transactions
services = object : MockServices(cordappPackages, BOB_NAME, generateKeyPair(), DUMMY_NOTARY_KEY) { services = object : MockServices(cordappPackages, rigorousMock<IdentityServiceInternal>().also {
doNothing().whenever(it).justVerifyAndRegisterIdentity(argThat { name == BOB_NAME })
}, BOB_NAME, generateKeyPair(), DUMMY_NOTARY_KEY) {
override val vaultService = makeVaultService(database.hibernateConfig, schemaService) override val vaultService = makeVaultService(database.hibernateConfig, schemaService)
override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) { override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) {
for (stx in txs) { for (stx in txs) {

View File

@ -1,6 +1,9 @@
package net.corda.node.services.vault package net.corda.node.services.vault
import co.paralleluniverse.fibers.Suspendable import co.paralleluniverse.fibers.Suspendable
import com.nhaarman.mockito_kotlin.argThat
import com.nhaarman.mockito_kotlin.doNothing
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.Amount import net.corda.core.contracts.Amount
import net.corda.core.contracts.Issued import net.corda.core.contracts.Issued
import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateAndRef
@ -34,6 +37,7 @@ import net.corda.finance.contracts.asset.DUMMY_CASH_ISSUER_NAME
import net.corda.finance.contracts.getCashBalance import net.corda.finance.contracts.getCashBalance
import net.corda.finance.schemas.CashSchemaV1 import net.corda.finance.schemas.CashSchemaV1
import net.corda.finance.utils.sumCash import net.corda.finance.utils.sumCash
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.testing.* import net.corda.testing.*
import net.corda.testing.contracts.VaultFiller import net.corda.testing.contracts.VaultFiller
@ -83,9 +87,8 @@ class NodeVaultServiceTest {
vaultFiller = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY) vaultFiller = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY)
// This is safe because MockServices only ever have a single identity // This is safe because MockServices only ever have a single identity
identity = services.myInfo.singleIdentityAndCert() identity = services.myInfo.singleIdentityAndCert()
issuerServices = MockServices(cordappPackages, DUMMY_CASH_ISSUER_NAME, DUMMY_CASH_ISSUER_KEY) issuerServices = MockServices(cordappPackages, rigorousMock(), DUMMY_CASH_ISSUER_NAME, DUMMY_CASH_ISSUER_KEY)
bocServices = MockServices(cordappPackages, BOC_NAME, BOC_KEY) bocServices = MockServices(cordappPackages, rigorousMock(), BOC_NAME, BOC_KEY)
services.identityService.verifyAndRegisterIdentity(DUMMY_CASH_ISSUER_IDENTITY) services.identityService.verifyAndRegisterIdentity(DUMMY_CASH_ISSUER_IDENTITY)
services.identityService.verifyAndRegisterIdentity(BOC_IDENTITY) services.identityService.verifyAndRegisterIdentity(BOC_IDENTITY)
} }
@ -125,7 +128,7 @@ class NodeVaultServiceTest {
assertThat(w1).hasSize(3) assertThat(w1).hasSize(3)
val originalVault = vaultService val originalVault = vaultService
val services2 = object : MockServices() { val services2 = object : MockServices(rigorousMock(), MEGA_CORP.name) {
override val vaultService: NodeVaultService get() = originalVault override val vaultService: NodeVaultService get() = originalVault
override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) { override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) {
for (stx in txs) { for (stx in txs) {
@ -468,7 +471,7 @@ class NodeVaultServiceTest {
@Test @Test
fun addNoteToTransaction() { fun addNoteToTransaction() {
val megaCorpServices = MockServices(cordappPackages, MEGA_CORP.name, MEGA_CORP_KEY) val megaCorpServices = MockServices(cordappPackages, rigorousMock(), MEGA_CORP.name, MEGA_CORP_KEY)
database.transaction { database.transaction {
val freshKey = identity.owningKey val freshKey = identity.owningKey
@ -575,7 +578,9 @@ class NodeVaultServiceTest {
val identity = services.myInfo.singleIdentityAndCert() val identity = services.myInfo.singleIdentityAndCert()
assertEquals(services.identityService.partyFromKey(identity.owningKey), identity.party) assertEquals(services.identityService.partyFromKey(identity.owningKey), identity.party)
val anonymousIdentity = services.keyManagementService.freshKeyAndCert(identity, false) val anonymousIdentity = services.keyManagementService.freshKeyAndCert(identity, false)
val thirdPartyServices = MockServices() val thirdPartyServices = MockServices(rigorousMock<IdentityServiceInternal>().also {
doNothing().whenever(it).justVerifyAndRegisterIdentity(argThat { name == MEGA_CORP.name })
}, MEGA_CORP.name)
val thirdPartyIdentity = thirdPartyServices.keyManagementService.freshKeyAndCert(thirdPartyServices.myInfo.singleIdentityAndCert(), false) val thirdPartyIdentity = thirdPartyServices.keyManagementService.freshKeyAndCert(thirdPartyServices.myInfo.singleIdentityAndCert(), false)
val amount = Amount(1000, Issued(BOC.ref(1), GBP)) val amount = Amount(1000, Issued(BOC.ref(1), GBP))

View File

@ -89,7 +89,7 @@ class VaultQueryTests {
services = databaseAndServices.second services = databaseAndServices.second
vaultFiller = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY) vaultFiller = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY)
vaultFillerCashNotary = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY, CASH_NOTARY) vaultFillerCashNotary = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY, CASH_NOTARY)
notaryServices = MockServices(cordappPackages, DUMMY_NOTARY.name, DUMMY_NOTARY_KEY, DUMMY_CASH_ISSUER_KEY, BOC_KEY, MEGA_CORP_KEY) notaryServices = MockServices(cordappPackages, rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY, DUMMY_CASH_ISSUER_KEY, BOC_KEY, MEGA_CORP_KEY)
identitySvc = services.identityService identitySvc = services.identityService
// Register all of the identities we're going to use // Register all of the identities we're going to use
(notaryServices.myInfo.legalIdentitiesAndCerts + BOC_IDENTITY + CASH_NOTARY_IDENTITY + MINI_CORP_IDENTITY + MEGA_CORP_IDENTITY).forEach { identity -> (notaryServices.myInfo.legalIdentitiesAndCerts + BOC_IDENTITY + CASH_NOTARY_IDENTITY + MINI_CORP_IDENTITY + MEGA_CORP_IDENTITY).forEach { identity ->
@ -1324,15 +1324,15 @@ class VaultQueryTests {
fun `unconsumed fungible assets for selected issuer parties`() { fun `unconsumed fungible assets for selected issuer parties`() {
// GBP issuer // GBP issuer
val gbpCashIssuerName = CordaX500Name(organisation = "British Pounds Cash Issuer", locality = "London", country = "GB") val gbpCashIssuerName = CordaX500Name(organisation = "British Pounds Cash Issuer", locality = "London", country = "GB")
val gbpCashIssuerServices = MockServices(cordappPackages, gbpCashIssuerName, generateKeyPair()) val gbpCashIssuerServices = MockServices(cordappPackages, rigorousMock(), gbpCashIssuerName, generateKeyPair())
val gbpCashIssuer = gbpCashIssuerServices.myInfo.singleIdentityAndCert() val gbpCashIssuer = gbpCashIssuerServices.myInfo.singleIdentityAndCert()
// USD issuer // USD issuer
val usdCashIssuerName = CordaX500Name(organisation = "US Dollars Cash Issuer", locality = "New York", country = "US") val usdCashIssuerName = CordaX500Name(organisation = "US Dollars Cash Issuer", locality = "New York", country = "US")
val usdCashIssuerServices = MockServices(cordappPackages, usdCashIssuerName, generateKeyPair()) val usdCashIssuerServices = MockServices(cordappPackages, rigorousMock(), usdCashIssuerName, generateKeyPair())
val usdCashIssuer = usdCashIssuerServices.myInfo.singleIdentityAndCert() val usdCashIssuer = usdCashIssuerServices.myInfo.singleIdentityAndCert()
// CHF issuer // CHF issuer
val chfCashIssuerName = CordaX500Name(organisation = "Swiss Francs Cash Issuer", locality = "Zurich", country = "CH") val chfCashIssuerName = CordaX500Name(organisation = "Swiss Francs Cash Issuer", locality = "Zurich", country = "CH")
val chfCashIssuerServices = MockServices(cordappPackages, chfCashIssuerName, generateKeyPair()) val chfCashIssuerServices = MockServices(cordappPackages, rigorousMock(), chfCashIssuerName, generateKeyPair())
val chfCashIssuer = chfCashIssuerServices.myInfo.singleIdentityAndCert() val chfCashIssuer = chfCashIssuerServices.myInfo.singleIdentityAndCert()
listOf(gbpCashIssuer, usdCashIssuer, chfCashIssuer).forEach { identity -> listOf(gbpCashIssuer, usdCashIssuer, chfCashIssuer).forEach { identity ->
services.identityService.verifyAndRegisterIdentity(identity) services.identityService.verifyAndRegisterIdentity(identity)

View File

@ -69,8 +69,8 @@ class VaultWithCashTest {
database = databaseAndServices.first database = databaseAndServices.first
services = databaseAndServices.second services = databaseAndServices.second
vaultFiller = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY) vaultFiller = VaultFiller(services, DUMMY_NOTARY, DUMMY_NOTARY_KEY)
issuerServices = MockServices(cordappPackages, DUMMY_CASH_ISSUER_NAME, DUMMY_CASH_ISSUER_KEY, MEGA_CORP_KEY) issuerServices = MockServices(cordappPackages, rigorousMock(), DUMMY_CASH_ISSUER_NAME, DUMMY_CASH_ISSUER_KEY, MEGA_CORP_KEY)
notaryServices = MockServices(cordappPackages, DUMMY_NOTARY.name, DUMMY_NOTARY_KEY) notaryServices = MockServices(cordappPackages, rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
notary = notaryServices.myInfo.legalIdentitiesAndCerts.single().party notary = notaryServices.myInfo.legalIdentitiesAndCerts.single().party
} }
@ -101,7 +101,7 @@ class VaultWithCashTest {
@Test @Test
fun `issue and spend total correctly and irrelevant ignored`() { fun `issue and spend total correctly and irrelevant ignored`() {
val megaCorpServices = MockServices(cordappPackages, MEGA_CORP.name, MEGA_CORP_KEY) val megaCorpServices = MockServices(cordappPackages, rigorousMock(), MEGA_CORP.name, MEGA_CORP_KEY)
val freshKey = services.keyManagementService.freshKey() val freshKey = services.keyManagementService.freshKey()
val usefulTX = val usefulTX =

View File

@ -19,11 +19,8 @@ import net.corda.node.internal.configureDatabase
import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.nodeapi.internal.persistence.DatabaseConfig import net.corda.nodeapi.internal.persistence.DatabaseConfig
import net.corda.testing.* import net.corda.testing.*
import net.corda.testing.node.MockNetwork import net.corda.testing.node.*
import net.corda.testing.node.MockNodeParameters
import net.corda.testing.node.MockServices
import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties
import net.corda.testing.node.createMockCordaService
import org.junit.After import org.junit.After
import org.junit.Assert.* import org.junit.Assert.*
import org.junit.Before import org.junit.Before
@ -50,7 +47,7 @@ class NodeInterestRatesTest {
private val DUMMY_CASH_ISSUER_KEY = generateKeyPair() private val DUMMY_CASH_ISSUER_KEY = generateKeyPair()
private val DUMMY_CASH_ISSUER = Party(CordaX500Name(organisation = "Cash issuer", locality = "London", country = "GB"), DUMMY_CASH_ISSUER_KEY.public) private val DUMMY_CASH_ISSUER = Party(CordaX500Name(organisation = "Cash issuer", locality = "London", country = "GB"), DUMMY_CASH_ISSUER_KEY.public)
private val services = MockServices(listOf("net.corda.finance.contracts.asset"), DUMMY_CASH_ISSUER.name, DUMMY_CASH_ISSUER_KEY, MEGA_CORP_KEY) private val services = MockServices(listOf("net.corda.finance.contracts.asset"), rigorousMock(), DUMMY_CASH_ISSUER.name, DUMMY_CASH_ISSUER_KEY, MEGA_CORP_KEY)
// This is safe because MockServices only ever have a single identity // This is safe because MockServices only ever have a single identity
private val identity = services.myInfo.singleIdentity() private val identity = services.myInfo.singleIdentity()

View File

@ -1,5 +1,7 @@
package net.corda.irs.contract package net.corda.irs.contract
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.Amount import net.corda.core.contracts.Amount
import net.corda.core.contracts.UniqueIdentifier import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.SignedTransaction
@ -18,6 +20,7 @@ import net.corda.finance.contracts.FixOf
import net.corda.finance.contracts.Frequency import net.corda.finance.contracts.Frequency
import net.corda.finance.contracts.PaymentRule import net.corda.finance.contracts.PaymentRule
import net.corda.finance.contracts.Tenor import net.corda.finance.contracts.Tenor
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.testing.* import net.corda.testing.*
import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices
import org.junit.Rule import org.junit.Rule
@ -212,10 +215,9 @@ class IRSTests {
@Rule @Rule
@JvmField @JvmField
val testSerialization = SerializationEnvironmentRule() val testSerialization = SerializationEnvironmentRule()
private val megaCorpServices = MockServices(listOf("net.corda.irs.contract"), MEGA_CORP.name, MEGA_CORP_KEY) private val megaCorpServices = MockServices(listOf("net.corda.irs.contract"), rigorousMock(), MEGA_CORP.name, MEGA_CORP_KEY)
private val miniCorpServices = MockServices(listOf("net.corda.irs.contract"), MINI_CORP.name, MINI_CORP_KEY) private val miniCorpServices = MockServices(listOf("net.corda.irs.contract"), rigorousMock(), MINI_CORP.name, MINI_CORP_KEY)
private val notaryServices = MockServices(listOf("net.corda.irs.contract"), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY) private val notaryServices = MockServices(listOf("net.corda.irs.contract"), rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
@Test @Test
fun ok() { fun ok() {
trade().verifies() trade().verifies()
@ -311,7 +313,11 @@ class IRSTests {
*/ */
@Test @Test
fun generateIRSandFixSome() { fun generateIRSandFixSome() {
val services = MockServices(listOf("net.corda.irs.contract")) val services = MockServices(listOf("net.corda.irs.contract"), rigorousMock<IdentityServiceInternal>().also {
listOf(MEGA_CORP, MINI_CORP).forEach { party ->
doReturn(party).whenever(it).partyFromKey(party.owningKey)
}
}, MEGA_CORP.name)
var previousTXN = generateIRSTxn(1) var previousTXN = generateIRSTxn(1)
previousTXN.toLedgerTransaction(services).verify() previousTXN.toLedgerTransaction(services).verify()
services.recordTransactions(previousTXN) services.recordTransactions(previousTXN)

View File

@ -36,9 +36,8 @@ class TransactionGraphSearchTests {
* @param signer signer for the two transactions and their commands. * @param signer signer for the two transactions and their commands.
*/ */
fun buildTransactions(command: CommandData): GraphTransactionStorage { fun buildTransactions(command: CommandData): GraphTransactionStorage {
val megaCorpServices = MockServices(listOf("net.corda.testing.contracts"), MEGA_CORP.name, MEGA_CORP_KEY) val megaCorpServices = MockServices(listOf("net.corda.testing.contracts"), rigorousMock(), MEGA_CORP.name, MEGA_CORP_KEY)
val notaryServices = MockServices(listOf("net.corda.testing.contracts"), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY) val notaryServices = MockServices(listOf("net.corda.testing.contracts"), rigorousMock(), DUMMY_NOTARY.name, DUMMY_NOTARY_KEY)
val originBuilder = TransactionBuilder(DUMMY_NOTARY) val originBuilder = TransactionBuilder(DUMMY_NOTARY)
.addOutputState(DummyState(random31BitValue()), DummyContract.PROGRAM_ID) .addOutputState(DummyState(random31BitValue()), DummyContract.PROGRAM_ID)
.addCommand(command, MEGA_CORP_PUBKEY) .addCommand(command, MEGA_CORP_PUBKEY)

View File

@ -23,6 +23,7 @@ import net.corda.node.services.config.VerifierType
import net.corda.nodeapi.internal.config.User import net.corda.nodeapi.internal.config.User
import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices
import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties
import net.corda.testing.node.makeTestIdentityService
import java.nio.file.Path import java.nio.file.Path
/** /**
@ -31,7 +32,7 @@ import java.nio.file.Path
*/ */
@JvmOverloads @JvmOverloads
fun ledger( fun ledger(
services: ServiceHub = MockServices(), services: ServiceHub = MockServices(makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)), MEGA_CORP.name),
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit
): LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter> { ): LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter> {
return LedgerDSL(TestLedgerDSLInterpreter(services)).also { dsl(it) } return LedgerDSL(TestLedgerDSLInterpreter(services)).also { dsl(it) }
@ -47,7 +48,7 @@ fun transaction(
transactionBuilder: TransactionBuilder = TransactionBuilder(notary = DUMMY_NOTARY), transactionBuilder: TransactionBuilder = TransactionBuilder(notary = DUMMY_NOTARY),
cordappPackages: List<String> = emptyList(), cordappPackages: List<String> = emptyList(),
dsl: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail dsl: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail
) = ledger(services = MockServices(cordappPackages)) { ) = ledger(services = MockServices(cordappPackages, makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)), MEGA_CORP.name)) {
dsl(TransactionDSL(TestTransactionDSLInterpreter(this.interpreter, transactionBuilder))) dsl(TransactionDSL(TestTransactionDSLInterpreter(this.interpreter, transactionBuilder)))
} }

View File

@ -29,6 +29,7 @@ import net.corda.node.services.api.SchemaService
import net.corda.node.services.config.BFTSMaRtConfiguration import net.corda.node.services.config.BFTSMaRtConfiguration
import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.config.NodeConfiguration
import net.corda.node.services.config.NotaryConfig import net.corda.node.services.config.NotaryConfig
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.node.services.keys.E2ETestKeyManagementService import net.corda.node.services.keys.E2ETestKeyManagementService
import net.corda.node.services.messaging.MessagingService import net.corda.node.services.messaging.MessagingService
import net.corda.node.services.transactions.BFTNonValidatingNotaryService import net.corda.node.services.transactions.BFTNonValidatingNotaryService
@ -274,7 +275,7 @@ class MockNetwork(defaultParameters: MockNetworkParameters = MockNetworkParamete
network = messagingServiceSpy network = messagingServiceSpy
} }
override fun makeKeyManagementService(identityService: IdentityService, keyPairs: Set<KeyPair>): KeyManagementService { override fun makeKeyManagementService(identityService: IdentityServiceInternal, keyPairs: Set<KeyPair>): KeyManagementService {
return E2ETestKeyManagementService(identityService, keyPairs) return E2ETestKeyManagementService(identityService, keyPairs)
} }

View File

@ -27,6 +27,7 @@ import net.corda.node.services.schema.NodeSchemaService
import net.corda.node.services.transactions.InMemoryTransactionVerifierService import net.corda.node.services.transactions.InMemoryTransactionVerifierService
import net.corda.node.services.vault.NodeVaultService import net.corda.node.services.vault.NodeVaultService
import net.corda.node.internal.configureDatabase import net.corda.node.internal.configureDatabase
import net.corda.node.services.api.IdentityServiceInternal
import net.corda.nodeapi.internal.persistence.CordaPersistence import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.nodeapi.internal.persistence.DatabaseConfig import net.corda.nodeapi.internal.persistence.DatabaseConfig
import net.corda.nodeapi.internal.persistence.HibernateConfiguration import net.corda.nodeapi.internal.persistence.HibernateConfiguration
@ -46,10 +47,11 @@ fun makeTestIdentityService(identities: Iterable<PartyAndCertificate> = emptySet
* A singleton utility that only provides a mock identity, key and storage service. However, this is sufficient for * A singleton utility that only provides a mock identity, key and storage service. However, this is sufficient for
* building chains of transactions and verifying them. It isn't sufficient for testing flows however. * building chains of transactions and verifying them. It isn't sufficient for testing flows however.
*/ */
open class MockServices( open class MockServices private constructor(
cordappLoader: CordappLoader, cordappLoader: CordappLoader,
override val validatedTransactions: WritableTransactionStorage, override val validatedTransactions: WritableTransactionStorage,
private val initialIdentityName: CordaX500Name = MEGA_CORP.name, override val identityService: IdentityServiceInternal,
private val initialIdentityName: CordaX500Name,
vararg val keys: KeyPair vararg val keys: KeyPair
) : ServiceHub, StateLoader by validatedTransactions { ) : ServiceHub, StateLoader by validatedTransactions {
companion object { companion object {
@ -75,13 +77,13 @@ open class MockServices(
/** /**
* Makes database and mock services appropriate for unit tests. * Makes database and mock services appropriate for unit tests.
* @param keys a list of [KeyPair] instances to be used by [MockServices]. * @param keys a list of [KeyPair] instances to be used by [MockServices].
* @param identityService an instance of [IdentityService], see [makeTestIdentityService]. * @param identityService an instance of [IdentityServiceInternal], see [makeTestIdentityService].
* @param initialIdentityName the name of the first (typically sole) identity the services will represent. * @param initialIdentityName the name of the first (typically sole) identity the services will represent.
* @return a pair where the first element is the instance of [CordaPersistence] and the second is [MockServices]. * @return a pair where the first element is the instance of [CordaPersistence] and the second is [MockServices].
*/ */
@JvmStatic @JvmStatic
fun makeTestDatabaseAndMockServices(keys: List<KeyPair>, fun makeTestDatabaseAndMockServices(keys: List<KeyPair>,
identityService: IdentityService, identityService: IdentityServiceInternal,
cordappPackages: List<String> = emptyList(), cordappPackages: List<String> = emptyList(),
initialIdentityName: CordaX500Name): Pair<CordaPersistence, MockServices> { initialIdentityName: CordaX500Name): Pair<CordaPersistence, MockServices> {
val cordappLoader = CordappLoader.createWithTestPackages(cordappPackages) val cordappLoader = CordappLoader.createWithTestPackages(cordappPackages)
@ -89,8 +91,7 @@ open class MockServices(
val schemaService = NodeSchemaService(cordappLoader.cordappSchemas) val schemaService = NodeSchemaService(cordappLoader.cordappSchemas)
val database = configureDatabase(dataSourceProps, DatabaseConfig(), identityService, schemaService) val database = configureDatabase(dataSourceProps, DatabaseConfig(), identityService, schemaService)
val mockService = database.transaction { val mockService = database.transaction {
object : MockServices(cordappLoader, initialIdentityName = initialIdentityName, keys = *(keys.toTypedArray())) { object : MockServices(cordappLoader, identityService, initialIdentityName, *(keys.toTypedArray())) {
override val identityService get() = identityService
override val vaultService: VaultServiceInternal = makeVaultService(database.hibernateConfig, schemaService) override val vaultService: VaultServiceInternal = makeVaultService(database.hibernateConfig, schemaService)
override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) { override fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>) {
@ -106,10 +107,10 @@ open class MockServices(
} }
} }
constructor(cordappLoader: CordappLoader, initialIdentityName: CordaX500Name = MEGA_CORP.name, vararg keys: KeyPair) : this(cordappLoader, MockTransactionStorage(), initialIdentityName = initialIdentityName, keys = *keys) private constructor(cordappLoader: CordappLoader, identityService: IdentityServiceInternal, initialIdentityName: CordaX500Name, vararg keys: KeyPair) : this(cordappLoader, MockTransactionStorage(), identityService, initialIdentityName, *keys)
constructor(cordappPackages: List<String>, initialIdentityName: CordaX500Name = MEGA_CORP.name, vararg keys: KeyPair) : this(CordappLoader.createWithTestPackages(cordappPackages), initialIdentityName = initialIdentityName, keys = *keys) constructor(cordappPackages: List<String>, identityService: IdentityServiceInternal, initialIdentityName: CordaX500Name, vararg keys: KeyPair) : this(CordappLoader.createWithTestPackages(cordappPackages), identityService, initialIdentityName, *keys)
constructor(vararg keys: KeyPair) : this(emptyList(), MEGA_CORP.name, *keys) constructor(identityService: IdentityServiceInternal, initialIdentityName: CordaX500Name, vararg keys: KeyPair) : this(emptyList(), identityService, initialIdentityName, *keys)
constructor() : this(generateKeyPair()) constructor(identityService: IdentityServiceInternal, initialIdentityName: CordaX500Name) : this(identityService, initialIdentityName, generateKeyPair())
val key: KeyPair get() = keys.first() val key: KeyPair get() = keys.first()
@ -120,7 +121,6 @@ open class MockServices(
} }
final override val attachments = MockAttachmentStorage() final override val attachments = MockAttachmentStorage()
override val identityService: IdentityService = makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY))
override val keyManagementService: KeyManagementService by lazy { MockKeyManagementService(identityService, *keys) } override val keyManagementService: KeyManagementService by lazy { MockKeyManagementService(identityService, *keys) }
override val vaultService: VaultService get() = throw UnsupportedOperationException() override val vaultService: VaultService get() = throw UnsupportedOperationException()
@ -152,7 +152,7 @@ open class MockServices(
override fun jdbcSession(): Connection = throw UnsupportedOperationException() override fun jdbcSession(): Connection = throw UnsupportedOperationException()
} }
class MockKeyManagementService(val identityService: IdentityService, class MockKeyManagementService(val identityService: IdentityServiceInternal,
vararg initialKeys: KeyPair) : SingletonSerializeAsToken(), KeyManagementService { vararg initialKeys: KeyPair) : SingletonSerializeAsToken(), KeyManagementService {
private val keyStore: MutableMap<PublicKey, PrivateKey> = initialKeys.associateByTo(HashMap(), { it.public }, { it.private }) private val keyStore: MutableMap<PublicKey, PrivateKey> = initialKeys.associateByTo(HashMap(), { it.public }, { it.private })

View File

@ -10,8 +10,10 @@ import net.corda.finance.contracts.asset.DUMMY_CASH_ISSUER
import net.corda.finance.contracts.asset.DUMMY_CASH_ISSUER_KEY import net.corda.finance.contracts.asset.DUMMY_CASH_ISSUER_KEY
import net.corda.loadtest.LoadTest import net.corda.loadtest.LoadTest
import net.corda.loadtest.NodeConnection import net.corda.loadtest.NodeConnection
import net.corda.testing.*
import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyContract
import net.corda.testing.node.MockServices import net.corda.testing.node.MockServices
import net.corda.testing.node.makeTestIdentityService
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
private val log = LoggerFactory.getLogger("NotaryTest") private val log = LoggerFactory.getLogger("NotaryTest")
@ -21,7 +23,7 @@ data class NotariseCommand(val issueTx: SignedTransaction, val moveTx: SignedTra
val dummyNotarisationTest = LoadTest<NotariseCommand, Unit>( val dummyNotarisationTest = LoadTest<NotariseCommand, Unit>(
"Notarising dummy transactions", "Notarising dummy transactions",
generate = { _, _ -> generate = { _, _ ->
val issuerServices = MockServices(DUMMY_CASH_ISSUER_KEY) val issuerServices = MockServices(makeTestIdentityService(listOf(MEGA_CORP_IDENTITY, MINI_CORP_IDENTITY, DUMMY_CASH_ISSUER_IDENTITY, DUMMY_NOTARY_IDENTITY)), MEGA_CORP.name, DUMMY_CASH_ISSUER_KEY)
val generateTx = Generator.pickOne(simpleNodes).flatMap { node -> val generateTx = Generator.pickOne(simpleNodes).flatMap { node ->
Generator.int().map { Generator.int().map {
val issueBuilder = DummyContract.generateInitial(it, notary.info.legalIdentities[1], DUMMY_CASH_ISSUER) // TODO notary choice val issueBuilder = DummyContract.generateInitial(it, notary.info.legalIdentities[1], DUMMY_CASH_ISSUER) // TODO notary choice