Example #1
0
    def __init__(self,
                 url,
                 magic_phrase,
                 max_turns=10,
                 callback=None,
                 callback_params=1,
                 msg_q=False):
        print('starting service')
        self.start_proba = 1.0
        self.magic_phrase = magic_phrase
        self.url = replace_localhost(url)
        self.bot = Alice()
        self.max_turns = max_turns
        self.sending_message = False
        self._id = None
        self.use_msg_q = msg_q  # msg_q sets whether or not we are queueing messages
        self.websocket = 'ws://%s/websocket' % self.url
        self.client = MeteorClient(self.websocket)
        self.client.ddp_client.ddpsocket.extra_headers = [('Bot', 'true')]
        print(self.client.ddp_client.ddpsocket.handshake_headers)
        self.client.connect()

        self.idle_time = 3 * 60
        self.thread_time = 2
        self.max_retry = 3
Example #2
0
    def decrypt(label, encrypted):
        retrieval = {}
        retrieval["label"] = label
        retrieval["policy_encrypting_key"] = Alice.get_policy_encrypting_key(
            label)
        retrieval["alice_verifying_key"] = Alice.get_verifying_key()
        retrieval["message_kit"] = encrypted

        response = requests.post(f"{Bob.bob}/retrieve",
                                 data=json.dumps(retrieval))
        plaintext = json.loads(response.content)['result']['cleartexts'][0]
        return plaintext
Example #3
0
def main():
    # 使用するqubitを用意
    bit_count = int(input('Bit count : '))
    qubits = [cirq.LineQubit(i) for i in range(bit_count)]

    alice = Alice()
    bob = Bob()
    eve = Eve()

    # アリスはランダムなビット列を生成する
    alice.create_origin_bits(bit_count)

    circuit = cirq.Circuit.from_ops(
        # アリスはX基底またはH基底でランダムにエンコードする
        # alice.set_initial_qubits(qubits),
        alice.encode(qubits),
        # # イヴが盗聴した場合
        # eve.decode(qubits),
        # ボブはX基底またはH基底でランダムにデコードする
        bob.decode(qubits))
    print(circuit)
    # ボブは結果を測定する
    bob.measure_qubits(circuit)

    # アリスとボブは互いにどのビットをどの基底でエンコード・デコードしたかを教えあう
    # 基底が一致したビットを抽出し、秘密鍵とする
    alice.set_secret_key(bob.decode_gates)
    bob.set_secret_key(alice.encode_gates)
Example #4
0
def main():
    k = 2
    #RSA

    alice = Alice(k)
    bank = Bank()
    merchant = Merchant()

    return start_simulation(alice, bank, merchant)
Example #5
0
def is_host_running():
    is_running = True

    try:
        alice_verifying_key = Alice.get_verifying_key()
        bob_encrypting_key, bob_verifying_key = Bob.get_keys()
    except:
        is_running = False

    return is_running
Example #6
0
def main(username, password, site, category, update):

    alice = Alice()
    alice.setup(username, password, site, update)

    a, p = alice.send_message()
    print('\na value (or alpha^r mod p): {0}'.format(a))
    bob = Bob()
    bob.setup(a, p)

    b = bob.receive_message()
    print('\nb value (or a^k mod p): {0}'.format(b))
    print('\nalpha raised to k mod p: {0}'.format(pow(alice.alpha, bob.k, p)))
    alice.compute_rwd(b, category)
Example #7
0
def run_transcription_loop():
    bot = Alice()
    r = sr.Recognizer()
    r.energy_threshold = 4000
    with sr.Microphone(device_index=None, sample_rate=16000,
                       chunk_size=1024) as source:
        while True:
            print("Awaiting user input.")
            audio = r.listen(source)
            print("Attempting to transcribe user input.")
            try:
                result = r.recognize_google(
                    audio, key=GOOGLE_SPEECH_RECOGNITION_API_KEY)
                z = bot.handle_action(result)
                if (z == 0):
                    bot.speak("Have a nice day and thank you")
                    sys.exit("Error message")

            except sr.UnknownValueError:
                bot.speak("Sorry come again")
            except sr.RequestError:
                bot.speak("Internet connection error")
            except:
                print("")
