def listen():
    try:
        serversocket = network.start_server('localhost', RELAY_PORT)
        next_ip = None
        while True:
            logger.log('CURRENT RELAY NODE: ' + str(RELAY_PORT))
            logger.log('RECIEVING PORT:' + str(RELAY_PORT) +
                       ' FORWARDING PORT:' + str(FORWARDING_PORT))

            clientsocket, address = serversocket.accept()
            payload = network.recv_by_size(clientsocket)
            previous_ip = parse_address(address)
            logger.log('received payload from: ', previous_ip)
            logger.log('Payload (trunc): ', payload[:100], newline=True)
            logger.header('---- BEGIN DECRYPTION OF RECEIVED PAYLOAD ----')
            next_ip, message = deserialize_payload(payload)

            logger.log('begin forwarding payload to next node...')
            response = forward_payload(next_ip, message)
            if response is not None:
                '''
            Case: send to previous_ip
            '''
                # encrypt layer
                logger.log('Response returned from: ' + next_ip, newline=True)
                logger.header('---- BEGIN ENCRYPTION OF RETURN PAYLOAD ----')
                logger.log('Payload being encrypted (trunc):', response[:100])

                logger.log('aes_key used:', DECRYPTED_AES_KEY)
                encrypted_payload = network.prepend_length(
                    serialize_payload(response))

                logger.log('send payload to previous node: ', previous_ip)
                clientsocket.sendall(encrypted_payload)

            clientsocket.close()
    except Exception:
        logger.error("Unable to connect to server")
        logger.error(traceback.format_exc())
    return
def forward_payload(next_ip, message):
    if is_exit_node(message):
        logger.log('EXIT NODE FOUND')
        logger.log('begin request to destination')
        req = requests.get(next_ip)
        return req.text.encode()

    else:
        logger.log('RELAY NODE FOUND')
        logger.log('next relay node is: ' + next_ip)
        message = message.encode()
        host, port = next_ip.split(':')
        relay_socket = network.connect_server('localhost', FORWARDING_PORT,
                                              host, port)
        payload = network.prepend_length(message)
        relay_socket.sendall(payload)
        response = network.recv_by_size(relay_socket)

        relay_socket.close()
        return response

    return