Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Hyperledger Cookbook
Hyperledger Cookbook

Hyperledger Cookbook: Over 40 recipes implementing the latest Hyperledger blockchain frameworks and tools

By Xun (Brian) Wu , Chuanfeng Zhang , Zhibin (Andrew) Zhang
€22.99 €15.99
Book Apr 2019 310 pages 1st Edition
eBook
€22.99 €15.99
Print
€28.99
Subscription
€14.99 Monthly
eBook
€22.99 €15.99
Print
€28.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Apr 30, 2019
Length 310 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781789534887
Category :
Languages :
Concepts :
Table of content icon View table of contents Preview book icon Preview Book

Hyperledger Cookbook

Working with Hyperledger Fabric

Hyperledger Fabric is the most widely-used permissioned blockchain in the Hyperledger family. It is an open source enterprise-grade platform that leverages a highly-modular and configurable architecture. Hyperledger Fabric is optimized for a broad range of industry use cases, including the finance, banking, healthcare, insurance, and public sectors, as well as supply chains and digital asset management.

Hyperledger Fabric supports smart contact development in general-purpose programming languages, such as Java, Go, and Node.js. Hyperledger Fabric is also operating under a governance model to build trust between participants on a shared network.

In this chapter, we will cover the following recipes:

  • Reviewing the Hyperledger Fabric architecture and components
  • Installing Hyperledger Fabric on AWS
  • Building the Fabric network
  • Adding an organization to a channel
  • Using CouchDB
  • Writing your first application

Reviewing the Hyperledger Fabric architecture and components

We will review and examine various Hyperledger Fabric components and architectures throughout this recipe. Hyperledger Fabric has three core components, which are peers, ordering service, and Fabric CA:

  • Peer: A node on the network that maintains the state of the ledger and manages chaincode. Any number of peers may participate in a network. A peer can be an endorser, which executes transactions, or a committer, which verifies the endorsements and validates transactions results. An endorser is always a committer. Peers form a peer-to-peer gossip network. A peer manages the events hub and delivers events to the subscribers.
  • Ordering service: Packages transactions into blocks to be delivered to peers, since it communicates only with peers. The ordering service is the genesis of a network. Clients of the ordering service are peers and applications. A group of orderers run a communication service, called an ordering service, to provide an atomic broadcast. The ordering service accepts transactions and delivers blocks. The ordering service processes all configuration transactions to set up network policies (including readers, writers, and admins). The orderer manages a pluggable trust engine (such as CFT or BFT) that performs the ordering of the transactions.
  • Fabric CA: Fabric CA is the certificate authority that issues PKI-based certificates to network member organizations and users. Fabric CA supports LDAP for user authentication and HSM for security. Fabric CA issues one root certificate to member organizations and one enrollment certificate to each authorized user.

Hyperledger Fabric also have several important key features and concepts:

  • Fabric ledger: Maintained by each peer and consists of two parts: the blockchain and the world state. Transaction read/write and channel configurations sets are written to the blockchain. A separate ledger is maintained for each channel for each peer that joins. The world state has options of either LevelDB or CouchDB, where LevelDB is a simple key-value store and CouchDB is a document store that allows complex queries. The smart contract decides what is written into the world state.
  • Channel: Provides privacy between different ledgers and exists in the scope of a channel. Channels can be shared across an entire network of peers, and peers can participate in multiple channels. Channels can be permissioned for a specific set of participants. Chaincode is installed on peers to access the world state. Chaincode is instantiated on specific channels. Channels also support concurrent execution for performance and scalability.
  • Organization: Define boundaries within a Fabric blockchain network. Each organization defines an MSP for the identities of administrators, users, peers, and orderers. A network can include many organizations, representing a consortium. Each organization has an individual ID.
  • Endorsement policy: The conditions by which a transaction can be endorsed. A transaction can only be considered valid if it has been endorsed according to its policy. Each chaincode is deployed with an endorsement policy. Endorsement system chaincode (ESCC) signs the proposal response on the endorsing peer and validation system chaincode (VSCC) validates the endorsement.
  • Membership services provider (MSP): Manages a set of identities within a distributed Fabric network. It provides identities for peers, orderers, client applications, and administrators. Where the identities can be Fabric CA or external CA, MSP provides authentication, validation, signing and issuance. MSP support different crypto standards with a pluggable interface. A network can include multiple MSPs (typically one per organization), which can include TLS crypto material for encrypted communications.

Getting ready

We will look into a sample transaction flow on Hyperledger Fabric. Fabric uses the execute-order-validate blockchain transaction flow architecture shown in the following diagram:

How to do it...

