Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
74 views41 pages

Blockchain 2510793

Practical 4 implements ERC-20 token standard functions like totalSupply, balanceOf, transfer

Uploaded by

Colab Practical
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)
74 views41 pages

Blockchain 2510793

Practical 4 implements ERC-20 token standard functions like totalSupply, balanceOf, transfer

Uploaded by

Colab Practical
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
You are on page 1/ 41

SIES (NERUL) COLLEGE OF ARTS, SCIENCE AND

COMMERCE
NAAC ACCREDITED ‘A’ GRADE COLLEGE(ISO
9001:2015 CERTIFIED INSTITUTION) NERUL, NAVI
MUMBAI - 400706

Seat No: 2510793

Certified that MANASI SANTOSH MIRGAL______

Of Class M.SC.IT (PART 2) has duly completed the practical

course in the subject of ______BLOCKCHAIN___________

during the academic year 2021-2022 as per the syllabus

prescribed by the University of Mumbai.

Subject Teacher External Examiner

Head of Department Principal


PRACTICAL 1
Write the following programs for Blockchain in Python:
Aim: A. A simple client class that generates the private and public keys by using the built-in
Python RSA algorithm and test it.

# import libraries
import hashlib
import binascii
import datetime
import collections

# following imports are required by PKI


import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5

# ------- Client Class

class Client:
def __init__(self):
random = Crypto.Random.new().read
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)

@property
def identity(self):
return binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
B. A transaction class to send and receive money and test it.

# ------- Transaction Class

class Transaction:

def __init__(self, sender, recipient, value):


self.sender = sender
self.recipient = recipient
self.value = value
self.time = datetime.datetime.now()

def to_dict(self):
if self.sender == "Genesis":
identity = "Genesis"
else:
identity = self.sender.identity

return collections.OrderedDict({
'sender': identity,
'recipient': self.recipient,
'value': self.value,
'time' : self.time})

def sign_transaction(self):
private_key = self.sender._private_key
signer = PKCS1_v1_5.new(private_key)
h = SHA.new(str(self.to_dict()).encode('utf8'))
return binascii.hexlify(signer.sign(h)).decode('ascii')
C. Create multiple transactions and display them.

# ------- Creating Multiple Transactions


transactions = []
def display_transaction(transaction):
#for transaction in transactions:
dict = transaction.to_dict()
print ("sender: " + dict['sender'])
print ('-----')
print ("recipient: " + dict['recipient'])
print ('-----')
print ("value: " + str(dict['value']))
print ('-----')
print ("time: " + str(dict['time']))
print ('-----')
Owais = Client()
Sanjay = Client()
Ashwin = Client()
Nishant = Client()

t0 = Transaction ( t2.sign_transaction()
"Genesis", transactions.append(t2)
Owais.identity,
500.0 t3 = Transaction(
) Sanjay,
Nishant.identity,
t1 = Transaction( 2.0
Owais, )
Sanjay.identity, t3.sign_transaction()
15.0 transactions.append(t3)
)
t1.sign_transaction() t4 = Transaction(
transactions.append(t1) Ashwin,
Sanjay.identity,
t2 = Transaction( 4.0
Owais, )
Ashwin.identity, t4.sign_transaction()
6.0 transactions.append(t4)
)
t5 = Transaction( transactions.append(t9)
Nishant,
Ashwin.identity, t10 = Transaction(
7.0 Nishant,
) Sanjay.identity,
t5.sign_transaction() 3.0
transactions.append(t5) )
t10.sign_transaction()
t6 = Transaction( transactions.append(t10)
Sanjay,
Ashwin.identity, # signature = t1.sign_transaction()
3.0
) for transaction in transactions:
t6.sign_transaction() display_transaction (transaction)
transactions.append(t6) print ('--------------')

t7 = Transaction(
Ashwin,
Owais.identity,
8.0
)
t7.sign_transaction()
transactions.append(t7)

t8 = Transaction(
Ashwin,
Sanjay.identity,
1.0
)
t8.sign_transaction()
transactions.append(t8)

t9 = Transaction(
Nishant,
Owais.identity,
5.0
)
t9.sign_transaction()
D. Create a blockchain, a genesis block and execute it.

# ------- Block Class

class Block:
def __init__(self):
self.verified_transactions = []
self.previous_block_hash = ""
self.Nonce = ""
last_block_hash = ""

# ------- Creating Genesis Block

block0 = Block()
block0.previous_block_hash = None
Nonce = None
block0.verified_transactions.append (t0)
digest = hash (block0)
last_block_hash = digest

# ------- Adding Genesis Block

TPCoins = []
def dump_blockchain (self):
print ("Number of blocks in the chain: " + str(len (self)))
for x in range (len(TPCoins)):
block_temp = TPCoins[x]
print ("block # " + str(x))
for transaction in block_temp.verified_transactions:
print ('------dump_blockchain--------')
display_transaction (transaction)
print ('--------------')
print ('=====================================')

