Пример #1
0
    def test_density_operator(self):
        """
        Test EQSN.
        """
        backend = EQSNBackend()
        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)

        q1 = backend.create_EPR(alice.host_id, bob.host_id)
        q2 = backend.receive_epr(bob.host_id, alice.host_id, q_id=q1.id)

        density_operator = backend.density_operator(q1)
        expected = np.diag([0.5, 0.5])
        self.assertTrue(np.allclose(density_operator, expected))

        # remove qubits
        backend.measure(q1, False)
        backend.measure(q2, False)

        network.stop(True)
        """
        Test Qutip
        """
        backend = QuTipBackend()
        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)

        q1 = backend.create_EPR(alice.host_id, bob.host_id)
        q2 = backend.receive_epr(bob.host_id, alice.host_id, q_id=q1.id)

        density_operator = backend.density_operator(q1)
        expected = np.diag([0.5, 0.5])
        self.assertTrue(np.allclose(density_operator, expected))

        # remove qubits
        backend.measure(q1, False)
        backend.measure(q2, False)

        network.stop(True)
Пример #2
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()
Пример #3
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, '01')

    messages = hosts['bob'].classical
    i = 0
    while i < 5 and len(messages) == 0:
        messages = hosts['bob'].classical
        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 == '01')
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #4
0
def main():
    backend = EQSNBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.0

    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)

    ack_received_1 = hosts['alice'].send_classical(
        hosts['bob'].host_id, 'hello bob one', await_ack=True)
    hosts['alice'].max_ack_wait = 0.0
    ack_received_2 = hosts['alice'].send_classical(
        hosts['bob'].host_id, 'hello bob one', await_ack=True)
    assert ack_received_1
    assert not ack_received_2
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #5
0
    def _pop_qubit_with_id_and_host_from_qubit_dict(self, q_id, from_host_id, purpose=None):

        from qunetsim.components.network import Network     #For getting network ticks
        network = Network.get_instance()

        def _pop_purpose_from_purpose_dict():
            nonlocal q_id, from_host_id

            if q_id not in self._purpose_dict:
                return None
            pur = self._purpose_dict[q_id].pop(from_host_id, None)
            if pur is not None:
                if not self._purpose_dict[q_id]:
                    del self._purpose_dict[q_id]
                return pur
            return None

        purp = _pop_purpose_from_purpose_dict()
        if purp is not None:
            if purpose is None or purpose == purp:
                (qubit, storetime) = self._qubit_dict[q_id].pop(from_host_id, None)
                if self.coherence_time > 0 and network.tick - storetime > self.coherence_time:
                    if not self._qubit_dict[q_id]:
                        del self._qubit_dict[q_id]
                    return None
                elif qubit is not None:
                    if not self._qubit_dict[q_id]:
                        del self._qubit_dict[q_id]
                return qubit, purp
            else:
                if q_id not in self._purpose_dict:
                    self._purpose_dict[q_id] = {}
                self._purpose_dict[q_id][from_host_id] = purp
        return None
Пример #6
0
 def test_multiple_backends(self):
     for b in TestBackend.backends:
         backend1 = b()
         backend2 = b()
         network = Network.get_instance()
         network.start(["Alice", "Bob"], backend1)
         _ = Host('Alice', backend2)
         _ = Host('Bob', backend1)
         self.assertEqual(str(backend1._hosts), str(backend2._hosts))
         network.stop(True)
Пример #7
0
    def test_adding_hosts_to_backend(self):
        for b in TestBackend.backends:
            backend = b()
            network = Network.get_instance()
            network.start(["Alice"], backend)
            alice = Host('Alice', backend)
            alice.start()

            network.add_host(alice)
            network.stop(True)
Пример #8
0
    def setUp(self):
        network = Network.get_instance()
        network.start(["host_1"], EQSNBackend())

        self.controller_host = ControllerHost(
            host_id="host_1",
            computing_host_ids=["QPU_1"])
        network.add_host(self.controller_host)

        self._network = network
Пример #9
0
def test_adding_hosts_to_backend(backend_generator):
    print("Starrting adding a host test...")
    backend = backend_generator()
    network = Network.get_instance()
    network.start(["Alice"], backend)
    alice = Host('Alice', backend)
    alice.start()

    network.add_host(alice)
    network.stop(True)
    print("Test was successfull!")