In this section, we will review how a transaction is created on the Hyperledger Fabric network:

  1. The Client Application submits a transaction proposal for smart contact A to the network. The endorsement policy requires three endorsers—E0, E1, and E2—to sign together.
  2. The endorsers execute proposed transactions. At this time, three endorsers—E0, E1, E2—will each execute the proposed transaction independently. None of these executions will update the ledger. Each execution will capture the set of read and written (RW) data, which will now flow in the fabric network. All transactions should be signed and encrypted.
  3. RW sets are asynchronously returned to the client application with a transaction proposal. The RW sets are signed by each endorser and will be processed later.
  4. All transactions that returned from the Fabric network are submitted for ordering. The application can submit responses as a transaction to be ordered, and ordering happens across the Fabric in parallel with transactions submitted by other applications.
  5. Ordering Service collects transactions into proposed blocks for distribution to committing peers. This proposed blocks can then be deliver to other peers in a hierarchy. There are two ordering algorithms available: SOLO (single node for development) and Kafka (crash-fault-tolerance for production). In the production system, it is suggested to use Kafka.
  6. Committing peers validate the transactions. All committing peers validate against the endorsement policy and check whether RW sets are still valid for the current world state. World state is not update if there is invalid transctions but are retained on the ledger while validated transactions are applied to the world state.
  7. Client applications can register to be notified on the status of transactions, to find out whether they succeed or fail, and when blocks are added to the ledger. Client applications will be notified by each peer to which they are independently connected.

How it works...

We reviewed how transaction flow works in Fabric. Fabric uses the execute-order-validate model with the following seven steps:

  1. Client application submits a transaction proposal
  2. Endorsers execute the proposed transactions
  3. Client applications receive transaction proposal response
  4. Transactions are submitted for ordering
  5. Transactions are delivered to committing peer
  6. Validated transaction are applied to world state
  7. Client applications get notified with the status of the transaction

In the next recipe, we will walk through how to install Hyperledger Fabric on Amazon Web Services (AWS).

Installing Hyperledger Fabric on AWS

To install and run the recipe in this chapter, you need AWS EC2 Ubuntu Server 16.04 with 4 GB of memory. We will use the Fabric 1.3 release as it is the most stable release as of writing this recipe.

Getting ready

