Blockshell launched

This commit is contained in:
Daxeel Soni 2018-01-25 16:04:48 +05:30
parent ec29d01e9d
commit a11085e9bd
4 changed files with 167 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.pyc

56
blockshell.py Normal file
View File

@ -0,0 +1,56 @@
import hashlib
import datetime
import json
from colorama import Fore, Back, Style
import time
# index, timestamp, previousHash, blockHash, data
class Block:
def __init__(self, data, index=0):
self.index = index
self.previousHash = ""
self.data = data
self.timestamp = str(datetime.datetime.now())
self.nonce = 0
self.hash = self.calculateHash()
def calculateHash(self):
hashData = str(self.index) + str(self.data) + self.timestamp + str(self.nonce)
return hashlib.sha256(hashData).hexdigest()
def mineBlock(self, difficulty):
print Back.RED + "\n[Status] Mining block (" + str(self.index) + ") with PoW ..."
startTime = time.time()
while self.hash[:difficulty] != "0"*difficulty:
self.nonce += 1
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
class Blockchain:
def __init__(self):
self.chain = [self.createGenesisBlock()]
self.difficulty = 3
def createGenesisBlock(self):
return Block("Genesis Block")
def addBlock(self, newBlock):
newBlock.index = len(self.chain)
newBlock.previousHash = self.chain[-1].hash
newBlock.mineBlock(self.difficulty)
self.chain.append(newBlock)
self.writeBlocks()
def writeBlocks(self):
dataFile = file("chain.txt", "w")
chainData = []
for eachBlock in self.chain:
chainData.append(eachBlock.__dict__)
dataFile.write(json.dumps(chainData, indent=4))
dataFile.close()

91
bls.py Normal file
View File

@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
# import modules
import click
import urllib
import json
from blockshell import Block, Blockchain
# Supported commands
SUPPORTED_COMMANDS = [
'dotx',
'allblocks',
'getblock',
'help'
]
# Init blockchain
coin = Blockchain()
# Create group of commands
@click.group()
def cli():
pass
# Start lbc cli
@cli.command()
@click.option("--difficulty", default=3, help="Difine dufficulty level of blockchain.")
def init(difficulty):
"""Initialize local blockchain"""
print """
____ _ _ _____ _ _ _
| _ \ | | | | / ____| | | | | | |
| |_) | | | ___ ___ | | __ | (___ | |__ ___ | | | |
| _ < | | / _ \ / __| | |/ / \___ \ | '_ \ / _ \ | | | |
| |_) | | | | (_) | | (__ | < ____) | | | | | | __/ | | | |
|____/ |_| \___/ \___| |_|\_\ |_____/ |_| |_| \___| |_| |_|
> A command line utility for learning Blockchain concepts.
> Type 'help' to see supported commands.
"""
# Set difficulty of blockchain
coin.difficulty = difficulty
# Start lbc chell
while True:
cmd = raw_input("[LBC] $ ")
processInput(cmd)
# Process input from LBC shell
def processInput(cmd):
userCmd = cmd.split(" ")[0]
if len(cmd) > 0:
if userCmd in SUPPORTED_COMMANDS:
globals()[userCmd](cmd)
else:
# error
msg = "Command not found. Try help command for documentation"
throwError(msg)
# ------------------------------------
# Supported Commands Methods
# ------------------------------------
def dotx(cmd):
txData = cmd.split("dotx ")[-1]
if "{" in txData:
txData = json.loads(txData)
print "Doing transaction..."
coin.addBlock(Block(data=txData))
def allblocks(cmd):
print ""
for eachBlock in coin.chain:
print eachBlock.hash
print ""
def getblock(cmd):
blockHash = cmd.split(" ")[-1]
for eachBlock in coin.chain:
if eachBlock.hash == blockHash:
print ""
print eachBlock.__dict__
print ""
def help(cmd):
print "Commands:"
print " dotx <transaction data> Create new transaction"
print " allblocks Fetch all mined blocks in blockchain"
def throwError(msg):
print "Error : " + msg

19
setup.py Normal file
View File

@ -0,0 +1,19 @@
from setuptools import setup
setup(
name="blockshell",
version='0.1',
author = "Daxeel Soni",
author_email = "daxeelsoni44@gmail.com",
url = "https://daxeel.github.io",
description = ("A command line utility for learning Blockchain concepts."),
py_modules=['bls'],
install_requires=[
'Click',
'colorama'
],
entry_points='''
[console_scripts]
blockshell=bls:cli
''',
)