Пример #10
0
def main():
    backend = CQCBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)

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

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

    hosts['alice'].storage_epr_limit = 1
    hosts['bob'].storage_epr_limit = 1

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

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

    hosts['alice'].max_ack_wait = 10

    hosts['alice'].send_epr(hosts['bob'].host_id, await_ack=True)
    hosts['alice'].send_epr(hosts['bob'].host_id, await_ack=True)

    assert hosts['alice'].shares_epr(hosts['bob'].host_id)
    assert len(hosts['alice'].get_epr_pairs(hosts['bob'].host_id)) == 1
    assert hosts['bob'].shares_epr(hosts['alice'].host_id)
    assert len(hosts['bob'].get_epr_pairs(hosts['alice'].host_id)) == 1

    hosts['alice'].set_epr_memory_limit(2, hosts['bob'].host_id)
    hosts['bob'].set_epr_memory_limit(2)

    hosts['alice'].send_epr(hosts['bob'].host_id, await_ack=True)
    hosts['alice'].send_epr(hosts['bob'].host_id, await_ack=True)

    alice_pairs = hosts['alice'].get_epr_pairs(hosts['bob'].host_id)
    bob_pairs = hosts['bob'].get_epr_pairs(hosts['alice'].host_id)
    assert len(alice_pairs) == 2
    assert len(bob_pairs) == 2

    for q in alice_pairs:
        q.measure()
    for q in bob_pairs:
        q.measure()

    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #11
0
def test_multiple_backends(backend_generator):
    print("Starting multiple backends test...")
    backend1 = backend_generator()
    backend2 = backend_generator()
    assert backend1._cqc_connections == backend2._cqc_connections
    network = Network.get_instance()
    network.start(["Alice", "Bob"], backend1)
    alice = Host('Alice', backend2)
    bob = Host('Bob', backend1)
    assert str(backend1._cqc_connections) == str(backend2._cqc_connections)
    assert str(backend1._hosts) == str(backend2._hosts)
    network.stop(True)
    print("Test was successfull!")
Пример #12
0
    def _add_qubit_to_qubit_dict(self, qubit, purpose, from_host_id):
        from qunetsim.components.network import Network
        network = Network.get_instance()
        def _add_purpose_to_purpose_dict(q_id):
            nonlocal purpose, from_host_id
            if q_id not in self._purpose_dict:
                self._purpose_dict[q_id] = {}
            self._purpose_dict[q_id][from_host_id] = purpose

        if qubit.id not in self._qubit_dict:
            self._qubit_dict[qubit.id] = {}
        self._qubit_dict[qubit.id][from_host_id] = (qubit, network.tick)
        _add_purpose_to_purpose_dict(qubit.id)
Пример #13
0
def main():
    network = Network.get_instance()
    nodes = ['Alice', 'Eve', 'Bob']
    network.start(nodes)
    network.delay = 0.1

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

    host_eve = Host('Eve')
    host_eve.add_connections(['Alice', 'Bob'])
    host_eve.start()

    host_bob = Host('Bob')
    host_bob.add_connection('Eve')
    host_bob.delay = 0.2
    host_bob.start()

    network.add_host(host_alice)
    network.add_host(host_eve)
    network.add_host(host_bob)
    # network.draw_classical_network()
    # network.draw_quantum_network()
    network.start()

    alice_basis, bob_basis, alice_bits, alice_encoded = preparation()
    print("Alice bases: {}".format(alice_basis))
    print("Bob bases: {}".format(bob_basis))
    print("Alice bits: {}".format(alice_bits))
    print("Alice encoded: {}".format(alice_encoded))

    if INTERCEPTION:
        host_eve.q_relay_sniffing = True
        host_eve.q_relay_sniffing_fn = eve_sniffing_quantum

    t1 = host_alice.run_protocol(alice, (
        host_bob.host_id,
        alice_basis,
        alice_bits,
        alice_encoded,
    ))
    t2 = host_bob.run_protocol(bob, (
        host_alice.host_id,
        bob_basis,
    ))
    t1.join()
    t2.join()

    network.stop(True)
    exit()
