This chapter is mostly targeted to developers who want to learn installation, programming, unit testing, deployment, and functional testing of the Corda ledger. This chapter also comes with a sample project that can be downloaded by developers.
- 1.
Download and install Java 8 in your machine, and add the location of the bin folder of the JDK installation for the PATH variable in System Variables. You can check if Java is installed properly by checking “java -version” on the command line.
- 2.
Download git from https://git-scm.com/download and install in your machine. Again, check up through “git --version” on your command line.
- 3.
Download and install IntelliJ IDE from www.jetbrains.com/idea/download/download-thanks.html?code=IIC . This is the most suitable IDE to develop and run Corda.
Note If you still need any help in setting up the machines, then the best place to start would be to watch the CordaBootcamp videos shown in Figure 3-1, which are freely available on YouTube ( www.youtube.com/playlist?list=PLi1PppB3-YrVq5Qy_RM9Qidq0eh-nL11N ).

Corda Bootcamp videos on YouTube
The Corda community also arranges classroom as well as online sessions with CordaBootcamp, which is usually a one-day session. However, you should have some knowledge of Blockchain and expertise in Java to grasp it all in 6–8 hours. Now let’s do it manually in the chapter. But first let’s go through some of the core concepts.
States
The state class has to implement ContractState interface, which has only one method, namely, getParticipants(), which retrieves List<AbstractParty> (i.e., a list of abstract parties).
With each transaction, the data in the state object changes, and hence at any point of time a state object can have multiple historical versions and only one current version.
LinearState
OwnableState
QueryableState
SchedulableState
Note A state must implement ContractState or one of its descendants.
LinearState
In Corda, which has Blockchain-like features, data is always immutable. However, same data can have multiple versions updated by each transaction that handles the data. For example, a property represented by a data object can have different owners updated with each new transaction. However, some unique data like the propertyId should remain the same for tracking the history of transactions. For such purposes, LinearState is used.
Any state class that implements the LinearState interface represents data that can change over time. This interface comes with a default primary key known as linearId, which is a UniqueIdentifier that remains unaltered, whereas other customized data in the object implementing LinearState can get updated in later states. At any point in time, the state can have many different versions, one of them being current and the rest being historical data. However, as already mentioned, all those versions would share the same linearId. This makes the audit trail and tracking process easier.
After this chapter, you can visit chapter 6 to learn how LinearState is used in a land registry use case.
OwnableState
The OwnableState interface stands for a state with an owner and is not associated with any unique ID as linearId. This interface has just one method, withNewOwner(), which has to be implemented by the state class.
One may wonder why someone even needs an OwnableState. Well, it’s mostly used for fungible assets whose values or units may vary over a period of time and also can be interchanged, merged, and split. Let’s say I have a fungible asset of some cryptocurrencies whose owner is me; in a future transaction I may pass it on to someone else as the new owner. You can visit https://github.com/kid101/EncumbranceDemo to find a fine example of OwnableState type of Cake and Expiry state objects.
QueryableState
Implementing QueryableState, the class can access the data in the database deployed in the individual node. It comes with two methods: supportedSchemas() and generateMappedObject(). The QueryableState interface uses schemas where all or part of the main state object are stored in a local database and can produce results to fine-tune vault queries from the API layer. You can visit the land registry project in the next chapter and find how QueryableState is used for fine-tuned queries on Corda.
SchedulableState
This is mostly used for event scheduling for future actions. The only method it has is nextScheduledActivity().
There are two more classes we must discuss that are part of almost all state objects.
CordaSerializable
It’s interesting to note that not all data are permitted to be stored on Corda network. In order to whitelist only the data which are supposed to be saved, they have to be annotated with @CordaSerializable. However, all these states already do that, and hence implementing any of these states, our data in state class is marked as serializable.
Amount
The amount is a special type of class in Corda that is often a positive number associated with a currency: Amount<Currency> or asset.
Note that amounts of different tokens do not mix, and attempting to add or subtract two amounts of different currencies will throw IllegalArgumentException. Instead of representing actual value and currency fields separately, a clubbed value of amount fields is very frequently used in Corda for financial transactions.
Contract
The contract class has to implement a verify() method where we have to keep all our business logic.
Ricardian Contract
Corda uses Ricardian contracts, where prose like actual contract sentences is translated into code for validation of transactions in real time.
requireThat
requireThat
Commands
Listing 3-2.
Listing 3-3.
Time Windows
Sometimes the transactions have to be agreed by all parties within a particular time period. At that time, a “Time Window” is used with a start and end time that the notary keeps under observation. The transaction must be committed within that time period.
Listing 3-4.
We will see more examples with this method later in this chapter.
Attachment
Corda gives us the facility to transfer and store attachment files in the nodes. These attachments can be receipts, images, or shared data in PDF, jpg, doc, and similar formats; however, all such files have to be converted to zip or jar formats before saving. Refer to the eHospital project in chapter 7 for the implementation side of attachment.
LedgerTransaction
A LedgerTransaction is passed on to the contract with number of inputs, outputs, commands, attachments, notaries, and time windows. Inside contract’s verify method, we do a validation check of all.
Flow
A flow represents the business flows that involve creating new states, validating them by contracts, and committing them all to the ledger. The call() is the default function of a flow between different nodes and is marked with the @Suspendable annotation. Flow framework in Corda has the option to run many active flows running in concurrency. These flows can go on even for days.
A flow involves a FlowLogic and TransactionBuilder class.
FlowLogic
FlowLogic<T> represents a business flow where we can update the ledger, do database activity, call another flow, and so on. Here <T> represents the class that it would return. A flow can be of many different types and can have subflows as well.
InitiatingFlow
If annotated as InitiatingFlow, it means the flow can be initiated on its own.
InitiatedBy
If annotated as InitiatedBy, it means that it is initiated by another flow and cannot be hit directly. Such a flow can have a FlowLogic<Unit> as the return type if we do not wish to return anything back to the caller of the flow.
StartableByRPC
If annotated as StartableByRPC, it means the flow can be initiated by RPC connection, which is the interface between the outside of a Corda node and its internals.
FinalityFlow
A transaction is finalized by a FinalityFlow, where the transaction is sent to notary and saved to all relevant vaults for local storage.
TransactionBuilder
Inside the call() method of a flow, a TransactionBuilder is used to create a transaction, which can involve input(s), output(s), command(s), time window(s), notaries, attachments, and so on.
ProgressTracker
In a business flow, ProgressTracker helps to trace the progress of an operation. Usually we define a number of progress tracker steps each with a label and get the report on the console.
Vault
Vault is the local database of the node where only the data relevant to that node or that owner gets saved. This data can be queried and retrieved as and when required. It’s worth noting that this data can be of unconsumed (i.e., latest) or consumed (i.e., historic states) state objects. Hence, we can track all the transformations of state of a particular state object at any time. The queries can be done either on the basis of the liner ID or on any other parameter basis, which we will discuss in later in this chapter with example.
Oracles
We know that in a private permissioned distributed ledger such as Corda, all transactions happen within the network. However, what if we need data from some external services? For example, a particular transaction may need today’s exchange rate for calculation of some payment. Oracles are network services that help us to bridge such gaps by connecting to the external world and getting us the information that we need in the transaction. They can also help in committing transactions in some external service if that is a requirement of the transaction.
Project Setup
Now please download the code from github with the following instruction on the command line. This in fact is the same project as taught in the CordaBootcamp video, but with a few modifications such as completing whatever code is missing in the original source (as instructed in the videos):
git clone “ https://github.com/ ” URL provided by the Apress location“/bootcamp-cordapp.git”

