Reader small image

You're reading from  Hands-On Blockchain with Hyperledger

Product typeBook
Published inJun 2018
PublisherPackt
ISBN-139781788994521
Edition1st Edition
Concepts
Right arrow
Authors (6):
Nitin Gaur
Nitin Gaur
author image
Nitin Gaur

Nitin Gaur, is the director of IBM's Blockchain Labs, and an IBM Distinguished Engineer.
Read more about Nitin Gaur

Luc Desrosiers
Luc Desrosiers
author image
Luc Desrosiers

Luc Desrosiers is an IBM-certified IT architect with 20+ years of experience.
Read more about Luc Desrosiers

Venkatraman Ramakrishna
Venkatraman Ramakrishna
author image
Venkatraman Ramakrishna

Venkatraman Ramakrishna is an IBM researcher, with a BTech from IIT Kharagpur and PhD from UCLA.
Read more about Venkatraman Ramakrishna

Petr Novotny
Petr Novotny
author image
Petr Novotny

Petr Novotny is a research scientist at IBM Research, with an MSc from University College London and PhD from Imperial College London, where he was also a post-doctoral research associate.
Read more about Petr Novotny

Salman A. Baset
Salman A. Baset
author image
Salman A. Baset

Dr. Salman A. Baset is the CTO of security in IBM Blockchain Solutions.
Read more about Salman A. Baset

Anthony O'Dowd
Anthony O'Dowd
author image
Anthony O'Dowd

Anthony O'Dowd is a Distinguished Engineer at IBM, focusing on Blockchain. He led IBM's contribution to the design and development of the new smart contract and application SDKs found in Hyperledger Fabric v2. Anthony has also made significant contributions to Hyperledger Fabric documentation and samples.
Read more about Anthony O'Dowd

View More author details
Right arrow

Chapter 4. Designing a Data and Transaction Model with Golang

In Hyperledger Fabric, chaincode is a form of a smart contract written by a developer. Chaincode implements a business logic agreed upon by stakeholders of the blockchain network. The functionality is exposed to client applications for them to invoke, provided they have the correct permissions.

Chaincode runs as an independent process in its own container, isolated from the other components of the Fabric network. An endorsing peer manages the lifetime of the chaincode and of the transaction invocations. In response to client invocations, the chaincode queries and updates the ledger and generates a transactions proposal.

In this chapter, we will learn how to develop chaincode in the Go language and we will implement the smart contract business logic of the scenario. Finally, we will explore the key concepts and libraries necessary for developing a fully functional chaincode.

While in the next sections we will explore snippets of code...

Starting the chaincode development


Before we can start coding our chaincode, we need to first start up our development environment.

The steps of setting up the development environment has been explained in Chapter 3, Setting the Stage with a Business Scenario. However, we now proceed with starting up the Fabric network in dev-mode. This mode allows us to control how we built and run the chaincode. We will use this network to run our chaincode in the development environment.

Here is how we start the Fabric network in dev mode:

$ cd $GOPATH/src/trade-finance-logistics/network
$ ./trade.sh up -d true  

Note

If you encounter any error while the network start, it could be caused by some left-over Docker container.  You can resolve this by stopping the network using ./trade.sh down -d true and running the following command: ./trade.sh clean -d true. The -d true option tells our script to take action on the dev network.

Our development network is now running in four Docker containers. The network is...

Creating a chaincode


We are now ready to start to implementing our chaincode, which we will program in the Go language. There are several IDEs available that provide support for Go. Some of the better IDEs include Atom, Visual Studio Code, and many more. Whatever environment you opt for will work with our example.

The chaincode interface

Every chaincode must implement the Chaincode interface, whose methods are called in response to the received transaction proposals. The Chaincode interface defined in the SHIM package is shown in the following listing:

type Chaincode interface { 
    Init(stub ChaincodeStubInterface) pb.Response 
    Invoke(stub ChaincodeStubInterface) pb.Response 
} 

As you can see, the Chaincode type defines two functions: Init and Invoke.

Both functions have a single argument, stub, of the type ChaincodeStubInterface.

The stub argument is the main object that we will use when implementing the chaincode functionality, as it provides functions for accessing and modifying the...

Access control


Before we delve into the implementation of Chaincode functions, we need to first define our access control mechanism.

A key feature of a secure and permissioned blockchain is access control. In Fabric, the Membership Services Provider (MSP) plays a pivotal role in enabling access control. Each organization of a Fabric network can have one or more MSP providers. The MSP is implemented as a Certificate Authority (Fabric CA). More information on Fabric CA, including its documentation, is available at: https://hyperledger-fabric-ca.readthedocs.io/.

Fabric CA issues Enrollment Certificates (ecerts) for network users. The ecert represents the identity of the user and is used as a signed transaction when a user submits to Fabric. Prior to invoking a transaction, the user must therefore first register and obtain an ecert from the Fabric CA.

Fabric supports an Attribute-based Access Control (ABAC) mechanism that can be used by the chaincode to control access to its functions and data...

Implementing chaincode functions