Example #8
0
def main():

    host_addr = '127.0.0.1'
    host_port = 8082
    server_sni_hostname = 'example.com'
    server_cert = 'server.crt'
    client_cert = 'client.crt'
    client_key = 'client.key'

    username = "******"
    password = "******"
    site = "apple.com"
    update = False
    category = 'complex'

    alice = Alice()
    alice.setup(username, password, site, update)
    a, p = alice.send_message()

    alice_tuple = (a, p)

    serialized_data = pickle.dumps(alice_tuple)

    context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
                                         cafile=server_cert)
    context.load_cert_chain(certfile=client_cert, keyfile=client_key)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn = context.wrap_socket(s,
                               server_side=False,
                               server_hostname=server_sni_hostname)
    conn.connect((host_addr, host_port))
    print("SSL established. Peer: {}".format(conn.getpeercert()))
    conn.sendall(serialized_data)

    # get b from server (bob)
    bob_data = conn.recv(4096)
    b = pickle.loads(bob_data)

    conn.close()

    alice.compute_rwd(b, category)
Example #9
0
# -*- coding: utf-8 -*-
"""
2019/1/10 NPYLM (文字n-gramの追加)
"""
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import collections
from pyp import PYP, PYP_prior
from alice import Alice
import pickle
import math
alice = Alice()
char_n_global = 3
#seq = ["A","B","A","B","C","D","A","B","A","B","C","D","C","D","A","B","A","B","A","B","C","D","C","D","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","C","D","C","D","C","D","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","C","D","C","D","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","C","D","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","C","D","C","D","B","A","B","A","B","A","C","D","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B"]

#start_symbol = "<SOS>"
#start_symbol = alice.start_symbol
#end_symbol = "<EOS>"
#end_symbol = alice.end_symbol
#seq = ["A","A","A","B","A","A","A","A","B","A","A","A","A","B","A","A"]


class G0():  #一様分布
    def __init__(self, V):
        self.V = V
        self.num_customers = V
        self.context = ()
        self.n = 0
        self.context_restaurant = {}
Example #10
0
    def play(self, board, direction, **options):

        cols = len(board)
        rows = len(board[0])

        if direction == HORIZ:

            if not self.__left__:

                for x in range(cols):

                    col = board[x]

                    if self.__left__:
                        break

                    for y in range(rows):

                        if col[y] == direction:
                            self.__vide__ = False
                            self.__left__ = x == 0

                            if self.__left__:
                                break

                            elif 0 <= x - 1 and board[x - 1][y] == EMPTY:
                                return (x - 1, y)
                            elif 0 <= y - 1 and board[x][y - 1] == EMPTY:
                                return (x, y - 1)
                            elif 0 <= x - 1 and y + 1 < rows and board[x - 1][
                                    y + 1] == EMPTY:
                                return (x - 1, y + 1)

            if not self.__right__:

                for x in reversed(range(cols)):

                    col = board[x]

                    if self.__right__:
                        break

                    for y in range(rows):

                        if col[y] == direction:
                            self.__vide__ = False
                            self.__right__ = x == cols - 1

                            if self.__right__:
                                break

                            if x + 1 < cols and board[x + 1][y] == EMPTY:
                                return (x + 1, y)
                            elif y + 1 < rows and board[x][y + 1] == EMPTY:
                                return (x, y + 1)
                            elif x + 1 < cols and 0 <= y - 1 and board[x + 1][
                                    y - 1] == EMPTY:
                                return (x + 1, y - 1)

            if self.__vide__:
                x = cols // 2
                y = rows // 2
                return (x, y) if board[x][y] == EMPTY else (x - 1, y)
            else:
                return Alice().play(board, direction)

        elif direction == VERTI:

            if not self.__top__:

                for y in range(rows):

                    if self.__top__:
                        break

                    for x in range(cols):

                        if board[x][y] == direction:
                            self.__vide__ = False
                            self.__top__ = y == 0

                            if self.__top__:
                                break

                            elif 0 <= y - 1 and board[x][y - 1] == EMPTY:
                                return (x, y - 1)
                            elif x + 1 < cols and 0 <= y - 1 and board[x + 1][
                                    y - 1] == EMPTY:
                                return (x + 1, y - 1)

            if not self.__bottom__:

                for y in reversed(range(rows)):

                    if self.__bottom__:
                        break

                    for x in range(cols):

                        if board[x][y] == direction:
                            self.__vide__ = False
                            self.__bottom__ = y == rows - 1

                            if self.__bottom__:
                                break

                            elif 0 <= x - 1 and y + 1 < rows and board[x - 1][
                                    y + 1] == EMPTY:
                                return (x - 1, y + 1)
                            elif y + 1 < rows and board[x][y + 1] == EMPTY:
                                return (x, y + 1)

            if self.__vide__:
                x = cols // 2
                y = rows // 2
                return (x, y) if board[x][y] == EMPTY else (x, y + 1)
            else:
                return Alice().play(board, direction)
