Example #1
0
def entangle(host):  # 01 - 10
    q1 = Qubit(host)
    q2 = Qubit(host)
    q1.X()
    q1.H()
    q2.X()
    q1.cnot(q2)
    return q1, q2
Example #2
0
File: e91.py Project: tqsd/QuNetSim
def alice(alice, bob, number_of_entanglement_pairs):
    angles = [0, np.pi / 4, np.pi / 2]
    bases_choice = [
        random.randint(1, 3) for i in range(number_of_entanglement_pairs)
    ]
    test_results_alice = []
    test_bases_alice = []
    sifted_key_alice = []

    for i in range(number_of_entanglement_pairs):

        qubit_a = Qubit(alice)
        qubit_b = Qubit(alice)

        # preparation of singlet state (1/sqrt(2))*(|01> - |10>)
        qubit_a.X()
        qubit_b.X()
        qubit_a.H()
        qubit_a.cnot(qubit_b)

        print('Sending EPR pair %d' % (i + 1))
        _, ack_arrived = alice.send_qubit(bob, qubit_b, await_ack=True)
        if ack_arrived:

            #rotate qubit and measure
            base_a = bases_choice[i]
            qubit_a.rz(angles[base_a - 1])
            meas_a = qubit_a.measure()

            ack_arrived = alice.send_classical(bob, base_a, await_ack=True)
            if not ack_arrived:
                print("Send data failed!")

            message = alice.get_next_classical(bob, wait=2)
            if message is not None:
                base_b = message.content

                if (base_a == 2 and base_b == 1) or (base_a == 3
                                                     and base_b == 2):
                    sifted_key_alice.append(meas_a)
                elif (base_a == 1
                      and base_b == 1) or (base_a == 1 and base_b == 3) or (
                          base_a == 3 and base_b == 1) or (base_a == 3
                                                           and base_b == 3):
                    test_bases_alice.append('a' + str(base_a))
                    test_results_alice.append(str(meas_a))
            else:
                print("The message did not arrive")
        else:
            print('The EPR pair was not properly established')

    ack_arrived = alice.send_classical(bob,
                                       (test_results_alice, test_bases_alice),
                                       await_ack=True)
    if not ack_arrived:
        print("Send data failed!")

    print("Sifted_key_alice: ", sifted_key_alice)
Example #3
0
def q_bit(host, encode):
    q = Qubit(host)
    if encode == '+':
        q.H()
    if encode == '-':
        q.X()
        q.H()
    if encode == '0':
        q.I()
    if encode == '1':
        q.X()
    return q
Example #4
0
    def test_teleport_superdense_combination(self):
        global hosts

        hosts['alice'].send_superdense(hosts['bob'].host_id, '11')
        messages = hosts['bob'].classical
        i = 0
        while i < TestOneHop.MAX_WAIT and len(messages) == 0:
            messages = hosts['bob'].classical
            i += 1
            time.sleep(1)

        q = Qubit(hosts['alice'])
        q.X()

        hosts['alice'].send_teleport(hosts['bob'].host_id, q)
        q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
        i = 0
        while q2 is None and i < TestOneHop.MAX_WAIT:
            q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
            i += 1
            time.sleep(1)

        self.assertIsNotNone(messages)
        self.assertTrue(len(messages) > 0)
        self.assertEqual(messages[0].sender, hosts['alice'].host_id)
        self.assertEqual(messages[0].content, '11')

        self.assertIsNotNone(q2)
        assert q2 is not None
        self.assertEqual(q2.measure(), 1)
Example #5
0
def main():
    backend = CQCBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.7
    hosts = {'alice': Host('Alice', backend), 'bob': Host('Bob', backend)}

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    q = Qubit(hosts['alice'])
    q.X()

    q_id = hosts['alice'].send_qubit(hosts['bob'].host_id, q)
    i = 0
    rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
    while i < 5 and rec_q is None:
        rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
        i += 1
        time.sleep(1)

    assert rec_q is not None
    assert rec_q.measure() == 1
    print("All tests succesfull!")
    network.stop(True)
    exit()
