You are on page 1of 67

Certified Blockchain Developer Hyperledger (CBDH), Official Exam Study Guide

Book is published by Blockchain Training Alliance, Inc.


Copyright © 2018

All rights reserved. No part of this book may be reproduced or utilized in any form by any means,
electronic or mechanical, including photocopying, scanning, recording, or by information storage or
retrieval systems, without express permission in writing from the author, with the exception of small
excerpts used in published reviews.

Limit of Liability / Disclaimer of Warranty / Terms of Use


While the publisher and author have used their best efforts in preparing this book, they make no
representations or warranties with respect to the accuracy or completeness of the contents of this book
and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose.
There are no warranties which extend beyond the descriptions contained in this paragraph. No warranty
may be created or extended by sales representatives or written sales materials. The advice and
strategies contained herein may not apply or be suitable for your situation. You should consult with a
professional where appropriate. The accuracy and completeness of the information provided herein and
the opinions stated herein are not guaranteed or warranted to produce any particular results, and the
advice and strategies contained herein are not suitable for every individual. By providing information or
links to other companies or websites, the publisher and the author do not guarantee, approve or
endorse the information or products available at any linked websites or mentioned companies, or
persons, nor does a link indicate any association with or endorsement by the publisher or author. This
publication is designed to provide information with regard to the subject matter covered. It is offered or
sold with the understanding that neither the publisher nor the author is engaged in rendering legal,
accounting, investment, or other professional service. If legal advice or other expert assistance is
required, the services of a competent professional should be sought. This publication is no guarantee of
passing this exam or other exam in the future. Neither the publisher or the author shall be liable for any
loss or loss of profit or any other commercial damages, including but not limited to special, incidental,
consequential, or other damages.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 1
Table of Contents
CHAPTER 1: INTRODUCTION TO BLOCKCHAIN ................................................................7
What Is Blockchain..........................................................................................................7
Type of Networks in Blockchain ......................................................................................7
Public Network ................................................................................................................7
Permissioned Network.....................................................................................................7
Private Network .............................................................................................................. 7
The Need for Blockchain .................................................................................................8
Centralized System .........................................................................................................8
Decentralized System .....................................................................................................8
Components of Blockchain ..............................................................................................9
Consensus ......................................................................................................................9
Provenance .....................................................................................................................9
Immutability .....................................................................................................................9
Finality .............................................................................................................................9
Asset Transfer Example on Blockchain .........................................................................10
Chapter One Quiz .........................................................................................................11
CHAPTER 2: HOW BLOCKCHAIN WORKS ........................................................................14
Introduction ...................................................................................................................14
Structure of Blockchain .................................................................................................14
Block .............................................................................................................................14
Hash..............................................................................................................................15
Blockchain .....................................................................................................................15
Distributed .....................................................................................................................16
Smart Contract ..............................................................................................................16
Consensus Algorithm ....................................................................................................16
Different Types of Consensus Algorithms......................................................................16
Proof of Work ................................................................................................................16
Proof of Stake ...............................................................................................................17
Practical Byzantine Fault Tolerance (PBFT) ..................................................................17
Separate Functions (actors) of Blockchain ....................................................................17
Blockchain Developer ....................................................................................................17

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 2
Blockchain Operator ......................................................................................................17
Blockchain Regulator ....................................................................................................18
Blockchain User ............................................................................................................18
Membership Service Provider........................................................................................18
Chapter Two Quiz .........................................................................................................19
CHAPTER 3: INTRODUCTION TO HYPERLEDGER...........................................................21
What is Hyperledger ......................................................................................................21
Why Hyperledger ..........................................................................................................21
Composer Modeling Language .....................................................................................22
Hyperledger Modules and Platforms .............................................................................23
Explorer .........................................................................................................................23
Sawtooth .......................................................................................................................24
Indy ...............................................................................................................................24
Hyperledger Application ................................................................................................24
Hyperledger Architecture...............................................................................................25
Membership Services ....................................................................................................25
Blockchain .....................................................................................................................25
Chaincode .....................................................................................................................25
Membership ..................................................................................................................25
Registration services .....................................................................................................26
Identity Management .....................................................................................................26
Auditability Services ......................................................................................................26
Blockchain’s Main Components ....................................................................................26
P2P Protocol .................................................................................................................26
Distributed Ledger .........................................................................................................26
Consensus Manager .....................................................................................................26
Transaction ...................................................................................................................27
Code deploying transaction ...........................................................................................27
Code invoking transaction .............................................................................................27
Chaincode .....................................................................................................................27
REST Server .................................................................................................................28
Secure Container ..........................................................................................................28
Secure Registry .............................................................................................................28
Hyperledger Fabric........................................................................................................29
Chapter Three Quiz.......................................................................................................29

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 3
CHAPTER 4: HYPERLEDGER FABRIC FUNDAMENTALS .................................................32
Introduction ...................................................................................................................32
Fabric Definitions ..........................................................................................................32
Transactions..................................................................................................................32
Orderer..........................................................................................................................32
Ledger ...........................................................................................................................32
Nodes............................................................................................................................32
Client .............................................................................................................................33
Peer ..............................................................................................................................33
Endorser .......................................................................................................................33
Ordering nodes .............................................................................................................33
Ordering Services API ...................................................................................................33
Broadcast ......................................................................................................................33
Deliver ...........................................................................................................................33
Channels .......................................................................................................................34
Certificate Authority .......................................................................................................34
Distributed Ledger .........................................................................................................34
Nodes ...........................................................................................................................35
Channels .......................................................................................................................36
Node Types: Ordered, Anchor & Endorser ....................................................................37
Client Node: ..................................................................................................................37
Peer Node: ....................................................................................................................37
Endorsing Peers (Endorsers) ........................................................................................37
Ordering Service Nodes (Orderers) ...............................................................................38
Committing Peers (Committers) ....................................................................................38
Committing Peers Verify endorsements and validate transaction results. ......................38
HyperLedger Transaction Flow: .....................................................................................38
Endorsement Policies ....................................................................................................39
Transaction evaluation against endorsement policy ......................................................40
Membership Service Provider (MSP) ............................................................................41
Certificate Authority .......................................................................................................41
Chapter Four Quiz.........................................................................................................42
CHAPTER 5: PARTICIPANT, IDENTITIES & ACCESS CONTROL .....................................44
Introduction ...................................................................................................................44
Participants and identities .............................................................................................44

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 4
Chapter Five Quiz .........................................................................................................46
CHAPTER 6: HYPERLEDGER – CLIENT APP ....................................................................47
Introduction ...................................................................................................................47
High Level Architecture .................................................................................................47
Queries: ........................................................................................................................47
Events ...........................................................................................................................48
Chapter Six Quiz ...........................................................................................................49
CHAPTER 7: CREATING FRONT END INTERACTIVE INTERFACES ................................50
Introduction ...................................................................................................................50
Front End Application Patterns ......................................................................................50
Composer Rest Server middleware Architecture: ..........................................................50
Custom middleware pattern: ..........................................................................................51
Desktop Application Architecture ...................................................................................51
CHAPTER 8: CHAINCODE ..................................................................................................52
Importing of other files ...................................................................................................52
Choosing a location for the chaincode...........................................................................52
Initializing and invoking chaincode ................................................................................53
Implementing the chaincode application ........................................................................55
Putting All The Code Together ......................................................................................56
Chapter Eight Quiz ........................................................................................................57
CHAPTER 9: HYPERLEDGER COMPOSER .......................................................................59
Foreword .......................................................................................................................59
What is Hyperledger Composer ? .................................................................................59
Connection Profiles .......................................................................................................59
Business Network Cards ...............................................................................................59
Queries and Events.......................................................................................................60
Access Controls and Historian Registry ........................................................................60
Architecture ...................................................................................................................60
Modeling Language.......................................................................................................60
Composer System Namespaces ...................................................................................61
Declaring Resources .....................................................................................................61
Concepts .......................................................................................................................62
Primitive Types .............................................................................................................62
Arrays ...........................................................................................................................63
Relationships ................................................................................................................63

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 5
Field Validators .............................................................................................................63
Imports and Decorators .................................................................................................64
Chapter Nine Quiz.........................................................................................................65

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 6
CHAPTER 1: INTRODUCTION
TO BLOCKCHAIN
What Is Blockchain
Blockchain can be described as a growing list of data blocks which are linked to each
other and secured by cryptography. The Blockchain is in essence a record (or ledger) of
who holds what! The “what” are assets that represent anything of value, such as money,
property (personal or real), business transactions, or anything else where ownership
records are needed for tracking. Anytime an asset changes, a transaction is added to the
Blockchain. Blockchain serves as an open distributed ledger that is replicated thousands
of times in a given network. The database in a network is shared by all the computers on a
given network (possibly thousands or more) simultaneously. The links (or blocks) are
chained together by using a hashing function. Hence the term Blockchain.

Type of Networks in Blockchain

Public Network

Public networks (also referred to as non-permissioned networks) are large and


decentralized systems of networks where anyone can participate. They are expensive to
maintain and are slow. They are however more secure and immutable than private and
permissioned networks. Bitcoin and Ethereum are examples of public networks.

Permissioned Network

On a permissioned network, only authorized persons or organizations can write data onto
the blockchain. The organization authorizes people who can access and view the data.
This type of network is less expensive and easier to maintain. They are very fast and
require less storage space. The protocols and governance of these networks is authorized
by an industry consortium. An example of permissioned network is Ripple.

Private Network

In a private network, write permissions are kept centralized to one organization. Both
privacy and confidentiality are key to participants. Read permissions may be public or
restricted to an arbitrary extent. The transactions made in a private network are faster,

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 7
and a smaller transaction fee is required. It is a highly trusted network. The devices are
well connected, and any faults can be resolved by human intervention, which can be
easily approved by the users since the users trust the single organization in control of the
blockchain. An example of private network is Hyperledger Fabric.

The Need for Blockchain


Centralized System
They are many participants involved in a business network. Participants can be a
government organization, customer, suppliers, banks etc. The flow of goods, services and
transactions are managed in a business network.
In a network of many organizational partners every participant has their own copy of the
database. Each network manages their own centralized database, and each have their
own set of protocols governing their database.

Disadvantages
• Maintaining individual databases requires a lot of time and effort. Also, a failure in
one network results in the failure of the whole succeeding network.
• A lot of time is wasted in bringing up the network and continuing with the process
of transfer.
• This system of centralized distributed system is very inefficient and expensive to
maintain.
• It is vulnerable to fraud, malicious and cyber-attacks.