Example #11
0
from alice import Alice
from bob import Bob
import numpy as np
import datetime

alice_messages = np.arange(10000)
print("Alice's messages: " + str(alice_messages))
bob_messages = np.arange(5000, 15000)
print("Bob's messages: " + str(bob_messages))
file_path = '.'

alice = Alice(alice_messages, file_path)
bob = Bob(bob_messages, file_path)
t1 = datetime.datetime.now()
intersection = alice.evaluate_intersection()
t2 = datetime.datetime.now()
print('Actual intersection: ' + str(intersection))
print('Evaluating intersection took: ' + str(t2 - t1))
Example #12
0
def run_transcription_loop():
    bot = Alice()
    r = sr.Recognizer()
    r.energy_threshold = 4000
    with sr.Microphone(device_index=None, sample_rate=16000,
                       chunk_size=1024) as source:
        while True:
            print("Awaiting user input.")
            audio = r.listen(source)
            print("Attempting to transcribe user input.")
            try:
                result = r.recognize_google(
                    audio, key=GOOGLE_SPEECH_RECOGNITION_API_KEY)
                z = bot.handle_action(result)
                if (z == 0):
                    bot.speak("Have a nice day and thank you")
                    sys.exit("Error message")

            except sr.UnknownValueError:
                bot.speak("Sorry come again")
            except sr.RequestError:
                bot.speak("Internet connection error")
            except:
                print("")


if __name__ == '__main__':
    bot = Alice()
    bot.speak("Hello Sir")
    run_transcription_loop()
Example #13
0
def parse_message(message_json):
    message = json.loads(message_json)
    msg_id = message['id']
    msg_cmd = message['cmd']

    # have a check to make sure that nucypher network is running.
    # if not, fail.
    if is_host_running() == False:
        output = {}
        output["id"] = msg_id
        output["cmd"] = "isHostRunning"
        output["type"] = "failure"
        output["result"] = "nuBox Host is not running"

        send_message(json.dumps(output))
        return

    if msg_cmd == "isHostRunning":
        output = {}
        output["id"] = msg_id
        output["cmd"] = "isHostRunning"
        output["type"] = "success"
        output["result"] = "nuBox Host is running"

        send_message(json.dumps(output))

    # get Bob's public keys
    elif msg_cmd == "bob_keys":
        output = {}
        output["id"] = msg_id
        output["cmd"] = "bob_keys"
        output["args"] = message['args']

        try:
            bob_encrypting_key, bob_verifying_key = Bob.get_keys()

            output["type"] = "success"
            output["result"] = {}
            output["result"]["bek"] = bob_encrypting_key
            output["result"]["bvk"] = bob_verifying_key
        except:
            output["type"] = "failure"

        send_message(json.dumps(output))

    # encrypt operation
    elif msg_cmd == 'encrypt':
        plaintext = message['args']['plaintext']
        label = message['args']['label']

        output = {}
        output["id"] = msg_id
        output["cmd"] = "encrypt"
        output["args"] = message['args']

        try:
            encrypted = Alice.encrypt(label, plaintext)
            output["type"] = "success"
            output["result"] = encrypted
        except Exception as e:
            output["type"] = "failure"
            output["result"] = str(e)

        send_message(json.dumps(output))

    # grant operation
    elif msg_cmd == 'grant':
        output = {}
        output["id"] = msg_id
        output["cmd"] = "grant"
        output["args"] = message['args']

        response = Bob.grant(label=message['args']['label'],
                             bob_encrypting_key=message['args']['bek'],
                             bob_verifying_key=message['args']['bvk'],
                             expiration=message['args']['expiration'])

        if response.status_code == 200:
            output["type"] = "success"
            output["result"] = "granted"
        else:
            logging.error(response.content.decode("utf-8"))
            output["type"] = "failure"
            output["result"] = "Failed to grant for this label"

        send_message(json.dumps(output))

    # revoke operation
    elif msg_cmd == 'revoke':
        label = message['args']['label']
        bvk = message['args']['bvk']

        output = {}
        output["id"] = msg_id
        output["cmd"] = "revoke"
        output["args"] = message['args']

        response = Alice.revoke(label, bvk)
        if response.status_code == 200:
            output["type"] = "success"
            output["result"] = "Revoked"
        else:
            logging.error(response.content.decode("utf-8"))
            output["type"] = "failure"
            output["result"] = "Failed to revoke for this label"

        send_message(json.dumps(output))

    # decrypt operation
    elif msg_cmd == 'decrypt':
        encrypted = message['args']['encrypted']
        label = message['args']['label']

        output = {}
        output["id"] = msg_id
        output["cmd"] = "decrypt"
        output["args"] = message['args']

        try:
            plaintext = Bob.decrypt(label, encrypted)
            output["type"] = "success"
            output["result"] = plaintext
        except:
            output["type"] = "failure"
            output["result"] = "Failed to decrypt for this label"

        send_message(json.dumps(output))
