Ejemplo n.º 1
0
 def dessinerTableau(self, screen):
     LISTE = pygame.sprite.Group()
     screen.blit(self.background, (0, 0))
     imbloc = pygame.image.load('brick-wall.png')
     imressort = pygame.image.load('ressort.png')
     impic = pygame.image.load('sprite_pic0.png')
     impieceor = pygame.image.load('pieceor.png')
     b = None
     for i in range(30):
         for j in range(40):
             if self.table[i][j] == 1:
                 b = Bloc(imbloc, j * 25, i * 25, 0, (0, 0), 1)
                 LISTE.add(b)
             elif self.table[i][j] == 3:
                 b = Bloc(impic, j * 25, i * 25, 0, (0, 0), 3)
                 LISTE.add(b)
             elif self.table[i][j] == 4:
                 b = Bloc(imressort, j * 25, i * 25, 0, (0, 0), 4)
                 LISTE.add(b)
             elif self.table[i][j] == 5:
                 b = Bloc(impieceor, j * 25, i * 25, 0, (0, 0), 5)
                 LISTE.add(b)
             LISTE.draw(screen)
             pygame.display.flip()
     return LISTE
Ejemplo n.º 2
0
    def miner(self):
        # S'il n'y a pas de tx non confirmées on renvoie False
        if not self.txs_non_confirmees:
            return False

        # Nous créons un nouveau bloc
        # la hauteur est incrémentée
        # les transactions sont celles non confirmées
        # le timestamp c'est l'heure actuelle
        # le hachage_précédent c'est le hachage du dernier bloc
        # de la chaine
        nv_bloc = Bloc(
            hauteur=self.dernier_bloc.hauteur + 1,
            txs=self.txs_non_confirmees,
            timestamp=time.time(),
            hachage_precedent=self.dernier_bloc.hachage,
        )

        # Nous ajoutons le nouveau bloc avec la preuve du travail à notre chaine.
        self.ajouter_bloc(nv_bloc, preuve=self.preuve_de_travail(nv_bloc))

        # Nous vidons la liste de transaction non confirmées
        self.txs_non_confirmees = []

        # et nous renvoyons Vrai si tout c'est bien passé.
        return True
Ejemplo n.º 3
0
 def save_data(self):
     """Save blocchain + open submissions snapshot to a file."""
     try:
         with open('blocchain-{}.bit'.format(self.node_id), mode='w') as f:
             saveable_chain = [
                 bloc.__dict__ for bloc in
                 [
                     Bloc(bloc_el.index,
                           bloc_el.previous_hash,
                           [tx.__dict__ for tx in bloc_el.submissions],
                           bloc_el.proof,
                           bloc_el.timestamp) for bloc_el in self.__chain
                 ]
             ]
             f.write(json.dumps(saveable_chain))
             f.write('\n')
             saveable_tx = [tx.__dict__ for tx in self.__open_submissions]
             f.write(json.dumps(saveable_tx))
             f.write('\n')
             f.write(json.dumps(list(self.__peer_nodes)))
             # save_data = {
             #     'chain': blocchain,
             #     'ot': open_submissions
             # }
             # f.write(pickle.dumps(save_data))
     except IOError:
         print('Saving failed!')
Ejemplo n.º 4
0
def regenere_blockchain_avec(chaine_recue):
    # Nous appelons cette fonction lorsque le notre noeud s'enregistre auprès d'un autre
    # noeud serveur.  Nous reconstruisons alors notre blockchain

    # Nous instantion un nouvelle objet Blockchain
    blockchain_regeneree = Blockchain()
    # Pour lequel nous créeons le bloc de genèse
    blockchain_regeneree.creer_bloc_genese()

    # Ensuite pour chaque bloc 'reçu' ie récupéré dans la chaine reçue
    for idx, bloc_recu in enumerate(chaine_recue):
        # nous créons un objet bloc avec une copie des données reçues
        # hauteur, transaction, timestamp, hachage_précedent nonce
        # mais nous ignorons le premier bloc (bloc de genese) car nous
        # l'avons cree manuellement
        if idx == 0:
            # aussi si idx == 0 au passe au bloc suivant directement
            continue
        bloc = Bloc(
            bloc_recu["hauteur"],
            bloc_recu["txs"],
            bloc_recu["timestamp"],
            bloc_recu["hachage_precedent"],
            bloc_recu["nonce"],
        )
        # pour chaque bloc, nous vérifions bien que le hachage est valide
        bloc_ajoute = blockchain_regeneree.ajouter_bloc(
            bloc, preuve=bloc_recu["hachage"])
        # si l'ajout echoue, c'est qu'il y a une erreur et nous soulevons une
        # exception
        if not bloc_ajoute:
            raise Exception("Le contenu de la chaine a été modifié.")

    # Nous renvoyons la blockchain_regeneree
    return blockchain_regeneree