Example #6
0
    def test_epr_teleport_combination(self):
        q = Qubit(hosts['alice'])
        q.X()

        q_id = hosts['alice'].send_epr(hosts['eve'].host_id)
        hosts['alice'].send_teleport(hosts['eve'].host_id, q)

        q1_epr = None
        q2_epr = None
        q_teleport = None

        q1_epr = hosts['alice'].get_epr(hosts['eve'].host_id,
                                        q_id,
                                        wait=TestTwoHop.MAX_WAIT)

        q2_epr = hosts['eve'].get_epr(hosts['alice'].host_id,
                                      q_id,
                                      wait=TestTwoHop.MAX_WAIT)

        q_teleport = hosts['eve'].get_data_qubit(hosts['alice'].host_id,
                                                 wait=TestTwoHop.MAX_WAIT)

        self.assertIsNotNone(q1_epr)
        self.assertIsNotNone(q2_epr)
        self.assertIsNotNone(q_teleport)
        self.assertEqual(q1_epr.measure(), q2_epr.measure())
        self.assertEqual(q_teleport.measure(), 1)
Example #7
0
def main():
    network = Network.get_instance()
    network.start()

    host_alice = Host('Alice')
    host_bob = Host('Bob')
    host_eve = Host('Eve')

    host_alice.add_connection('Bob')
    host_bob.add_connections(['Alice', 'Eve'])
    host_eve.add_connection('Bob')

    host_alice.start()
    host_bob.start()
    host_eve.start()

    network.add_hosts([host_alice, host_bob, host_eve])

    q = Qubit(host_alice)
    print(q.id)
    q.X()

    host_alice.send_epr('Eve', await_ack=True)
    print('done')
    host_alice.send_teleport('Eve', q, await_ack=True)
    q_eve = host_eve.get_data_qubit(host_alice.host_id, q.id, wait=5)

    assert q_eve is not None
    print(q.id)
    print('Eve measures: %d' % q_eve.measure())
    network.stop(True)
Example #8
0
def qubit_send_w_retransmission(host, q_size, receiver_id, checksum_size_per_qubit):
    """
    Sends the data qubits along with checksum qubits , with the possibility of retransmission.

    :param host: Sender of qubits
    :param q_size: Number of qubits to be sent
    :param receiver_id: ID of the receiver
    :param checksum_size_per_qubit: Checksum qubit per data qubit size
    :return:
    """
    bit_arr = np.random.randint(2, size=q_size)
    print('Bit array to be sent: ' + str(bit_arr))
    qubits = []
    for i in range(q_size):
        q_tmp = Qubit(host)
        if bit_arr[i] == 1:
            q_tmp.X()
        qubits.append(q_tmp)

    check_qubits = host.add_checksum(qubits, checksum_size_per_qubit)
    checksum_size = int(q_size / checksum_size_per_qubit)
    qubits.append(check_qubits)
    checksum_cnt = 0
    for i in range(q_size + checksum_size):
        if i < q_size:
            q = qubits[i]
        else:
            q = qubits[q_size][checksum_cnt]
            checksum_cnt = checksum_cnt + 1

        q_success = False
        got_ack = False
        number_of_retransmissions = 0

        while not got_ack and number_of_retransmissions < MAX_NUM_OF_TRANSMISSIONS:
            print('Alice prepares qubit')
            err_1 = Qubit(host)
            # encode logical qubit
            q.cnot(err_1)

            _, ack_received = host.send_qubit(receiver_id, q, await_ack=True)
            if ack_received:
                err_1.release()
                got_ack = True
                q_success = True

            if not q_success:
                print('Alice: Bob did not receive the qubit')
                # re-introduce a qubit to the system and correct the error
                q = Qubit(host)
                err_1.cnot(q)

            number_of_retransmissions += 1

        if number_of_retransmissions == 10:
            print("Alice: too many attempts made")
            return False
    return True
Example #9
0
 def encode(self, host_sender, bitstring, bases):
     encoded_qubits = []
     for i in range(len(bitstring)):
         q = Qubit(host_sender)
         if bases[i] == "0":
             if bitstring[i] == "0":
                 pass  # initialized in 0
             elif bitstring[i] == "1":
                 q.X()
         elif bases[i] == "1":
             if bitstring[i] == "0":
                 q.H()
             elif bitstring[i] == "1":
                 q.X()
                 q.H()
         encoded_qubits.append(q)
     # Stop the network at the end of the example
     # network.stop(stop_hosts=True)
     return encoded_qubits
Example #10
0
def alice(host):
    for _ in range(AMOUNT_TRANSMIT):
        s = 'Hi Eve.'
        print("Alice sends: %s" % s)
        host.send_classical('Eve', s, await_ack=True)

    for _ in range(AMOUNT_TRANSMIT):
        print("Alice sends qubit in the |1> state")
        q = Qubit(host)
        q.X()
        host.send_qubit('Eve', q, await_ack=True)
