Exemplo n.º 1
0
 def handle(self):
     debug.output(
         debug.info,
         '[server] new connection from ' + str(self.client_address))
     content_length = int(receive(self.request, 10))
     msg = decode_from_bytes(receive(self.request, content_length))
     if isinstance(msg, HeartbeatMessage):
         debug.output(debug.info, msg.timestamp)
         self.request.send(wrap_message(HeartbeatMessage()))
     elif isinstance(msg, GetPeersMessage):
         debug.output(
             debug.info, '[server] receive %s from ' % str(type(msg)) +
             str(self.client_address))
         debug.output(debug.info,
                      '[server] send to ' + str(self.client_address))
         self.request.send(
             wrap_message(PeersMessage(peers.get_known_peers())))
         debug.output(debug.info,
                      '[server] sent to ' + str(self.client_address))
     elif isinstance(msg, PeersMessage):
         debug.output(
             debug.info, '[server] receive %s from ' % str(type(msg)) +
             str(self.client_address))
         for peer in msg.peers:
             peers.add_peer(peer)
         self.request.send(wrap_message(HeartbeatMessage()))
     else:
         handle_message(msg)
         self.request.send(wrap_message(HeartbeatMessage()))
     debug.output(debug.info, '[server] exit handle')
Exemplo n.º 2
0
    def send_message(self, msg):
        if not self.connected:
            debug.output(debug.verbose,
                         '[sender] try connect to %s' % str(self.peer))
            self.s.connect((self.peer.ip, self.peer.port))
            self.connected = True
            debug.output(debug.verbose,
                         '[sender] connected to %s' % str(self.peer))

        debug.output(debug.verbose,
                     '[sender] send %s to %s' % (str(msg), str(self.peer)))
        content = wrap_message(msg)
        self.s.send(content)
        content_length = int(receive(self.s, 10))
        return decode_from_bytes(receive(self.s, content_length))
Exemplo n.º 3
0
 def run(self):
     print 'connecting...'
     self.connect()
     print 'sending messages...'
     send(self.socket, self.message, 'request')
     res = receive(self.socket, 'response')
     print res
Exemplo n.º 4
0
def node_finished():
    d = utils.receive(request.data)
    if d not in blockchain.peers:
        blockchain.peers.append(d)
    sched.add_job(SCHED_master_node,
                  args=[blockchain, sched, node_registry],
                  id='master_node')
    return "Ok master received. Thank you node."
Exemplo n.º 5
0
    def receive_file(self):
        file_name = receive(self.client)
        print(file_name)
        file_location = self.directory + file_name
        create_save_file(file_location, self.client)
        self.files_mt_times[file_name] = self.get_mtime(file_name)

        self.print_file_list()
Exemplo n.º 6
0
def post_next_block():
    random_id = random.randint(0, 5000)
    idx = int(utils.receive(request.data))
    log_info(
        '[router./sync_next_block]({}) Posting block ({}) for requester...'.
        format(random_id, idx))
    block_list = blockchain.chain[[idx]]
    if len(block_list) != 0:
        block_dict = block_list[0].export_block_to_dict()
        return json.dumps(block_dict)
    else:
        return "None"
Exemplo n.º 7
0
def import_block_from_other_node():
    random_id = random.randint(0, 5000)
    log_info(
        '[router./peer_gossiped_new_block]({}) Import block from another node...'
        .format(random_id))
    new_block_dict = utils.receive(request.data)
    log_info("[router./peer_gossiped_new_block]({}) Recieved block: {}".format(
        random_id, new_block_dict['block_hash'][:25]))
    sched.add_job(SCHED_validate_and_add_possible_block,
                  args=[new_block_dict, blockchain, sched, random_id],
                  id='validate_possible_block')
    log_info('[router./peer_gossiped_new_block]({}) Queued.'.format(random_id))
    return "blockchain_{}_received_block".format(blockchain.chain_id)
