From 17efafea02bb0e083ad1b77b61c967d652d17d4f Mon Sep 17 00:00:00 2001
From: Denis Gremaud <denis.gremuad@gmail.com>
Date: Fri, 16 Apr 2021 11:59:38 +0200
Subject: [PATCH] ok blockchain

---
 blockchain/input.txt          | Bin 0 -> 449 bytes
 blockchain/test.txt           | Bin 0 -> 51 bytes
 blockchain_gremaud_tefridj.py | 182 ++++++++++++++++++++++++++++++++++
 input.txt                     |   4 +
 test.jpg => test_image.jpg    | Bin
 test.pdf => test_pdf.pdf      | Bin
 6 files changed, 186 insertions(+)
 create mode 100644 blockchain/input.txt
 create mode 100644 blockchain/test.txt
 create mode 100644 blockchain_gremaud_tefridj.py
 create mode 100644 input.txt
 rename test.jpg => test_image.jpg (100%)
 rename test.pdf => test_pdf.pdf (100%)

diff --git a/blockchain/input.txt b/blockchain/input.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4efbe386abffd854811b30f5f76367dd5d66a174
GIT binary patch
literal 449
zcmZQ%U_Bhx_TUeP{yT5w&iUyMFC+}Utl4PKY58y3->h)^gFfnsWr=wuiRq~dDWwWN
z`9-O@3Z4bUrMU{lr9}#*c?u<|6(y+(>4#V59bQ?KSy-B?ker{Jo2sDhQVNmNQ^3Mf
zS4b@`Q79}`&&*LM$S*EFydou4p)@a5Atkf8q$o3~v?Mb>Pa!2$At$w@q$ssmp&+NU
zSRubuAvZrWuUH{3zbH2`Csj{@m&-Y|qy$YH$mrBOg_8Wz5{2Z%VvvIh5{nX(a#9r%
z%TkjSl2dbXz}`tKO3XXFJTbFap|~V5FD0=kMUR)uIX|zYC^54rH8(Y{MB(rPu(R?D
zGV?$#DmuKfATckcG*w3-Clw_)^3*}r79<uc6ldlZ<Un+%K*K;GG3W5g#FG5XqEtOz
zF3%i=lA`?5vQ&lQ)MACA#N^Dp)MAB{#JpmNU8$vIMX6xVCo1G*mXsV`S(I2(T9m4g
VlUS0Om#UDQlUQ5~3Ti#>OaOv2s%8KH

literal 0
HcmV?d00001

diff --git a/blockchain/test.txt b/blockchain/test.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0bdc04c78f645138deb73a7c35eb02bdf3f047a9
GIT binary patch
literal 51
zcmZQ#U^{m(ZOM5n!}D9*&aBv5eOS+I-?e*J^WQlf&W%{u$yJhCT%wSipIcCrT3no&
IpQro>0F4$H$p8QV

literal 0
HcmV?d00001

diff --git a/blockchain_gremaud_tefridj.py b/blockchain_gremaud_tefridj.py
new file mode 100644
index 0000000..5645925
--- /dev/null
+++ b/blockchain_gremaud_tefridj.py
@@ -0,0 +1,182 @@
+"""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é
+    
\ No newline at end of file
diff --git a/input.txt b/input.txt
new file mode 100644
index 0000000..495c587
--- /dev/null
+++ b/input.txt
@@ -0,0 +1,4 @@
+L'avantage du Lorem Ipsum sur un texte générique comme 'Du texte. Du texte. Du texte.' est qu'il possède une distribution de lettres plus ou moins normale. 
+Cette distribution est en tout cas comparable avec celle du français standard.
+Contrairement à une opinion répandue, le Lorem Ipsum n'est pas simplement du texte aléatoire.
+Il trouve ses racines dans une oeuvre de la littérature latine classique.
\ No newline at end of file
diff --git a/test.jpg b/test_image.jpg
similarity index 100%
rename from test.jpg
rename to test_image.jpg
diff --git a/test.pdf b/test_pdf.pdf
similarity index 100%
rename from test.pdf
rename to test_pdf.pdf
-- 
GitLab