Пример #14
0
def main():
    print("Skip test, this test has to be updated!")
    return
    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)}

    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)

    # print(f"ack test - SEND CLASSICAL - started at {time.strftime('%X')}")
    hosts['alice'].send_classical(
        hosts['bob'].host_id, 'hello bob one', await_ack=True)
    hosts['alice'].send_classical(
        hosts['bob'].host_id, 'hello bob two', await_ack=True)
    # print(f"ack test - SEND CLASSICAL - finished at {time.strftime('%X')}")

    saw_ack_1 = False
    saw_ack_2 = False
    messages = hosts['alice'].classical
    # print([m.seq_num for m in messages])
    for m in messages:
        if m.content == Constants.ACK and m.seq_num == 0:
            saw_ack_1 = True
        if m.content == Constants.ACK and m.seq_num == 1:
            saw_ack_2 = True
        if saw_ack_1 and saw_ack_2:
            break

    assert saw_ack_1
    assert saw_ack_2
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #15
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)}

    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)

    hosts['alice'].send_classical(hosts['bob'].host_id, 'Hello Bob', False)
    hosts['bob'].send_classical(hosts['alice'].host_id, 'Hello Alice', False)

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

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

    assert len(alice_messages) > 0
    assert alice_messages[0].sender == hosts['bob'].host_id
    assert alice_messages[0].content == 'Hello Alice'

    assert (len(bob_messages) > 0)
    assert (bob_messages[0].sender == hosts['alice'].host_id)
    assert (bob_messages[0].content == 'Hello Bob')
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #16
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_id, _ = hosts['alice'].send_epr(hosts['eve'].host_id, await_ack=True)

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

    assert q1 is not None

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

    assert q2 is not None
    assert q1.measure() == q2.measure()
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #17
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_id = hosts['alice'].send_epr(hosts['bob'].host_id)
    q1 = hosts['alice'].shares_epr(hosts['bob'].host_id)
    i = 0
    while not q1 and i < MAX_WAIT:
        q1 = hosts['alice'].shares_epr(hosts['bob'].host_id)
        i += 1
        time.sleep(1)

    i = 0
    q2 = hosts['bob'].shares_epr(hosts['alice'].host_id)
    while not q2 and i < 5:
        q2 = hosts['bob'].shares_epr(hosts['alice'].host_id)
        i += 1
        time.sleep(1)

    assert hosts['alice'].shares_epr(hosts['bob'].host_id)
    assert hosts['bob'].shares_epr(hosts['alice'].host_id)
    q_alice = hosts['alice'].get_epr(hosts['bob'].host_id, q_id)
    q_bob = hosts['bob'].get_epr(hosts['alice'].host_id, q_id)
    assert q_alice is not None
    assert q_bob is not None
    assert q_alice.measure() == q_bob.measure()
    assert not hosts['alice'].shares_epr(hosts['bob'].host_id)
    assert not hosts['bob'].shares_epr(hosts['alice'].host_id)
    print("All tests succesfull!")
    network.stop(True)
    exit()