Ejemplo n.º 5
0
def dessiner_niveau(surface, niveau, listesprite):

    for j, ligne in enumerate(niveau):
        for i, case in enumerate(ligne):
            if case == 1:
                b = Bloc(imbloc, i * 50, j * 50, 0, (0, 0))
                listesprite.add(b)
                screen.blit(b.image, b.pos)
Ejemplo n.º 6
0
 def dessinerTableau(self, screen, listesprite):
     screen.blit(self.background, (0, 0))
     imbloc = pygame.image.load('brick-wall.png')
     imressort = pygame.image.load('ressort.png')
     b = None
     for i in range(40):
         for j in range(40):
             if self.table[i][j] == 1:
                 b = Bloc(imbloc, j * 25, i * 25, 0, (0, 0), 1)
                 listesprite.add(b)
                 #screen.blit(b.image, b.pos)
             elif self.table[i][j] == 4:
                 b = Bloc(imressort, j * 25, i * 25, 0, (0, 0), 4)
                 listesprite.add(b)
             listesprite.draw(screen)
     return listesprite
     pygame.display.flip()
Ejemplo n.º 7
0
 def save(self):
     """
     Saves the current bloc into the apartments.json file
     """
     # bloc_dict = self.bloc.get()
     # for apartment_id in bloc_dict.keys():
     #    bloc_dict[apartment_id] = Apartment.to_dictionary(bloc_dict[apartment_id])
     #
     fp = open("apartments.json", "w")
     fp.write(json.dumps(Bloc.to_dictionary(self.bloc)))
     fp.close()
Ejemplo n.º 8
0
 def __init__(self, public_key, node_id):
     """The constructor of the Blocchain class."""
     # Our starting bloc for the blocchain
     genesis_bloc = Bloc(0, '', [], 86400, 1577836799)
     # Initializing our (empty) blocchain list
     self.chain = [genesis_bloc]
     # Unhandled submissions
     self.__open_submissions = []
     self.public_key = public_key
     self.__peer_nodes = set()
     self.node_id = node_id
     self.resolve_conflicts = False
     self.load_data()
Ejemplo n.º 9
0
 def load_data(self):
     """Initialize blocchain + open submissions data from a file."""
     try:
         with open('blocchain-{}.bit'.format(self.node_id), mode='r') as f:
             # file_content = pickle.loads(f.read())
             file_content = f.readlines()
             # blocchain = file_content['chain']
             # open_submissions = file_content['ot']
             blocchain = json.loads(file_content[0][:-1])
             # We need to convert  the loaded data because submissions
             # should use OrderedDict
             updated_blocchain = []
             for bloc in blocchain:
                 converted_tx = [Submission(
                     tx['voter'],
                     tx['candidate'],
                     tx['zero'],         #added to hold day zero, countdown until final vote
                     tx['signature'],
                     tx['amount']) for tx in bloc['submissions']]
                 updated_bloc = Bloc(
                     bloc['index'],
                     bloc['previous_hash'],
                     converted_tx,
                     bloc['proof'],
                     bloc['timestamp'])
                 updated_blocchain.append(updated_bloc)
             self.chain = updated_blocchain
             open_submissions = json.loads(file_content[1][:-1])
             # We need to convert  the loaded data because submissions
             # should use OrderedDict
             updated_submissions = []
             for tx in open_submissions:
                 updated_submission = Submission(
                     tx['voter'],
                     tx['candidate'],
                     tx['zero'],
                     tx['signature'],
                     tx['amount'])
                 updated_submissions.append(updated_submission)
             self.__open_submissions = updated_submissions
             peer_nodes = json.loads(file_content[2])
             self.__peer_nodes = set(peer_nodes)
     except (IOError, IndexError):
         pass
     finally:
         print('Cleanup!')