From the Hyperledger Fabric website (https://hyperledger-fabric.readthedocs.io/en/release-1.3/prereqs.html), the prerequisites for this recipe are as follows:

  • Operating systems: Ubuntu Linux 14.04 / 16.04 LTS (both 64-bit), or macOS 10.12
  • cURL tool: The latest version
  • Docker engine: Version 17.06.2-ce or greater
  • Docker-compose: Version 1.14 or greater
  • Go: Version 1.10.x
  • Node: Version 8.9 or higher (note: version 9 is not supported)
  • npm: Version 5.x
  • Python: 2.7.x

We chose Amazon Ubuntu Server 16.04. If you don't have experience with installing Ubuntu in EC2, please refer to the AWS document: https://aws.amazon.com/getting-started/tutorials/launch-a-virtual-machine/.

You can also chose to install Ubuntu in your local machine virtual box. A tutorial for this can be found at http://www.psychocats.net/ubuntu/virtualbox or https://askubuntu.com/questions/142549/how-to-install-ubuntu-on-virtualbox.

How to do it...

To install Hyperledger on AWS, follow these steps:

  1. Execute the following commands to update the software on your system:
        $ sudo apt-get update
  1. Install curl and the golang software package:
        $ sudo apt-get install curl
$ sudo apt-get install golang
$ export GOPATH=$HOME/go
$ export PATH=$PATH:$GOPATH/bin
  1. Install Node.js, npm, and Python:
        $ sudo apt-get install nodejs
$ sudo apt-get install npm
$ sudo apt-get install python
  1. Install and upgrade docker and docker-compose:
        $ sudo apt-get install docker
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg |
sudo apt-key add -

$ sudo add-apt-repository "deb [arch=amd64]
https://download.docker.com/linux/ubuntu
$(lsb_release -cs) stable"

$ sudo apt-get update
$ apt-cache policy docker-ce
$ sudo apt-get install -y docker-ce
$ sudo apt-get install docker-compose
$ sudo apt-get upgrade

  1. Let's customize and update Node.js and golang to the proper versions:
        $ wget https://dl.google.com/go/go1.11.2.linux-amd64.tar.gz
$ tar -xzvf go1.11.2.linux-amd64.tar.gz
$ sudo mv go/ /usr/local
$ export GOPATH=/usr/local/go
$ export PATH=$PATH:$GOPATH/bin
$ curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
$ sudo apt-get install -y nodejs
  1. Verify the installed software package versions:
        $ curl --version
$ /usr/local/go/bin/go version
$ python -V
$ node -v
$ npm -version
$ docker --version
$ docker-compose --version

The result should look like this:

  1. Install Hyperledger Fabric 1.3:
        $ curl -sSL http://bit.ly/2ysbOFE | sudo bash -s 1.3.0

It will take a few minutes to download the Docker images. When it is done, the results should look like this:

This completes the installation of the Hyperledger Fabric on the AWS EC2 machine. We will build up the network in the next recipe.

How it works...

We installed several prerequisites, so let's explain what each software package is and how they work together to build the Hyperledger Fabric platform:

  • cURL: A tool used to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP, or FILE). The command is designed to work without user interaction.
  • Docker: A tool to create, deploy, and run applications using containers. Containers allow developers to package applications with all of the parts it needs, such as libraries and other dependencies, and ship it out as one package.
  • Docker Compose: It is a tool which is used for defining and running Multi-container application. You can create and start all the services with help of a single command from your configuration YAML file.
  • Go: An open source programming language that makes it easy to build simple, reliable, and efficient software. Hyperledger Fabric is primarily developed using the Go language.
  • Node.js: A platform built on Chrome's JavaScript runtime to easily build fast and scalable network applications. Node.js is considered to be more lightweight and efficient since it uses event-driven, non-blocking I/O models, which make it more feasible for data-intensive real-time applications.
  • npm package manager: A tool that will allow you to install third-party libraries (other people's code) using the command line.
  • Python: A general-purpose programming language for developing both desktop and web applications. Python is also used to develop complex scientific and numeric applications. It is designed with features to facilitate data analysis and visualization.

With this Hyperledger Fabric installation, it will download and install samples and binaries to your system. The sample applications installed are useful for learning the capabilities and operations of Hyperledger Fabric:

  • balance-transfer: A sample Node.js app to demonstrate fabric-client and fabric-ca-client Node.js SDK APIs.
  • basic-network: A basic network with certificates and key materials, predefined transactions, and one channel, mychannel.
  • bin: Binary and scripts for fabric-ca, orderer, and peer.
  • chaincode: Chaincode developed for fabcar, marbles, and a few other examples.
  • chaincode-docker-devmode: Develops chaincode in dev mode for rapid code/build/run/debug.
  • config: YAML files to define transaction, orderer, organization, and chaincode.
  • fabcar: A sample Node.js app to demonstrate the capabilities with chaincode deployment, query, and updating the ledger.
  • fabric-ca: Uses the Fabric CA client and server to generate all crypto material and learn how to use attribute-based access control.
  • first-network: Builds the first hyperledger fabric network with byfn.sh and eyfn.sh.
  • Jenkinsfile: Jenkins is a suite of plugins that supports implementing and integrating continuous-delivery pipelines. The definition of a Jenkins pipeline is typically written into a text file, Jenkinsfile, which in turn is checked into a project's source-control repository.
  • scripts: There are two scripts in this directory: bootstrap.sh and Jenkins_Scripts.

Now that we have successfully installed Hyperledger Fabric on an AWS EC2 virtual machine, in the next recipe, we will set up the first Hyperledger Fabric network.

Building the Fabric network

To run this recipe, you need to complete the Reviewing the Hyperledger Fabric architecture and components recipe in this chapter to install Hyperledger Fabric with samples and binaries on the AWS EC2 instance.

How to do it...

There is a Build your first network (BYFN) sample installed with Hyperledger Fabric. We will use that to provision a sample Hyperledger Fabric network that consists of two organizations, each maintaining two peer nodes, and a solo ordering service. To do this, follow these steps:

  1. Log in as a default user and execute the byfn.sh script to generate certificates and keys for the network:
        $ cd ~
$ sudo chmod 777 -R fabric-samples
$ cd fabric-samples/first-network
$ sudo ./byfn.sh generate
  1. Bring up the Fabric network by executing the byfn.sh script using the up option:
        $ cd ~
$ cd fabric-samples/first-network
$ sudo ./byfn.sh up

You should see the following output, which states that the network has started successfully:

  1. Bring down the Fabric network by executing the byfn.sh script using the down option to shut down and clean up the network. This kills the containers, removes the crypto material and artifacts, and deletes the chaincode images. The following code shows how to do this:
        $ cd ~
$ cd fabric-samples/first-network
$ sudo ./byfn.sh down

Let's review the byfn.sh script, shown as follows. This script is well documented, and you should read about it in detail to understand each execution step during the network startup process:

We will review and exam the Hyperledger Fabric byfn.sh script using the command-line interface.

  1. Use the tool for crypto and certificate generation, called cryptogen, which uses a YAML configuration file as the base to generate the certificates:
        OrdererOrgs:
- Name: Orderer
Domain: example.com
Specs:
- Hostname: orderer
PeerOrgs:
- Name: Org1
Domain: org1.example.com
EnableNodeOUs: true
Template:
Count: 2
Users:
Count: 1
- Name: Org2
Domain: org2.example.com
EnableNodeOUs: true
Template:
Count: 2
Users:
Count: 1

The following command will generate the YAML file:

        $ cd ~
$ cd fabric-samples/first-network
$ sudo ../bin/cryptogen generate --config=./crypto-config.yaml

On execution of the previous command, you will find a new directory crypto-config is created, and inside there are directories that correspond to ordererOrganizations and peerOrganizations. We have two organizations, ( Org1.example.com and Org2.example.com ) network artifacts.

  1. Let's generate the configuration transaction. The tool to generate the configuration transaction is called configtxgen. The artifacts generated in this step are the orderer genesis block, the channel configuration transaction, and one anchor peer transaction for each peer organization. There will also be a configtx.yaml file that is broken into several sections: profiles (describe the organizational structure of the network), organizations (the details regarding individual organizations), orderer (the details regarding the orderer parameters), and application (application defaults—not needed for this recipe).

The profiles that are needed for this recipe are shown as follows:

        Profiles:

TwoOrgsOrdererGenesis:
<<: *ChannelDefaults
Orderer:
<<: *OrdererDefaults
Organizations:
- *OrdererOrg
Capabilities:
<<: *OrdererCapabilities
Consortiums:
SampleConsortium:
Organizations:
- *Org1
- *Org2
TwoOrgsChannel:
Consortium: SampleConsortium
Application:
<<: *ApplicationDefaults
Organizations:
- *Org1
- *Org2
Capabilities:
<<: *ApplicationCapabilities

Let's go with the detailed command-line steps to understand what is happening:

        $ export FABRIC_CFG_PATH=$PWD
$ sudo ../bin/configtxgen -profile TwoOrgsOrdererGenesis -
outputBlock ./channel-artifacts/genesis.block

$ export CHANNEL_NAME=mychannel
$ sudo ../bin/configtxgen -profile TwoOrgsChannel
-outputCreateChannelTx ./channel-artifacts/channel.tx
-channelID $CHANNEL_NAME

$ sudo ../bin/configtxgen -profile TwoOrgsChannel
-outputAnchorPeersUpdate ./channel-artifacts/Org1MSPanchors.tx
-channelID $CHANNEL_NAME -asOrg Org1MSP

$ sudo ../bin/configtxgen -profile TwoOrgsChannel
-outputAnchorPeersUpdate ./channel-artifacts/Org2MSPanchors.tx
-channelID $CHANNEL_NAME -asOrg Org2MSP

Here, we write the blockchain genesis block, create the first channel transaction, and write anchor peer updates. You may not care how exactly it is done, but this is how Fabric is built from the bottom up. You can see that four new files are generated and stored in the channel-artifacts directory:

  • genesis.block
  • channel.tx
  • Org1MSPanchors.tx
  • Org2MSPanchors.tx
  1. The Docker Compose tool is used to bring up Docker containers. We use docker-compose-cli.yaml to keep track of all Docker containers that we bring up:
        $ cd ~
$ cd fabric-samples/first-network
$ sudo docker-compose -f docker-compose-cli.yaml up -d

  1. We have brought up six nodes: cli, orderer.example.com, peer0.org1.example.com, peer0.org2.example.com, peer1.org1.example.com, and peer1.org2.example.com:
  1. Use the peer CLI to set up the network. Using the peer command line within the Docker CLI container for this step, we will create the channel using channel.tx so that peers can join the channel. Please note that some commands are extremely long as we need to set up peer environment variables (note that the default is peer0.org1), as follows:
        $ cd ~
$ cd fabric-samples/first-network
$ sudo docker exec -it cli bash
$ export CHANNEL_NAME=mychannel

$ peer channel create -o orderer.example.com:7050 -c
$CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --
cafile/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem
$ peer channel join -b mychannel.block

// for peer0.org2
$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/
fabric/peer/crypto/peerOrganizations/org2.example.com/
users/Admin@org2.example.com/msp
CORE_PEER_ADDRESS=peer0.org2.example.com:7051
CORE_PEER_LOCALMSPID="Org2MSP"
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/
hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/
peers/peer0.org2.example.com/tls/ca.crt
$ peer channel join -b mychannel.block

// for peer1.org1
CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/
hyperledger/fabric/peer/crypto/peerOrganizations/
org1.example.com/users/Admin@org1.example.com/msp
CORE_PEER_ADDRESS=peer1.org1.example.com:7051
CORE_PEER_LOCALMSPID="Org1MSP"
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/
hyperledger/fabric/peer/crypto/peerOrganizations/
org1.example.com/peers/peer1.org1.example.com/tls/ca.crt
peer channel join -b mychannel.block

// for peer1.org2
CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer1.org2.example.com:7051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls/ca.crt peer channel join -b mychannel.block

This will create a connection between all four peers:

  1. Update the anchor peer on each organization. We use the files we created in the Installing Hyperledger Fabric on AWS section (Org1MSPanchors.tx and Org2MSPanchors.tx) and apply them to Peer0 of both Org1 and Org2:
        $ peer channel update -o orderer.example.com:7050 -c $CHANNEL_NAME 
-f
./channel-artifacts/Org1MSPanchors.tx --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
ordererOrganizations/example.com/orderers/orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem

$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/
fabric/peer/crypto/peerOrganizations/org2.example.com/
users/Admin@org2.example.com/msp
CORE_PEER_ADDRESS=peer0.org2.example.com:7051
CORE_PEER_LOCALMSPID="Org2MSP"
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/
hyperledger/fabric/peer/crypto/peerOrganizations/
org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
peer channel update -o orderer.example.com:7050 -c
$CHANNEL_NAME -f ./channel-artifacts/Org2MSPanchors.tx
--tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
  1. Using the CLI, we need to install the chaincode to peer0 Org1 and peer0 Org2. The chaincode is specified in the -p option in the command and the chaincode name is mycc. This is shown in the following code:
$ peer chaincode install -n mycc -v 1.0 -p github.com/chaincode/chaincode_example02/go/

$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer0.org2.example.com:7051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt peer chaincode install -n mycc -v 1.0 -p github.com/chaincode/chaincode_example02/go//orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
  1. Instantiate the chaincode from peer0.org2. We will use -c to initialize this with a value of 100, and b with 200. We use -p to define the endorsement policy. This is shown in the following code:
$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer0.org2.example.com:7051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n mycc -v 1.0 -c '{"Args":["init","a", "100", "b","200"]}' -P "AND ('Org1MSP.peer','Org2MSP.peer')"
  1. Execute a query on peer0 Org1 on the a value. We should get the correct value of 100 back:
$ peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'
  1. Using the CLI, create a transaction by invoking chaincode. In this example, we will move 10 from a to b. Install chaincode on peer1 org2, and then query from peer1 org2 for the latest value of a:
$ CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer1.org2.example.com:7051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls/ca.crt peer chaincode install -n mycc -v 1.0 -p github.com/chaincode/chaincode_example02/go/

$CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer1.org2.example.com:7051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls/ca.crt peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'

This takes some time, but we will eventually receive the result of 90, which is correct after 10 is removed from 100:

This concludes building our first Fabric network. We will look at how to make changes to the existing network and add an organization to a channel in the next recipe.

How it works...

We covered the following steps to build our Fabric network:

  • Generating the crypto/certificate using cryptogen
  • Generating the configuration transaction using configtxgen
  • Bring up the nodes based on what is defined in the docker-compose file
  • Using the CLI to set up the first network
  • Using the CLI to install and instantiate the chaincode
  • Using the CLI to invoke and query the chaincode

This recipe helps you to understand the Hyperledge Fabric components and shows how we can quickly set up a Hyperledger Fabric network using sample chaincode (mycc). You should be able to modify the scripts and run other samples, such as fabcar and marble02, which are provided under the fabric-sample/chaincode directory.

Fabric provides the following commands used in the byfn.sh script. In the following chapters and recipes, these commands will be used to operate and manage the Fabric network environment:

  • peer: Operates and configures a peer
  • peer chaincode: Manages chaincode on the peer
  • peer channel: Manages channels on the peer
  • peer node: Manages the peer
  • peer version: Returns the peer version
  • cryptogen: Utility for generating crypto material
  • configtxgen: Creates configuration data, such as the genesis block
  • configtxlator: Utility for generating channel configurations
  • fabric-ca-client: Manage identities
  • fabric-ca-server: Manages the fabric-ca server

Now that we have set up our first network, let's add an organization to the channel.

Adding an organization to a channel

This recipe serves as an extension to the BYFN recipe. We will demonstrate how to add a new organization Org3 to the application's channel (mychannel).

Getting ready...

To run this recipe, you need complete the Reviewing the Hyperledger Fabric architecture and components recipe in this chapter to install Hyperledger Fabric with samples and binaries on the AWS EC2 instance.

How to do it...

Since we need add the new organization, Org3, to BYFN, we will first bring up the BYFN network. Follow these steps:

  1. Bring up the first network using the following command:
        $ cd ~
$ cd fabric-samples/first-network
$ sudo ./byfn.sh generate
$ sudo ./byfn.sh up

  1. Execute the script to add Org3 into the mychannel channel:
    $ cd ~
$ cd fabric-samples/first-network
$ sudo ./eyfn.sh up

The following screenshot confirms org3 is added to mychannel successfully:

We can test this by running a query against Org3 peer0.

  1. To shut down and clean up the network, execute the following:
        $ cd fabric-samples/first-network
$ sudo ./eyfn.sh down
$ sudo ./byfn.sh down

How it works...

Like what we did in the Building the Fabric network recipe, the eyfn.sh script is a good resource to understand how things work.

We will also look into the command-line steps to see the internal building blocks to add an organization to a channel:

  1. Generate the org3 certificates:
        $ cryptogen generate --config=./org3-crypto.yaml
  1. Generate the org3 configuration materials:
        $ configtxgen -printOrg Org3MSP
  1. Generate and submit the transaction configuration for organization 3:
         $ peer channel fetch config config_block.pb -o 
orderer.example.com:7050 -c mychannel --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
$ configtxlator proto_encode --input config.json
--type common.Config
$ configtxlator proto_encode --input modified_config.json
--type common.Config
$ configtxlator compute_update --channel_id mychannel
--original original_config.pb --updated modified_config.pb
$ configtxlator proto_decode --input config_update.pb
--type common.ConfigUpdate

  1. Configure the transaction to add org3, which has been created:
        $ peer channel signconfigtx -f org3_update_in_envelope.pb
  1. Submit the transaction from a different peer (peer0.org2), who also signs it:
        $ peer channel update -f org3_update_in_envelope.pb -c mychannel -o 
orderer.example.com:7050 --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem
  1. Get the org3 peer to join the network:
        $ peer channel fetch 0 mychannel.block -o orderer.example.com:7050 
-c mychannel --tls --cafile /opt/gopath/src/github.com/
hyperledger/fabric/peer/
crypto/ordererOrganizations/
example.com/orderers/orderer.example.com/

msp/tlscacerts/tlsca.example.com-cert.pem
$ peer channel join
-b mychannel.blockcd fabric-samples/first-network
  1. Install and update the chaincode:
         $ peer chaincode install -n mycc -v 2.0 -l golang -p    
github.com/chaincode/chaincode_example02/go/
$ peer chaincode upgrade -o orderer.example.com:7050
--tls true --cafile /opt/gopath/src/github.com/hyperledger/
fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem
-C
mychannel -n mycc -v 2.0 -c
'{"Args":["init","a","90","b","210"]}'

-P 'AND ('\''Org1MSP.peer'\'','\''Org2MSP.peer'\'',
'\''Org3MSP.peer'\'')'
  1. Query peer0 org3:
        $ peer chaincode query -C mychannel -n mycc 
