beautified messages

This commit is contained in:
Ryan Bakkes 2023-11-11 20:30:06 +01:00
parent e0edbfefaf
commit 39c3b09b81
6 changed files with 40 additions and 32 deletions

View File

@ -1,6 +1,5 @@
from classes.Transaction import Tx from classes.Transaction import Tx
from classes.TxBlock import TxBlock from classes.TxBlock import TxBlock
from helpers import SignatureHelper as signatureHelper
from helpers import UtilityHelper as utilityHelper from helpers import UtilityHelper as utilityHelper
import time import time
@ -31,12 +30,12 @@ def exploreBlocks(self):
user_input = int(user_input) -1 user_input = int(user_input) -1
except: except:
utilityHelper.clearScreen() utilityHelper.clearScreen()
print("Wrong input, try again") print(f"{utilityHelper.warningMessage('Wrong input, try again')}")
return return
if user_input > len(blocks) - 1 or user_input < 0: if user_input > len(blocks) - 1 or user_input < 0:
utilityHelper.clearScreen() utilityHelper.clearScreen()
print("Wrong input, try again") print(f"{utilityHelper.warningMessage('Wrong input, try again')}")
return return
# print all info of the block # print all info of the block
@ -92,7 +91,7 @@ def exploreBlocks(self):
exploreBlocks(self) exploreBlocks(self)
case _: case _:
utilityHelper.clearScreen() utilityHelper.clearScreen()
print("Wrong input, try again") print(f"{utilityHelper.warningMessage('Wrong input, try again')}")
return return
def createBlock(self): def createBlock(self):
@ -106,20 +105,20 @@ def createBlock(self):
lastBlock = lastBlock[-1] lastBlock = lastBlock[-1]
if lastBlock != None and time.time() - lastBlock.date < 180: if lastBlock != None and time.time() - lastBlock.date < 180:
print(f"You can only mine a block every 3 minutes. Time left: {int(180 - (time.time() - lastBlock.date))}") print(f"{utilityHelper.bcolors.WARNING}You can only mine a block every 3 minutes. Time left: {int(180 - (time.time() - lastBlock.date))}{utilityHelper.bcolors.ENDC}")
return False return False
if lastBlock != None and lastBlock.metadata['validated'] == False: if lastBlock != None and lastBlock.metadata['validated'] == False:
print("You can only mine a block if the last block is validated") print(f"{utilityHelper.warningMessage('You can only mine a block if the last block is validated')}")
return False return False
transactions = Tx() transactions = Tx()
transactions = utilityHelper.loadFile("../data/transaction_pool.dat") transactions = utilityHelper.loadFile("../data/transaction_pool.dat")
if len(transactions) < 5: if len(transactions) < 5:
print("You need atleast 5 transactions to mine a block") print(f"{utilityHelper.warningMessage('You need atleast 5 transactions to mine a block')}")
return False return False
print("Select items out the pool to mine a block, last 2 values added to list.") print("Select items out the pool to mine a block, 2 values already selected.")
if input("Press enter to continue... (type b to return)") == "b": if input("Press enter to continue... (type b to return)") == "b":
return False return False
utilityHelper.clearScreen() utilityHelper.clearScreen()
@ -132,7 +131,6 @@ def createBlock(self):
fees[x] = transaction.inputs[0][1] - transaction.outputs[0][1] fees[x] = transaction.inputs[0][1] - transaction.outputs[0][1]
x+=1 x+=1
print(fees)
fees_list = list(fees.keys()) fees_list = list(fees.keys())
selected_transactions = fees_list[:2] selected_transactions = fees_list[:2]
available_transactions = fees_list[2:] available_transactions = fees_list[2:]
@ -153,20 +151,20 @@ def createBlock(self):
for i in user_input: for i in user_input:
try: try:
if int(i) not in available_transactions: if int(i) not in available_transactions:
print("Wrong input, try again") print(f"{utilityHelper.warningMessage('Wrong input, try again')}")
return False return False
selected_transactions.append(int(i)) selected_transactions.append(int(i))
except: except:
utilityHelper.clearScreen() utilityHelper.clearScreen()
print("Wrong input, try again") print(f"{utilityHelper.warningMessage('Wrong input, try again')}")
return False return False
if len(selected_transactions) > 10: if len(selected_transactions) > 10:
print("You can only select up to 10 transactions") print(f"{utilityHelper.warningMessage('You can only select up to 10 transactions')}")
return False return False
if len(selected_transactions) < 5: if len(selected_transactions) < 5:
print("You need atleast 5 transactions to mine a block") print(f"{utilityHelper.warningMessage('You need atleast 5 transactions to mine a block')}")
return False return False
only_personal = True only_personal = True
@ -179,7 +177,7 @@ def createBlock(self):
only_personal = False only_personal = False
if only_personal: if only_personal:
print("You need atleast 1 transaction from another user") print(f"{utilityHelper.warningMessage('You need atleast 1 transaction from another user')}")
return False return False
if lastBlock == []: if lastBlock == []:
lastBlock = None lastBlock = None
@ -200,18 +198,18 @@ def createBlock(self):
utilityHelper.clearScreen() utilityHelper.clearScreen()
if not block.good_nonce(): if not block.good_nonce():
print("ERROR! Bad nonce") print(f"{utilityHelper.errorMessage('ERROR! Bad nonce')}")
return False return False
print("Success! Nonce is good!") print(f"{utilityHelper.successMessage('Success! Nonce is good!')}")
print(f'Accepted Nonce = {str(nonce)}') print(f'Accepted Nonce = {str(nonce)}')
print("elapsed time: " + str(elapsed) + " s.") print("elapsed time: " + str(elapsed) + " s.")
if elapsed < MIN_MINING_TIME: if elapsed < MIN_MINING_TIME:
print("Mining declined, too fast") print(f"{utilityHelper.errorMessage('Mining declined, too fast')}")
return False return False
elif elapsed > MAX_MINING_TIME: elif elapsed > MAX_MINING_TIME:
print("Mining declined, too Slow") print(f"{utilityHelper.errorMessage('Mining declined, too Slow')}")
return False return False
# add block to blockchain # add block to blockchain
@ -298,7 +296,7 @@ def validateMinedBlock(self):
try: try:
del blocks[-1] del blocks[-1]
except: except:
print("error biatch") print(f"{utilityHelper.errorMessage('Something went wrong')}")
return False return False
utilityHelper.resetFile("../data/ledger.dat") utilityHelper.resetFile("../data/ledger.dat")

