Blockchain chaincode for Java developers

Blockchain chaincode for Java developers

How to write chaincode for Hyperledger Fabric v0.6 using the Java language

Published on March 15, two thousand seventeen / Updated: March 30, 2017

You’ve most likely heard about blockchain, but maybe you’re not sure how it applies to you as a Java™ developer. This tutorial will clear up any confusion. In a step-by-step treatment, I’ll showcase you how to use the Hyperledger Fabric v0.6 to build, run, and execute clever contracts, or chaincode, written in the Java language. You’ll install devices, define your local blockchain network, and ultimately, build and run a chaincode clever contract.

Get a monthly roundup of the best free instruments, training, and community resources to help you put blockchain to work.


For this tutorial, I’ll assume that you have the following prerequisites:

  • You’ve heard of blockchain or the Hyperledger Fabric framework
  • You have intermediate Java programming skill and practice with both the language and platform
  • You are familiar with or (ideally) versed in using:
    • Eclipse IDE
    • Docker and Docker Compose
    • Gradle
    • Linux directive line
    • SoapUI or another HTTP client software, such as Postman

You should also be convenient installing software on your computer with minimal guidance. In the interest of space, I’m not including detailed installation instructions for all the software you need; the websites where you can obtain the software provide installation instructions.

Before we dive into the meat of the tutorial, I want to talk a little about blockchain.

Blockchain basics

A lot of hype surrounds blockchain, but it’s well deserved. Not only is the technology itself cool, it’s disruptive and has the potential to revolutionize the way business is done on the Internet.

Recommended content for blockchain developers

Sharpen your abilities with developerWorks tutorials, courses, blogs, and community support in the Blockchain Developer Center.

How? Well, let’s think about the fundamental attributes of a successful business deal:

  • Trust: We have a deal, but can I indeed trust you to honor it (or you me)?
  • Transparency: Permits a look “behind the curtain” (which can both build trust and lessen the need for it).
  • Accountability: Defines criteria to determine whether or not all parties agree that the deal has been honored.

The health of any business relationship inbetween two or more parties will mean varying levels of the three attributes above (for example, more trust means less transparency required, and vice versa), but some of all of them must be present, or there will be problems.

“ Blockchain technology is rapidly making its way to a software development project near you. Will you be ready? ”

How does blockchain help? Very first of all, through the use of a common framework, business fucking partners can establish an upfront network of trust. Then, through the use of a ledger that is visible to all business parties, blockchain provides transparency. Eventually, through the use of consensus from all parties in the form of brainy contracts (or chaincode), there is accountability.

So what does this mean for you as a Java developer?

The rapid growth of the Hyperledger community and the Hyperledger Fabric means that blockchain technology is rapidly making its way to a software development project near you. Will you be ready?

The blockchain technology landscape

Sometimes development technology can get in the way of solving the business problem. My main purpose is in this tutorial is to demonstrate you how to write Java chaincode, so I’ve chosen the simplest development stack for that purpose.

That said, there are other choices for the components of the stack. For this tutorial, I’ll use Docker as the network container environment, but another option is Vagrant with VirtualBox. If you’ve never used Vagrant, you should at least attempt it out.

Whereas Docker is a container environment, Vagrant uses virtualization. When combined with VirtualBox, a virtualization environment provides a different level of control over the computing environment that some developers choose (which makes it an ideal choice for fabric developers).

If you want to learn more about containerization versus virtualization, check out “What is Docker? A Primer on the Benefits of Containers for Applications” on the developerWorks blog.

IBM® Bluemix® is a choice for developers who just want to write code and not have to worry about containers, virtualization, or any infrastructure, for that matter. And albeit Bluemix supports running a total IBM Blockchain network, it does not yet support chaincode development using the Java language. I expect this to switch very soon, so stay tuned.

An ice sculpture from an avalanche?

The Hyperledger Fabric is very fluid (to put it mildly). You may notice from time to time that parts of your project just stop working. Don’t fright — this is just the nature of technology in its infancy.

If, say, you notice that a documentation link in this tutorial no longer works, the content may still exist — it’s just been moved to a different location.

