0% found this document useful (0 votes)
21 views16 pages

Exp-5 200

Blockchain KJSCE Exp 5

Uploaded by

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

Exp-5 200

Blockchain KJSCE Exp 5

Uploaded by

asmi.takle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

K. J.

Somaiya College of Engineering, Mumbai-77


Department of Computer Engineering

Title: Creation of a private block chain cryptocurrency


Batch: BCT-3 Roll No.: 16010121200
Objective: Creation of a private block chain cryptocurrency
Experiment No. 5
Expected Outcome of Experiment:

CO Outcome

CO1 Describe the basic concepts of Blockchain and Distributed Ledger Technology.

CO5 Design a private Blockchain platform.

Books/ Journals/ Websites referred:


1. https://rejolut.com/blog/creating-your-own-blockchain-network/

2. https://ideausher.com/blog/how-to-make-a-private-blockchain/

3. https://youtu.be/mYlHT9bB6OE

4. https://www.smashingmagazine.com/2020/02/cryptocurrency-blockchain-node-js/

Abstract:

Centralized ledger: A centralized ledger is a database administered and controlled by a single entity, such as a business, government body, or

financial institution. All data is stored in a single location in a centralized ledger system, and access to that data is controlled by authorized individuals

or institutions.

Cryptocurrency: Cryptocurrency, sometimes called crypto-currency or crypto, is any form of currency that exists digitally or virtually and uses

cryptography to secure transactions. Cryptocurrencies don't have a central issuing or regulating authority, instead using a decentralized system to

record transactions and issue new units.

Types of cryptocurrencies:

1. Binance Coin (BNB): Binance Coin is native to Binance, the world’s largest cryptocurrency exchange as of 2024. Transaction fees for

this exchange are reduced for users who choose to pay in BNB. This has encouraged the adoption of Binance Coin, making it one of the

largest crypto coins in the market. To ensure its value remains stable, Binance destroys or “burns” a fixed percentage of the coins in

circulation.

2. Tether (USDT): Tether is a type of stablecoin, designed to have a less-volatile price by being linked to an external asset. In this case, each

coin is backed by an equivalent number of US dollars, which keeps it from experiencing the same kind of pricing volatility that other

cryptocurrencies face. There is however, some debate about whether it truly is fully backed by the dollar.

3. Solana (SOL): SOL is the native coin of the Solana platform, which functions on a blockchain system, just like Ethereum and Bitcoin.

Solana’s network can perform a whopping 50,000 transactions per second, making this platform especially attractive to investors looking

to trade quickly.

Related Theory: -

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 1
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

Coins: A coin is any cryptocurrency that uses its own independent blockchain. For example, Bitcoin is considered a “coin” because it runs on its own

infrastructure. Similarly, Ether is operated via the Ethereum blockchain.

What Are Coins Used for? When Bitcoin was created, it was envisioned as a replacement for traditional fiat currencies. Along with other crypto

coins, it was designed to work in the same ways as paper money and metal coins, meaning it can be used for many of the things normally used with US

dollars or euros, including:

 Storing value
 Exchanging for other currencies
 Paying for goods and services
 Transferring to others

Tokens: Like coins, tokens are also digital assets that can be bought and sold. However, tokens are a non-native asset, meaning that they use another

blockchain’s infrastructure. These include Tether, which is hosted on the Ethereum blockchain, and others, including Chainlink, Uniswap, and

Polygon.

What Are Tokens Used For? Most crypto tokens are designed to be used within a blockchain project or decentralized app (dapp). Unlike crypto

coins, tokens aren’t mined; they are created and distributed by the project developer. Once tokens are in the hands of purchasers, they can be used in

countless ways.

UTXO Model: An unspent transaction output (UTXO) is the amount of digital currency that remains after a cryptocurrency transaction. You can think

of it as the change you receive after buying an item, but it is not a lower denomination of the currency—it is a transaction output in the database

generated by the network to allow for non-exact change transactions.

Geth (go-ethereum): It is a Go implementation of Ethereum - a gateway into the decentralized web. Geth has been a core part of Ethereum since the

very beginning. Geth was one of the original Ethereum implementations making it the most battle-hardened and tested client. Geth is an Ethereum

execution client meaning it handles transactions, deployment and execution of smart contracts and contains an embedded computer known as the

Ethereum Virtual Machine. Running Geth alongside a consensus client turns a computer into an Ethereum node.

Implementation:

The following is the app.py

import hashlib

import json

import random

import string

import rsa

import base64

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 2
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

from flask import Flask, render_template, request, jsonify

# Utility function to hash data

def hash_data(data):

return hashlib.sha256(data.encode('utf-8')).hexdigest()

# Function to generate a random transaction ID

def generate_transaction_id():

return ''.join(random.choices(string.digits + string.ascii_uppercase, k=6))

# Sign and Verify

def sign_data(private_key, message):