Decentralized System
Blockchain solves the above-mentioned problem. Blockchain is a decentralized and
distributed ledger that is used to record transactions across the network. By storing data
across its network, the blockchain eliminates the risks that come with data being held
centrally.

Advantages
• Each participant in a network has their own replicated copy of the ledgers. There is
transparency to all the participants involved in the network.
• Anyone in the network can update the records with the help of consensus.
• It helps save time because any changes made are real time.
• The decentralized distributed system of records reduces cost and effort by cutting
down intermediaries involved in the process of auditing.
• As everyone in the given network has the replicated copy of ledgers, a failure in
one node does not affect the entire network.
• Blockchain networks are highly secure because it’s a distributed system and is
highly secured with a privacy system. It creates a digital trust among two
participants as every system uses the same data and same sets of protocols for
the flow of business processes.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 8
Components of Blockchain
The components that describe the blockchain are:
Consensus
Consensus breaks away from the older design of a centralized system. In a centralized
system, it is directly operated by known and trustworthy individuals of the organization.
Blockchain on the other hand is an open decentralized database and controlled by many
individuals. To create trust, laws are enforced which decides authority and trust in the
network. This authority enables nodes to continuously and sequentially record
transactions on a public book, creating a chain of blocks.
Every participant in a business network can submit information to the blockchain. The
transaction can be mistrusting and malicious. Through consensus, the data is evaluated
and agreed by all the participants of the network. After consensus is made the transaction
gets permanently incorporated in the blockchain. All transactions are synchronized across
the network validating that only valid transactions are stored. This helps maintain
consistency and trust that the transaction committed is valid. Every blockchain has they
own algorithm for reaching consensus.
Provenance
Provenance means recording the history of data, from its inception to various stages of
the data lifecycle. Provenance provides a detailed record of how the data was collected,
where it was stored and how it is used. Blockchain holds complete provenance details of
each component of data transfer. It is accessible to all the participants in a business
network. It improves the system utilization and increases trust. It maintains a complex
system of record in supply chain based industries.
Immutability
Immutability in blockchain means once a transaction has been written and committed to
the ledger it cannot be changed. This provides trust that once the data is written it cannot
be altered. Blockchains are open distributed databases and are vulnerable to attack and
tampering of data. To prevent this, blockchain uses hashes and blocks. Hashes are the
basis of security and immutability in a blockchain by using hashes that can easily detect
whether the data is being tampered with.
Finality
Finality is same as immutability. This means that once a transaction is committed it cannot
be reverted back and changed.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 9
Asset Transfer Example on Blockchain
An example of asset transfer.

There are four companies in a business network and all are sharing a shared resource a
container.

Company A has the container initially. Company C requests for the container. The
container gets transferred from Company A to Company C. Once the container is
transferred both A & C update they individual databases. Company B and C database do
not get updated as all the participants have centralized system of database. Each
company keeps their own centralized database. Now, Company B requests for that asset.
The container either must be returned back to location A or location A has to inform
location B that the asset has been transferred to location C. This consumes a lot of time
and effort. It also creates a lot of ambiguity and is expensive to maintain.

To overcome this problem blockchain is used. In blockchain, individual nodes have the

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 10
same replicated copy of the ledger. Whenever a transaction takes place all the ledgers in
the network gets updated simultaneously. Thus, all the other nodes in the network can
find out the transactional history of the container. Blockchain ensures provenance and
immutability. It builds a digital trust among all the nodes in a network. This solves the age
old double-spend accounting problem of two parties claiming to own the same asset.

Chapter One Quiz


1. A Blockchain is by definition a ledger of ___________.
a. a computer folder
b. data
c. anything of value
d. Bitcoin

2. The Blockchain ledger is on a distributed network that is ___________.


a. shared by all the computers on the network
b. controlled by a central authority
c. controlled by a common administrator
d. shared by other non-Blockchain networks

3. Blockchain public networks are most noted for being ______________


a. very expensive to operate
b. being accessible to anyone
c. used for cryptocurrency exchange
d. all of the above

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 11
4. Permissioned networks are only used by________
a. anyone with network permissions
b. participants with a private key
c. authorized persons
d. industry officials

5. Private networks provide ______________ to it’s participants.


a. a fast network connection
b. access to anyone who needs it
c. non-centralized control
d. privacy and confidentiality

6. A centralized computer system is______________


a. very inexpensive to maintain
b. very secure
c. not suitable for use with Blockchain
d. a very good choice for a Blockchain network

7. Consensus on the Blockchain defines________________


a. agreement of a valid transaction by all the network nodes
b. basic security of the computer network
c. the labeling of each data block
d. security between two blocks of data

8. Blockchain provenance is defined as _______________


a. recording the first block of data on the Blockchain
b. a record of the network configuration
c. the history of the recorded Blockchain data
d. none of the above

9. Immutability provides the_________________


a. assurance that a transaction cannot be altered
b. network configuration cannot be changed
c. network nodes will never fail
d. guarantee that participants will never put bad information on the Blockchain

10. When an asset is transferred on the Blockchain it _______________


a. guarantees that all network nodes are functioning
b. solves the double-spend accounting problem
c. still belongs to the original owner until paperwork is completed
d. is only recorded by the recipient’s bank

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 12
Quiz Answers
1. c
2. a
3. d
4. c
5. d
6. c
7. a
8. c
9. a
10. b

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 13
CHAPTER 2: HOW
BLOCKCHAIN WORKS
Introduction
Blockchains are intended to securely exchange assets without the involvement of
middlemen. An asset is defined as anything of value. This can be money, property, title,
digital rights, or anything else deemed of value that ownership must be kept track of.
It should be noted that while most consider cryptocurrency to be an asset of value,
Blockchain technology (i.e. enterprise Blockchain) has no dependence on, and typically
does not use cryptocurrency as a token of value.
Blockchain data is served by decentralized distributed databases which work in cohesion,
to record a consensus of a transaction and store a collection of transactions into a block.
Blockchain uses cryptographic hashing to maintain the integrity of the data. Though
creating hashes is trivial for a CPU, blockchain requires the hash values to have a specific
form to get committed. This content hash attached to each block makes it immune to any
further tampering of data, thus making the block ‘immutable’. Generating a specific hash
requires many nodes working together in full throttle. With each successful transaction to
the ledger, participating nodes will be rewarded.

Structure of Blockchain
Block
A block contains data of the transaction, hash of the block and hash of the previous block.
The structure of the block is:

BLOCK 1

DATA

PREVIOUS

HASH HASH

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 14
Hash

Hashing means taking an input string of any length and giving out an output of a fixed
length. In the context of cryptocurrencies like Bitcoin, the transactions are taken as an
input and run through a hashing algorithm which gives an output of a fixed length.

Above is an example of SHA256 Hash generation. No matter how big or small your input
is, the output will always have a fixed 256-bits length.

Even if slight changes are made to the input the changes get reflected in the hash.
Blockchain hash functions makes it immutable.
Blockchain

Blockchain consist of blocks chained together using a hash. Blockchain is immutable.


Immutability is achieved by using the hash functionality.
Blockchains are secure by design as every block contains the hash of the previous block.
Any changes made are reflected throughout the chain.

BLOCK 1 BLOCK 2

DATA DATA

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 15
PREVIOUS HASH PREVIOUS HASH

HASH HASH

Distributed
The blockchain database is distributed. Every node in the network has their own copy of the
replicated ledgers. This makes the database tamper proof.
Smart Contract

Smart contracts are business logics that must be implemented in the blockchain. Smart
contracts not only define the rules and penalties around an agreement in the same way
that a traditional contract does, but also automatically enforces those obligations. Smart
contracts must run multiple times to achieve consensus. It guarantees consistency in a
transaction and detects duplicates in a blockchain. Smart contracts, often created by
computer programmers through the help of smart contract development tools, are entirely
digital and written using programming code languages such as C++, Go, Python, Java.
This code defines the rules and consequences in the same way that a traditional legal
document would, stating the obligations, benefits and penalties which may be due to
either party in various circumstances. This code can then be automatically executed by a
distributed ledger system.

Smart contracts provide autonomy in making an agreement. They also build trust as the
documents are encrypted in a shared ledger. They also back up all data as it is duplicated
many times, and transaction costs are reduced since the involvement of intermediaries
are removed.
Consensus Algorithm
Consensus algorithm is an agreement among a group of participants in a network.
Consensus in a distributed system is challenging. Consensus algorithms are resilient to
failures of nodes, partitioning of the network, message delays, messages reaching out-of-
order and corrupted messages. They also must deal with selfish and deliberately
malicious nodes.
Several algorithms are proposed in the research literature to solve this, with each algorithm
making the required set of assumptions in terms of synchrony, message broadcasts,
failures, malicious nodes, performance and security of the messages exchanged.

Different Types of Consensus Algorithms

Proof of Work
Proof of work is the most commonly used consensus algorithm. This algorithm is used by
the largest cryptocurrency, Bitcoin. In proof of work, every participant in a network does
not have to send messages to reach consensus. The miners compete to add the next
block (a set of transactions) in the chain by racing to solve an extremely difficult

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 16
cryptographic puzzle. The miner who solves the puzzle first wins the mining fee that is
paid. This is called proof of work meaning trying to prove that series of transaction are
valid.

It requires a lot of computational power and resources which makes it expensive.


Hyperledger Fabric does not support proof of work.
Proof of Stake

In proof of stake, the mining is done by a validator who is selected by the network based
on stake. A validator is a person who has the highest amount of wealth(coins). This is
efficient as there is less computational cost. No block rewards, only a transactional fee is
rewarded. It is safer as network attacks become more expensive. Ethereum is now using
proof of stake consensus.
Practical Byzantine Fault Tolerance (PBFT)

In Byzantine General Problem, Byzantine army are camped outside an enemy city, each
division commanded by its own general. The generals can communicate with one another
only by messenger. After observing the enemy, they must decide upon a common plan of
action. However, some of the generals may be traitors, trying to prevent the loyal generals
from reaching an agreement. The generals must decide on when to attack the city, but
they need a strong majority of their army to attack at the same time. The generals must
have an algorithm to guarantee that (a) all loyal generals decide upon the same plan of
action, and (b) a small number of traitors cannot cause the loyal generals to adopt a bad
plan. The loyal generals will all do what the algorithm says they should, but the traitors
may do anything they wish. The algorithm must guarantee condition (a) regardless of what
the traitors do. The loyal generals should not only reach an agreement but should agree
upon a reasonable plan.
The above problem is solved by Practical Byzantine General’s Problem. IBM backed
Hyperledger uses this consensus algorithm. In PBFT each node maintains an internal
storage. When a node receives a message, it is signed by the node to verify its format.
Once enough of the same responses are reached, then a consensus is met that the
message is a valid transaction.

