This commit is contained in:
Spekulaas 2024-01-21 20:56:17 +01:00
parent 77126c6464
commit 0f14b0b590
5 changed files with 127 additions and 25 deletions

View File

@ -6,6 +6,7 @@ from helpers import TaskHelper as taskHelper
import time import time
import pickle import pickle
import os
MIN_MINING_TIME = 0 MIN_MINING_TIME = 0
MAX_MINING_TIME = 20 MAX_MINING_TIME = 20
@ -266,7 +267,10 @@ def createBlock(self):
fees += transactions[i].inputs[0][1] - transactions[i].outputs[0][1] fees += transactions[i].inputs[0][1] - transactions[i].outputs[0][1]
fees = round(fees, 2) fees = round(fees, 2)
print(f"After validating you will receive a reward of {fees + 25} coins!") print(f"After validating you will receive a reward of {fees + 25} coins!")
new_reward = Tx()
new_reward.createRewardTransaction(block.metadata['miner'], self.user.private_ser, "MINE", fees)
socketHelper.sendObj(self.peer_ip_addr, new_reward, self.peer_port)
utilityHelper.addFile("../data/transaction_pool.dat", new_reward)
return True return True
def validateMinedBlock(self): def validateMinedBlock(self):
@ -355,26 +359,38 @@ def validateMinedBlock(self):
def socketBlock(block): def socketBlock(block):
# check if item is indeed a cblock # check if item is indeed a cblock
if type(block) != TxBlock: if type(block) != TxBlock:
return False return False, False, None
# check if ID exists in ledger # check if ID exists in ledger
last_block = getLastBlock() last_block = getLastBlock()
block_status = block.is_valid()
block.metadata['validated_by'].append("" + os.getenv("IP") + ":" + os.getenv("PORT"))
block.metadata['validated'] = block_status
if last_block == []: if last_block == []:
if block.id != 0: if block.id != 0:
return False, True return False, True, None
else: else:
block.previousBlock = None
return addBlockToChain(block, last_block) return addBlockToChain(block, last_block)
if block.id < last_block.id: if block.id < last_block.id:
return False, True return False, False, block
if last_block.id == block.id and last_block.metadata['validated'] == False: if block_status:
if block.id == last_block.id and block.blockHash == last_block.blockHash and last_block.metadata['validated'] == False:
block.previousBlock = last_block.previousBlock
return updateBlockValidation(block) return updateBlockValidation(block)
if block.id == last_block.id + 1: if block.id == last_block.id + 1 and block.previousHash == last_block.blockHash:
block.previousBlock = last_block
return addBlockToChain(block, last_block) return addBlockToChain(block, last_block)
return False, False, block
def canAddBlock(last_block): def canAddBlock(last_block):
if last_block == [] or last_block == None: if last_block == [] or last_block == None:
return True return True
@ -405,18 +421,17 @@ def transactionsInPool(transactions, block):
def addBlockToChain(block, last_block): def addBlockToChain(block, last_block):
if not canAddBlock(last_block): if not canAddBlock(last_block):
return False, False return False, False, block
# get transaction pool # get transaction pool
transactions = Tx() transactions = Tx()
transactions = utilityHelper.loadFile("../data/transaction_pool.dat") transactions = utilityHelper.loadFile("../data/transaction_pool.dat")
if not transactionsInPool(transactions, block): if not transactionsInPool(transactions, block):
print("deze man") return False, True, block
return False, True
if len(block.data) < 5 or len(block.data) > 10: if len(block.data) < 5 or len(block.data) > 10:
return False, False return False, False, block
utilityHelper.addFile("../data/ledger.dat", block) utilityHelper.addFile("../data/ledger.dat", block)
utilityHelper.resetFile("../data/transaction_pool.dat") utilityHelper.resetFile("../data/transaction_pool.dat")
@ -424,20 +439,22 @@ def addBlockToChain(block, last_block):
if transaction not in block.data: if transaction not in block.data:
utilityHelper.addFile("../data/transaction_pool.dat", transaction) utilityHelper.addFile("../data/transaction_pool.dat", transaction)
return True, False return True, False, block
def updateBlockValidation(block): def updateBlockValidation(block):
blocks = utilityHelper.loadFile("../data/ledger.dat") blocks = utilityHelper.loadFile("../data/ledger.dat")
last_block = getLastBlock()
if blocks == []: if blocks == []:
return False, False return False, False, block
try: try:
del blocks[-1] del blocks[-1]
except: except:
return False, False return False, False, block
utilityHelper.resetFile("../data/ledger.dat") utilityHelper.resetFile("../data/ledger.dat")
block.previousBlock = last_block
blocks.append(block) blocks.append(block)
if block.metadata['false_validations'] >= 3: if block.metadata['false_validations'] >= 3:
@ -449,12 +466,41 @@ def updateBlockValidation(block):
del blocks[-1] del blocks[-1]
except: except:
print(f"{utilityHelper.errorMessage('Something went wrong')}") print(f"{utilityHelper.errorMessage('Something went wrong')}")
return False, True return False, True, block
for b in blocks: for b in blocks:
utilityHelper.addFile("../data/ledger.dat", b) utilityHelper.addFile("../data/ledger.dat", b)
return True, False return True, False, block
def removeInvalid(block):
blocks = utilityHelper.loadFile("../data/ledger.dat")
last_block = getLastBlock()
if blocks == []:
return False
if last_block.blockHash == block.blockHash:
# try to delete
try:
del blocks[-1]
except:
return False
# remove last transaction from pool
transactions = Tx()
transactions = utilityHelper.loadFile("../data/transaction_pool.dat")
if transactions[-1].type == 1 and transactions[-1].outputs[0][0] == block.metadata['miner']:
try:
del transactions[-1]
except:
return False
utilityHelper.resetFile("../data/ledger.dat")
for b in blocks:
utilityHelper.addFile("../data/ledger.dat", b)
return True