Example #11
0
def alice(host):
    for _ in range(amount_transmit):
        s = 'Hi Eve.'
        print("Alice sends: %s" % s)
        host.send_classical('Eve', s, await_ack=True)

    for _ in range(amount_transmit):
        print("Alice sends qubit in the |1> state")
        q = Qubit(host)
        q.X()
        host.send_qubit('Eve', q, await_ack=False)
Example #12
0
    def test_teleport(self):
        q = Qubit(hosts['alice'])
        q.X()

        hosts['alice'].send_teleport(hosts['eve'].host_id, q)
        q2 = None
        i = 0
        while i < TestTwoHop.MAX_WAIT and q2 is None:
            q2 = hosts['eve'].get_data_qubit(hosts['alice'].host_id)
            i += 1
            time.sleep(1)

        self.assertIsNotNone(q2)
        self.assertEqual(q2.measure(), 1)
Example #13
0
    def preparation_and_distribution():
        for serial in range(NO_OF_SERIALS):
            for bit_no in range(QUBITS_PER_MONEY):
                random_bit = randint(0, 1)
                random_base = randint(0, 1)

                bank_bits[serial].append(random_bit)
                bank_basis[serial].append(random_base)
                q = Qubit(host)
                if random_bit == 1:
                    q.X()
                if random_base == 1:
                    q.H()
                host.send_qubit(customer, q, True)
Example #14
0
def main():
    backend = CQCBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.7
    hosts = {'alice': Host('Alice', backend), 'bob': Host('Bob', backend)}

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    hosts['alice'].send_superdense(hosts['bob'].host_id, '11')

    messages = hosts['bob'].classical
    i = 0
    while i < 5 and len(messages) == 0:
        messages = hosts['bob'].classical
        i += 1
        time.sleep(1)

    q = Qubit(hosts['alice'])
    q.X()

    hosts['alice'].send_teleport(hosts['bob'].host_id, q)
    q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
    i = 0
    while q2 is None and i < 5:
        q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
        i += 1
        time.sleep(1)

    assert messages is not None
    assert len(messages) > 0
    assert (messages[0].sender == hosts['alice'].host_id)
    assert (messages[0].content == '11')

    assert q2 is not None
    assert (q2.measure() == 1)
    print("All tests succesfull!")
    network.stop(True)
    exit()
