CCBT Lab
CCBT Lab
CCBT Lab
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.
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 Node.js application, you need to go through the following steps:
1
Reg no : 420421104060
Execute
1. Node.js
2. Express.js
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, Node.js will ask you to enter some details to build the .json file such as:
npm i express
2
Reg no : 420421104060
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, we don’t have to
restart the Node.js server each time any changes are made. nodemon will implicitly detect the changes
and restart the server for us.
npm i -g nodemon
package.json
{
"name":
"samplerestapi",
"version": "1.0.0",
"description": "Edureka REST API with Node.js",
"main": "script.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Edureka",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"joi": "^13.1.0"
}
}
Docker file
3
Reg no : 420421104060
1 FROM node:9-slim
2
3 # WORKDIR specifies the application directory
4
5 WORKDIR /app
6
7 # Copying package.json file to the app directory
8 COPY package.json /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
Build Docker Image
# Starting the application using npm start
CMD
Building ["npm","start"]
a Docker image is rather easy and can be done using a simple command. Belo w I have written
down the command that you need to type in your terminal and execute it:
4
Reg no : 420421104060
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 Node.js
Docker article, I will show you how to execute this 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:
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
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
5
Reg no : 420421104060
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
Step 2: From inside this directory, you can directly run ./network.sh script file through which we run
the Test Network. By default, we would be running ./network.sh 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.
./network.sh 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
./network.sh up
./network.sh up
6
Reg no : 420421104060
If the above command completes successfully, you will see the logs of the nodes being created below
picture:
The environment we are going to set up has three main tools as follows.
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:
7
Reg no : 420421104060
We can check the installation by using the $ geth version command as follows.
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.
8
Reg no : 420421104060
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 ;
9
Reg no : 420421104060
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
genesis.json
10
Reg no : 420421104060
datadir param specifies where we should save our network’s data. After initializing this, the root folder
should contain something like following.
To list all created account lists you can use the account list command as
11
Reg no : 420421104060
As the next step, we need to specify following startnode.sh file. This script will start the network with
given params.
startnode.sh
As the next step we need to log into the Geth console using the attach command as follows.
This will start the Geth console. To list all accounts we can use following command.
Result:
Thus the Installation of Docker Container,Node.js and HyperledgerFabric and Etherum Network are
executed successfully.
12
Reg no : 420421104060
Ex:No: 2 Create and deploy a blockchain network using Hyperledger Fabric SDK for Java
Date :
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:
Steps
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:
13
Reg no : 420421104060
network_resources/crypto-config
network_resources/config
The automated scripts to build the network are provided under network directory. The network/docker-
compose.yaml file defines the blockchain network topology.
cd network
chmod +x build.sh
./build.sh
cd network
chmod +x stop.sh
./stop.sh
cd network
chmod +x teardown.sh
./teardown.sh
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.
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
cd target
14
Reg no : 420421104060
cp blockchain-java-sdk-0.0.1-SNAPSHOT-jar-with-dependencies.jar blockchain-client.jar
Copy this built jar into network_resources directory. This is required as the java code can access required
artifacts during execution.
cp blockchain-client.jar ../../network_resources
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/CreateChannel.java. To create and initialize the
channel, run the following command.
cd ../../network_resources
Output:
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.
Output:
15
Reg no : 420421104060
INFO: Instantiate proposal request fabcar on channel mychannel with Fabric client Org2MSP admin
Note: The chaincode fabcar.go was taken from the fabric samples available at -
https://github.com/hyperledger/fabric-samples/tree/release-1.4/chaincode/fabcar/go.
A new user can be registered and enrolled to an MSP. Execute the below command to register a new user
and enroll to Org1MSP.
16
Reg no : 420421104060
Output:
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.
Output:
id:a298b9e27bdb0b6ca18b19f9c78a5371fb4d9b8dd199927baf37379537ca0d0f
INFO:
17
Reg no : 420421104060
Output:
INFO: [{"Key":"CAR1",
"Record":{"make":"Chevy","model":"Volt","colour":"Red","owner":"Nick"}}]
INFO: {"make":"Chevy","model":"Volt","colour":"Red","owner":"Nick"}
Program:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeoutException;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
18
Reg no : 420421104060
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
class Sample {
.identity(wallet, "user1")
.networkConfig(networkConfigFile);
19
Reg no : 420421104060
e.printStackTrace();
Result:
Thus the creation and deploy a blockchain network using Hyperledger Fabric SDK for Java are
executed successfully.
20
Reg no : 420421104060
Ex:No: 3 Interact with a blockchain network and execute transactions and requests against a
blockchain network
Date :
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:
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.
• Git
• Python 2.7.x
yperledger has a bash script available to make this process extremely easy. Run the following commands
in your terminal:
Run the following commands in your Terminal, and make sure you’re NOT using sudo when running
npm commands.
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.
21
Reg no : 420421104060
Basically what we did here was just download and start a local Fabric network. We can stop is using
./stopFabric.sh if we want to. At the end of our development session, we should run ./teardownFabric.sh
you’ll be greeted with something similar to the above. Select Business Network and name it cards-
trading-network as shown below:
22
Reg no : 420421104060
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 org.example.biznet.cto 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.
23
Reg no : 420421104060
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:
This is the first time we’ve used --> 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.
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 logic.js with the following code:
Add a new rule in permissions.acl 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.
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:
This command tells Hyperledger Composer we want to build a BNA from a directory which is our
current root folder.
24
Reg no : 420421104060
We can install and deploy the network to our local Fabric runtime using the PeerAdmin user. To install
the business network, type
25
Reg no : 420421104060
The networkName and networkVersion must be the same as specified in your package.json 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
26
Reg no : 420421104060
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:
27
Reg no : 420421104060
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.
28
Reg no : 420421104060
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:
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.
29
Reg no : 420421104060
Click on Submit Transaction in the left and make card point to TradingCard#2 and newOwner point
to Trader#3 like this:
30
Reg no : 420421104060
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:
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 http://localhost:4200/ 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
31
Reg no : 420421104060
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
32
Reg no : 420421104060
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:
33
Reg no : 420421104060
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
34
Reg no : 420421104060
Date :
Aim:
To Deploy an asset-transfer app using blockchain. Learn app development within aHyperledger
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.
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.
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
35
Reg no : 420421104060
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 network.sh shell script.
Next, let’s deploy the chaincode by calling the ./network.sh 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.
36
Reg no : 420421104060
JavaScript Application
This directory contains sample programs that were developed using the Fabric SDK for Node.js.
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 package.json. The
most important of which is the fabric-network Node.js 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:
connection profile
In the sample path, making
application code sure the you
below, connection
will seeprofile exists,getting
that after and specifying
reference where
to the tocommon
create
37
Reg no : 420421104060
the wallet, enrollAdmin() is executed and the admin credentials are generated from the Certificate
Authority.
// 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/admin.id file
Because the admin registration step is bootstrapped when the Certificate Authority is started, we
only need to enroll the admin.
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:
38
Reg no : 420421104060
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();
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 gateway.connect(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 gateway.getNetwork(channelName);
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.
// 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.
console.log('\n--> Submit Transaction: InitLedger, function creates the initial set of assets on the
ledger');
await contract.submitTransaction('InitLedger');
39
Reg no : 420421104060
40
Reg no : 420421104060
Evalua te Transact io n: Get AllAssets, fun ct io n returns all t he current assets o n t he ledger
Resul t: [
{
41
Reg no : 420421104060
"Key": "asset1",
"Record": {
"ID": "asset1",
"Color": "blue",
"Size": 5,
"Owner": "Tomoko",
"AppraisedValue": 300,
"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"
42
Reg no : 420421104060
}
},
{
"Key": "asset6",
"Record": {
"ID": "asset6",
"Color": "white",
"Size": 15,
"Owner": "Michel",
"AppraisedValue": 800,
"docType": "asset"
}
}
]
43
Reg no : 420421104060
Terminal output:
Terminal output:
44
Reg no : 420421104060
When you are finished using the asset-transfer sample, you can bring down the test network
using network.sh script.
Result:
Thus the deployment of an asset-transfer app using blockchain within a Hyperledger Fabric
network are executed successfully.
45
Reg no : 420421104060
Date :
Aim:
To build a web app that tracks fitness club rewards using Hyperledger Fabric
several steps:
Procedure:
You need to set up a Hyperledger Fabric network with a few nodes. Refer to the official documentation
for detailed instructions.
Define smart contracts to handle fitness club rewards. Here's a simple example in Go:
package main
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
type RewardsContract struct {
contractapi.Contract
}
reward := Reward{
MemberID: memberID,
Points: points,
}
}
3. Develop a web application frontend:
You can use any frontend framework like React, Vue.js, etc. Here's a simple React component to interact
with the smart contract:
RewardsComponent.js
47
Reg no : 420421104060
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.
48
Reg no : 420421104060
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.
49
Reg no : 420421104060
Ex: No:6 Car auction network using the Hyperledger fabric node SDK
Date :
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 Node.js 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.
Follow the instructions provided by IBM to set up a Hyperledger Fabric network using the IBM
Blockchain Starter Plan.
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"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
50
Reg no : 420421104060
auction.HighestBid = bidAmount
51
Reg no : 420421104060
auction.HighestBidder = bidder
updatedAuctionJSON, _ := json.Marshal(auction)
return ctx.GetStub().PutState(auctionID, updatedAuctionJSON)
return fmt.Errorf("bid amount should be higher than the current highest bid")
}
func (c *CarAuctionContract) GetAuction(ctx contractapi.TransactionContextInterface, auctionID string)
(*Auction, error) {
}
var auction Auction
err = json.Unmarshal(auctionJSON, &auction)
if err != nil {
return nil, err
}
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.
// app.js
const fs = require('fs');
52
Reg no : 420421104060
try {
await gateway.connect(ccp, {
wallet,
identity: 'user1',
});
await gateway.disconnect();
} catch (error) {
process.exit(1);
main();
53
Reg no : 420421104060
Output:
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.
54
Reg no : 420421104060
Ex: No:7
Creating Crypto-currency Wallet
Date :
AIM :
STEPS:
1. Choose the type of wallet.
2. Sign up for an account, buy the device or download the software needed.
3. Set up security features, including a recovery phrase.
4. Purchase crypto currency or transfer coins from another wallet or exchange.
SOURCE CODE:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
public class CryptoWallet {
private PrivateKey privateKey;
private PublicKey publicKey;
public CryptoWallet() {
generateKeyPair();
}
public void generateKeyPair() {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom random = SecureRandom.getInstanceStrong();
55
lOM oAR c P S D | 2794 756 0
keyGen.initialize(ecSpec, random);
KeyPair keyPair =
keyGen.generateKeyPair();privateKey =
keyPair.getPrivate();
publicKey = keyPair.getPublic();
} catch (Exception
e) {
e.printStackTrace(
);
}}
public static void main(String[] args) {
CryptoWallet wallet = new
CryptoWallet();
System.out.println("Private Key: " +
wallet.privateKey);System.out.println("Public Key:
" + wallet.publicKey);
}}
EXPECTED OUTPUT:
RESULT:
Thus the program creating a Crypto currency wallet has been executed successfully.
56