medmond919 icon

Blockchain example

medmond919 | PRO | 05/13/19 05:56:23 PM UTC | 0 ⭐ | 504 👁️ | Never ⏰ | []
Python |

4.39 KB

|

None

|

0 👍

/

0 👎

import datetime as date
import hashlib as hasher
import random
 
# Les utilisateurs de la blockchain, qui vont effectuer des transactions
users = ["Alice", "Bob", "Charlie", "You"]
 
class Transaction:
  def __init__(self, sender, receiver, amount):
    self.sender = sender
    self.receiver = receiver
    self.amount = amount
 
class Block:
 def __init__(self, index, timestamp, data, previous_hash, nonce):
   self.index = index
   self.timestamp = timestamp
   self.data = data
   self.previous_hash = previous_hash
   self.nonce = nonce
   self.hash = self.hash_block()
 
   #Hashing
 def hash_block(self):
   sha = hasher.sha256()
   # TODO : créer un objet sha 256 bits. Documentation : https://docs.python.org/2/library/hashlib.html
   # sha = .........
 
   # TODO : hasher toutes les informations contenues dans un block
   # sha.update((str(self.index) + ......... + str(self.previous_hash)).encode())
    
   sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.nonce) +  str(self.previous_hash)).encode())
   # TODO : renvoyer la représentation du hash en hexadécimal
   return sha.hexdigest()
   #return sha. .....
 
 
# Méthode pour créer manuellement le premier block d’index 0, daté d’aujourd’hui, de nonce 1 et et de data et hash arbitraire.
def create_genesis_block():
     
 #return Block(........)
 return Block(0, date.datetime.now(), "Genesis Block", "0", 1)
 
# Méthode pour ajouter un block valide à la blockchain, en se basant sur les informations du block précédant.
def next_block(last_block):
 this_index = last_block.index + 1
 #TODO : Incrémenter l'index du block à créer
 #this_index=......
 
 this_timestamp = date.datetime.now()
 #TODO : Indiquer a date de création du bloc
 #this_timestamp = ...
 
#TODO : Créer une transaction qui prend aléatoirement un sender parmi la liste des users, qui envoie une montant compris entre 1 et 100 à un des receivers restant dans la liste.
# rnd = random.Random()
 rnd = random.Random()
 user_transactions = users.copy()
 sender = rnd.choice(user_transactions)  
 user_transactions.remove(sender)
 receiver = rnd.choice(user_transactions)
 amount = rnd.randint(1, 100)
 
 this_data = Transaction(sender, receiver, amount)
 
 previous_hash = last_block.hash
 #TODO : Indiquer le hash du bloc précédant le bloc à créer
 #previous_hash= ......
 
 this_nonce = proof_of_work(last_block.nonce, this_index, this_timestamp, this_data, previous_hash)
 
 return Block(this_index, this_timestamp, this_data, previous_hash, this_nonce)
 
 
# Algorithme Proof-of-Work de calcul d'une valeur spéciale (nonce) prouvant la validité d'un bloc.
# TODO : Pour être considérée comme valide, cette valeur spéciale (nonce) doit permettre que le hash du block débute par 4 zéros :
def proof_of_work(last_nonce, this_index, this_timestamp, this_data, previous_hash):
  incrementor = 0;
  block = Block(this_index, this_timestamp, this_data, previous_hash, incrementor)
  # Valeur qui va s'incrémenter jusqu'à atteindre une valeur spéciale (nonce) valide
  #incrementor = .......
  while (str(block.hash)[:4] != '0000'):
    
    #print(Block(this_index, this_timestamp, this_data, previous_hash, incrementor).hash)
    #while ... :
    incrementor += 1
    block = Block(this_index, this_timestamp, this_data, previous_hash, incrementor)
 
  return incrementor
 
 
# Initialisation de la blockchain
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
 
# Lancement de la blockchain sur 20 blocks
num_of_blocks_to_add = 20
for i in range(0, num_of_blocks_to_add):
 block_to_add = next_block(previous_block)
 #TODO : Créer le block suivant
 #block_to_add =
 
 blockchain.append(block_to_add)
 #TODO : Enchaîner le nouveau bloc à la blockchain existante
 #blockchain.append(...)
 
 previous_block = block_to_add
 #TODO : Mettre à jour le dernier bloc
 #previous_block = ...
 
 print( "Block " + str(block_to_add.index) +" has been added to the blockchain!")
 print("----------------------------------------")
 print("Data: " + str(block_to_add.data.sender) + " sent " + str(block_to_add.data.amount) + " to " + str(block_to_add.data.receiver))
 print("Timestamp: " + str(block_to_add.timestamp))
 print("Nonce: "+ str(block_to_add.nonce))
 print("Hash: "+ block_to_add.hash+"\n")
 
#TODO : parcourir la blockchain (c'est une liste) pour afficher le solde de chaque user.

Comments