An introduction to chained code for Java developers

You may have heard of blockchain, but you may not be sure what it does for Java™ developers. This tutorial will help you out. I’ll show you step-by-step how to use Hyperledger Fabric V0.6 to build, run, and execute smart contract or chain code written in the Java language. You’ll install tools to define a local blockchain network, build and run a chain code smart contract.

For an overview of blockchain, see the developerWorks blog “What is blockchain? Introduction to distributed ledger technology “.

The premise condition

This tutorial assumes that you meet the following prerequisites:

  • Heard of blockchain or the Hyperledger Fabric framework
  • Moderate level of Java programming knowledge and experience with the language and platform
  • To be familiar with or (preferably) proficient in the use of:
    • Eclipse IDE
    • Docker and Docker Compose
    • Gradle
    • The Linux command line,
    • SoapUI or another HTTP client software such as Postman

You should also be able to install software on your computer with minimal guidance. Due to space constraints, I won’t cover detailed installation instructions for all the necessary software; The web site that provides your software should provide installation instructions.

Before diving into this tutorial, I want to say a few words about blockchain.

Blockchain Fundamentals

Despite all the hype around blockchain, it’s worth the money. Not only is the technology interesting in its own right, but it is disruptive and has the potential to revolutionise the way business is done on the Internet.

How to change? Let’s think about the basic attributes of a successful business transaction:

  • Trust: We have an agreement, but can I really trust you to honor it (or respect me)?
  • Transparency: Allows you to look behind the scenes (this builds trust and reduces the need for it).
  • Accountability: Defines the conditions that determine whether all parties agree that the agreement is being complied with. The health of any business relationship between two or more parties corresponds to different levels of the three attributes above (for example, more trust means less transparency is required, and vice versa), but some of these attributes must be present or problems will arise.

“Blockchain technology is being rapidly applied to software development projects near you. Are you ready?”

How does blockchain help? First, by using a common framework, business partners can build a network of trust in advance. Blockchain then provides transparency by using a ledger that is visible to all trading parties. Finally, accountability is established by adopting the consensus of all parties (in the form of smart contracts or linked codes).

What does this mean for Java developers?

The rapid growth of the Hyperledger community and Hyperledger Fabric means that blockchain technology is rapidly being applied to software development projects around you. Are you ready?

Development situation of blockchain technology

Sometimes, development technology can get in the way of solving a business problem. The main purpose of this tutorial is to show how to write Java chain code, so I chose the simplest combination of development techniques to do so.

That is, components in the composition have other options. In this tutorial, I’ll use Docker as a network container environment, while the other option is Vagrant with VirtualBox. If you’ve never used Vagrant, you should at least try it.

Docker is a container environment, while Vagrant uses virtualization. When combined with VirtualBox, the virtualization environment provides varying degrees of control over the computing environment, which is favored by some developers (making it an ideal choice for Fabric developers).

To learn more about the relative merits of containerization versus virtualization, see “What is a Docker?” on developerWorks blogs. A brief introduction to the benefits of containers for applications “.

If developers just want to write code and don’t have to worry about containers, virtualization, or any infrastructure, then IBM® Bluemix® is an option. Although Bluemix supports running a full IBM blockchain network, it does not currently support developing chain code in the Java language. This situation is expected to change soon, so stay tuned.

If you’re under the impression that the development of blockchain technology at the time was very unstable, you’re right. However, this means that you are exposed to blockchain and chain code at the right time (from the beginning). As the technology matures, your investment in learning it early will continue to pay off handsomely.

Blockchain is one of the disruptive technologies that could revolutionize the way everyone does business. Such technologies include not only B2B, but also B2C and even C2C. It’s really a very exciting time.

Let’s get started!

Setting up the Development Environment

To run chain code, you first need to set up your development environment.

After completing this section, you are ready to run a Hyperledger Java chain code example in which you will deploy and invoke transactions on real chain code. Then I’ll show you how to write a new chain code program (almost) from scratch.

In this section, you will:

  • Set up the network environment – for running your local blockchain network.
  • Install build software – for building your chain code.
  • Install an HTTP client – for invoking transactions on your chain code.
  • Start the blockchain network.
  • Build the Java Shim client JAR.

To be honest, there’s a lot of setup to do to write chain code. However, if you follow these instructions and work a little harder, your efforts will be well worth it.

1. Set the network environment

This tutorial will run local blockchain networks using Docker and images of pre-built blockchain network components from Docker Hub. Fabric can be built from scratch if you want (it’s open source, after all), but at this stage it’s easier to use a pre-built Hyperledger Fabric image provided in Docker Hub.

As I mentioned in the introduction, another option (which you may have seen in Hyperledger documents) is to use Vagrant and VirtualBox. Vagrant is a good choice for fabric developers, but as chain code developers, we care more about building, running, and testing chain code than dealing with fabric itself.