Ejemplo n.º 10
0
 def resolve(self):
     """Checks all peer nodes' blocchains and replaces the local one with
     longer valid ones."""
     # Initialize the winner chain with the local chain
     winner_chain = self.chain
     replace = False
     for node in self.__peer_nodes:
         url = 'http://{}/chain'.format(node)
         try:
             # Send a request and store the response
             response = requests.get(url)
             # Retrieve the JSON data as a dictionary
             node_chain = response.json()
             # Convert the dictionary list to a list of bloc AND
             # submission objects
             node_chain = [
                 Bloc(bloc['index'],
                       bloc['previous_hash'],
                       [
                     Submission(
                         tx['voter'],
                         tx['candidate'],
                         tx['zero'],
                         tx['signature'],
                         tx['amount']) for tx in bloc['submissions']
                 ],
                     bloc['proof'],
                     bloc['timestamp']) for bloc in node_chain
             ]
             node_chain_length = len(node_chain)
             local_chain_length = len(winner_chain)
             # Store the received chain as the current winner chain if it's
             # longer AND valid
             if (node_chain_length > local_chain_length and
                     Verification.verify_chain(node_chain)):
                 winner_chain = node_chain
                 replace = True
         except requests.exceptions.ConnectionError:
             continue
     self.resolve_conflicts = False
     # Replace the local chain with the winner chain
     self.chain = winner_chain
     if replace:
         self.__open_submissions = []
     self.save_data()
     return replace
Ejemplo n.º 11
0
 def add_bloc(self, bloc):
     """Add a bloc which was received via broadcasting to the localb
     lockchain."""
     # Create a list of submission objects
     submissions = [Submission(
         tx['voter'],
         tx['candidate'],
         tx['zero'],
         tx['signature'],
         tx['amount']) for tx in bloc['submissions']]
     # Validate the proof of work of the bloc and store the result (True
     # or False) in a variable
     proof_is_valid = Verification.valid_proof(
         submissions[:-1], bloc['previous_hash'], bloc['proof'])
     # Check if previous_hash stored in the bloc is equal to the local
     # blocchain's last bloc's hash and store the result in a bloc
     hashes_match = hash_bloc(self.chain[-1]) == bloc['previous_hash']
     if not proof_is_valid or not hashes_match:
         return False
     # Create a bloc object
     converted_bloc = Bloc(
         bloc['index'],
         bloc['previous_hash'],
         submissions,
         bloc['proof'],
         bloc['timestamp'])
     self.__chain.append(converted_bloc)
     stored_submissions = self.__open_submissions[:]
     # Check which open submissions were included in the received bloc
     # and remove them
     # This could be improved by giving each submission an ID that would
     # uniquely identify it
     for itx in bloc['submissions']:
         for opentx in stored_submissions:
             if (opentx.voter == itx['voter'] and
                     opentx.candidate == itx['candidate'] and
                     opentx.zero == itx['zero'] and
                     opentx.amount == itx['amount'] and
                     opentx.signature == itx['signature']):
                 try:
                     self.__open_submissions.remove(opentx)
                 except ValueError:
                     print('Item was already removed')
     self.save_data()
     return True
Ejemplo n.º 12
0
    def __init__(self):
        """
        The construction for the app. Used for reading the bloc from the file
        """
        # read apartments from file
        try:
            fp = open("apartments.json", "r")
            temp_dict = json.loads(fp.read())
            fp.close()
        except ValueError:  # handle empty json
            temp_dict = {}

        # load the apartments into the dict
        # for key in temp_dict:
        #    temp_dict[key] = Apartment.from_dictionary(temp_dict[key])

        # create the bloc object
        self.bloc = Bloc.from_dictionary(temp_dict)

        # undo variables
        self._undo_last_operation = None
        self._undo_bloc = None
Ejemplo n.º 13
0
def verifier_ajouter_bloc():
    # Ce point d'entré permet d'ajouter un bloc à la blockchain
    # du noeud serveur

    # Nous récupérons les données associées avec l'url 'ajouter_bloc'
    donnes_recues = request.get_json()

    # Nous instantions un objet bloc avec mais
    bloc = Bloc(
        donnes_recues["hauteur"],
        donnes_recues["txs"],
        donnes_recues["timestamp"],
        donnes_recues["hachage_precedent"],
        donnes_recues["nonce"],
    )
    # Nous stockons séparément la preuve (hachage)
    preuve = donnes_recues["hachage"]
    # pour la vérifier au moment de l'ajout
    validation_ajout = blockchain.ajouter_bloc(bloc, preuve)

    # Nous renvoyons des messages de validations si tous c'est bien passé.
    return (("Le Bloc a été ajouter à la chaine", 201) if validation_ajout else
            ("Le bloc a été ignoré par le noeud.", 400))