Working with evolving technology can have similar pitfalls. Being an early adopter means you sometimes have to adapt, so go with the flow.

If you are getting the impression that the blockchain technology landscape is very fluid at the moment, you’re correct. However, this means you’re getting into blockchain and chaincode at just the right time: on the ground floor. As this technology matures, your investment in learning it at this early stage will pay spectacular dividends down the road.

Blockchain is one of those disruptive technologies that has the potential to revolutionize the way everyone does business. Not just B2B, but B2C, and eventually C2C. This is a very titillating time, indeed.

Let’s get embarked!

Set up your development environment

In order to run chaincode, you very first need to set up your development environment.

Once you’ve finished this section, you’ll be ready to run one of the Hyperledger Java chaincode examples, where you’ll deploy and invoke transactions on real chaincode. After that, I’ll display you how to write a fresh chaincode program from scrape (well, almost).

In this section you will:

  1. Set up the network environment — to run your local blockchain network.
  2. Install the build software — to build your chaincode.
  3. Install an HTTP client — to invoke transactions on your chaincode.
  4. Begin the blockchain network.
  5. Build the Java shim client JAR.

I won’t lie to you; there is fairly a bit of setup work to be done in order to write chaincode. But if you go after these instructions and apply a little diligence, it will be worth it.

Set up the network environment

In this tutorial, you’ll use Docker, along with pre-built blockchain network component pics from Docker Hub, to run your local blockchain network. You could build the fabric from scrape if you wished to (it’s open source, after all), but at this stage, it’s lighter to use the pre-built Hyperledger Fabric pics available in Docker Hub.

As I mentioned in the introduction, another option (and one you may see in the Hyperledger docs) is to use Vagrant and VirtualBox. Vagrant is a excellent choice for fabric developers, however as chaincode developers, we’re more worried with building, running, and testing our chaincode than working with the fabric itself.

If you already have Docker version 1.12 or higher installed, you can skip to the next section (“Install the build software”) In the instructions that go after, I’ll assume you do not have Docker installed (that is, you are not upgrading from a previous version of Docker). The Docker installation will also install Docker Compose, a implement for defining and running applications that require numerous containers, as the local Hyperledger blockchain network you will run in this tutorial does.

Install Docker

Installation instructions for Mac, Windows, and Linux can be found here:

Verify Docker installation

To test your Docker installation, open a terminal window (or instruction prompt on Windows) and type the following guidelines:

You should get output like this:

If you want to see Docker in act, you can run the hello-world pic like this:

Install the build software

For the build system, the Hyperledger Fabric uses Gradle, and you will use that for this tutorial as well. Gradle is a build automation system that combines elementary syntax to specify build components, along with the best features of Apache Ant and Apache Maven to create a powerful build system that’s effortless to use. It’s no wonder so many developers are switching their projects over to Gradle.

Read more about Gradle (and some of its high-profile users) on the Gradle main page.

Install Gradle

To install Gradle, go after the instructions here:

Verify Gradle installation

To verify your Gradle installation, open a terminal window and execute this instruction:

You should see output like this:

Install an HTTP client

Next up is the HTTP client software, which permits your chaincode to communicate with the Hyperledger blockchain fabric’s REST interface. Your browser can issue an HTTP GET , but to interact with the fabric you need to be able to POST messages. This means you need an HTTP client.

The HTTP client I’ve chosen for this tutorial is SoapUI, which provides a free community edition that’s powerful, effortless to use, and contains many features.

Install SoapUI

To install SoapUI, go after the instructions here:

Verify SoapUI installation

To verify that SoapUI is installed, begin the application on your computer. On Mac OS, SoapUI should open to the SoapUI Starter Page, shown in Figure 1.

Figure 1. SoapUI on Mac OS X

Begin the blockchain network

The Hyperledger Fabric is written in Go, and the GOPATH is a term you will see often in the Hyperledger docs, so if you plan to do much chaincode development using Hyperledger, you should get comfy with it.

The GOPATH is the root of your Go environment. Source code, binaries, and other Golang packages are all referenced relative to this path.

Now that you have installed the necessary software to develop and test your chaincode, it’s time to embark your local blockchain network. The very first step is to define the network’s configuration.

