Demystifying the Fabric Chaincode with an Example

Posted on Wed, Mar 27, 2019 @ 3:36 pm

In this series of blog posts, I will take you through the steps involved in the design, architecture, and implementation of a fully functional Enterprise Blockchain Application. I will do so by sharing content from various stages of developing a sample application for Loan Origination and Payment on Blockchain. If you follow through the end of this series, you will have a better understanding of the internal workings of the blockchain application.

We are building this application in IBM Blockchain Platform 2.0 Beta. Please check out my previous post — Design and Architecture of a Blockchain Application for better continuity.


Chaincode is the “smart contract” of Hyperledger Fabric. They encapsulate business logic and can be written in Go, Node.js, or Java. Yes, Fabric is polyglot and can provide a runtime sandbox for the chaincode to run in the previously mentioned programming languages.

A chaincode is typically used to read, write, and update the ledger of the given channel. The fabric chaincode library provides useful APIs (shim) for chaincodes to access and update its states, get access to transaction context, and also call other chaincodes. I will walk you through these with pseudocode of the chaincode we built for our sample application.

A chaincode that stores all loan requests

In our sample application, loanrequest.go is a simple chaincode that stores the loan applications of all applicants by applicant ID and provides functions to manage the lifecycle of those loan request. The state stored in the ledger is actually a key-value pair with the key being the combination of applicant ID and loan request ID, the value will be the details of the specific loan request. Let me breakdown the chaincode into smaller units for easy understanding:


import (
	pb ""

Pay attention to “” because you will need this to do pretty much anything with the ledger.

Chaincode interface

All chaincodes must implement “Chaincode” interface. This interface provides two key functions, Init and Invoke.

Init will be called once when you instantiate the chaincode or upgrade a chaincode. Use this to initialize or migrate a state.

Invoke will be called to update or query the ledger — Invoke is the entry point to your chaincode from fabric client SDK.

// The chaincode that manages the lifecycle of the loans by applicants
type LoanRequest struct {}

//Implementaion of Chaincode Interface. 

//We are not doing much in this function
func(t *LoanRequest) Init(stub shim.ChaincodeStubInterface) pb.Response {

    return shim.Success(nil)

// Invoke - Our entry point for Invocations
func(t *LoanRequest) Invoke(stub shim.ChaincodeStubInterface) pb.Response {

    function, args: = stub.GetFunctionAndParameters()

    // Handle different functions
    function == "newLoanRequest" {

        return t.publishNewLoanRequest(stub, args)
    } else if
    function == "updateRequestStatus" {

        return t.updateLoanRequest(stub, args)
    } else if
    function == "listRequestsByApplicant" {

       return t.getAllLoanRequests(stub, args)

    // No matching function received
    return shim.Error("Received unknown invoke function name - '" + function +"'")


ChaincodeStubInterface provides useful functions to query and update the states in the ledger and to invoke other chaincodes. In our case, we will use PutState to store the new loan request onto the ledger in the default channel (by installing and instantiating this chaincode in the default channel) and hence making it available for all the parties in the network.

func(t * LoanRequest) publishNewLoanRequest(stub shim.ChaincodeStubInterface, args[] 
string) pb.Response {

    var requestId string
    var err error

    //Assignments from args
    requestId = args[0] //State Key
    loanrequestJson, _: = json.Marshal(args[1]) //State Value
    err = stub.PutState(requestId, [] byte(string(loanJson))) //Initiate the Tx

    if err != nil {
        return shim.Error(err.Error())

    //Event to emit after Tx is commited
    stub.SetEvent("NewLoanRequestRecived", [] byte(string(loanId)));

    return shim.Success(nil)

As you can see the ledger stores a simple key-value pair with the key being request ID mapped to a JSON representing the loan request:

  "applicant": {
    "name": "string",
    "gender": "string",
    "age": 0,
    "ssn": 0,
    "annualIncome": 0
  "loan": {
    "amount": 0,
    "propertyId": 0,
    "propertyType": "string",
    "address": "string"

Pay attention to the stub.SetEvent because this is an instruction for the chaincode to emit an event when the transaction (PutState) is committed. This is the event our Event hub will listen and react to.

Make sure you have only one event per transaction.


Use GetQueryResult to query your ledger. You can use “selector” to query the underlying CouchDB ledger like in the sample below:

func (t *LoanRequest) getAllLoanRequests(stub shim.ChaincodeStubInterface, args []string) 
pb.Response {
	var err error
	var query string
	query = args[0]
	queryString := "{\"selector\":"+query+"}"
	applications, err := stub.GetQueryResult(queryString)
	if err != nil {
		return shim.Error(err.Error())
	defer applications.Close()

	// buffer is a JSON array containing QueryResults
	var buffer bytes.Buffer

	existingApplication := false
	for applications.HasNext() {
		queryResponse, err := applications.Next()
		if err != nil {
			return shim.Error(err.Error())
	        // Add a comma before array members,suppress it for the first array member
		if existingApplication == true {
		existingApplication = true
	stub.SetEvent("GetLoan", buffer.Bytes());
	return shim.Success(buffer.Bytes())

In conclusion, you can write a simple chaincode using the shim interfaces Chaincode and ChaincodeStubInterface.

I hope you found this short post useful. The next post in the series will be on the Java Fabric client SDK, showing how the chaincode functions can be invoked, integrating your enterprise applications to the blockchain behind the scenes. Hang tight—you are only a few steps away from fully understanding the internals of a fully functional blockchain application.


Package shim

Package shim provides APIs for the chaincode to access its state variables, transaction context and call other…

Chaincode for Developers – hyperledger-fabricdocs master documentation

whose methods are called in response to received transactions. In particular, the method is called when a chaincode…

About the Author

Ganeshram Ramamurthy is ObjectFrontier’s technical director and heads technology for presales. For many years, Ganesh has been designing and developing enterprise applications across various domains. He has a keen interest in emerging technologies and is now spearheading blockchain initiatives at OFS.

Leave a Reply

Your email address will not be published. Required fields are marked *