Separate Functions (actors) of Blockchain

Blockchain Developer

The blockchain developer’s primary responsibility is to develop applications and smart


contracts, and design how they interact with the ledger and the other components of the
blockchain network.
Blockchain Operator
Blockchain operators are responsible for deployment and the operations part of the
blockchain.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 17
Blockchain Regulator

Regulators have the overall authority in a business network. They have high privilege to
access the ledgers content. Blockchain architects have broad understanding of
applications, smart contracts, events and integration, peers, consensus and security. They
must keep consideration about performance, maintenance, security and functioning of the
network.
Blockchain User

The blockchain users are the participants in a network. They interact with the blockchain
without knowing the internal functionality of the blockchain.
Membership Service Provider

The Membership Service Provider (MPS) manages the different type of certificates
needed for permissions in the network. The MSP is used to sign, verify, provision, and
authenticate all certificates in Hyperledger fabric. Hyperledger Fabric allows for multiple
certification authorities to be setup for multiple network members at the same time. X.509
is the most popular certificate used. It is defined as follows:

X.509 Certificate
Definition - What does X.509 Certificate mean?
An X.509 certificate is any certificate under the X.509 specification standard for public key
infrastructure and Privilege Management Infrastructure (PMI).
The X.509 provides standardized formats for:
• Attribute certificates
• Public key certificates
• Certificate revocation lists
• Certification validation algorithms
These certificates are used for identity validation and for transmission of encrypted data
that only the owner (person, organization or software) of a specific certificate is able to
decrypt and read.
X.509 certificates act as secure identifiers, digital passports which contain information
about the owner. The certificate is tied to a public key value which is associated with the
identity contained in the certificate. This tells the application or server that the entity trying
to access it is legitimate and known, and should be given access.
The certificate contains information regarding the subject of a certificate (the owner) and
the issuing certification authority (CA).
X.509 certificates include:
• Owner’s information or subject distinguished name (DN)
• Public key associated with the subject
• Version information
• Serial number of the certificate
• Another distinguished name identifying the issuer of the certificate (CA)
• Digital signature of the CA
• Information on the algorithm used to create the digital certificate
To ensure the validity of the certificate, it must be signed by a certification authority, which
is a trusted node that confirms the integrity of the public key value contained in the

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 18
certificate. The certificate is signed by the CA by adding a digital signature encoded with
the CA’s private key. The CA has a declared public key which is known by all supporting
applications and devices, who then validate a certificate by decoding the digital signature
within the certificate using the CA’s public key.

Chapter Two Quiz

1. One of Blockchain’s greatest advantages is _______________


a. not using a fiat currency for transactions
b. using a centralized database
c. the creation of private data storage
d. the elimination of using middlemen

2. Blockchain’s use of cryptographic hashing provides for _____________


a. the maintaining of data integrity
b. making data blocks tamper proof
c. network security to work in unison
d. All of the above

3. The hashing function requires that ______________


a. all recorded data in each block be the same
b. the network administrator agrees with the hash value
c. hash of the previous block is the same as in the present block
d. none of the above

4. The value of a hash can ______________


a. represent the value or data of anything
b. only be determined by the network controller
c. be predetermined by the Blockchain
d. only be derived by using the SHA256 algorithm

5. A smart contract is used in a Blockchain to _______________


a. help banks conduct normal business transactions
b. use business logics to define business agreements
c. eliminate the use of computer programmers
d. make participants accountable for paying network fees

6. Smart Contracts are preferred over traditional contracts because__________


a. provide autonomy in making an agreement
b. all transaction details are programmed into the agreement
c. obligations are automatically forced by the contract
d. all of the above

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 19
7. The consensus algorithms are used because _______________
a. they can include specific rules or conditions to be met
b. they increase the network security from hacking
c. they prevent node failure
d. they increase network speed

8. Proof of Work is _________________


a. fully supported in Hyperledger fabric
b. only used in cryptocurrency trading
c. used to save energy
d. commonly used for gaining consensus

9. Proof of Stake _______________


a. uses more energy than proof of work
b. provides a block award if successful
c. uses mining by a validator
d. does not use mining for consensus

10. An X.509 certificate is used for ________________


a. certification of transaction consensus
b. validating node performance
c. the issuing of private keys
d. identity validation

Quiz Answers
1. d
2. d
3. c
4. a
5. b
6. d
7. a
8. d
9. c
10. d

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 20
CHAPTER 3: INTRODUCTION
TO HYPERLEDGER
What is Hyperledger

Hyperledger is an open source collaborative effort created for open industrial blockchain
development. It started in December 2015 by the Linux Foundation. Linux Foundation’s
objectives were to create an environment in which communities of software developers
and companies meet and coordinate to build blockchain frameworks.

Why Hyperledger
Although blockchain has emerged as a world changing industry, it is challenged by the
lack of scalability, and the lack of support for confidential and private transactions. To
meet the varied demands of the critical and complex business market demands,
Hyperledger has been designed and implemented to resolve these issues.
Each blockchain network serves a different goal with each network ledger. Every ledger
has its own core functionality, and one ledger is not dependent on other’s network ledger
functionality. Although every network is independent of each other, it still must address
each other to allow transactions on one ledger, allowing it to discover and utilize the
appropriate transaction and smart contracts on the other ledgers.
Under an “Umbrella Strategy” Hyperledger promotes and incubates business blockchain
technologies, libraries, frameworks, interfaces, and application. Currently, Hyperledger is
overseeing the following projects:
Hyperledger Fabric: Hyperledger Fabric is a blockchain framework. Hyperledger Fabric
allows components, such as consensus and membership services, to be plug-and-play. In
hyperledger fabric, all transactions are ordered into block, and are then delivered from and
ordering service to peers on a blockchain channel.Hyperledger Fabric leverages container
technology to host smart contracts called “chaincode” that comprise the application logic
of the system. It should be noted that “hyperledger fabric” does not perform mining.

• Hyperledger Composer: Fabric Composer is a new open-source application


development framework, which simplifies the creation of Hyperledger Fabric blockchain
applications, thus reducing the time and complexity of development. The tool aims at
helping users to create blockchain applications based on Hyperledger Fabric without
needing to know the low-level (Go Programming) details involved in blockchain
networks.

If we want to build our blockchain application directly on Hyperledger Fabric we have to


write our Chaincode in GO or Java Programming Language which is comparatively

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 21
different than JavaScript because its composer is quite easy to code smart contract
using Model file (.cto) and angular JavaScript. Hyperledger Composer primarily uses
JavaScript for chaincode development.

Hyperledger Composer has following main components:


1) Business Network Archive: Capturing the core data in a business network,
including the business model, transaction logic, and access controls, the Business
Network Archive packages these elements up and deploys them to a runtime.
Business Network Archive files are stored as “.bna” files.

2) Composer Playground: This web-based tool allows developers to learn


Hyperledger Composer, model out their business network (domain), test that
network, and deploy that network to a live instance of a blockchain network. The
playground keeps the development model in browser storage, allowing them to be
easily uploaded or downloaded. The playground also allows for CRUD (create,
read, update, delete) operations to be performed on asset transactions which are
created and logged. Composer playground offers a repository of sample business
networks that can provide a base for building your own business network.

Composer Modeling Language


Composer Modeling Language is an object-oriented modeling language that defines the
domain model for a business network definition. The modeling language is saved as a
.cto file.

A CTO file consists of:


● A single namespace, in which all resource declarations are implicitly.

● The overall “model” defines the representation of assets.

● A set of resource definitions that includes assets, transactions, participants, and


events.

● Values may be assigned to any field variable.

● The option to import resources from other namespaces.

● When using composer modeling language, the words “asset” and “participant” are
reserved.

● Asset ownership instance is defined in a relationship field. (symbol: o)

● The modeling language does not support multiple inheritance.

Composer System Namespaces


The organization namespace is defined in the namespace line of the .cto file. As stated

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 22
earlier, all resources are implicitly part of this namespace.
There is a system namespace which contains base definitions of asset, event, partcipant,
and transactions. These base definitions are abstract types that are implicitly extended by
all new assets, events, participants, and transactions.
Events and transactions in the system namespace are defined by an eventID or
transactionID and a timestamp. The system namespace also includes definitions of
registries, historian records, identities, and system transactions.
Declaring Resources
In Composer, resources are:
● Assets, participants, transactions, and events

● Enumerated types

● Concepts

Resource definitions all have the following inherent properties:


● A namespace defined by the namespace of its parent file

● A name and an identifying field (unique identity)

○ The identifying field is after the name if the resource is an asset or participant

○ If the resource is an event or transaction, the identifying field is set


automatically

● An optional super-type that the resource definition extends

● An optional “Abstract” declaration indicates that this type cannot be instantiated, but
can be extended to create a new resource definition.
● A set of named properties. The properties must be named and the primitive data type
defined. Properties and data are owned by each resource

● A set of relationships to other Composer types that are not allowed by the resource but
may be referenced from the resource. Relationships are unidirectional.
REST API support and integration capabilities: A LoopBack connector for business
networks has been developed that exposes a running network as a REST API which can
easily be consumed by client applications and integrate non-blockchain applications. This
allows for easier front end application development without having to know the network
internal application structure.

Other Hyperledger Modules and Platforms

Explorer
• Hyperledger Explorer: Hyperledger Blockchain Explorer is a blockchain module
and one of the Hyperledger projects hosted by The Linux Foundation. Designed to

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 23
create a user-friendly Web application, Hyperledger Blockchain Explorer can view,
invoke, deploy, or query blocks, transactions, and associated data, network
information (name, status, list of nodes), chain codes, and transaction families, as
well as any other relevant information stored in the ledger.
Sawtooth
• Hyperledger Sawtooth: Hyperledger Sawtooth is a modular platform for building,
deploying, and running distributed ledgers. Distributed ledgers provide a digital
record (such as asset ownership) that is maintained without a central authority or
implementation.
Indy
• Hyperledger Indy: Hyperledger Indy is a distributed ledger, purpose built for
decentralized identity. It provides tools, libraries, and reusable components for
creating and using independent digital identities rooted on blockchains or other
distributed ledgers so that they are interoperable across administrative domains,
applications, and any other “silo.”

