Image courtesy of pixabay.com

Chaincode on the Go — Smart contracts on the Hyperledger Fabric blockchain

Rammohan Raja
Published in
4 min readSep 29, 2017

--

For a plain English introduction to blockchain please read Blockchain for the Businessperson. And for a brief overview on Fabric (short for Hyperledger Fabric) please go through Hyperledger Fabric brings Blockchain to the Enterprise.

Discover and review best Blockchain softwares

It took a decade and more for me to finally put my linked list knowledge to practical use. If not for blockchain technology I would have gone to my grave without using any of my linked lists skills. Next time somebody asks you about linked lists in those sad interviews, you can be content with the fact that it does have some practical use in your career.

Finally… a real life use case for linked lists.

Blockchain is a quite literally a chain of data blocks. Just like nodes in a linked list the blocks in a blockchain are linked to each other using pointers/references. You start at the latest block (head node of the linked list) and can traverse the chain all the way to the genesis block. The block in the blockchain, like the node in the linked list, contains some data (e.g. transaction data) in it, a secure hash of the previous block and a secure hash of all the data in the current block.

Rather than build your own blockchain from scratch you preferably use an existing implementation. Fabric is an open source blockchain implementation backed by IBM. It is a permissioned blockchain for use in real world business applications. Fabric provides controlled access to data while still providing all the benefits of blockchains like, shared ledger, smart contracts, privacy and consensus. This article will hover at a relatively high level to keep the learning curve as sane as possible. To further narrow the scope I will concentrate on those aspects of Fabric that are relevant to a developer.

Get Best Software Deals Directly In Your Inbox

Chaincode ≈ Stored procedure

Developers write chaincode (smart contracts in the Fabric world) that interacts with the shared ledger. An apt analogy would be stored procedure used to manipulate data in the database. Fabric was written on Go language. And as you would have guessed, the first supported language to write smart contracts/chaincode is also Go. Work is underway to support other languages. But being the eager beavers we are, we will learn Go language and write our first smart contract.

We live in a world where computer languages have become like Hollywood productions. Even before a language becomes a hit a new one is released. The game of thrones of computer languages seems to be the trend. There is no point in mastering any of these languages. By the time you do, another one would have dethroned the old favorite.

All transactions, query or update, on the ledger are done through chaincodes. Access to chaincodes is permissioned. This way we can make sure a doctor can run the chaincode to view a medical record but not anybody else. Pharmacists can only run the chaincode to view a prescription, while the doctor can run the chaincode to write a prescription.

func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
return shim.Success(nil)
}

func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {

function, args := APIstub.GetFunctionAndParameters()

if function == "queryCar" {
return s.queryCar(APIstub, args)
} else if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "createCar" {
return s.createCar(APIstub, args)
} else if function == "queryAllCars" {
return s.queryAllCars(APIstub)
} else if function == "changeCarOwner" {
return s.changeCarOwner(APIstub, args)
}

return shim.Error("Invalid Smart Contract function name.")
}

This is the skeleton of a simple chaincode implementation. It has two functions Init and Invoke. Init is called when the chaincode is first installed or when an existing chaincode is upgraded. For example, creating an asset when the chaincode is first installed. Invoke is called when we need the chaincode to query or modify the shared leger. Both functions have the reference to the shim API (shim.ChaincodeStubInterface) that is actually used to query or update the shared ledger. The state change to the shared ledger takes effect only after transaction is validated and successfully committed. The complete samples along with instructions on executing them are present here.

While we can only write chaincode in Go, we can invoke them using multiple APIs for numerous languages. For example, this is how you would call a chaincode using JavaScript.

var options = {
wallet_path: path.join(__dirname, './network/creds'),
user_id: 'PeerAdmin',
channel_id: 'mychannel',
chaincode_id: 'fabcar',
network_url: 'grpc://localhost:7051',
};

const request = {
chaincodeId: options.chaincode_id,
txId: transaction_id,
fcn: 'queryAllCars',
args: ['']
};

The complete source is available here. The example above calls the following function in the fabcar smart contract.

func (s *SmartContract) queryAllCars(APIstub shim.ChaincodeStubInterface) sc.Response {

startKey := "CAR0"
endKey := "CAR999"

................
................
................

return shim.Success(buffer.Bytes())
}

As is evident, writing a chaincode for Fabric is not rocket science. But setting up the network and getting it up and running would not be a walk in the park. Fabric project has done an excellent job of documenting the steps. I am not going to duplicate that here. So set aside a few days and load up on patience!

--

--