View File

@ -1,8 +1,8 @@
import sqlite3 import sqlite3
from helpers import UtilityHelper as utilityHelper
class DatabaseHelper: class DatabaseHelper:
def __init__(self, db=None): def __init__(self, db=None):
print("Initializing database")
self.conn = None self.conn = None
self.cursor = None self.cursor = None
@ -48,7 +48,6 @@ class DatabaseHelper:
self.cursor.execute("SELECT * FROM `users` WHERE (`username` = ? AND `password` = ?)", (username, password,)) self.cursor.execute("SELECT * FROM `users` WHERE (`username` = ? AND `password` = ?)", (username, password,))
return self.cursor.fetchone() return self.cursor.fetchone()
except sqlite3.Error as error: except sqlite3.Error as error:
print(error)
return None return None
def createUser(self, private_key, public_key, username, password): def createUser(self, private_key, public_key, username, password):
@ -59,7 +58,6 @@ class DatabaseHelper:
self.commit() self.commit()
return True return True
except sqlite3.Error as error: except sqlite3.Error as error:
print(error)
return False return False
def changePassword(self, user_privatekey, old_password, password): def changePassword(self, user_privatekey, old_password, password):
@ -75,7 +73,6 @@ class DatabaseHelper:
return True return True
except sqlite3.Error as error: except sqlite3.Error as error:
print(error)
return None return None
def changeUsername(self, user_privatekey, username): def changeUsername(self, user_privatekey, username):
@ -90,7 +87,6 @@ class DatabaseHelper:
return True return True
except sqlite3.Error as error: except sqlite3.Error as error:
print(error)
return None return None
def deleteUser(self, user_privatekey): def deleteUser(self, user_privatekey):
@ -106,7 +102,6 @@ class DatabaseHelper:
return True return True
except sqlite3.Error as error: except sqlite3.Error as error:
print(error)
return None return None
def fetchUserByUsername(self, username): def fetchUserByUsername(self, username):
@ -119,7 +114,6 @@ class DatabaseHelper:
return self.cursor.fetchone() return self.cursor.fetchone()
except sqlite3.Error as error: except sqlite3.Error as error:
print(error)
return None return None
def checkMigrations(self): def checkMigrations(self):