Example #14
0
  parser.add_argument('key_amount', help="Amount of keys to create")
  parser.add_argument('key_size', help="Size of each key in bytes")
  parser.add_argument('-v', '--verbose', action="store_true", help="Verbose output")
  parser.add_argument('-e', '--eve', action="store_true", help="Eve is present")

  args = parser.parse_args()

  key_amount = int(args.key_amount)
  key_size = int(args.key_size)
  verbose = args.verbose
  eve_exists = args.eve
  detected = 0

  for i in range(key_amount):

    alice = Alice()
    bob = Bob()
    eve = Eve()

    alice.reset()
    bob.reset()

    qubits = bob.send_qubits(key_size * 8 * 4)

    qubits = qubits
    qubits = qubits
    qubits = qubits
    qubits = qubits
    if(eve_exists == True):
      qubits = eve.measure_qubits(qubits)
    qubits = qubits
Example #15
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--point-permute", help="enable the point-and-permute optimization", action='store_true')
    parser.add_argument("--free-xor", help="enable the free-XOR optimization", action='store_true')
    parser.add_argument("--grr3", help="enable the GRR3 optimization", action='store_true')
    args = parser.parse_args()

    if args.grr3 and not args.point_permute:
        print("The GRR3 optimization requires the point-and-permute optimization to be enabled")
        exit(0)

    if args.free_xor:
        config.USE_FREE_XOR = True
        print("Optimization enabled: free-XOR")

    if args.point_permute:
        config.USE_POINT_PERMUTE = True
        print("Optimization enabled: point-and-permute")

    if args.grr3:
        config.USE_GRR3 = True
        print("Optimization enabled: GRR3")

    alice = Alice()
    bob = Bob()

    # In this implementation we store wires as strings, whose values are those supplied by the user. 
    # These strings uniquely identify the corresponding wire. Not to be confused with labels, for which there are 
    # two for every unique wire!
    print(
        "Welcome! Please define your circuit by entering a sequence of logic gate specifications of the form \"z = x "
        "OP y\", where:")
    print(" - x and y are identifiers that uniquely specify the gate's two input wires, ")
    print(" - z is an identifier that uniquely specifies the gate's output wire")
    print(" - OP is the gate operation, which is one of \"and\", \"or\", \"xor\"")
    print(
        "Please enter one logic gate per line. When you are finished defining gates and are ready to proceed, "
        "please enter a blank line.")
    wires = dict()
    out_wires = []
    in_wires = []
    while True:
        gate_info = input()
        if not gate_info:
            break
        gate_info = gate_info.split()
        gate = Gate()
        if gate_info[3] == "and":
            gate.op = 'AND'
        elif gate_info[3] == "or":
            gate.op = 'OR'
        elif gate_info[3] == "xor":
            gate.op = 'XOR'
        else:
            raise ValueError("Operation must be one of \"and\", \"or\", \"xor\"")

        gate.in1 = gate_info[2]
        gate.in2 = gate_info[4]
        gate.out = gate_info[0]

        gates[gate.out] = gate

        wires[gate.in1] = ""
        wires[gate.in2] = ""
        wires[gate.out] = ""

        in_wires.append(gate.in1)
        in_wires.append(gate.in2)
        out_wires.append(gate.out)

        wires[gate_info[0]] = ""
        wires[gate_info[2]] = ""
        wires[gate_info[4]] = ""

    input_wires = []
    output_wires = []

    for w in wires:  # select the wires that are ONLY input and ONLY output
        if w in in_wires and w not in out_wires:
            input_wires.append(w)
        if w in out_wires and w not in in_wires:
            output_wires.append(w)

    print("Detected the following INPUT wires:  " + str(input_wires))
    print("Detected the following OUTPUT wires: " + str(output_wires))

    alice_wires = []
    alice_wire_values = []
    bob_wires = []
    bob_wire_values = []

    print("Among the input wires " + str(
        input_wires) + ", which are supplied by Alice, the garbler? Please enter the wire identifiers seperated by commas.")
    alice_wires = input().split(",")

    if len(alice_wires) > 0:  # Alice has at least one input
        print(
            "What are Alice's boolean input values? Please enter a sequence of 0s and 1s corresponding to her input wires, separated by commas.")
        alice_wire_values = list(map(int, input().split(",")))

        # ...therefore, the remaining inputs must be owned by Bob
        for w in input_wires:
            if w not in alice_wires:
                bob_wires.append(w)

        if len(bob_wires) > 0:
            print("The remaining input wires, " + str(bob_wires),
                  " must be supplied by Bob. Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.")
            bob_wire_values = list(map(int, input().split(",")))
        else:
            print("Assuming all inputs are supplied by Alice, and Bob only evaluates.")

    else:  # Alice has no inputs; all inputs must be owned by Bob
        print(
            "Assuming all inputs are supplied by Bob, the evaluator. What are Bob's boolean input values? Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.")
        bob_input_values = input().split(",")

    # TODO Instead of exiting, handle bad user input gracefully.
    assert (len(alice_wires) == len(alice_wire_values))
    assert (len(bob_wire_values) == len(bob_wire_values))

    alice.input_wires = dict(zip(alice_wires, alice_wire_values))
    bob.input_wires = dict(zip(bob_wires, bob_wire_values))

    print()
    print("Successfully generated the following circuit: ")
    circuit = Circuit()
    # at the moment, we only support one output wire; hence output_wires[0]
    # but the infrastructure is in place to change this, if we so desire
    # to do this, we would likely have to represent the circuit as a digraph instead of a tree
    # and reimplement our construction and evaluation algorithms accordingly 
    circuit.build(output_wires[0], gates)
    circuit.tree.show()

    # Give the circuit to Alice to garble
    alice.circuit = circuit

    # Instruct Alice to generate labels and garble garble gates using the generated labels
    print()
    print("Alice generates labels for the circuit, and garbles gates accordingly:")
    alice.garble_gates()

    # Instruct Alice to permute the garbled tables
    print()
    print("Alice permutes the entries in each garbled gate's garbled truth table:")
    alice.permute_entries()

    # Transfer the circuit to Bob
    print()
    print("Alice transfers the circuit to Bob.")
    bob.circuit = alice.circuit

    for wire in alice.input_wires:
        # Transfer the labels corresponding to Alice's input to Bob
        bob.known_labels[wire] = alice.wire_labels[wire][alice.input_wires[wire]]

    # Simulate OT between Alice and Bob so that Bob can acquire labels corresponding to his input
    print()
    print("Bob uses OT to request from Alice labels corresponding to his input bits:")
    bob.request_labels(alice)

    # Instruct Bob to evaluate the circuit
    print()
    print("Bob proceeds to evaluate the circuit:")
    result = bob.evaluate()

    print()
    print("Alice reveals the value of the label that Bob computed as the circuit's output:")
    # Instruct Alice to reveal the result of Bob's computation
    alice.reveal_result(result)
