Select Git revision
blockchain_gremaud_tefridj.py
blockchain_gremaud_tefridj.py 6.34 KiB
"""Programme permetant de crée une blockchain
Usage:
======
python blockchain_gremaud_tefridj.py file_name
file_name: le nom du fichier pour commencer la blockchain
"""
__authors__ = ("Denis Gremaud", "Yanis Tefridj")
__contact__ = ("denis.gremaud@etu.hesge.ch", "yanis.tefridj@etu.hesge.ch")
__version__ = "1.0.0"
__copyright__ = "copyleft"
__date__ = "16.04.21"
__version__= "1.0.1"
import sys
import hashlib
import sys
import math
import os
import time
NONCE_SIZE = 13 # number of numbre that should be 0 in nonce
"""permet de lire un fichier
Args:
file_name: le path ou nom du fichier a lire
Returns:
les bytes du fichier lu
"""
def read_file_blockchain(input_file_path, mode=1):
if mode == 1:
file = open(input_file_path, "rb")
file_open = file.read()
return file_open
elif mode == 2:
file = open(input_file_path, "rb")
file_number = file.read(1)
file_hash = file.read(32)
return file_number, file_hash
"""permet d'écrire un fichier
Args:
file_name: le path ou nom du fichier a écrire
data: les données a écrire
Returns:
none
"""
def write_file_blockchain(input_file_path, data):
file = open(input_file_path, "wb")
file.write(data)
file.close()
"""permet d'obtenir le hash d'un fichier en sha256
Args:
file: le contenu du fichier a hasher
print_hash: variable initialiser a false mais si true permet d'afficher le hash
Returns:
le hash du contenu du fichier
"""
def hash_data(data, print_hash=False):
hash_file = hashlib.sha256(data).hexdigest()
if print_hash == True:
print('hash : {}'.format(hash_file))
return hash_file
"""permet de lire un fichier et ensuite de le hash en sha256
Args:
file_name: le path ou nom du fichier a lire et a hash
print_hash: variable initialiser a false mais si true permet d'afficher le hash
Returns:
le hash du contenu du fichier
"""
def hash_file(input_file_path, print_hash=False):
return hash_data(read_file_blockchain(input_file_path), print_hash)
class blockchain:
def __init__(self, input_file_path="", strength=13):
self.first_block = block(input_file_path)
self.total_block = 0
self.strength = strength
self.insert(self.first_block)
def insert(self, block):
data_header = block.block_number + block.block_prev_hash
data = read_file_blockchain(block.file_path)
data = data_header + bytearray(data)
byte_lenght = 1
block.block_hash = hash_data(data + (block.nonce).to_bytes(byte_lenght, byteorder ='big'))
while(int(block.block_hash, 16) > (1 << (256 - self.strength))):
block.nonce += 1
if (block.nonce == ((1 << (byte_lenght*8)) - 1)):
byte_lenght += 1
block.block_hash = hash_data(data + (block.nonce).to_bytes(byte_lenght, byteorder ='big'))
block.nonce = block.nonce.to_bytes(byte_lenght, byteorder ='big')
output_file_path = os.path.join("blockchain", input_file_path)
write_file_blockchain(output_file_path, data + block.nonce)
if self.total_block != 0:
block.block_obj = self.first_block
self.first_block = block
self.total_block += 1
def read(self, input_file_path):
read_b = block(input_file_path)
read_b.block_number, read_b.block_prev_hash = read_file_blockchain(input_file_path, mode=2)
read_b.block_hash = hash_file(input_file_path)
return read_b
class block:
def __init__(self, file_path, block_number=0, block_prev_hash=0x00, block_obj=None, nonce=0):
self.block_number = block_number.to_bytes(1, byteorder ='big')
self.block_prev_hash = block_prev_hash.to_bytes(32, byteorder ='big')
self.file_path = file_path
self.nonce = nonce
self.block_obj = block_obj
self.block_hash = ""
def print_block(input_file_path, block_current):
print("Insertion de [", input_file_path, "]\n")
print("Numéro du block : ", block_current.block_number[0])
print("Hash du block pointé : 0x", block_current.block_prev_hash.hex())
print("Nonce : ", int.from_bytes(block_current.nonce, byteorder ='big'))
print("Hash du block inséré : 0x", block_current.block_hash)
print("-"*90)
if __name__ == '__main__':
if len(sys.argv) > 1: # on test si on a spécifié un nom de fichier à trier
input_file_path = sys.argv[1]
if os.path.exists(input_file_path) == True:
if os.path.isdir('blockchain') is not True:
os.mkdir('blockchain')
t = time.time()
blockchain = blockchain(input_file_path, NONCE_SIZE)
t = time.time() - t
print("\nTemps d'insertion : ", t)
input_file_path = os.path.join("blockchain", input_file_path)
first_block_read = blockchain.read(input_file_path)
print_block(input_file_path, blockchain.first_block)
input_file_path = input("\nEntrer un nouveau chemin de fichier à insérer : ")
while input_file_path != "exit":
if os.path.exists(input_file_path) == True:
block_input = block(input_file_path, blockchain.total_block, int(blockchain.first_block.block_hash, 16), blockchain.first_block)
t = time.time()
blockchain.insert(block_input)
t = time.time() - t
print("\nTemps d'insertion : ", t)
input_file_path = os.path.join("blockchain", input_file_path)
block_read = blockchain.read(input_file_path)
print_block(input_file_path, blockchain.first_block)
input_file_path = input("\nEntrer un nouveau chemin de fichier à insérer : ")
else:
print("Le fichier spécifié n'existe pas !") # message affiché si le fichier n'existe pas
print("si vous voulez quitter ecriver juste exit")
input_file_path = input("\nEntrer un nouveau chemin de fichier à insérer : ")
else:
print("Le fichier spécifié n'existe pas !") # message affiché si le fichier n'existe pas
else:
print("Vous devez spécifié un nom de fichier !") # message affiché si il y a pas de fichier spécifié