Open IntelliJ IDEA IDE

Select Gradle on IntelliJ IDEA

Select location

Project on IntelliJ IDEA
TDD in Corda: Unit Testing and More
Decentralized applications take much effort to get tested with all the nodes up and running in real-life-like environments. It’s crucial to unit test the code and make sure that the contracts and flows are working as expected in all positive, negative, and boundary conditions. Unit testing can be done by using mock objects. In fact, Corda’s unit testing model inspires the adoption of a test-driven development (TDD) model where states, contracts, and flows should be written and immediately unit tested before running and testing in integration mode.
Corda API for Unit Testing
Corda provides full support for TDD for unit testing of contracts and states. It also provides built-in mock services to unit test in complete isolation. The following are a few.
MockServices
This interface helps us to write contract tests using the “ledger” method, with data and service isolation of each test with no side effects.
TestIdentity
This class represents a mocked node or party that encapsulates a test identity with a CordaX500Name (name of the individual or organization, as well as the country and locality) and a key pair, as well as a range of utility methods for use during testing.
Project Import Test

ProjectImportedOKTest
Unit Testing of State

Run StateTests
tokenStateHasIssuerOwnerAndAmountParamsOfCorrectTypeInConstructor(): Checks if TokenState can be instantiated successfully
tokenStateHasGettersForIssuerOwnerAndAmount(): Checks if issuer, owner, and amount are set properly in the object
tokenStateImplementsContractState(): Checks if the state object is actually an instance of ContractState interface
tokenStateHasTwoParticipantsTheIssuerAndTheOwner(): Checks if the participants who would be notified when state is updated include Alice and Bob (i.e., the issuer and the borrower). Note this is because we have added both in the getParticipants() method in TokenState.java

StateTests results
Unit Testing of Contract

Fix for running unit testing of contract
Then completely rebuild the project (Build ➤ Rebuild Project). Now ContractTests will work.
Unit Testing of Flow
Now open the TokenIssueFlow.java in your IDE; you will find that the code is written in the call() method with the following flow as instructed in the Bootcamp video.

IllegalStateException

Edit configurations
Listing 3-5.
Note
The forward or backward slash depends upon the OS you are working in. I am doing so on Windows, hence using “/”, whereas Mac and Linux users can use “\”.