Because distributed ledgers cannot be altered after the fact, it is essential that use cases
for ledger-based identity carefully consider foundational components, including
performance, scale, trust model, and privacy. In particular, Privacy by Design and privacy-
preserving technologies are critically important for a public identity ledger where
correlation can take place on a global scale.

For all these reasons, Hyperledger Indy has developed specifications, terminology, and
design patterns for decentralized identity along with an implementation of these
concepts that can be leveraged and consumed both inside and outside the Hyperledger
Consortium.

Hyperledger Application
Business contracts can be coded (programmed) into smart contracts to allow two parties
to automate contractual agreement with high degree of trust and confidendentiality.
Hyperledger provides privacy control to protect sensitive business information from being
disclosed to outside parties which may also have access to the ledger. This so-called
privacy challenge is an important attribute of using Blockchain ledger technology (DLT).
There are instances where contracts must made public, accessible to all parties of a ledger.
Example is a ledger used for offers seeking bids.
This type of ledger is standardized so the bidders can easily find them. Assets like Financial
securities must be able to be dematerialized on a blockchain network. The stake holder of
the asset type has direct access to each asset, allowing them to initiate trade and acquire
information of an asset without going through layers of intermediaries. A stakeholder must
be able to access asset information in real time and should be able to add business rules
for any given asset type, which reduces cost by implementing automation logic. The creator
of an asset can make the asset private and confidential, or public as the use case warrants.
The blockchain fabric provides a means to every participant on a supply chain network to

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 24
input and track the details of asset transfer right from production to storage to final sale of
goods and services. It helps track provenance and maintain immutable records of all
aspects of the product lifecycle. It helps keep provenance, so it can deep search
backward in time through many transactional layers.

Hyperledger Architecture
The Hyperledger Fabric business network is divided into three categories; Membership,
Blockchain, and Chaincode.

Membership Services

Membership services provide identity, privacy, and confidentiality to the network. Basic
access to the network is determined through the role of the member, who may all have
separate legal and/or independent entities. Depending on the network, different
authentication schemes are used for assigning identity. For transacting, the participants
must obtain identities.

The Reputation Manager enables auditors to view transactions pertaining to a participant,


providing that each auditor has been granted proper access authority, based on the role of
the participants.

Blockchain
Blockchain services manages the distributed ledger through a peer to peer protocol that is
built on HTTP/2.

The optimized data structure provides efficient schemes for maintaining the world state
(i.e. the state of all transactions on the Blockchain) replicated at many participants.
Different consensus algorithms are enforced to guarantee strong consistency.
Chaincode
Chaincode services are secured and lightweight. The environment is a “locked down” and
secured container with a set of signed base images which contains secure OS and
Chaincode language, runtime and SDK images for Golang, Java, and Node.js. Additional
programming language can also be used if required.

Membership
Hyperledger is a private validator network protocol. All the entities in a network must
register with membership services to obtain an identity with access and transaction
authority on the network. Validators determine the level of permissions required to
transact. The network setup also defines the network as permissive, allowing the ease of
access. It supports for rapid and high adoption for a more controlled and restrictive
environment.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 25
Registration Services
Registration service provides the control and management of authorizations for
Hyperledger participation.
Identity Management
Identity Management services offers assurance and authorized disclosure of association
of identities and roles to Hyperledger participants.
Auditability Services
Auditability services provides the capability to provide authorized entities the means to link
transactions of individual users or groups of users according to the affiliation or roles. It
also provides capability to access the system activity of an individual user, or the system
itself.

Blockchain’s Main Components


Blockchain consists of three major components; P2P Protocol, Distributed Ledger and
Consensus Manager.
P2P Protocol
P2P Protocol is implemented over HTTP/2 standards and uses Google RPC. It provides
many capabilities like bi-direction streaming, flow control and multiplexing requests over a
single connection. It works with existing Internet infrastructure, including firewalls, proxies
and security. P2P component defines messages used by peer nodes, from point to point
to multicast.

Distributed Ledger
Distributed Ledger manages the world state and the transaction log in the blockchain. The
world state is defined as the state of all transactions on the Blockchain, where all nodes
agree that all blocks on the Blockchain are at the same state. It implements three key
attributes. It efficiently calculates the cryptographic hash of the entire dataset of each
block. It efficiently transmits a minimal “delta” changes to the dataset, when a peer is out
of sync and needs to “catch up”. It minimizes the amount of stored data required for each
peer to operate.

Consensus Manager
Consensus Manager defines the interface between the consensus algorithm and the other
Hyperledger components. The consensus manager receives transactions and depending
on the algorithm decides how to organize and execute the transaction. Successful
execution of transaction results in changes to the ledger.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 26
Transaction
Hyperledger supports two types of transactions.

Code deploying transaction

Code deploying transaction submits, updates or terminates a chaincode. The validating


nodes protects the authenticity and integrity of the code and its executing environment.
Code invoking transaction

Code invoking transaction is an API call to a chaincode function. It is similar to how a URI
invokes a servlet in JEE. The displayed function is called upon the instantiation of the
chaincode. Each chaincode maintains its own state and a function call is made to trigger
chaincode state changes.
Event stream in a decentralized network is complex in nature. An event can appear to
occur multiple times once on each peer node and callbacks can end up receiving multiple
invocations for the same event. Therefore, a peer node manages the events that the
applications are interacting with. The peer nodes state events as their conditions are
satisfied, in no special order. If events do not continue to be created, the application can
capture events if required.
Note: The initial instantiation applies to all peers in the channel, and is affected upon any
peer that has the chaincode installed. Therefore, you would need to install the chaincode
on peer0 in order to execute the instantiate command through it.
Now that we want to access the chaincode on peer1, we must install the chaincode on
peer1 as well. In general, a chaincode has to be installed only on those peers through
which the chaincode needs to be accessed from. In particular, the chaincode must be
installed on any peer receiving endorsement requests for that chaincode.

Chaincode
Chaincode is a decentralized transactional program, running on the validating nodes. As
with every chaincode, it implements the Chaincode interface in particular, Init and Invoke
functions.

Init is called during Instantiate transaction after the chaincode container has been
established for the first time, allowing the chaincode to initialize its internal data.

Invoke is called to update or query the ledger in a proposal transaction. Updated state
variables are not committed to the ledger until the transaction is committed.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 27
REST Server
A REST (Representational State Transfer) Server is often used to proxy requests to
Hyperledger chaincode. This provides a well defined process for accessing blockchain
services.

The REST server

The REST server uses a business network card specified during startup
to connect to and discover the assets, participants, and transactions within
a deployed business network. This information visibility is required in order
to generate the REST API. This business network card is known as the
discovery business network card. By default, the discovery business
network card is also used to handle all requests to the REST API.
However, the REST server can also be configured to multiple user mode,
which allows authenticated users to supply their own business network
cards for handling requests to the REST API.

Secure Container
Chaincode Services uses Docker to host (deploy) the chaincode without relying on any
virtual machine or computer language. Docker provides a secured, lightweight method to
sandbox chaincode execution. The environment is a "locked down" and secured
container, along with a set of signed base images containing secure OS and chaincode
language, runtime and SDK images for Golang. Additional programming languages can
be enabled, if required.
Secure Registry

Secure Registry Services enables Secured Docker Registry of base Hyperledger images
and custom images containing chaincodes.
Since assets in Hyperledger Fabric are represented in JSON or Binary, hyperledger
includes the REST and JSON RPC APIs, events, and an SDK for applications to
communicate with the network. Typically, applications interact with a peer node, which
requires some form of authentication to ensure that the entity has proper privilege;
messages from a client are signed by the client identity and verified by the peer node.
Hyperledger provides a set of CLIs to administer and manage the network. CLI can also
be used during development to test chaincodes. REST API and SDK are built on top of
JSON RPC API, which is the most complete API layer. SDK will be available in Go
(Golang), JavaScript, and Java; additional programming languages can be added as
necessary.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 28
Hyperledger Fabric
Hyperledger Fabric was developed by IBM, and is used to develop blockchain
applications with a modular architecture, so that components such as consensus and
membership services can be plug-and-play.

A fabric model consists of peer of nodes which executes smart contracts, accesses ledger
data, endorse transaction and interface with applications.

The fabric framework is implemented on Go. It enables consortium blockchains with


different level of permissions. Fabric uses container to host smart contracts that has the
business logics of the application.

Chapter Three Quiz

1. Hyperledger can best be described as a ____________________


a. newer version of Proof of Work
b. efficient way to mine transactions
c. umbrella supporting multiple blockchain technologies
d. none of the above

2. Advantages of using Hyperledger Fabric include ______________


a. allowing components to be plug-and-play
b. using any programming language available
c. not having to use an ordering service
d. making the mining process easier

3. Developing with Fabric Composer __________________


a. increases the time of development
b. requires low level programming skills
c. simplifies development of applications
d. requires the use of Python programming language

4. Hyperledger Composer has two main components that are_________________


a. Modeling Language and Fabric
b. Business Network Archive and Playground
c. participant and namespace
d. Fabric and public certification key

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 29
5. The domain model created by the Composer Modeling language may define_________
a. values to any field variable
b. representation of assets
c. a single namespace
d. all of the above

6. A system namespace is important because ______________________


a. it contains base definitions of transactions
b. it contains the network locations of nodes
c. it eliminates the need to define registries
d. it removes all abstract definitions

7. Resource definition properties include all of these attributes except___________


a. a namespace
b. an identity field
c. bi-directional relationships to other composer types
d. abstract declarations

8. Using Hyperledger, the stake holder of an asset can_____________


a. utilize smart contracts
b. directly access an asset without an intermediary
c. add business rules to a contract at any time
d. All of the above
e. None of the above

9. Hyperledger fabric business network is divided into three categories.


a. Sawtooth, Fabric, and Indy
b. Composer, Fabric, and Chaincode
c. Blockchain, Chaincode, and Membership
d. Blockchain, Registration, Identity

10. Blockchain’s main components are?


a. Network, Ledger, and Consensus
b. Hyperledger, Ethereum, and Network protocol
c. Fabric, Composer, and Explorer
d. Distributed ledger, P2P Protocol, and Consensus mgr.

11. The chaincode’s interface inplements the following functions __________


a. open and close
b. query and update
c. init. and run
d. invoke and init

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 30
12. What application is used by Hyperledger Fabric to communicate with the network?
a. JSON
b. Binary
c. SDK
d. RPC API

