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. In this blog, we will learn how to develop Chaincode using Golang for a blockchain network based on Hyperledger Fabric v0.6.
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.
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() 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”.
- 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.
- 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.
- 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.