View File

@ -5,6 +5,8 @@ from classes.TxBlock import TxBlock
from helpers import DatabaseHelper as databaseHelper from helpers import DatabaseHelper as databaseHelper
from helpers import UtilityHelper as utilityHelper from helpers import UtilityHelper as utilityHelper
from helpers import BlockHelper as blockHelper from helpers import BlockHelper as blockHelper
from helpers import TransactionHelper as transactionHelper
from helpers import TaskHelper as taskHelper
import socket import socket
import pickle import pickle
@ -39,6 +41,7 @@ def recvObj(socket):
def sendObj(ip_addr, blk, port): def sendObj(ip_addr, blk, port):
try: try:
print("sending to peer")
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((ip_addr, port)) soc.connect((ip_addr, port))
data = pickle.dumps(blk) data = pickle.dumps(blk)
@ -47,7 +50,7 @@ def sendObj(ip_addr, blk, port):
return True return True
except: except:
print("Could not connect to peer") print("Could not connect to peer")
utilityHelper.close() # utilityHelper.close()
return False return False
def connection(ip, port, db): def connection(ip, port, db):
@ -64,20 +67,27 @@ def connection(ip, port, db):
print(">>: ") print(">>: ")
if item.is_valid(): if item.is_valid():
if item.type == 0:
if item.outputs[0][1] > taskHelper.getBalanceWithOutgoingPoolByPublicKey(item.inputs[0][0], taskHelper.getBalanceByPublicKey(item.inputs[0][0])):
print(f"{utilityHelper.errorMessage('Received transaction is not valid')}")
sendObj(os.getenv("PEER_IP"), ["INVALID TRANSACTION",item], int(os.getenv("PEER_PORT")))
continue
utilityHelper.addFile("../data/transaction_pool.dat", item) utilityHelper.addFile("../data/transaction_pool.dat", item)
continue continue
print(f"{utilityHelper.errorMessage('Received transaction is not valid')}") print(f"{utilityHelper.errorMessage('Received transaction is not valid')}")
sendObj(os.getenv("PEER_IP"), ["INVALID TRANSACTION",item], int(os.getenv("PEER_PORT")))
if type(item) == TxBlock: if type(item) == TxBlock:
print() print()
print(f"{utilityHelper.blinkMessage('Received block from peer')}") print(f"{utilityHelper.blinkMessage('Received block from peer')}")
print(">>: ") print(">>: ")
valid, exit = blockHelper.socketBlock(item) valid, exit, block = blockHelper.socketBlock(item)
if not valid: if not valid:
print(f"{utilityHelper.errorMessage('Received block is not valid')}") print(f"{utilityHelper.errorMessage('Received block is not valid')}")
sendObj(os.getenv("PEER_IP"), ["INVALID BLOCK",block], int(os.getenv("PEER_PORT")))
continue continue
if exit: if exit:
@ -120,6 +130,20 @@ def connection(ip, port, db):
db.updateLogStatus(item[1]) db.updateLogStatus(item[1])
continue continue
case "INVALID TRANSACTION":
print()
print(f"{utilityHelper.errorMessage('Last send transaction is not valid, removing from pool...')}")
print(">>: ")
transactionHelper.removeTransaction(item[1])
continue
case "INVALID BLOCK":
print()
print(f"{utilityHelper.errorMessage('Last send block is not valid, removing from ledger...')}")
blockHelper.removeInvalid(item[1])
print(">>: ")
continue
if type(item) == str: if type(item) == str:
match item: match item:
case "EXIT": case "EXIT":