-c '{"Args":["query","a"]}'
  1. Invoke the transaction to move 10 from a to b again on a different peer:
        $ peer chaincode invoke -o orderer.example.com:7050 --tls true 
--cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem
-C
mychannel -n mycc --peerAddresses peer0.org1.example.com:7051
--tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/
fabric/peer/crypto/
peerOrganizations/org1.example.com/peers/
peer0.org1.example.com
/tls/ca.crt
--peerAddresses peer0.org2.example.com:7051

--tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/
fabric/peer/
crypto/peerOrganizations/org2.example.com/peers/
peer0.org2.example.com/tls/ca.crt
--peerAddresses peer0.org3.example.com:7051
--tlsRootCertFiles/opt/gopath/src/github.com/hyperledger/
fabric/
peer/crypto/peerOrganizations/org3.example.com/peers/
peer0.org3.example.com/tls/ca.crt
-c '{"Args":["invoke","a","b","10"]}'


This concludes how to add an organization to an existing network in a channel. We will look at how to use CouchDB to review transactions in the next recipe.

Following all the previous steps will create our first network, which consists of two organizations, two peers per organization, and single Solo ordering service. In this recipe, we showed you how to add a third organization to an application channel with its own peers to an already running first network, and then join it to the new channel.

When you view the log file, you will be able to see details in the following order:

  • Generating Org3 config material
  • Generating and submitting config tx to add Org3
  • Creating config transaction to add Org3 to the network
  • Installing jq
  • Config transaction to add Org3 to the network
  • Signing the config transaction
  • Submitting the transaction from a different peer (peer0.org2), which also signs it
  • Configure transaction to add Org3 to network submitted
  • Having Org3 peers join the network
  • Getting Org3 on to your first network
  • Fetching the channel config block from orderer
  • peer0.org3 joined the mychannel channel
  • peer1.org3 joined the mychannel channel
  • Installing chaincode 2.0 on peer0.org3
  • Upgrading chaincode to have Org3 peers on the network
  • Finishing adding Org3 to your first network
  • Chaincode is installed on peer0.org1
  • Chaincode is installed on peer0.org2
  • Chaincode is upgraded on peer0.org1 on the mychannel channel
  • Finished adding Org3 to your first network!

Updating modification policies or altering batch sizes or any other channel configuration can be updated using the same approach but for now we will focus solely on the integration of a new organization.

There's more...

The following block shows the org3-crypto.yaml section for Org3:

# --------------------------------------------------------------------------
# "PeerOrgs" - Definition of organizations managing peer nodes
# ---------------------------------------------------------------------------
PeerOrgs:
# ---------------------------------------------------------------------------
# Org3
# ---------------------------------------------------------------------------
- Name: Org3
Domain: org3.example.com
EnableNodeOUs: true
Template:
Count: 2
Users:
Count: 1

The following block shows the configtx.yaml section for Org3:

#################################################################################
# Section: Organizations
#
# - This section defines the different organizational identities which will
# be referenced later in the configuration.
#
################################################################################
Organizations:
- &Org3
# DefaultOrg defines the organization which is used in the sampleconfig
# of the fabric.git development environment
Name: Org3MSP
# ID to load the MSP definition as
ID: Org3MSP
MSPDir: crypto-config/peerOrganizations/org3.example.com/msp
AnchorPeers:
# AnchorPeers defines the location of peers which can be used for cross org gossip #communication. Note, this value is only
# encoded in the genesis block in the Application section context
- Host: peer0.org3.example.com
Port: 7051

In the next recipe, we will look at how smart contracts work with CouchDB.

Using CouchDB

In this recipe, we will explore how to start up a network using CouchDB and then look at transactions applied into CouchDB from a web UI. To successfully execute this recipe, you need install the Hyperledger Fabric with samples and binaries on the AWS EC2 instance.

How to do it...

To use CouchDB, follow these steps:

  1. Make sure network is not up. If it is up, shut down the network, as shown here:
        $ cd fabric-samples/first-network
$ sudo ./byfn.sh down
  1. Start up the BYFN network using CouchDB:

Here we will start up the network by using the CouchDB database.

        $ cd fabric-samples/first-network
$ sudo ./byfn.sh up -c mychannel -s couchdb

Following screenshot shows our network starting up:

  1. Install chaincode by navigating into the CLI container using the command-line interface:
        $ sudo docker exec -it cli bash
$ peer chaincode install -n marbles -v 1.0
-p github.com/chaincode/marbles02/go
  1. Instantiate the chaincode:
        $ export CHANNEL_NAME=mychannel
$ peer chaincode instantiate -o orderer.example.com:7050
--tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem
-C
$CHANNEL_NAME -n marbles -v 1.0 -c '{"Args":["init"]}' -P "OR
('Org0MSP.peer','Org1MSP.peer')"
  1. Invoke the chaincode. The following commands invoke chaincode to create marble.
        $ peer chaincode invoke -o orderer.example.com:7050 --tls 
--cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/
crypto/ordererOrganizations/example.com/orderers/
orderer.example.com/
msp/tlscacerts/tlsca.example.com-cert.pem
-C $CHANNEL_NAME -n marbles -c

'{"Args":["initMarble","marble5","blue","35","tom"]}'

Following screenshot shows successful creation of chanincode:

  1. Open the CouchDB UI by navigating to http://host-ip:5984/_utils/#/_all_dbs (in my case, my AWS public IP address is 3.91.245.92, so the URL is http://3.91.245.92:5984/_utils/#/_all_dbs):

In order to allow public access to CouchDB, we need open port 5984. Navigate to the AWS security group under the instance, launch the wizard, and choose Action | Edit Inbound Rules | Add Inbound Rule. This is shown as follows. After this, click Save. You can follow the below example to allow all IP address to access CouchDB:

  1. From mychannel_marbles, we can query and see the transaction ID with marble5:
  1. Click marble5, and you will see the default marble5 files:

Here, we saw how to use CouchDB to view how transactions get created, and updated them on the Fabric network. We will write a smart contract and deploy it as an application in the next recipe.

How it works...

In this recipe, we learned how to use CouchDB as the state database with Hyperledger Fabric. We also looked at how to use CouchDB to deploy Marbles to the network.

Hyperledger Fabric supports two types of peer databases: LevelDB is the default state database embedded in the peer node and stores chaincode data as simple key-value pairs; and CouchDB is an optional alternate state database that supports rich queries when chaincode data values are modeled as JSON. This recipe describes the steps required to use CouchDB as the state database with Fabric. CouchDB is a JSON document datastore rather than a pure key-value store, therefore enabling indexing of the contents of the documents in the database.

In the last recipe, we will show you how to write your first smart contract application and deploy it into the blockchain.

Writing your first application

In this recipe, we will explore how to create a smart contract and then deploy it into the blockchain.

To run this recipe, you need to have completed the Installing Hyperledger Fabric on AWS recipe in this chapter to install Hyperledger Fabric with samples and binaries on the AWS EC2 instance.

How to do it...

To write your first application, follow these steps:

  1. Set up the development environment:
        $ cd ~
cd fabric-samples/first-network
sudo docker ps
sudo ./byfn.sh down
sudo docker rm -f $(sudo docker ps -aq)
sudo docker network prune
cd ../fabcar && ls

You will notice that there are a few Node.js file present in fabcar folder such as enrollAdmin.js, invoke.js, query.js, registerUser.js, and package.json and all others packaged into one startFabric.sh file.

  1. Install the Fabric client:
        $ sudo npm install -g npm@5.3.0
$ sudo npm update

You will notice from the following screenshot that the Fabric client 1.3.0 and Fabric CA client 1.30 packages are installed:

  1. Execute the following command to launch the network:
        $ sudo ./startFabric.sh node
  1. Open a new Terminal to stream the Docker logs:
        $ sudo docker logs -f ca.example.com

This will open the Docker file, which will look similar to the following screenshot:

Next, we will use the Node.js script to run, query, and update the records on Fabric network.

Accessing the API with SDK

In this recipe, the application uses an SDK to access the APIs that permit queries and updates to the ledger. Now we will perform the following steps:

  1. Enroll an admin user with the enrollAdmin.js script:
        $ sudo node enrollAdmin.js

When we launch the network, an admin user needs to be registered with certificate authority. We send an enrollment call to the CA server and retrieve the enrollment certificate (eCert) for this user. We then use this admin user to subsequently register and enroll other users:

  1. Register and enroll a user called user1 using the registerUser.js script:
        $ sudo node registerUser.js
  1. With the newly-generated eCert for the admin user, let's communicate with the CA server once more to register and enroll user1. We can use the ID of user1 to query and update the ledger:
  1. Let's run a query against the ledger:
        $ sudo node query.js
  1. It returns the following screenshot. You will find that there are 10 cars on the network, from CAR0 to CAR9. Each has a color, doctype, make, model, and owner:

  1. The following chaincode constructs the query using the queryAllCars function to query all cars:
         // queryCar chaincode function - requires 1 argument,
ex: args: ['CAR4'],
// queryAllCars chaincode function - requires no arguments,
ex: args: [''],
const request = {
//targets : --- letting this default to the
peers assigned to the channel
chaincodeId: 'fabcar',
fcn: 'queryAllCars',
args: ['']
}
  1. Update the ledger. To do this, we will update the invoke.js script. This time, the fabcar chaincode uses the createCar function to insert a new car, CAR10, into the ledger:
        var request = {
//targets: let default to the peer assigned to the client
chaincodeId: 'fabcar',
fcn: 'createCar',
args: ['CAR10', 'Chevy', 'Volt', 'Red', 'Nick'],
chainId: 'mychannel',
txId: tx_id
};

sudo node invoke.js

Here we will complete the transaction when CAR10 is created.

  1. Execute a query to verify the changes made. Change query.js using the queryCar function to query CAR10:
        var request = {
//targets: let default to the peer assigned to the client
chaincodeId: 'fabcar',
fcn: 'queryCar',
args: ['CAR10'],
chainId: 'mychannel',
txId: tx_id
};

  1. Run query.js again. We can now extract CAR10 from the ledger with the response as {"color":"Red","docType":"car","make":"Chevy","model":"Volt","owner":"Nick"}:
      sudo node query.js

This will result in the following query:

  1. Shut down the Fabric network:
      sudo docker stop $(sudo docker ps -a -q)
sudo docker rm $(sudo docker ps -a -q)
sudo docker ps

We have gone through the steps to query and update the transaction using smart contract chaincode. Now, let's see how it works under the hood.

How it works...

This concludes the recipe to create and deploy your first smart contract chaincode.

In the previous steps, we used query.js to query the key-value pair store. We can also query for the values of one or more keys, or perform complex searches on JSON data-storage formats. The following diagram shows how the query works:

The following is a representation of different functions in chaincode, which explains that we should first define the code functions to all the available APIs in the chaincode interface:

The following diagram shows the process of updating the ledger. Once an update to the ledger is proposed and endorsed, it will be returned to the application, and will in turn send the updated ledger to be ordered and written to every peer's ledger:

We learned how to write a small smart contract chaincode on the Fabric network to perform a transaction data query and update. In the next chapter, you will learn how to write an end-to-end Hyperledger Fabric application using all that we have learned in this chapter.

See also

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Plan, design, and create a full-fledged private decentralized application using Hyperledger services
  • Master the ins and outs of the Hyperledger network using real-world examples
  • Packed with problem-solution-based recipes to tackle pain areas in the blockchain development cycle

Description

Hyperledger is an open-source project and creates private blockchain applications for a range of domains. This book will be your desk reference as you explore common and not-so-common challenges faced while building blockchain networks using Hyperledger services. We'll work through all Hyperledger platform modules to understand their services and features and build end-to-end blockchain applications using various frameworks and tools supported by Hyperledger. This book's independent, recipe-based approach (packed with real-world examples) will familiarize you with the blockchain development cycle. From modeling a business network to integrating with various tools, you will cover it all. We'll cover common and not-so-common challenges faced in the blockchain life cycle. Later, we'll delve into how we can interact with the Hyperledger Fabric blockchain, covering all the principles you need to master, such as chaincode, smart contracts, and much more. We'll also address the scalability and security issues currently faced in blockchain development. By the end of this book, you will be able to implement each recipe to plan, design, and create a full-fledged, private, decentralized application to meet organizational needs.

What you will learn

Create the most popular permissioned blockchain network with Fabric and Composer Build permissioned and permission-less blockchains using Sawtooth Utilize built-in Iroha asset/account management with role-based permissions Implement and run Ethereum smart contracts with Burrow Get to grips with security and scalability in Hyperledger Explore and view blockchain data using Hyperledger Explorer Produce reports containing performance indicators and benchmarks using Caliper

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Apr 30, 2019
Length 310 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781789534887
Category :
Languages :
Concepts :

Table of Contents

12 Chapters
Preface Chevron down icon Chevron up icon
Working with Hyperledger Fabric Chevron down icon Chevron up icon
Implementing Hyperledger Fabric Chevron down icon Chevron up icon
Modeling a Business Network Using Hyperledger Composer Chevron down icon Chevron up icon
Integrating Hyperledger Fabric with Explorer Chevron down icon Chevron up icon
Working with Hyperledger Sawtooth Chevron down icon Chevron up icon
Operating an Ethereum Smart Contract with Hyperledger Burrow Chevron down icon Chevron up icon
Working with Hyperledger Iroha Chevron down icon Chevron up icon
Exploring the CLI with Hyperledger Indy Chevron down icon Chevron up icon
Hyperledger Blockchain Scalability and Security Chevron down icon Chevron up icon
Hyperledger Blockchain Ecosystem Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.