migrate python3 + add cri blocks specific data

This commit is contained in:
Aurelien Rebourg 2023-04-27 18:04:14 +02:00
parent f23af007d8
commit 5f743a6b63
Signed by: Aurelien
GPG Key ID: F02826677ABB98C1
9 changed files with 207 additions and 175 deletions

1
.gitignore vendored
View File

@ -1,6 +1,7 @@
*.pyc
chain.txt
venv/
.venv/
build/
dist/
blockshell/

View File

@ -23,41 +23,32 @@ Latest Mined Blocks | Block Details
![](https://preview.ibb.co/iZa5jG/Screen_Shot_2018_01_25_at_11_25_22_PM.png) | ![](https://preview.ibb.co/cDB0Jb/Screen_Shot_2018_01_25_at_11_25_35_PM.png)
## 📦 Installation
Step 1 - Create project directory
```
mkdir <project_name> && cd project_name
```
Step 2 - Create new virtual environment with python version 2.7.
```
virtualenv venv
```
Step 3 - Activate virtual environment
```
source venv/bin/activate
```
or
```
source venv/Scripts/activate
```
Step 4 - Clone this repo
Step 1 - Clone this repo
```
git clone https://github.com/daxeel/blockshell.git
```
Step 5 - Change directory to cloned one
Step 2 - Change directory to cloned one
```
cd blockshell
```
Step 6 - Install blockshell
Step 3 - Create virtualenv
```
python3 -m venv .venv
```
Step 4 - Enable virtualenv
```
source .venv/bin/activate
```
Step 5 - Install blockshell
```
pip install --editable .
```
Step 7 - Try "blockshell" command and test installation!
Step 6 - Try "blockshell" command and test installation!
```
blockshell
```

View File

@ -12,12 +12,16 @@ __maintainer__ = "Daxeel Soni"
# ==================================================
# ================= IMPORT MODULES =================
# ==================================================
import os
import hashlib
import datetime
import json
from colorama import Fore, Back, Style
import time
import sys
import base64
from numpy import random
from PIL import Image
# ==================================================
# =================== BLOCK CLASS ==================
@ -26,26 +30,52 @@ class Block:
"""
Create a new block in chain with metadata
"""
def __init__(self, data, index=0):
self.index = index
def __init__(self):
self.index = -1
self.previousHash = ""
self.data = data
self.uid_epita = -1
self.email_epita = ""
self.firstname = ""
self.lastname = ""
self.image = ""
self.timestamp = str(datetime.datetime.now())
self.nonce = 0
self.hash = self.calculateHash()
@classmethod
def fromSave(cls, data):
block = cls()
for key, value in data.items():
setattr(block, key, value)
return block
@classmethod
def fromValues(cls, uid_epita, email_epita, firstname, lastname, index = 0):
block = cls()
block.index = index
block.uid_epita = uid_epita
block.email_epita = email_epita
block.firstname = firstname
block.lastname = lastname
block.createRandomImage()
return block
def calculateHash(self):
"""
Method to calculate hash from metadata
"""
hashData = str(self.index) + str(self.data) + self.timestamp + self.previousHash + str(self.nonce)
return hashlib.sha256(hashData).hexdigest()
hashData = str(self.index) + str(self.previousHash) + str(self.uid_epita) + str(self.email_epita) + str(self.firstname) + str(self.lastname) + str(self.image) + str(self.timestamp) + str(self.nonce)
return hashlib.sha256(hashData.encode('utf-8')).hexdigest()
def mineBlock(self, difficulty):
"""
Method for Proof of Work
"""
print Back.RED + "\n[Status] Mining block (" + str(self.index) + ") with PoW ..."
print(Back.RED + "\n[Status] Mining block (" + str(self.index) + ") with PoW ...")
startTime = time.time()
while self.hash[:difficulty] != "0"*difficulty:
@ -53,9 +83,22 @@ class Block:
self.hash = self.calculateHash()
endTime = time.time()
print Back.BLUE + "[ Info ] Time Elapsed : " + str(endTime - startTime) + " seconds."
print Back.BLUE + "[ Info ] Mined Hash : " + self.hash
print Style.RESET_ALL
print(Back.BLUE + "[ Info ] Time Elapsed : " + str(endTime - startTime) + " seconds.")
print(Back.BLUE + "[ Info ] Mined Hash : " + self.hash)
print(Style.RESET_ALL)
def createRandomImage(self):
"""
Method to create random image in base64
"""
imgarray = random.rand(30, 30, 3) * 255
image = Image.fromarray(imgarray.astype('uint8')).convert('RGB')
image.save('random.png')
with open("random.png", "rb") as imageFile:
self.image = str(base64.b64encode(imageFile.read()))
if os.path.exists("random.png"):
os.remove("random.png")
# ==================================================
# ================ BLOCKCHAIN CLASS ================
@ -72,7 +115,7 @@ class Blockchain:
"""
Method create genesis block
"""
return Block("Genesis Block")
return Block.fromValues(-1, "init@epita.fr", "Genesis", "Block")
def addBlock(self, newBlock):
"""
@ -88,9 +131,24 @@ class Blockchain:
"""
Method to write new mined block to blockchain
"""
dataFile = file("chain.txt", "w")
chainData = []
for eachBlock in self.chain:
chainData.append(eachBlock.__dict__)
dataFile.write(json.dumps(chainData, indent=4))
dataFile.close()
with open("chain.txt", "w") as dataFile:
chainData = []
for eachBlock in self.chain:
chainData.append(eachBlock.__dict__)
dataFile.write(json.dumps(chainData, indent=4))
def loadBlocks(self, filename):
"""
Method to load existing blockchain from file
"""
try:
with open(filename, "r") as dataFile:
chainData = json.loads(dataFile.read())
self.chain = []
for eachBlock in chainData:
self.chain.append(Block.fromSave(eachBlock))
except Exception as e:
print(Back.RED + "[Error] No existing blockchain found.")
print(Back.RED + "[Error] Creating new blockchain.")
print(Style.RESET_ALL)
self.writeBlocks()

103
bscli.py
View File

@ -16,6 +16,7 @@ import click
import urllib
import json
from blockchain.chain import Block, Blockchain
from colorama import Fore, Back, Style
# ==================================================
# ===== SUPPORTED COMMANDS LIST IN BLOCKSHELL ======
@ -27,6 +28,31 @@ SUPPORTED_COMMANDS = [
'help'
]
def printLogo():
print("""
____ _ _ _____ _ _ _
| _ \ | | | | / ____| | | | | | |
| |_) | | | ___ ___ | | __ | (___ | |__ ___ | | | |
| _ < | | / _ \ / __| | |/ / \___ \ | '_ \ / _ \ | | | |
| |_) | | | | (_) | | (__ | < ____) | | | | | | __/ | | | |
|____/ |_| \___/ \___| |_|\_\ |_____/ |_| |_| \___| |_| |_|
> A command line utility for learning Blockchain concepts.
> Type 'help' to see supported commands.
> Project by Daxeel Soni - https://daxeel.github.io
""")
def startShell():
"""
Method to start Blockshell CLI
"""
printLogo()
# Start blockshell shell
while True:
cmd = input("[BlockShell] $ ")
processInput(cmd)
# Init blockchain
coin = Blockchain()
@ -45,37 +71,39 @@ def cli():
@click.option("--difficulty", default=3, help="Define difficulty level of blockchain.")
def init(difficulty):
"""Initialize local blockchain"""
print """
____ _ _ _____ _ _ _
| _ \ | | | | / ____| | | | | | |
| |_) | | | ___ ___ | | __ | (___ | |__ ___ | | | |
| _ < | | / _ \ / __| | |/ / \___ \ | '_ \ / _ \ | | | |
| |_) | | | | (_) | | (__ | < ____) | | | | | | __/ | | | |
|____/ |_| \___/ \___| |_|\_\ |_____/ |_| |_| \___| |_| |_|
> A command line utility for learning Blockchain concepts.
> Type 'help' to see supported commands.
> Project by Daxeel Soni - https://daxeel.github.io
coin.writeBlocks()
# Set difficulty of blockchain
coin.difficulty = difficulty
"""
# Start blockshell shell
startShell()
@cli.command()
@click.argument("filename", type=click.Path(exists=True))
@click.option("--difficulty", default=3, help="Define difficulty level of blockchain.")
def load(filename, difficulty):
"""Load blockchain from file"""
# Load blockchain from file
coin.loadBlocks(filename)
# Set difficulty of blockchain
coin.difficulty = difficulty
# Start blockshell shell
while True:
cmd = raw_input("[BlockShell] $ ")
processInput(cmd)
startShell()
# Process input from Blockshell shell
def processInput(cmd):
"""
Method to process user input from Blockshell CLI.
"""
userCmd = cmd.split(" ")[0]
if len(cmd) > 0:
splitted = cmd.split(" ")
userCmd = splitted[0]
if len(splitted) and len(userCmd) > 0:
if userCmd in SUPPORTED_COMMANDS:
globals()[userCmd](cmd)
globals()[userCmd](splitted[1:])
else:
# error
msg = "Command not found. Try help command for documentation"
@ -85,47 +113,50 @@ def processInput(cmd):
# ==================================================
# =========== BLOCKSHELL COMMAND METHODS ===========
# ==================================================
def dotx(cmd):
def dotx(args):
"""
Do Transaction - Method to perform new transaction on blockchain.
"""
txData = cmd.split("dotx ")[-1]
if "{" in txData:
txData = json.loads(txData)
print "Doing transaction..."
coin.addBlock(Block(data=txData))
print("Doing transaction...")
coin.addBlock(Block.fromValues(int(args[0]), args[1], args[2], args[3]))
def allblocks(cmd):
"""
Method to list all mined blocks.
"""
print ""
print("")
for eachBlock in coin.chain:
print eachBlock.hash
print ""
print(eachBlock.hash)
print("")
def getblock(cmd):
def getblock(args):
"""
Method to fetch the details of block for given hash.
"""
blockHash = cmd.split(" ")[-1]
blockHash = args[0]
for eachBlock in coin.chain:
if eachBlock.hash == blockHash:
print ""
print eachBlock.__dict__
print ""
print("")
print(eachBlock.__dict__)
print("")
def help(cmd):
"""
Method to display supported commands in Blockshell
"""
print "Commands:"
print " dotx <transaction data> Create new transaction"
print " allblocks Fetch all mined blocks in blockchain"
print " getblock <block hash> Fetch information about particular block"
print("Commands:")
print(" dotx <uid> <mail> <firstname> <lastname> Create new transaction")
print(" allblocks Fetch all mined blocks in blockchain")
print(" getblock <block hash> Fetch information about particular block")
def throwError(msg):
"""
Method to throw an error from Blockshell.
"""
print "Error : " + msg
print(f"{ Fore.RED }{ msg }{ Fore.RESET }")
def printSuccess(msg):
"""
Method to print success message from Blockshell.
"""
print(f"{ Fore.GREEN }{ msg }{ Fore.RESET }")

View File

@ -11,7 +11,9 @@ setup(
install_requires=[
'Click',
'colorama',
'flask'
'flask',
'numpy',
'Pillow'
],
entry_points='''
[console_scripts]

View File

@ -7,7 +7,7 @@
<meta name="author" content="Daxeel Soni">
<title>Blockshell | Block Data</title>
<!-- Bootstrap core CSS -->
<link href="https://blackrockdigital.github.io/startbootstrap-bare/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<!-- Custom styles for this template -->
<style>
body {
@ -53,9 +53,12 @@
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-10" style="margin-top:20px;">
<h2><span class="badge badge-primary">{{data['hash']}}</span></h2>
<div class="col-lg-12" style="margin-top:20px;">
<h2><span class="badge bg-primary">{{data['hash']}}</span></h2>
<br>
<div class="d-flex justify-content-center" style="height: 8rem;">
<img src="data:image/png;base64,{{data['image64']}}" class="img-thumbnail" alt="Block image" style="image-rendering: pixelated;" height="100%">
</div>
<table class="table table-dark table-striped">
<tr>
<td><b>Height</b></td>
@ -66,8 +69,20 @@
<td>{{data['timestamp']}}</td>
</tr>
<tr>
<td><b>Data</b></td>
<td>{{data['data']}}</td>
<td><b>EPITA UID</b></td>
<td>{{data['uid_epita']}}</td>
</tr>
<tr>
<td><b>EPITA email</b></td>
<td>{{data['email_epita']}}</td>
</tr>
<tr>
<td><b>Firstname</b></td>
<td>{{data['firstname']}}</td>
</tr>
<tr>
<td><b>Lastname</b></td>
<td>{{data['lastname']}}</td>
</tr>
<tr>
<td><b>Hash</b></td>
@ -85,52 +100,13 @@
<p class="lead">
</p>
</div>
<div class="col-lg-2" style="margin-top:30px;">
<div class="card" style="width: 13rem;">
<img class="card-img-top" src="https://preview.ibb.co/e7SO4G/Logomakr_1rc0_PA.png" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">About Project</h5>
<p class="card-text">Project BlockShell is created by with a vision to teach blockchain concepts to students and programmers.</p>
<a href="https://daxeel.github.io" target="_blank" class="btn btn-primary">Contact Creator</a>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Blockshell Creator</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<img class="card-img-top" src="https://image.ibb.co/nqzp4w/Daxeel_3.jpg" alt="Card image cap">
<br><br>
<a href="https://daxeel.github.io" target="_blank" class="btn btn-primary col-md-12">View Profile</a>
</div>
<div class="col-md-8">
<h5 class="card-title">Daxeel Soni</h5>
<p class="card-text">Young software engineer and with the passion of startup product building using tech skills. I am a co-lead of Facebook Developers Circle, Ahmedabad. A technology educator and speaker invited to various institutes and events such as IIM, Nirma, Google Developers Group, Facebook events etc.</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- <footer class="fixed-bottom">
<p>Project by <a href="https://daxeel.github.io" target="_blank">Daxeel Soni</a></p>
</footer> -->
<!-- Bootstrap core JavaScript -->
<script src="https://blackrockdigital.github.io/startbootstrap-bare/vendor/jquery/jquery.min.js"></script>
<script src="https://blackrockdigital.github.io/startbootstrap-bare/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
</body>
</html>

View File

@ -7,7 +7,7 @@
<meta name="author" content="Daxeel Soni">
<title>Blockshell | All Blocks</title>
<!-- Bootstrap core CSS -->
<link href="https://blackrockdigital.github.io/startbootstrap-bare/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<!-- Custom styles for this template -->
<style>
body {
@ -53,62 +53,32 @@
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-10" style="margin-top:20px;">
<h1><span class="badge badge-primary">Latest Blocks</span></h1>
{% for item in data -%}
<div class="alert alert-success" role="alert">
<a href="/block/{{item.hash}}" target="_blank">{{ item.hash }}</a>
</div>
{%- endfor %}
<p class="lead">
</p>
</div>
<div class="col-lg-2" style="margin-top:80px;">
<div class="card" style="width: 13rem;">
<img class="card-img-top" src="https://preview.ibb.co/e7SO4G/Logomakr_1rc0_PA.png" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">About Project</h5>
<p class="card-text">Project BlockShell is created by with a vision to teach blockchain concepts to students and programmers.</p>
<a href="https://daxeel.github.io" target="_blank" class="btn btn-primary">Contact Creator</a>
<h1><span class="badge bg-primary">Latest Blocks</span></h1>
{% for item in data -%}
<div class="col-md-3">
<a href="/block/{{item.hash}}" class="btn" target="_blank">
<div class="card h-100" style="width: 8rem;">
<img src="data:image/png;base64, {{ item.image64 }}" style="image-rendering: pixelated;" class="card-img-top" alt="...">
<div class="card-body">
<h6 class="card-title">Block {{ item.index }}</h6>
<small>{{ item.firstname }} {{ item.name }}</small>
</div>
<div class="card-footer">
<small class="text-muted">{{ item.hash }}</small>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Blockshell Creator</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<img class="card-img-top" src="https://image.ibb.co/nqzp4w/Daxeel_3.jpg" alt="Card image cap">
<br><br>
<a href="https://daxeel.github.io" target="_blank" class="btn btn-primary col-md-12">View Profile</a>
</div>
<div class="col-md-8">
<h5 class="card-title">Daxeel Soni</h5>
<p class="card-text">Young software engineer and with the passion of startup product building using tech skills. I am a co-lead of Facebook Developers Circle, Ahmedabad. A technology educator and speaker invited to various institutes and events such as IIM, Nirma, Google Developers Group, Facebook events etc.</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</a>
</div>
{%- endfor %}
<p class="lead">
</p>
</div>
</div>
<!-- <footer class="fixed-bottom">
<p>Project by <a href="https://daxeel.github.io" target="_blank">Daxeel Soni</a></p>
</footer> -->
<!-- Bootstrap core JavaScript -->
<script src="https://blackrockdigital.github.io/startbootstrap-bare/vendor/jquery/jquery.min.js"></script>
<script src="https://blackrockdigital.github.io/startbootstrap-bare/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
</body>
</html>

View File

@ -7,7 +7,7 @@
<meta name="author" content="Daxeel Soni">
<title>Blockshell | All Blocks</title>
<!-- Bootstrap core CSS -->
<link href="https://blackrockdigital.github.io/startbootstrap-bare/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<!-- Custom styles for this template -->
<style>
body {
@ -173,7 +173,7 @@
<p>Project by <a href="https://daxeel.github.io" target="_blank">Daxeel Soni</a></p>
</footer> -->
<!-- Bootstrap core JavaScript -->
<script src="https://blackrockdigital.github.io/startbootstrap-bare/vendor/jquery/jquery.min.js"></script>
<script src="https://blackrockdigital.github.io/startbootstrap-bare/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
</body>
</html>

3
web.py
View File

@ -30,6 +30,8 @@ def mined_blocks():
f = open("chain.txt", "r")
data = json.loads(f.read())
f.close()
for item in data:
item['image64'] = item['image'][2:-1]
return render_template('blocks.html', data=data)
@app.route('/block/<hash>')
@ -42,6 +44,7 @@ def block(hash):
f.close()
for eachBlock in data:
if eachBlock['hash'] == hash:
eachBlock['image64'] = eachBlock['image'][2:-1]
return render_template('blockdata.html', data=eachBlock)
# Run flask app