Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

SANJAYBHAI RAJGURU COLLEGE OF

ENGINEERING
RAJKOT

LAB MANUAL

Blockchain
(3171618)
BLOCKCHAIN Er. No.

SANJAYBHAI RAJGURU COLLEGE OF


ENGINEERING

CERTIFICATE

This is to certify that Shri / Kum.

…………………………..……………………………… Enroll No. …………………..of


B.E. …th Semester……………………branch has satisfactorily completed
the laboratory work in ……………………….

Date of Submission: …………………………

Staff Sign Head of department

2
BLOCKCHAIN Er. No.

INDEX

Sr.No. Date Experiment Description Faculty Sign

1 Ethereum –With respect to Ethereum

2 Installing Hyperledger Fabric

3 Hyperledger Fabric Demo

4 Build Network with Network configuration.

5 Understanding the Docker Compose topology

3
BLOCKCHAIN Er. No.

Practical-1
Aim: Ethereum –With respect to Ethereum

What is an Ethereum node or client?


Ethereum nodes are computers participating in Ethereum blockchain network. These nodes are
actual computers running software that verifies, stores, and sometimes creates blocks. The
actual software is called a "client," and it allows us to interact with the blockchain using the
JSON-RPC API, parse and verify the blockchain, and read or write to smart-contracts.

Ethereum is reaching far more developers than ever. With this growth adoption of Ethereum,
there has been a flow of multiple Ethereum clients in the industry. Nethermind, Aleth, Geth,
and Trinity are the official libraries written and maintained by the Ethereum foundation.
Meanwhile, Parity (now known as OpenEthereum) and Hyperledger Besu are two of the most
popular third-party clients.

Geth is the most popular Ethereum client out today. It is aimed to be the fastest, lightest, and
most secure Ethereum Client. It's written in the Go programming language and maintained by a
group of core Ethereum Foundation developers and other contributors. In this article, we will
learn how to run a Geth node.

Why use Geth?


There are many reasons you'd use Geth, but our favorite reasons are:

 Geth is the official client software provided by the Ethereum foundation.


 Comes with a JavaScript console (run it with `geth console`).
 Has an interoperable JavaScript client (web3js).
 Built-in access to the Rinkeby test net (or build your own private Ethereum network).
 It is generally considered to be the reference implementation for other Ethereum
nodes.

Installing Geth

We can install Geth in many ways and on many types of systems; here are a few quick starts for
standard methods:

Installing Using a Package Manager

macOS

4
BLOCKCHAIN Er. No.

On macOS, Geth can be installed very easily by using go-ethereum's Homebrew tap:

Windows

The fastest and easiest way to install and run geth on windows is by downloading pre-compiled
binaries from here. The page has an installer as well a .zip file; the installer will put geth into
your PATH automatically, while the .zip file contains the .exe files, which directly can be run
without bothering to run the installer.

Install Geth using Docker

Geth team also maintains four different docker images for running the latest stable or
development versions of Geth.

 ethereum/client-go:latest is the latest development version of Geth


 ethereum/client-go:stable is the latest stable version of Geth
 ethereum/client-go:{version} is the stable version of Geth at a specific version number
 ethereum/client-go:release-{version} is the latest stable version of Geth at a particular version
family

To installed Geth client using docker run

The image has the following ports automatically exposed:

 8545 TCP, used by the HTTP based JSON RPC API


 8546 TCP, used by the WebSocket based JSON RPC API
 30303 TCP and UDP, used by the P2P protocol running the network

5
BLOCKCHAIN Er. No.

 30304 UDP, used by the P2P protocol's new peer discovery overlay

Manage Accounts and Account states.

ETHEREUM OPTIONS:
--config value TOML configuration file
--datadir.minfreedisk value Minimum free disk space in MB, o
nce reached triggers auto shut down (default = --cache.gc converted to
MB, 0 = disabled)
--keystore value Directory for the keystore (defa
ult = inside the datadir)
--usb Enable monitoring and management
of USB hardware wallets
--pcscdpath value Path to the smartcard daemon (pc
scd) socket file
--networkid value Explicitly set network id (integ
er)(For testnets: use --ropsten, --rinkeby, --goerli instead) (default
: 1)
--syncmode value Blockchain sync mode ("snap", "f
ull" or "light") (default: snap)
--exitwhensynced Exits after block synchronisatio
n completes
--gcmode value Blockchain garbage collection mo
de ("full", "archive") (default: "full")
--txlookuplimit value Number of recent blocks to maint
ain transactions index for (default = about one year, 0 = entire chain
) (default: 2350000)
--ethstats value Reporting URL of a ethstats serv
ice (nodename:secret@host:port)
--identity value Custom node name
--lightkdf Reduce key-derivation RAM & CPU
usage at some expense of KDF strength
--eth.requiredblocks value Comma separated block number-to-
hash mappings to require for peering (<number>=<hash>)
--mainnet Ethereum mainnet
--ropsten Ropsten network: pre-configured
proof-of-stake test network
--rinkeby Rinkeby network: pre-configured
proof-of-authority test network
--goerli Görli network: pre-configured pr
oof-of-authority test network
--sepolia Sepolia network: pre-configured
proof-of-work test network

6
BLOCKCHAIN Er. No.

--kiln Kiln network: pre-configured pro


of-of-work to proof-of-stake test network
--datadir value Data directory for the databases
and keystore (default: "~/.ethereum")
--datadir.ancient value Data directory for ancient chain
segments (default = inside chaindata)
--remotedb value URL for remote database

Mining

Mining is the process through which new blocks are created. Geth actually creates new blocks
all the time, but these blocks need to be secured through proof-of-work so they will be
accepted by other nodes. Mining is all about creating these proof-of-work values.

The proof-of-work computation can be performed in multiple ways. Geth includes a CPU miner,
which does mining within the geth process. We discourage using the CPU miner with the
Ethereum mainnet. If you want to mine real ether, use GPU mining.

GPU mining

The ethash algorithm is memory hard and in order to fit the DAG into memory, it needs 1-2GB
of RAM on each GPU.

Installing ethminer

To get ethminer, you need to install the ethminer binary package or build it from source.
See https://github.com/ethereum-mining/ethminer/#build for the official ethminer
build/install instructions. At the time of writing, ethminer only provides a binary for Microsoft
Windows.
First create an account to hold your block rewards.

geth account new

Follow the prompts and enter a good password.

7
BLOCKCHAIN Er. No.

In the following examples, we will use 0xC95767AC46EA2A9162F0734651d6cF17e5BfcF10 as


the example address.

Now start geth and wait for it to sync the blockchain. This will take quite a while.

geth --http --miner.etherbase 0xC95767AC46EA2A9162F0734651d6cF17e5BfcF10

Now we’re ready to start mining. In a new terminal session, run ethminer and connect it to
geth:

ethminer -G -p http://127.0.0.1:8545

CPU Mining with Geth

When you start up your ethereum node with geth it is not mining by default.
geth --mine --miner.threads=4

You can also start and stop CPU mining at runtime using the console. miner.start takes an
optional parameter for the number of miner threads.

> miner.start(8)
true
> miner.stop()
true

In order to earn ether you must have your etherbase (or coinbase) address set. This etherbase
defaults to your primary account. If you don’t have an etherbase address, then geth --mine will
not start up.
You can set your etherbase on the command line:

geth --miner.etherbase '0xC95767AC46EA2A9162F0734651d6cF17e5BfcF10' --mine 2>> geth.lo


g

You can reset your etherbase on the console too:

> miner.setEtherbase(eth.accounts[2])

8
BLOCKCHAIN Er. No.

Note that your etherbase does not need to be an address of a local account, just an existing
one.
There is an option to add extra data (32 bytes only) to your mined blocks. By convention this is
interpreted as a unicode string, so you can set your short vanity tag.

> miner.setExtra("ΞTHΞЯSPHΞЯΞ")

You can check your hashrate with miner.hashrate, the result is in H/s (Hash operations per
second).

> eth.hashrate
712000

After you successfully mined some blocks, you can check the ether balance of your etherbase
account. Now assuming your etherbase is a local account:

> eth.getBalance(eth.coinbase).toNumber();
'34698870000000'

You can check which blocks are mined by a particular miner (address) with the following code
snippet on the console:

> function minedBlocks(lastn, addr) {


addrs = [];
if (!addr) {
addr = eth.coinbase
}
limit = eth.blockNumber - lastn
for (i = eth.blockNumber; i >= limit; i--) {
if (eth.getBlock(i).miner == addr) {
addrs.push(i)
}
}
return addrs
}

9
BLOCKCHAIN Er. No.

// scans the last 1000 blocks and returns the blocknumbers of blocks mined by your coinbase
// (more precisely blocks the mining reward for which is sent to your coinbase).
> minedBlocks(1000, eth.coinbase)
[352708, 352655, 352559]

Note that it will happen often that you find a block yet it never makes it to the canonical chain.
This means when you locally include your mined block, the current state will show the mining
reward credited to your account, however, after a while, the better chain is discovered and we
switch to a chain in which your block is not included and therefore no mining reward is
credited. Therefore it is quite possible that as a miner monitoring their coinbase balance will
find that it may fluctuate quite a bit.
The logs show locally mined blocks confirmed after 5 blocks. At the moment you may find it
easier and faster to generate the list of your mined blocks from these logs.

Practical – 2

10
BLOCKCHAIN Er. No.

Installing Hyperledger Fabric

Prerequisites

1. cURL — latest version


2. Docker — version 17.06.2-ce or greater
3. Docker Compose — version 1.14.0 or greater
4. Golang — version 1.11.x
5. Nodejs — version 8.x (other versions are not in support yet)
6. NPM — version 5.x
7. Python 2.7

Windows 10 Pro for the Fabric v1.4 installation.

Installing components

Step 1: Install the CLI tools

There are a few useful CLI tools for Composer developers. The most important one
is composer-cli , which contains all the essential operations, so we'll install that first. Next, we'll
also pick up generator-hyperledger-composer , composer-rest-server and Yeoman plus
the generator-hyperledger-composer . Those last 3 are not core parts of the development
environment, but they'll be useful if you're following the tutorials or developing applications
that interact with your Business Network, so we'll get them installed now.
Note that you should not use su or sudo for the following npm commands.
Essential CLI tools:

npm install -g [email protected]

install -g [email protected]
Utility for running a REST Server on your machine to expose your business networks as RESTful
APIs:

npm install -g [email protected]

install -g [email protected]
Useful utility for generating application assets:

npm install -g [email protected]

-g [email protected]

11
BLOCKCHAIN Er. No.

Yeoman is a tool for generating applications, which utilises generator-hyperledger-composer :

npm install -g yo

Step 2: Install Playground

If you've already tried Composer online, you'll have seen the browser app "Playground". You
can run this locally on your development machine too, giving you a UI for viewing and
demonstrating your business networks.
Browser app for simple editing and testing Business Networks:

npm install -g [email protected]

nstall -g [email protected]
Step 3: Set up your IDE

Whilst the browser app can be used to work on your Business Network code, most users will
prefer to work in an IDE. Our favourite is VSCode , because a Composer extension is available.
Install VSCode from this URL: https://code.visualstudio.com/download
Open VSCode, go to Extensions, then search for and install the Hyperledger
Composer extension from the Marketplace.
Step 4: Install Hyperledger Fabric
This step gives you a local Hyperledger Fabric runtime to deploy your business networks to.
In a directory of your choice (we will assume ~/fabric-dev-servers ), get the .tar.gz file that
contains the tools to install Hyperledger Fabric:

mkdir ~/fabric-dev-servers && cd ~/fabric-dev-servers

curl -O https://raw.githubusercontent.com/hyperledger/composer-
tools/master/packages/fabric-dev-servers/fabric-dev-servers.tar.gz

tar -xvf fabric-dev-servers.tar.gz

A zip is also available if you prefer: just replace the .tar.gz file with fabric-dev-servers.zip and
the tar -xvf command with a unzip command in the preceding snippet.
Use the scripts you just downloaded and extracted to download a local Hyperledger Fabric v1.1
runtime:

12
BLOCKCHAIN Er. No.

cd ~/fabric-dev-servers

export FABRIC_VERSION=hlfv11

./downloadFabric.sh

13
BLOCKCHAIN Er. No.

Practical-3

Aim: Hyperledger Fabric Demo

We’ll go through three principle steps:


1. Setting up a development environment. Our application needs a network to interact
with, so we’ll download one stripped down to just the components we need for
registration/enrollment, queries and updates:

2. Learning the parameters of the sample smart contract our app will use. Our smart
contract contains various functions that allow us to interact with the ledger in different
ways. We’ll go in and inspect that smart contract to learn about the functions our
applications will be using.

3. Developing the applications to be able to query and update assets on the ledger. We’ll
get into the app code itself (our apps have been written in Javascript) and manually
manipulate the variables to run different kinds of queries and updates.

Install the clients & launch the network


Run the following command to install the Fabric dependencies for the applicat ions. We are
concerned with fabric-ca-client which will allow our app(s) to communicate with the CA
server and retrieve identity material, and with fabric-client which allows us to load the
identity material and talk to the peers and ordering service.

14
BLOCKCHAIN Er. No.

npm install

Launch your network using the startFabric.sh shell script. This command will spin up our
various Fabric entities and launch a smart contract container for chaincode written in
Golang:

./startFabric.sh
You also have the option of running this tutorial against chaincode written in Node.js. If
you’d like to pursue this route, issue the following command instead:

./startFabric.sh node

How Applications Interact with the Network

For a more in-depth look at the components in our fabcar network (and how they’re
deployed) as well as how applications interact with those components on more of a
granular level, see Understanding the Fabcar Network.

Developers more interested in seeing what applications do – as well as looking at the code
itself to see how an application is constructed – should continue. For now, the most
important thing to know is that applications use a software development kit (SDK) to
access the APIs that permit queries and updates to the ledger.

Enrolling the Admin User


To stream your CA logs, split your terminal or open a new shell and issue the following:

docker logs -f ca.example.com

Now hop back to your terminal with the fabcar content…

When we launched our network, an admin user – admin – was registered with our
Certificate Authority. Now we need to send an enroll call to the CA server and retrieve the
enrollment certificate (eCert) for this user. We won’t delve into enrollment details here,
but suffice it to say that the SDK and by extension our applications need this cert in
order to form a user object for the admin. We will then use this admin object to
subsequently register and enroll a new user. Send the admin enroll call to the CA server:

15
BLOCKCHAIN Er. No.

node enrollAdmin.js
This program will invoke a certificate signing request (CSR) and ultimately output an eCert
and key material into a newly created folder – hfc-key-store – at the root of this project.
Our apps will then look to this location when they need to create or load the identity
objects for our various users.

Register and Enroll user1


With our newly generated admin eCert, we will now communicate with the CA server once
more to register and enroll a new user. This user – user1 – will be the identity we use
when querying and updating the ledger. It’s important to note here that it is
the admin identity that is issuing the registration and enrollment calls for our new user
(i.e. this user is acting in the role of a registrar). Send the register and enroll calls
for user1 :

node registerUser.js

Similar to the admin enrollment, this program invokes a CSR and outputs the keys and
eCert into the hfc-key-store subdirectory. So now we have identity material for two
separate users – admin & user1 . Time to interact with the ledger…

Querying the Ledger


Queries are how you read data from the ledger. This data is stored as a series of key -value
pairs, and you can query for the value of a single key, multiple keys, or – if the ledger is
written in a rich data storage format like JSON – perform complex searches against it
(looking for all assets that contain certain keywords, for example).

This is a representation of how a query works:

16
BLOCKCHAIN Er. No.

First, let’s run our query.js program to return a listing of all the cars on the ledger. We will
use our second identity – user1 – as the signing entity for this application. The following
line in our program specifies user1 as the signer:

fabric_client.getUserContext('user1', true);
Recall that the user1 enrollment material has already been placed into our hfc-key-
store subdirectory, so we simply need to tell our application to grab that identity. With
the user object defined, we can now proceed with reading from the ledger. A function that
will query all the cars, queryAllCars , is pre-loaded in the app, so we can simply run the
program as is:

node query.js
It should return something like this:

Successfully loaded user1 from persistence


Query has completed, checking results
Response is
[{"Key":"CAR0",
"Record":{"colour":"blue","make":"Toyota","model":"Prius","owner":"Tomoko"}},
{"Key":"CAR1",
"Record":{"colour":"red","make":"Ford","model":"Mustang","owner":"Brad"}},
{"Key":"CAR2",
"Record":{"colour":"green","make":"Hyundai","model":"Tucson","owner":"Jin Soo"}},
{"Key":"CAR3",
"Record":{"colour":"yellow","make":"Volkswagen","model":"Passat","owner":"Max"}},

17
BLOCKCHAIN Er. No.

{"Key":"CAR4",
"Record":{"colour":"black","make":"Tesla","model":"S","owner":"Adriana"}},
{"Key":"CAR5",
"Record":{"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}},
{"Key":"CAR6",
"Record":{"colour":"white","make":"Chery","model":"S22L","owner":"Aarav"}},
{"Key":"CAR7",
"Record":{"colour":"violet","make":"Fiat","model":"Punto","owner":"Pari"}},
{"Key":"CAR8",
"Record":{"colour":"indigo","make":"Tata","model":"Nano","owner":"Valeria"}},
{"Key":"CAR9",
"Record":{"colour":"brown","make":"Holden","model":"Barina","owner":"Shotaro"}}]
These are the 10 cars. A black Tesla Model S owned by Adriana, a red Ford Mustang owned
by Brad, a violet Fiat Punto owned by Pari, and so on. The ledger is key -value based and, in
our implementation, the key is CAR0 through CAR9 . This will become particularly
important in a moment.

Let’s take a closer look at this program. Use an editor (e.g. atom or visual studio) and
open query.js .

The initial section of the application defines certain variables such as channel name, cert
store location and network endpoints. In our sample app, these variables have been baked-
in, but in a real app these variables would have to be specified by the app dev.

var channel = fabric_client.newChannel('mychannel');


var peer = fabric_client.newPeer('grpc://localhost:7051');
channel.addPeer(peer);

var member_user = null;


var store_path = path.join(__dirname, 'hfc-key-store');
console.log('Store path:'+store_path);
var tx_id = null;
This is the chunk where we construct our query:

// 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',

18
BLOCKCHAIN Er. No.

args: ['']
};
When the application ran, it invoked the fabcar chaincode on the peer, ran
the queryAllCars function within it, and passed no arguments to it.

You’ll see that we have the following functions available to


call: initLedger , queryCar , queryAllCars , createCar , and changeCarOwner .

Let’s take a closer look at the queryAllCars function to see how it interacts with the
ledger.

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

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

resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)


This defines the range of queryAllCars . Every car between CAR0 and CAR999 – 1,000
cars in all, assuming every key has been tagged properly – will be returned by the query.

Below is a representation of how an app would call different functions in chaincode. Each
function must be coded against an available API in the chaincode shim interface, which in
turn allows the smart contract container to properly interface with the peer ledger.

19
BLOCKCHAIN Er. No.

Updating the Ledger

Now that we’ve done a few ledger queries and added a bit of code, we’re ready to update
the ledger. There are a lot of potential updates we could make, but let’s start by creating a
car.

Below we can see how this process works. An update is proposed, endorsed, the n returned
to the application, which in turn sends it to be ordered and written to every peer’s ledger:

Our first update to the ledger will be to create a new car. We have a separate Javascript
program – invoke.js – that we will use to make updates. Just as with queries, use an editor
to open the program and navigate to the code block where we construct our invocation:

// createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord',
'Black', 'Tom'],
// changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Barry'],
// must send the proposal to endorsing peers
var request = {
//targets: let default to the peer assigned to the client
chaincodeId: 'fabcar',
fcn: '',
args: [''],
chainId: 'mychannel',
txId: tx_id
};

20
BLOCKCHAIN Er. No.

Save it and run the program:

node invoke.js

21
BLOCKCHAIN Er. No.

Practical-4
Aim: Build Network with Network configuration.

The build your first network (BYFN) scenario provisions a sample Hyperledger Fabric network
consisting of two organizations, each maintaining two peer nodes, and a “solo” ordering
service.

Install prerequisites
Before we begin, if you haven’t already done so, you may wish to check that you have all
the Prerequisites installed on the platform(s) on which you’ll be developing blockchain
applications and/or operating Hyperledger Fabric.

You will also need to Install Samples, Binaries and Docker Images. You will notice that there are
a number of samples included in the fabric-samples repository. We will be using the first-
network sample. Let’s open that sub-directory now.

cd fabric-samples/first-network

Want to run it now?


We provide a fully annotated script - byfn.sh - that leverages these Docker images to quickly
bootstrap a Hyperledger Fabric network comprised of 4 peers representing two different
organizations, and an orderer node. It will also launch a container to run a scripted execution
that will join peers to a channel, deploy and instantiate chaincode and drive execution of
transactions against the deployed chaincode.

Here’s the help text for the byfn.sh script:

Usage:
byfn.sh <mode> [-c <channel name>] [-t <timeout>] [-d <delay>] [-f <docker-compose-file>] [-s
<dbtype>] [-l <language>] [-i <imagetag>] [-v]
<mode> - one of 'up', 'down', 'restart', 'generate' or 'upgrade'
- 'up' - bring up the network with docker-compose up
- 'down' - clear the network with docker-compose down
- 'restart' - restart the network
- 'generate' - generate required certificates and genesis block
- 'upgrade' - upgrade the network from v1.0.x to v1.1
-c <channel name> - channel name to use (defaults to "mychannel")

22
BLOCKCHAIN Er. No.

-t <timeout> - CLI timeout duration in seconds (defaults to 10)


-d <delay> - delay duration in seconds (defaults to 3)
-f <docker-compose-file> - specify which docker-compose file use (defaults to docker-
compose-cli.yaml)
-s <dbtype> - the database backend to use: goleveldb (default) or couchdb
-l <language> - the chaincode language: golang (default), node or java
-i <imagetag> - the tag to be used to launch the network (defaults to "latest")
-v - verbose mode
byfn.sh -h (print this message)

Typically, one would first generate the required certificates and


genesis block, then bring up the network. e.g.:

byfn.sh generate -c mychannel


byfn.sh up -c mychannel -s couchdb
byfn.sh up -c mychannel -s couchdb -i 1.1.0-alpha
byfn.sh up -l node
byfn.sh down -c mychannel
byfn.sh upgrade -c mychannel

Taking all defaults:


byfn.sh generate
byfn.sh up
byfn.sh down
If you choose not to supply a channel name, then the script will use a default name
of mychannel . The CLI timeout parameter (specified with the -t flag) is an optional value; if you
choose not to set it, then the CLI will give up on query requests made after the default setting
of 10 seconds.

Generate Network Artifacts


Ready to give it a go? Okay then! Execute the following command:

./byfn.sh generate
You will see a brief description as to what will occur, along with a yes/no command line prompt.
Respond with a y or hit the return key to execute the described action.

Generating certs and genesis block for channel 'mychannel' with CLI timeout of '10' seconds
and CLI delay of '3' seconds
Continue? [Y/n] y
proceeding ...
/Users/xxx/dev/fabric-samples/bin/cryptogen

23
BLOCKCHAIN Er. No.

##########################################################
##### Generate certificates using cryptogen tool #########
##########################################################
org1.example.com
2017-06-12 21:01:37.334 EDT [bccsp] GetDefault -> WARN 001 Before using BCCSP, please call
InitFactories(). Falling back to bootBCCSP.
...

/Users/xxx/dev/fabric-samples/bin/configtxgen
##########################################################
######### Generating Orderer Genesis block ##############
##########################################################
2017-06-12 21:01:37.558 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
2017-06-12 21:01:37.562 EDT [msp] getMspConfig -> INFO 002 intermediate certs folder not
found at [/Users/xxx/dev/byfn/crypto-
config/ordererOrganizations/example.com/msp/intermediatecerts]. Skipping.: [stat
/Users/xxx/dev/byfn/crypto-
config/ordererOrganizations/example.com/msp/intermediatecerts: no such file or directory]
...
2017-06-12 21:01:37.588 EDT [common/configtx/tool] doOutputBlock -> INFO 00b Generating
genesis block
2017-06-12 21:01:37.590 EDT [common/configtx/tool] doOutputBlock -> INFO 00c Writing
genesis block

#################################################################
### Generating channel configuration transaction 'channel.tx' ###
#################################################################
2017-06-12 21:01:37.634 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
2017-06-12 21:01:37.644 EDT [common/configtx/tool] doOutputChannelCreateTx -> INFO 002
Generating new channel configtx
2017-06-12 21:01:37.645 EDT [common/configtx/tool] doOutputChannelCreateTx -> INFO 003
Writing new channel tx

#################################################################
####### Generating anchor peer update for Org1MSP ##########
#################################################################
2017-06-12 21:01:37.674 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
2017-06-12 21:01:37.678 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO
002 Generating anchor peer update
2017-06-12 21:01:37.679 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO
003 Writing anchor peer update

#################################################################

24
BLOCKCHAIN Er. No.

####### Generating anchor peer update for Org2MSP ##########


#################################################################
2017-06-12 21:01:37.700 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
2017-06-12 21:01:37.704 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO
002 Generating anchor peer update
2017-06-12 21:01:37.704 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO
003 Writing anchor peer update
This first step generates all of the certificates and keys for our various network entities,
the genesis block used to bootstrap the ordering service, and a collection of configuration
transactions required to configure a Channel.

Bring Up the Network


Next, you can bring the network up with one of the following commands:

./byfn.sh up
The above command will compile Golang chaincode images and spin up the corresponding
containers. Go is the default chaincode language, however there is also support
for Node.js and Java chaincode. If you’d like to run through this tutorial with node
chaincode, pass the following command instead:

# we use the -l flag to specify the chaincode language


# forgoing the -l flag will default to Golang

./byfn.sh up -l node
Once again, you will be prompted as to whether you wish to continue or abort. Respond
with a y or hit the return key:

Starting for channel 'mychannel' with CLI timeout of '10' seconds and CLI delay of '3'
seconds
Continue? [Y/n]
proceeding ...
Creating network "net_byfn" with the default driver
Creating peer0.org1.example.com
Creating peer1.org1.example.com
Creating peer0.org2.example.com
Creating orderer.example.com
Creating peer1.org2.example.com
Creating cli

25
BLOCKCHAIN Er. No.

____ _____ _ ____ _____


/ ___| |_ _| / \ | _ \ |_ _|
\___ \ | | / _ \ | |_) | | |
___) | | | / ___ \ | _ < | |
|____/ |_| /_/ \_\ |_| \_\ |_|

Channel name : mychannel


Creating channel...

The logs will continue from there. This will launch all of the containers, and then drive a
complete end-to-end application scenario. Upon successful completion, it should report
the following in your terminal window:

Query Result: 90
2017-05-16 17:08:15.158 UTC [main] main -> INFO 008 Exiting.....
===================== Query successful on peer1.org2 on channel 'mychannel'
=====================

===================== All GOOD, BYFN execution completed =====================

_____ _ _ ____
| ____| | \ | | | _ \
| _| | \| | | | | |
| |___ | |\ | | |_| |
|_____| |_| \_| |____/

Bring Down the Network

The following will kill your containers, remove the crypto material and four artifacts,
and delete the chaincode images from your Docker Registry:

./byfn.sh down
Once again, you will be prompted to continue, respond with a y or hit the return
key:

Stopping with channel 'mychannel' and CLI timeout of '10'


Continue? [Y/n] y
proceeding ...
WARNING: The CHANNEL_NAME variable is not set. Defaulting to a blank string.
WARNING: The TIMEOUT variable is not set. Defaulting to a blank string.
Removing network net_byfn
468aaa6201ed
...

26
BLOCKCHAIN Er. No.

Untagged: dev-peer1.org2.example.com-mycc-1.0:latest
Deleted: sha256:ed3230614e64e1c83e510c0c282e982d2b06d148b1c498bbdcc429e2b2531e91
...

Crypto Generator
We will use the cryptogen tool to generate the cryptographic material (x509 certs and
signing keys) for our various network entities. These certificates are representative of
identities, and they allow for sign/verify authentication to take place as our entities
communicate and transact.

How does it work?


Cryptogen consumes a file - crypto-config.yaml - that contains the network topology and
allows us to generate a set of certificates and keys for both the Organizations and the
components that belong to those Organizations. Each Organization is provisioned a unique
root certificate ( ca-cert ) that binds specific components (peers and orderers) to that Org.
By assigning each Organization a unique CA certificate, we are mimicking a typical network
where a participating Member would use its own Certificate Authority. Transactions and
communications within Hyperledger Fabric are signed by an entity’s private key
( keystore ), and then verified by means of a public key ( signcerts ).

You will notice a count variable within this file. We use this to specify the number of peers
per Organization; in our case there are two peers per Org. We won’t delve into the
minutiae of x.509 certificates and public key infrastructure right now. If you’re interested,
you can peruse these topics on your own time.

Before running the tool, let’s take a quick look at a snippet from the crypto-config.yaml .
Pay specific attention to the “Name”, “Domain” and “Specs” parameters under
the OrdererOrgs header:

OrdererOrgs:
#---------------------------------------------------------
# Orderer
# --------------------------------------------------------
- Name: Orderer
Domain: example.com
CA:
Country: US
Province: California

27
BLOCKCHAIN Er. No.

Locality: San Francisco


# OrganizationalUnit: Hyperledger Fabric
# StreetAddress: address for org # default nil
# PostalCode: postalCode for org # default nil
# ------------------------------------------------------
# "Specs" - See PeerOrgs below for complete description
# -----------------------------------------------------
Specs:
- Hostname: orderer
# -------------------------------------------------------
# "PeerOrgs" - Definition of organizations managing peer nodes
# ------------------------------------------------------
PeerOrgs:
# -----------------------------------------------------
# Org1
# ----------------------------------------------------
- Name: Org1
Domain: org1.example.com
EnableNodeOUs: true
The naming convention for a network entity is as follows - “{{.Hostname}}.{{.Domain}}”. So
using our ordering node as a reference point, we are left with an ordering node named -
orderer.example.com that is tied to an MSP ID of Orderer . This file contains extensive
documentation on the definitions and syntax. You can also refer to the Membership
Service Providers (MSP) documentation for a deeper dive on MSP.

After we run the cryptogen tool, the generated certificates and keys will be saved to a
folder titled crypto-config .

Configuration Transaction Generator


The configtxgen tool is used to create four configuration artifacts:

 orderer genesis block ,


 channel configuration transaction ,
 and two anchor peer transactions - one for each Peer Org.

Please see configtxgen for a complete description of this tool’s functionality.

28
BLOCKCHAIN Er. No.

The orderer block is the Genesis Block for the ordering service, and the channel
configuration transaction file is broadcast to the orderer at Channel creation time. The
anchor peer transactions, as the name might suggest, specify each Org’s Anchor Peer on
this channel.

How does it work?


Configtxgen consumes a file - configtx.yaml - that contains the definitions for the sample
network. There are three members - one Orderer Org ( OrdererOrg ) and two Peer Orgs
( Org1 & Org2 ) each managing and maintaining two peer nodes. This file also specifies a
consortium - SampleConsortium - consisting of our two Peer Orgs. Pay specific attention
to the “Profiles” section at the top of this file. You will notice that we have two unique
headers. One for the orderer genesis block - TwoOrgsOrdererGenesis - and one for our
channel - TwoOrgsChannel .

These headers are important, as we will pass them in as arguments when we create our
artifacts.

Create a Channel Configuration Transaction


Next, we need to create the channel transaction artifact. Be sure to
replace $CHANNEL_NAME or set CHANNEL_NAME as an environment variable that can
be used throughout these instructions:

# The channel.tx artifact contains the definitions for our sample channel

export CHANNEL_NAME=mychannel && ../bin/configtxgen -profile TwoOrgsChannel -


outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
You should see an output similar to the following in your terminal:

2017-10-26 19:24:05.324 EDT [common/tools/configtxgen] main -> INFO 001 Loading


configuration
2017-10-26 19:24:05.329 EDT [common/tools/configtxgen] doOutputChannelCreateTx ->
INFO 002 Generating new channel configtx
2017-10-26 19:24:05.329 EDT [common/tools/configtxgen] doOutputChannelCreateTx ->
INFO 003 Writing new channel tx
Next, we will define the anchor peer for Org1 on the channel that we are constructing.
Again, be sure to replace $CHANNEL_NAME or set the environment variable for the

29
BLOCKCHAIN Er. No.

following commands. The terminal output will mimic that of the channel transaction
artifact:

../bin/configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-


artifacts/Org1MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org1MSP
Now, we will define the anchor peer for Org2 on the same channel:

../bin/configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-


artifacts/Org2MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org2MSP

Start the network


We will leverage a script to spin up our network. The docker-compose file references the
images that we have previously downloaded, and bootstraps the orderer with our
previously generated genesis.block .

We want to go through the commands manually in order to expose the syntax and
functionality of each call.

First let’s start our network:

docker-compose -f docker-compose-cli.yaml up -d
If you want to see the realtime logs for your network, then do not supply the -d flag. If
you let the logs stream, then you will need to open a second terminal to execute the CLI
calls.

Environment variables
For the following CLI commands against peer0.org1.example.com to work, we need to
preface our commands with the four environment variables given below. These variables
for peer0.org1.example.com are baked into the CLI container, therefore we can operate
without passing them. HOWEVER, if you want to send calls to other peers or the orderer,
then you can provide these values accordingly by editing the docker-compose-
base.yaml before starting the container. Modify the following four environment variables
to use a different peer and org.

# Environment variables for PEER0

30
BLOCKCHAIN Er. No.

CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/cryp
to/peerOrganizations/org1.example.com/users/[email protected]/msp
CORE_PEER_ADDRESS=peer0.org1.example.com:7051
CORE_PEER_LOCALMSPID="Org1MSP"
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/c
rypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
Create & Join Channel
Recall that we created the channel configuration transaction using the configtxgen tool in
the Create a Channel Configuration Transaction section, above. You can repeat that process
to create additional channel configuration transactions, using the same or different
profiles in the configtx.yaml that you pass to the configtxgen tool. Then you can repeat
the process defined in this section to establish those other channels in your network.

We will enter the CLI container using the docker exec command:

docker exec -it cli bash


If successful you should see the following:

root@0d78bb69300d:/opt/gopath/src/github.com/hyperledger/fabric/peer#
If you do not want to run the CLI commands against the default
peer peer0.org1.example.com , replace the values of peer0 or org1 in the four
environment variables and run the commands:

# Environment variables for PEER0

export
CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/cryp
to/peerOrganizations/org1.example.com/users/[email protected]/msp
export CORE_PEER_ADDRESS=peer0.org1.example.com:7051
export CORE_PEER_LOCALMSPID="Org1MSP"
export
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/c
rypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
Next, we are going to pass in the generated channel configuration transaction artifact that
we created in the Create a Channel Configuration Transaction section (we called
it channel.tx ) to the orderer as part of the create channel request.

31
BLOCKCHAIN Er. No.

We specify our channel name with the -c flag and our channel configuration transaction
with the -f flag. In this case it is channel.tx , however you can mount your own
configuration transaction with a different name. Once again we will set
the CHANNEL_NAME environment variable within our CLI container so that we don’t have
to explicitly pass this argument. Channel names must be all lower case, less than 250
characters long and match the regular expression [a-z][a-z0-9.-]* .

export CHANNEL_NAME=mychannel

# the channel.tx file is mounted in the channel-artifacts directory within your CLI container
# as a result, we pass the full path for the file
# we also pass the path for the orderer ca-cert in order to verify the TLS handshake
# be sure to export or replace the $CHANNEL_NAME variable appropriately

peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-


artifacts/channel.tx

32
BLOCKCHAIN Er. No.

Practical: 5

Aim: Understanding the Docker Compose topology


The BYFN sample offers us two flavors of Docker Compose files, both of which are
extended from the docker-compose-base.yaml (located in the base folder). Our first
flavor, docker-compose-cli.yaml , provides us with a CLI container, along with an orderer,
four peers. We use this file for the entirety of the instructions on this page.

The second flavor, docker-compose-e2e.yaml , is constructed to run end-to-end tests using


the Node.js SDK. Aside from functioning with the SDK, its primary differentiation is that
there are containers for the fabric-ca servers. As a result, we are able to send REST calls to
the organizational CAs for user registration and enrollment.

If you want to use the docker-compose-e2e.yaml without first running the byfn.sh script,
then we will need to make four slight modifications. We need to point to the private keys
for our Organization’s CA’s. You can locate these values in your crypto -config folder. For
example, to locate the private key for Org1 we would follow this path - crypto-
config/peerOrganizations/org1.example.com/ca/ . The private key is a long hash value
followed by _sk . The path for Org2 would be - crypto-
config/peerOrganizations/org2.example.com/ca/ .

In the docker-compose-e2e.yaml update the FABRIC_CA_SERVER_TLS_KEYFILE variable for


ca0 and ca1. You also need to edit the path that is provided in the command to start the ca
server. You are providing the same private key twice for each CA container.

Using CouchDB
The state database can be switched from the default (goleveldb) to CouchDB. The same
chaincode functions are available with CouchDB, however, there is the added ability to
perform rich and complex queries against the state database data content contingent upon
the chaincode data being modeled as JSON.

To use CouchDB instead of the default database (goleveldb), follow the same procedures
outlined earlier for generating the artifacts, except when starting the network
pass docker-compose-couch.yaml as well:

33
BLOCKCHAIN Er. No.

docker-compose -f docker-compose-cli.yaml -f docker-compose-couch.yaml up -d


chaincode_example02 should now work using CouchDB underneath.

You can use chaincode_example02 chaincode against the CouchDB state database using
the steps outlined above, however in order to exercise the CouchDB query capabilities you
will need to use a chaincode that has data modeled as JSON, (e.g. marbles02). You can
locate the marbles02 chaincode in the fabric/examples/chaincode/go directory.

We will follow the same process to create and join the channel as outlined in the Create &
Join Channel section above. Once you have joined your peer(s) to the channel, use the
following steps to interact with the marbles02 chaincode:

 Install and instantiate the chaincode on peer0.org1.example.com:

# be sure to modify the $CHANNEL_NAME variable accordingly for the instantiate


command

peer chaincode install -n marbles -v 1.0 -p github.com/chaincode/marbles02/go


peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.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')"

 Create some marbles and move them around:

# be sure to modify the $CHANNEL_NAME variable accordingly

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile


/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com -cert.pem -C
$CHANNEL_NAME -n marbles -c '{"Args":["initMarble","marble1","blue","35","tom"]}'
peer chaincode invoke -o orderer.example.com:7050 --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com -cert.pem -C
$CHANNEL_NAME -n marbles -c '{"Args":["initMarble","marble2","red","50","tom"]}'
peer chaincode invoke -o orderer.example.com:7050 --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com -cert.pem -C
$CHANNEL_NAME -n marbles -c '{"Args":["initMarble","marble3","blue","70","tom"]}'

34
BLOCKCHAIN Er. No.

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile


/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C
$CHANNEL_NAME -n marbles -c '{"Args":["transferMarble","marble2","jerry"]}'
peer chaincode invoke -o orderer.example.com:7050 --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com -cert.pem -C
$CHANNEL_NAME -n marbles -c '{"Args":["transferMarblesBasedOnColor","blue","jerry"]}'
peer chaincode invoke -o orderer.example.com:7050 --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/examp
le.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com -cert.pem -C
$CHANNEL_NAME -n marbles -c '{"Args":["delete","marble1"]}'

 If you chose to map the CouchDB ports in docker-compose, you can now view the state
database through the CouchDB web interface (Fauxton) by opening a browser and
navigating to the following URL:

http://localhost:5984/_utils
You should see a database named mychannel (or your unique channel name) and the
documents inside it.

35
BLOCKCHAIN Er. No.

Que-1: What is the difference between Bitcoin blockchain and Ethereum blockchain?

36
BLOCKCHAIN Er. No.

Que.2 What are the properties of Blockchain?

37
BLOCKCHAIN Er. No.

Que.3 What is a ledger? Is Blockchain an incorruptible ledger?

38
BLOCKCHAIN Er. No.

Que.4 What are the benefits of Blockchain that you know?

39
BLOCKCHAIN Er. No.

Que: 5 What is cryptography? What is its role in Blockchain?

40
BLOCKCHAIN Er. No.

Que.6 What is a node in Ethereum? How can you connect with a node?

41
BLOCKCHAIN Er. No.

Que.7 Mention some of the popular Blockchain-based smart contracts.

42
BLOCKCHAIN Er. No.

Que. 8 How does bitcoin use blockchain?

43

You might also like