Very first, create a directory that will serve as the root of all of the source code you’ll use for chaincode development. In this tutorial I’ll use

/home/mychaincode (or C:\home\chaincode on Windows).

Next, set the GOPATH environment variable to this path. We won’t be compiling any Go code, nor building Golang packages or other binaries, but Golang terminology is baked into Hyperledger, so it’s a good idea to get comfy with thinking in terms of the Go language and GOPATH .

On Linux, you would execute this directive:

Or on Windows, you might use something like:

Next, you must tell Docker Compose how to compose and run the blockchain peer network. The definition of the network is in YAML, and you should name it docker-compose.yml. You can call the file something else, but when you embark Docker Compose, you must specify the -f flag. I recommend sticking with the default, which is docker-compose.yml.

Create the docker-compose.yml file in the root of your GOPATH . Paste in the following contents:

There is a lot going on here, much of which is beyond the scope of this tutorial, but I want to explain a few things.

  • This file tells Docker Compose to define two services:
    • membersrvc : The member services knot that provides membership services, specifically a certificate authority (CA), which is responsible for treating all of the cryptographic logistics (such as issuing and revoking certificates). The pre-built Docker photo you’ll use for this is called hyperledger/fabric-membersrvc .
    • vp0 : The lone validating peer knot in the network. For development purposes, we don’t need an extravagant validating peer network; a single peer will do. The pre-built Docker photo you will use for this is called hyperledger/fabric-peer .
  • A number of environment variables are set by the vp0 peer. Notice the CORE_LOGGING_LEVEL variable is set to DEBUG . This produces a large amount of output, which can be handy at times. However, if you want less output, switch the level to INFO . See “Logging Control” in the Hyperledger Setup docs for more information about the logging levels.

    More information can be found about the Docker Compose YML file definition on Docker’s website.

    Next, notice that the CORE_SECURITY_ENABLED value is false . This means the fabric will not require you to send any type of end-user credentials. Security is beyond the scope of this tutorial, but if you are interested in learning more, you can check out this note on security functionality for your chaincode requests.

    Ultimately, a word of caution: Switching any of these values from their defaults (especially the port values) may cause the examples in this tutorial to fail to work. A blockchain network is a set of distributed software components that require precisely coordinated communication. I very recommend you do not switch the port values from their default values until you understand how all the components of the fabric interoperate.

    Now that the blockchain network definition is in place, you’re ready to embark your local blockchain network. To do this, run Docker Compose. Navigate to your $GOPATH and execute this instruction:

    You should get output in the terminal window like this:

    This output tells you the network is up and running, and ready to accept chaincode registration requests.

    Note: The highlighted lines should only show up the very first time you run your blockchain network, because Docker has to download the photos from Docker Hub. Once they are downloaded to your computer, Docker will only pull them if the pictures from Docker Hub are newer than the ones you have on your computer.

    Now you’re ready to build the Java shim client JAR, which permits your Java language chaincode to communicate with the Hyperledger Fabric framework.

    Build the Java shim client JAR

    Before you can run the chaincode examples, you need to get the latest source code from Hyperledger’s GitHub repository.

    Very first, you will need to clone the Hyperledger Fabric on your local machine in order to build your chaincode (Note: This is a makeshift measure; at some point the Java shim client JAR should be accessible from the central Maven repository).

    Note: Recall from earlier that you set your GOPATH to

    /home/mychaincode on Linux (or Mac) or C:\home\mychaincode on Windows.

    Execute this guideline to create the directory structure the fabric build scripts expect:

    Next, navigate to the bottom of the fresh directory structure you created:

    From here you need to retrieve the Hyperledger source code so you can build the Java shim client JAR.

    There are two ways to access the Hyperledger source.

    Navigate to the Hyperledger GitHub mirror and click on the Clone or download button, then Download ZIP (see Figure Two). A ZIP file called will be downloaded to your computer, which you can extract to $GOPATH/src/ . Note: make sure to switch the name of the root directory from fabric-master to fabric when you extract the file.

    Navigate to $GOPATH/src/ , copy the URL from the text field in the “Clone with HTTPS” box (see Figure Two), and execute this instruction using the copied URL:

    You should see terminal window output like this from the git directive:

    Figure Two. Hyperledger GitHub mirror

    Now you’re ready to build the Java chaincode shim client JAR. Navigate to $GOPATH/src/ and run these two guidelines:

    The Gradle build output should look like this:

    The last thing the build does is add the shim client JAR to your local Maven repository. At this point, you’re ready to build your chaincode. Unless you update your fabric source code at some point in the future, or just want to rebuild the shim client JAR again for some reason, you won’t have to run the Java shim client JAR build again.

    Deploy and run a Java chaincode example

    Now that you’ve defined and embarked your local blockchain network, and have built and installed the Java shim client JAR to your local Maven repository, you’re ready to build, register, and invoke transactions on one of the Java chaincode examples that ship with the Hyperledger Fabric that you downloaded earlier.

    Here are the steps you’ll go after:

    1. Build the example using Gradle.
    2. Register the example with the validating peer network, by running a script that is created for you by the Gradle build.
    3. Deploy the example to the local blockchain network using SoapUI.
    4. Invoke transactions on the example chaincode using SoapUI.

    Build the example

    Navigate to the $GOPATH/src/ directory.

    Next, launch the Gradle build via the directive line using this guideline:

    You should see output like this:

    The build creates a standalone distribution that’s located within the directory build/distributions in two forms: a TAR file and a ZIP file, and each of these files contains everything you need to run the chaincode, including a script to drive it called Example.

    The Example chaincode is now ready to be registered with the local blockchain network.

    Register the example

    Make sure your local blockchain network is running. If not, you’ll need to commence it up. See the section titled “Begin the blockchain network” if you need a refresher.

    If you’re not already there, navigate to $GOPATH/src/ .

    Next, extract (or Example.tar) in the build/distributions directory:

    “Why so many files?” you may wonder. The distribution contains everything you need to run the chaincode standalone (in its own process), along with all dependent JARs.

    To register the chaincode example, within the build/distributions folder, execute the following script:

    This runs a standalone process that registers the chaincode example with the local blockchain network. You should see terminal window output like this:

    Take a look at the console for your local blockchain network, and you should see lines of output that look like this:

    Make a note of the chaincodeID name in the registration log output ( hello for the Example; see line 8 in the preceding). You’ll need that later for the JSON message when you deploy the Example chaincode through the fabric’s REST interface.

    The preceding output indicates that the Example chaincode is running and has been registered with the local blockchain validating peer network, and is ready to be deployed.

    Deploy the example

    The Hyperledger Fabric provides a REST web service interface that you use to interact with the fabric. The very first interaction with the fabric is to deploy your chaincode. Make sure your local blockchain network is running, then begin SoapUI, and click the REST button to create a fresh REST project. You should see a dialog box like Figure Three, where you come in the based URL used for all REST requests:

    Figure Three. SoapUI Fresh REST project dialog

    Come in http://localhost:7050 as the URL, then click OK. Port seven thousand fifty is the default REST port used by the fabric, and since your blockchain network is running on your local computer, you will use localhost as the host name.

    When SoapUI comes up, you can do a quick smoke test to make sure it can communicate with your local blockchain network. Expand the fresh REST resource you just created until you see Request one , then open it in the Editor window. Use GET for the method, and under resource inject /chain. Make sure to click the JSON option on the output tab, then run the request (by clicking on the arrow icon). When you execute this request, it simply comes back the current block hash in the output tab, located on the right-hand side of the editor window, as you can see in Figure Four:

    Figure Four. Blockchain smoke test

    If you see a JSON message that looks similar to the one in Figure four (the currentBlockHash value for your network will be different, of course), then you’re ready to deploy the Example chaincode.

    Right-click on the endpoint under REST Project one (http://localhost:7050) and choose Fresh Resource; you should see a “Fresh REST Resource” dialog box (see Figure Five) with a Resource Path field:

    Figure Five. SoapUI Fresh Resource dialog

    Come in /chaincode as the resource path, then click OK, and you should see the fresh resource display up in your SoapUI Projects panel. Open up the request for this resource (by default it will be called Request 1), switch the method to POST , and paste this JSON into the request area, located in the lower left corner of the request editor window:

    Three things to note:

    • Line Trio: The method value must be deploy .
    • Lines 6-7: The in the JSON message must match the chaincodeID when you registered the Example chaincode in the previous section ( hello for the Example chaincode).
    • Line 13: The id value is used to coordinate requests. You don’t need to worry about it so much for this tutorial, but notice that it is always sent back on the response (see the next listing).

    When you submit this request, the JSON output should look like this:

    Figure six shows a screenshot of what this looks like in SoapUI. The JSON output message will emerge in the output tab, which is located on the right-hand side of the request editor.

    Figure 6. SoapUI Chaincode deploy request

    The network log output in the terminal window should include lines that look like this:

    Lines 3-4 display the output indicating the network has received the deploy message and the fabric is deploying your chaincode. Lines 13-14 showcase that your chaincode has been deployed successfully.

    Take note of output like this in the terminal window running your chaincode:

    I’ve included all of the output for context, and you should see lines like 11-13 when you send the deploy message to your blockchain network.

    Invoke a transaction on the example

    Eventually, you will invoke the hello method and see it demonstrate up in the log messages of the terminal window running your chaincode.

    Under the chaincode resource in SoapUI, right-click on Method 1 and choose Clone Method. Call the method Invoke , and click OK. Open Request 1 under your fresh Invoke method and paste in this JSON request:

    When you run the request, you should see this JSON response:

    Figure seven shows a screenshot of what this looks like in SoapUI.

    Figure 7. SoapUI Chaincode invoke request

    The network log output should include lines that look like this:

    And the chaincode log output like this:

    Once again, I’ve shown all the chaincode output. You can see where the hello function was invoked (line 16).

    Now you’ve seen how to build, deploy, and run Java chaincode on your local blockchain network. In the next section, you’ll write a chaincode program (almost) from scrape using the Eclipse IDE, build the chaincode program using Gradle, and exercise it using SoapUI.

    Write your very first Java chaincode program

    In the previous section, you got familiar with how to build, run, deploy, and invoke chaincode, but you haven’t yet written any Java code.

    In this section, you’ll use the Eclipse IDE, a plugin for Gradle that works with Eclipse, and a skeleton Java chaincode project called ChaincodeTutorial to write your very first Java chaincode program. You’ll get the skeleton code from a GitHub repo I created for this tutorial, import that code into Eclipse, add code to make the chaincode clever contract function according to the requirements, and build that code using Gradle from within your Eclipse IDE.

    Here are the steps you’ll go after:

    1. Install the Gradle Buildship plugin for Eclipse.
    2. Clone the ChaincodeTutorial project from GitHub.
    3. Import the project into Eclipse.
    4. Explore the chaincode skeleton project.
    5. Write the Java chaincode.
    6. Build the Java chaincode.

    When you’ve ended this section, your chaincode will be ready to run on your local blockchain network.

    Install the Gradle Buildship plugin for Eclipse

    You can use any IDE you like, but the instructions in this tutorial are for Eclipse. Note: The Buildship Gradle plugin helps integrate Gradle with Eclipse, but you will still need to have installed Gradle on your computer.

    If you’ve been following along with the tutorial, you should already have Gradle installed on your computer; if it’s not installed, do that now. Refer to the “Install the build software” section to see how to install Gradle on your computer.

    To install the Buildship Gradle plugin for Eclipse, which helps your Gradle installation work with Eclipse, within Eclipse, go to Help > Eclipse Marketplace. In the Eclipse Marketplace dialog, come in buildship in the Find text field and click the Go button. You should see something like Figure 8, showcasing the Buildship Gradle Integration Two.0 plugin as the very first result of the search:

    Figure 8. Eclipse Marketplace: Gradle Buildship plugin

    Under Buildship Gradle Integration, click the Install button and go after the prompts. When you click Finish, the Buildship Gradle plugin for Eclipse will be installed, and you’ll be asked to restart Eclipse.

    When Eclipse reopens, Gradle should be fully integrated with your Eclipse IDE. You are now ready to clone the ChaincodeTutorial repository from GitHub.

    Clone the ChaincodeTutorial project from GitHub

    Now that you have your Eclipse IDE configured to work with Gradle, you will clone the ChaincodeTutorial code from GitHub and import the code into Eclipse. Open a directive prompt or terminal window, navigate to your $GOPATH , and execute this guideline:

    Your directive output should look something like this:

    This instruction clones the Blockchain ChaincodeTutorial repo from GitHub to your $GOPATH . It consists of a skeleton Java chaincode project you can build, run, and experiment with in your local blockchain network.

    But before you can do any of that, you need to import the code into Eclipse.

    Import the project into Eclipse

    In Eclipse, go to File > Import. > Gradle > Existing Gradle project. A wizard dialog box should open (see Figure 9).

    Figure 9. Eclipse Import Wizard: Gradle Project

    Click Next. On the dialog box that comes up next in the wizard (see Figure Ten), browse to $GOPATH/ChaincodeTutorial , and click Finish to import the project.

    Figure Ten. Eclipse Import Wizard: Gradle Project (Project root directory)

    When the project has finished importing, make sure to select the Java Perspective, and the ChaincodeTutorial project you just imported will demonstrate up in the Project Explorer view.

    Now that you have the code imported into your Eclipse workspace, you are ready to write your chaincode.

    Explore the chaincode skeleton project

    In this section you’ll explore the chaincode project so you understand how it is supposed to function before you write any Java code.

    As developers, we love to write code, so I don’t want to deprive you of the chance to write Java code. However, the project setup can be elaborate, and I don’t want that to get in the way of the main point of this tutorial. To that end, I’ve provided most of the code you will need.

    Before you leap in, let’s take a quick look at the base class, called AbstractChaincode , which is located in the com.makotojava.learn.blockchain.chaincode package, and shown in Listing 1.

    Listing 1. The AbstractChaincode class

    The very first thing I want to point out is that AbstractChaincode is a subclass of ChaincodeBase , which is from the fabric shim client (lines 7, Ten).

    Lines 17-19 demonstrate the methods you need to implement in the ChaincodeLog class (which is a subclass of AbstractChaincode ) to treat the initialization, ledger query, and log functions, respectively.

    Lines 22-36 display the run() method of the ChaincodeBase class (from the chaincode shim client), where we figure out what function has been invoked and to which handler the call should be delegated. The class is extensible in that any other functions than init and query (such as the log function) are treated by handleOther() , which you must also implement.

    Now, open the ChaincodeLog class in the com.makotojava.learn.blockchain.chaincode package.

    I’ve provided only a skeleton for you to skin out — that is, I’ve provided just enough code so that it compiles. You’ll have to write the rest of the code. You should run the JUnit tests and see that they fail (because you haven’t written the implementation yet), and why. In other words, you can use the JUnit tests as a guide for decently implementing the code.

    Now, if this feels a little over your head, don’t worry; I’ve provided the solution, which is located in com.makotojava.learn.blockchain.chaincode.solution , in case you get stuck (or if you just want a reference to guide you through the implementation).

    Write the Java chaincode

    Very first, a little background on what you need to know in order to implement the chaincode methods in ChaincodeLog . The ChaincodeStub class is how your Java chaincode communicates with the Hyperledger Fabric framework, and recall that the ledger is at the core of the transparency aspect of blockchain technology. What makes a wise contract (accountability) work is the state of the ledger, and your chaincode accesses the ledger’s state through the ChaincodeStub . By accessing the ledger state, you’re able to implement a wise contract (a.k.a., chaincode).

    There are a number of methods on ChaincodeStub that permit you to store, retrieve, and liquidate items from the ledger’s current state, but I’ll limit our discussion in this tutorial to two methods, which store and retrieve the ledger state:

    putState(String key, String value) — Stores the specified state value in the ledger, mapped according to the specified key.

    getState() — Gets the state value associated with the specified key and comebacks it as a String

    When writing the code for this tutorial, you will use the putState() and getState() functions whenever you need to store or retrieve state values from the ledger, respectively. The ChaincodeLog class only stores and retrieves values from the ledger to implement its brainy contract, so this is all you need to know to implement the methods. More complicated chaincode would make use of some of the other methods in ChaincodeStub (but those are also beyond the scope of this tutorial).

    I’m a big fan of test-driven development (TDD), so in TDD style, I’ve written the unit tests very first. Go ahead and run them and observe them fail. After that, you’ll write code that goes after the specifications until the unit tests pass. The job of the unit tests is to ensure the expected behavior, and by studying the unit tests, you should have enough information to implement the methods.

    However, I have also written javadoc comments at the top of each method that might help (in case you’re fresh to TDD or JUnit). Inbetween the code in the JUnit tests and the javadoc comments in the skeleton ChaincodeLog , you should have everything you need to implement the chaincode after you finish this section of the tutorial.

    From the Project Explorer view (in the Java perspective) navigate to the ChaincodeLogTest class, right-click on it and choose Run As > Gradle Test. When it runs, you should see something like Figure 11, showcasing the tree of all Gradle tasks that ran. Tasks that ended successfully are indicated with check marks next to them.

    Figure 11. Eclipse: Gradle Executions view

    The exclamation icons in the Gradle Executions tab indicate the Gradle tasks corresponding to the unit tests that failed (there are four and they all failed, just as we expected).

    Because of the way I’ve written the JUnit test cases, each test method corresponds to a method in ChaincodeLog that you’ll have to correctly implement as part of this tutorial.

    Implement getChaincodeID()

    Very first, you need to implement getChaincodeID() . Its contract is to come back the unique identifier for your chaincode. I’ve defined a constant called CHAINCODE_ID at the top of the ChaincodeLog class that you should use. Feel free to switch its value, but if you switch the chaincode id returned by getChaincodeID() , make sure it is unique within your network, and don’t leave behind to switch the attribute of your JSON messages as well.

    Exercise: Finish the getChaincodeID() method. If you need a reference, look in the com.makotojava.learn.blockchain.chaincode.solution package.

    Implement handleInit()

    Next, implement the handleInit() method. Its contract is to treat initializing your chaincode program, which in this case means that it will add a message (specified by the caller) to the ledger and comeback that message to the caller if the call succeeds.

    Exercise: Accomplish the handieInit() method. If you need a reference, look in the com.makotojava.learn.blockchain.chaincode.solution package.

    Implement handleQuery()

    Next up is the handleQuery() method. Its contract is to query the ledger, which it does by taking the specified key(s), querying the ledger for the value(s) that matches the key(s), and returning the value(s) to the caller. If numerous keys are specified, the values that are returned should be separated by commas.

    Be sure to write code to output the results of the query call, so you can see the results in the console output (take a peek at the solution if you want to see how I did it).

    Exercise: Finish the handleQuery() method. If you need a reference, look in the com.makotojava.learn.blockchain.chaincode.solution package.

    Implement handleOther()

    Eventually, you need to implement the handleOther() method, whose contract is to treat other messages (which is pretty broad open, but that’s why it’s extensible). This is where you will implement the log function, whose contract is to add a message specified by the caller to the ledger, and come back that message to the caller if the call was successful. This looks very similar to what happens in the init function, so perhaps you could leverage that in your implementation.

    Exercise: Finish the handleOther() method. If you need a reference, look in the com.makotojava.learn.blockchain.chaincode.solution package.

    If the code you wrote for each of the preceding exercises meets the requirements as I’ve laid them out in this section (and in the code comments), then your JUnit tests should all pass, and your chaincode should work fine when it is deployed and running in your local blockchain network.

    Recall, I’ve provided a solution in case you get stuck (but you owe it to yourself to attempt to implement the methods on your own before peeking at the solution).

    Build the Java chaincode

    Now that you’ve written your Java chaincode and all your JUnit tests pass, it’s time for you to build your chaincode using Eclipse and the Gradle Buildship plugin for Eclipse. Pull up the Gradle Tasks view by going to Window > Showcase View > Other. then search for gradle, select Gradle Tasks, and click OK. (See Figure 12.)

    Figure 12. Eclipse: Display View: Gradle Tasks view

    When the Gradle Tasks view opens, expand the ChaincodeTutorial > build knot, and select build and clean. (See Figure 13.)

    Figure 13. Eclipse: Gradle Tasks view

    Right-click on build and clean, then choose Run Gradle Tasks (Gradle will figure out the correct order to run these). Your Gradle Executions view should showcase a clean build, as shown in Figure 14, where you have only check marks next to each item.

    Figure 14. Eclipse: Gradle Executions view: clean build

    When the build finishes, you should have a directory instantaneously subordinate to your $GOPATH/ChaincodeTutorial directory (where you cloned the code from GitHub earlier) called build/distributions that contains your chaincode (this should look familiar, as you did this earlier in the tutorial for the hello example).

    Now that you have built your Java chaincode, you are ready to deploy, run, and invoke transactions on it in your local blockchain network.

    Deploy and run your Java chaincode

    In this section, you will embark and register your chaincode, deploy it, and invoke transactions on it via the Hyperledger Fabric REST interface, as you did earlier in the tutorial with the hello example. Make sure your local blockchain is running (see the section, “Embark the blockchain network” for a refresher on this).

    Here are the steps you will go after:

    1. Register your Java chaincode.
    2. Deploy your Java chaincode.
    3. Invoke transactions on your Java chaincode.

    Register your Java chaincode

    You will need to extract the build/distributions/ file and run the chaincode script, exactly as you did earlier in this tutorial when running the hello example (see the section, “Register the example”).

    When you run the ChaincodeTutorial script, the output should look something like this:

    Now your Java chaincode is registered with your local blockchain network, and you’re ready to deploy and test your chaincode.

    Deploy your Java chaincode

    As you did with the hello example chaincode, you will use the fabric’s REST interface to deploy and invoke transactions on your Java chaincode.

    Open SoapUI. If you are convenient doing so, you can create a fresh REST project and all of its requests yourself, or you can import the SoapUI REST project that I have included in the GitHub project you cloned earlier. The SoapUI project is located in the $GOPATH/ChaincodeTutorial directory.

    To deploy your chaincode, navigate to the ChaincodeLog Deploy request, as shown in Figure 15, and submit the request.

    Figure 15. SoapUI: ChaincodeLog Deploy request

    If you are not using the SoapUI project from GitHub (or are using a different HTTP client), the JSON request you should submit looks like this:

    Submit the request. If it succeeds you should get a JSON response like this one:

    Now your chaincode is deployed and ready to run.

    Invoke transactions on your Java chaincode

    Now that your Java chaincode is deployed and initialized, you can invoke transactions on it. In this section, you will invoke the log and query functions as transactions.

    To invoke the log function, open the ChaincodeLog Log request and submit the request. (See Figure 16.)

    Figure 16. SoapUI: ChaincodeLog log request

    If you’re not using the SoapUI project from GitHub (or are using a different HTTP client), the JSON request you should submit looks like this:

    If the request succeeds, you should get a JSON response like this one:

    To invoke the query function, open the ChaincodeLog Query request and submit the request. (See Figure 17.)

    Figure 17. SoapUI: ChaincodeLog Query request

    If you are not using the SoapUI project from GitHub (or are using a different HTTP client), the JSON request you should submit looks like this:

    If the request succeeds, you should get a JSON response like this one:

    The terminal window output of the solution code looks like this:

    Congratulations! You’ve just taken the very first step into your future.

    I encourage you to play around with the ChaincodeTutorial project, add methods to it, switch the implementations, and so forward. Get comfy with writing chaincode. Good luck, and have joy!


    This tutorial gave you a brief overview of blockchain technology and of the wise contract, which is implemented as a chaincode program, and the current technology landscape with respect to blockchain.

    We went through the steps to set up your Java chaincode development environment, including the software you need to install, how to define and run your local blockchain network, and how to deploy and invoke transactions against one of the example Java chaincode programs from the Hyperledger Fabric project in GitHub.

    You learned how to use Eclipse, JUnit, and Gradle to write and build your very first Java chaincode program, and then deploy and invoke transactions against your Java chaincode program.

    You’ve taken a hands-on look at blockchain technology and brainy contracts, and are placed flawlessly to write more complicated Java chaincode as blockchain technology matures and proliferates in the marketplace.

    So where you do you go from here?

    Next steps

    Here are a few suggestions to help you build on what you’ve learned so far:

    Related video:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *