0% found this document useful (0 votes)
5 views68 pages

Ccs339 CBT Front 1233

The document outlines the course structure for the Cryptocurrency and Blockchain Technologies Laboratory (CCS339) at SRM TRP Engineering College, detailing course outcomes, objectives, and a list of experiments. It emphasizes understanding blockchain technology, implementing applications using Hyperledger Fabric and Ethereum, and addressing research challenges in the cryptocurrency domain. Additionally, it includes the vision and mission statements of the institute and department, along with program educational objectives and specific outcomes for graduates in Computer Science and Engineering.

Uploaded by

bornwithai0511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views68 pages

Ccs339 CBT Front 1233

The document outlines the course structure for the Cryptocurrency and Blockchain Technologies Laboratory (CCS339) at SRM TRP Engineering College, detailing course outcomes, objectives, and a list of experiments. It emphasizes understanding blockchain technology, implementing applications using Hyperledger Fabric and Ethereum, and addressing research challenges in the cryptocurrency domain. Additionally, it includes the vision and mission statements of the institute and department, along with program educational objectives and specific outcomes for graduates in Computer Science and Engineering.

Uploaded by

bornwithai0511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SRM TRP ENGINEERING COLLEGE

IRUNGALUR, TIRUCHIRAPALLI– 621 105

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN


TECHNOLOGIES LABORATORY

Name

Roll No.

Reg. No.
SRM TRP ENGINEERING COLLEGE
IRUNGALUR, TRICHY
COURSE OUTCOME

Course Code CCS339


Title Of The Course Cryptocurrency and Blockchain Laboratory
Regulations 2021
Pre Requisites Cryptography

Course Competency
Outcome
CCS339.1 Understand emerging abstract models for Blockchain Technology
CCS339.2 Identify major research challenges and technical gaps existing between theory
and practice in the crypto currency domain.
CCS339.3 It provides conceptual understanding of the function of Blockchain as a method
of securing distributed ledgers, how consensus on their contents is achieved, and
the new applications that they enable.
CCS339.4 Apply hyperledger Fabric and Ethereum platform to implement the Block chain
Application.

Course PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CCS339.1 3 3 2 2 1 - - - 1 - - 2
CCS339.2 3 3 3 3 1 - - - 2 - - 2
CCS339.3 3 3 3 3 2 - - - 3 - - 2
CCS339.4 3 2 3 2 3 - - - 3 - - 2
CCS339 3 2.75 2.75 2.5 1.75 - - - 2.25 - - 2

CO-PSO Matrices

Course code PSO1 PSO2


CCS339.1 3 1
CCS339.2 1 2
CCS339.3 2 3
CCS339.4 2 2
CCS339 2 2.2

1 Slight 2 Moderate 3 Substantial

3
SRM TRP ENGINEERING COLLEGE
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

Vision of the Institute

To carve the youth as dynamic, competent, valued and knowledgeable Technocrats through research,
innovation and entrepreneurial development for accomplishing the global expectations.

Mission of the Institute

M1: To inculcate academic excellence in engineering education to create talented professionals


M2: To promote research in basic sciences and applied engineering among faculty and students to fulfill
the societal expectations.
M3: To enhance the holistic development of students through meaningful interaction with industry and
academia.
M4: To foster the students on par with sustainable development goals thereby contributing to the process
of nation building
M5: To nurture and retain conducive lifelong learning environment towards professional excellence.

Vision of the Department

To be recognized as Centre of Excellence for innovation and research in computer science and engineering
through the futuristic technologies by developing technocrats with ethical values to serve the society at
global level.
Mission of the Department

M1: To develop quality and technically competent computer professionals through excellence in academics.
M2: To encourage the faculty and students towards research and development with advanced tools and
technologies.
M3: To enhance industry institute interaction to build a strong technical expertise among the students.
M4: To inculcate leadership skills with ethical behaviors and social consciousness within the students.
M5: To nurture professional empowerment among students through continuous Learning.

