How to implement Blockchain using IBM Services

kiran patil
YML Innovation Lab
Published in
10 min readDec 28, 2016

In this post, I will walk you through the implementations of simple amount transfer between users on Blockchain Network using IBM’s Blockchain service. If you had gone through my previous post you would now be knowing basic things about Blockchain. After going through this post which is kind of tutorial, you will be knowing how to set up your own Blockchain network, and build up decentralized applications like bitcoin etc. Before building up the applications let us understand IBM’s Blockchain key concepts and important terms.

Important concepts of Blockchain

Blockchain is a business network consisting of nodes (“members”) who exchange the items of value through a shared ledger and posses content which are always sync with others.

A business network

Blockchain network consist of decentralised nodes (market participants) connected peer-to-peer. Each node follows the protocol to validate and commit transaction in order to reach a common agreement.

Shared Ledger

It acts a source of truth for business applications which stores transaction on blockchain. It records all the transactions and it can be accessed by all the nodes. It is replicated so each participant has their own copy.

Consensus

Data in the ledger are synchronized between all the ledgers in the network. Consensus ensures that these shared ledgers are exact copies, and lowers the risk of fraudulent transactions since tampering would have to occur across many places at the exact same time.

Smart Contracts

Apart from just token system, some business application needs to perform some operations (execution of code related to some functionality). Smart Contracts are verified,signed and encoded in programming language. For example, Ethereum is an open source blockchain project built to realize the possibility of implementing a turing-complete programming language capability to implement the smart contracts.

Key terms involved in IBM’s BlockChain

The following terms are instrumental in gaining a holistic understanding of blockchain concept :

Transactor : It’s a network candidate connected to the blockchain network through a node, who is responsible for submitting the transactions from a client using API or SDK.

Transaction : Transactor makes a request to execute some function on the blockchain network. Different type of transaction are deploy, invoke, and query, which are implemented through the chaincode functions set forth in the fabric’s (explained later) API contract.

Chaincode : Embedded logic that encodes the rules for specific types of network transactions. Developers write chaincode applications and deploy them to the network. End users then invoke chaincode through a client-side application that interfaces with a network peer, or node. Chaincode runs network transactions, which if validated, are appended to the shared ledger and modify world state.

Ledger : It can be said as a system of cryptographically-linked blocks, containing transactions and the current world state. In contains data related to every transaction along with data for currently-running chaincode applications.

World state : Key-value database used by chaincodes to store their state when executed by a transaction.

Validating peer : A network node that runs the consensus protocol for the network to validate transactions and maintain the ledger. Validated transactions are appended to the ledger, in blocks. If a transaction fails consensus, it is purged from the block and therefore, not written to the ledger. A validating peer (VP) has authority to deploy, invoke and query chaincode.

Non-validating peer : A network node that functions as a proxy, connecting transactors to validating peers. A non-validating peer (NVP) forwards invocation requests to its connected validating peer (VP). It also hosts the event stream server and the REST service.

Permissioned network : A blockchain network where each node is required to maintain a member identity on the network, and each node has access to only the transactions that its permissions allow.

Fabric : The Hyperledger Fabric is an implementation of blockchain technology, leveraging familiar and proven technologies. It is a modular architecture allowing pluggable implementations of various function.

IBM’s Blockchain Service

For Blockchain developers IBM provides service on Bluemix with a choice between two four-node development and test blockchain networks, at the click of a button. Developers don’t need to start from scratch. They can directly start writing applications and deploying chaincode. IBM provides a peer-to-peer permissioned blockchain network, built on top of Hyperledger Fabric v0.6.1 code from the Linux Foundation’s Hyperledger Project. Blockchain networks are used to securely and efficiently exchange and track digital assets, and to permanently record all transactions on the shared ledger. You can go through the IBM’s Network and Application architecture to understand the IBM’s blockchain network and basic data flow of the blockchain apps.

You can go through chaincode tutorial to learn and build up chaincode which will be deployed on the network peer. After successfully deploying the chaincode, Client App/User with the help of SDK/API Interaction can make read/write calls to the chaincode shared ledger. IBM supports golang to write chaincode.

If you followed the chaincode tutorial you might be now knowing the following things :

What is chaincode?

How do I implement chaincode?

What dependencies exist?

What are the major functions?

How do I pass different values to my arguments?

How do I securely enroll a user on my network?

How do I compile my chaincode?

How do I interact with my chaincode through the REST API?

Amount Transfer Demo

Now Let’s understand how we explored the IBM’s blockchain service to build up a wallet system and allow users to send money. Since we can interact to any of the network nodes on the blockchain network through REST API , we can build up our own server in any languages which supports REST services. We used Google app engine to have server locally which can be written in golang. From our local server we make REST calls to chaincode.

Application Communication Flow

Above diagram shows the application flow of our demo. There are three distinct parts/worlds that you need to keep straight. They should be thought of as isolated environments that communicate over HTTP. This walk through will jump from one to another as we setup and explain each part. It’s important to identify which part is which. There are certain keywords and context clues to help you identify one from another.

  1. The Chaincode Part — This is GoLang code that runs on/with a peer on your blockchain network. Also, called cc. Anything blockchain happens here.
  2. The Client Side HTML/JS Part — This code is running in the user’s browser. User interaction code happens here.
  3. The Server Side Part — This App Engine Server code running our application’s backend.