Example #16
0
class BotWrapper:
    def __init__(self,
                 url,
                 magic_phrase,
                 max_turns=10,
                 callback=None,
                 callback_params=1,
                 msg_q=False):
        print('starting service')
        self.start_proba = 1.0
        self.magic_phrase = magic_phrase
        self.url = replace_localhost(url)
        self.bot = Alice()
        self.max_turns = max_turns
        self.sending_message = False
        self._id = None
        self.use_msg_q = msg_q  # msg_q sets whether or not we are queueing messages
        self.websocket = 'ws://%s/websocket' % self.url
        self.client = MeteorClient(self.websocket)
        self.client.ddp_client.ddpsocket.extra_headers = [('Bot', 'true')]
        print(self.client.ddp_client.ddpsocket.handshake_headers)
        self.client.connect()

        self.idle_time = 3 * 60
        self.thread_time = 2
        self.max_retry = 3

    def restart_idler(self):
        ''' Restarts the idle watcher '''
        print('restarting idler')
        if hasattr(self, 'idler_thread') and self.idler_thread:
            self.idler_thread.cancel()
        self.idler_thread = threading.Timer(self.idle_time,
                                            self.idle_user_handler)
        self.idler_thread.start()

    def idle_user_handler(self):
        """ Handler that disconnects conversation in the event that a user leaves """

        print('user is idle disconnect')
        self.idler_thread = None
        self.end_convo()

    def login(self,
              user='******',
              pwd='botbot',
              callback=None,
              callback_params=0):
        print('logging in')

        def set_user(data):
            self.set_user_id(data['id'])
            print('user id set to', self._id)
            if callback and callback_params == 1:
                print('running callback with 1 parameter')
                callback(self)
            elif callback and callback_params == 0:
                callback()

        # TODO make this into threading timers.
        while not self._id:
            self.client.login(user,
                              pwd,
                              callback=func_wrap(set_user, params=1))
            time.sleep(0.5)

    def logout(self):
        self.client.logout()