Exemplo n.º 8
0
 def listen_to_server(self):
     while self.client:
         command = receive(self.client)
         print("Command from Server: " + command)
         if command == ERROR:
             self.remove_user_name_field()
             self.show_user_name_field(
                 "Username exists. Enter another username")
         elif command == ACCEPTED:
             self.print_it(self.user_name + ": is Connected to the server")
             self.print_file_list()
             self.remove_user_name_field()
             self.show_file_dialog()
         elif command == UPLOADING_FILE:
             self.receive_file()
         elif command == INVALIDATE:
             file_name = receive(self.client)
             self.print_it("Server Invalidation " + file_name)
             self.send_to_server(PULL)
             self.send_to_server(file_name)
             self.print_it("Client pulling " + file_name)
         elif command == VOTING:
             file_name = receive(self.client)
             print("Server has started the voting", file_name)
             time.sleep(3)
             option = random.choice([True, False])
             if option:
                 self.print_it("Voting For Deleting: \n" + file_name)
                 self.print_it("My Vote: " + COMMIT)
             else:
                 self.print_it("Voting For Deleting: \n" + file_name)
                 self.print_it("My Vote:" + ABORT)
             self.send_to_server(VOTING_RESPONSE)
             self.send_to_server(file_name)
             self.send_to_server(COMMIT if option else ABORT)
         elif command == DELETE:
             file_name = receive(self.client)
             self.print_it("Deleting: " + file_name)
             os.remove(self.directory + file_name)
             del self.files_mt_times[file_name]
             self.print_it("Deleted: " + file_name)
             self.print_file_list()
         elif command == VOTING_RESULT:
             decision = receive(self.client)
             file_name = receive(self.client)
             self.print_it("Vote for: " + file_name)
             self.print_it("Vote Result: " + decision)
             if decision == COMMIT:
                 self.send_to_server(DELETE)
                 self.send_to_server(file_name)
                 self.print_it("Deleted file Committed")
             else:
                 self.send_to_server(FETCH)
                 self.send_to_server(file_name)
                 self.print_it("Deleted file Restored")
         elif command == SHUTDOWN:
             self.stop()
         time.sleep(0.01)
Exemplo n.º 9
0
def import_transaction_from_other_node():
    random_id = random.randint(0, 5000)
    log_info(
        '[router./peer_gossiped_new_transaction]({}) Import transaction from another node...'
        .format(random_id))
    new_transaction_dict = utils.receive(request.data)
    log_info(
        "[router./peer_gossiped_new_transaction]({}) Recieved transaction: {}".
        format(random_id, new_transaction_dict['signature'][:25]))
    sched.add_job(SCHED_validate_and_add_possible_transaction,
                  args=[new_transaction_dict, blockchain, random_id],
                  id='validate_possible_transaction-' + str(random_id))
    log_info('[router./peer_gossiped_new_transaction]({}) Queued.'.format(
        random_id))
    return "blockchain_{}_received_transaction".format(blockchain.chain_id)
Exemplo n.º 10
0
 def receive_file(self, client_socket, user_name, text, command):
     file_name = receive(
         client_socket)  # if the received command is 'UPLOADING_FILE'
     server_location = self.directory + file_name
     if file_name:
         create_save_file(
             server_location,
             client_socket)  # puts the recieved file in the server location
     self.print_on_left_gui(MESSAGE, user_name, text + " " +
                            file_name)  # print the message on gui
     if command == BROADCAST:
         self.broadcast_to_all_clients(
             file_name)  # calls broadcast function
     else:
         self.invalidate_clients(file_name, client_socket)
     print_file_list(self.directory, self.gui.print_files,
                     self.gui.file_list_panel,
                     "Files in Server:")  # print the message on gui
Exemplo n.º 11
0
    

    print("\n\n==================== Simulation complete ===============\n\n")
    # collect all blocks from peers
    max_height = config.END_OF_CHAIN
    chain = [utils.ListDict() for h in range(max_height+1)]
    for p, peer in enumerate(blockchain.peers):
        print('\n\n--------------------------')
        log_info('Processing peer ({})/({}) @ {} ...'.format(p, len(blockchain.peers), peer))
        idx = 0
        block_height = 0
        while block_height < max_height:
            log_info('\tGetting block ({})/({}) ... latest height obtained: ({})'.format(idx,max_height,block_height))
            response = utils.broadcast(str(idx), [peer], "/sync_next_block")
            if response[0] != None:
                block_dict = utils.receive(response[0])
            else:
                block_dict = None
            if type(block_dict) == dict:
                block_hash = block_dict['block_hash']
                block_height = block_dict['height']
                log_info('(height,hash) = {},\n\t\t{}'.format(block_height,block_hash[0:25]))
                block_dict['height'] = int(block_dict['height'])
                block_dict['timestamp'] = float(block_dict['timestamp'])
                chain[block_height].append(block_hash,block_dict)
            else:
                log_info('invalid...')
            idx = idx + 1
    log_info('Chain saved: {}'.format([len(each) for each in chain]))
    
    consensus = len(chain[-1]) == 1