def main():
    backend = EQSNBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.0

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

    network.start(nodes, backend)
    network.packet_drop_rate = 0.5
    network.delay = 0

    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)

    # ACKs for 1 hop take at most 2 seconds
    hosts['alice'].max_ack_wait = 0.5
    num_acks = 0
    # don't make more then 10 attempts, since of receiver window.
    num_messages = 20
    for _ in range(num_messages):
        ack = hosts['alice'].send_classical(hosts['bob'].host_id,
                                            'Hello Bob',
                                            await_ack=True)
        if ack:
            num_acks += 1

    num_messages_bob_received = len(hosts['bob'].classical)
    assert num_acks != num_messages
    assert num_acks < num_messages
    assert num_messages_bob_received < num_messages

    # ACKs can also get dropped
    assert num_messages_bob_received > num_acks
    assert float(num_acks) / num_messages < 0.9
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #19
0
    def setUp(self):
        network = Network.get_instance()
        network.start(["host_1", "QPU_1", "QPU_2", "QPU_3"], EQSNBackend())

        clock = Clock()

        self.computing_host_1 = ComputingHost(host_id="QPU_1",
                                              controller_host_id="host_1",
                                              clock=clock,
                                              total_qubits=2)

        self.computing_host_2 = ComputingHost(host_id="QPU_2",
                                              controller_host_id="host_1",
                                              clock=clock,
                                              total_qubits=2)

        self.computing_host_3 = ComputingHost(host_id="QPU_3",
                                              controller_host_id="host_1",
                                              clock=clock,
                                              total_qubits=2)

        self.controller_host = ControllerHost(
            host_id="host_1",
            clock=clock,
            computing_host_ids=["QPU_1", "QPU_2", "QPU_3"])

        self.computing_host_1.add_connections(['QPU_2', 'QPU_3'])
        self.computing_host_1.start()
        self.computing_host_2.add_connections(['QPU_1', 'QPU_3'])
        self.computing_host_2.start()
        self.computing_host_3.add_connections(['QPU_1', 'QPU_2'])
        self.computing_host_3.start()

        self.controller_host.start()

        network.add_hosts([
            self.controller_host, self.computing_host_1, self.computing_host_2,
            self.computing_host_3
        ])

        self.network = network
        self.clock = clock
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)

    hosts['alice'].send_superdense(hosts['eve'].host_id, '11')
    hosts['alice'].send_classical(hosts['eve'].host_id, 'hello')

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

    assert (len(messages) > 0)
    assert messages[0].sender == hosts['alice'].host_id
    assert (messages[0].content == 'hello')
    assert (messages[1].sender == hosts['alice'].host_id)
    assert (messages[1].content == '11')
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #21
0
def test_epr_generation(backend_generator):
    print("Starting EPR generation backend.")
    backend = backend_generator()
    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)

    # Test multiple times to eliminate probabilistic effects
    for _ in range(10):
        q1 = backend.create_EPR(alice.host_id, bob.host_id)
        q2 = backend.receive_epr(bob.host_id, alice.host_id, q_id=q1.id)
        assert q1.id == q2.id
        assert backend.measure(q1, False) == backend.measure(q2, False)

    network.stop(True)
    print("Test was successful")
Пример #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)

    network.use_hop_by_hop = False
    hosts['alice'].send_classical(hosts['eve'].host_id, 'testing123')

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

    assert len(messages) > 0
    assert messages[0].sender == hosts['alice'].host_id
    assert messages[0].content == 'testing123'
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #23
0
def main():
    backend = EQSNBackend()
    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_id = hosts['alice'].send_epr(hosts['bob'].host_id)
    q1 = hosts['alice'].get_epr(hosts['bob'].host_id, q_id)
    i = 0
    while q1 is None and i < 5:
        q1 = hosts['alice'].get_epr(hosts['bob'].host_id, q_id)
        i += 1
        time.sleep(1)

    assert q1 is not None
    i = 0
    q2 = hosts['bob'].get_epr(hosts['alice'].host_id, q_id)
    while q2 is None and i < 5:
        q2 = hosts['bob'].get_epr(hosts['alice'].host_id, q_id)
        i += 1
        time.sleep(1)

    assert q2 is not None
    assert (q1.measure() == q2.measure())
    print("All tests succesfull!")
    network.stop(True)
    exit()
Пример #24
0
    def test_epr_generation(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)

            # Test multiple times to eliminate probabilistic effects
            for _ in range(5):
                q1 = backend.create_EPR(alice.host_id, bob.host_id)
                q2 = backend.receive_epr(bob.host_id,
                                         alice.host_id,
                                         q_id=q1.id)
                assert q1.id == q2.id
                assert backend.measure(q1, False) == backend.measure(q2, False)

            network.stop(True)
Пример #25
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)
Пример #26
0
from qunetsim.objects import Logger, Packet, Message, Qubit
from qunetsim.components.network import Network
from qunetsim.utils.constants import Constants
import numpy as np
import random

network = Network.get_instance()