4
Program Educational Objectives (PEO's)

The graduate of Computer Science and Engineering will have

PEO1: Ability to analyze and get solutions in the field of Computer Science and Engineering through
application of fundamental knowledge of Mathematics, Science and Electronics (Preparation).
PEO2: Innovative ideas, methods and techniques thereby rendering expertise to the industrial and societal
needs in an effective manner and will be a competent computer/software engineer (Core Competency).
PEO3: Good and broad knowledge with interpersonal skills so as to comprehend, analyze, design and create
novel products and solutions for real-time applications (Breadth).
PEO4: Professional with ethical values to develop leadership, effective communication skills and teamwork
to excel in career. (Professionalism)
PEO5: Strive to learn continuously and update their knowledge in the specific fields of computer science
& engineering for the societal growth. (Learning environment).

Program Specific Outcome (PSO's)


The graduates of Bachelor of Engineering in Computer Science and Engineering Programme will be able
to:

PSO1: Use Data structures, Data management, Networking, System software, Data science with high
end programming skills to design and implement automation in various domains of emerging technologies.

PSO2: Apply engineering knowledge in project development with the end products and services in the field
of hardware and software platform to accomplish the industry expectations.

5
Program Outcomes (PO'S)

PO1: Engineering knowledge: Apply the basic knowledge of science, mathematics and engineering
fundamentals in the field of Computer Science and Engineering to solve complex engineering problems.
PO2: Problem analysis: Ability to use basic principles of mathematics, natural sciences, and engineering
sciences to Identify, formulate, review research literature and analyze Computer Science and engineering
problems.
PO3: Design/development of solutions: Ability to design solutions for complex Computer Science and
engineering problems and basic design system to meet the desired needs within realistic constraints such as
manufacturability, durability, reliability, sustainability and economy with appropriate consideration for the
public health, safety, cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Ability to execute the experimental activities using
research-based knowledge and methods including analyze, interpret the data and results with valid
conclusion.
PO5: Modern tool usage: Ability to use state of the art of techniques, skills and modern engineering tools
necessary for engineering practice to satisfy the needs of the society with an understanding of the limitations.
PO6: The Engineer and Society: Ability to apply reasoning informed by the contextual knowledge to assess
the impact of Computer Science and engineering solutions in legal, health, cultural, safety and societal
context and the consequent responsibilities relevant to the professional engineering practice.
PO7: Environment and sustainability: Ability to understand the professional responsibility and
accountability to demonstrate the need for sustainable development globally in Computer Science domain
with consideration of environmental effect.
PO8: Ethics: Ability to understand and apply ethical principles and commitment to address the professional
ethical responsibilities of an engineer.
PO9: Individual and team work: Ability to function efficiently as an individual or as a group member or
leader in a team in multidisciplinary environment.
PO10: Communication: Ability to communicate, comprehend and present effectively with engineering
community and the society at large on complex engineering activities by receiving clear instructions for
preparing effective reports, design documentation and presentations.
PO11: Project management and finance: Ability to acquire and demonstrate the knowledge of contemporary
issues related to finance and managerial skills in one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12: Life-long learning: Ability to recognize and adapt to the emerging field of application in engineering
and technology by developing self-confidence for lifelong learning process.

6
CCS339 CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES LT P C
2 0 2 3

COURSE OBJECTIVES:
• To understand the basics of Blockchain
• To learn Different protocols and consensus algorithms in Blockchain
• To learn the Blockchain implementation frameworks
• To understand the Blockchain Applications
• To experiment the Hyperledger Fabric, Ethereum networks

LIST OF EXPERIMENTS:

1. Install and understand Docker container, [Link], Java and Hyperledger Fabric, Ethereum
and perform necessary software installation on local machine/create instance on cloud to run.

2. Create and deploy a blockchain network using Hyperledger Fabric SDK for Java Set up and initialize the
channel, install and instantiate chain code, and perform invoke and query on your blockchain network.

3. Interact with a blockchain network. Execute transactions and requests against a blockchain
network by creating an app to test the network and its rules.

4. Deploy an asset-transfer app using blockchain. Learn app development within a Hyperledger Fabric
network.

5. Use blockchain to track fitness club rewards. Build a web app that uses Hyperledger Fabric
to track and trace member rewards.

6. Car auction network: A Hello World example with Hyperledger Fabric Node SDK and IBM Blockchain
Starter Plan. Use Hyperledger Fabric to invoke chain code while storing results and data in the starter
Plan.

TOTAL:30 PERIODS
COURSE OUTCOMES:
At th end of this course, the students will be able to:

CO1: Understand emerging abstract models for Blockchain Technology


CO2: Identify major research challenges and technical gaps existing between theory and practice in the
crypto currency domain.
CO3: It provides conceptual understanding of the function of Blockchain as a method of securing
distributed ledgers, how consensus on their contents is achieved, and the new applications that they
enable.
CO4: Apply hyperledger Fabric and Ethereum platform to implement the Block chain Application.

7
INDEX

SI:No Experiment Page No Marks Signature


1 Install and understand Docker container, [Link], Java
and Hyperledger Fabric, Ethereum and perform
necessary software installation on local machine/create
instance on cloud to run
2 Create and deploy a blockchain network using
Hyperledger Fabric SDK for Java Set up and initialize
the channel, install and instantiate chain code, and
perform invoke and query on your blockchain network.
3 Interact with a blockchain network. Execute transactions
and requests against a blockchain network by creating
an app to test the network and its rules.

4 Deploy an asset-transfer app using blockchain. Learn


app development within a Hyperledger Fabric network
5 Use blockchain to track fitness club rewards. Build a
web app that uses Hyperledger Fabric to track and trace
member rewards
6 Car auction network: A Hello World example with
Hyperledger Fabric Node SDK and IBM Blockchain
Starter Plan. Use Hyperledger Fabric to invoke chain
code while storing results and data in the starter Plan.

CONTENT BEYOND SYLLABUS


7 Implementing a Decentralized Exchange (DEX) on
Ethereum.

8 Creating a Blockchain-based Voting System.

8
Ex:No:1 Installation of Docker Container,[Link] and HyperledgerFabric and Etherum
Network.

Aim:
To Install and understand Docker container, [Link], Java and Hyperledger Fabric, Ethereum and
perform necessary software installation on local machine/create instance on cloud to run.

Docker:

Docker is a containerization platform which is used for packaging an application and its dependencies
together within a Docker container. This ensures the effortless and smooth functioning of our application
irrespective of the changes in the environment.

Talking about Docker Container it is nothing but a standardized unit that is used to deploy a particular
application or environment and can be built dynamically. We can have any container such as Ubuntu,
CentOS, etc. based on your requirement with respect to Operating Systems.

Dockerfile

A Dockerfile is basically a text document that contains the list of commands which can be invoked by a
user using the command line in order to assemble an image. Thus, by reading instructions from this
Dockerfile, Docker automatically builds images.

For executing multiple command line instructions successively you can create an automated build using
the following command:

docker build

Docker Image

A Docker Image can be considered something similar to a template which is typically used to build Docker
Containers. In other words, these read-only templates are nothing but the building blocks of a Docker
Container. In order to execute an image and build a container you need to use the following command:

docker run

The Docker Images that you create using this command are stored within the Docker Registry. It can be
either a user’s local repository or a public repository like a Docker Hub which allows multiple users to
collaborate in building an application.

Docker Container

A Docker Container is the running instance of a Docker Image. These containers hold the complete package
that is required to execute the application. So, these are basically ready to use applications which are created
from Docker Images that is the ultimate utility of Docker.

9
I guess, now you are quite familiar with Docker. If you want to learn more about Docker you can refer to
our other blogs on Docker.

In order to Dockerize a [Link] application, you need to go through the following steps:

Create [Link] Application

Create a Docker file

Build Docker Image

Execute

Create [Link] Application

Building REST API using [Link]


Here, we will be creating a simple CRUD REST application for Library Management using [Link] and
[Link]. To build this application, you will need to install the following:

1. [Link]
2. [Link]
3. Joi
4. nodemon (Node Monitor)

First, you need to create your project directory. Next, open the command prompt and navigate to your
project directory. Once there, you need to call npm using the below command:

1. npm init

When you hit enter, [Link] will ask you to enter some details to build the .json file such as:

Next, we will be installing [Link] using the below command:

npm i express

10
Finally, I will be installing a node monitoring package called nodemon. It keeps a watch on all the files
with any type of extension present in this folder. Also, with nodemon on the watch, you don’t have to
restart the [Link] server each time any changes are made. nodemon will implicitly detect the changes and
restart the server for you.

npm i -g nodemon

[Link]

{
"name":
"samplerestapi",
"version": "1.0.0",
"description": "Edureka REST API with [Link]",
"main": "[Link]",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Edureka",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"joi": "^13.1.0"
}
}

Create a Docker file

Docker file

1 FROM node:9-slim
2
3 # WORKDIR specifies the application directory
4
5 WORKDIR /app
6
7 # Copying [Link] file to the app directory
8 COPY [Link] /app
9
10 # Installing npm for DOCKER
11 RUN npm install
12
13
14 # Copying rest of the application to app directory
15 COPY . /app
16
# Starting the application using npm start
CMD ["npm","start"]

11
Build Docker Image

Building a Docker image is rather easy and can be done using a simple command. Below I have written
down the command that you need to type in your terminal and execute it:

1 docker build -t <docker-image-name> <file path>

If we are getting an output something similar to the above screenshot, then it means that your application
is working fine and the docker image has been successfully created. In the next section of this [Link]
Docker article, I will show you how to execute this Docker Image.

Executing the Docker Image

Since you have successfully created your Docker image, now you can run one or more Docker containers
on this image using the below-given command:

1 docker run it -d -p <HOST PORT>:<DOCKER PORT> <docker-image-name>

This command will start your docker container based on your Docker image and expose it on the specified
port in your machine. In the above command -d flag indicates that you want to execute your Docker
container in a detached mode. In other words, this will enable your Docker container to run in the

12
background of the host machine. While the -p flag specifies which host port will be connected to the docker
port.

To check whether your application has been successfully Dockerized or not, you can try launching it on
the port you have specified for the host in the above command.

If We want to see the list of images currently running in your system, We can use the below command:

1 docker ps

Installing Fabric-samples Repository


To start out with fabric samples install the Fabric-samples bash script:
url -sSLO [Link] &&
chmod +x [Link]
Then you can pull docker containers by running one of these commands:
./[Link] docker samples
./[Link] d s
To install binaries for Fabric samples you can use the command below:
./[Link] binary

Building First Network

Step 1: Navigate through the Fabric-samples folder and then through the Test network folder where
you can find script files using these we can run our network. The test network is provided for learning
about Fabric by running nodes on your local machine. Developers can use the network to test their
smart contracts and applications.
cd fabric-samples/test-network

13
Step 2: From inside this directory, you can directly run ./[Link] script file through which we run
the Test Network. By default, we would be running ./[Link] down command to remove any
previous network containers or artifacts that still exist. This is to ensure that there are no conflicts
when we run a new network.
./[Link] down

Step 3: Now you can bring up a network using the following command. This command creates a fabric
network that consists of two peer nodes and one ordering node. No channel is created when you run
./[Link] up

./[Link] up

If the above command completes successfully, you will see the logs of the nodes being created below
picture:

Etherum Network Installation

The environment we are going to set up has three main tools as follows.

1. The Go Ethereum Implementation or GETH

2. TestRPC that we are going to test put Smart Contracts

3. Truffle Build framework

14
Installing Geth

Geth , also known as Go Ethereum is a command line interface which allows us to run a full Ethereum
node. Geth is implemented in GO and it will allow us to mine blocks , generate ether, deploy and interact
with smart contracts , transfer funds , block history inspection and create accounts etc..

Geth can be used to get connected to the public Ethereum network as well apart from to create your own
private network for development purposes.

Step 1:

After that we need to add the Ethereum repository as follows.

Then , update the repositories.

Then install the Ethereum.

We can check the installation by using the $ geth version command as follows.

15
Installing Test RPC

Test RPC is an Ethereum node emulator implemented in NodeJS. The purpose of this Test RPC is to
easily start the Ethereum node for test and development purposes.

To install the Test RPC ;

Installing Truffle

Truffle is a build framework and it takes care of managing your Contract artifacts so you don’t have to.
Includes support for custom deployments, library linking and complex Ethereum applications.

To install ;

16
Check the installation as follows.

Setting up a Private Ethereum network

First of all create a folder to host the database and private accounts that we are going to create. In my
case it is ~/ETH/pvt.

First of all we need to place the genesis block in our root (~/ETH/pvt). The file should be defined as
[Link]

17
To initialize the chain instance , we need to use following geth command.

datadir param specifies where we should save our network’s data. After initializing this, the root folder
should contain something like following.

18
We can use the following geth command for this purpose.

To list all created account lists you can use the account list command as

As the next step, we need to specify following [Link] file. This script will start the network with
given params.

[Link]

As the next step we need to log into the Geth console using the attach command as follows.

19
This will start the Geth console. To list all accounts we can use following command.

Account Creation output:

Result:

Thus the Installation of Docker Container,[Link] and HyperledgerFabric and Etherum Network are
executed successfully.

20
Ex:No: 2 Create and deploy a blockchain network using Hyperledger Fabric SDK for Java

Aim:

To create and deploy a blockchain network using Hyperledger Fabric SDK for Java

Procedure:
Set up and initialize the channel, install and instantiate chaincode, and perform invoke and query on your
blockchain network
Blockchain is a shared, immutable ledger for recording the history of transactions. The Linux Foundation’s
Hyperledger Fabric, the software implementation of blockchain IBM is committed to, is a permissioned
network. Hyperledger Fabric is a platform for distributed ledger solutions underpinned by a modular
architecture delivering high degrees of confidentiality, resiliency, flexibility and scalability.

In a Blockchain solution, the Blockchain network works as a back-end with an application front-end to
communicate with the network using a SDK. To set up the communication between front-end and back-
end, Hyperledger Fabric community offers a number of SDKs for a wide variety of programming languages
like the NodeJS SDK and Java SDK. This code pattern explains the methodology to create, deploy and test
the blockchain network using Hyperledger Fabric SDK Java.

It would be helpful for the Java developers, who started to look into Hyperledger Fabric platform and
would like to use Fabric SDK Java for their projects. The SDK helps facilitate Java applications to manage
the lifecycle of Hyperledger channels and user chaincode. The SDK also provides a means to execute user
chaincode, query blocks and transactions on the channel, and monitor events on the channel. This code
pattern will help to get the process started to build a Hyperledger Fabric v1.4.1 Java application.

When the reader has completed this pattern, they will understand how to create, deploy and test a
blockchain network using Hyperledger Fabric SDK Java. This pattern will provision a Hyperledger Fabric
1.4.1 network consisting of two organizations, each maintaining two peer node, two certificate authorities
(ca) for each organization and a solo ordering service. The following aspects will be demonstrated in this
code pattern:

 Create and initialize channel


 Install and instantiate chain code
 Register and enroll the users
 Perform invoke and query on the blockchain network.

Steps

1. Setup the Blockchain Network

Clone this repo using the following command.

$ git clone [Link]

To build the blockchain network, the first step is to generate artifacts for peers and channels using
cryptogen and configtx. The utilities used and steps to generate artifacts are explained here. In this
pattern all required artifacts for the peers and channel of the network are already generated and provided
to use as-is. Artifacts can be located at:

network_resources/crypto-config
21
network_resources/config

The automated scripts to build the network are provided under network directory. The network/docker-
[Link] file defines the blockchain network topology.

cd network

chmod +x [Link]

./[Link]

To stop the running network, run the following script.

cd network

chmod +x [Link]

./[Link]

To delete the network completely, following script need to execute.

cd network

chmod +x [Link]

./[Link]

2. Build the client based on Fabric Java SDK

The previous step creates all required docker images with the appropriate configuration.

Java Client

The java client sources are present in the folder java of the repo.

Check your environment before executing the next step. Make sure, you are able to run mvn commands
properly.

If mvn commands fails, please refer to Pre-requisites to install maven.

To work with the deployed network using Hyperledger Fabric SDK java 1.4.1, perform the following
steps.

Open a command terminal and navigate to the java directory in the repo. Run the command mvn install.

cd ../java

mvn install

A jar file [Link] is built and can be found


under the target folder. This jar can be renamed to [Link] to keep the name short.

cd target

cp [Link] [Link]
22
Copy this built jar into network_resources directory. This is required as the java code can access required
artifacts during execution.

cp [Link] ../../network_resources

3. Create and Initialize the channel

In this code pattern, we create one channel mychannel which is joined by all four peers. The java source
code can be seen at src/main/java/org/example/network/[Link]. To create and initialize the
channel, run the following command.

cd ../../network_resources

java -cp [Link] [Link]

Output:

INFO: Deleting - users

Apr 20, 2018 [Link] PM [Link] main

INFO: Channel created mychannel

Apr 20, 2018 [Link] PM [Link] main

INFO: [Link] at grpc://localhost:7051

Apr 20, 2018 [Link] PM [Link] main

INFO: [Link] at grpc://localhost:7056

Apr 20, 2018 [Link] PM [Link] main

INFO: [Link] at grpc://localhost:8051

Apr 20, 2018 [Link] PM [Link] main

INFO: [Link] at grpc://localhost:8056

4. Deploy and Instantiate the chaincode

This code pattern uses a sample chaincode fabcar to demo the usage of Hyperledger Fabric SDK Java
APIs. To deploy and instantiate the chaincode, execute the following command.

java -cp [Link] [Link]

Output:

INFO: Deploying chaincode fabcar using Fabric client Org1MSP admin

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code deployment SUCCESS

Apr 23, 2018 [Link] AM [Link] main


23
INFO: fabcar- Chain code deployment SUCCESS

Apr 23, 2018 [Link] AM [Link] deployChainCode

INFO: Deploying chaincode fabcar using Fabric client Org2MSP admin

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code deployment SUCCESS

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code deployment SUCCESS

Apr 23, 2018 [Link] AM [Link] instantiateChainCode

INFO: Instantiate proposal request fabcar on channel mychannel with Fabric client Org2MSP admin

Apr 23, 2018 [Link] AM [Link] instantiateChainCode

INFO: Instantiating Chaincode ID fabcar on channel mychannel

Apr 23, 2018 [Link] AM [Link] instantiateChainCode

INFO: Chaincode fabcar on channel mychannel instantiation


[Link]@723ca036[Not completed]

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code instantiation SUCCESS

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code instantiation SUCCESS

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code instantiation SUCCESS

Apr 23, 2018 [Link] AM [Link] main

INFO: fabcar- Chain code instantiation SUCCESS

Note: The chaincode [Link] was taken from the fabric samples available at -
[Link]

5. Register and enroll users

A new user can be registered and enrolled to an MSP. Execute the below command to register a new user
and enroll to Org1MSP.

java -cp [Link] [Link]

Output:

24
INFO: Deleting - users

log4j:WARN No appenders could be found for logger ([Link]).

log4j:WARN Please initialize the log4j system properly.

log4j:WARN See [Link] for more info.

Apr 23, 2018 [Link] AM [Link] enrollAdminUser

INFO: CA -[Link] Enrolled Admin.

Apr 23, 2018 [Link] AM [Link] registerUser

INFO: CA -[Link] Registered User - user1524459395783

Apr 23, 2018 [Link] AM [Link] enrollUser

INFO: CA -[Link] Enrolled User - user1524459395783

6. Perform Invoke and Query on network

Blockchain network has been setup completely and is ready to use. Now we can test the network by
performing invoke and query on the network. The fabcar chaincode allows us to create a new asset which
is a car. For test purpose, invoke operation is performed to create a new asset in the network and query
operation is performed to list the asset of the network. Perform the following steps to check the same.

java -cp [Link] [Link]

Output:

INFO: CA -[Link] Enrolled Admin.

Apr 20, 2018 [Link] PM [Link] sendTransactionProposal

INFO: Sending transaction proposal on channel mychannel

Apr 20, 2018 [Link] PM [Link] sendTransactionProposal

INFO: Transaction proposal on channel mychannel OK SUCCESS with transaction

id:a298b9e27bdb0b6ca18b19f9c78a5371fb4d9b8dd199927baf37379537ca0d0f

Apr 20, 2018 [Link] PM [Link] sendTransactionProposal

INFO:

Apr 20, 2018 [Link] PM [Link] sendTransactionProposal

INFO: [Link]@22f31dec[Not completed]

Apr 20, 2018 [Link] PM [Link] main

INFO: Invoked createCar on fabcar. Status - SUCCESS

25
java -cp [Link] [Link]

Output:

Apr 20, 2018 [Link] PM [Link] enrollAdminUser

INFO: CA -[Link] Enrolled Admin.

Apr 20, 2018 [Link] PM [Link] main

INFO: Querying for all cars ...

Apr 20, 2018 [Link] PM [Link] queryByChainCode

INFO: Querying queryAllCars on channel mychannel

Apr 20, 2018 [Link] PM [Link] main

INFO: [{"Key":"CAR1",
"Record":{"make":"Chevy","model":"Volt","colour":"Red","owner":"Nick"}}]

Apr 20, 2018 [Link] PM [Link] main

INFO: Querying for a car - CAR1

Apr 20, 2018 [Link] PM [Link] queryByChainCode

INFO: Querying queryCar on channel mychannel

Apr 20, 2018 [Link] PM [Link] main

INFO: {"make":"Chevy","model":"Volt","colour":"Red","owner":"Nick"}

Program:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

26
import [Link];

class Sample {

public static void main(String[] args) throws IOException {

// Load an existing wallet holding identities used to access the network.

Path walletDirectory = [Link]("wallet");

Wallet wallet = [Link](walletDirectory);

// Path to a common connection profile describing the network.

Path networkConfigFile = [Link]("[Link]");

// Configure the gateway connection used to access the network.

[Link] builder = [Link]()

.identity(wallet, "user1")

.networkConfig(networkConfigFile);

// Create a gateway connection

try (Gateway gateway = [Link]()) {

// Obtain a smart contract deployed on the network.

Network network = [Link]("mychannel");

Contract contract = [Link]("fabcar");

// Submit transactions that store state to the ledger.

byte[] createCarResult = [Link]("createCar")

.submit("CAR10", "VW", "Polo", "Grey", "Mary");

[Link](new String(createCarResult, StandardCharsets.UTF_8));

27
// Evaluate transactions that query state from the ledger.

byte[] queryAllCarsResult = [Link]("queryAllCars");

[Link](new String(queryAllCarsResult, StandardCharsets.UTF_8));

} catch (ContractException | TimeoutException | InterruptedException e) {

[Link]();

Result:

Thus the creation and deploy a blockchain network using Hyperledger Fabric SDK for Java are
executed successfully.

28
Ex:No: 3 Interact with a blockchain network and execute transactions and requests against a
blockchain network

Aim:

To Interact with a blockchain network and execute transactions and requests against a blockchain
network by creating an app to test the network and its rules.

Procedure:

Installing the prerequisites, tools, and a Fabric runtime

1. Installing Prereqs

Now that we have a high level understanding of what is needed to build these networks, we can start
developing. Before we do that, though, we need to make sure we have the prerequisites installed on our
system. An updated list can be found here.

 Docker Engine and Docker Compose

 Nodejs and NPM

 Git

 Python 2.7.x
yperledger has a bash script available to make this process extremely easy. Run the following commands
in your terminal:

2. Installing tools to ease development

Run the following commands in your Terminal, and make sure you’re NOT using sudo when running npm
commands.

3. Installing a local Hyperledger Fabric runtime

Let’s go through the commands and see what they mean. First, we make and enter a new directory. Then,
we download and extract the tools required to install Hyperledger Fabric.

We then specify the version of Fabric we want, at the time of writing we need 1.2, hence hlfv12. Then, we
download the fabric runtime and start it up.

29
Also, if you type ls you’ll see this:

Basically what we did here was just download and start a local Fabric network. We can stop is using
./[Link] if we want to. At the end of our development session, we should run ./[Link]

Creating and deploying our business network


1. Generating a business network

Open terminal in a directory of choice and type yo hyperledger-composer

you’ll be greeted with something similar to the above. Select Business Network and name it cards-trading-
network as shown below:

30
2. Modeling our business network

The first and most important step towards making a business network is identifying the resources present.
We have four resource types in the modeling language:

Assets

Participants

Transactions

Events

For our cards-trading-network , we will define an asset typeTradingCard , a participant type Trader , a
transaction TradeCard and an event TradeNotification.

Go ahead and open the generated files in a code editor of choice. Open up [Link] which is
the modeling file. Delete all the code present in it as we’re gonna rewrite it (except for the namespace
declaration).

This contains the specification for our asset TradingCard . All assets and participants need to have a unique
identifier for them which we specify in the code, and in our case, it’s cardId

Also, our asset has a GameType cardType property which is based off the enumerator defined below.
Enums are used to specify a type which can have up to N possible values, but nothing else. In our example,
no TradingCard can have a cardType other than Baseball, Football, or Cricket.

Now, to specify our Trader participant resource type, add the following code in the modeling file

This is relatively simpler and quite easy to understand. We have a participant type Trader and they’re
uniquely identified by their traderIds.

31
Now, we need to add a reference to our TradingCards to have a reference pointing to their owner so we
know who the card belongs to. To do this, add the following line inside your TradingCard asset:

--> Trader owner

so that the code looks like this:

This is the first time we’ve used --&gt; and you must be wondering what this is. This is a relationship
pointer. o and --> are how we differentiate between a resource’s own properties vs a relationship to another
resource type. Since the owner is a Trader which is a participant in the network, we want a reference to
that Trader directly, and that’s exactly what --> does.

Finally, go ahead and add this code in the modeling file which specifies what parameters will be required
to make a transaction and emitting an event.

3. Adding logic for our transactions

To add logic behind the TradeCard function, we need a Javascript logic file. Create a new directory named
lib in your project’s folder and create a new file named [Link] with the following code:

4. Defining permissions and access rules

Add a new rule in [Link] to give participants access to their resources. In production, you would
want to be more strict with these access rules. You can read more about them here.

5. Generating a Business Network Archive (BNA)

Now that all the coding is done, it’s time to make an archive file for our business network so we can deploy
it on our local Fabric runtime. To do this, open Terminal in your project directory and type this:

composer archive create --sourceType dir –sourceName

This command tells Hyperledger Composer we want to build a BNA from a directory which is our current
root folder.

32
6. Install and Deploy the BNA file

We can install and deploy the network to our local Fabric runtime using the PeerAdmin user. To install the
business network, type

composer network install --archiveFile cards-trading-network@[Link] --card PeerAdmin@hlfv1

To deploy the business network, type

composer network start --networkName cards-trading-network --networkVersion 0.0.1 --networkAdmin


admin --networkAdminEnrollSecret adminpw --card PeerAdmin@hlfv1 --file [Link]

33
The networkName and networkVersion must be the same as specified in your [Link] otherwise it
won’t work.

--file takes the name of the file to be created for THIS network’s business card. This card then needs to be
imported to be usable by typing

composer card import --file [Link]

We can now confirm that our network is up and running by typing

composer network ping --card admin@cards-trading-network


--card this time takes the admin card of the network we want to ping.
If everything went well, you should see something similar to this:

Testing our Business Network


Now that our network is up and running on Fabric, we can start Composer Playground to interact with it.
To do this, type composer-playground in Terminal and open up [Link] in your browser and
you should see something similar to this:

34
Press Connect Now for admin@cards-trading-network and you’ll be greeted with this screen:

The Define page is where we can make changes to our code, deploy those changes to upgrade our network,
and export business network archives.
Head over to the Test page from the top menu, and you’ll see this:

35
Select Trader from Participants, click on Create New Participant near the top right, and make a
new Trader similar to this:

Go ahead and make a couple more Traders. Here are what my three traders look like with the names
Haardik, John, and Tyrone.

36
Click on TradingCard from the left menu and press Create New Asset. Notice how the owner field is
particularly interesting here, looking something like this:

Go ahead and finish making a TradingCard something similar to this:

Notice how the owner fields points to Trader#1 aka Haardik for me. Go ahead and make a couple more
cards, and enable a couple to have forTrade set to true.

37
Notice how my Card#2 has forTrade == true?
Now for the fun stuff, let’s try trading cards :D

Click on Submit Transaction in the left and make card point to TradingCard#2 and newOwner point
to Trader#3 like this:

Generating a REST API Server

38
Doing transactions with Playground is nice, but not optimal. We have to make client-side software for
users to provide them a seamless experience, they don’t even have to necessarily know about the underlying
blockchain technology. To do so, we need a better way of interacting with our business network. Thankfully,
we have the composer-rest-server module to help us with just that.
Type composer-rest-server in your terminal, specify admin@cards-trading-network , select never use
namespaces, and continue with the default options for the rest as follows:

Open [Link] and you’ll be greeted with a documented version of an automatically


generated REST API :D

Generating an Angular application which uses the REST API

To create the Angular web application, type yo hyperledger-composer in your Terminal, select Angular,
choose to connect to an existing business network with the card admin@cards-trading-network, and
connect to an existing REST API as well.

This will go on to run npm install , give it a minute, and once it’s all done you’ll be able to load
up [Link] and be greeted with a page similar to this:
Edit: Newer versions of the software may require you to run npm install yourself and then run npm start

39
You can now play with your network from this application directly, which communicates with the network
through the REST server running on port 3000.

Congratulations! You just set up your first blockchain business network using Hyperledger Fabric and
Hyperledger Composer :D

You can add more features to the cards trading network, setting prices on the cards and giving a balance to
all Trader. You can also have more transactions which allow the Traders to toggle the value of forTrade .
You can integrate this with non blockchain applications and allow users to buy new cards which get added
to their account, which they can then further trade on the network.

The possibilities are endless, what will you make of them? Let me know in the comments :D

1. Get a modal to open when you press the button


The first change we need to make is have the button open the modal window. The code already contains
the required modal window, the button is just missing the (click) and data-target attributes.
To resolve this, open up /cards-trading-angular-app/src/app/TradeCard/[Link]
The file name can vary based on your transaction name. If you have multiple transactions in your business
network, you’ll have to do this change across all the transaction resource type HTML files.
Scroll down till the very end and you shall see a <button> tag. Go ahead and add these two attributes to
that tag:
(click)="resetForm();" data-target="#addTransactionModal"
so the line looks like this:

<button type=”button” class=”btn btn-primary invokeTransactionBtn” data-toggle=”modal”


(click)=”resetForm();” data-target=”#addTransactionModal”>Invoke<;/button>
The (click) attribute calls resetForm(); which sets all the input fields to empty, and data-target specifies the
modal window to be opened upon click.
Save the file, open your browser, and try pressing the invoke button. It should open this modal:

40
2. Removing unnecessary fields

Just getting the modal to open isn’t enough. We can see it requests transactionId and timestamp from us
even though we didn’t add those fields in our modeling file. Our network stores these values which are
intrinsic to all transactions. So, it should be able to figure out these values on it’s own. And as it turns out,
it actually does. These are spare fields and we can just comment them out, the REST API will handle the
rest for us.
In the same file, scroll up to find the input fields and comment out the divs responsible for those input
fields inside addTransactionModal

Save your file, open your browser, and press Invoke. You should see this:

41
You can now create transactions here by passing data in these fields. Since card and newOwner are
relationships to other resources, we can do a transaction like this:

Press Confirm, go back to the Assets page, and you will see that TradingCard#2 now belongs to Trader#1:

Result:

Thus the Interact with a blockchain network and execute transactions by creating app are executed
successfully.

42
Ex:No: 4 Deploy an asset-transfer app using blockchain

Aim: To Deploy an asset-transfer app using blockchain. Learn app development within a
Hyperledger Fabric network.
Procedure:
The private asset transfer smart contract is deployed with an endorsement policy that requires an
endorsement from any channel member. This allows any organization to create an asset that they own
without requiring an endorsement from other channel members. The creation of the asset is the only
transaction that uses the chaincode level endorsement policy. Transactions that update or transfer existing
assets will be governed by state based endorsement policies or the endorsement policies of private data
collections.

About Asset Transfer

This Asset Transfer (basic) sample demonstrates how to initialize a ledger with assets, query those assets,
create a new asset, query a single asset based on an asset ID, update an existing asset, and transfer an
asset to a new owner. It involves the following two components:

1. Sample application: which makes calls to the blockchain network, invoking transactions implemented
in the chaincode (smart contract). The application is located in the following fabric-samples directory:

2. Smart contract itself, implementing the transactions that involve interactions with the ledger. The smart
contract (chaincode) is located in the following fabric-samples directory

3. Explore a sample smart contract. We’ll inspect the sample assetTransfer (javascript) smart contract to
learn about the transactions within it, and how they are used by an application to query and update the
ledger.

3. Interact with the smart contract with a sample application. Our application will use the asset Transfer
smart contract to create, query, and update assets on the ledger. We’ll get into the code of the app and the
transactions they create, including initializing the ledger with assets, querying an asset, querying a range
of assets, creating a new asset, and transferring an asset to a new owner.

Install the Hyperledger Fabric SDK for [Link].

If you are on Windows, you can install the windows-build-tools with npm which installs all
required compilers and tooling by running the following command

43
Set up the blockchain network

Navigate to the test-network subdirectory within your local clone of the fabric-
samples repository.

If you already have a test network running, bring it down to ensure the environment is clean.

Launch the Fabric test network using the [Link] shell script.

Next, let’s deploy the chaincode by calling the ./[Link] script with the chaincode name and
language options.

If the chaincode is successfully deployed, the end of the output in your terminal should look similar
to below:

Sample application

Next, let’s prepare the sample Asset Transfer Javascript application that will be used to interact with
the deployed chaincode.

JavaScript Application
Open a new terminal, and navigate to the application-javascript folder.

44
This directory contains sample programs that were developed using the Fabric SDK for [Link]. Run
the following command to install the application dependencies. It may take up to a minute to
complete:

This process is installing the key application dependencies defined in the application’s [Link]. The
most important of which is the fabric-network [Link] module; it enables an application to use identities,
wallets, and gateways to connect to channels, submit transactions, and wait for notifications. This tutorial
also uses the fabric-ca-client module to enroll users with their respective certificate authorities,
generating a valid identity which is then used by the fabric-network module to interact with the
blockchain network.

Once npm install completes, everything is in place to run the application. Let’s take a look at the sample
JavaScript application files we will be using in this tutorial. Run the following command to list the files
in this directory:

Let’s run the application and then step through each of the interactions with the smart contract
functions. From the asset-transfer-basic/application-javascript directory, run the following
command:

In the sample application code below, you will see that after getting reference to the common
connection profile path, making sure the connection profile exists, and specifying where to create the
wallet, enrollAdmin() is executed and the admin credentials are generated from the Certificate
Authority.

async function main() {


try {
45
const ccp = buildCCP();

// build an instance of the fabric ca services client based on


// the information in the network configuration
const caClient = buildCAClient(FabricCAServices, ccp);

// setup the wallet to hold the credentials of the application user


const wallet = await buildWallet(Wallets, walletPath);

// in a real application this would be done on an administrative flow, and only once
await enrollAdmin(caClient, wallet);

This command stores the CA administrator’s credentials in the wallet directory. You can find
administrator’s certificate and private key in the wallet/[Link] file

Because the admin registration step is bootstrapped when the Certificate Authority is started, we only
need to enroll the admin.

Second, the application registers and enrolls an application user

Now that we have the administrator’s credentials in a wallet, the application uses the admin user to
register and enroll an app user which will be used to interact with the blockchain network. The section
of the application code is shown below.

Scrolling further down in your terminal output, you should see confirmation of the app user
registration similar to this:

You will notice that in the following lines of application code, the application is getting reference to
the Contract using the contract name and channel name via Gateway:

// Create a new gateway instance for interacting with the fabric network.
// In a real application this would be done as the backend server session is setup for
// a user that has been verified.
const gateway = new Gateway();

46
try {
// setup the gateway instance
// The user will now be able to create connections to the fabric network and be able to
// submit transactions and query. All transactions submitted by this gateway will be
// signed by this user using the credentials stored in the wallet.
await [Link](ccp, {
wallet,
identity: userId,
discovery: {enabled: true, asLocalhost: true} // using asLocalhost as this gateway is using a
fabric network deployed locally
});

// Build a network instance based on the channel where the smart contract is deployed
const network = await [Link](channelName);

// Get the contract from the network.


const contract = [Link](chaincodeName);

When a chaincode package includes multiple smart contracts, on the getContract() API you can
specify both the name of the chaincode package and a specific smart contract to target. For
example:

Fourth, the application initializes the ledger with some sample data

The submitTransaction() function is used to invoke the chaincode InitLedger function to populate
the ledger with some sample data.

Sample application 'InitLedger' call

// Initialize a set of asset data on the channel using the chaincode 'InitLedger' function.
// This type of transaction would only be run once by an application the first time it was started after
it
// deployed the first time. Any updates to the chaincode deployed later would likely not need to run
// an "init" type function.
[Link]('\n--> Submit Transaction: InitLedger, function creates the initial set of assets on the
ledger');
await [Link]('InitLedger');
[Link]('*** Result: committed');

Chaincode 'InitLedger' function


async InitLedger(ctx) {
const assets = [
{

ID: 'asset1',
47
Color: 'blue',
Size: 5,
Owner: 'Tomoko',
AppraisedValue: 300,
},
{
ID: 'asset2',
Color: 'red',
Size: 5,
Owner: 'Brad',
AppraisedValue: 400,
},
{
ID: 'asset3',
Color: 'green',
Size: 10,
Owner: 'Jin Soo',
AppraisedValue: 500,
},
{
ID: 'asset4',
Color: 'yellow',
Size: 10,
Owner: 'Max',
AppraisedValue: 600,
},
{
ID: 'asset5',
Color: 'black',
Size: 15,
Owner: 'Adriana',
AppraisedValue: 700,
},
{
ID: 'asset6',
Color: 'white',
Size: 15,
Owner: 'Michel',
AppraisedValue: 800,
},
];

for (const asset of assets) {


[Link] = 'asset';
await [Link]([Link], [Link]([Link](asset)));
[Link](`Asset ${[Link]} initialized`);
}
}

The terminal output entry should look similar to below:

48
Fifth, the application invokes each of the chaincode functions

Sample application 'GetAllAssets' call

Chaincode 'GetAllAssets' function

The terminal output should look like this:

Evalua te Transac tion: GetAllAssets, fun ction returns all the curre nt assets on the ledger
Resul t: [
{
"Key": "asset1",
"Record": {
"ID": "asset1",
"Color": "blue",
"Size": 5,
"Owner": "Tomoko",
"AppraisedValue": 300,

49
"docType": "asset"
}
},
{
"Key": "asset2",
"Record": {
"ID": "asset2",
"Color": "red",
"Size": 5,
"Owner": "Brad",
"AppraisedValue": 400,
"docType": "asset"
}
},
{
"Key": "asset3",
"Record": {
"ID": "asset3",
"Color": "green",
"Size": 10,
"Owner": "Jin Soo",
"AppraisedValue": 500,
"docType": "asset"
}
},
{
"Key": "asset4",
"Record": {
"ID": "asset4",
"Color": "yellow",
"Size": 10,
"Owner": "Max",
"AppraisedValue": 600,
"docType": "asset"
}
},
{
"Key": "asset5",
"Record": {
"ID": "asset5",
"Color": "black",
"Size": 15,
"Owner": "Adriana",
"AppraisedValue": 700,
"docType": "asset"
}
},
{
"Key": "asset6",
"Record": {
"ID": "asset6",
"Color": "white",
50
"Size": 15,
"Owner": "Michel",
"AppraisedValue": 800,
"docType": "asset"
}
}
]

Next, the sample application submits a transaction to create ‘asset13’.

Sample application 'CreateAsset' call

Sample application 'ReadAsset' call

Chaincode 'ReadAsset' function

51
Terminal output:

Sample application 'UpdateAsset' call

Chaincode 'UpdateAsset' function

52
Terminal output:

When you are finished using the asset-transfer sample, you can bring down the test network
using [Link] script.

Result:
Thus the deployment of an asset-transfer app using blockchain within a Hyperledger Fabric
network are executed successfully.

53
Ex: No:5 Fitness Club rewards using Hyperledger Fabric

Aim:

To build a web app that tracks fitness club rewards using Hyperledger Fabric

several steps:

Procedure:

1. Set up Hyperledger Fabric network.

2. Define smart contracts for handling rewards.

3. Develop a web application frontend.

4. Connect the frontend to the Hyperledger Fabric network.

1. Set up Hyperledger Fabric network:

You need to set up a Hyperledger Fabric network with a few nodes. Refer to the official documentation
for detailed instructions.

2. Define smart contracts:

Define smart contracts to handle fitness club rewards. Here's a simple example in Go:

package main

import (
"encoding/json"
"fmt"

"[Link]/hyperledger/fabric-contract-api-go/contractapi"
)

type RewardsContract struct {


[Link]
}

type Reward struct {


MemberID string `json:"memberID"`
Points int `json:"points"`
}
func (rc *RewardsContract) IssueReward(ctx [Link], memberID string,
points int) error {
reward := Reward{

54
MemberID: memberID,
Points: points,
}

rewardJSON, err := [Link](reward)


if err != nil {
return err
}
return [Link]().PutState(memberID, rewardJSON)

}
func (rc *RewardsContract) GetReward(ctx [Link], memberID string)
(*Reward, error) {
rewardJSON, err := [Link]().GetState(memberID)
if err != nil {

return nil, err


}

if rewardJSON == nil {
return nil, [Link]("reward for member %s not found", memberID)
}
var reward Reward

err = [Link](rewardJSON, &reward)


if err != nil {
return nil, err
}
return &reward, nil
}
3. Develop a web application frontend:
You can use any frontend framework like React, [Link], etc. Here's a simple React component to interact
with the smart contract:
[Link]
import React, { useState } from 'react';
import { useContract } from './useContract'; // Assume this hook connects to the contract
const RewardsComponent = () => {
55
const [memberID, setMemberID] = useState('');
const [points, setPoints] = useState('');
const { issueReward, getReward } = useContract();
const handleIssueReward = async () => {
await issueReward(memberID, points);
};
const handleGetReward = async () => {
const reward = await getReward(memberID);
[Link](reward);
};
return (
<div>
<input type="text" placeholder="Member ID" value={memberID} onChange={(e) =>
setMemberID([Link])} />
<input type="number" placeholder="Points" value={points} onChange={(e) =>
setPoints([Link])} />
<button onClick={handleIssueReward}>Issue Reward</button>
<button onClick={handleGetReward}>Get Reward</button>
</div>
);
};
export default RewardsComponent;
4. Connect the frontend to the Hyperledger Fabric network:

Use a library like fabric-network to interact with the Hyperledger Fabric network. Implement functions
like issueReward and getReward to interact with the smart contract.

Now, integrate this frontend component into your web application. Here's a screenshot of what the UI
might look like:

In this example, users can input a member ID and points to issue rewards, and they can retrieve rewards
by providing the member ID.

Remember, this is a basic example. In a real-world application, you would need to consider security,
scalability, and other factors. Additionally, you'll need to handle user authentication, authorization, and
other functionalities as per your requirements.

Result:

Thus the blockchain to track fitness club rewards and build a web app that uses Hyperledger Fabric to
track and trace member rewards are executed successfully.
56
Ex: No:6 Car auction network using the Hyperledger fabric node SDK

Aim:

To create a "Hello World" example of a car auction network using the Hyperledger Fabric
Node SDK and IBM Blockchain Starter Plan

Procedure:

1. Set up a Hyperledger Fabric network using the IBM Blockchain Starter Plan.

2. Define and deploy chaincode (smart contract) for the car auction.

3. Develop a [Link] application using the Hyperledger Fabric Node SDK to interact with the chaincode.

4. Implement basic functionalities such as creating an auction, bidding, and retrieving auction results.

1. Set up a Hyperledger Fabric network using IBM Blockchain Starter Plan:

Follow the instructions provided by IBM to set up a Hyperledger Fabric network using the IBM
Blockchain Starter Plan.

2. Define and deploy chaincode:

Define chaincode for the car auction network. This chaincode will contain functions to create auctions,
place bids, and retrieve auction results.

Program:

package main
import (
"encoding/json"
"fmt"
"[Link]/hyperledger/fabric-contract-api-go/contractapi"
)
type CarAuctionContract struct {
[Link]
}

type Auction struct {


ID string `json:"id"`

Car string `json:"car"`


HighestBid int `json:"highestBid"`

57
HighestBidder string `json:"highestBidder"`
}
func (c *CarAuctionContract) CreateAuction(ctx [Link], auctionID
string, car string) error {
auction := Auction{
ID: auctionID,
Car: car,
}
auctionJSON, err := [Link](auction)
if err != nil {

return err
}
return [Link]().PutState(auctionID, auctionJSON)
}
func (c *CarAuctionContract) PlaceBid(ctx [Link], auctionID string,
bidder string, bidAmount int) error {

auctionJSON, err := [Link]().GetState(auctionID)


if err != nil {
return err
}
if auctionJSON == nil {
return [Link]("auction %s does not exist", auctionID)
}

var auction Auction


err = [Link](auctionJSON, &auction)
if err != nil {

return err
}

if bidAmount > [Link] {


[Link] = bidAmount

58
[Link] = bidder
updatedAuctionJSON, _ := [Link](auction)
return [Link]().PutState(auctionID, updatedAuctionJSON)
}
return [Link]("bid amount should be higher than the current highest bid")
}
func (c *CarAuctionContract) GetAuction(ctx [Link], auctionID string)
(*Auction, error) {
auctionJSON, err := [Link]().GetState(auctionID)
if err != nil {

return nil, err


}
if auctionJSON == nil {
return nil, [Link]("auction %s does not exist", auctionID)
}

var auction Auction


err = [Link](auctionJSON, &auction)
if err != nil {
return nil, err
}
return &auction, nil
}

3. Develop a [Link] application:

Use the Hyperledger Fabric Node SDK to interact with the chaincode. This application will have
functions to create auctions, place bids, and retrieve auction results.

// [Link]

const { Gateway, Wallets } = require('fabric-network');

const path = require('path');

const fs = require('fs');

const ccpPath = [Link]( dirname, '..', '[Link]');

const ccpJSON = [Link](ccpPath, 'utf8');


59
const ccp = [Link](ccpJSON);

async function main() {

try {

const walletPath = [Link]([Link](), 'wallet');

const wallet = await [Link](walletPath);

const gateway = new Gateway();

await [Link](ccp, {

wallet,

identity: 'user1',

discovery: { enabled: true, asLocalhost: true }

});

const network = await [Link]('mychannel');

const contract = [Link]('carAuction');

// Invoke chaincode functions here

await [Link]();

} catch (error) {

[Link](`Failed to submit transaction: ${error}`);

[Link](1);

main();

4. Implement basic functionalities:

Implement functions in `[Link]` to interact with the chaincode.

async function createAuction(auctionID, car) {

await [Link]('CreateAuction', auctionID, car);

[Link](`Auction ${auctionID} created for car ${car}`);

async function placeBid(auctionID, bidder, bidAmount) {

60
await [Link]('PlaceBid', auctionID, bidder, bidAmount);

[Link](`Bid placed for auction ${auctionID} by ${bidder} with amount ${bidAmount}`);

async function getAuction(auctionID) {

const auctionJSON = await [Link]('GetAuction', auctionID);

const auction = [Link]([Link]());

[Link](`Auction ${auctionID}: ${[Link](auction, null, 2)}`);

Output:

Auction CAR123 created for car BMW

Bid placed for auction CAR123 by bidder1 with amount 5000

Auction CAR123: {

"id": "CAR123",

"car": "BMW",

"highestBid": 5000,

"highestBidder": "bidder1"

Result:

Thus the creation of "Hello World" example of a car auction network using the Hyperledger Fabric
Node SDK and IBM Blockchain Starter Plan are executed successfully.

61
CONTENT BEYOND SYLLABUS

62
Ex: No:7 Implementing a Decentralized Exchange (DEX) on Ethereum

Aim:

Create and deploy a decentralized exchange (DEX) smart contract on the Ethereum blockchain.

Steps by Step Procedure

1. Set up the development environment:


o Install Truffle, Ganache, and MetaMask.
o Initialize a new Truffle project.

2. Write the DEX smart contract:

 Create a new file named [Link] in the contracts folder.

pragma solidity ^0.8.0;

contract DEX {

struct Order {

uint256 id;

address trader;

uint256 amount;

uint256 price;

bool isBuy;

uint256 public nextOrderId = 1;

mapping(uint256 => Order) public orders;

event OrderPlaced(uint256 id, address trader, uint256 amount, uint256 price, bool isBuy);
63
function placeOrder(uint256 amount, uint256 price, bool isBuy) public {

orders[nextOrderId] = Order(nextOrderId, [Link], amount, price, isBuy);

emit OrderPlaced(nextOrderId, [Link], amount, price, isBuy);

nextOrderId++;

3. Deploy the smart contract:

 Create a migration script in the migrations folder.

JavaScript

const DEX = [Link]("DEX");

[Link] = function (deployer) {

[Link](DEX);

};

4. Interact with the DEX smart contract:

 Use Truffle console to interact with the contract.

truffle console

[Link]().then(instance => [Link](100, 1, true, { from: [Link][0] }))

EXPLANATION:

 Decentralized Exchange (DEX): A platform that enables peer-to-peer trading of


cryptocurrencieswithout intermediaries.
 Smart Contract: A self-executing contract with the terms of the agreement directly written into
code.
 Order: A record of a trade request, including details like trader address, amount, price, and type
(buy or sell).

Result :
Thus the a decentralized exchange (DEX) smart contract on the Ethereum blockchain was created and
deployed Successfully.
64
Ex: No:8 Creating a Blockchain-based Voting System

Aim:

To design and implement a secure, transparent, and tamper-proof voting system using blockchain

technology.

Materials Needed:

 Computer with internet access


 Programming environment (e.g., Visual Studio Code)
 Blockchain platform (e.g., Ethereum)
 Smart contract language (e.g., Solidity)
 Development tools (e.g., Truffle, Ganache)
 MetaMask wallet

Steps:

1. Setup Development Environment:


o Install [Link] and npm.
o Install Truffle and Ganache.
o Set up MetaMask wallet.

Bash
# Installing [Link] and npm
sudo apt update
sudo apt install nodejs npm

# Installing Truffle and Ganache


npm install -g truffle
npm install -g ganache-cli

2. Create a New Truffle Project:

o Initialize a new Truffle project.


o Create a new directory for the project and navigate into it.
o Run truffle init to initialize the project.

Bash

mkdir VotingSystem
cd VotingSystem
truffle init

3. Develop Smart Contracts:

 Create a smart contract for the voting system using Solidity.


 Define the structure of the contract, including functions for adding candidates, casting votes, and
tallying results.
65
 Ensure the contract includes security measures to prevent double voting and tampering

// contracts/[Link]

pragma solidity ^0.8.0;

contract Voting {

struct Candidate {

uint id;

string name;

uint voteCount;

mapping(uint => Candidate) public candidates;

mapping(address => bool) public voters;

uint public candidatesCount;

event VoteCasted(uint candidateId);

function addCandidate(string memory _name) public {

candidatesCount++;

candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);

function vote(uint _candidateId) public {

require(!voters[[Link]], "You have already voted.");

require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate.");

66
voters[[Link]] = true;

candidates[_candidateId].voteCount++;

emit VoteCasted(_candidateId);

function getCandidate(uint _candidateId) public view returns (uint, string memory, uint) {

Candidate memory candidate = candidates[_candidateId];

return ([Link], [Link], [Link]);

4. Deploy Smart Contracts:


o Use Ganache to create a local blockchain for testing.
o Deploy the smart contract to the local blockchain using Truffle.

bash
# Start Ganache
ganache-cli

# Compile and deploy the contract


truffle compile
truffle migrate –reset

5. Create Frontend Interface:


o Develop a simple web interface using HTML, CSS, and JavaScript.
o Connect the frontend to the smart contract using [Link].

Html

<!-- [Link] -->


<!DOCTYPE html>
<html>
<head>
<title>Voting System</title>
<script src="[Link]
<script src="[Link]"></script>
</head>
<body>
<h1>Voting System</h1>
<div id="candidates"></div>
67
<button onclick="vote(1)">Vote for Candidate 1</button>
<button onclick="vote(2)">Vote for Candidate 2</button>
</body>
</html>

Javascript

// [Link]
let web3 = new Web3([Link] || "[Link]
let contractAddress = "YOUR_CONTRACT_ADDRESS";
let abi = [
// ABI JSON here
];

let votingContract = new [Link](abi, contractAddress);

async function vote(candidateId) {


let accounts = await [Link]();
[Link](candidateId).send({ from: accounts[0] });
}

async function getCandidates() {


let candidatesCount = await [Link]().call();
for (let i = 1; i <= candidatesCount; i++) {
let candidate = await [Link](i).call();
[Link]("candidates").innerHTML += `<p>${candidate[1]}: ${candidate[2]}
votes</p>`;
}
}

getCandidates();

6. Test the System:


o Conduct thorough testing to ensure the system works as expected.
o Simulate multiple voting scenarios to check for security and accuracy.

Expected Outcomes and Results:

 Secure Voting Process: The system should ensure that only eligible voters can cast their votes and
that each voter can vote only once.
 Transparency: All transactions (votes) should be recorded on the blockchain, making the voting
process transparent and verifiable.
 Tamper-Proof: The use of blockchain technology should make it nearly impossible to alter or tamper
with the votes once they are recorded.
 Real-Time Results: The system should provide real-time updates on the voting results, allowing users
to see the progress as votes are cast and counted.

68
Result :

Thus the a secure, transparent, and tamper-proof voting system using blockchain technology was

created and executed Successfully.

69

You might also like