Quiz Answers
1. c 7. c
2. a 8. d
3. c 9. c
4. b 10. d
5. d 11. d
6. a 12. c

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 31
CHAPTER 4: HYPERLEDGER
FABRIC FUNDAMENTALS
Introduction
In this chapter, the fundamental blocks of Hyperledger Fabric, what constitutes the distributed
ledger in fabric, types of nodes in fabric, endorsement policies, membership cards, and the
certificate authority will be covered.

Fabric Definitions

Transactions

Simply defined, every time an asset changes state, a transaction is recorded on the ledger
(Blockchain). A transaction is invoked by the SDK and sent to the endorsing peer to verify it
and authenticate it. A transaction either creates new chaincode or invokes transactions on
already deployed chaincode.

Orderer

An orderer is defined as a communication node responsible for the


distribution of Blockchain transactions. In hyperledger fabric, all
transactions are ordered into block, and are then delivered from a
ordering service to peers on a blockchain channel.

Ledger

Ledger provides the provenance capability in blockchain. All the peers (nodes) in a
network contain the ledger. An orderer node may also have ledgers. In reference to a
peer, we refer to the ledger as Peer Ledger and in reference to an orderer, it is referred to
as an orderer Ledger.
Ledger is constructed by the ordering services as ordered hash chain of blocks of valid
and invalid transactions. The hash chain enforces the total order of blocks in a ledger and
each of these blocks contain an array of ordered transaction.
Nodes
Nodes in a network are the communication entities in a blockchain. There are three kinds
of nodes:

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 32
Client

Client represents the entity that acts on behalf of the end user. It submits the actual
transaction-invocation to the endorser and broadcasts all the transaction proposals to the
ordering services. The client may connect to any of the peers of its choice.

Peer
A peer receives updates in the form of blocks from the ordering services and maintains
the ledger. Peers can also take up duties of the endorser.
Endorser

Endorsing peer is the gateway to the start with the Hyperledger Fabric. It authorizes a
given transaction before it is committed. Every chaincode must specify an endorsement
(not including criteria) that refers to a set of endorsing peers, which it is executed on.
Once executed, the chaincode saves the updated asset state change to the Blockchain.
To simplify this concept, endorser peers receive updated data blocks from the orderer
peers.This policy describes the conditions for the valid transaction endorsement.

Ordering Nodes
Ordering services handles the main function of the Hyperledger Fabric to maintain
consistency in the transactions processes. Ordering services provides a shared
communication to clients and peers and helps in broadcasting the messages containing
transactions.
The channels can be defined as per the requirement provided. It ensures privacy in a
network. Ordering services may support many channels. Client can connect to any given
channel, initiate transactions, and send and obtain messages from one or more
endorsers.
Ordering Services API
Ordering service provides peers with an interface that helps connect to the channel
provided by the ordering service.
Broadcast
A client calls this to broadcast an arbitrary message blob for dissemination over the
channel. This is also called request(blob) in the BFT context, when sending a request to a
service.
Deliver
The ordering service calls this on the peer to deliver the message blob with the specified
non-negative integer sequence number and hash of the most recently delivered blob. In
other words, it is an output event from the ordering service. Deliver() is also sometimes
called notify() in pub-sub systems or commit() in BFT systems.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 33
Channels
Channels provide the way of communication of private and confidential transaction across
a network. The channel is defined by each component in the network anchor peers per
member, shared ledger, chaincode application and the ordering service nodes. Channels
allow any customer, participant, or vendor to have their own ledger on the Blockchain.
Each party must be authorized to transact on the channel.
Certificate Authority
Certificate Authority provides certificate services to blockchain users. These services
provide services like user enrollment, transaction invoked, and a TLS secured connection
between users or components of blockchain.
In the lab section we will create our first business network, model our first university use-case,
write chaincode and its test.

Finally, we shall deploy the created business network and test it using chai and mocha
framework. Also use explorer to add entries to the asset and validate the transaction history
using the Historian registry and explorer.

Distributed Ledger
The ledger is the sequenced, tamper-resistant record of all state transitions. State transitions
are a result of chaincode invocations (“transactions”) submitted by participating parties. Each
transaction results in a set of asset key-value pairs that are committed to the ledger as
creates, updates, or deletes.

Fabric Ledger has two parts:


• State data: Representation of current state of the assets. Asset state data can be changed
upon changes to the state of the data.
• Transaction Logs: Record of all the transactions (in the order they are received) which
modified the state data, and once the data is written it is immutable and cannot be
changed.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 34
Transaction Logs: (World) State data

Type Is Immutable Mutable


Operations Create, Retrieve ALL – CRUD
DB levelDB levelDB / CouchDB
Behavior Embedded within Key-value paired (Json or
Peers Binary)
Query Supports Simple CouchDB Supports
Query complex queries

The ledger system in Hyperledger fabric uses levelDB. By definition, LevelDB allows
concurrent writers to safely insert data into the database by providing internal synchronization.
LevelDB uses very coarse-grained synchronization which forces all writes to proceed in an
ordered, first-come-first-served basis, effectively reduces throughput to a single thread.
State database options include LevelDB and CouchDB. LevelDB is the default key-value state
database embedded in the peer process. CouchDB is an optional alternative external state
database. Like the LevelDB key-value store, CouchDB can store any binary data that is
modeled in chaincode (CouchDB attachment functionality is used internally for non-JSON
binary data). But as a JSON document store, CouchDB additionally enables rich query against
the chaincode data, when chaincode values (e.g. assets) are modeled as JSON data.
Each transaction has a unique ID, it’s time-stamped and contains signatures of every
endorsing peer and are submitted to ordering service

The ledger is comprised of a blockchain (‘chain’) to store the immutable, sequenced record in
blocks, as well as a state database to maintain current fabric state. There is one ledger per
channel. Each peer maintains a copy of the ledger for each channel of which they are
member.

Nodes
The concept of node is common in all blockchain technologies. Node becomes the
communication end point in blockchain technology. Nodes connect to other nodes and that is
how a blockchain is formed.
Nodes use a type of peer-to-peer protocol for keeping the distributed ledger in sync across the
network.

In a public blockchain like Ethereum; anyone can participate as a node by downloading node
client called wallet. But in the case of a permissioned Hyperledger network, things are quite
different.

In Hyperledger, nodes need a valid certificate to be able to communicate to the network and
the participants use applications that connect to the network by way of the nodes. Participant’s
identity is not the same as the nodes identity. When a participant executes or invokes a
transaction, their certificate is used for signing that transaction. The network validates if the
node’s certificate should be trusted. In case the nodes certificate is revoked or has expired,
the transaction that appeared to be signed by a valid certificate is broadcasted to the network.
The transaction will be rejected because the certificate that the node used was expired or had
been revoked.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 35
In Hyperledger, all Nodes are NOT equal. There are three distinct types of nodes:

1. Client Node: That initiates the transaction


2. Peer Nodes: Commits Transaction & keeps the data in sync across the ledger
3. Ordered: They are the communication backbones and responsible for the distribution of
the transactions

Channels

Members can participate on multiple Hyperledger blockchain networks. Transactions in each


network is separate and isolated and is made possible by way of using channels.
Channel is a data partitioning mechanism to control transaction visibility only to stakeholders. Other
members on the network are not allowed to access the channel and will not see transactions on
the channel.

A chaincode may be deployed on multiple channels, each instance is isolated within its
channel. Similarly, each channel maintains their own chaincode and ledger. (Hyperledger
version 1.x)

Separation of the ledger, by defining the specific channel for each ledger and peer node
memberships are defined in the Chaincode configuration. It is stored in the Genesis block of
the ledger, which also stores the members, policies, and anchor peers. The Genesis block
defines the read/write access on a channel.

Peers are connected to the channel and can receive all the transactions that are broadcasted
on that channel. Consensus takes place within a channel by members of the channel.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 36
Node Types: Ordered, Anchor & Endorser

Client Node

The client represents the entity that acts on behalf of an end-user. It must connect to a peer for
communicating with the blockchain. The client may connect to any peer of its choice. Clients create
and thereby invoke transactions.

Peer Node
They are nodes that maintain the state and copy of a shared ledger. Peers are authenticated by
certificates issued by MSP. In Hyperledger Fabric, there are three types of peer nodes depending
upon the assigned roles:

Endorsing Peers (Endorsers)

An endorser executes and endorses transactions.

The endorsing peers take the role of endorsing transactions before they are ordered and
committed as per the policy defined in Chaincode. The client application creating the
transaction sends it to the endorsing peers as per the policy in chaincode. The endorsement
policy is instantiated at the chaincode of the client application and forwarded to the endorsing
peers. The endorsing peer evaluates and validates the transaction and produces an
endorsement signature and then returns it to the application. There may be one or more pre-
specified set of endorsing peers involved as per the endorsement policy. The transaction is
evaluated and declared valid only if it has been endorsed by the endorsing peers as per
policy.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 37
Ordering Service Nodes (Orderers)
• Responsible for consistent ledger state across the network
o Consensus Mechanism
o Ensures order of Transactions
• Creates Blocks & Provides atomic delivery/broadcast
• Message Oriented Middleware options for orderer service in Hyperledger:
o SOLO: Single Node, supports multiple channels (Good for Development)
o Kafka: High throughput, scalable & Fault Tolerant

All transactions from the network are received by the orderer, which orders and groups them,
then packages the transactions and creates blocks. The orderer service delivers blocks to the
committing peers that can be part of a Channel. The orderer services do not review
transaction information. The orderer makes guaranteed atomic delivery of blocks to the
committing peers on the channel.

The orderer supports multiple channels using a publish/subscribe messaging system (based
on Apache Kafka and Zookeeper). The ordered provides a Practical Byzantine Fault
Tolerance (PBFT) for failures without a single-point of failure.

Ordering service nodes also provide the following services:

• Authentication of clients
• Maintenance of a system chain that defines ordering service configurations, root certs and
MSP IDs for authenticated organizations and a grouping of profiles containing the various
consortia within the network.
• Filtering and validation for configuration transactions that reconfigure or create a channel.

Committing Peers (Committers)


Committing Peers Verify endorsements and validate transaction results.
The committing peers receive blocks from the Orderer service, which have already been
endorsed by the endorsing peers. The Committing peers ultimately commit the transactional
state by adding the blocks to the ledger. Before committal, the peers validate or invalidate the
transaction by verifying if the endorsement policies are met, authenticate the signatures, and
verify the version info (if there is any double spending).