VM options
and click Apply and then the OK button. Now you can run the FlowTests and all tests should work.
Deploy and Run
Listing 3-6.
Listing 3-7.

deployNodes
PartyA
PartyB
PartyC
Notary
truststore.jks: acts as key store for the network root CA
nodekeystore.jks: acts as key store of the node that secures identity key pairs
certificatessslkeystore.jks: acts as the store for the node’s TLS key pairs and certificates
Listing 3-8.

runnodes
Note that the build.gradle file in the project root has the most configurations related to Corda.
Now open the build.gradle file to check the configuration of nodes under “deployNodesJava” task. You can see that it has instructions to create a build folder in the “./build/nodes” location.
You can see that apart from the notary there are three more nodes named PartyA, PartyB, PartyC (i.e., four nodes in total).
Listing 3-9.

Flow list
Listing 3-10.

TokenIssueFlow with exception
Listing 3-11.

TokenIssueFlow running successfully
Open the TokenIssueFlow.java file in the IDE and check its details. Note that the order of parameters in the command line should be exactly same as the order in the constructor in TokenIssueFlow.
Vault Query
Listing 3-12.
Listing 3-13.

vaultQuery
You can see details as owner, issuer, amount, contract class, state class, notary, txhash (or transaction ID), status, and so on in this state detail.
Listing 3-14.

vaultQuery shows no data for nonparticipating nodes
We can add a web interface in front of this flow layer and expose it as a REpresentational State Transfer (REST) endpoint that the front end can hit for different kinds of services.
Exposing REST Endpoints for Integration with UI
You can use REST API to expose different services. You can use any front-end technology like angular, reactjs, or simple Java Server Pages (JSP) to integrate with the API layer. Now download the LandRegistry project, which is elaborated in the next chapter with the “gitclone ..” command from the Apress location.
cordapp: contains API class where we expose REST endpoints and flows. You can optionally have a plug-in class for attaching endpoints with front-end code. You can create a separate front-end project also. In the LandRegistry project in the next chapter, you can find how API class is used to expose REST endpoints
cordapp-contracts-states: contains all states and contracts

Project layouts
You have to run the same commands as before: “gradlew clean” and “gradlewdeployNodes” followed by “build\nodes\runnodes” to get the servers up and running before you start testing.
Functional Testing
Through REST calls
Through nodes
Let’s try both ways to test the functionality of the DApp.
Test Through REST Calls
The nodes take a little while (perhaps minutes) to run, and once they are up you can interact with them. First, let’s see if the data is actually stored in the Corda ledger. In the absence of a proper UI, you can test it using a REST client. There are many REST clients available on the market; I have used “Advanced REST Client” or ARC for Chrome browser.

TokenIssueFlow with exception
It won’t return any data as we have not added any.
Test Through Nodes
Listing 3-15.
Listing 3-16.

No output data on vaultQuery
Listing 3-17.
Listing 3-18.

Flow list
Listing 3-19.

Successful InitiatePropertyFlow run
Now again, hit the REST API with getAllCurrentPropertyDetails endpoint and see the output. This will be discussed in more detail in the next chapter.
Troubleshooting
I found many known issues while coding, for which you can refer to the following web page. Refresh the project and build every time you change anything in the setting to take effect.
https://github.com/corda/bootcamp-cordapp/wiki/Troubleshooting
Use Cases
Finance
Insurance
Travel
Manufacturing and supply chain
Healthcare
Telecommunication services
Tokenization
Agriculture
Government/land registry
We will cover one or two use cases in each of these verticals in later chapters.
Quiz
- 1.What are the different installable software packages in Corda?
- A.
Community
- B.
Enterprise
- C.
Both
- A.
- 2.A linearId is mandatory in which contract state subinterface in Corda?
- A.
LinearState
- B.
OwnableState
- A.
- 3.What are the different methods in the contract interface in Corda?
- A.
Validate
- B.
Verify
- C.
Check
- D.
Contract interface in Corda does not have any methods; it’s a marker interface
- A.
- 4.Does Corda support attachments?
- A.
Yes
- B.
No
- A.
- 5.Can we broadcast state data to multiple nodes in Corda?
- A.
Yes
- B.
No
- A.
- 6.To represent fungible assets, what kind of state object do we use?
- A.
LinearState
- B.
OwnableState
- C.
QueryableState
- D.
SchedulableState
- A.
- 7.A call() method in a flow must be annotated with which of the following?
- A.
@Suspendable
- B.
@CordaSerializable
- A.
Answers
1 C, 2 A, 3 B, 4 A, 5 A, 6 B, 7 A
Reference
Test Driven Development for Blockchain Apps with R3 Corda — How to Write Contracts and Unit Tests ( https://medium.com/corda/test-driven-development-for-blockchain-apps-with-r3-corda-how-to-write-contracts-and-unit-tests-f2360fe7a97d )