def encode(sender,
           receiver,
           protocol,
           payload=None,
           payload_type='',
           sequence_num=-1,
           await_ack=False):
    """
    Encodes the data with the sender, receiver, protocol, payload type and sequence number and forms the packet
    with data and the header.
    Args:
        sender(str): ID of the sender
        receiver(str): ID of the receiver
        protocol(str): ID of the protocol of which the packet should be processed.
        payload : The message that is intended to send with the packet. Type of payload depends on the protocol.
        payload_type(str): Type of the payload.
        sequence_num(int): Sequence number of the packet.
        await_ack(bool): If the sender should await an ACK
    Returns:
         (Packet): Encoded packet
    """
Пример #27
0
def main():
    # Testing
    eve_interception = False  # Set it as true to test interception
    b = BB84()
    # Network initialization
    network = Network.get_instance()
    nodes = ['Alice', 'Bob', 'Eve']
    network.start(nodes)
    host_alice = Host('Alice')
    host_alice.add_connection('Eve')
    host_alice.start()

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

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

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

    # Eve intercepts
    if (eve_interception):
        host_eve.q_relay_sniffing = True
        host_eve.q_relay_sniffing_fn = b.eve_sniffing_quantum

    network.draw_quantum_network()
    network.draw_classical_network()

    KEY_LENGTH = 500  # the size of the key in bit
    np.random.seed(0)
    secret_key = np.random.randint(2, size=KEY_LENGTH)
    print("Secret Key: ", secret_key)

    # Step 1: Alice's Prepares encoding basis and choose a random bitstring
    alice_bitstring, alice_bases = b.select_encoding(KEY_LENGTH)
    print("alice_bitstring: ", alice_bitstring[:10])
    print("alice_bases: ", alice_bases[:10])

    # Step 2: Bob selects bases for measurement
    bob_bases = b.select_measurement(KEY_LENGTH)
    print("Bob_bases: ", bob_bases[:10])

    # Step 3: Alice encodes the qubits
    encoded_qubits = b.encode(host_alice, alice_bitstring, alice_bases)
    print('Encoded bits: ', encoded_qubits)

    # Step 4: Alice sends the qubits
    q_ids = b.send(host_alice, host_bob, encoded_qubits)
    print(q_ids)

    # Step 5: Bob measures the received qubits
    Bob_received_message = b.receive(host_bob, host_alice, q_ids)
    print('Bob received qubits', Bob_received_message)
    bob_bits, bob_bitstring = b.measurement(bob_bases, Bob_received_message)
    print('Bob measured ', bob_bitstring)

    # Step 6: Bob uses Alice's announced bases to see where they agreed with
    # his decoding bases
    seq_no = b.send_classically(host_alice, alice_bases, KEY_LENGTH, host_bob)
    print(seq_no)
    bases_bob_received_arr, bases_bob_received_string = b.receive_classically(
        host_bob, host_alice, seq_no)
    print('Bob Received Bases from Alice', bases_bob_received_string)
    Bob_agreeing_bases = b.compare_bases(bases_bob_received_string, bob_bases)
    print(Bob_agreeing_bases)

    # Bob announces where they agreed on encoding and
    # decoding bases classically.
    seq_no = b.send_classically(host_bob, bob_bases, KEY_LENGTH, host_alice)
    print(seq_no)
    Alice_received_bases, Alice_received_bases_string = b.receive_classically(
        host_alice, host_bob, seq_no)
    print('Alice Received Bases from Bob', Alice_received_bases_string)
    Alice_agreeing_bases = b.compare_bases(alice_bases,
                                           Alice_received_bases_string)
    print(Alice_agreeing_bases)

    # Step 7: Alice and Bob construct their keys
    alice_key = b.construct_key_from_indices(
        alice_bitstring, Alice_agreeing_bases)  # Alice Side
    bob_key = b.construct_key_from_indices(bob_bitstring, Bob_agreeing_bases)

    # Preview the first 10 elements of each Key:
    print("alice_key: ", alice_key[:10])
    print("bob_key: ", bob_key[:10])
    print("Alice's key is equal to Bob's key: ", alice_key == bob_key)

    if (alice_key == bob_key):
        message = "QKD is cool!"
        print("Original Messge:", message)
        encrypted_message = b.encrypt_message(message, alice_key)
        print("Encrypted message:", encrypted_message)
        decrypted_message = b.decrypt_message(encrypted_message, bob_key)
        print("Decrypted message:", decrypted_message)