Hyperledger Transaction Flow:


Assuming the Hyperledger Fabric 1.0 up and running, in a typical transaction flow of asset
exchange:
• All application users and peer node members are registered in the MSP and issued with
Keys/certificates from the CA for authenticating the network. The Chaincode representing the
initial state is installed on the peers and the channels are active.

• The application client initiates a transaction (Client A makes a request to Client B to transfer
an asset). The endorsement policy states that the request must be endorsed by Peer A and
Peer B.
• The application submits a transaction proposal to the endorsing peers A and B.
• The endorsing peers receive and verify the transaction proposal and its signature, then

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 38
executes the transaction and return a signed proposal response back to the application client.
• The application client verifies the responses from the endorsing peers. It assembles the
response into a transaction and sends it to the Orderer service.
• The Orderer services order the transactions chronologically and package those
transactions as blocks specific to a channel.
• The Orderer service delivers the blocks of the transactions to all the peers on the channel.
• The peers perform the validation of the blocks for endorsement policy, signatures, verification
and version info, and finally appends the block to the chain and commits the state to the
database. It then notifies the application client.

Endorsement Policies
An endorsement policy is a condition which endorses a transaction. Blockchain peers have a
pre-specified set of endorsement policies, which are referenced by a deploy transaction that
installs specific chaincode. Endorsement policies can be parameterized, and these
parameters can be specified by a deploy transaction.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 39
To guarantee blockchain and security properties, the set of endorsement policies should be a
set of proven policies with a limited set of functions to ensure bounded execution time
(termination), determinism, performance and security guarantees.

Dynamic addition of endorsement policies (e.g., by deploy transaction on chaincode deploy


time) is very sensitive in terms of bounded policy evaluation time (termination), determinism,
performance and security guarantees. Therefore, dynamic addition of endorsement policies is
not allowed, but may be supported in the future.

Transaction evaluation against endorsement policy

A transaction is declared valid only if it has been endorsed according to the policy. An invoked
transaction on a chaincode must first obtain an endorsement that satisfies the chaincodes
policy or it will not be committed. This takes place through the interaction between the
submitting client and the endorsing peers as explained in Section 2.

Formally, the endorsement policy is predicated on the endorsement, and potentially further
state that evaluates to TRUE or FALSE. For deployed transactions the endorsement is
obtained according to a system-wide policy (for example, from the system chaincode).

An endorsement policy predicate refers to certain variables. Potentially it may refer to:

1. Keys or identities relating to the chaincode (found in the metadata of the chaincode),
for example, a set of endorsers;
2. Further metadata of the chaincode;
3. Elements of the endorsement and endorsement, Tran-proposal;
4. And potentially more.

The above list is ordered by increasing expressiveness and complexity, that is, it will be
relatively simple to support policies that only refer to keys and identities of nodes.

The evaluation of an endorsement policy predicate must be deterministic. An endorsement


shall be evaluated locally by every peer, such that a peer does not need to interact with other
peers, yet all correct peers evaluate the endorsement policy in the same way.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 40
Membership Service Provider (MSP)
“Abstract component of the system that provides credentials to the clients, and the peers to
participate in the Hyperledger Fabric network”
MSP implementation is based on the PKI (Public Key Infrastructure). Service it Provides:
• Authorization Service
o Role based
o Examples:
 Can this user issue further identity?
 Can user deploy chaincode?
 Authentication Service
o Where users Identity gets validated
o Examples:
 Is the user’s/peer’s certificate valid?
 Is peer allowed to participate?

Certificate Authority
As a platform for permissioned blockchain networks, Hyperledger Fabric includes a modular
Certificate Authority (CA) component for managing the network identities of all member
organizations and their users.
The requirement for a permissioned identity for every user enables ACL-based control over
network activity and guarantees that every transaction is ultimately traceable to a registered
user.
• The CA (Fabric CA by default) issues a root certificate (rootCert) to each member
(organization or individual) that is authorized to join the network.
• The CA also issues an enrollment certificate (eCert) to each member component, server-side
applications and occasionally end users.
• Each enrolled user is granted an allocation of transaction certificates (tCerts). Each tCert
authorizes one network transaction.
This certificate-based control over network membership and actions enables members to
restrict access to private and confidential channels, applications, and data, by specific user
identities.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 41
Chapter Four Quiz

1. In fabric, a transaction is invoked by _____ and sent to the _____ to verify it.
a. an API, Blockchain
b. the SDK, endorsing peer
c. the ordering node, client
d. the service API, endorsing peer

2. The ____________ provides provenance capability in the Blockchain.


a. certificate authority
b. Blockchain Channel
c. ledger
d. consensus function

3. Before an Endorser authorizes a transaction to be put on the Blockchain, it must _________


a. receive an updated block from an orderer peer
b. receive an updated block from a client
c. receive an updated block from the Blockchain
d. receive an updated block from the node channel

4. The three communication node types are ________________


a. orderer, client, and network
b. broadcast, peer, and network
c. client, network, and and peer
d. endorser, client, and peer

5. The interface that allows peers to connect to the channel are provided by ____________
a. certificate authority
b. ordering service provider
c. endorsing peer
d. ordering node

6. Blockchain channels are used to ______________


a. provide an alternate communication channel for the Blockchain
b. provide the customer with a choice of nodes to use for communication
c. provide an alternate transaction communication channel
d. allow any customer to have their own ledger on the Blockchain

7. Fabric ledger contains both state data (which can be changed) and transactions logs
that cannot be changed once written to?
a. True
b. False

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 42
8. Nodes communicate with each other on the Blockchain and stay synchronized by _____
a. comparing valid authority certificates
b. using first-in first-out protocol
c. using peer-to-peer protocol
d. using a network timing API

9. The separation of ledgers in each channel and peer node is defined ___________
a. by the anchor peers
b. by the orderer peers
c. by the endorser peers
d. in the genesis block

10. To guarantee Blockchain security, the endorsement policies should __________


a. include embedded passwords known only to clients
b. include a very complex set of functions making complying difficult
c. include a limited set of functions to guarantee termination
d. include specific security functions to permit long execution times

11. Certificate Authorities provide many types of identity certificates, which are used to ____
a. authorize members to join the network
b. enroll applications and components
c. guarantee every transaction is tracable
d. allocate transactions
e. all of the above

Quiz Answers
1. b
2. c
3. a
4. d
5. b
6. d
7. a
8. c
9. d
10. c
11. e

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 43
CHAPTER 5: PARTICIPANT,
IDENTITIES & ACCESS CONTROL
Introduction
In this chapter, access control and authorization are covered, which are an important part of
Hyperledger and the security architecture of a business network. Hyperledger enables an
administrator to control the resources and/or data that a participant, or a participant’s role is
authorized to see or do in a business network.

In the lab section we will explore and define an ACL file for our University example use-case
and provide access permissions to different participants.

Access control rules (the language that defines ACLs) fall into two main areas:

• Authority to access system, network or administrative resources and operations in the


System namespace (governing Network and System operations). (Namespace: a unique
term used across multiple model files)
• Authority to access resources or perform operations within a given business network itself
(like Create, Read, Update assets)

Finally, we will use the online Playground to try some simple and conditional access rules. In
doing so, we will interact with our University use case network as various identities. This will
show how to apply access control to the users of the blockchain.

Participants and Identities


A Participant is an actor in a business network. A participant might represent an individual or
an organization. A participant can create assets and share assets with other participants. A
participant can interact with assets by submitting transactions.

A participant has an identity set that can be validated to prove the identity of that participant.

Hyperledger Fabric is a Private Permissioned Network for Businesses. Businesses interact


with only known identities.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 44
In Hyperledger, participants are separated from the set of identities they can use to interact with a
business network.

For a new participant to join a business network, a new instance of that participant must be created
in the business network. The participant instance stores all the required information about that
participant, but it does not give that participant access to interact with the business network.

To grant the participant access to interact with the business network, an identity must be issued to
that participant. The new participant can then use that identity document to interact with the
business network.

An Identity usually expires after a specified time period. An Identity may also be lost or stolen. If the
identity expires, or if it needs to be replaced, then it must be Revoked so it can no longer be used
to interact with the business network.

However, revoking an identity document does not remove the information about that participant
and any assets they own. Revoking the identity document simply removes the participant’s ability
to interact with the business network using that identity. Access to the business network can be
restored by issuing the participant with a new identity.

These participant and identity management actions are performed by an existing participant in the
business network, for example a regulatory body, or a participant in the same organization who has
been trusted to manage participants/identities in that organization.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 45
Chapter Five Quiz:

1. Hyperledger access control rules enable ________________


a. certificates to be validated
b. clients to add their own contract rules
c. access permissions
d. network security access

2. System access authority to use network resources is specified by ______


a. specific certificate authority
b. smart contract terms
c. the system namespace
d. access control rules

3. A participant is an _____ in a business network who represents ________.


a. node, a client
b. client, a company
c. actor, an organization
d. organization, a network

4. Hyperledger Fabric is a private permissioned business network for ___________


a. any new participant to join
b. known identities
c. any new or old client instances
d. connecting to other business networks

5. A new instance for a participant to join a network provides _____________


a. access to the business network
b. information about the participant
c. a new participant identity set
d. access to all network ledgers

Quiz Answers
1. c
2. d
3. c
4. b
5. b

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 46
CHAPTER 6: HYPERLEDGER –
CLIENT APP
Introduction
This chapter will cover how to build the client app, which can interact with the fundamental blocks of
Hyperledger blockchain i.e.;
Connecting to the Business Network
Access Participant and Asset registries
Invoke Transactions
Query Resources (Static & Dynamic Queries)
Handling events

High Level Architecture


Model file, Transaction functions (chaincode), access control file and the static query file make the
Business Network Archive (Package) for the Hyperledger Fabric.

We will use Node.js and composer SDK to connect to the Fabric network and access/interaction with
the blockchain resources.

Queries
The native query language can filter results returned using criteria and can be invoked in transactions
to perform operations, such as updating or removing assets on result sets.

Queries are defined in a query file (.qry) in the parent directory of the business network definition.
Queries contain a WHERE clause, which defines the criteria by which assets or participants are
selected.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 47
Events

Event creates notifications of significant operations on the Blockchain (e.g. a new block), as well as
notifications related to a milestone achieved while processing a smart contract/chaincode. Does not
include event distribution.

The client app can subscribe to this event and take appropriate business actions. It’s an important
part of any system to provide an insight ask for immediate attentions.