At this point, we now have the basic building blocks of chaincode. We have the Init method, which initiates the chaincode and the Invoke method, which receives request from the client and the access control mechanism. Now, we need to define the functionality of the chaincode.

Based on our scenario, the following tables summarize the list of functions that record and retrieve data to and from the ledger to provide the business logic of the smart contract. The tables also define the access control definitions of organization member, which are needed in order to invoke the respective functions.

The following table illustrates the chaincode modification functions, that is, how to record transactions on the ledger:

Testing chaincode


Now we can write unit tests for our chaincode functions, we will use the in-built automated Go testing framework. For more information and documentation, visit Go's official website at: https://golang.org/pkg/testing/

The framework automatically seeks and executes functions with the following signature:

 func TestFname(*testing.T)

The function name Fname is an arbitrary name that must start with an uppercase letter.

Note that the test suite file containing unit tests must end with the suffix, _test.go; therefore, our test suite file will be named tradeWorkflow_test.go and placed in the same directory as our chaincode file. The first argument of the test function is of the type T, which provides functions for managing test states and supporting formatted test logs. The output of the test is written into the standard output, it can be inspected in the terminal.

SHIM mocking

The SHIM package provides a comprehensive mocking model that can be used to test chaincodes. In our unit...

Chaincode design topics


Composite keys

We often need to store multiple instances of one type on the ledger, such as multiple trade agreements, letters of credit, and so on. In this case, the keys of those instances will be typically constructed from a combination of attributes—for example, "Trade" + ID, yielding ["Trade1","Trade2", ...]. The key of an instance can be customized in the code, or API functions can be provided in SHIM to construct a composite key (in other words, a unique key) of an instance based on a combination of several attributes. These functions simplify composite key construction. Composite keys can then be used as a normal string key is used to record and retrieve values using the PutState() and GetState() functions.

The following snippet shows a list of functions that create and work with composite keys:

// The function creates a key by combining the attributes into a single string. 
// The arguments must be valid utf8 strings and must not contain U+0000 (nil byte) and...

Logging output


Logging is a vital part of system code, enabling the analysis and detection of runtime problems.

Logging in Fabric is based on the standard Go logging package, github.com/op/go-logging. The logging mechanism provides severity-based control of logs and pretty-printing decoration of messages. The logging levels are defined in decreasing order of severity, as follows:

CRITICAL | ERROR | WARNING | NOTICE | INFO | DEBUG 

The log messages are combined from all components and written into the standard error file (stderr). Logging can be controlled by the configuration of peers and modules, as well as in the code of the chaincode.

Configuration

The default configuration of peer logging is set to the level INFO, but this level can be controlled in the following ways:

  1. A command line option logging level. This option overrides default configurations, shown as follows:
peer node start --logging-level=error  

Note that any module or chaincode can be configured through the command line option,...

Summary


Design and implementation a well-functioning chaincode is a complex software engineering task which requires both the knowledge of the Fabric architecture, API functions and of GO language as well as the correct implementation of the business requirements.

In this chapter, we have learned step-by-step how to start a blockchain network in dev mode suitable for implementation and testing of the chaincode and how to use CLI to deploy and invoke chaincode. We have then learned how to implement the chaincode of our scenario. We explored the Init and Invoke functions through which Chaincode receives requests from clients, explored access control mechanism and the various APIs available to developer to implement chaincode functionality.

Finally, we learned how to test chaincode and how to integrate logging functionality into the code. To get ready for the next chapter, you should now stop your network using ./trade.sh down -d true.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-On Blockchain with Hyperledger
Published in: Jun 2018Publisher: PacktISBN-13: 9781788994521
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (6)

author image
Nitin Gaur

Nitin Gaur, is the director of IBM's Blockchain Labs, and an IBM Distinguished Engineer.
Read more about Nitin Gaur

author image
Luc Desrosiers

Luc Desrosiers is an IBM-certified IT architect with 20+ years of experience.
Read more about Luc Desrosiers

author image
Venkatraman Ramakrishna

Venkatraman Ramakrishna is an IBM researcher, with a BTech from IIT Kharagpur and PhD from UCLA.
Read more about Venkatraman Ramakrishna

author image
Petr Novotny

Petr Novotny is a research scientist at IBM Research, with an MSc from University College London and PhD from Imperial College London, where he was also a post-doctoral research associate.
Read more about Petr Novotny

author image
Salman A. Baset

Dr. Salman A. Baset is the CTO of security in IBM Blockchain Solutions.
Read more about Salman A. Baset

author image
Anthony O'Dowd

Anthony O'Dowd is a Distinguished Engineer at IBM, focusing on Blockchain. He led IBM's contribution to the design and development of the new smart contract and application SDKs found in Hyperledger Fabric v2. Anthony has also made significant contributions to Hyperledger Fabric documentation and samples.
Read more about Anthony O'Dowd

Function name

Permission to invoke

Description

requestTrade

Importer

Requests a trade agreement

acceptTrade

Exporter

Accepts a trade agreement

requestLC

Importer

Requests a letter of credit

issueLC

Importer

Issues a letter of credit

acceptLC

Exporter

Accepts a letter of...