If you have Docker version 1.12 or higher installed, you can skip to the next section (” Installing build Software “). In the instructions below, assume that you have not yet installed Docker (that is, you are not upgrading from a previous Docker version). Docker Compose is also installed as part of the Docker installation process, a tool for defining and running applications that require multiple containers, such as the local Hyperledger blockchain network you’ll be running in this tutorial.

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

Install Docker on Mac, Windows, and Linux

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

docker -v
docker-compose -v
Copy the code

You get the following output:

$docker -v docker version 1.13.1, build 092Cba3 $docker-compose -v docker-compose version 1.11.1, build 7C5d5e4Copy the code

To see Docker in action, you can run the Hello-world image, as shown below:

$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
78445dd45222: Pull complete 
Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
Status: Downloaded newer image for hello-world:latest
 

Hello from Docker! This message shows that your installation appears to be working correctly.

 
To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image whichruns the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the  Docker client,which sent it
    to your terminal.
 
To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash
 
Share images, automate workflows, and more with a free Docker ID:
 https://cloud.docker.com/
 
For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/
Copy the code

2. Install the build software

For the build system, Hyperledger Fabric uses Gradle, which will also be used in this tutorial. Gradle is a build automation system that combines simple syntax for specifying build components with the best features of Apache Ant and Apache Maven to create a powerful build system that is easy to use. It is not surprising that so many developers are switching their projects to Gradle. Note that this article uses Gradle version 3.3. Using other versions of Gradle may cause your project to fail to build.

You can learn more about Gradle (and some of its most famous users) on the Gradle home page.

Install Gradle To install Gradle, follow the instructions below:

Install Gradle on Mac, Windows, and Linux

Verify Gradle Installation To verify Gradle installation, open a terminal window and run this command:

gradle -v
Copy the code

You should see the following output:

$gradle -v -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- gradle 3.3 ------------------------------------------------------------ Build time: 2017-01-03 15:31:04 UTC Revision: 075893 a3d0798c0c1f322899b41ceca82e4e134b Groovy: 2.4.7 Ant: Apache Ant (TM) version 1.9.6 compiled on June 29, 2015 the JVM: 1.8.0_102 (Oracle Corporation 25.102-B14) OS: Mac OS X 10.12.3x86_64Copy the code

####3. Install the HTTP client

Next you install the HTTP client software, which allows the chain code to communicate with the REST interface of the Hyperledger blockchain structure. Your browser can issue HTTP GET, but to interact with Fabric, you need to be able to issue messages via POST. This means that you need an HTTP client.

The HTTP client I chose for this tutorial is SoapUI, which provides a powerful, easy-to-use, free community version with many features.

Install SoapUI To install SoapUI, follow the instructions below:

Install SoapUI for Mac OS, Windows, and Linux

Verifying SoapUI Installation To verify that SoapUI is installed, start the application on your computer. On Mac OS, the SoapUI Starter Page is displayed when SoapUI is opened, as shown in Figure 1.

SoapUI on Mac OS X

4. Start the blockchain network

Now that you have installed the software needed to develop and test the chain code, it’s time to launch your local blockchain network. The first step is to define the configuration of the network.

First, create a directory to use as the root directory for all source code used during chained code development. In this tutorial, I will use ~ /home/myChaincode (or C:\ Home \ Chaincode on Windows).

Next, set the GOPATH environment variable to this path. We won’t compile any Go code, nor will we build Golang packages or other binaries, but the Golang terminology is fused into Hyperledger, so it’s a good idea to be familiar with the Go language and GOPATH’s way of thinking.

On Linux, run the following command:

export GOPATH=~/home/mychaincode
Copy the code

Or on Windows, you can use the following command:

SET GOPATH=C:\home\mychaincode
Copy the code

Next, Docker Compose must tell Docker Compose how to create and run a blockchain peer-to-peer network. The network is defined using YAML and should be named docker-comemage.yml. You can name the file something else, but you must specify the -f flag when you start Docker Compose. It is recommended to stick with the default name, which is docker-comedy.yml.

Create the docker-comemage. yml file in the root directory of GOPATH. Paste the following:

