I have been following the official tutorials on how to implement observer nodes from here and here. I tried testing the flow to broadcast the transaction to observer nodes, however, I am not sure if I implemented the flow correctly. After running the flow, no states showed up in the vault of the observer node. No states (that corresponded to the transaction that was broadcast) showed up when I ran a RPC vault query nor did it show when I accessed the H2 database of the observer node. Debugging showed that the flow code was called. No exception was thrown as well.
Is the flow working correctly? Also how can I view the broadcasted transactions as an observer node - is it stored as a consumed state in its vault?
The flow code:
object BroadcastTransaction {
#InitiatingFlow
class BroadcastTransactionToObservers(private val stx: SignedTransaction, private val observers: List<Party>) : FlowLogic<Unit>() {
#Suspendable
override fun call() {
val sessions = observers.map { initiateFlow(it) }
sessions.forEach { subFlow(SendTransactionFlow(it, stx)) }
}
}
#InitiatedBy(BroadcastTransactionToObservers::class)
class RecordTransactionAsObserver(private val otherSession: FlowSession) :FlowLogic<Unit>() {
#Suspendable
override fun call() {
subFlow( ReceiveTransactionFlow(
otherSideSession = otherSession,
checkSufficientSignatures = true,
statesToRecord = StatesToRecord.ALL_VISIBLE
)
)
}
}
}
How I call the flow:
subFlow(BroadcastTransaction.BroadcastTransactionToObservers(fullySignedTx, listOf(observer)))
Prior initiating flow:
#InitiatingFlow
#StartableByRPC
class Initiator (val id: String,
val transferParty : Party,
val observer : Party) : BaseFlow() {
#Suspendable
override fun call() : SignedTransaction {
progressTracker.currentStep = ID_OTHER_NODES
val notary = serviceHub.networkMapCache.notaryIdentities[0]
progressTracker.currentStep = EXTRACTING_VAULT_STATES
val stateAndRef = getItemStateByItemId(id)
val inputState = stateAndRef.state.data
progressTracker.currentStep = TX_BUILDING
val txBuilder = TransactionBuilder(notary = notary)
val outputState = createOutput(inputState)
val signerKeys = listOf(ourIdentity.owningKey, transferParty.owningKey)
val cmd = Command(outputState.command, signerKeys)
txBuilder.addInputState(stateAndRef)
.addOutputState(outputState.ownableState, CONTRACT_ID)
.addCommand(cmd)
progressTracker.currentStep = TX_VERIFICATION
txBuilder.verify(serviceHub)
progressTracker.currentStep = TX_SIGNING
val signedTx = serviceHub.signInitialTransaction(txBuilder)
progressTracker.currentStep = SENDING_AND_RECEIVING_DATA
val sessions = setOf(initiateFlow(transferParty))
progressTracker.currentStep = SIGS_GATHERING
val fullySignedTx: SignedTransaction = subFlow(CollectSignaturesFlow(signedTx, sessions, SIGS_GATHERING.childProgressTracker()))
subFlow(BroadcastTransaction.BroadcastTransactionToObservers(fullySignedTx, listOf(observer)))
progressTracker.currentStep = FINALISATION
return subFlow(FinalityFlow(fullySignedTx, setOf(ourIdentity),FINALISATION.childProgressTracker()))
}
You are broadcasting the transaction to the observer before it has received a signature from the notary as part of FinalityFlow. Nodes will not record a transaction's states in their vault unless it has all the required signatures, including the notary's.
Try moving the call to FinalityFlow above the call to BroadcastTransaction.BroadcastTransactionToObservers.
Related
I had cloned the cordapp-kotlin-template . I've defined a state called LoadState which looks like this:
#BelongsToContract(LoadContract::class)
data class LoadState(
val loadId: String,
val transporterName: String? = null,
val vehicleModel: String? = null,
val regLicenseNo: String? = null,
val totalWeight: Int? = null,
val notes: String? = null,
val suppliers: MutableList<SupplierDetailsModel> = mutableListOf(),
val recycler: Party,
override val participants: List<AbstractParty> = listOf(recycler)
) : QueryableState {
override fun generateMappedObject(schema: MappedSchema): PersistentState {
if (schema is LoadSchemaV1) {
return PersistentLoadState(this.loadId)
} else {
throw IllegalArgumentException("Unsupported Schema.")
}
}
override fun supportedSchemas(): Iterable<MappedSchema> {
return listOf(LoadSchemaV1())
}
}
When I use the application for the first time and issue a LoadState say LO123 it works fine. The state is issued and recorded in the vault as well.
This is how my the LoadState issue flow looks like:
#Suspendable
override fun call(): SignedTransaction {
val notary = serviceHub.networkMapCache.getNotary(CordaX500Name.parse("O=Notary,L=London,C=GB"))
progressTracker.currentStep = TX_COMPONENTS
val recyclerName = CordaX500Name(
organisation = "MyRecycler",
locality = "Mumbai",
country = "IN"
)
val recycler = serviceHub.identityService.wellKnownPartyFromX500Name(recyclerName)
?: throw IllegalArgumentException("Could not find party Recycler.")
val outputState = LoadState(
loadId = req.loadId,
loadDate = req.loadDate,
transporterName = req.transporterName,
vehicleModel = req.vehicleModel,
regLicenseNo = req.regLicenseNo,
totalWeight = req.totalWeight,
assets = req.assets,
suppliers = req.suppliers,
recycler = recycler,
notes = req.notes
)
val command = Command(LoadContract.Commands.Create(), listOf(ourIdentity.owningKey))
progressTracker.currentStep = TX_BUILDING
val txBuilder = TransactionBuilder(notary = notary)
.addOutputState(outputState, LoadContract.ID)
.addCommand(command)
// signing the transaction
progressTracker.currentStep = TX_SIGNING
val signedTx = serviceHub.signInitialTransaction(txBuilder)
// verifying the transaction
progressTracker.currentStep = TX_VERIFICATION
txBuilder.verify(serviceHub)
// We finalise the transaction and then send it to the counterparty.
progressTracker.currentStep = FINALIZATION
val recyclerSession = initiateFlow(recycler)
return subFlow(FinalityFlow(signedTx, listOf()))
}
Now there's a requirement to add a new field to our LoadState:
val myNewField: String? = null
After adding this new field to the LoadState I'm running the deployNodes command. Once the build folders are generated I'm copying the contents of the Node/cordapps folder to my old build Node/cordapps folder.
Now, while starting the nodes I'm running the migration commands (core schemas and app schemas). Once the migration process is complete and the nodes are up, I'm calling an api endpoint which invokes a flow which takes L0123 as input, copies it, and modifies some params and create a new output state of type LoadState. The error is thrown at:
txBuilder.verify(serviceHub) in my UpdateLoadFlow. This is how my update flow looks like:
#Suspendable
override fun call(): SignedTransaction {
val notary = serviceHub.networkMapCache.getNotary(CordaX500Name.parse("O=Notary,L=London,C=GB"))
progressTracker.currentStep = TX_COMPONENTS
val recyclerName = CordaX500Name(
organisation = "MyRecycler",
locality = "Mumbai",
country = "IN"
)
val recycler = serviceHub.identityService.wellKnownPartyFromX500Name(recyclerName)
?: throw IllegalArgumentException("Could not find party Recycler.")
val inputState = QueryVault().queryLoadById(req.loadId, Vault.StateStatus.UNCONSUMED, serviceHub.vaultService)
?: throw Exception("Load ${req.loadId} not found.")
val vaultData = inputState.state.data
var outputState = vaultData.copy(myNewField = "some new value");
val command = Command(LoadContract.Commands.Update(), listOf(ourIdentity.owningKey))
progressTracker.currentStep = TX_BUILDING
val txBuilder = TransactionBuilder(notary = notary)
.addInputState(inputState)
.addOutputState(outputState, LoadContract.ID)
.addCommand(command)
txBuilder.verify(serviceHub)
// signing the transaction
progressTracker.currentStep = TX_SIGNING
val signedTx = serviceHub.signInitialTransaction(txBuilder)
// verifying the transaction
progressTracker.currentStep = TX_VERIFICATION
// We finalise the transaction and then send it to the counterparty.
progressTracker.currentStep = FINALIZATION
val recyclerSession = initiateFlow(recycler)
return subFlow(FinalityFlow(signedTx, listOf()))
}
Please help me out with this.
After our discussion in the above comments section, it appears that your states have been issued using Whitelist zone constraint.
Also looking at the code it is clear that you have not explicitly added Whitelist Zone constraints for your states.
Then there remain two more possibilities by which states are issued using Whitelist Zone constraint.
One is you are using some Corda version before 4 or you have included the necessary configs to include white list zone constraints in network bootstrapper as specified here.
You have two options - either start from scratch and make sure you use Corda 4.
If you cannot start from scratch follow this path to first migrate the whitelist zone constraints to signature constraints, before running your UpdateLoadFlow. You can refer to this blog which talks about constraint migration.
I'm currently training to become a corda developer.
I've created a simple corDapp which only has 1 participant, Here is the state I created:
#BelongsToContract(UserContract::class)
class UserState(val name: String,
val age: Int,
val address: String,
val gender: GenderEnums,
val node: Party,
val status: StatusEnums,
override val linearId: UniqueIdentifier,
override val participants : List<Party>
) : LinearState
So when I run the corDapp, I get my desired output https://imgur.com/mOKhNpI
But what I want to do is to update the vault. I would, for example, like to update the address from "Pampanga" to "Manila", But I don't know where to start. All I know is that since States are immutable, you have to consume the state first.
I tried to create a flow:
#InitiatingFlow
#StartableByRPC
class UpdateUserFlows(private val name :String,
private val age : Int,
private val address : String,
private val gender: GenderEnums,
private val status : StatusEnums,
private val counterParty: Party): FlowLogic<SignedTransaction>() {
private fun userStates(): UserState {
return UserState(
name = name,
age = age,
address = address,
gender = gender,
status = status,
node = ourIdentity,
linearId = UniqueIdentifier(),
participants = listOf(ourIdentity, counterParty)
)
}
#Suspendable
override fun call(): SignedTransaction {
val transaction: TransactionBuilder = transaction()
val signedTransaction: SignedTransaction = verifyAndSign(transaction)
val sessions: List<FlowSession> = (userStates().participants - ourIdentity).map { initiateFlow(it) }.toSet().toList()
val transactionSignedByAllParties: SignedTransaction = collectSignature(signedTransaction, sessions)
return recordTransaction(transactionSignedByAllParties, sessions)
}
private fun transaction(): TransactionBuilder {
val notary: Party = serviceHub.networkMapCache.notaryIdentities.first()
val issueCommand = Command(UserContract.Commands.Issue(), userStates().participants.map { it.owningKey })
val builder = TransactionBuilder(notary = notary)
builder.addOutputState(userStates(), UserContract.ID)
builder.addCommand(issueCommand)
return builder
}
private fun verifyAndSign(transaction: TransactionBuilder): SignedTransaction {
transaction.verify(serviceHub)
return serviceHub.signInitialTransaction(transaction)
}
#Suspendable
private fun collectSignature(
transaction: SignedTransaction,
sessions: List<FlowSession>
): SignedTransaction = subFlow(CollectSignaturesFlow(transaction, sessions))
#Suspendable
private fun recordTransaction(transaction: SignedTransaction, sessions: List<FlowSession>): SignedTransaction =
subFlow(FinalityFlow(transaction, sessions))
}
But it's not working.
You are right, states are immutable in Corda and to mimic an update you basically need to create a transaction where the input is your current version of the state (i.e. address = Pampanga), and the output would be a new instance of UserState which has the same linearId and other attribute values as the input, but a different address value (i.e. Manila).
This way you are creating a new state (the output of the transaction), but because it will have the same linearId value; it would be as if you updated the input to become the output, this will allow you to see all the previous versions of a state by querying the vault by its linearId.
You didn't share the code of your contract, but you need to add a new command (let's call it Update); and also you need to add the verification rules that apply to it.
Inside your flow, you'd use that command (instead of Issue).
i want to use addIssueTokens to add token to TransactionBuilder.
my code
#InitiatingFlow
#StartableByRPC
class Issue(val otherParty: Party) : FlowLogic<SignedTransaction>() {
override val progressTracker = ProgressTracker()
#Suspendable
override fun call() : SignedTransaction{
val jpyToken = createFungibleToken("JPY", 1000, otherParty)
val gbToken = createFungibleToken("GB", 1000, otherParty)
val notary = serviceHub.networkMapCache.notaryIdentities.single()
val txBuilder = TransactionBuilder(notary)
//may be add other output input
//....
//add token to txBuilder
addIssueTokens(txBuilder, listOf(jpyToken,gbToken))
txBuilder.verify(serviceHub)
// Sign the transaction
val ptx = serviceHub.signInitialTransaction(txBuilder, ourIdentity.owningKey)
// Instantiate a network session with the shareholder
val holderSession = initiateFlow(otherParty)
val sessions = listOf(holderSession)
// Ask the shareholder to sign the transaction
val stx = subFlow(CollectSignaturesFlow(ptx, listOf(holderSession)))
return subFlow<SignedTransaction>(FinalityFlow(stx, sessions))
}
fun createFungibleToken(symbol:String,amout:Long,target : AbstractParty) : FungibleToken{
val tokenType = TokenType(symbol, 0)
val issuedTokenType = IssuedTokenType(ourIdentity, tokenType)
val amount = Amount<IssuedTokenType>(amout, issuedTokenType)
return FungibleToken(amount, target)
}
}
#InitiatedBy(Issue::class)
class IssueResponder(val otherPartySession: FlowSession) : FlowLogic<SignedTransaction>() {
#Suspendable
override fun call(): SignedTransaction {
val signTransactionFlow = object : SignTransactionFlow(otherPartySession) {
override fun checkTransaction(stx: SignedTransaction) = requireThat {
}
}
val txId = subFlow(signTransactionFlow).id
return subFlow(ReceiveFinalityFlow(otherPartySession, expectedTxId = txId))
}
}
shell: start flow
>>start com.template.flows.Issue otherParty: "O=PartyB,L=New York,C=US"
Starting
Collecting signatures from counterparties.
Starting
Broadcasting transaction to participants
Done
Flow completed with result: SignedTransaction(id=547B812BA5574168DA8085C87AADFCAFA2A098CF62F375C21D450C0FE2402547)
it seems that Flow completed. but i check partyB database ,there is no data in vault_states table .
why?
ps.i knew how to use com.r3.corda.lib.tokens.workflows.flows.rpc.IssueTokens flow
The holder is not a required signer when issuing tokens; try removing the CollectSignaturesFlow and SignTransactionFlow calls from the initiator and responder flows; only keep FinalityFlow and ReceiveFinalityFlow.
You can see here that the required signers are:
The issuer on issuing.
The holder on moving.
The issuer and holder on redeeming.
But also the contract says here that there could be other signers on issue; so I'm not 100% sure that's the cause of the problem.
Try removing the signature flows and re-run your test; and let me know if it worked.
Another thing, check the logs of the initiating node (the log is inside logs folder inside your node's folder structure); are there any errors?.
I am trying to make use of Composite Key feature to show how an asset on the ledger could be controlled using a composite key. I get following error in my flow code:
java.lang.IllegalArgumentException: Could not find Party for Anonymous(DLHpGSdYSvv7vLRGJuuZSsTWQpk7ehkB7B1K1bzV68YmY7)
at net.corda.core.identity.IdentityUtils.groupAbstractPartyByWellKnownParty(IdentityUtils.kt:47)
at net.corda.core.identity.IdentityUtils.groupAbstractPartyByWellKnownParty(IdentityUtils.kt:63)
at net.corda.core.flows.FinalityFlow.getPartiesToSend(FinalityFlow.kt:96)
at net.corda.core.flows.FinalityFlow.call(FinalityFlow.kt:54)
at net.corda.core.flows.FinalityFlow.call(FinalityFlow.kt:28)
at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:290)
at com.example.flow.ExampleFlow$Initiator.call(ExampleFlow.kt:102)
at com.example.flow.ExampleFlow$Initiator.call(ExampleFlow.kt:34)
Below is my State definition
data class LandState(val alice: Party, val bob: Party, override val linearId: UniqueIdentifier = UniqueIdentifier()): LinearState{
val owner: AbstractParty = AnonymousParty (CompositeKey.Builder().addKeys(alice.owningKey, bob.owningKey).build())
override val participants: List<AbstractParty> = listOf(owner)}
Below is my contract code
override fun verify(tx: LedgerTransaction) {
val command = tx.commands.requireSingleCommand<Commands.Create>()
requireThat {
"No inputs should be consumed when issuing an IOU." using (tx.inputs.isEmpty())
"Only one output state should be created." using (tx.outputs.size == 1)
val out = tx.outputsOfType<LandState>().single()
"Command must be signed by the Composite key holder" using (command.signers.contains(out.owner.owningKey))
}
}
Below is my Flow
object ExampleFlow {
#InitiatingFlow
#StartableByRPC
class Initiator( val alice: Party,
val bob: Party) : FlowLogic<SignedTransaction>() {
/**
* The progress tracker checkpoints each stage of the flow and outputs the specified messages when each
* checkpoint is reached in the code. See the 'progressTracker.currentStep' expressions within the call() function.
*/
companion object {
object GENERATING_TRANSACTION : Step("Generating transaction based on new IOU.")
object VERIFYING_TRANSACTION : Step("Verifying contract constraints.")
object SIGNING_TRANSACTION : Step("Signing transaction with our private key.")
object GATHERING_SIGS : Step("Gathering the counterparty's signature.") {
override fun childProgressTracker() = CollectSignaturesFlow.tracker()
}
object FINALISING_TRANSACTION : 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()
/**
* The flow logic is encapsulated within the call() method.
*/
#Suspendable
override fun call(): SignedTransaction {
// 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 landState = LandState(alice, bob)
// val iouState = IOUState(iouValue, serviceHub.myInfo.legalIdentities.first(), otherParty)
val txCommand = Command(IOUContract.Commands.Create(), listOf(landState.owner.owningKey))
val txBuilder = TransactionBuilder(notary)
.addOutputState(landState, IOU_CONTRACT_ID)
.addCommand(txCommand)
// Stage 2.
progressTracker.currentStep = VERIFYING_TRANSACTION
// Verify that the transaction is valid.
// 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 otherPartyFlow = initiateFlow(bob)
val fullySignedTx = subFlow(CollectSignaturesFlow(partSignedTx, setOf(otherPartyFlow), GATHERING_SIGS.childProgressTracker()))
txBuilder.verify(serviceHub)
// Stage 5.
progressTracker.currentStep = FINALISING_TRANSACTION
// Notarise and record the transaction in both parties' vaults.
return subFlow(FinalityFlow(fullySignedTx))
}
}
#InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
#Suspendable
override fun call(): SignedTransaction {
val signTransactionFlow = object : SignTransactionFlow(otherPartyFlow) {
override fun checkTransaction(stx: SignedTransaction) = requireThat {
}
}
return subFlow(signTransactionFlow)
}
}}
Am I missing anything? The owner field in the above sate is of type AnonymousParty since composite key is of type public key and not a well known certificate.
You can't use CollectSignaturesFlow with CompositeKeys. You need to define your own custom flow for collecting the required signatures.
Why? Because CollectSignaturesFlow works out who to request signatures from based on the parties listed in the commands. Since the CompositeKey does not correspond to a specific party, the node does not know who to request a signature from and throws an exception.
I'm trying to create a flow to Issue and Move currency.
The Contract i have use is the CommercialPaper from the tutorial
https://docs.corda.net/tutorial-contract.html. But i can't get it to work. Here is my flow from the code. I use following commands in the CLI after starting up all the nodes (notery/networkmap,PartyA,PartyB)
start CPIssueFlow value: 6
start CPMoveFlow value: 3, otherParty: "O=PartyB,L=New York,C=US"
The error i get is 'Insufficient funds' from the function 'gatherOurInputs'. Can How can i fix this?
UPDATE:
The github repo is : https://github.com/WesleyCap/Corda/
The Code is updated. The CPIssueFlow didnt work correctly. Now i get the next error.
Contract verification failed: Failed requirement: for reference [00] at issuer C=GB,L=London,O=PartyA the amounts balance: 6 - 0 != 0, contract: net.corda.finance.contracts.asset.Cash#58e904ed, transaction: 71F70042CDA3D46E05ABE319DA5F14D3BDBBB1C80A24753AA9AC660DCD830109
package com.template
import co.paralleluniverse.fibers.Suspendable
import com.template.CommercialPaperContract.Companion.CP_PROGRAM_ID
import net.corda.core.contracts.*
import net.corda.core.flows.*
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.Party
import net.corda.core.node.ServiceHub
import net.corda.core.node.services.VaultService
import net.corda.core.node.services.vault.QueryCriteria
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.ProgressTracker
import net.corda.finance.DOLLARS
import net.corda.finance.EUR
import net.corda.finance.contracts.asset.CASH
import net.corda.finance.contracts.asset.Cash
import net.corda.finance.contracts.asset.PartyAndAmount
import net.corda.finance.issuedBy
import java.time.Instant
import java.util.*
import net.corda.core.node.services.vault.builder
import net.corda.core.utilities.OpaqueBytes
import net.corda.finance.flows.AbstractCashFlow
import net.corda.finance.flows.CashIssueFlow
import net.corda.finance.schemas.CashSchemaV1
import net.corda.core.contracts.Amount
import net.corda.core.flows.StartableByRPC
// *********
// * Flows *
// *********
object CPIssueFlow {
#InitiatingFlow
#StartableByRPC
class Initiator(val value: Long) : FlowLogic<Unit>() {
/** The progress tracker provides checkpoints indicating the progress of the flow to observers. */
override val progressTracker = tracker()
companion object {
object PREPARING : ProgressTracker.Step("Gathering the required inputs.")
object CREATECURRENCY : ProgressTracker.Step("Creating cash.")
object SIGNING : ProgressTracker.Step("Sign the transaction.")
object TOVAULT : ProgressTracker.Step("Returning the newly-issued cash state.")
fun tracker() = ProgressTracker(PREPARING, CREATECURRENCY, SIGNING, TOVAULT)
}
/** The flow logic is encapsulated within the call() method. */
#Suspendable
override fun call() {
progressTracker.currentStep = PREPARING
val notary = serviceHub.networkMapCache.notaryIdentities[0]
val builder = TransactionBuilder(notary)
val amount = Amount(value , EUR)
val issuer = ourIdentity.ref(1)
progressTracker.currentStep = CREATECURRENCY
val signers = Cash().generateIssue(builder, amount.issuedBy(issuer), ourIdentity, notary)
progressTracker.currentStep = SIGNING
val tx = serviceHub.signInitialTransaction(builder, signers)
progressTracker.currentStep = TOVAULT
subFlow(FinalityFlow(tx))
}
}
#InitiatedBy(CPIssueFlow.Initiator::class)
class Acceptor(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 CommercialPaperState transaction." using (output is CommercialPaperState)
}
}
return subFlow(signTransactionFlow)
}
}
}
object CPMoveFlow {
#InitiatingFlow
#StartableByRPC
class Initiator(val value: Long, val otherParty: Party) : FlowLogic<Unit>() {
/** The progress tracker provides checkpoints indicating the progress of the flow to observers. */
override val progressTracker = tracker()
companion object {
object PREPARING : ProgressTracker.Step("Getting the needed information")
object PREPARESTATES : ProgressTracker.Step("Creating inputstates,outputstates and commands")
object ADDSTATESTOTX : ProgressTracker.Step("Add inputstates,outputstates and commands to the transaction")
object VERIFYTX : ProgressTracker.Step("Verify transaction")
object SIGNING : ProgressTracker.Step("Signing the transaction")
object SENDTOVAULT : ProgressTracker.Step("Put the transaction in the vault")
fun tracker() = ProgressTracker(PREPARING, PREPARESTATES, ADDSTATESTOTX, VERIFYTX, SIGNING, SENDTOVAULT)
}
/** The flow logic is encapsulated within the call() method. */
#Suspendable
override fun call() {
progressTracker.currentStep = PREPARING
val notary = serviceHub.networkMapCache.notaryIdentities[0]
val txBuilder = TransactionBuilder(notary = notary)
val issuer = ourIdentity.ref(1)
val amount = Amount(value , EUR)
progressTracker.currentStep = PREPARESTATES
// We create the transaction components.
val (inputStates, residual) = gatherOurInputs(serviceHub,runId.uuid ,amount.issuedBy(issuer) , notary)
val outputState = CommercialPaperState(issuer, otherParty, amount.issuedBy(issuer), Instant.now())
val outputContractAndState = StateAndContract(outputState, CP_PROGRAM_ID)
val cmd = Command(CommercialPaperContract.Commands.Move(), listOf(ourIdentity.owningKey, otherParty.owningKey))
progressTracker.currentStep = ADDSTATESTOTX
txBuilder.withItems(outputContractAndState, cmd)
txBuilder.addInputState(inputStates[0])
progressTracker.currentStep = VERIFYTX
txBuilder.verify(serviceHub)
progressTracker.currentStep = SIGNING
val signedTx = serviceHub.signInitialTransaction(txBuilder)
val otherpartySession = initiateFlow(otherParty)// Creating a session with the other party.
val fullySignedTx = subFlow(CollectSignaturesFlow(signedTx, listOf(otherpartySession), CollectSignaturesFlow.tracker())) // Obtaining the counterparty's signature.
progressTracker.currentStep = SENDTOVAULT
// Finalising the transaction.
subFlow(FinalityFlow(fullySignedTx))
}
}
#InitiatedBy(CPMoveFlow.Initiator::class)
class Acceptor(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 IOU transaction." using (output is CommercialPaperState)
}
}
return subFlow(signTransactionFlow)
}
}
// This is equivalent to the Cash.generateSpend
// Which is brought here to make the filtering logic more visible in the example
private fun gatherOurInputs(serviceHub: ServiceHub,
lockId: UUID,
amountRequired: Amount<Issued<Currency>>,
notary: Party?): Pair<List<StateAndRef<Cash.State>>, Long> {
// extract our identity for convenience
val ourKeys = serviceHub.keyManagementService.keys
val ourParties = ourKeys.map { serviceHub.identityService.partyFromKey(it) ?: throw IllegalStateException("Unable to resolve party from key") }
val fungibleCriteria = QueryCriteria.FungibleAssetQueryCriteria(owner = ourParties)
val notaries = notary ?: serviceHub.networkMapCache.notaryIdentities.first()
val vaultCriteria: QueryCriteria = QueryCriteria.VaultQueryCriteria(notary = listOf(notaries as AbstractParty))
val logicalExpression = builder { CashSchemaV1.PersistentCashState::currency.equal(amountRequired.token.product.currencyCode) }
val cashCriteria = QueryCriteria.VaultCustomQueryCriteria(logicalExpression)
val fullCriteria = fungibleCriteria.and(vaultCriteria).and(cashCriteria)
val eligibleStates = serviceHub.vaultService.tryLockFungibleStatesForSpending(lockId, fullCriteria, amountRequired.withoutIssuer(), Cash.State::class.java)
check(eligibleStates.isNotEmpty()) { "Insufficient funds" }
val amount = eligibleStates.fold(0L) { tot, (state) -> tot + state.data.amount.quantity }
val change = amount - amountRequired.quantity
return Pair(eligibleStates, change)
}
}
During the CPMoveFlow, you're attempting to gather cash from your vault. However, you don't have any at this point.
In order for the cash to be used as an input into this transaction, it will need to come from somewhere. In these situations where you're building out a prototype/testing, your best bet is to self issue yourself cash.
Take a look at the code in the flow here.
Edit:
gatherOurInputs is insufficient to correctly spend cash. You will need both inputs and outputs where the inputs is cash you previously self issued and the output will x amount of that cash with the other party now as the owner.
The easiest way forward would be to use the Cash.generateSpend function which will add both the inputs and outputs for you to the transaction e.g.
Cash.generateSpend(serviceHub, txBuilder, amount, otherParty)
You will now see a different error pertaining to contract verification failing for your commercial paper, but I'll leave that to you to debug. The unit test framework within Corda is really good for this.