当前位置: 首页 > 知识库问答 >
问题:

如何在FlowResponder中调用子流

邵展
2023-03-14

我有关于FlowResponder下的呼叫流程的问题。

场景说明

如您所见,我只需要为NodeB调用subflow进行插入/更新。我能做到吗?

在这里,当我尝试,我得到了这个错误

在此启动流程代码

package th.co.jventures.ddlp.cordapp.flows

import co.paralleluniverse.fibers.Suspendable
import net.corda.confidential.IdentitySyncFlow
import net.corda.core.contracts.Command
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.contracts.requireThat
import net.corda.core.flows.*
import net.corda.core.identity.Party
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.ProgressTracker
import net.corda.core.utilities.unwrap
import th.co.jventures.ddlp.cordapp.contracts.CustomerContract
import th.co.jventures.ddlp.cordapp.core.commons.CordappConstants
import th.co.jventures.ddlp.cordapp.dto.CustomerIssueData
import th.co.jventures.ddlp.cordapp.services.CustomerService
import th.co.jventures.ddlp.cordapp.states.Address
import th.co.jventures.ddlp.cordapp.states.Consent
import th.co.jventures.ddlp.cordapp.states.CustomerState
import th.co.jventures.ddlp.cordapp.utils.CordappValidationUtils.Companion.requiredNotWhen
import java.util.*

@InitiatingFlow
@StartableByRPC
class CustomerIssueFlow(private val customerIssueData: CustomerIssueData) : FlowLogic<String>() {

    companion object {
        object GENERATING_TRANSACTION : ProgressTracker.Step("Generating transaction based on new IOU.")
        object VERIFYING_TRANSACTION : ProgressTracker.Step("Verifying contract constraints.")
        object SIGNING_TRANSACTION : ProgressTracker.Step("Signing transaction with our private key.")
        object GATHERING_SIGS : ProgressTracker.Step("Gathering the counterparty's signature.") {
            override fun childProgressTracker() = CollectSignaturesFlow.tracker()
        }

        object FINALISING_TRANSACTION : ProgressTracker.Step("Obtaining notary signature and recording transaction.") {
            override fun childProgressTracker() = FinalityFlow.tracker()
        }

        fun tracker() = ProgressTracker(
                GENERATING_TRANSACTION,
                VERIFYING_TRANSACTION,
                SIGNING_TRANSACTION,
                GATHERING_SIGS,
                FINALISING_TRANSACTION
        )
    }

    override val progressTracker = tracker()

