medmond919

Blockchain example

May 13th, 2019
561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.39 KB | None | 0 0
  1. import datetime as date
  2. import hashlib as hasher
  3. import random
  4.  
  5. # Les utilisateurs de la blockchain, qui vont effectuer des transactions
  6. users = ["Alice", "Bob", "Charlie", "You"]
  7.  
  8. class Transaction:
  9.   def __init__(self, sender, receiver, amount):
  10.     self.sender = sender
  11.     self.receiver = receiver
  12.     self.amount = amount
  13.  
  14. class Block:
  15.  def __init__(self, index, timestamp, data, previous_hash, nonce):
  16.    self.index = index
  17.    self.timestamp = timestamp
  18.    self.data = data
  19.    self.previous_hash = previous_hash
  20.    self.nonce = nonce
  21.    self.hash = self.hash_block()
  22.  
  23.    #Hashing
  24.  def hash_block(self):
  25.    sha = hasher.sha256()
  26.    # TODO : créer un objet sha 256 bits. Documentation : https://docs.python.org/2/library/hashlib.html
  27.    # sha = .........
  28.  
  29.    # TODO : hasher toutes les informations contenues dans un block
  30.    # sha.update((str(self.index) + ......... + str(self.previous_hash)).encode())
  31.    
  32.    sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.nonce) +  str(self.previous_hash)).encode())
  33.    # TODO : renvoyer la représentation du hash en hexadécimal
  34.    return sha.hexdigest()
  35.    #return sha. .....
  36.  
  37.  
  38. # 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.
  39. def create_genesis_block():
  40.      
  41.  #return Block(........)
  42.  return Block(0, date.datetime.now(), "Genesis Block", "0", 1)
  43.  
  44. # Méthode pour ajouter un block valide à la blockchain, en se basant sur les informations du block précédant.
  45. def next_block(last_block):
  46.  this_index = last_block.index + 1
  47.  #TODO : Incrémenter l'index du block à créer
  48.  #this_index=......
  49.  
  50.  this_timestamp = date.datetime.now()
  51.  #TODO : Indiquer a date de création du bloc
  52.  #this_timestamp = ...
  53.  
  54. #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.
  55. # rnd = random.Random()
  56.  rnd = random.Random()
  57.  user_transactions = users.copy()
  58.  sender = rnd.choice(user_transactions)  
  59.  user_transactions.remove(sender)
  60.  receiver = rnd.choice(user_transactions)
  61.  amount = rnd.randint(1, 100)
  62.  
  63.  this_data = Transaction(sender, receiver, amount)
  64.  
  65.  previous_hash = last_block.hash
  66.  #TODO : Indiquer le hash du bloc précédant le bloc à créer
  67.  #previous_hash= ......
  68.  
  69.  this_nonce = proof_of_work(last_block.nonce, this_index, this_timestamp, this_data, previous_hash)
  70.  
  71.  return Block(this_index, this_timestamp, this_data, previous_hash, this_nonce)
  72.  
  73.  
  74. # Algorithme Proof-of-Work de calcul d'une valeur spéciale (nonce) prouvant la validité d'un bloc.
  75. # 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 :
  76. def proof_of_work(last_nonce, this_index, this_timestamp, this_data, previous_hash):
  77.   incrementor = 0;
  78.   block = Block(this_index, this_timestamp, this_data, previous_hash, incrementor)
  79.   # Valeur qui va s'incrémenter jusqu'à atteindre une valeur spéciale (nonce) valide
  80.   #incrementor = .......
  81.   while (str(block.hash)[:4] != '0000'):
  82.    
  83.     #print(Block(this_index, this_timestamp, this_data, previous_hash, incrementor).hash)
  84.     #while ... :
  85.     incrementor += 1
  86.     block = Block(this_index, this_timestamp, this_data, previous_hash, incrementor)
  87.  
  88.   return incrementor
  89.  
  90.  
  91. # Initialisation de la blockchain
  92. blockchain = [create_genesis_block()]
  93. previous_block = blockchain[0]
  94.  
  95. # Lancement de la blockchain sur 20 blocks
  96. num_of_blocks_to_add = 20
  97. for i in range(0, num_of_blocks_to_add):
  98.  block_to_add = next_block(previous_block)
  99.  #TODO : Créer le block suivant
  100.  #block_to_add =
  101.  
  102.  blockchain.append(block_to_add)
  103.  #TODO : Enchaîner le nouveau bloc à la blockchain existante
  104.  #blockchain.append(...)
  105.  
  106.  previous_block = block_to_add
  107.  #TODO : Mettre à jour le dernier bloc
  108.  #previous_block = ...
  109.  
  110.  print( "Block " + str(block_to_add.index) +" has been added to the blockchain!")
  111.  print("----------------------------------------")
  112.  print("Data: " + str(block_to_add.data.sender) + " sent " + str(block_to_add.data.amount) + " to " + str(block_to_add.data.receiver))
  113.  print("Timestamp: " + str(block_to_add.timestamp))
  114.  print("Nonce: "+ str(block_to_add.nonce))
  115.  print("Hash: "+ block_to_add.hash+"\n")
  116.  
  117. #TODO : parcourir la blockchain (c'est une liste) pour afficher le solde de chaque user.
Advertisement
Add Comment
Please, Sign In to add comment