In the lab section we will generate an event in the chaincode and client app will subscribe for this
event. We can then utilize this event to either send an email or appropriately notify the participant.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 48
Chapter Six Quiz
1. The following are Hyperledger fundamental blocks, except for _________
a. authority certificates
b. asset registries
c. dynamic queries
d. invoking transactions

2. The Hyperledger fabric business network archive is made up of __________


a. static query file
b. chaincode functions
c. models
d. all the above
e. none of the above

3. Interaction with the fabric network resources is accomplished by __________


a. sending static queries
b. using an API
c. using Node.js and SDK
d. node interface

4. Invoking queries define what criteria by the business network?


a. what network node to use
b. participant selection
c. what business rules to use
d. which language the Blockchain uses

5. Blockchain events are used to _________


a. create notifications
b. complete a smart contract
c. change event sequences in the Blockchain
d. notify the client of a node problem

Quiz Answers
1. a
2. d
3. c
4. b
5. a

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 49
CHAPTER 7: CREATING FRONT
END INTERACTIVE INTERFACES
Introduction
This chapter will instruct the student how to build a complete end-to-end interactive use case utilizing
the University example that was used earlier. This will cover the missing links and FAQs
How do we invoke the chaincode from an HTML or a frontend application?
How do we setup the node server and routes to run the client app?
How does the blockchain look in a real work scenario?
How can an end-user access the blockchain?

Front End Application Patterns


Composer Rest Server middleware Architecture:

Considerations:
• Rest server must be secured – HTTPS
• Should use authentication – [Passport]
• Should use multi-user mode for rest api

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 50
Custom Middleware Pattern

Advantages:
• More secure
• Better control and can plug in existing enterprise applications

Desktop Application Architecture

Pros:
• Most Secure
Cons:
• App distribution

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 51
Chapter 8: Chaincode
Importing of Other Files
It is possible to import other contracts from other files. For example, the following code shows how
to import dependencies for our chaincode. This code imports the shim package and the peer
protobuf package.

package main
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)

Choosing a Location for the Chaincode


When writing chaincode, you will want to make sure that you have the Go programming language
installed and setup with the correct configuration.
You will want to make sure that a directory is created for your chaincode application as a child
directory of
$GOPATH/src/

The following command will create such a directory called sample_code.


mkdir -p $GOPATH/src/sample_code

To enter into the directory, you can use the following command:

cd $GOPATH/src/sample_code

Alternatively, you can use the && command to both create the directory and enter it on the same
line, like so:

mkdir -p $GOPATH/src/sample_code && cd $GOPATH/src/sample_code


Now we can create the source file that we will fill with chaincode:

touch sample_code.go

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 52
Initializing and Invoking Chaincode

We can then implement the init function. Init is called during chaincode instantiation, and it will
initialize any data. Here’s how it’s done in chaincode:
// Init is called during chaincode instantiation to initialize any data.
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response
{
}

We then check for validity by retrieving the arguments to the init call using the
ChaincodeStubInterface.GetStringArgs function. We expect a key-value pair.

// Init is called during chaincode instantiation to initialize any


// data. Note that chaincode upgrade also calls this function to reset
// or to migrate data, so be careful to avoid a scenario where you
// inadvertently clobber your ledger's data!
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response {
// Get the args from the transaction proposal
args := stub.GetStringArgs()
if len(args) != 2 {
return shim.Error("Incorrect arguments. Expecting a key and a value")
}
}

This will establish that the call is valid. We can now store the initial state to the ledger. We can do
this by calling ChaincodeStubInterface.PutState and putting the key and value into the function
argument

// Init is called during chaincode instantiation to initialize any


// data. Note that chaincode upgrade also calls this function to reset
// or to migrate data, so be careful to avoid a scenario where you
// inadvertently clobber your ledger's data!
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response {
// Get the args from the transaction proposal
args := stub.GetStringArgs()
if len(args) != 2 {
return shim.Error("Incorrect arguments. Expecting a key and a value")
}

// Set up any variables or assets here by calling stub.PutState()

// We store the key and the value on the ledger


err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0]))
}
return shim.Success(nil)
}

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 53
To invoke the chaincode, the invoke function’s signature needs to be included like so:
// Invoke is called per transaction on the chaincode. Each transaction is
// either a 'get' or a 'set' on the asset created by Init function. The 'set'
// method may create a new asset by specifying a new key-value pair.
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
}

As with the init function before, it is necessary to extract the arguments from the
ChaincodeStubInterface. The argument of the invoke function is the name of the chaincode
application function that you want to invoke.

In the following example, the application will only have the set function and get function. This
allows developers to set or access the current state of an asset.

First, call ChaincodeStubInterface.GetFunctionAndParameters to extract the function name and


parameters to the chaincode application function:

// Invoke is called per transaction on the chaincode. Each transaction is


// either a 'get' or a 'set' on the asset created by Init function. The Set
// method may create a new asset by specifying a new key-value pair.
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
// Extract the function and args from the transaction proposal
fn, args := stub.GetFunctionAndParameters()
}

Next we have to check the function name as being either set or get and invoking those chaincode
application functions, then return an appropriate response via shim.Success or shim.Error
function:

// Invoke is called per transaction on the chaincode. Each transaction is


// either a 'get' or a 'set' on the asset created by Init function. The Set
// method may create a new asset by specifying a new key-value pair.
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
// Extract the function and args from the transaction proposal
fn, args := stub.GetFunctionAndParameters()

var result string


var err error
if fn == "set" {
result, err = set(stub, args)
} else {
result, err = get(stub, args)
}
if err != nil {
return shim.Error(err.Error())
}

// Return the result as success payload


return shim.Success([]byte(result))
}

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 54
Implementing the Chaincode Application

Now our example chaincode application implements two functions that can be invoked via the
invoke function. The following example code will implement these functions.

Note that in order to access the ledger’s state, you use the ChaincodeStubInterface.PutState and
ChaincodeStubInterface.GetState functions of the chaincode shim API:

// Set stores the asset (both key and value) on the ledger. If the key exists,
// it will override the value with the new one
func set(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 2 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value")
}
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return "", fmt.Errorf("Failed to set asset: %s", args[0])
}
return args[1], nil
}
// Get returns the value of the specified asset key
func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 1 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key")
}
value, err := stub.GetState(args[0])
if err != nil {
return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err)
}
if value == nil {
return "", fmt.Errorf("Asset not found: %s", args[0])
}
return string(value), nil
}

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 55
Putting All The Code Together
We can finish up this sample application by adding the main function. The main function will call the
shim.Start function. The following is all the code put together:

package main
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
// SimpleAsset implements a simple chaincode to manage an asset
type SimpleAsset struct {
}
// Init is called during chaincode instantiation to initialize any
// data. Note that chaincode upgrade also calls this function to reset
// or to migrate data.
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response {
// Get the args from the transaction proposal
args := stub.GetStringArgs()
if len(args) != 2 {
return shim.Error("Incorrect arguments. Expecting a key and a value")
}
// Set up any variables or assets here by calling stub.PutState()
// We store the key and the value on the ledger
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0]))
}
return shim.Success(nil)
}
// Invoke is called per transaction on the chaincode. Each transaction is
// either a 'get' or a 'set' on the asset created by Init function. The Set
// method may create a new asset by specifying a new key-value pair.
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
// Extract the function and args from the transaction proposal
fn, args := stub.GetFunctionAndParameters()
var result string
var err error
if fn == "set" {
result, err = set(stub, args)
} else { // assume 'get' even if fn is nil
result, err = get(stub, args)
}
if err != nil {
return shim.Error(err.Error())
}
// Return the result as success payload
return shim.Success([]byte(result))
}
// Set stores the asset (both key and value) on the ledger. If the key exists,
// it will override the value with the new one
func set(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 2 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value")
}

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 56
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return "", fmt.Errorf("Failed to set asset: %s", args[0])
}
return args[1], nil
}
// Get returns the value of the specified asset key
func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 1 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key")
}
value, err := stub.GetState(args[0])
if err != nil {
return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err)
}
if value == nil {
return "", fmt.Errorf("Asset not found: %s", args[0])
}
return string(value), nil
}
// main function starts up the chaincode in the container during instantiate
func main() {
if err := shim.Start(new(SimpleAsset)); err != nil {
fmt.Printf("Error starting SimpleAsset chaincode: %s", err)
}
}

Finally, you can compile your chaincode:


go get -u --tags nopkcs11 github.com/hyperledger/fabric/core/chaincode/shim
go build --tags nopkcs11

Chapter 8 Quiz
1. The “init” method is called when:
a) there is an error in the code
b) a chaincode receives an invoke function
c) a chaincode receives an “instantiate” or “upgrade” transaction
d) an asset is created
2. The “invoke” method is called in response to:
a) receiving an transaction to process transaction proposals
b) receiving an asset
c) sending a transaction
d) receiving an instantiate transaction

3. Every chaincode program must implement the:


a) Chaincode panel
b) Chaincode interface
c) Chaincode policy
d) Chaincode parameters

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 57
4. Which of the following is used to access and modify the ledger?
a) SimpleAssetInterface
b) LedgerInterface
c) ChaincodeStubInterface
d) BlockInterface
5. Which of the following functions are NOT required in chaincode?
a) Init
b) Start
c) Invoke
6. The necessary package dependencies for chaincode is:
a) shim and peer protobuf
b) only shim
c) only peer protobuf
d) There are no necessary dependencies
7. Functions retrieves function arguments using:
a) ChaincodeStringInterface.GetStubArgs
b) ChaincodeFunctionInterface.GetStringArgs
c) ChaincodeMainInterface.GetArgs
d) ChaincodeStubInterface.GetStringArgs
8. To _______ function is used to store a state in the ledger:
a) ChaincodeStubInterface.PutState
b) ChaincodeStubInterface.GetState
c) ChaincodeLedgerInterface.PutState
d) ChaincodeLedgerInterface.StoreState

9. In general, what function will call the shim.Start function?


a) Main
b) Start
c) Invoke
d) Set

Chapter 8 Quiz Solution


1) C
2) A
3) B
4) C
5) B
6) A
7) D
8) A
9) A

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 58
Chapter 9: Hyperledger
Composer
Foreword
This chapter will guide you through the basics of Hyperledger Composer. For more detailed
instructions, use the Composer documentation as reference. If you want to play around with
Hyperledger Composer concepts, you can use the Hyperledger Composer Playground. You
can find detailed instructions on how to use the playground here.