    @Suspendable
    override fun call(): String {
        // Obtain a reference to the notary we want to use.
        val notary = serviceHub.networkMapCache.notaryIdentities[0]

        // Stage 1.
        progressTracker.currentStep = GENERATING_TRANSACTION
        // Generate an unsigned transaction.

        val customerService = serviceHub.cordaService(CustomerService::class.java)

        //#################################################################//
        val pahNode = serviceHub.networkMapCache.getPeerByLegalName(CordappConstants.Node.PAH) as Party
        val participants = listOf(ourIdentity, pahNode)

        val customerStateAndRef = customerService.findByIdCardNoAndPartner(idCarNo = customerIssueData.customerData.idCardNo!!, partner = customerIssueData.customerData.partner!!)

        //check duplicate customer
        requiredNotWhen(customerStateAndRef == null, "Customer already registered")

        val addresses = customerIssueData.customerData.addresses?.map { it ->
            Address(
                    seqId = it.seqId,
                    id = UUID.randomUUID().toString(),
                    type = it.type,
                    houseNumber = it.houseNumber,
                    street = it.street,
                    subDistrict = it.subDistrict,
                    district = it.district,
                    province = it.province,
                    postalCode = it.postalCode,
                    countryCode = it.countryCode,
                    mobile = it.mobile,
                    telephone = it.telephone
            )
        }

        val consentsArray = customerIssueData.customerData.consents?.map { it ->
            Consent(
                    id = UUID.randomUUID().toString(),
                    partner = it.partner,
                    product = it.product,
                    reference = it.reference,
                    createDate = it.createDate
            )
        }

        val linearId = UniqueIdentifier()

        val customerState = CustomerState(
                linearId = linearId,
                externalCustomerNo = customerIssueData.customerData.externalCustomerNo!!,
                title = customerIssueData.customerData.title!!,
                firstName = customerIssueData.customerData.firstName!!,
                middleName = customerIssueData.customerData.middleName!!,
                lastName = customerIssueData.customerData.lastName!!,
                idCardNo = customerIssueData.customerData.idCardNo!!,
                email = customerIssueData.customerData.email!!,
                partner = customerIssueData.customerData.partner!!,
                product = customerIssueData.customerData.product!!,
                consents = consentsArray,
                status = CordappConstants.CustomerStatus.Active,
                addresses = addresses,
                participants = participants,
                createDate = Date(),
                createBy = customerIssueData.customerData.username!!,
                changeDate = Date(),
                changeBy = customerIssueData.customerData.username!!
        )

        val txCommand = Command(CustomerContract.Commands.Issue(), customerState.participants.map { it.owningKey })
        val txBuilder = TransactionBuilder(notary)
                .addOutputState(customerState, CustomerContract.CONTRACT_ID)
                .addCommand(txCommand)

        //#################################################################//
        // Stage 2.
        progressTracker.currentStep = VERIFYING_TRANSACTION
        // Verify that the transaction is valid.
        txBuilder.verify(serviceHub)

        // Stage 3.
        progressTracker.currentStep = SIGNING_TRANSACTION
        // Sign the transaction.
        val partSignedTx = serviceHub.signInitialTransaction(txBuilder)

        // Stage 4.
        progressTracker.currentStep = GATHERING_SIGS
        // Send the state to the counterparty, and receive it back with their signature.
        val session = (customerState.participants - ourIdentity).map { initiateFlow(it) }
        val fullySignedTx = subFlow(CollectSignaturesFlow(partSignedTx, session, GATHERING_SIGS.childProgressTracker()))

        // Stage 5.
        progressTracker.currentStep = FINALISING_TRANSACTION
        // Notarise and record the transaction in both parties' vaults.

        subFlow(FinalityFlow(fullySignedTx, FINALISING_TRANSACTION.childProgressTracker()))
        return customerState.linearId.toString()
    }

}

@InitiatedBy(CustomerIssueFlow::class)
class CustomerIssueFlowResponder(val otherSideSession: FlowSession) : FlowLogic<SignedTransaction>() {// TwoPartyDealFlow.Acceptor(otherSideSession) {

    @Suspendable
    override fun call(): SignedTransaction {

        // val finalTx = super.call()
        println("######## START CustomerIssueFlowResponder ########################################################")
        println(ourIdentity)
        val signTransactionFlow = object : SignTransactionFlow(otherSideSession) {
            override fun checkTransaction(stx: SignedTransaction) = requireThat {
                // val output = stx.tx.outputs.single().data
                //"This must be an CustomerState." using (output is CustomerState)
            }
        }

        val stx = subFlow(ReceiveTransactionFlow(otherSideSession, checkSufficientSignatures = false))
        val customerState = stx.tx.outputs.single().data as CustomerState
        subFlow(CustomerPAHIssueOrUpdateFlow(customerState))
        println("######## END CustomerIssueFlowResponder ########################################################")

        return subFlow(signTransactionFlow)


    }
}

和子流

package th.co.jventures.ddlp.cordapp.flows

