By Peter Li, Developer Evangelist at R3
Welcome! You are one of the 7.1 million active Java developers around the world, and perhaps one of the 12 million developers who have learned the Java language in their life.
In this article, I will guide you in building your very first blockchain application using Corda, a blockchain platform running inside a JVM, with only using Java. Get ready to stand out among your fellow Java peers!
What you need…
In this article, I will not go through the details on what a blockchain is and why people need blockchain. I will go directly into coding and explain the logic of decentralization as we go. So here is what you will need to follow along:
- Your choice of IDE or code editor.
- A JVM environment with a minimum of 2GB of RAM. (Most desktop/laptop/VMs are capable of running Corda. I challenge you to run your application on a Pi!).
- Last, but not least, your Java knowledge!
What shall we build…
Of course, we are going to start with a “Hello-World” app! We will build an app that sends a message of “Hello World” from one party on the blockchain to another.
In the Corda world, the blockchain application that you write is called a CorDapp. It only consists of three components:
- State: The real-world assets/objects that get created, updated, stored, and spent. For example, a loanbook, a tokenized bicycle, or a game board.
- Contract: The rules that regulate/verify the state transaction, updating, and consumption.
- Flow: The instructions that tell how each transaction should be executed.
Without further ado, Let’s start coding.
Step 1: Corda State
Clone the Cordapp-template-java at here.
Open it using your choice of the code editor, and navigate to:
In the Corda world, most of the data is transacted in an object called State. Each State will have an @BelongsToContract() annotation indicating which contract file will be used to verify this State in the transaction. State and contract are 1 to 1 pegged. Continue on our Hello-world CorDapp, we will simply add a few lines to make the above TemplateState carry a message. We will have 3 attributes for our State.
- A String message
- A message sender
- A message receiver
Create three variables, instantiate the variables, create the getters, fill out the participant’s list, and there you have it, a Corda State. Step one of creating your blockchain application is done.
Step 2: Corda Contract
Navigate to /contracts/src/main/java/com/template/contracts/TemplateContract.java
In the Corda world, every transaction that involves a State has to be verified by a contract. Each contract consists of three required components:
- A Contract Id for later reference
- A verify() method to examine the transaction
- A Commands interface to indicate the transaction’s intent regarding the State. Note that all standard contracts (excluding token contracts because they are pre-written) must utilize commands and we normally define them in an interface here for convenience.
In the Commands interface, we create a command called send, which we will later use to indicate our transaction’s intent.
In the verify() method, we ask:
- The message string that is carried in the state inside the transaction must be “Hello-World”.
By the end of this step, you will have written your contract.
Step 3: Corda Flows
Last step before you have an operational blockchain application! Navigate to /workflows/src/main/java/com/template/flows/Initiator.Java
In the Corda world, initiator flows trigger the business actions in your application. Whether it is sending a transaction or delivering a message, there has to be an initiator to signal the action. Besides the private variables and the constructor, initiator flow consists of a signature method called call() .
This method will automatically run whenever the initiator is called. This is where the payload is added to the transaction, signing, and signature collections all take place. Now, let’s fill it out to suit our Hello-World case.
In this Hello-World initiator flow, we have to:
- Get a reference to the notary service. [To prevent double spend]
- Compose the state that carries the Hello World message. [To produce the output]
- Create a new TransactionBuilder object, and add the State with Hello-World message as an output state, as well as a command to the transaction builder. [To compose the transaction]
- Verify and sign it with our KeyPair. [To self verify and sign]
- Collect the other party’s signature using the SignTransactionFlow. [To reach consensus among counter parties]
- Finalize the transaction and broadcast to all involved parties. [To store the transaction onto ledger]
And this will be the initiator flow for sending our Hello-World to the counterparty. But, we are not done here. We have to take care the responding part of this initiator. Now, navigate to /workflows/src/main/java/com/template/flows/Responder.Java
The responder flow, as its name indicates, will respond to the corresponding initiator flow from the counter party’s side. The annotation@InitiatedBy shows which initiator does it correlated to.
Similarly, the responder also has an auto-run call() the method will re-examine and save the transaction locally (on the counterparty node’s end since the responder was triggered at the counterparty side).
As of now, you have completed the writing of your very first blockchain application. Shall we try to run them?
Running the Hello-World Blockchain CorDapp…
Go to the terminal, and navigate to the project folder /cordapp-template-java/ and run the following code to deploy your application.
- ./gradlew clean deployNodes for Unix, andgradlew.bat clean deployNodes for Windows
A successful bootstrapping will yield a message of:
Now, run the following code to run the bootstrapped environment:
- ./build/nodes/runnodes for Unix, and .buildnodesrunnodes.bat for Windows.
We should be expecting three nodes starting up and launching their shell in different tabs.
Now let’s send out “Hello-world” from PartyA to PartyB.
Go to PartyA’s shell and run:
flow start Initiator sendTo: PartyB
We should be expecting the following message:
Thus far, we have sent a “Hello-World” message from one party to another party via a distributed system! But is it? Let’s check!
Navigate to PartyB’s node shell and run:
run vaultQuery contractStateType: com.template.states.TemplateState
There it is! A Template State that carries the “Hello-World” and is sent from PartyA to PartyB.
What is so ‘blockchain’ about this app?
You might wonder, wait a minute, I only see an app that sends a message between parties, where is the block? and where is the chain? By deploying and running the app, you have successfully launched a local distributed ledger system commonly referred to as “blockchain”.
The state that carries the message string is the block. And you will connect the later states that are relevant to the previously generated states via transaction, which we can view them as “chains”.
And this State-Transaction chain is only shared on the need-to-know basis between participating parties. (Recall the participant list in Step 1). Hence, in the Corda world, the data is shared distributively. There will not be a centralized database that records every parties’ transactions.
Coming back to our Hello-World sample, transaction(txHash:736AA884909641571B56AD965d3B…94E4F457C) carries the genesis block(State), that can be used as an input of another transaction and the chain will go on and on. Similar as the concept with Blockchains:
- Corda States(Blocks) are linked by Corda Transactions(Chains)
Want to learn more about building awesome blockchain applications on Corda? Be sure to visit https://corda.net, check out our community page to learn how to connect with other CorDapp developers, or sign up for one of our newsletters for the latest updates.
— Peter Li is a Developer Evangelist at R3, an enterprise blockchain software firm working with a global ecosystem of more than 350 participants across multiple industries from both the private and public sectors to develop on Corda, its open-source blockchain platform, and Corda Enterprise, a commercial version of Corda for enterprise usage.
Follow Peter on twitter here.