# ------- Adding Genesis Block

TPCoins.append (block0)
dump_blockchain(TPCoins)
E. Create a mining function and test it.

# ------- Creating Miners


def sha256(message):
return hashlib.sha256(message.encode('ascii')).hexdigest()
def mine(message, difficulty=1):
assert difficulty >= 1
prefix = '1' * difficulty
for i in range(1000):
digest = sha256(str(hash(message)) + str(i))
if digest.startswith(prefix):
print ("after " + str(i) + " iterations found nonce: "+ digest)
return digest
mine ("test message", 2)
F. Add blocks to the miner and dump the blockchain.

# ------- Adding Blocks


last_transaction_index = 0

# Miner 2 adds a block


block = Block()

for i in range(3):
temp_transaction = transactions[last_transaction_index]
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)
TPCoins.append (block)
last_block_hash = digest
# Miner 3 adds a block
block = Block()

for i in range(3):
temp_transaction = transactions[last_transaction_index]
#display_transaction (temp_transaction)
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1

block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)

TPCoins.append (block)
last_block_hash = digest
dump_blockchain(TPCoins)
PRACTICAL 2

Aim: Install and use Metamask wallet.

Go to the Chrome Web Store Extension section and search for Metamask.
Click on the Add to Chrome button.
Once the installation is complete, click on the Get Started button.
If this is your first time creating a wallet, create on the “Create Wallet” button.

If there is already a wallet, then click on the Import wallet button.


Create a password for your wallet. This password is to be entered every time this
application is launched.
Backup the secret phrase. It is the only way to access your wallet if you forget the
password.
Click on the next button
Click on the confirm button, and your wallet is created.
Click on Settings
Click on get ether and request some test ether from the faucet.

OUTPUT:
PRACTICAL 3
Implement and demonstrate the use of the following in Solidity:
1) Variable
pragma solidity ^0.5.0;
contract prac3a
{
uint sum = 4; //state variable
uint x;
address a;
string s = "welcome";

function add(uint x)public


{
uint y=2; //local variable
sum = sum+x+y;
}
function display() public view returns (uint)
{
return sum;
}
function displayMsg() public view returns (string memory)
{
return s;
}
}
OUTPUT:
2) Operators
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function add (uint x,uint y) public view returns(uint){
uint result = x + y;
return result;
}
function sub () public view returns(uint){
uint a = 8;
uint b = 3.0;
uint result = a - b;
return result;
}
function mul() public view returns(uint){
uint p = 3;
uint q = 5;
uint result = p * q;
return result;
}
function div() public view returns(uint){
uint s = 9;
uint t = 3;
uint result = s / t;
return result;
}
}
OUTPUT:
3) Loops
pragma solidity ^0.5.0;
contract Types {

uint[] data;
function loop() public returns(uint[] memory){
for(uint i=0; i<5; i++){
data.push(i);
}
return data;
}
}
OUTPUT:

While loop
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

// Declaring a dynamic array


uint[] data;

// Declaring state variable


uint8 j = 0;

// Defining a function to
// demonstrate While loop'
function loop(
) public returns(uint[] memory){
while(j < 5) {
j++;
data.push(j);
}
return data;
}
}
OUTPUT:
4) Decision Making
pragma solidity ^0.5.0;

// Creating a contract
contract Types {

// Declaring state variables


uint i = 10;
bool even;

// Defining function to
// demonstrate the use of
// 'if...else statement'
function decision_making(
) public payable returns(bool){
if(i%2 == 0){
even = true;
}
else{
even = false;
}
return even;
}

}
OUTPUT:
5) Arrays
Arrdemo1
pragma solidity ^0.5.0;
contract arraydemo1
{
uint [] arr1;
uint[6] arr2=[10,20,30];

function display() public view returns (uint[6] memory)


{
return arr2;
}
}
OUTPUT:
Arrdemo2
pragma solidity ^0.5.0;
contract arraydemo2
{
uint sum = 4; //state variable
uint x=5;
uint [] arr1;

function display() public view returns (uint[] memory)


{
return arr1;
}

function arraydemo() public


{
while(x>0)
{
arr1.push(x);
x=x-1;
}
}
}
OUTPUT:
6) Enums
Enumdemo
pragma solidity ^0.5.0;
contract enumDemo
{
enum week_days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

week_days week;
week_days choice;

//Setting a default value


week_days constant default_value = week_days.Sunday;

//Defining a function to set value of choice


function set_value() public
{
choice = week_days.Tuesday;
}

function get_choice() public view returns (week_days)


{
return choice;
}

//Defining function to return default value


function get_defaultvalue() public view returns (week_days)
{
return default_value;
}
}
OUTPUT:
Enumdemo1
pragma solidity ^0.5.0;
contract test
{
enum FreshJuiceSize{SMALL, MEDIUM, LARGE}
FreshJuiceSize choice;
FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

function setSize() public {


choice = FreshJuiceSize.SMALL;
}
function get_choice() public view returns (FreshJuiceSize) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}
}
OUTPUT:
7) Structs
pragma solidity ^0.5.0;
contract structDemo {

struct Book
{
string name;
string author;
uint id;
bool availability;
}

Book book2;

Book book1 = Book("A Little Life", "Hanya Yanagihara", 2, false);

function set_book_detail() public


{
book2 = Book("Almond", "Sohn Won-pyung", 1, true);
}

function book_info() public view returns (string memory, string memory, uint, bool)
{
return(book1.name, book1.author, book1.id, book1.availability);
}
function get_details() public view returns (string memory, uint)
{
return(book2.name, book2.id);
}
}
OUTPUT:
PRACTICAL 4
1) Pure Functions
pragma solidity ^0.5.0;