#    def find_and_join_room(self):
#        """ Finds a room and joins it """
#        self.find_room(callback=(lambda roomId : self.join_room(roomId)))
#
#    def find_room(self, callback=None):
#        print('looking for an open room')
#        def room_callback():
#            print('looking for a room')
#            user = self.client.find_one('users')
#            print('user dict',user.items())
#            if user["in_convo"]:
#                roomObj = user["curConvo"]
#                print('roomid: ', roomObj)
#            else:
#                openrooms = self.client.find('convos') # {curSessions : {$lt  :2}}
#                roomObj = openrooms[0] if openrooms and len(openrooms) > 0 else -1
#
#            # TODO may have issues with room id when user is in convo
#            if roomObj != -1:
#                if type(roomObj) == str:
#                    print(roomObj, 'room')
#                    print('openrooms', openrooms)
#                callback(roomObj['_id'])
#                # Add user to room
#
#            else:
#                print('No rooms found. Back to the bat cave')
#        self.subscribe('currentUser',params=[], callback=func_wrap(
#            lambda : room_callback()
#            )
#        )

    def subscribe(self, collection, params=[], callback=None):
        """ Wrapper for subscribe to avoid issues with already subscribed rooms """
        try:
            print("subscribing to {}".format(collection))
            self.client.subscribe(collection, params, callback)
        except MeteorClientException:
            print(
                'Already subscribed to {}. Running callback with None'.format(
                    collection))
            if callback:
                callback(None)

    def join_room(self, roomId, otherUserId, callback=None):
        """ Join a room based on roomId """
        print('join room with id', roomId)
        self.roomId = roomId
        self.msg_queue = []
        self.available = False
        self.client.call(
            'convos.addUserToRoom',
            params=[roomId, self.magic_phrase],
            callback=func_wrap(lambda: self.subscribe(
                'chat', [roomId],
                func_wrap(lambda: self.subscribe(
                    'msgs', [roomId],
                    func_wrap(lambda: self.subscribe(
                        'currentUsers', [roomId],
                        func_wrap(lambda: self.watch_room(
                            roomId,
                            func_wrap(lambda: self.send_ready(
                                roomId, otherUserId, callback)))))))))))

    def send_ready(self, roomId, otherUserId, callback=None):
        self.client.call('convos.botReady',
                         params=[roomId, otherUserId, self.magic_phrase],
                         callback=callback)

    def unsubscribe(self, collection):
        """ Unsubscribe from the collection """
        try:
            self.client.unsubscribe(collection)
        except MeteorClientException:
            print('\t"{}" not subscribed to.'.format(collection))

    def end_convo(self):
        """ End the conversation """
        print('end conversation and unsubscribe from it all')
        self.client.remove_all_listeners('added')
        self.client.remove_all_listeners('changed')

        self.unsubscribe('chat')
        self.unsubscribe('msgs')
        self.unsubscribe('currentUsers')

        self.client.call('users.exitConvo', [])
        self.client.call('convos.updateRatings', [self.roomId, 'not'])
        self.available = True
        if hasattr(self, 'idler_thread') and self.idler_thread:
            self.idler_thread.cancel()

    def set_wpm(self):
        """ Set the words per minute of the bot """
        wpm = random.randint(150, 200)
        self.cps = 60 / (wpm * 5)
        print('Setting wpm : {} '.format(wpm))

    def prime_bot(self, convo_obj):
        """  the conversational bot """
        print('convo_obj', convo_obj)
        input_msg = 'hi'
        if 'msgs' in convo_obj and convo_obj['msgs']:
            topic_msg_id = convo_obj['msgs'][0]
            msg_obj = self.client.find_one('messages',
                                           selector={'_id': topic_msg_id})
            if msg_obj:
                input_msg = msg_obj['message']

        msg = self.bot.message(input_msg, self.roomId)
        if random.random() > self.start_proba:
            self.send_message(msg)

    def watch_room(self, roomId, callback=None):
        """
        Setup Event Listeneres for a room and checks to make sure that the room is updating
        """
        self.turns = 0
        convo_obj = self.client.find_one('convos', selector={'_id': roomId})
        self.room_closed = convo_obj['closed']
        self.set_wpm()

        self.last_message = ""
        self.confirmed_messages = [
        ]  # all messages sent by the user that have been confirmed
        self.thread = MessageHandlerThread(self)

        def message_added(collection, id, fields):
            """ callback for when a message is added """
            if (collection == 'messages' and 'message' in fields
                    and 'user' in fields):
                print(type(self._id), type(fields['user']), self._id,
                      fields['user'])
                if fields['user'] != self._id and self.last_message != fields[
                        'message']:
                    self.restart_idler()
                    self.receive_message(fields['message'])
                    self.last_message = fields['message']
                    self.thread.message_received = True
                elif fields['user'] == self._id:
                    print('\t messages from self detected')
                    self.confirmed_messages.append(fields['message'])

        self.client.on('added', message_added)

        def watch_convo(collection, id, fields, cleared):
            """ callback for when any part of the conversation is updated """
            if self.roomId and collection == "convos" and id == self.roomId:
                # print('\t',fields)
                if 'closed' in fields:
                    print('\tRoom is closed: ', fields['closed'])
                    self.room_closed = fields['closed']
                    self.end_convo()
                if 'msgs' in fields:
                    print('\tMessages updated in convo "{}"'.format(id))
                    # TODO this is bugggy
                    self.thread.convo_updated = True
                if 'turns' in fields:
                    print('\tTurns updated to "{}"'.format(fields['turns']))
                    self.turns = fields['turns']
            elif self.roomId == id:
                print(collection, id, fields)

        self.client.on('changed', watch_convo)
        # mark the bot as ready to talk
        self.restart_idler()
        self.prime_bot(convo_obj)
        print("before thread")
        self.thread.start()
        print("after thread")

        if callback:
            callback(None)

    def respond(self):
        """ Kind of a hacky way to respond to the conversation """
        print("responding")
        if self.msg_queue and self.use_msg_q:
            partner_msg = self.msg_queue[0]
            self.msg_queue = self.msg_queue[1:]
            msg = self.bot.message(partner_msg, self.roomId)
            print(msg)
            self.send_message(msg)

        if self.msg_queue and not self.sending_message:
            partner_msg = self.msg_queue[-1]
            self.msg_queue = self.msg_queue[:-1]
            msg = self.bot.message(partner_msg, self.roomId)
            print(msg)
            self.send_message(msg)

    def still_in_conv(self):
        """ Returns whether the conversation is still moving """
        in_conv = self.roomId != None and not self.client.find_one(
            'convos', selector={'_id': self.roomId})['closed']
        print('\tstill in conv', in_conv)
        if not in_conv:
            self.end_convo()
        print(
            '\tclosed: ',
            self.client.find_one('convos', selector={'_id':
                                                     self.roomId})['closed'])
        return in_conv

    def get_convo_dict(self):
        if self.roomId:
            return self.client.find_one('convos',
                                        selector={'_id': self.roomId})
        else:
            return {}

    def get_message(self, idx):
        ''' Returns the message at idx'''
        convo_dict = self.get_convo_dict()
        if convo_dict:
            topic_msg_id = convo_dict['msgs'][idx]
            msg_dict = self.client.find_one('messages',
                                            selector={'_id': topic_msg_id})
            # print(msg_dict)
            if msg_dict:
                return msg_dict['message']
        return ''

    def received_message(self, message):
        """ Checks whether the bot actually sent the message """
        # TODO add handler that removes a confirmed message to save memory
        return message in self.confirmed_messages

    def retry_message(self, message, retry=0, callback=None):
        """ Handler that makes attempts to connect a user back into a conversation """
        # TODO set as properties
        if retry == 0 or not self.received_message(
                message) and retry < self.max_retry:
            self.update_conversation(message, callback)

            if retry != 0:
                print('\t\tRetry {} of sending "{}"'.format(retry, message))

            t = threading.Timer(self.thread_time,
                                lambda: self.retry_message(message, retry + 1))
            t.start()
        elif retry >= self.max_retry:
            print(
                '\tMax retries reached - couldn\'t verify whether {} was received'
                .format(message))
        else:
            print('\t"{}" successfully received'.format(message))

    def update_conversation(self, message, callback=None):
        self.client.call('convos.updateChat', [message, self.roomId], callback)

    def _send_message(self, message, callback=None):
        self.last_message_sent = message
        if self.still_in_conv():
            self.retry_message(message, callback=callback)
        else:
            print('Not responding - conversation is OVER')
        self.sending_message = False

    def send_message(self, message, callback=None):
        # calculates typing speed based on rough cps for user
        sleep_time = self.cps * len(message)
        print("Preparing to send '{}' Waiting '{}' seconds.".format(
            message, sleep_time))
        t = threading.Timer(sleep_time,
                            lambda: self._send_message(message, callback))
        t.start()

    def receive_message(self, message):
        """ Called whenever the bot receives a message """
        print('Received "{}"'.format(message))
        self.msg_queue.append(message)
        # message = 'sup then' # self.bot.message(message)

        # self.send_message(message)

    def set_user_id(self, id):
        self.available = True
        print('set user id to ', id)
        self._id = id
