Deploy a Single Organization Blockchain Network Using Hyperledger Fabric 2.0 and NodeJs

OrderStack
The Startup
Published in
8 min readApr 11, 2020

--

Deploy a Single Organization Blockchain Network Using Hyperledger Fabric 2.0 and NodeJs

Whenever you read something about “blockchain” the first thing that comes to your mind is Bitcoin. But blockchain provides so much more than that. Simply put, blockchain technology allows a series of interconnected computers to reach an agreement on shared data. This technology is helpful in a lot of fields that aren’t cryptocurrencies; like supply chain management, digital identity, voting, healthcare, IoT, etc.

In this article, we will talk about how you can use the Hyperledger Fabric blockchain framework to deploy your own blockchain network! The Hyperledger Fabric framework is used widely in several industry use cases such as education, healthcare, IoT, logistics, supply chain, etc. Hyperledger Fabric framework is a private blockchain and is one of the most popular and widely adopted blockchain frameworks.

The most challenging part of going through the Hyperledger Fabric documentation is that it is way too complicated to understand. After taking painstaking efforts to understand the documentation, we have come up with our own boilerplate which uses the Hyperledger Fabric samples as the code base, with our own folder structure. The folder structure and code implementation we have used are easy to understand with appropriate comments wherever needed.

Prerequisites

Before we get started, you should be familiar with the key components of the hyper ledger fabric environment as given in the official Hyperledger Fabric Getting Started documentation.

We assume you have the basic prerequisites installed. You can set up your blockchain environment with the help of the official Hyperledger Fabric documentation.

We are almost there, now all you need to do before we get started is clone https://github.com/orderstack/hyperledger-fabric-v2-starter

Getting Started

This guide works only for Linux and macOS users, this does not work on Windows platform.

After the environment is set, we can get started with the deployment.

Getting started with Hyperledger Fabric 2.0

To see the folder structure of the code, you can check out our hyperledger-fabric-v2-starter repository. There is a detailed description of the folder structure inside the repository.

This sample demonstrates how you can use Peer channel-based event services to replicate the data on your blockchain network to an off-chain database. Using an off-chain database allows you to analyze the data from your network or build a dashboard without degrading the performance of your application.

Use Case

The use case we will be testing in this article is that of marbles. This use case is from the Hyperledger Fabric documentation (You can read more about it here). A sample data of marbles with information of its owners, quantity, etc are set in the database. Every transaction of the trading of marbles is recorded in the blockchain. So whenever a marble is transferred to another owner or whenever a marble needs to be deleted from the database, its transaction is recorded in the blockchain and is immutable.

Initialize the network

Let’s start by initializing the network!

Use the following command to initialize the Hyperledger Fabric binaries and Docker images from the Hyperledger repository.

./init.sh

This command will download all the binaries for Hyperledger Fabric and related configs. This might take a while to happen.

Starting the Network

Use the following command to start the sample network:

# Before getting to the next step, make sure you change the directory to network/scriptscd ./network/scripts./network.sh up createChannel -ca

This command will deploy an instance of the Fabric test network.

The network consists of:

  • One ordering service
  • One peer organization
  • CA(Certificate Authority) for the organization

The command also creates a channel named mychannel.

If you want to run the network without the certificate authority (ca), you can run the command below:

./network.sh up createChannel

Note: This sample uses Node Fabric SDK application code similar to connect to a running instance of the Fabric test network.

Installing the Chaincode

Use the following command to install the chain code:

./deployCCSingleOrg.sh

This bash file has a series of commands which start with packaging the marbles chaincode, approving it and finally committing the chaincode to the network. This marble chaincode will be installed on the peer and deployed to the channel.

Testing the Chaincode

Use the following command to test the chain code:

./testCCSingleOrg.sh

This command will create a marble called marble5555 and try to read the marble data which has been committed to the chaincode.

The output will be as follows:

Using organization 1
Using organization 1
2020-04-09 17:22:52.587 IST [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200
waiting for chaincode to reflect
2020-04-09 17:23:02.718 IST [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200 payload:"{\"color\":\"blue\",\"docType\":\"marble\",\"name\":\"marble555\",\"owner\":\"tom\",\"size\":35}"

Summary

We have completed the following things in this section:

  • We have initialized all the required binaries for the network.
  • We have started the network and also created a channel for the organization.
  • We have installed and tested the chaincode.

Now in the following section, we will understand how to start a channel event listener by using the Hyperledger Fabric NodeJs SDK.

Channel Event Listener

Configuration

The configuration for the listener is stored in the network/code/config.json file:

{
"peer_name": "peer0.org1.example.com",
"channelid": "mychannel",
"use_couchdb": true,
"create_history_log": true,
"couchdb_address": "http://admin:password@localhost:5984"
}
  • peer_name: is the target peer for the listener.
  • channelid: is the channel name for block events.
  • use_couchdb: If set to true, events will be stored in a local instance of CouchDB. If set to false, only a local log of events will be stored.
  • create_history_log: If true, a local log file will be created with all of the block changes.
  • couchdb_address: is the local address for an off-chain CouchDB database.

Starting the channel event listener

If you set the “use_couchdb” option to true in network/code/config.json, you can run the following command to initialize the couch instance and a few more dependencies.

# Note: This command needs to be executed from the network/code directory./offChainInit.sh

This will run a series of commands

# Following command start a local instance of CouchDB using docker
docker run -e COUCHDB_USER=admin -e COUCHDB_PASSWORD=password --publish 5990:5984 --detach --name offchaindb couchdb
docker start offchaindb
# You need to install Node.js version 8.9.x to use the sample application code.
# Following command to install the required dependencies:
npm install
# After we have installed the application dependencies, we can use the Node.js SDK
# to create the identity our listener application will use to interact with the
# network. Following command is executed to enroll the admin user
node enrollAdmin.js
# Following command to register and enroll an application user
node registerUser.js
# Then we can then use our application user to start the block event listener
node blockEventListener.js

If the command is successful, you should see the output of the listener reading the configuration blocks of mychannel in addition to the blocks that recorded the approval and commitment of the marbles chaincode definition.

Listening for block events, nextblock: 0
Added block 0 to ProcessingMap
Added block 1 to ProcessingMap
Added block 2 to ProcessingMap
Added block 3 to ProcessingMap
Added block 4 to ProcessingMap
Added block 5 to ProcessingMap
Added block 6 to ProcessingMap
------------------------------------------------
Block Number: 0
------------------------------------------------
Block Number: 1
------------------------------------------------
Block Number: 2
------------------------------------------------
Block Number: 3
Block Timestamp: 2019-08-08T19:47:56.148Z
ChaincodeID: _lifecycle
[]
------------------------------------------------
...
...

blockEventListener

blockEventListener.js creates a listener named "off-chain-listener" on the channel mychannel. The listener writes each block added to the channel to a processing map called BlockMap for temporary storage and ordering purposes. blockEventListener.js uses nextblock.txt to keep track of the latest block that was retrieved by the listener. The block number may be set to a previous block number in order to replay previous blocks. The file may also be deleted and all blocks will be replayed when the block listener is started.

BlockProcessing

BlockProcessing.js runs as a daemon and pulls each block in order from the BlockMap. It then uses the read-write set of that block to extract the latest key-value data and store it in the database. The configuration blocks of mychannel does not store any data to the database because the blocks did not contain a read-write set.

The channel event listener also writes metadata from each block to a log file defined as channelid_chaincodeid.log. In this example, events will be written to a file named mychannel_marbles.log. This allows you to record a history of changes made by each block for each key in addition to storing the latest value of the world state.

Note: Leave the blockEventListener.js running in a terminal window. Open a new window to execute the next parts of the starter.

Generate data on the blockchain

Now that our listener is setup, we can generate data using the marbles chaincode and use our application to replicate the data to our database.

Open a new terminal and navigate to the network/code directory.

You can use the addMarbles.js file to add random sample data to the blockchain. The file uses the configuration information stored in addMarbles.json to create a series of marbles. This file will be created during the first execution of addMarbles.js if it does not exist. This program can be run multiple times without changing the properties. The nextMarbleNumber will be incremented and stored in the addMarbles.json file.

{
"nextMarbleNumber": 100,
"numberMarblesToAdd": 20
}

Open a new window/terminal and run the following command to add 20 marbles to the blockchain:

node addMarbles.js

This command will add sample marble data to the database.

After the marbles have been added to the ledger, use the following command to transfer one of the marbles to a new owner:

node transferMarble.js marble110 james

This command will transfer the marble named ‘marble110’ to a new owner, ‘james’ and a transaction will be recorded of this transfer.

Now run the following command to delete the marble that was transferred:

node deleteMarble.js marble110

This command will delete the marble ‘marble110’ from the database and a transaction will be recorded of the deletion of the marble.

Off-chain CouchDB storage:

If you followed the instructions above and set use_couchdb to true, blockEventListener.js will create two tables in the local instance of CouchDB. blockEventListener.js is written to create two tables for each channel and for each chaincode.

The first table is an offline representation of the current world state of the blockchain ledger. This table was created using the read-write set data from the blocks. If the listener is running, this table should be the same as the latest values in the state database running on your peer. The table is named after the channelid and chaincodeid and is named mychannel_marbles in this example. You can navigate to this table using your browser: http://127.0.0.1:5984/mychannel_marbles/_all_docs

Clean up

Note: This command needs to be executed from the network/scripts directory

If you are finished using the sample application, you can bring down the network and any accompanying artifacts by running the following command:

./network.sh down

Running the script will complete the following actions:

  • Bring down the Fabric test network.
  • Takes down the local CouchDB database.
  • Remove the certificates you generated by deleting the network/code/wallet folder.
  • Delete network/code/nextblock.txt so you can start with the first block next time you operate the listener.
  • Removes network/code/addMarbles.json.

Using this process, one can easily deploy a single-node blockchain network. More importantly, we hope it helps with providing valuable hands-on experience using blockchain.

Thanks for reading, have a productive day. Keep Coding!

--

--

OrderStack
The Startup

At OrderStack, we bring to you an augmented tech team that sells engineering as a service! We work with start-ups to build bespoke MVPs.