membersrvc:
  image: hyperledger/fabric-membersrvc
  ports:
    - "7054:7054"
  command: membersrvc vp0: image: Hyperledger /fabric-peer:x86_64-0.6.0-preview ports: -"7050:7050"
    - "7051:7051"
    - "7053:7053"
  environment:
    - CORE_PEER_ADDRESSAUTODETECT=true
    - CORE_VM_ENDPOINT=unix:///var/run/docker.sock
    - CORE_LOGGING_LEVEL=DEBUG
    - CORE_PEER_ID=vp0
    - CORE_PEER_PKI_ECA_PADDR=membersrvc:7054
    - CORE_PEER_PKI_TCA_PADDR=membersrvc:7054
    - CORE_PEER_PKI_TLSCA_PADDR=membersrvc:7054
    - CORE_SECURITY_ENABLED=false
    - CORE_SECURITY_ENROLLID=test_vp0
    - CORE_SECURITY_ENROLLSECRET=MwYpmSRjupbT
  links:
    - membersrvc
  command: sh -c "sleep 5; peer node start --peer-chaincodedev"
Copy the code

There’s a lot going on here, most of which is outside the scope of this tutorial, but I want to explain it a little bit.

  • This file tells Docker Compose to define two services:
    • Membersrvc: A member service node that provides member services; specifically, it is a certificate issuing Authority (CA) that handles all encryption and decryption (such as issuing and revoking certificates). Name the pre-built Docker image used for this purpose hyperledger/fabric-membersrvc.
    • Vp0: indicates an individual peer in the network. For development purposes, we don’t need the luxury of performing peer-to-peer authentication, just one peer node. Name the pre-built Docker image used for this purpose Hyperledger/Fabric-peer: x86_64-0.6.0-Preview. Note that because of the Fabric version upgrade, omitting the colon and subsequent characters causes a build error. The Fabric 0.6 version is specified here. Hyperledger /fabric-peer Equals Hyperledger /fabric-peer: latest.
  • Some environment variables are set by the VP0 peer. Notice that the CORE_LOGGING_LEVEL variable is set to DEBUG. This produces a lot of output, which is sometimes handy. However, if you want less output, you can change the level to INFO. See log Control in the Hyperledger Setup documentation for more information on log levels. You can find more information about the Docker Compose YML file definition on the Docker website.

Next, notice that CORE_SECURITY_ENABLED has a value of false. This means that Fabric does not require you to send end user credentials of any kind. Security is outside the scope of this tutorial, but if you are interested in learning more, you can refer to the security feature description on your chain code request.

One final word of caution: Any changes to the default Settings for any of these values, especially port values, could result in the examples in this tutorial not working. A blockchain network is a set of distributed software components that require precisely coordinated communication. It is strongly recommended that you do not change the default port values until you understand how all components of the fabric interact.

Once the blockchain is defined, you can start the local blockchain network. To do this, run Docker Compose. Navigate to your $GOPATH and execute this command:

docker-compose up
Copy the code

You should get the following output in the terminal window:

$ docker-compose up
.
.
Pulling membersrvc (hyperledger/fabric-membersrvc:latest)...
latest: Pulling from hyperledger/fabric-membersrvc
.
.
Status: Downloaded newer image for hyperledger/fabric-membersrvc:latest
Pulling vp0 (hyperledger/fabric-peer:latest)...
latest: Pulling from hyperledger/fabric-peer
.
.
Status: Downloaded newer image forhyperledger/fabric-peer:latest Creating mychaincode_membersrvc_1 Creating mychaincode_vp0_1 Attaching to mychaincode_membersrvc_1, Mychaincode_vp0_1 vp0_1 | 19:30:03. 773 [logging] LoggingInit - > DEBU 001 Setting the default logging level to DEBUGfor command 'node'Vp0_1 | 19:30:03. 773 / nodeCmd serve - > INFO 002 RunninginChaincode development mode... vp0_1 | 19:30:04. 146 / peer chatWithSomePeers - > DEBU 07 Starting up the first peer of c A new network vp0_1 | 19:30:04. 146 consensus/statetransfer verifyAndRecoverBlockchain - > DEBU 7 d Validating existing  blockchain, highest validated block is 0, Valid through 0 vp0_1 | 19:30:04. 146 consensus/statetransfer blockThread - > INFO 07 e Validated blockchain to the Genesis block vp0_1 | 19:30:04. 146 1 - > consensus/handler DEBU 07 f Starting up the message threadforConsenter vp0_1 | 19:30:04. 146 / nodeCmd serve - > INFO 080 Starting peer with ID = name:"vp0", network ID=dev, address=172.17.0.3:7051, RootNodes =, validator=trueVp0_1 | 19:30:04. 146 [rest] StartOpenchainRESTServer - > INFO 081 the Initializing the rest service on 0.0.0.0:7050, TLS is disabled. Vp0_1 | 19:30:04. 147 / peer ensureConnected - > DEBU 082 Starting peer reconnect service (touch service), with period = 6s . .Copy the code

This output tells you that the network is up and ready to accept chain code registration requests.

Note: The highlighted lines should only appear when the blockchain network is first run, as Docker needs to download the image from the Docker Hub. After images are downloaded to your computer, Docker will only pull them in if the images from the Docker Hub are newer than the images on your computer.