View File

@ -4,6 +4,7 @@ from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from helpers import UtilityHelper as utilityHelper
def generateKeys(): def generateKeys():
private_key = rsa.generate_private_key(public_exponent=65537,key_size=2048) private_key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
@ -81,5 +82,5 @@ def verify(message, signature, public_ser):
except InvalidSignature: except InvalidSignature:
return False return False
except: except:
print("Error executing 'public_key.verify'") print(f"{utilityHelper.errorMessage('Error executing <public_key.verify>')}")
return False return False

View File

@ -1,5 +1,4 @@
from classes.Transaction import Tx from classes.Transaction import Tx
from classes.TxBlock import TxBlock
from helpers import UtilityHelper as utilityHelper from helpers import UtilityHelper as utilityHelper
from helpers import TaskHelper as taskHelper from helpers import TaskHelper as taskHelper

View File

@ -24,6 +24,18 @@ def computeHash(data):
def clearScreen(): def clearScreen():
os.system('cls' if os.name == 'nt' else 'clear') os.system('cls' if os.name == 'nt' else 'clear')
def printLogo():
print(f"""{bcolors.HEADER}
----------------------v1.0.0----------------------
____ _ _ _
/ ___| ___ ___ __| | ___| |__ __ _(_)_ __
| | _ / _ \ / _ \ / _` |/ __| '_ \ / _` | | '_ \
| |_| | (_) | (_) | (_| | (__| | | | (_| | | | | |
\____|\___/ \___/ \__,_|\___|_| |_|\__,_|_|_| |_|
------------------Initializing--------------------
{bcolors.ENDC}""")
def createFile(fileloc): def createFile(fileloc):
try: try:
savefile = open(fileloc, "xb") savefile = open(fileloc, "xb")

View File

@ -11,17 +11,21 @@
from helpers.DatabaseHelper import DatabaseHelper from helpers.DatabaseHelper import DatabaseHelper
from helpers.MenuHelper import MenuHelper from helpers.MenuHelper import MenuHelper
from helpers import UtilityHelper as utilityHelper from helpers import UtilityHelper as utilityHelper
from time import sleep
if __name__ == "__main__": if __name__ == "__main__":
utilityHelper.clearScreen()
utilityHelper.printLogo()
# start db connection # start db connection
db = DatabaseHelper("../data/goodchain.db") db = DatabaseHelper("../data/goodchain.db")
db.checkMigrations() db.checkMigrations()
# check ledger and pool file # check ledger and pool file
if utilityHelper.createFile("../data/ledger.dat"): utilityHelper.createFile("../data/ledger.dat")
print("Created ledger") utilityHelper.createFile("../data/transaction_pool.dat")
if utilityHelper.createFile("../data/transaction_pool.dat"):
print("Created transaction pool") sleep(1)
# start menu # start menu
menu = MenuHelper(db) menu = MenuHelper(db)