import co.paralleluniverse.fibers.Suspendable
import net.corda.core.contracts.Command
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.contracts.requireThat
import net.corda.core.flows.*
import net.corda.core.identity.Party
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.ProgressTracker
import net.corda.core.utilities.loggerFor
import th.co.jventures.ddlp.cordapp.contracts.CustomerContract
import th.co.jventures.ddlp.cordapp.core.commons.CordappConstants
import th.co.jventures.ddlp.cordapp.services.CustomerService
import th.co.jventures.ddlp.cordapp.states.CustomerState

@InitiatingFlow
@StartableByService
@StartableByRPC
class CustomerPAHIssueOrUpdateFlow(private val customerState: CustomerState) : FlowLogic<String>() {

    companion object {
        val log = loggerFor<CustomerPAHIssueOrUpdateFlow>()

        object GENERATING_TRANSACTION : ProgressTracker.Step("Generating transaction based on new IOU.")
        object VERIFYING_TRANSACTION : ProgressTracker.Step("Verifying contract constraints.")
        object SIGNING_TRANSACTION : ProgressTracker.Step("Signing transaction with our private key.")
        object GATHERING_SIGS : ProgressTracker.Step("Gathering the counterparty's signature.") {
            override fun childProgressTracker() = CollectSignaturesFlow.tracker()
        }

        object FINALISING_TRANSACTION : ProgressTracker.Step("Obtaining notary signature and recording transaction.") {
            override fun childProgressTracker() = FinalityFlow.tracker()
        }

        fun tracker() = ProgressTracker(
                GENERATING_TRANSACTION,
                VERIFYING_TRANSACTION,
                SIGNING_TRANSACTION,
                GATHERING_SIGS,
                FINALISING_TRANSACTION
        )
    }

    override val progressTracker = tracker()

    @Suspendable
    override fun call(): String {
        // Obtain a reference to the notary we want to use.
        val notary = serviceHub.networkMapCache.notaryIdentities[0]

        // Stage 1.
        progressTracker.currentStep = GENERATING_TRANSACTION
        // Generate an unsigned transaction.

        val customerService = serviceHub.cordaService(CustomerService::class.java)

        //#################################################################//
        val pahNode = serviceHub.networkMapCache.getPeerByLegalName(CordappConstants.Node.PAH) as Party
        //val participants = listOf(ourIdentity, pahNode)

        val customerStateAndRef = customerService.findByIdCardNoAndPartner(idCarNo = customerState.idCardNo!!, partner = CordappConstants.PartnerNameList.PAH)

        val txBuilder = TransactionBuilder(notary)
        if (customerStateAndRef == null) {
            log.info("===================================================")
            val linearId = UniqueIdentifier()
            val customerOutputState = customerState.copy(linearId = linearId, participants = listOf(pahNode), partner = CordappConstants.PartnerNameList.PAH)
            val txCommand = Command(CustomerContract.Commands.Issue(), customerState.participants.map { it.owningKey })

            log.info("Create new JVC Customer : {}", customerOutputState)

            txBuilder.addOutputState(customerOutputState, CustomerContract.CONTRACT_ID)
                    .addCommand(txCommand)
            log.info("===================================================")
        } else {
            log.info("===================================================")
            val txCommand = Command(CustomerContract.Commands.Update(), customerState.participants.map { it.owningKey })
            val customerOutputState = customerState.copy(participants = listOf(pahNode), partner = CordappConstants.PartnerNameList.PAH)

            log.info("Update existing JVC Customer : {}", customerOutputState)

            txBuilder.addInputState(customerStateAndRef)
            txBuilder.addOutputState(customerOutputState, CustomerContract.CONTRACT_ID)
                    .addCommand(txCommand)
            log.info("===================================================")
        }

        //#################################################################//
        // Stage 2.
        progressTracker.currentStep = VERIFYING_TRANSACTION
        // Verify that the transaction is valid.
        txBuilder.verify(serviceHub)

        // Stage 3.
        progressTracker.currentStep = SIGNING_TRANSACTION
        // Sign the transaction.
        val partSignedTx = serviceHub.signInitialTransaction(txBuilder)

        // Stage 4.
        progressTracker.currentStep = GATHERING_SIGS
        // Send the state to the counterparty, and receive it back with their signature.
        val session = (customerState.participants - ourIdentity).map { initiateFlow(it) }
        val fullySignedTx = subFlow(CollectSignaturesFlow(partSignedTx, session, GATHERING_SIGS.childProgressTracker()))

        // Stage 5.
        progressTracker.currentStep = FINALISING_TRANSACTION
        // Notarise and record the transaction in both parties' vaults.

        /*For syndicate loan phase
        //Initial default wallet with 0.00 THB
        subFlow(WalletIssueFlow(WalletIssueData(
                amount = BigDecimal.ZERO,
                currency = DEFAULT_CURRENCY,
                customerId = linearId.id.toString()
                )))
        */

        subFlow(FinalityFlow(fullySignedTx, FINALISING_TRANSACTION.childProgressTracker()))
        return customerState.linearId.toString()
    }

}

