Blockchain Journal
Blockchain Journal
VIVEKANANDEDUCATION SOCIETY’S
INSTITUTE OF TECHNOLOGY
Since 1962
CERTIFICATE
INDEX
THEORY:
WHAT IS CRYPTOGRAPHY?
Cryptography is a method of protecting information and communications through the use
of codes, so that only those for whom the information is intended can read and process it.
In computer science, cryptography refers to secure information and communication
techniques derived from mathematical concepts and a set of rule-based calculations called
algorithms, to transform messages in ways that are hard to decipher. These deterministic
algorithms are used for cryptographic key generation, digital signing, verification to protect
data privacy, web browsing on the internet and confidential communications such as credit
card transactions and email.
CAESAR CIPHER
The Caesar Cipher technique is one of the earliest and simplest methods of encryption
technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced
by a letter with a fixed number of positions down the alphabet. For example with a shift of
1, A would be replaced by B, B would become C, and so on. The method is apparently
named after Julius Caesar, who apparently used it to communicate with his officials.
CODE:
2
Heetika Vaity Blockchain Lab SYMCA- 57/B
return outText
encode = caesar_encrypt('abcDEF', 2)
print(encode)
decode = caesar_encrypt(caesar_encrypt('abcDEF',2),26-2)
print(decode)
OUTPUT:
CONCLUSION:
From this practical, I have learned and implemented the caesar cipher in the python.
3
Name of Student : Heetika Mahesh Vaity
THEORY:
RSA algorithm is a public key encryption technique and is considered as the most secure
way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence
named RSA algorithm.
Algorithm:
The RSA algorithm holds the following features −
You will have to go through the following steps to work on RSA algorithm −
2
Heetika Vaity Blockchain Lab SYMCA- 57/B
Encryption Formula
Consider a sender who sends the plain text message to someone whose public key is (n,e).
To encrypt the plain text message m in the given scenario, use the following syntax
C = me mod n
Decryption Formula
The decryption process is very straightforward and includes analytics for calculation in a
systematic approach. Considering receiver C has the private key d, the result modulus will
be calculated as −
Plaintext, m = cd mod n
3
Heetika Vaity Blockchain Lab SYMCA- 57/B
CODE:
import math
4
Heetika Vaity Blockchain Lab SYMCA- 57/B
d = mod_inverse(e, phi)
if d is None:
raise ValueError("Modular inverse does not exist. Choose different values for e.")
# Encryption
c = pow(msg, e, n)
print(f"Encrypted data = {c}")
# Decryption
m = pow(c, d, n)
print(f"Original Message Sent = {m}")
OUTPUT:
CONCLUSION:
From this practical, I have understood how to implement the RSA algorithm in python.
5
Name of Student : Heetika Mahesh Vaity
THEORY:
Introduction to Hashing
Hashing is the process of converting raw information into a scrambled format such that it cannot be
reversed to its original form. This is achieved through a function known as the hash function, which
performs mathematical operations on the plaintext input. The output of this function is called the
hash value or digest.
● Irreversibility: Hash functions are designed to be irreversible, meaning that the hash digest
should not allow the original plaintext to be reconstructed.
● Consistency: The same input will always produce the same hash value, regardless of how
many times the function is applied.
Applications of Hashing
1. Password Hashing:
○ Websites convert user passwords into hash values before storing them on servers.
During login, the server recalculates the hash of the provided password and
compares it with the stored hash for validation.
2. Integrity Verification:
○ When uploading files to a website, a hash of the file is often provided. Users can
recalculate the hash of the downloaded file and compare it with the provided hash to
ensure the file’s integrity.
Hash functions transform data into a fixed-size hash value. The process involves breaking the data
into blocks and converting them into a shorter, fixed-length key or value. The term “hash” refers to
both the hash function and the hash value.
● Hash functions were initially created to compress data, reducing memory requirements for
large files. The resulting hashes are stored in hash tables, which facilitate quick data
lookups.
● Hash functions ensure that each input generates a unique identifier, and any duplication of
hash outputs (collisions) indicates a potential issue.
2
Heetika Vaity Blockchain Lab SYMCA- 57/B
Overview:
● SHA-256 is part of the SHA-2 family of hash algorithms. It was introduced in 2001 by the
NSA and NIST as an improvement over the SHA-1 family, which was becoming vulnerable to
brute-force attacks.
● The "256" in SHA-256 refers to the length of the final hash digest: 256 bits (32 bytes).
Significance:
● SHA-256 generates a unique, fixed-size 256-bit hash. It is a one-way function, which means
the original data cannot be derived from the hash.
Applications:
● SHA-256 is widely used for data integrity checks, authentication, anti-tamper measures,
digital signatures, and in blockchain technologies.
Limitations:
The hashlib module in Python provides a common interface to various secure hash and message
digest algorithms. Supported algorithms include:
Functions in hashlib:
3
Heetika Vaity Blockchain Lab SYMCA- 57/B
CODE:
import hashlib
string="Heetika Vaity"
encoded=string.encode()
result = hashlib.sha256(encoded)
OUTPUT:
CONCLUSION:
From this practical, I have learned & implemented sha-256 hashing using hashlib in python.
4
Name of Student : Heetika Mahesh Vaity
THEORY:
A Merkle tree, also known as a hash tree, is a specialized data structure used for data
verification and synchronization. It organizes data in a hierarchical manner where each
non-leaf node is a hash of its child nodes. All leaf nodes are positioned at the same depth
and are as far left as possible. This structure ensures data integrity and is particularly
useful for efficient data management and verification.
Structure:
● Leaf Nodes: Represent the hash values of the data blocks or transactions. They are
the bottom-most level of the tree.
● Non-Leaf Nodes: Each non-leaf node is a hash of its two child nodes. The hash of a
non-leaf node is computed by combining the hashes of its children.
● Root Node: The topmost node, known as the root hash or Merkle root, represents a
hash of the entire tree. It provides a single fingerprint for the entire dataset.
Process:
1. Hashing Data Blocks: Start by hashing the individual data blocks. These hashes
form the leaf nodes of the tree.
2. Building the Tree: Pair up leaf nodes and compute the hash of each pair to form the
next level of the tree. Repeat this process until only one hash remains, which
becomes the root hash.
3. Root Hash: The root hash serves as a compact representation of all the data in the
tree. It enables efficient verification of data integrity.
2
Heetika Vaity Blockchain Lab SYMCA- 57/B
Hash Functions
A hash function maps an input (or "message") to a fixed-size output, known as a hash or
digest. The primary characteristics of a hash function include:
● Uniqueness: Each unique input produces a unique hash output, allowing for data
fingerprinting.
● Deterministic: The same input will always produce the same hash output.
● Fast Computation: The hash function should quickly compute the hash value for
any given input.
● Collision Resistance: It should be computationally infeasible to find two different
inputs that produce the same hash output.
Hash functions are crucial in Merkle trees for ensuring that small changes in data are
reflected in the hash values, making it easier to detect discrepancies.
3
Heetika Vaity Blockchain Lab SYMCA- 57/B
In a binary Merkle tree, each non-leaf node has exactly two children. This binary structure
is commonly used because it simplifies the computation and verification of hash values.
Example Structure:
Advantages:
● Efficient Verification: To verify the integrity of a data block, you only need to
traverse a small part of the tree, rather than checking the entire dataset.
● Change Detection: Small changes in the data will propagate up the tree, altering the
root hash. This allows for quick detection of data changes or inconsistencies.
1. Distributed Systems:
○ Merkle trees are used in distributed systems to ensure that the same data
exists across multiple locations. They help in identifying discrepancies
between replicas of data.
2. Database Consistency:
○ Systems like Apache Cassandra use Merkle trees to detect inconsistencies
between database replicas. By comparing Merkle roots, the system can
efficiently identify which parts of the data are out of sync.
3. Blockchain and Cryptocurrencies:
○ Merkle trees are integral to blockchain technology. They are used in
cryptocurrencies like Bitcoin to ensure data integrity and facilitate efficient
verification of transactions. Each block in the blockchain includes a Merkle
root, which represents all the transactions within the block.
CODE:
4
Heetika Vaity Blockchain Lab SYMCA- 57/B
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
5
Heetika Vaity Blockchain Lab SYMCA- 57/B
res.append(root.data)
return res
6
Heetika Vaity Blockchain Lab SYMCA- 57/B
key_node = temp
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
if key_node :
x = temp.data
deleteDeepest(root,temp)
key_node.data = x
return root
OUTPUT:
7
Heetika Vaity Blockchain Lab SYMCA- 57/B
CONCLUSION:
From this practical, I have successfully learned & implemented the merkle tree in python.
8
Name of Student : Heetika Mahesh Vaity
AIM: Install Geth Ethereum Node (Show installation steps also). Create a
Genesis block and a private chain. Use geth commands to create user
accounts, mine, transact etc.
THEORY:
What is a node?
Geth:
2
Heetika Vaity Blockchain Lab SYMCA- 57/B
Genesis Block:
● A genesis block refers to the first block in a blockchain and is usually hardcoded into
its application’s software. A blockchain has multiple “blocks” (containing validated
transactions and recorded activity data) linked together by a metaphorical chain.
● Each “block” of a crypto asset contains referential data for the previous one and
derives its value/legitimacy from its predecessor.The genesis block, thus, refers to
the first block (Block 0 or Block 1) of a new blockchain, to which all other
subsequent blocks are attached.
● A genesis block is unique as it is the only block in a blockchain that does not
reference a predecessor block, and in almost all cases, the first mining rewards it
unlocks are unspendable.
● Genesis blocks have special significance, as they form the very foundation of a
blockchain and often contain interesting stories or hidden meanings. For instance,
Bitcoin’s genesis block contains the now-famous message ” The Times 03/Jan/2009
Chancellor on brink of second bailout for banks”— a reference to the deteriorating
financial conditions of that time and the rationale for creating cryptocurrencies like
Bitcoin and Ethereum. Bitcoin’s genesis block in 2009 contained 50 BTC.
● The Bitcoin genesis block is very intriguing not just for its included message, but
also due to the fact that the next block was timestamped nearly six days later (the
average time is 10 minutes).
3
Heetika Vaity Blockchain Lab SYMCA- 57/B
STEPS/OUTPUT:
Download the latest release of Geth for Windows, make sure you download the 64-bit
version.
4
Heetika Vaity Blockchain Lab SYMCA- 57/B
5
Heetika Vaity Blockchain Lab SYMCA- 57/B
Open up notepad, copy & paste the code below into a new file called “genesis.json” and save
this file in our Private-chain folder.
"config": {
"chainId": 4777,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0
},
"alloc" : {},
"difficulty" : "0x400",
"extraData" : "",
"gasLimit" : "0x7A1200",
"parentHash" :
"0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp" : "0x00"
6
Heetika Vaity Blockchain Lab SYMCA- 57/B
Now, we have to initialize our Ethereum Node. For that, open the command
prompt and change your current directory to the Private Chain folder.
B) run geth:
7
Heetika Vaity Blockchain Lab SYMCA- 57/B
Command: personal.newAccount()
Command: eth.accounts
Command: eth.coinbase
H) CHECKING BALANCE:
Command: eth.getBalance(eth.accounts[0])
8
Heetika Vaity Blockchain Lab SYMCA- 57/B
I) MINING:
Command:
miner.start()
miner.stop()
eth.blockNumber
Command: personal.unlockAccount(eth.accounts[0])
Command: eth.getBalance(eth.accounts[1])
9
Heetika Vaity Blockchain Lab SYMCA- 57/B
M) MINING:
miner.start()
miner.stop()
N) CHECK BALANCE:
Command:
eth.getBalance(eth.accounts[0])
eth.getBalance(eth.accounts[1])
O) GET TRANSACTION:
Command:
eth.getTransaction(“;0x2a7c7851424ca4ed55667ea09a17ff44d73ec53658f759fdb852db9
0100260c4”)
10
Heetika Vaity Blockchain Lab SYMCA- 57/B
Command:
web3.fromWei(eth.getBalance(eth.accounts[0]), “ether”)
web3.fromWei(eth.getBalance(eth.accounts[1]), “ether”)
Command: eth.getBlock(“latest”)
Command: eth.getBlock(100)
11
Heetika Vaity Blockchain Lab SYMCA- 57/B
CONCLUSION:
12
Name of Student : Heetika Mahesh Vaity
THEORY:
Development Tools:
● Injected Web3: A configuration where a dApp (like Remix IDE) connects to the
Ethereum network via a web3 provider injected by MetaMask. This setup allows the
dApp to interact with the blockchain through MetaMask’s wallet.
1
Heetika Vaity Blockchain Lab SYMCA-57/B
1. Install Ganache:
○ Download Ganache from the Truffle Suite website and install it on your
machine.
○ Launch Ganache. It will start a local Ethereum blockchain and display a list of
accounts with private keys and Ether balances.
2. Install MetaMask:
○ Add MetaMask as a browser extension from the MetaMask website.
○ Set up MetaMask by creating a new wallet or importing an existing one. Make
sure to securely store your seed phrase.
○ Connect MetaMask to the Ganache network:
■ Open MetaMask and go to Settings > Networks > Add Network.
■ Enter Ganache network details (usually, http://localhost:7545
for Ganache default).
3. Install and Use Remix IDE:
○ Access Remix IDE via its web interface or by downloading the desktop
application.
○ Ensure that Remix is set to use the Injected Web3 environment:
■ In Remix, go to the Deploy & Run Transactions tab.
■ Choose Injected Web3 from the environment dropdown. Remix
should connect to MetaMask, and MetaMask should be connected to
Ganache.
4. Deploy a Smart Contract:
Write a simple smart contract in Solidity using Remix IDE. Here’s an example of a basic
smart contract:
contract SimpleStorage {
uint256 public storedData;
2
Heetika Vaity Blockchain Lab SYMCA-57/B
○ Ensure Injected Web3 is selected. You should see the MetaMask network
and accounts.
○ Deploy the contract by clicking the Deploy button. MetaMask will prompt
you to confirm the transaction.
5. Interacting with the Contract:
○ After deployment, you can interact with the smart contract directly from
Remix. The deployed contract address and functions will be accessible
through Remix’s interface.
STEPS:
3
Heetika Vaity Blockchain Lab SYMCA-57/B
4
Heetika Vaity Blockchain Lab SYMCA-57/B
5
Heetika Vaity Blockchain Lab SYMCA-57/B
● Keep the network name as localhost and paste the RPC Url, put Chain ID as 1337 and set
Currency Symbol to ETH and save
6
Heetika Vaity Blockchain Lab SYMCA-57/B
7
Heetika Vaity Blockchain Lab SYMCA-57/B
● Import account
8
Heetika Vaity Blockchain Lab SYMCA-57/B
9
Heetika Vaity Blockchain Lab SYMCA-57/B
10
Heetika Vaity Blockchain Lab SYMCA-57/B
Remix IDE:
11
Heetika Vaity Blockchain Lab SYMCA-57/B
CODE:
election.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
12
Heetika Vaity Blockchain Lab SYMCA-57/B
// Voted event
event votedEvent(
uint indexed _candidateId
);
constructor() {
addCandidate("N MODI, BJP");
addCandidate("A Kejriwal, AAP");
addCandidate("Rahul G, Congress");
addCandidate("Nikhil, JDS");
}
13
Heetika Vaity Blockchain Lab SYMCA-57/B
14
Heetika Vaity Blockchain Lab SYMCA-57/B
15
Heetika Vaity Blockchain Lab SYMCA-57/B
16
Heetika Vaity Blockchain Lab SYMCA-57/B
● Try to check candidate no : 5 , you will get the error, because the candidate 5 is not
available.
● Check whether the voter has voted or not by providing the account number. It
returns true if it has voted otherwise
17
Heetika Vaity Blockchain Lab SYMCA-57/B
● Check how many votes are received by the candidate [for example, candidate 1]
18
Heetika Vaity Blockchain Lab SYMCA-57/B
● Check whether the voter has voted or not by providing the account number. It
returns true if it has voted otherwise no
19
Heetika Vaity Blockchain Lab SYMCA-57/B
● Check your balance: [Transaction processing fee has been debited from the
metamask account]
CONCLUSION:
By using Ganache, MetaMask, and Remix IDE together, you create a local Ethereum
development environment. Ganache provides a private blockchain for testing, MetaMask
manages Ethereum accounts and interactions, and Remix IDE offers a powerful platform for
smart contract development and deployment. The Injected Web3 environment facilitates
seamless communication between Remix and MetaMask, enabling efficient testing and
development of smart contracts.
20
Name of Student : Heetika Mahesh Vaity
THEORY:
Solidity
Key Features:
1. Statically Typed: Variables must be declared with a specific data type (e.g., uint,
address, bool), which helps catch errors at compile time.
2. Contract-oriented: The primary building block of Solidity is the contract, which can
contain data and functions.
3. Inheritance: Solidity supports inheritance, allowing contracts to inherit properties
and methods from other contracts, enabling code reuse.
4. Libraries: Developers can create libraries to hold reusable code that can be shared
across contracts.
5. Events: Solidity allows contracts to emit events, which can be used to log
information and facilitate communication between contracts and the front end.
6. Modifiers: These are functions that can be used to change the behavior of functions
in a declarative way, often used for access control.
1
Heetika Vaity Blockchain Lab SYMCA-57/B
Smart Contracts
Definition: Smart contracts are self-executing contracts with the terms of the agreement
directly written into code. They run on a blockchain, enabling trustless transactions and
automation.
Characteristics:
Use Cases:
Components:
● Functions: Define how the contract behaves and interacts with the blockchain.
● State Variables: Hold the data of the contract.
● Events: Enable the contract to log important information for external listeners
2
Heetika Vaity Blockchain Lab SYMCA-57/B
contract q1 {
uint256 l = 50;
uint256 w = 25;
uint256 s = 9;
uint256 r = 5;
3
Heetika Vaity Blockchain Lab SYMCA-57/B
uint256 circumference = 2 * 3 * r;
return circumference;
}
}
OUTPUT:
4
Heetika Vaity Blockchain Lab SYMCA-57/B
contract q2 {
function gross_salary(uint256 basic_salary) public view returns
(uint256) {
if (basic_salary <= 10000) {
uint256 hra = basic_salary * 20 / 100;
uint256 da = basic_salary * 80 / 100;
uint256 gross_salary_total = basic_salary + hra + da;
return gross_salary_total;
}
else if (basic_salary >= 10001 && basic_salary <= 20000) {
uint256 hra = basic_salary * 25 / 100;
uint256 da = basic_salary * 90 / 100;
uint256 gross_salary_total = basic_salary + hra + da;
return gross_salary_total;
}
else if (basic_salary >= 20001) {
uint256 hra = basic_salary * 30 / 100;
uint256 da = basic_salary * 95 / 100;
uint256 gross_salary_total = basic_salary + hra + da;
return gross_salary_total;
}
}
}
5
Heetika Vaity Blockchain Lab SYMCA-57/B
OUTPUT:
6
Heetika Vaity Blockchain Lab SYMCA-57/B
contract q3 {
struct student {
uint256 rollNo;
string name;
string placedCompany;
string degreeCourse;
}
student[] s;
function addStudent(
uint256 rollNo,
string memory name,
string memory placedCompany,
string memory degreeCourse
)
public
{
s.push(student(rollNo, name, placedCompany, degreeCourse));
}
7
Heetika Vaity Blockchain Lab SYMCA-57/B
if (s[i].rollNo == rollNumber) {
return (s[i].rollNo, s[i].name);
}
}
return (s[0].rollNo, s[0].name); // Consider handling cases where
no student is found
}
function getAllStudents()
public
view
returns (student[] memory)
{
return s;
}
}
OUTPUT:
8
Heetika Vaity Blockchain Lab SYMCA-57/B
9
Heetika Vaity Blockchain Lab SYMCA-57/B
contract q4 {
struct Consumer {
uint256 units;
string name;
string addr;
uint256 consumerID;
uint256 amount;
}
Consumer[] consumer;
function addConsumerInfo(
uint256 units,
string memory name,
string memory addr,
uint256 consumerID
)
public
{
consumer.push(Consumer(units, name, addr, consumerID, 0));
}
10
Heetika Vaity Blockchain Lab SYMCA-57/B
uint256 i = 0;
uint256 amount = 0;
uint256 surcharge = 0;
uint256 units = 0;
11
Heetika Vaity Blockchain Lab SYMCA-57/B
return (
consumer[i].units,
consumer[i].name,
consumer[i].addr,
consumer[i].consumerID,
consumer[i].amount
);
}
}
return (
consumer[0].units,
consumer[0].name,
consumer[0].addr,
consumer[0].consumerID,
consumer[0].amount
);
}
function displayAllInfo()
public
view
returns (Consumer[] memory)
{
return consumer;
}
}
OUTPUT:
12
Heetika Vaity Blockchain Lab SYMCA-57/B
CONCLUSION:
Solidity and smart contracts represent a revolutionary approach to digital agreements and
automation. Their unique properties, such as transparency, immutability, and autonomy,
are paving the way for new business models and decentralized applications. As the
blockchain ecosystem continues to evolve, understanding these concepts becomes
increasingly essential for developers and businesses alike.
13
Name of Student : Heetika Mahesh Vaity
THEORY:
Truffle framework:
4. Network management for deploying to any number of public & private networks.
5. Package management with EthPM & NPM, using the ERC190 standard.
You can install Truffle with NPM in your command line like this:
Smart Contract:
A smart contract is a stand-alone script usually written in Solidity and compiled into binary
or JSON and deployed to a specific address on the blockchain. In the same way that we can
call a specific URL endpoint of a RESTful API to execute some logic through an HttpRequest,
we can similarly execute the deployed smart contract at a specific address by submitting
the correct data along with the necessary Ethereum to call the deployed and compiled
Solidity function.
1
Heetika Vaity Blockchain Lab SYMCA-57/B
→ 1. Install Node JS and Truffle Suite to develop and migrate the smart
contracts into the Private Blockchain network. Make use of Truffle tools
like compile, migrate and test for compilation, migration and testing the
smart contracts through Blockchain.
● Now that you have a private blockchain running, you need to configure your
environment for developing smart contracts.
● The first dependency you'll need is Node Package Manager, or NPM, which comes
with Node.js.
● You can see if you have node already installed by going to your terminal and typing:
$ node –v
● Otherwise, Download from: URL: https://nodejs.org/en/
Truffle Framework:
Truffle Framework, which provides a suite of tools for developing Ethereum smart contacts
with the Solidity programming language.
► Smart Contract Management
► Automated Testing
► Deployment & Migrations
► Network Management
► Script Runner
► Client Side Development
You can install Truffle with NPM in your command line like this:
2
Heetika Vaity Blockchain Lab SYMCA-57/B
package.json:
{
"name": "blockchain-toolkit-8",
"version": "1.0.0",
"description": "The Complete Blockchain Developer Toolkit for 2019 & Beyond",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "[email protected]",
"license": "ISC",
"devDependencies": {
"bootstrap": "4.1.3",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"chai-bignumber": "^2.0.2",
"dotenv": "^4.0.0",
"ganache-cli": "^6.1.8",
"lite-server": "^2.3.0",
"nodemon": "^1.17.3",
"solidity-coverage": "^0.4.15",
"truffle": "5.0.0-beta.0",
"truffle-contract": "3.0.6",
"truffle-hdwallet-provider": "^1.0.0-web3one.0"
}
}
3
Heetika Vaity Blockchain Lab SYMCA-57/B
$ npm install
► $ touch ./contracts/MyContract.sol
MyContract.sol:
pragma solidity >=0.4.2 <=0.8.17;
contract MyContract {
string value;
constructor() public {
value = "myValue";
}
function get() public view returns (string memory) {
return value;
4
Heetika Vaity Blockchain Lab SYMCA-57/B
}
function set(string memory _value) public {
value = _value;
}
}
Run:
► $ truffle compile
Update the project configuration file (Find the file truffle-config.js and paste the
following code:)
truffle-config.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
},
solc: {
optimizer: {
enabled: true,
runs: 200
}
}
}
5
Heetika Vaity Blockchain Lab SYMCA-57/B
Create a migration script inside the migrations directory to deploy the smart
contract to the personal blockchain network.
Run:
$ touch migrations/2_deploy_contracts.js
2_depoy_contracts.js:
var MyContract = artifacts.require("./MyContract.sol");
module.exports = function(deployer)
{
deployer.deploy(MyContract);
};
► truffle migrate
► $ truffle console
6
Heetika Vaity Blockchain Lab SYMCA-57/B
7
Heetika Vaity Blockchain Lab SYMCA-57/B
Go to cmd prompt
$ mkdir blockchain-toolkit-overloading
$ cd blockchain-toolkit-overloading
$ truffle init
$ touch package.json
package.json:
{
"name": "blockchain-toolkit-overloading",
"version": "1.0.0",
"description": "The Complete Blockchain Developer Toolkit for 2019 & Beyond",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "[email protected]",
"license": "ISC",
"devDependencies": {
"bootstrap": "4.1.3",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"chai-bignumber": "^2.0.2",
"dotenv": "^4.0.0",
"ganache-cli": "^6.1.8",
"lite-server": "^2.3.0",
"nodemon": "^1.17.3",
"solidity-coverage": "^0.4.15",
"truffle": "5.0.0-beta.0",
"truffle-contract": "3.0.6",
"truffle-hdwallet-provider": "^1.0.0-web3one.0"
}
}
8
Heetika Vaity Blockchain Lab SYMCA-57/B
npm install
Update the project config file( find truffle-config.js and paste the code)
truffle-config.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*", // Match any network id
},
},
solc: {
optimizer: {
enabled: true,
runs: 200,
},
},
};
In contracts folder:
overloading.js:
pragma solidity >=0.4.2 <=0.8.0;
contract overloading {
function getSum(uint a, uint b) public pure returns (uint) {
return a + b;
}
function getSum(
uint a,
uint b,
uint c
) public pure returns (uint) {
return a + b + c;
9
Heetika Vaity Blockchain Lab SYMCA-57/B
}
function callSumWithTwoArguments() public pure returns (uint) {
return getSum(1, 2);
}
function callSumWithThreeArguments() public pure returns (uint) {
return getSum(1, 2, 3);
}
}
In migration folder:
2_deploy_contracts.js:
var overloading = artifacts.require("./overloading.sol");
module.exports = function (deployer) {
deployer.deploy(overloading);
};
● truffle compile
● truffle migrate
10
Heetika Vaity Blockchain Lab SYMCA-57/B
● truffle console
overloading.deployed().then((instance) => {app = instance} )
app.getSum(5,6)
app.callSumWithTwoArguments()
app.callSumWithThreeArguments()
CONCLUSION:
Hence, we have successfully executed the smart contract using the truffle framework.
11
Name of Student : Heetika Mahesh Vaity
● Many of the advantages of dApps center around the program's ability to safeguard
user privacy. With decentralized apps, users do not need to submit their personal
information to use the function the app provides. DApps use smart contracts to
complete the transaction between two anonymous parties without the need to rely
on a central authority. • Proponents interested in free speech point out that dApps
can be developed as alternative social media platforms. A decentralized social
media platform would be resistant to censorship because no single participant on
the blockchain can delete messages or block messages from being posted.
● Ethereum is a flexible platform for creating new dApps, providing the infrastructure
needed for developers to focus their efforts on finding innovative uses for digital
applications. This could enable rapid deployment of dApps in a variety of industries
including banking and finance, gaming, social media, and online shopping
1
Heetika Vaity Blockchain Lab SYMCA-57/B
● test directory: this is where we'll write our tests for our smart contracts.
● truffle.js file: this is the main configuration file for our Truffle project
Steps to follow:
1. Create a project directory for our dApp in the command line like this:
$ mkdir election
$ cd election
2. Install truffle:
npm install -g truffle
3. From within your project directory, install the pet shop box from the command line
like this:
$ truffle unbox pet-shop
5. Migrate:
truffle migrate
7. inside the console, let's get an instance of our deployed smart contract and see if we
can read the candidate's name from the contract. From the console, run this code:
Election.deployed().then(function(instance) { app = instance })
Here Election is the name of the variable that we created in the migration file. We
retrieved a deployed instance of the contract with the deployed() function, and
assigned it to an app variable inside the promise's callback function.
9. Client-Side Application
$ truffle migrate --reset
10. Next, start your development server from the command line like this:
$ npm run dev or $ npm run start
2
Heetika Vaity Blockchain Lab SYMCA-57/B
SOURCE CODE:
1. contracts/Election.sol:
3
Heetika Vaity Blockchain Lab SYMCA-57/B
candidates[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
}
2. contracts/Migrations.sol:
3. Migrations/1_initial_migrations.js:
4. Migrations/2_deploy_contracts.js:
4
Heetika Vaity Blockchain Lab SYMCA-57/B
5. truffle-config.js:
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// for more about customizing your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop: {
port: 7545
}
}
};
6. test/election.js:
5
Heetika Vaity Blockchain Lab SYMCA-57/B
}).then(function(candidate) {
assert.equal(candidate[0], 2, "contains the correct id");
assert.equal(candidate[1], "Candidate 2", "contains the correct name");
assert.equal(candidate[2], 0, "contains the correct votes count");
});
});
6
Heetika Vaity Blockchain Lab SYMCA-57/B
}).then(function(candidate2) {
var voteCount = candidate2[2];
assert.equal(voteCount, 0, "candidate 2 did not receive any votes");
});
});
7. index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
7
Heetika Vaity Blockchain Lab SYMCA-57/B
<script
src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">Election Results</h1>
<hr/>
<br/>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="candidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
<div class="form-group">
<label for="candidatesSelect">Select Candidate</label>
<select class="form-control" id="candidatesSelect">
</select>
</div>
8
Heetika Vaity Blockchain Lab SYMCA-57/B
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
➢ cd election
➢ truffle migrate
9
Heetika Vaity Blockchain Lab SYMCA-57/B
10
Heetika Vaity Blockchain Lab SYMCA-57/B
➢ truffle console
➢ truffle test
11
Heetika Vaity Blockchain Lab SYMCA-57/B
12
Heetika Vaity Blockchain Lab SYMCA-57/B
OUTPUT:
CAST VOTE:
COUNT OF VOTES:
13
Heetika Vaity Blockchain Lab SYMCA-57/B
SOURCE CODE:
14
Heetika Vaity Blockchain Lab SYMCA-57/B
➢ npm install
15
Heetika Vaity Blockchain Lab SYMCA-57/B
➢ npm start
OUTPUT:
Create 4 accounts on metamask [import from ganache] and assign the private key
address to manufacturer, third party, delivery, customer:
Manufacturer: Account 3
Third Party: Account 4
Delivery Hub: Account 5
Customer: Account 6
also, connect website (http://localhost:3000) to all 4 account & switch account based
on the role
16
Heetika Vaity Blockchain Lab SYMCA-57/B
ADD ROLES:
CLICK ON CONFIRM:
17
Heetika Vaity Blockchain Lab SYMCA-57/B
MANUFACTURER:
ADD PRODUCT:
CONFIRM TRANSACTION:
18
Heetika Vaity Blockchain Lab SYMCA-57/B
EXPLORER:
CHECK WHETHER THE PRODUCT IS ADDED SUCCESSFULLY OR NOT:
19
Heetika Vaity Blockchain Lab SYMCA-57/B
THIRD PARTY:
BUY PRODUCT:
20
Heetika Vaity Blockchain Lab SYMCA-57/B
SHIP PRODUCT:
RECEIVE PRODUCT:
21
Heetika Vaity Blockchain Lab SYMCA-57/B
22
Heetika Vaity Blockchain Lab SYMCA-57/B
CUSTOMER:
PURCHASE PRODUCT:
THIRD PARTY:
PRODUCTS TO BE SHIPPED:
23
Heetika Vaity Blockchain Lab SYMCA-57/B
DELIVERY HUB:
Products To be Received:
24
Heetika Vaity Blockchain Lab SYMCA-57/B
25
Heetika Vaity Blockchain Lab SYMCA-57/B
DELIVERY HUB:
SHIP PRODUCT:
CUSTOMER:
RECEIVE:
26
Heetika Vaity Blockchain Lab SYMCA-57/B
CUSTOMER:
PRODUCT:
27
Heetika Vaity Blockchain Lab SYMCA-57/B
EXPLORER:
PRODUCT HISTORY: [ALL TRANSACTIONS]
CONCLUSION:
28
Name of Student : Heetika Mahesh Vaity
Abstract:
Blockchain technology has gained significant attention for its potential to revolutionize
various industries through its transparent, secure, and decentralized nature. This project
presents a proof of concept implementation of a blockchain system using Java, aiming to
explore the fundamental concepts and demonstrate the feasibility of a custom blockchain
implementation in a popular programming language. The dissertation provides an
overview of blockchain technology, the motivations behind the project, and a
comprehensive analysis of the design, implementation, and evaluation of the Java-based
blockchain system.
The project starts with a thorough literature review, encompassing the essential principles
of blockchain technology and prior efforts in implementing blockchains in Java. This
knowledge serves as the foundation for the project's methodology, guiding the selection of
suitable software tools and the design of the blockchain architecture. Key aspects of the
project include the data structures for blocks and transactions, the implementation of a
consensus mechanism (Proof of Work in this case), cryptographic techniques for securing
data, and optional features such as smart contracts.
The core implementation covers essential elements of a blockchain system, including the
data structure for blocks, transaction processing, block validation and mining, networking
with peer-to-peer communication, and security measures to safeguard the integrity of the
blockchain.
The results and evaluation section discusses the testing methodology, performance metrics,
and the validation of the proof of concept implementation. By evaluating the blockchain
system's performance and functionality, the project highlights its potential for practical
applications and identifies the challenges faced during the implementation process. The
evaluation is also presented alongside comparisons with existing blockchain solutions.
The discussion section interprets the project's findings, explores the implications of the
proof of concept, and delves into its practical applications and use cases. The limitations
and scalability of the Java-based blockchain are also discussed, providing insight into areas
for potential improvement and further research.
1
Heetika Vaity Blockchain Lab SYMCA-57/B
technology. This research project not only lays the groundwork for potential real-world
applications of Java-based blockchains but also serves as a valuable resource for future
research and enhancements in the field.
1. Introduction
2
Heetika Vaity Blockchain Lab SYMCA-57/B
limitations. The scope encompasses the design, implementation, testing, and evaluation of
the blockchain system, with an emphasis on understanding how blockchain technology can
be leveraged in a Java-based environment.
2. Implementation
2.1 Code
Block.java
package vesit.bc.mp.g1.poc_impl_blockchain;
import java.util.Date;
import vesit.bc.mp.g1.poc_impl_blockchain.utility.StringUtil;
3
Heetika Vaity Blockchain Lab SYMCA-57/B
utility/StringUtil.java
package vesit.bc.mp.g1.poc_impl_blockchain.utility;
import java.security.MessageDigest;
runner/Driver.java
package vesit.bc.mp.g1.poc_impl_blockchain.runner;
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
import vesit.bc.mp.g1.poc_impl_blockchain.Block;
4
Heetika Vaity Blockchain Lab SYMCA-57/B
5
Heetika Vaity Blockchain Lab SYMCA-57/B
2.2 Demo
3. Conclusion
In the implementation of the blockchain project, key objectives were achieved by leveraging
blockchain's decentralized, secure, and transparent nature. The project successfully
established a distributed ledger that ensures data immutability, providing tamper-proof
records and enhancing trust among participants. Smart contracts were implemented to
automate processes, reducing the need for intermediaries and increasing efficiency.
Additionally, security protocols like cryptography safeguarded transactions and user
identities. Overall, the blockchain integration demonstrated significant improvements in
transparency, security, and operational efficiency for the project's use case.