Пример #1
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    backend = CQCBackend()
    network.start(nodes, backend)
    network.delay = 0.7

    hosts = {'alice': Host('Alice', backend), 'bob': Host('Bob', backend)}

    network.delay = 0
    # 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)

    q1 = Qubit(hosts['alice'])
    hosts['alice'].send_qubit('Bob', q1, await_ack=True)
    q1 = Qubit(hosts['alice'])
    hosts['alice'].send_qubit('Bob', q1, await_ack=True)
    q1 = Qubit(hosts['alice'])
    hosts['alice'].send_qubit('Bob', q1, await_ack=True)
    q1 = Qubit(hosts['bob'])
    hosts['bob'].send_qubit('Alice', q1, await_ack=True)
    network.stop(True)
    exit()
Пример #2
0
    def test_get_qubits_by_id(self):
        host = Host('A')
        q1 = Qubit(host)
        q2 = Qubit(host)
        q3 = Qubit(host)

        host2 = Host('B')
        q4 = Qubit(host2)

        host.add_epr('B', q1)
        host.add_data_qubit('C', q2)
        host.add_ghz_qubit('D', q3)

        host2.add_data_qubit('A', q4)

        # Test all types of qubits
        self.assertEqual(q1, host.get_qubit_by_id(q1.id))
        self.assertEqual(q2, host.get_qubit_by_id(q2.id))
        self.assertEqual(q3, host.get_qubit_by_id(q3.id))

        # Test getting qubits from other hosts
        self.assertIsNone(host.get_qubit_by_id(q4.id))

        # Test getting qubits that don't exist
        self.assertIsNone(host.get_qubit_by_id('fake'))
Пример #3
0
def entangle(host):  # 01 - 10
    q1 = Qubit(host)
    q2 = Qubit(host)
    q1.X()
    q1.H()
    q2.X()
    q1.cnot(q2)
    return q1, q2
Пример #4
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
Пример #5
0
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)
Пример #6
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)
Пример #7
0
def protocol_alice(alice, bob, secret_key, sample_len):

    for bit in secret_key:

        q_bit = Qubit(alice)

        if bit == 1:
            q_bit.H()

        alice.send_qubit(bob, q_bit, await_ack=True)

    mes = alice.get_next_classical(bob)
    if mes is not None:
        test = mes.content
        secret_key = element_by_indexes(secret_key, test, 1)

        mes = alice.get_next_classical(bob)
        if mes is not None:
            sample_bob = mes.content

            if sample_bob == secret_key[:sample_len]:
                alice.send_classical(bob, "NO INTERCEPT", await_ack=True)
                print("alice key ", secret_key)
            else:
                alice.send_classical(bob, "EVE IS LISTENING", await_ack=True)
                print("STACCAH STACCAH")
Пример #8
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()
Пример #9
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)
Пример #10
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)
Пример #11
0
    def test_resetting_qubits(self):
        host = Host('A')
        q1 = Qubit(host)
        q2 = Qubit(host)
        q3 = Qubit(host)

        host.add_epr('B', q1)
        host.add_data_qubit('B', q2)
        host.add_ghz_qubit('B', q3)

        qs = host.get_data_qubits('B')
        self.assertEqual(len(qs), 1)

        host.reset_data_qubits('B')
        qs = host.get_data_qubits('B')
        self.assertEqual(len(qs), 0)
Пример #12
0
def teleport(sender, receiver):
    for i in range(10):
        q1 = Qubit(sender)
        sender.send_teleport(receiver.host_id,
                             q1,
                             await_ack=False,
                             no_ack=True)
        q2 = receiver.get_data_qubit(sender.host_id, q1.id, wait=-1)
        _ = q2.measure()
Пример #13
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)
Пример #14
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)
Пример #15
0
    def _establish_epr(self, sender, receiver, q_id, o_seq_num, blocked):
        """
        Instead doing an entanglement swap, for efficiency we establish EPR pairs
        directly for simulation, if an entanglement swap would have been possible.

        Args:
            sender (Host): Sender of the EPR pair
            receiver (Host): Receiver of the EPR pair
            q_id (str): Qubit ID of the sent EPR pair
            o_seq_num (int): The original sequence number
            blocked (bool): If the pair being distributed is blocked or not
        """
        host_sender = self.get_host(sender)
        host_receiver = self.get_host(receiver)
        q1 = Qubit(host_sender)
        q2 = Qubit(host_sender)
        q1.H()
        q1.cnot(q2)
        host_sender.add_epr(receiver, q1, q_id, blocked)
        host_receiver.add_epr(sender, q2, q_id, blocked)
        host_receiver.send_ack(sender, o_seq_num)
Пример #16
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
Пример #17
0
    def _prepare_qubits(self, prepare_qubit_op):
        """
        Follows the operation command to prepare the necessary qubits

        Args:
            prepare_qubit_op (Dict): Dictionary of information regarding
                the operation
        """

        qubits = {}
        for qubit_id in prepare_qubit_op['qids']:
            qubits[qubit_id] = Qubit(host=self, q_id=qubit_id)
        self._update_stored_qubits(qubits)
Пример #18
0
    def test_get_data_qubits(self):
        host = Host('A')
        q1 = Qubit(host)
        q2 = Qubit(host)
        q3 = Qubit(host)

        host.add_data_qubit('B', q1)

        qs = host.get_data_qubits('B')
        self.assertEqual(len(qs), 1)

        host.add_data_qubit('B', q2)
        host.add_data_qubit('B', q3)

        qs = host.get_data_qubits('B')
        self.assertEqual(len(qs), 3)

        qs = host.get_data_qubits('B', remove_from_storage=True)
        self.assertEqual(len(qs), 3)

        qs = host.get_data_qubits('B', remove_from_storage=True)
        self.assertEqual(len(qs), 0)
Пример #19
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)
Пример #20
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)
Пример #21
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)
Пример #22
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()
Пример #23
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()
Пример #24
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)
Пример #25
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()
Пример #26
0
def sender_qkd(alice, secret_key, receiver):
    sent_qubit_counter = 0
    for bit in secret_key:
        success = False
        while success == False:
            qubit = Qubit(alice)
            if bit == 1:
                qubit.H()
            # If we want to send 0, we'll send |0>
            # If we want to send 1, we'll send |+>
            alice.send_qubit(receiver, qubit, await_ack=True)
            message = alice.get_next_classical(receiver, wait=-1)
            if message is not None:
                if message.content == 'qubit successfully acquired':
                    print(f'Alice sent qubit {sent_qubit_counter+1} to Bob')
                    success = True
                    sent_qubit_counter += 1
Пример #27
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)
Пример #28
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)
Пример #29
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
Пример #30
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