Example #15
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    network.delay = 0.1

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.add_connection('Dean')
    host_eve.start()

    host_dean = Host('Dean')
    host_dean.add_connection('Eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    # Create a qubit owned by Alice
    q = Qubit(host_alice)
    # Put the qubit in the excited state
    q.X()
    # Send the qubit and await an ACK from Dean
    q_id = host_alice.send_qubit('Dean', q, no_ack=True)

    # Get the qubit on Dean's side from Alice
    q_rec = host_dean.get_data_qubit('Alice', q_id)

    # Ensure the qubit arrived and then measure and print the results.
    if q_rec is not None:
        m = q_rec.measure()
        print("Results of the measurements for q_id are ", str(m))
    else:
        print('q_rec is none')

    network.stop(True)
    exit()
Example #16
0
    def test_send_qubit_alice_to_bob(self):
        global hosts

        q = Qubit(hosts['alice'])
        q.X()

        q_id = hosts['alice'].send_qubit(hosts['bob'].host_id, q)
        i = 0
        rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
        while i < TestOneHop.MAX_WAIT and rec_q is None:
            rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
            i += 1
            time.sleep(1)

        self.assertIsNotNone(rec_q)
        self.assertEqual(rec_q.measure(), 1)
Example #17
0
def sender(host, distributor, r, epr_id):
    q = host.get_ghz(distributor, wait=10)
    b = random.choice(['0', '1'])
    host.send_broadcast(b)
    if b == '1':
        q.Z()

    host.add_epr(r, q, q_id=epr_id)
    sending_qubit = Qubit(host)
    sending_qubit.X()
    print('Sending %s' % sending_qubit.id)
    # Generate EPR if none shouldn't change anything, but if there is
    # no shared entanglement between s and r, then there should
    # be a mistake in the protocol
    host.send_teleport(r, sending_qubit, generate_epr_if_none=False, await_ack=False)
    host.empty_classical()
Example #18
0
    def test_channel_BEC_failure(self):
        global hosts

        hosts['alice'].quantum_connections[
            hosts['bob'].host_id].model = BinaryErasure(probability=1.0)
        q = Qubit(hosts['alice'])
        q.X()

        q_id = hosts['alice'].send_qubit(hosts['bob'].host_id, q)
        i = 0
        rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
        while i < TestChannel.MAX_WAIT and rec_q is None:
            rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
            i += 1
            time.sleep(1)

        self.assertIsNone(rec_q)
Example #19
0
    def test_teleport(self):
        global hosts

        q = Qubit(hosts['alice'])
        q.X()

        hosts['alice'].send_teleport(hosts['bob'].host_id, q)

        q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
        i = 0
        while q2 is None and i < TestOneHop.MAX_WAIT:
            q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
            i += 1
            time.sleep(1)

        self.assertIsNotNone(q2)
        assert q2 is not None
        self.assertEqual(q2.measure(), 1)
Example #20
0
def _send_key(packet):
    receiver = network.get_host(packet.receiver)
    sender = network.get_host(packet.sender)
    key_size = packet.payload[Constants.KEYSIZE]

    packet.protocol = Constants.KEY
    network.send(packet)

    secret_key = np.random.randint(2, size=key_size)
    msg_buff = []
    sender.qkd_keys[receiver.host_id] = secret_key.tolist()
    sequence_nr = 0
    # iterate over all bits in the secret key.
    for bit in secret_key:
        ack = False
        while not ack:
            # get a random base. 0 for Z base and 1 for X base.
            base = random.randint(0, 1)

            # create qubit
            q_bit = Qubit(sender)
            # Set qubit to the bit from the secret key.
            if bit == 1:
                q_bit.X()

            # Apply basis change to the bit if necessary.
            if base == 1:
                q_bit.H()

            # Send Qubit to Receiver
            sender.send_qubit(receiver.host_id, q_bit, await_ack=True)
            # Get measured basis of Receiver
            message = sender.get_next_classical_message(receiver.host_id, msg_buff, sequence_nr)
            # Compare to send basis, if same, answer with 0 and set ack True and go to next bit,
            # otherwise, send 1 and repeat.
            if message == "%d:%d" % (sequence_nr, base):
                ack = True
                sender.send_classical(receiver.host_id, ("%d:0" % sequence_nr), await_ack=True)
            else:
                ack = False
                sender.send_classical(receiver.host_id, ("%d:1" % sequence_nr), await_ack=True)

            sequence_nr += 1
Example #21
0
    def test_channel_Fibre_failure(self):
        global hosts

        hosts['alice'].quantum_connections[hosts['bob'].host_id].model = Fibre(
            length=10000000.0, alpha=1.0)
        q = Qubit(hosts['alice'])
        q.X()

        q_id = hosts['alice'].send_qubit(hosts['bob'].host_id, q)
        i = 0
        rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
        while i < TestChannel.MAX_WAIT and rec_q is None:
            rec_q = hosts['bob'].get_data_qubit(hosts['alice'].host_id, q_id)
            i += 1
            time.sleep(1)

        self.assertEqual(
            hosts['alice'].quantum_connections[
                hosts['bob'].host_id].model.transmission_p, 0.0)
        self.assertIsNone(rec_q)
Example #22
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    hosts = {'alice': Host('Alice'), 'bob': Host('Bob'), 'eve': Host('Eve')}

    network.delay = 0

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    # B <-> E
    hosts['bob'].add_connection('Eve')
    hosts['eve'].add_connection('Bob')

    hosts['alice'].start()
    hosts['bob'].start()
    hosts['eve'].start()

    for h in hosts.values():
        network.add_host(h)

    q = Qubit(hosts['alice'])
    q.X()
    q_id = hosts['alice'].send_qubit(hosts['eve'].host_id, q)

    i = 0
    q1 = None
    while i < MAX_WAIT and q1 is None:
        q1 = hosts['eve'].get_data_qubit(hosts['alice'].host_id, q_id)
        i += 1
        time.sleep(1)

    assert q1 != None
    assert q1.measure() == 1

    print("All tests succesfull!")
    network.stop(True)
    exit()
Example #23
0
def alice_qkd(alice, msg_buff, secret_key, receiver):
    sequence_nr = 0
    # iterate over all bits in the secret key.
    for bit in secret_key:
        ack = False
        while not ack:
            print("Alice sent %d key bits" % (sequence_nr + 1))
            # get a random base. 0 for Z base and 1 for X base.
            base = random.randint(0, 1)

            # create qubit
            q_bit = Qubit(alice)

            # Set qubit to the bit from the secret key.
            if bit == 1:
                q_bit.X()

            # Apply basis change to the bit if necessary.
            if base == 1:
                q_bit.H()

            # Send Qubit to Bob
            alice.send_qubit(receiver, q_bit, await_ack=True)

            # Get measured basis of Bob
            message = alice.get_next_classical_message(receiver, msg_buff,
                                                       sequence_nr)

            # Compare to send basis, if same, answer with 0 and set ack True and go to next bit,
            # otherwise, send 1 and repeat.
            if message == ("%d:%d") % (sequence_nr, base):
                ack = True
                alice.send_classical(receiver, ("%d:0" % sequence_nr),
                                     await_ack=True)
            else:
                ack = False
                alice.send_classical(receiver, ("%d:1" % sequence_nr),
                                     await_ack=True)

            sequence_nr += 1
Example #24
0
    def test_epr_teleport_combination(self):
        q = Qubit(hosts['alice'])
        q.X()

        q_id = hosts['alice'].send_epr(hosts['eve'].host_id)
        hosts['alice'].send_teleport(hosts['eve'].host_id, q)

        q1_epr = None
        q2_epr = None
        q_teleport = None

        i = 0
        while q1_epr is None and i < TestTwoHop.MAX_WAIT:
            q1_epr = hosts['alice'].get_epr(hosts['eve'].host_id, q_id)
            if q1_epr is not None:
                q1_epr = q1_epr
            i += 1
            time.sleep(1)

        i = 0
        while q2_epr is None and i < TestTwoHop.MAX_WAIT:
            q2_epr = hosts['eve'].get_epr(hosts['alice'].host_id, q_id)
            if q2_epr is not None:
                q2_epr = q2_epr
            i += 1
            time.sleep(1)

        i = 0
        while q_teleport is None and i < TestTwoHop.MAX_WAIT:
            q_teleport = hosts['eve'].get_data_qubit(hosts['alice'].host_id)
            if q_teleport is not None:
                q_teleport = q_teleport
            i += 1
            time.sleep(1)

        self.assertIsNotNone(q1_epr)
        self.assertIsNotNone(q2_epr)
        self.assertIsNotNone(q_teleport)
        self.assertEqual(q1_epr.measure(), q2_epr.measure())
        self.assertEqual(q_teleport.measure(), 1)
Example #25
0
def checksum_sender(host, q_size, receiver_id, checksum_size_per_qubit):
    bit_arr = np.random.randint(2, size=q_size)
    Logger.get_instance().log('Bit array to be sent: ' + str(bit_arr))
    qubits = []
    for i in range(q_size):
        q_tmp = Qubit(host)
        if bit_arr[i] == 1:
            q_tmp.X()
        qubits.append(q_tmp)

    check_qubits = host.add_checksum(qubits, checksum_size_per_qubit)
    checksum_size = int(q_size / checksum_size_per_qubit)
    qubits.append(check_qubits)
    checksum_cnt = 0
    for i in range(q_size + checksum_size):
        if i < q_size:
            q = qubits[i]
        else:
            q = qubits[q_size][checksum_cnt]
            checksum_cnt = checksum_cnt + 1

        host.send_qubit(receiver_id, q, await_ack=True)
Example #26
0
def qudp_sender(host, q_size, receiver_id):
    bit_arr = np.random.randint(2, size=q_size)
    data_qubits = []

    checksum_size = 3
    checksum_per_qubit = int(q_size / checksum_size)

    print('---------')
    print('Sender sends the classical bits: ' + str(bit_arr))
    print('---------')

    for i in range(q_size):
        q_tmp = Qubit(host)
        if bit_arr[i] == 1:
            q_tmp.X()
        data_qubits.append(q_tmp)

    checksum_qubits = host.add_checksum(data_qubits, checksum_per_qubit)
    data_qubits.extend(checksum_qubits)
    host.send_classical(receiver_id, checksum_size, await_ack=False)

    for q in data_qubits:
        host.send_qubit(receiver_id, q, await_ack=False)
Example #27
0
    def test_single_gates(self):
        for b in TestBackend.backends:
            backend = b()
            network = Network.get_instance()
            network.start(["Alice", "Bob"], backend)
            alice = Host('Alice', backend)
            bob = Host('Bob', backend)
            alice.start()
            bob.start()
            network.add_host(alice)
            network.add_host(bob)

            q = Qubit(alice)

            q.X()
            self.assertEqual(1, q.measure())

            q = Qubit(alice)

            q.H()
            q.H()
            self.assertEqual(0, q.measure())

            network.stop(True)
Example #28
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    hosts = {'alice': Host('Alice'),
             'bob': Host('Bob'),
             'eve': Host('Eve')}

    network.delay = 0

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    # B <-> E
    hosts['bob'].add_connection('Eve')
    hosts['eve'].add_connection('Bob')

    hosts['alice'].start()
    hosts['bob'].start()
    hosts['eve'].start()

    for h in hosts.values():
        network.add_host(h)

    q = Qubit(hosts['alice'])
    q.X()

    q_id = hosts['alice'].send_epr(hosts['eve'].host_id)

    # TODO: Why do we need this to pass the test?
    time.sleep(6)

    hosts['alice'].send_teleport(hosts['eve'].host_id, q)

    q1_epr = None
    q2_epr = None
    q_teleport = None

    i = 0
    while q1_epr is None and i < MAX_WAIT:
        q1_epr = hosts['alice'].get_epr(hosts['eve'].host_id, q_id)
        if q1_epr is not None:
            q1_epr = q1_epr
        i += 1
        time.sleep(1)

    i = 0
    while q2_epr is None and i < MAX_WAIT:
        q2_epr = hosts['eve'].get_epr(hosts['alice'].host_id, q_id)
        if q2_epr is not None:
            q2_epr = q2_epr
        i += 1
        time.sleep(1)

    i = 0
    while q_teleport is None and i < MAX_WAIT:
        q_teleport = hosts['eve'].get_data_qubit(hosts['alice'].host_id)
        if q_teleport is not None:
            q_teleport = q_teleport
        i += 1
        time.sleep(1)

    assert q1_epr is not None
    assert q2_epr is not None
    assert q_teleport is not None
    assert q1_epr.measure() == q2_epr.measure()
    assert(q_teleport.measure() == 1)
    print("All tests succesfull!")
    network.stop(True)
    exit()
Example #29
0
def _send_key(packet):
    def helper_recv(host, receive_from_id, buffer, sequence_nr):
        buffer.append(host.get_next_classical(receive_from_id, wait=-1))
        msg = "ACK"
        while msg == "ACK" or (msg.split(':')[0] != ("%d" % sequence_nr)):
            if len(buffer) == 0:
                buffer.append(host.get_next_classical(receive_from_id,
                                                      wait=-1))
            ele = buffer.pop(0)
            msg = ele.content
        return msg

    receiver = network.get_host(packet.receiver)
    sender = network.get_host(packet.sender)
    key_size = packet.payload[Constants.KEYSIZE]

    packet.protocol = Constants.REC_KEY
    network.send(packet)

    secret_key = []
    msg_buff = []
    sequence_nr = 0
    attempt_counter = 0

    # iterate over all bits in the secret key.
    for _ in range(key_size):
        ack = False
        while not ack:
            # get a random base. 0 for Z base and 1 for X base.
            base = random.randint(0, 1)
            bit = random.randint(0, 1)

            # create qubit
            q_bit = Qubit(sender)
            # Set qubit to the bit from the secret key.
            if bit == 1:
                q_bit.X()

            # Apply basis change to the bit if necessary.
            if base == 1:
                q_bit.H()

            # Send Qubit to Receiver
            sender.send_qubit(receiver.host_id, q_bit, await_ack=True)
            # Get measured basis of Receiver
            message = helper_recv(sender, receiver.host_id, msg_buff,
                                  sequence_nr)
            # Compare to send basis, if same, answer with 0 and set ack True and go to next bit,
            # otherwise, send 1 and repeat.
            if message == "%d:%d" % (sequence_nr, base):
                ack = True
                # Bit got accepted, add to key
                secret_key.append(bit)
                sender.send_classical(receiver.host_id, ("%d:0" % sequence_nr),
                                      await_ack=True)
            else:
                ack = False
                sender.send_classical(receiver.host_id, ("%d:1" % sequence_nr),
                                      await_ack=True)

            sequence_nr += 1
            attempt_counter += 1

    # Add key to keys of sender
    sender.qkd_keys[receiver.host_id] = (secret_key, attempt_counter)
Example #30
0
 def alice_do(s):
     q = Qubit(hosts['alice'])
     q.X()
     time.sleep(1)
     _ = hosts['alice'].send_qubit(hosts['bob'].host_id, q)