What is Hyperledger Composer ?


Hyperledger Composer is an incredibly extensive toolset that makes developing blockchain
applications incredibly simple. The primary aim of Hyperledger Composer is to accelerate
the time in developing a blockchain application, as well as make it easy to integrate those
blockchain applications with legacy business systems.
Composer allows developers to rapidly model a business network and integrate existing
systems/data into a blockchain application.
A business network consists of three main aspects: Assets, Participants, and Transactions.
Participants exchange assets by sending and receiving transactions.

Connection Profiles
Composer uses what’s called connection profiles to define the system to connect to. A
connection profile is a JSON document that acts as part of a business network card. The
connection profile is most often provided by creators of the system they refer to.

Business Network Cards


Business network cards are a combination of a connection profile, metadata, and an identity.
The metadata for the business network card may contain the name of the business network
to connect to.
Business network cards make the process of connecting to a business network much more
simple, and extends the concept of an identity outside the business network to a wallet of
identities, each one associated with a specific business network and connection profile.

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 59
Queries and Events
You can use queries to get data about the state of the blockchain. Queries are defined within
a business network, and can include variable parameters. Queries are sent using the
Composer API.
Events in Composer are defined in the business network definition in the same way as
participants or assets. Events are emitted by the transaction processor function once it has
been defined. An event indicates to external systems that something important has occurred
on the ledger. Applications subscribe to emitted events using the composer-client API.

Access Controls and Historian Registry


Developers of the business network can create a set of access controls. Access controls are
rules that determine which assets participants have access to in the business network and
the conditions in which they can access them. Access control is incredibly detailed, and
allows for complex conditions. Separating access control from transaction logic makes the
code significantly easier to inspect, debug, and develop.
A historian is a specialized type of registry that records successful transactions conducted
on the business network. The historian also records the participants and identities that sent
the successful transactions. The transactions are stored as HistorianRecord assets.

Architecture
Hyperledger Composer consists of the following high-level components:
● Execution Runtimes
● JavaScript SDK
● Command Line Interface
● REST Server
● LoopBack Connector
● Playground Web User Interface
● Yeoman code generator
● VSCode and Atom editor plugins

Modeling Language
The rest of this chapter will cover the Composer modeling language, an object-oriented
modeling language that defines the domain model for a business network definition. The
modeling language is saved as a .cto file.

A CTO file consists of:


© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 60
● A single namespace, in which all resource declarations are implicitly.
● A set of resource definitions that includes assets, transactions, participants, and
events
● The option to import resources from other namespaces

Composer System Namespaces


The organization namespace is defined in the namespace line of the .cto file. As stated
earlier, all resources are implicitly part of this namespace.

There is a system namespace which contains base definitions of asset, event, partcipant,
and transactions. These base definitions are abstract types that are implicitly extended by all
new assets, events, participants, and transactions.

Events and transactions in the system namespace are defined by an eventID or


transactionID and a timestamp. The system namespace also includes definitions of
registries, historian records, identities, and system transactions.

Declaring Resources
In Composer, resources are:

● Assets, participants, transactions, and events


● Enumerated types
● Concepts
Resource definitions all have the following inherent properties:

● A namespace defined by the namespace of its parent file


● A name and an identifying field
○ The identifying field is after the name if the resource is an asset or participant
○ If the resource is an event or transaction, the identifying field is set
automatically
● An optional super-type that the resource definition extends
● An optional “Abstract” declaration to indicate that this type cannot be created.
● A set of named properties. The properties must be named and the primitive data type
defined. Properties and data are owned by each resource
● A set of relationships to other Composer types that are not allowed by the resource
but may be referenced from the resource. Relationships are unidirectional.
Here is how an example Vehicle asset would be defined in the Composer modeling
language:

asset Vehicle identified by vin {


o String vin
}

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 61
Here is an example of Vehicle as a super-type, and a Car being considered an asset with a
set of parts:

asset Car extends Vehicle {


o String model
--> Part[] Parts
}

As a developer, sometimes you will want to declare an enumerated type. An enumerated


type is used to specify a type that might have N potential values. For example, the following
code defines a FoodType enumeration, which can take on the value FRUIT, VEGETABLE,
or MEAT:
enum FoodType {
o FRUIT
o DAIRY
o MEAT
}

If another resource is created (such as a participant), a property of that resource can be


defined by an enumerated type:
participant Store identified by storeId {
o String storeID
o FoodType product
}

Concepts
In composer, concepts are abstract classes that are not considered an asset, participant, or
transaction. For example, the following code shows an abstract concept Address being
defined, and then specialized for Canada. Concepts do not have an identified by field
because concepts cannot directly be stored in registries or referenced in relationships:
abstract concept Address {
o String street
o String city default ="New York"
o String country default = "US"
o Integer[] counts optional
}
concept CanadaAddress extends Address {
o String zipcode
}

Primitive Types
There are different types of Composer resources. A resource can be one of the following
types:

1. String: A UTF8 encoded String


© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 62
2. Double: A double precision 64 bit numeric value.
3. Integer: A 32 bit signed whole number.
4. Long: A 64 bit signed whole number.
5. DateTime: An ISO-8601 compatible time instance, with optional time zone and UTZ
offset.
6. Boolean: Either true or false.

Arrays
Any type in Composer can be declared as an Array like so:
Integer[] ageArray

The code above creates an array of Integers called ageArray. The following code creates an
array of relationships to the Food type, and stores it in a field called “incoming”:
--> Food[] incoming

Relationships
In Composer, a relationship is a tuple that consists of the following elements:

1. The namespace of the type that is being referenced


2. The type name of the type being referenced
3. The identifier of the instance being referenced
An example relationship could be: org.example.Vehicle#123456

The above example demonstrates a relationship to the Vehicle type declared in the
org.example namespace. It has an identifier of 123456

Relationships do not cascade. That means that removing the relationship does not have an
impact on the thing that is being pointed to. Furthermore, relationships are unidirectional.
Removing the thing being pointed to does not invalidate the relationship.

Relationships must be resolved to retrieve an instance of the object being referenced. If the
object does not exist anymore or if the information in the relationship is invalid then the act of
resolution may result in null.

Field Validators
String fields are allowed to include a regular expression. Regular expressions are used to
validate the contents of the field, which can lead to rich data validation as well as fewer
errors and less boilerplate code.

The following code declares a Farmer participant that contains a field postcode. Postcode
must conform to the regular expression for valid UK postcodes:

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 63
participant Farmer extends Participant {
o String firstName default="Old"
o String lastName default="McDonald"
o String address1
o String address2
o String county
o String postcode regex=/(GIR 0AA)|((([A-Z-[QVf]][0-9][0-9]?)|(([A-Z-[QVf]][A-
Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVf]][0-9][A-HJKPSTUW])|([A-Z-[QVf]][A-Z-[IJZ]][0-
9][ABEHMNPRVWfY])))) [0-9][A-Z-[CIKMOV]]{2})/
}

Double, Long, or Integer fields can include an optional range expression. The following code
declares a Vehicle asset with an integer field that must be 1995 or higher. Range
expressions can omit the lower or upper bound if checking isn’t required:
asset Vehicle extends Base {
o String model default="F150"
o String make default="FORD"
o String reg default="ABC123"
// A numeric field can have a range validation expression
o Integer year default=2016 range=[1990,] optional // model year must be 1990 or
higher
o Integer[] integerArray
o State state
o Double value
o String colour
o String V5cID regex=/^[A-z][A-z][0-9]{7}/
o String LeaseContractID
o Boolean scrapped default=false
o DateTime lastUpdate optional
--> Participant owner //relationship to a Participant, with the field named
'owner'.
--> Participant[] previousOwners optional // Nary relationship
o Customer customer
}

Imports and Decorators


To import a type from another namespace, use the import keyword with a fully-qualified type
name. You can also use the .* notation to import all the types from another namespace.
Here’s an example:
import org.example.SomeAsset
import org.example2.*

You can also add decorators to resources and properties of resources. Decorators are used
to annotate a model with metadata. The following code shows an example in which the foo
decorator is used for the Buyer participant, and argument1 and 55 are passed as arguments
to the decorator:
@foo("arg1", 2)
participant Buyer extends Person {
}

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 64
Decorators can have an any amount of arguments passed to it. Argument values must be
either a string, number, or boolean.

Chapter 9 Quiz
1. The primary purpose of Hyperledger Composer is:
a) Allowing blockchain applications to run on computers with slow processing power
b) Accelerate the time to develop a blockchain application
c) Make it easy to integrate blockchain technology into legacy systems
d) Both B and C
2. The connection profile:
a) Defines the participants that can connect to each other
b) Defines the system to connect to
c) Defines the systems to avoid
d) Defines connections between assets in a network
3. Business network cards are a combination of:
a) Connection profile, metadata, and identity
b) Connection profile and identity
c) Metadata only
d) None of the above
4. Applications subscribe to emitted events using which API?
a) Composer-emitter
b) Composer-app
c) Composer-event
d) Composer-client
5. Queries:
a) Get data about the state of the blockchain
b) Get data only about participants on a network
c) Are used to validate transactions
d) None of the above
6. A historian is:
a) A specialized business network that only allows certain participants
b) A specialized type of registry that records errors on the business network
c) A specialized type of registry that records all successful transactions
d) A specialized type of registry that records all participants on the network

7. Transactions are stored as what kind of asset?


a) HistorianRegistry
b) HistorianRecord
c) TransactionRegistry
d) TransactionRecord

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 65
8. Composer modeling language files are saved with which extension?
a) .EXE
b) .CTO
c) .CML
d) .CMP
9. A CTO file consists of:
a) A single namespace
b) Resource definitions
c) A and B
d) None of the above
10. Which of the following is NOT a high-level component of Composer?
a) Command Line Interface
b) REST Server
c) Playground Web User Interface
d) C++ SDK
11. What is the correct syntax to create an array called yearList that consists of Integers?
a) Integer[] yearList
b) yearList[Integer]
c) yearList[]
d) Integer yearList[]
12. Regular Expressions are used to:
a) Query the state of the blockchain
b) Validate the contents of the field
c) Validate participants on the network
d) Validate transactions on the business network

Chapter 9 Quiz Solution


1.) b
2.) b
3.) a
4.) d
5.) a
6.) c
7.) b
8.) b
9.) b
10.) d
11.) a

© Copyright 2018 | All Rights Reserved Blockchain Training Alliance, Inc. Page 66

You might also like