contract Test {

function getResult(
) public pure returns(
uint product, uint sum){
uint num1 = 2;
uint num2 = 4;
product = num1 * num2;
sum = num1 + num2;
}
}
OUTPUT:
2) Mathematical functions
pragma solidity ^0.5.0;

contract Test {
function callAddMod() public pure returns(uint){
return addmod(7, 3, 3);
}
function callMulMod() public pure returns(uint){
return mulmod(7, 3, 3);
}
}
OUTPUT:
3) Cryptographic function
pragma solidity ^0.5.0;

contract Test {
function callKeccak256() public pure returns(bytes32 result) {
return keccak256 ("DEVYANI");
}
function callsha256() public pure returns(bytes32 result) {
return sha256 ("DEVYANI");
}
function callripemd() public pure returns(bytes20 result) {
return ripemd160 ("DEVYANI");
}
}
OUTPUT:
PRACTICAL 5
Implement and demonstrate the use of the following in Solidity.
1) Inheritance
pragma solidity 0.5.0;

contract C {
uint private data;
uint public info;

constructor() public {
info = 10;
}

function increment (uint a) private pure returns(uint) {return a +1; }


function updateData(uint a) public {data = a; }
function getData() public view returns(uint) {return data; }
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
contract E is C {
uint private result;
C private c;

constructor() public {
c = new C();
}
function getComputedResult() public {
result = compute(3, 5);
}
function getResult() public view returns(uint) { return result; }
function getData() public view returns(uint) {return c.info(); }
}

contract D {
function readData() public returns(uint) {
C c = new C();
c.updateData(7);
return c.getData();
}
}
PRACTICAL 6
Implement and demonstrate the use of the following in Solidity
1) Assembly
//KEYWORD ‘assembly’

pragma solidity ^0.4.0;


contract Assembly_demo{
function add (uint a) view returns (uint b)
{ //Taking input
assembly {
let c:= add (a,16)
mstore (0x80, c){
let d := add(sload(c),12)
b:= d
}
b:=add(b,c)
}
}
}
PRACTICAL 7
Implement and demonstrate the use of the following in Solidity
1) Error Handling
pragma solidity ^0.8.0;

contract ErrorDemo{
function getSum(uint a, uint b) public pure returns(uint){
uint sum = a + b;
require(sum<255,"Invalid");
return sum;
}
}
PRACTICAL 8
Aim: Using Ganache with Remix
Remix IDE is a web browser-based IDE that allows you to write smart contracts in Solidity.
It also allows you to test, debug and deploy your smart contracts.
You can use Ganache to deploy your smart contract from Remix by following these steps:
1.Open Remix IDE in browser by navigating to http://remix.ethereum.org
2.Create a sample smart contract in solidity.
3.Compile the smart contract. Once it is compiled successfully go to deploy and run
transactions.
4. In the Environments drop down you will be able to see the following,
JavaScript VM, Injected Web3 and Web3 Provider.
5. Here, select Web3 provider which prompts you whether you want to connect to Ethereum
node. Clicking OK will gain prompt you to provide the Web3 provider endpoint.
6. Open Ganache. You can see HTTP URL under RPC server.

7. Copy it and paste it in Remix under Web3 provider endpoint. You should be able to
connect to Ganache with Remix.

8. If you have successfully connected to Ganache then you can see your 10 default Ganache
accounts each with 100 ether added into your remix.
9. Now click on deploy to deploy the contract to private Ethereum Blockchain using
Ganache.
10. Open Ganache and click on Transactions where your contract creation transaction will be
present.

Great you have deployed your smart contract in private Ethereum Blockchain.

Now, write a program using Remix IDE and deploy it.


pragma solidity >=0.5.0 <0.7.0;
contract HelloWorld {
function get()public pure returns (string memory){
return 'Hello Contracts';
}
}
Go over to Ganache and you will se that the blocks and transactions have been added to
reflect your input.

You might also like