View File

@ -9,7 +9,7 @@ def displayUnreadLogs(self):
return False return False
printLogs(logs) printLogs(logs)
socketHelper.testConnection(self.peer_ip_addr, self.peer_port) utilityHelper.testConnection(self.peer_ip_addr, self.peer_port)
for log in logs: for log in logs:
self.db.updateLogStatus(log[0]) self.db.updateLogStatus(log[0])
# NEW SEND USER # NEW SEND USER
@ -37,6 +37,8 @@ def getBalance(self):
balance = 0 balance = 0
blocks = utilityHelper.loadFile("../data/ledger.dat") blocks = utilityHelper.loadFile("../data/ledger.dat")
for block in blocks: for block in blocks:
if not block.metadata['validated']:
continue
for transaction in block.data: for transaction in block.data:
if transaction.outputs[0][0] == self.user.public_ser: if transaction.outputs[0][0] == self.user.public_ser:
balance += transaction.outputs[0][1] balance += transaction.outputs[0][1]
@ -44,6 +46,19 @@ def getBalance(self):
balance -= transaction.inputs[0][1] balance -= transaction.inputs[0][1]
return balance return balance
def getBalanceByPublicKey(public_key):
balance = 0
blocks = utilityHelper.loadFile("../data/ledger.dat")
for block in blocks:
if not block.metadata['validated']:
continue
for transaction in block.data:
if transaction.outputs[0][0] == public_key:
balance += transaction.outputs[0][1]
elif transaction.type != 1 and transaction.inputs[0][0] == public_key:
balance -= transaction.inputs[0][1]
return balance
def getBalanceWithOutgoingPool(self, balance): def getBalanceWithOutgoingPool(self, balance):
transactions = utilityHelper.loadFile("../data/transaction_pool.dat") transactions = utilityHelper.loadFile("../data/transaction_pool.dat")
for transaction in transactions: for transaction in transactions:
@ -51,6 +66,13 @@ def getBalanceWithOutgoingPool(self, balance):
balance -= transaction.inputs[0][1] balance -= transaction.inputs[0][1]
return balance return balance
def getBalanceWithOutgoingPoolByPublicKey(public_key, balance):
transactions = utilityHelper.loadFile("../data/transaction_pool.dat")
for transaction in transactions:
if transaction.type != 1 and transaction.inputs[0][0] == public_key:
balance -= transaction.inputs[0][1]
return balance
def getPersonalTransactions(self): def getPersonalTransactions(self):
blocks = utilityHelper.loadFile("../data/ledger.dat") blocks = utilityHelper.loadFile("../data/ledger.dat")
total = 0 total = 0
@ -87,7 +109,7 @@ def getPersonalTransactions(self):
print("-----------------------------------------------------------------------------------") print("-----------------------------------------------------------------------------------")
def createLog(self, public_key, date, info, unread = 0): def createLog(self, public_key, date, info, unread = 0):
socketHelper.testConnection(self.peer_ip_addr, self.peer_port) utilityHelper.testConnection(self.peer_ip_addr, self.peer_port)
self.db.createLog(public_key, date, info, unread) self.db.createLog(public_key, date, info, unread)
# NEW SEND USER # NEW SEND USER
socketHelper.sendObj(self.peer_ip_addr, ["CREATE LOG",public_key, date, info, unread], self.peer_port) socketHelper.sendObj(self.peer_ip_addr, ["CREATE LOG",public_key, date, info, unread], self.peer_port)

View File

@ -260,3 +260,13 @@ def pendingTransactions(self):
utilityHelper.clearScreen() utilityHelper.clearScreen()
print("Wrong input, try again") print("Wrong input, try again")
return return
def removeTransaction(transaction):
transactions = utilityHelper.loadFile("../data/transaction_pool.dat")
transactions.remove(transaction)
utilityHelper.resetFile("../data/transaction_pool.dat")
# add old transactions to pool
for transaction in transactions:
utilityHelper.addFile("../data/transaction_pool.dat", transaction)
return

View File

@ -68,7 +68,7 @@ def loadFile(fileloc):
return objs return objs
def loginStartup(self): def loginStartup(self):
blockHelper.validateMinedBlock(self) # blockHelper.validateMinedBlock(self)
taskHelper.displayUnreadLogs(self) taskHelper.displayUnreadLogs(self)
def errorMessage(text): def errorMessage(text):