Ejemplo n.º 14
0
from sys import exit
import perso
from bloc import Bloc

#Init fond
screen = pygame.display.set_mode((1000, 1000))
fond = pygame.image.load('sky.jpg')
screen.blit(fond, (0, 0))

#>Init perso
person = pygame.image.load('perso.png')
o = perso.Personnage(person, 200, 300, 10)

#Init Bloc
imbloc = pygame.image.load('Rectangle_.png')
b = Bloc(imbloc, 900, 900, 1, (-1, -1))
b.rect.width = 1
b.rect.height = 1

o.rect.width = 25
o.rect.height = 25

#Init Groupe
g = pygame.sprite.Group()
g.add(b)

pygame.key.set_repeat(400, 30)
while 1:
    g.update()
    for event in pygame.event.get():
        if event.type == KEYDOWN:
Ejemplo n.º 15
0
    def mine_bloc(self):
        global VOTE_WINDOW
        """Create a new bloc and add open submissions to it."""
        # update your ip (only if your publickey is registered) so that mining can be shared with all nodes
        if self.public_key is None:
            return None

        publickey = {"publickey": self.public_key}
        requests.post('https://blocbit.net/kitty.php' ,params=publickey)
        # Fetch the currently last bloc of the blocchain
        last_bloc = self.__chain[-1]
        #last_pf = last_bloc.proof
        #window = self.load_window_data()
        # Hash the last bloc (=> to be able to compare it to the stored hash
        # value)
        hashed_bloc = hash_bloc(last_bloc)
        proof = self.proof_by_vote()
        # Added to avoid blocchain startup error after genesis bloxk as it contains no submission i.e. no zero
        # last_pf = last_bloc.proof
        # if last_pf != 86400:
        #     zero = self.submission_zero()           
        # else:
        #     zero = 365.0
        zero = self.submission_zero()
        # Voters have the right to vote daily, so let's create a window submission
        # reward_submission = {
        #     'voter': 'STATION',
        #     'candidate': owner,
        #     'amount': 0 or 1
        # }
        Station_open = Submission(
            'STATION', self.public_key, zero, '', 1)
        Station_closed = Submission(
            'STATION', self.public_key, zero, '', 0)
        # Copy submission instead of manipulating the original
        # open_submissions list
        # This ensures that if for some reason the mining should fail,
        # we don't have the reward submission stored in the open submissions
        copied_submissions = self.__open_submissions[:]
        for tx in copied_submissions:
            if not Ballot.verify_submission(tx):
                return None
        
        # if global var is set to true award right and then set back to false
        if VOTE_WINDOW is False:
            copied_submissions.append(Station_closed)
        else:
            copied_submissions.append(Station_open)
            VOTE_WINDOW = False
        bloc = Bloc(len(self.__chain), hashed_bloc,
                      copied_submissions, proof)
        self.__chain.append(bloc)
        self.__open_submissions = []
        self.save_data()
        for node in self.__peer_nodes:
            url = 'http://{}/broadcast-bloc'.format(node)
            converted_bloc = bloc.__dict__.copy()
            converted_bloc['submissions'] = [
                tx.__dict__ for tx in converted_bloc['submissions']]
            try:
                response = requests.post(url, json={'bloc': converted_bloc})
                if response.status_code == 400 or response.status_code == 500:
                    print('Bloc declined, needs resolving')
                if response.status_code == 409:
                    self.resolve_conflicts = True
            except requests.exceptions.ConnectionError:
                continue
        return bloc
Ejemplo n.º 16
0
 def creer_bloc_genese(self):
     # créer un objet bloc
     bloc_genese = Bloc(0, [], 0, "0")
     # associer un hachage quelconque pour le premier bloc
     setattr(bloc_genese, "hachage", bloc_genese.calculer_hachage())
     self.chaine.append(bloc_genese)