Unable to remove participant from further transaction on same asset - corda

Parties in the business. .
Parties A , B , C
Asset : Order
Party A sends first transaction for both parties B and C
Party B sends next transaction to A and C (on same order , we used vault query to get input state)
Now we want Party C should not receive any future transaction on this Order. When we remove C from participant list we get following error. Looks like Corda is taking participant list from input state. Please suggest a solution to the problem.
java.lang.IllegalArgumentException: Flow sessions were not provided for the following transaction participants: [O=C, L=NV, C=US]

This error message comes from the FinalityFlow:
https://github.com/corda/corda/blob/56067acd208b1b58f17cca85c0eb40ad0e9a1ff5/core/src/main/kotlin/net/corda/core/flows/FinalityFlow.kt#L159-L161
To explain why you got that error, let's go back to the definition of participants:
https://github.com/corda/corda/blob/56067acd208b1b58f17cca85c0eb40ad0e9a1ff5/core/src/main/kotlin/net/corda/core/contracts/ContractState.kt#L19
A participant is any party that should be notified when the state is created or consumed.
Following that statement, when your transaction has one (or more) inputs and one (or more) outputs, then this transaction should be recorded (i.e. finalized) in the union of all participants of all input and output states, because again; following the participants definition, they should be notified when their states are created or consumed.
That's why, finality flow expects a FlowSession for each participant in the transaction, and throws the error that you saw when it finds a missing one.
Now, regarding privacy concerns (the other part of your question); even though FinalityFlow records the finalized transaction in the union of all participants; it doesn't record all outputs states in all vaults, it has a parameter called StatesToRecord which defaults to ONLY_RELEVANT:
https://github.com/corda/corda/blob/56067acd208b1b58f17cca85c0eb40ad0e9a1ff5/core/src/main/kotlin/net/corda/core/flows/FinalityFlow.kt#L47
Which means, a node will only register the states that it participates in.
So to summarize, the transaction will be recorded in the union of all participants (of all input/output states), but each participant will only register in their vault the relevant output states.
Important: The peer node that calls ReceiveFinalityFlow might override the default value of statesToRecord and choose ALL_VISIBLE which means record all output states of the transaction whether it's a participant or not:
https://github.com/corda/corda/blob/56067acd208b1b58f17cca85c0eb40ad0e9a1ff5/core/src/main/kotlin/net/corda/core/flows/FinalityFlow.kt#L272-L274
I suggest you read my article on privacy analysis using CDL here; it's more detailed about this topic: https://blog.b9lab.com/how-to-design-a-cordapp-and-analyze-privacy-leaks-using-cdl-views-da825953ff54

Related

Corda: Update and consume ContractState in a single transaction

Problem
Consider the following design problem in Corda. Suppose that I have a ContractState, say Order, which carries an explicit status, for instance its either ALIVE or CANCELED. The latter status relates to finished orders. I would like to have a transaction which takes a single, ALIVE input state Order and consumes it while changing its status to CANCELED. Can I have an atomic transition accomplishing this task? In other words, is it possible to record the reason why a state was consumed?
Anytime a state is added as an input to a transaction, it is considered consumed.
Let's say Order has 3 attributes: Order(linearId, status, reason).
To mimic updates in Corda, your transaction will take as an input the state to be updated; and produce a new state that has the same linearId but with different values for the remaining attributes. This way all states in your vault that have the same linearId are considered different versions of the same state, there will be only one UNCONSUMED version; which is the latest version.
Order(123, ALIVE, null) ---Update Tx---> Order(123, CANCELED, "No longer needed").
You might also consider not creating an output if the state is "canceled"; you just consume it and not create an output; meaning it no longer exists on the ledger and Corda doesn't track it: Order(123, ALIVE, null) ---Cancel Tx---> no output.

Corda is it possible to issue and consume state in same flow

I am trying to do simple fund transfer from one account to another account using simple state. 2 Flows have been created one for issue of transfer request with cash transfer and flow created to just consumed that transaction. My question is, is it possible to transfer and consume state in one flow ?
As per my opinion transaction must be consumed after transfer but also want to show it on UI.
Corda RPCQuery allowed to bring information of unconsumed states only, if I consume above transaction, is there way to show consumed transactions last state?
CordaRPCOps allows you to query for unconsumed states, consumed states, or both. Here's a simple way of querying for all states:
val criteria = QueryCriteria.VaultQueryCriteria(Vault.StateStatus.ALL)
val results = proxy.vaultQueryBy<ContractState>(criteria)
To show the last consumed state, you could retrieve all the consumed states in descending order of consumption and grab the first one, as follows:
val criteria = QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED)
val sortColumn = Sort.SortColumn(SortAttribute.Standard(Sort.VaultStateAttribute.CONSUMED_TIME), Sort.Direction.DESC)
val sorting = Sort(listOf(sortColumn))
val results = proxy.vaultQueryBy<Obligation>(criteria, sorting = sorting)
val lastConsumedState = results.states[0]
From any flow, you need to call FinalityFlow, in order to notarize
and record the transaction in individual parties' vault. So I think
after the issuance (or transfer), you need to call FinalityFlow
first. Only then you can use the issued state as input for the new
transaction.
The notary is responsible for avoiding the double spend
of the input state in any transaction. So you can not use any newly
issued state (as input to new transaction), until the notary is aware
of it.
Thus I think in your case, you will need to call FinalityFlow twice, once after each transaction (i.e. issuance & consumption).

