Starting with Blockchain Chaincode using Golang


Chaincode, or a smart contract is a fragment of code written in supported languages like Java or Go that is deployed onto a network of HyperLedger Fabric peer nodes.

Chaincodes run network transactions which are validated and then appended to the shared ledger. In simple terms, they are encapsulation of business network transactions in a code.

In this blog, we will learn how to develop chaincode with GoLang for a blockchain network based on Hyperledger Fabric v0.6.

Development environment required for Chaincode development:

  • Go Go 1.6 install
  • Hyperledger Fabric
    • Use the following command to install Hyperledger fabric 0.6:

git clone -b v0.6 http://gerrit.hyperledger.org/r/fabric

Implementing the chaincode interface

Following are the main functions required to implement the chaincode shim interface in your Go code.

Init() :

  • Init() is called when you first deploy your chaincode.

An example of using this function with Go can be,

As the name suggests, Init() is used to do any initialization your chaincode needs. In this example, stub.PutState() stores the first value in the args argument in the key “emp_name”.

Invoke()

  • It is called when we expect some “real work” to be done by the chaincode.

Example: Every time there’s a transaction, the ledger will be updated by invoking the chaincode.

Here, the Invoke() function calls a generic write function which will help you store any key value pair in the ledger.

Query() 

  • This function is called to get the state of chaincode.
  • Query is used to  only read the value of your chaincode state’s key/value pairs and it does not add any new blocks to the ledger.

Main()

  • The starting point for any Go program is the main function, so here it is used for starting the chaincode.
  • When the peer deploys its instance of the chaincode, the main function gets executed.

  • In this example, shim.Start(new(SampleChaincode)) line is used to start the chaincode and register it with the peer.
  • To verify this locally,  run the chaincode in your development environment, which should produce the following error:

[shim] CRIT : peer.address not configured, can’t connect to peer.

 

References:

Advertisements

About Himani Arora

Software consultant at Knoldus Software LLP.
This entry was posted in Scala and tagged , , , , , , . Bookmark the permalink.

One Response to Starting with Blockchain Chaincode using Golang

  1. Prabhat Kashyap says:

    Reblogged this on Prabhat Kashyap – Scala-Trek.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s