Tag Archives: Chaincode

Posted on Mon, Apr 22, 2019 @ 2:05 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 a blockchain application.

We (OFS) are building this application in IBM Blockchain Platform 2.0 Beta. Please check out my previous post — Demystifying the Fabric Chaincode with an Example for better continuity.

In this post, I will cover the nitty-gritty of invoking a fabric chaincode from your application with code samples. This post will get fairly technical quickly.

Going back to the design and architecture of our sample application, you can see that any calls to the Hyperledger Fabric are delegated to Hyperledger Gateway Services:

The Hyperledger Gateway Service is composed of the following components:

Asynch Service Invocation Handler — a set of REST APIs that acts as a gateway for downstream fabric calls. The calls are asynchronous and return immediately after invocations.

Hyperledger (Fabric) Invoker — a core component that uses fabric SDK for chaincode invocations.

Event Hub — a component that listens for chaincode events and pushes the event details to subscribers.

Let us review these components in detail:

Async Service Invocation Handler

It is important to embrace async programming when developing a blockchain application, due to the numerous steps between building and proposing a transaction and adding a transaction to a blockchain.

Hyperledger (Fabric) Invoker

The job that is submitted to the executor service in the step above implements the downstream fabric calls. Conceptually the steps look like this:

Step #1 Build a Transaction Proposal request

Step #2 Send the Transaction Proposal to endorsing peers

This is a synchronous process, and the execution waits here.

Step #3 Collect and verify the Proposal responses

Step #4 Send the Proposal responses to the Orderer

Observe the CompletableFuture, then wait for the promises to resolve and take domain specific actions. Resolved promises mean successful submission to Orderer.

The fabric SDK takes care of the next two steps internally:

  • Step #5 Orderer broadcasts the blocks to all Leader peers
  • Step #6 Leader peer broadcasts the blocks to other peers in the group

Event Hub

Given the async nature of the transaction with the blockchain, we took an event-driven approach to react to the events emitted from chaincode. The events could be a new borrower application added to the blockchain, alender adding a new proposal to the blockchain, etc.

These events are baked into the chaincode and will be emitted when the related transactions are added to the blockchain.

Listening to these chaincode events from your client is fairly straightforward.

I hope this post helped you to get some insights into how to develop a fabric chaincode client using Java Fabric client SDK. Stay tuned for more.

About the Author

gan

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.

 

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.

Basics

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:

Imports

import (

“fmt”

“bytes”

“encoding/json”

“github.com/hyperledger/fabric/core/chaincode/shim”

pb “github.com/hyperledger/fabric/protos/peer”

)

Pay attention to “github.com/hyperledger/fabric/core/chaincode/shim” 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

   if

   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.PutState

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.

ChaincodeStubInterface.GetQueryResult

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

buffer.WriteString(“[“)

 

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 {

buffer.WriteString(“,”)

}

buffer.WriteString(string(queryResponse.Value))

existingApplication = true

}

buffer.WriteString(“]”)

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.

References

Package shim

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

godoc.org

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… hyperledger-fabric.readthedocs.io

About the Author

gan

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.