signature = rsa.sign(message.encode('utf-8'), private_key, 'SHA-256')

return base64.b64encode(signature).decode('utf-8') # Convert bytes to base64 string

def verify_sign(public_key, message, signature):

try:

signature_bytes = base64.b64decode(signature.encode('utf-8')) # Convert base64 string back to bytes

rsa.verify(message.encode('utf-8'), signature_bytes, public_key)

return True

except:

return False

# Transaction class

class Transaction:

def __init__(self, transaction_id, sender, receiver, value, signature=None):

self.transaction_id = transaction_id

self.sender = sender

self.receiver = receiver

self.value = value

self.signature = signature

def to_dict(self):

return {

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 3
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

'transaction_id': self.transaction_id,

'sender': self.sender,

'receiver': self.receiver,

'value': self.value,

'signature': self.signature # Now this will be a base64 string

# Block class

class Block:

def __init__(self, index, transactions, previous_hash):

self.index = index

self.transactions = transactions

self.previous_hash = previous_hash

self.nonce = 0

self.hash = self.compute_hash()

def compute_hash(self):

block_dict = self.__dict__.copy()

block_dict['transactions'] = [tx.to_dict() for tx in self.transactions]

block_string = json.dumps(block_dict, sort_keys=True)

return hash_data(block_string)

def mine_block(self, difficulty=4):

target = '0' * difficulty

while self.hash[:difficulty] != target:

self.nonce += 1

self.hash = self.compute_hash()

# Blockchain class

class Blockchain:

def __init__(self):

self.chain = []

self.utxos = {} # Unspent Transaction Outputs

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 4
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

self.transaction_cost = 5

self.create_genesis_block()

def create_genesis_block(self):

genesis_block = Block(0, [], "0")

genesis_block.hash = "0" # Set hash to "0" for genesis block

genesis_block.nonce = 0 # Set nonce to 0 for genesis block

self.chain.append(genesis_block)

def add_block(self, transactions):

previous_block = self.chain[-1]

new_block = Block(len(self.chain), transactions, previous_block.hash)

new_block.mine_block(4) # Mine with difficulty 4

self.chain.append(new_block)

def update_chain_hashes(self, start_index):

for i in range(start_index, len(self.chain)):

if i > 0: # Skip genesis block

self.chain[i].previous_hash = self.chain[i - 1].hash

self.chain[i].hash = self.chain[i].compute_hash()

self.chain[i].mine_block(4) # Re-mine the block

def get_chain(self):

chain_data = []

for block in self.chain:

block_dict = block.__dict__.copy()

block_dict['transactions'] = [tx.to_dict() for tx in block.transactions]

chain_data.append(block_dict)

return chain_data

def update_utxos(self, transaction):

# If sender doesn't exist, add them with a balance of 100

if transaction.sender not in self.utxos:

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 5
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

self.utxos[transaction.sender] = 100

# If receiver doesn't exist, add them with a balance of 100

if transaction.receiver not in self.utxos:

self.utxos[transaction.receiver] = 100

# Sender must have enough UTXOs to cover value + transaction cost

total_amount = transaction.value + self.transaction_cost

sender_utxos = self.utxos[transaction.sender]

if sender_utxos >= total_amount:

self.utxos[transaction.sender] = sender_utxos - total_amount

self.utxos[transaction.receiver] += transaction.value

return True

return False

def add_transaction(self, transaction, private_key):

if self.update_utxos(transaction):

transaction.signature = sign_data(private_key, transaction.transaction_id)

self.chain[-1].transactions.append(transaction)

self.update_chain_hashes(len(self.chain) - 1)

return True

return False

def get_utxos(self):

return self.utxos

app = Flask(__name__)

blockchain = Blockchain()

@app.route('/')

def index():

return render_template('index.html', chain=blockchain.get_chain())

@app.route('/add_transaction', methods=['POST'])

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 6
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

def add_transaction():

block_index = int(request.form['block_index'])

transaction_id = generate_transaction_id()

sender = request.form['sender']

receiver = request.form['receiver']

value = float(request.form['value'])

# RSA key generation for signing (this would be done securely in production)

(public_key, private_key) = rsa.newkeys(512)

if 0 < block_index < len(blockchain.chain): # Prevent adding to genesis block

new_transaction = Transaction(transaction_id, sender, receiver, value)

if blockchain.add_transaction(new_transaction, private_key):

return jsonify(success=True)

else:

return jsonify(success=False, message="Insufficient balance")

else:

return jsonify(success=False, message="Invalid block index or cannot modify genesis block")

@app.route('/create_block', methods=['POST'])

def create_block():

blockchain.add_block([])

return jsonify(success=True)

@app.route('/get_chain')

def get_chain():

return jsonify(chain=blockchain.get_chain())

@app.route('/get_utxos')

def get_utxos():

return jsonify(utxos=blockchain.get_utxos())

@app.route('/get_balances')

def get_balances():

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 7
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

return jsonify(balances=blockchain.get_utxos())

if __name__ == '__main__':

app.run(debug=True)

The following is the templates/index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Blockchain Simulation</title>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<style>

body {

background-color: #f8f9fa;

padding-top: 2rem;

.block {

background-color: #ffffff;

border-radius: 0.5rem;

box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);

margin-bottom: 1.5rem;

transition: all 0.3s ease;

.block:hover {

transform: translateY(-5px);

box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);

.block-header {

background-color: #007bff;

color: white;

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 8
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

padding: 0.75rem;

border-top-left-radius: 0.5rem;

border-top-right-radius: 0.5rem;

.block-content {

padding: 1rem;

.transaction-list {

max-height: 200px;

overflow-y: auto;

.hash-value {

word-break: break-all;

font-size: 0.8rem;

.balances {

background-color: #28a745;

color: white;

padding: 1rem;

border-radius: 0.5rem;

margin-bottom: 1.5rem;

.input-group {

margin-bottom: 1rem;

.btn-primary, .btn-success {

margin-top: 1rem;

</style>

</head>

<body>

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 9
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

<div class="container">

<h1 class="text-center mb-4">Blockchain Simulation</h1>

<div id="balances" class="balances mb-4">

<h3>User Balances</h3>

<div id="balance-list"></div>

</div>

<div class="text-center mb-4">

<button class="btn btn-primary" onclick="createBlock()">Create New Block</button>

</div>

<div id="blockchain" class="row"></div>

</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

<script>

let blockchain = [];

function createBlock() {

fetch('/create_block', {method: 'POST'})

.then(response => response.json())

.then(data => {

if (data.success) {

renderBlockchain();

renderBalances();

});

function addTransaction(blockIndex) {

const sender = document.getElementById(`sender-${blockIndex}`).value;

const receiver = document.getElementById(`receiver-${blockIndex}`).value;

const value = parseFloat(document.getElementById(`value-${blockIndex}`).value);

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 10
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

if (sender && receiver && !isNaN(value)) {

fetch('/add_transaction', {

method: 'POST',

headers: {

'Content-Type': 'application/x-www-form-urlencoded',

},

body: `block_index=${blockIndex}&sender=${sender}&receiver=${receiver}&value=${value}`

})

.then(response => response.json())

.then(data => {

if (data.success) {

renderBlockchain();

renderBalances();

} else {

alert('Failed to add transaction: ' + data.message);

});

function renderBlockchain() {

fetch('/get_chain')

.then(response => response.json())

.then(data => {

blockchain = data.chain;

const blockchainContainer = document.getElementById('blockchain');

blockchainContainer.innerHTML = '';

blockchain.forEach((block, blockIndex) => {

const blockElement = document.createElement('div');

blockElement.className = 'col-md-6 col-lg-4 mb-4';

blockElement.innerHTML = `

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 11
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

<div class="block">

<div class="block-header">

<h4 class="m-0">Block ${block.index}</h4>

</div>

<div class="block-content">

<p><strong>Previous Hash:</strong> <br><span class="hash-value">${block.previous_hash}</span></p>

<p><strong>Hash:</strong> <br><span class="hash-value">${block.hash}</span></p>

<p><strong>Nonce:</strong> ${block.nonce}</p>

<h5>Transactions</h5>

<div class="transaction-list mb-3">

${block.transactions.map((tx) => `

<div class="mb-2">

<div><strong>Transaction:</strong> ${tx.sender} ${tx.receiver} ${tx.value}</div>

</div>

`).join('')}

</div>

${blockIndex > 0 ? `

<div class="input-group mb-2">

<input type="text" class="form-control" id="sender-${blockIndex}" placeholder="Sender">

<input type="text" class="form-control" id="receiver-${blockIndex}" placeholder="Receiver">

<input type="number" class="form-control" id="value-${blockIndex}" placeholder="Value">

</div>

<button class="btn btn-success w-100" onclick="addTransaction( ${blockIndex})">Add

Transaction</button>

` : ''}

</div>

</div>

`;

blockchainContainer.appendChild(blockElement);

});

});

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 12
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

function renderBalances() {

fetch('/get_balances')

.then(response => response.json())

.then(data => {

const balanceListContainer = document.getElementById('balance-list');

balanceListContainer.innerHTML = '';

for (const [user, balance] of Object.entries(data.balances)) {

balanceListContainer.innerHTML += `<p><strong>${user}:</strong> ${balance}</p>`;

});

document.addEventListener('DOMContentLoaded', () => {

renderBlockchain();

renderBalances();

});

</script>

</body>

</html>

Screenshots:

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 13
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 14
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 15
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering

Conclusion:

Successfully implemented a private block of cryptocurrency by ensuring each new block is connected to the previous block, forming a secure and

continuous cryptocurrency along with the UTXO model and the transaction fees deducting from the sender side.

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 16

You might also like