Exemplo n.º 12
0
    def handle_client_connection(self, client_socket, address):
        user_name = get_socket_address_string(
            client_socket)  # get socket address string to display on the panel
        while client_socket:
            command = receive(
                client_socket)  # receive a command from the client
            self.print_on_left_gui(
                COMMAND, user_name,
                command)  # print the commands on the left side of gui
            if command == USERNAME:
                user_name = receive(
                    client_socket)  # if the recieved command is 'USERNAME'
                if self.check_if_user_exists(
                        user_name):  # checks if the username exist
                    client_socket.send(
                        ERROR.encode()
                    )  # if username is already present the sends out the error
                else:
                    self.users.append(
                        user_name
                    )  # appends the username to the user_name list
                    self.print_on_left_gui(
                        MESSAGE, user_name,
                        "Connected")  # username message displayed on gui
                    client_socket.send(
                        ACCEPTED.encode()
                    )  # sends the message to the server saying username is accepted
                    print_client_list(self.users, self.gui.print_clients,
                                      self.gui.client_list_panel,
                                      "Connected Clients")

            elif command == UPLOADING_FILE:
                self.receive_file(
                    client_socket, user_name, "Uploaded",
                    BROADCAST)  # sending the updated file to other clients
            elif command == DELETED:  #if command isdeleted
                file_name = receive(client_socket)
                self.start_voting(client_socket, file_name)
            elif command == VOTING_RESPONSE:
                file_name = receive(client_socket)
                option = receive(client_socket)
                print(command, file_name, option)
                self.votes[file_name][client_socket] = option
                print(self.votes)
                current_file_voting = self.votes[file_name].values()
                if None not in current_file_voting:
                    currently_voted_clients = self.votes[file_name].keys()
                    client_started_deletion = list(
                        set(self.connections) -
                        set(currently_voted_clients))[0]
                    if len(set(current_file_voting)
                           ) == 1 and COMMIT in current_file_voting:
                        send(client_started_deletion,
                             VOTING_RESULT)  #checks for the voting result
                        send(client_started_deletion,
                             COMMIT)  #if the client commits
                        send(client_started_deletion, file_name)
                    else:
                        send(client_started_deletion,
                             VOTING_RESULT)  #checks for the voting result
                        send(client_started_deletion,
                             ABORT)  #if the client aborts
                        send(client_started_deletion, file_name)
            elif command == DELETE:
                file_name = receive(client_socket)
                self.print_on_left_gui(MESSAGE, user_name,
                                       "Deleting " + file_name)
                os.remove(self.directory + file_name)
                print_file_list(self.directory, self.gui.print_files,
                                self.gui.file_list_panel, "Files in Server:"
                                )  # print the files on the right side of panel
                self.delete_file_from_all_clients(file_name)
            elif command == FETCH:
                file_name = receive(client_socket)
                self.send_file_to_clients(client_socket, file_name)
            elif command == UPLOADING_CHANGED_FILE:
                self.receive_file(
                    client_socket, user_name, "Updated",
                    INVALIDATE)  # sending invalidate message to clients
            elif command == PULL:
                file_name = receive(client_socket)
                self.print_on_left_gui(
                    MESSAGE, user_name, "Pulling " + file_name
                )  # once the pull command is printed it sends the file to other clientsSe
                self.send_file_to_clients(client_socket, file_name)
            elif command == "":
                self.print_on_left_gui(
                    MESSAGE, user_name,
                    "Disconnected ")  # if the recieved command is ''
                if client_socket in self.connections:
                    self.connections.remove(
                        client_socket)  # remove the connections from list
                if user_name in self.users:
                    self.users.remove(
                        user_name)  # remove username from the list
                    print_client_list(self.users, self.gui.print_clients,
                                      self.gui.client_list_panel,
                                      "Connected Clients")
                client_socket = None
Exemplo n.º 13
0
def handle_echo(socket, address):
    expression = receive(socket, 'request')
    print 'Got one task from client: %s' % expression
    result = calculate(expression)
    send(socket, result, 'response')
    socket.close()
Exemplo n.º 14
0
def handle_echo(socket, address):
    expression = receive(socket, 'request')
    print 'Got one task from client: %s' % expression
    result = calculate(expression)
    send(socket, result, 'response')
    socket.close()