Пример #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()
def main():
    print("Test maximum data qubit has been skipped.")
    return
    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)}

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

    hosts['alice'].memory_limit = 1
    hosts['bob'].memory_limit = 1

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

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

    q_alice_id_1 = hosts['alice'].send_qubit(hosts['bob'].host_id,
                                             Qubit(hosts['alice']))
    time.sleep(2)
    q_alice_id_2 = hosts['alice'].send_qubit(hosts['bob'].host_id,
                                             Qubit(hosts['alice']))
    time.sleep(2)

    q_bob_id_1 = hosts['bob'].send_qubit(hosts['alice'].host_id,
                                         Qubit(hosts['bob']))
    time.sleep(2)
    q_bob_id_2 = hosts['bob'].send_qubit(hosts['alice'].host_id,
                                         Qubit(hosts['bob']))
    time.sleep(2)

    # Allow the network to process the requests
    # TODO: remove the need for this
    time.sleep(2)

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

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

    assert len(hosts['alice'].get_data_qubits(hosts['bob'].host_id)) == 1
    assert hosts['alice'].get_data_qubit(hosts['bob'].host_id,
                                         q_bob_id_1).measure() == 0
    assert hosts['alice'].get_data_qubit(hosts['bob'].host_id,
                                         q_bob_id_2) == None
    assert len(hosts['bob'].get_data_qubits(hosts['alice'].host_id)) == 1
    assert hosts['bob'].get_data_qubit(hosts['alice'].host_id,
                                       q_alice_id_1).measure() == 0
    assert hosts['bob'].get_data_qubit(hosts['alice'].host_id,
                                       q_alice_id_2) == None

    hosts['alice'].set_data_qubit_memory_limit(2, hosts['bob'].host_id)
    hosts['bob'].set_data_qubit_memory_limit(2)

    q_alice_id_1 = hosts['alice'].send_qubit(hosts['bob'].host_id,
                                             Qubit(hosts['alice']))
    time.sleep(2)
    q_alice_id_2 = hosts['alice'].send_qubit(hosts['bob'].host_id,
                                             Qubit(hosts['alice']))
    time.sleep(2)
    q_alice_id_3 = hosts['alice'].send_qubit(hosts['bob'].host_id,
                                             Qubit(hosts['alice']))
    time.sleep(2)

    q_bob_id_1 = hosts['bob'].send_qubit(hosts['alice'].host_id,
                                         Qubit(hosts['bob']))
    time.sleep(2)
    q_bob_id_2 = hosts['bob'].send_qubit(hosts['alice'].host_id,
                                         Qubit(hosts['bob']))
    time.sleep(2)
    q_bob_id_3 = hosts['bob'].send_qubit(hosts['alice'].host_id,
                                         Qubit(hosts['bob']))
    time.sleep(2)

    # Allow the network to process the requests
    time.sleep(3)

    i = 0
    while len(hosts['alice'].get_data_qubits(
            hosts['bob'].host_id)) < 2 and i < 5:
        time.sleep(1)
        i += 1

    i = 0
    while len(hosts['bob'].get_data_qubits(
            hosts['alice'].host_id)) < 2 and i < 5:
        time.sleep(1)
        i += 1

    assert len(hosts['alice'].get_data_qubits(hosts['bob'].host_id)) == 2
    assert hosts['alice'].get_data_qubit(hosts['bob'].host_id,
                                         q_bob_id_1).measure() == 0
    assert hosts['alice'].get_data_qubit(hosts['bob'].host_id,
                                         q_bob_id_2).measure() == 0
    assert hosts['alice'].get_data_qubit(hosts['bob'].host_id,
                                         q_bob_id_3) == None

    assert len(hosts['bob'].get_data_qubits(hosts['alice'].host_id)) == 2
    assert hosts['bob'].get_data_qubit(hosts['alice'].host_id,
                                       q_alice_id_1).measure() == 0
    assert hosts['bob'].get_data_qubit(hosts['alice'].host_id,
                                       q_alice_id_2).measure() == 0
    assert hosts['bob'].get_data_qubit(hosts['alice'].host_id,
                                       q_alice_id_3) == None
    print("All tests succesfull!")
    network.stop(True)
    exit()