Main steps involved in them are :

  1. The user will interact with our golang web server application in their browser.
  2. The client will make a http request to App Engine Server for user’s actions on web interface.
  3. App Engine Server will send http request to network peer to carry out the user’s actions.
  4. The peer will communicate to its chaincode container at its leisure (Request will stay in queue until they are executed).
  5. The cc container will carry out desired operation and record it to the ledger.

Now let’s build up our own chaincode for the demo. Every chaincode mainly contains three functions namely init() ,Query() and invoke().Let’s explore our chaincode function one by one.

init()

The Init function is called when you first deploy your chaincode. As the name implies, it is used to initialize the chaincode. In this example, Init configures the initial state of a two users as key/value pair on the ledger. We are storing name, password and balance as a value for the user.

If you carefully observe the init function , It is expecting 6 parameters (Twice [“name”,”password”,”balance”]). We are initializing two users along with password and balance to the share ledger and adding the user to the users array string.

Invoke()

The Invoke() function is generally called to do “real work” in blockchain network. For example whenever there is a transaction(need for creation of the block). Updating the ledger is achieved only by invoking your chaincode. It mainly accepts two parameters ; function name and an array of strings.

In our chaincode , Invoke function is called for two things :

Creation of new user

Amount transfer between users

So our invoke function intern calls appropriate function based on the “function” parameter that is sent in the request body of Invoke REST API.

For creating new users, the function parameter is “create_user” and the CreateUser function is expecting three parameters [“name”,”password”,”amount”]. It adds new user information to the ledger and username to the users array to maintain the users list.

For Amount transfer between users, “function” parameter is “transaction” and Transaction function is called by invoke.Transaction function is expecting three parameters [“userone”,”usertwo”,”amount”] in a way that ‘userone’ sends ‘amount’ money to ‘usertwo’. If there is no error while doing transaction operation, then appropriate amount is deducted from user1 balance and added to user2 balance. Both users value is updated at the share ledger with the help of stub.PutState function.

Query()

The Query() function is called to query your chaincode state and it does not add blocks to chain (ledger). Only deploy and Invoke functions add new blocks to the chain. We here used query function to query users state and users list.

Deploying the chaincode

To deploy the chaincode through the rest interface, the chaincode must be in Github repository and there should be user who is authenticated with network peer. We sent a deploy request to a peer, by specifying the URL for our chaincode repository and other parameters to intialize the chaincode. Below is the json body of the deploy request sent to a network peer.

You can see we sent 6 parameters in the “args” parameter as it is required by init function which is first executed when the chaincode is deployed on the network peer. If the deployment is successful you will receive 200 Ok response.

Complete chaincode go file can be found here.

Client Interface

Now let’s understand the client interface (web) for the Users (Admin and account user) and How our server is using the chaincode interface.

We developed a small web interface in golang. We hosted the server as Google App Engine(“locally”). When the server is up and running locally admin can call “http://localhost:8080/admin” through his browser. Our Server displays the admin page. Admin can see the list of the existing users and can create new user with the default password and balance.

Account User can open up “http://localhost:8080/user” page, the server will display a login page. If user logs in successfully they are redirected to the transfer asset page where the user can transfer money to any user on the list.

You can go through our Google App Engine code to have deep understanding about the HTML and server code of the demo. Here I will explain only the REST calls through curl that were made by our server to the chaincode.

Following are the use cases when the rest calls are made :

Admin creates a new user

When the admin makes a create user request from the web (“HTML”). Our server will make a POST REST call to the chaincode network. Main parameters in the request body are method,func and args along with the secure_context(authenticated user id). Since we need to call the invoke method to create user, We initialized the method = invoke , func = create_user and user parameters to the args and made a REST call to network node endpoint as shown in the curl request below

If the chaincode executes without any error and then it would have added new user to share ledger and replied back with a 200 OK response.

Amount Transfer request

When User makes the amount transfer request through the web. Our server will make POST request with the body parameters (method =‘invoke’, function = “transaction” and args =[“userone”,”usertwo”,”100”]).

Above curl post request made to the chaincode will call up the transaction function. If there is no error then `100` amount is transferred from ‘kiran’ to ‘arun’ and respective user’s balance is updated on the shared ledger.

Read User State

Query func on the chaincode is called whenever there is need of reading the current state on the ledger. User info must be read whenever the user makes a login request or reload his user’s page. So our server makes a POST request with the body parameters(method = “query”,function=”read” and args = “name”).

Above curl request is asking the chaincode to read the current state of kiran. If kiran object exists on the share ledger it will return with the user info related to kiran. Similarly, there is query request for getting the list of users which is useful for the user to select one user from the list of users to transfer money.

You can go through this video demo.

That’s all. Now you would have got basic idea about building up blockchain apps using IBM Blockchain Service.

Happy Coding. Thank you.

Developed at Innovation Labs @ Y Media Labs

--

--