Example #17
0
import random
from alice import Alice
from bob import Bob
from eve import Eve
from matplotlib import pyplot as plt
import pandas as pd

alice = Alice()
bob = Bob()
eve = Eve()
num_bits = [500]
bits = []
basis = []
qc_polarization = []  #양자채널로 보내진 polarization
count = 0
QBER = []
sum_QBER = 0
sum_data = 0
eavesdropping_rate = 0.1

for i in range(0, len(num_bits)):

    #print("비트의 개수 : ",num_bits[i])

    while (eavesdropping_rate <= 1):

        random.seed()

        alice.reset()
        bob.reset()
        eve.reset()
Example #18
0
# O "canal" representa o ambiente inseguro onde haverá a comunicação entre Bob e Alice
canal = "canal.txt"

# O caminho_chave_privada serve para provar que seus números secretos podem ser diferentes e que resultam na mesma chave privada
# NÃO É UTILIZADO EM UM SISTEMA DH REAL
caminho_chave_privada_alice = "chave_privada_alice.txt"
caminho_chave_privada_bob = "chave_privada_bob.txt"

# Limpa os arquivos privados e o canal público
limpa_canais(canal, caminho_chave_privada_alice, caminho_chave_privada_bob)

# É selecionado aleatoriamente um número primo positivo até 1000 e calculado sua menor raiz primitiva
(g, p) = calcula_raiz_primitiva_e_primo()

# São criados Alice e Bob recebendo o gerador e o número primo pelo canal público
alice = Alice(canal, caminho_chave_privada_alice, g, p)
bob = Bob(canal, caminho_chave_privada_bob, g, p)
input()

# Ada e Bob vão armazenar localmente as variáveis g e p que eles escolheram pelo público
alice.calcula_e_grava_A()
bob.calcula_e_grava_B()
input()

# Ada e Bob vão ler os resultados das chaves intermediárias um do outro que foram passados pela rede pública
alice.ler_B()
bob.ler_A()

# Os números secretos são salvos para provar que mesmo podendo ser diferentes, a chave privada é idêntica
# Ada e Bob vão gravar localmente sua chave privada, que será usada para descriptografar as mensagens
alice.mostrar_chave_secreta()
Example #19
0
def main_2():
    alice = Alice()
    bob = Bob()
    network = Network()