Corda Flow Participants How To Add & Remove

Can we add/remove participant in the subsequent transaction if the original transaction does not have it.
I have party A which has created one transaction and added a participant Party B. The state created in the transaction is shared with Party B. There are state properties like FirstName, LastName and Status.
Party B changes the status to green and then the transaction is completed and recorded to vault of Party B and Party A.
The same process is followed between Party A and Party C.
The same process is followed between Party A and Party D.
------Party B
/
Party A /-------Party C
\
------Party D
I have a use case wherein Party B, Party C, Party D can change the status in the state to Green. As soon as all the status becomes green, I want to initiate a flow at Party A.
What is the best way to implement this in Corda?
1) Yes you can add or remove by placing the participant inside the participant list you could initailize them as null at the start, just remember to send the flowSession to everyone that is involved in the state/transaction. However by performing this action do take note that the chain of transactions ( walk the chain ) will still apply hence the newly added participant would be able to view the history of the state so if there is a requirement for sensitive information to specific party it would be exposed to all participants for the state.
2) Yes you could do that also, there are two sections for the flow the #InitiatingFlow and the #InitiatedBy ( Responder ) flow you could put a logic here to query your vault for related transactions and do your logic operations
1)One way to do it would be to have your state property to have a List parties.
in your getParticipants() method which you've overridden in the state class return this list.
Now at the time of creating the state you can add as many parties as you want.
Once the state has been persisted. You can update this state now and add as many participants as you want to parties field.
2) Not sure in here but if you are party agnostic you can have a status ENUM in your state and make it go from PINE,PEAR,LIME,GREEN(Order of green color) and have each party update the status accordingly. Once green you can start your flow. Make your state scheduled-able and check if it's green you can start the flow to do whatever you want.
PS:This is a workaround I can think of from top of my head, I'm not sure if this an appropriate way to do it in corda.

Corda IsRelevant() work around?