You are now ready to build the Java Shim client JAR, which allows Java language chain code to communicate with the Hyperledger Fabric framework.

5. Build the Java Shim client JAR

Before running the chain code sample, you need to get the latest source code from Hyperledger’s GitHub repository.

First, you need to clone Hyperledger Fabric to the local machine in order to build the chain code (Note: this is an interim measure; At some point, the Java Shim client JAR should be accessible from the main Maven repository).

Note: Recall that you previously set GOPATH to ~ /home/myChaincode on Linux (or Mac) or C:\home\ MyChaincode on Windows.

Execute this command to create the directory structure expected by the structure build script:

mkdir -p $GOPATH/src/github.com/hyperledger
Copy the code

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

cd $GOPATH/src/github.com/hyperledger
Copy the code

You need the Hyperledger source code here to build the Java Shim client JAR.

Hyperledger source code can be obtained in two ways.

  • Without Git: Navigate to the Hyperledger GitHub image, select the V0.6 branch, and click the Clone or Download button, then Click Download ZIP (see Figure 2). A group called the fabric – master. Zip zip file has been downloaded to your computer, you can unzip it to $GOPATH/src/github.com/hyperledger. Note: Be sure to change the root directory name from fabric-master to fabric when you extract the file.

  • Use git: navigate to the $GOPATH/src/github.com/hyperledger, copy the URL text field to “Clone with HTTPS” box (see the arrows in figure 2), then use the copy the URL of the executing this command:

git clone https://github.com/hyperledger/fabric.git
Copy the code

or

git clone- b v0.6 https://gerrit.hyperledger.org/r/fabricCopy the code

You should see the git command return the following terminal window output:

$ git clone https://github.com/hyperledger/fabric.git
Cloning into 'fabric'. remote: Counting objects: 26976, done. remote: Compressing objects: 100% (406/406), done. remote: Total 26976 (delta 172), reused 0 (delta 0), pack-reused 26558 Receiving objects: 100% (26976/26976) and 43.68 MiB | 4.85 MiB/s, done. Resolving deltas: 100% (15114/15114), and done.Copy the code

You are now ready to build the Java chain code Shim client JAR. Navigate to the $GOPATH/src/github.com/hyperledger/fabric/core/chaincode/shim/java and run the following two commands:

gradle -b build.gradle clean
gradle -b build.gradle build
Copy the code

The Gradle build output should look like this:

$ cd $GOPATH/src/github.com/hyperledger/fabric/core/chaincode/shim/java $ gradle -b build.gradle clean Starting a Gradle Daemon (subsequent builds will be faster) :core:chaincode:shim:java:clean BUILD SUCCESSFUL Total time: 5.422 secs $gradle - b build. Gradle build: core: chaincode: shim: Java: copyProtos the UP - TO - DATE :core:chaincode:shim:java:extractIncludeProto :core:chaincode:shim:java:extractProto UP-TO-DATE :core:chaincode:shim:java:generateProto UP-TO-DATE :core:chaincode:shim:java:compileJava :core:chaincode:shim:java:processResources :core:chaincode:shim:java:classes :core:chaincode:shim:java:jar :core:chaincode:shim:java:assemble :core:chaincode:shim:java:extractIncludeTestProto :core:chaincode:shim:java:extractTestProto UP-TO-DATE :core:chaincode:shim:java:generateTestProto UP-TO-DATE :core:chaincode:shim:java:compileTestJava UP-TO-DATE :core:chaincode:shim:java:processTestResources UP-TO-DATE :core:chaincode:shim:java:testClasses UP-TO-DATE
:core:chaincode:shim:java:test UP-TO-DATE
:core:chaincode:shim:java:check UP-TO-DATE
:core:chaincode:shim:java:build
:core:chaincode:shim:java:copyToLib
:core:chaincode:shim:java:generatePomFileForMavenJavaPublication
:core:chaincode:shim:java:publishMavenJavaPublicationToMavenLocal
:core:chaincode:shim:java:publishToMavenLocal
 
BUILD SUCCESSFUL
 
Total time: 4.521 secs
Copy the code

The last thing you do during the build process is add the Shim client JAR to your local Maven repository. You are now ready to build the chain code. There is no need to run the Java Shim client JAR again unless you want to update the structural source code at some point in the future, or you want to rebuild the ShiM client JAR again for some reason.

If you want to learn about ethereum DApp development effectively, you can visit the most popular online interactive tutorials provided by Wisdom:

  • Suitable for blockchain novices Ethereum DApp combat introductory tutorial
  • Blockchain +IPFS+Node.js+MongoDB+Express decentralized ethereum e-commerce application development practice

More content can also be found on this Ethereum blog.