@InitiatedBy(CustomerPAHIssueOrUpdateFlow::class)
class CustomerPAHIssueOrUpdateFlowResponder(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val signTransactionFlow = object : SignTransactionFlow(otherPartyFlow) {
            override fun checkTransaction(stx: SignedTransaction) = requireThat {
                //val output = stx.tx.outputs.single().data
               // "This must be an CustomerState." using (output is CustomerState)
            }
        }

        return subFlow(signTransactionFlow)
    }
}

共有1个答案

杨轶
2023-03-14

此问题与从流调用子流无关。相反,问题在CustomeIssueFlowResder的这一行中:

val stx = subFlow(ReceiveTransactionFlow(otherSideSession, checkSufficientSignatures = false))

没有从流的另一端发送相应的事务,导致类型异常:

java.io.NotSerializableException:描述符net.corda的描述类型:Rd6hxg 0oJROxKDXK8OerA==应该是类类型net.corda.core.transactions.SignedTransaction但java.util.List

不要调用ReceiveTransactionFlow,只需使用SignTransactionFlow返回的事务。

 类似资料:
  • 我开始学钩子了。但是我不明白异步调用是如何工作的。早些时候我被使用 然后调用我的,但是我应该用useDispat()做什么?如果我只是调用 然后我的< code > foo() don t < code > console . log(2) 我正在使用thunk

  • 问题内容: 如何从其父范围调用在子范围中定义的方法? http://jsfiddle.net/wUPdW/ 问题答案: 您可以从父母到孩子使用: 工作jsfiddle:http : //jsfiddle.net/wUPdW/2/ 更新 :还有另一个版本,耦合性更低,更易于测试: jsfiddle:http : //jsfiddle.net/uypo360u/

  • 我有一个名为User的抽象类和一个扩展User的子类。User类包含一个方法:受保护的抽象空setId(String newId){}:它在User类中设置一个私有变量id。所以我的问题是,当我去创建setId()方法时,如果User类中的id是私有的,我如何引用它?据我所知,id变量不能被设置为受保护的。感谢任何能帮忙的人!

  • 问题内容: React钩子介绍了用于设置组件状态的方法。但是我如何使用钩子来代替如下代码的回调: 我想在状态更新后做一些事情。 我知道我可以用来做其他事情,但是我必须检查状态以前的值,这需要一个位代码。我正在寻找可以与钩子一起使用的简单解决方案。 问题答案: 您需要使用钩子来实现此目的。

  • React hooks引入了来设置组件状态。但是我如何使用钩子来替换回调,如下代码所示:

  • 问题内容: 我编写了如下代码块: 初始化后就可以了。将人员设置为时,不调用该方法。 问题答案: 问题在于操场不是现实生活。这只是不使用它们的又一个原因(我认为,对于苹果公司而言,这是一个可怕的错误)。使用真实的iOS应用项目,将按预期方式调用。 来自真实项目的示例: 这就是您期望的。