There were some changes in the API for 1.0 that had removed isRelevant(). What are the best workarounds for this?
Given a use case: If there are 100 parties that want to see this queryable state and all updates pertaining to it (but read-only and doesn't need to sign), do I need to add them all to the Participants list? The "observer" role doesn't exist yet? Is there an alsoInformed or something similar for the use case of just seeing static reference data?
The general function here is a shared linear queryable state where the issuer has the master to change/update which would propagate to all parties that want to "subscribe" to these changes. I believe this might work with a broadcast to a "club", but I don't think clubs exist yet or if they're dynamic groupings of the network map.
I'll go into a bit of background before answering... The concept of relevancy still exists in the platform. As you know, in Corda there are two data persistence stores; the storage service and the vault.
The storage service
The storage service is a key -> value store that persists data such as:
Serialised flow state machines
Attachments
Transactions
The storage service is great for storing large amounts of serialised data that can be indexed and retrieved by hash. However, it is awkward if one wishes to search for data within one of the stored objects. E.g. one cannot easily search for transaction output states of a specific type when using the transaction store. The approach would be to iterate through all transactions, deserialise them one by one, and filter by output type. It's cumbersome and not very efficient. This is why the vault and the concept of relevancy exists!
The vault
The vault exists to store state objects, as opposed to transactions. There is a master states table where the state reference, transaction id (that generated the output state) and some other meta data such as whether the state is consumed (or not), is stored. There's also a table for LinearStates and a table for OwnableStates. Also, if one wishes to add an ORM to their state, a database table is created for each type of state object reflecting the ORM definition. These properties can then be queried to pull out states from the vault that meet specific queries, e.g. "Any obligation states over £1000 with Alice as the lender that have not yet been consumed". That's the power of the vault!
Relevancy
Now, it is the case that not all transactions a node receives produce states that are relevant to that node. An example would be a payment vs payment transaction where Alice sends dollars to Bob and Bob sends pounds to Alice. As Bob now owns the dollars Alice previously owned, those dollars are now not relevant for Alice. As such, Alice shouldn't record the output state representing those dollars as she does not hold the right and obligations to those dollars. What Alice does do is to mark the old dollar state as consumed, thus it will now not count towards her total dollars balance and cannot be used as an input in another transaction (as it has already been spent).
How relevancy works in Corda
So, when a node receives a new transaction, it intersects the public keys defined in the participants property of each output state with all the public keys that the VaultService is aware of. If the resultant set fora particular state is not empty, then the state is relevant for the node. Simple.
What this means is that if a node receives a transaction where their public keys are not listed in an output states' participants field, then they will not store that output state in the vault. However, they will store the transaction in the transaction store, and it can still be queried.
The concept of relevancy for OwnableStates is simple, one either owns it or they don't. The concept for LinearStates that represent multi-lateral agreements is more complex. In versions M14 and below, one could override the functionality of isRelevant in a LinearState, however in V1 this has been removed in favour of an easier approach which just compares the participants keys to the vault keys (as described above).
Implications of the V1 approach to relevancy
As the OP notes, in V1, there will be the concept of transaction observers, where nodes that were not participants of a state can still store the state in their vault and query it as a "third party" state. I.e. it cannot be consumed or contribute to balance totals but it can be queried. In the meantime, we will have to work around the absence of that feature and the options are:
For LinearStates, add all intended observers to the participants list. Then, add an additional property to the state object called something like consumers that just contains the list of participants that can consume this state in a valid transaction, i.e. sign a transaction containing it. The contract for that state will then compare those public keys in the commands to those in the consumers list. This way all the observers will still store the state in their vaults. The FinalityFlow will broadcast this transaction to all participants. You can use randomly generated public keys if you don't want the observers to be known to other participants.
For OwnableStates, like Cash, there can only be one identity in participants, the owner. So the approach would be to use the FinalityFlow to send the transaction to a set of observers, then those observers would have to get the output states directly from the transaction. Cumbersome but temporary as we are working on transaction observers at this moment: https://r3-cev.atlassian.net/browse/CORDA-663.
Just a strawman of what I understood if this were to be in code.
i.e using obligation cordapp example
Obligation State
val consumers: List<AbstractParty> = listOf(lender, borrower)
override val participants: List<AbstractParty> get() = listOf(lender, borrower, extraActor)
Contract code verify
override fun verify(tx: LedgerTransaction){
val command = tx.commands.requireSingleCommand<Commands>()
when (command.value) {
is Obligation.Issue -> requireThat {
"The signers should only be the consumers for the obligation" using
(command.signers.toSet() == obligation.consumers.map { it.owningKey }.toSet())
}
Add Command specifying the signers need only be consumers during TX creation
val utx = TransactionBuilder(notary = notary)
.addOutputState(state, OBLIGATION_CONTRACT_ID)
.addCommand(Obligation.Issue(), state.consumers.map { it.owningKey })
.setTimeWindow(serviceHub.clock.instant(), 30.seconds)
In this way, the first tx allows the extraActor to commit the state into the ledger without signing. In a future tx proposal, the extraActor here can query its state table and propose a change of lifecycle in the state using a different command, whereby this time it may require all participants (if need be) to sign the command. i.e Obligation.DoSomethingExtra command with all participant signing (command.signers.toSet() == obligation.participants.map { it.owningKey }.toSet())

Write conflict in Dynamo

Imaging that there are two clients client1 and client2, both writing the same key. This key has three replicas named A, B, C. A first receives client1's request, and then client2', while B receives client2's request, and then client1's. Now A and B must be inconsistent with each other, and they cannot resolve conflict even using Vector Clock. Am I right?
If so, it seems that it is easy to occur write conflict in dynamo. Why so many open source projects based on dynamo's design?
If you're using Dynamo and are worried about race conditions (which you should be if you're using lambda)
You can check conditionals on putItem or updateItem, if the condition fails
e.g. during getItem the timestamp was 12345, add conditional that timestamp must equal 12345, but another process updates it, changes the timestamp to 12346, your put/update should fail now, in java for example, you can catch ConditionalCheckFailedException, you can do another get item, apply your changes on top, then resubmit the put/update
To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists.
For more information about PutItem, see Working with Items in the Amazon DynamoDB Developer Guide.
Parameters:
putItemRequest - Represents the input of a PutItem operation.
Returns:
Result of the PutItem operation returned by the service.
Throws:
ConditionalCheckFailedException - A condition specified in the operation could not be evaluated.
https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/AmazonDynamoDB.html#putItem-com.amazonaws.services.dynamodbv2.model.PutItemRequest-
Can't talk about HBase, but I can about Cassandra, which is inspired in Dynamo.
If that happens in Cassandra, the most recent key wins.
Cassandra uses coordinator nodes (which can be any node), that receive the client requests and resends them to all replica nodes. Meaning each request has its own timestamp.
Imagine that Client2 has the most recent request, miliseconds after Client1.
Replica A receives Client1, which is saved, and then Client2, which is saved over Client1 since Client2 is the most recent information for that key.
Replica B receives Client2, which is saved, and then Client1, which is rejected since has an older timestamp.
Both replicas A and B have Client2, the most recent information, and therefore are consistent.

Resources