Esempio n. 1
0
def main():
    # Create Simulaqron connections for each component
    with CQCConnection(name="Alice") as cqc_alice, CQCConnection(name="Bob") as cqc_bob, \
            CQCConnection(name="Eve") as cqc_eve:

        # Start up root server
        root = QChatServer(name="Eve", cqc_connection=cqc_eve)
        time.sleep(2)

        # Start up users
        alice_client = QChatClient(name="Alice", cqc_connection=cqc_alice)
        bob_client = QChatClient(name="Bob", cqc_connection=cqc_bob)
        time.sleep(2)

        # Send a superdense coded message
        alice_client.sendSuperDenseMessage("Bob", "Hello!")

        while True:
            messages = bob_client.getMessageHistory()
            if messages:
                print("Got messages!: {}".format(messages))
                break
            time.sleep(1)

        bob_client.sendSuperDenseMessage("Alice", "Hello to you too!")

        while True:
            messages = alice_client.getMessageHistory()
            if messages:
                print("Got messages!: {}".format(messages))
                break
            time.sleep(1)
Esempio n. 2
0
    def running(self):
        """
        Is the network up and running?
        """
        if self._running:
            return True
        for node in self.nodes:
            try:
                cqc = CQCConnection(node,
                                    retry_connection=False,
                                    network_name=self.name)
            except ConnectionRefusedError:
                self._running = False
                break
            except Exception as err:
                logging.exception(
                    "Got unexpected exception when trying to connect: {}".
                    format(err))
                raise err
            else:
                cqc.close()
        else:
            self._running = True

        return self._running
Esempio n. 3
0
 def testSingleGates(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             q = qubit(alice)
             q.X()
             q.measure(inplace=True)
             r = alice.flush()
             self.assertEqual(len(r), 2)
             self.assertEqual(r[1], 1)
             q.reset()
             q.Y()
             q.measure(inplace=True)
             r = alice.flush()
             self.assertEqual(r, [1])
             q.reset()
             q.Z()
             q.measure(inplace=True)
             r = alice.flush()
             self.assertEqual(r, [0])
             q.reset()
             q.H()
             q.H()
             q.measure()
             r = alice.flush()
             self.assertEqual(r, [0])
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 4
0
    def _atomic_flip(self, candidate1, candidate2, coeff):
        """
        Performs the basic biased coinflip between two parties.
        :param candidate1: the first party id.
        :param candidate2: the second party id.
        :param coeff: bias.
        :return: the winner id.
        """
        with CQCConnection(candidate1) as Alice:
            qA = qubit(Alice)
            qB = qubit(Alice)

            # Bias
            angle = 2 * math.acos(coeff)
            step = int(angle * 256 / (2 * math.pi))
            qA.rot_Y(step)
            qA.cnot(qB)
            qB.X()

            # Send qubit qB to Bob.
            Alice.sendQubit(qB, candidate2)

            # Measure the qubits.
            measured_value = qA.measure()

            with CQCConnection(candidate2) as Bob:
                qB = Bob.recvQubit()
                bob_value = qB.measure()
                assert measured_value + bob_value == 1

            if measured_value == 1:  # `candidate1` is a winner.
                return candidate1
            else:
                return candidate2
Esempio n. 5
0
    def setUpClass(cls):
        Settings.default_settings()
        cls.network = Network(nodes=["Alice", "Bob"])
        cls.network.start()

        cls.alice = CQCConnection("Alice")
        cls.bob = CQCConnection("Bob")
Esempio n. 6
0
def simulaqron():

    from cqc.pythonLib import CQCConnection
    from qpz_atomics.mappings.simulaqron import mapping

    with CQCConnection("Alice") as Alice:

        _ = qpz_atomics.lib(mapping, Alice)

        #use library to prepare a single qubit
        # all commands are applied locally: no need to specify the node
        q = _.PREP()

        # show info about created qubit
        _.DISP(q)

        # flip the qubit
        _.X(q)

        # sending to Bob (need to pass the arguments using the syntax used by the backend used)
        _.SEND(q, "Bob")

    with CQCConnection("Bob") as Bob:
        _ = qpz_atomics.lib(mapping, Bob)

        # receive a qubit
        q = _.RECV()

        # show info about this qubit
        _.DISP(q)
Esempio n. 7
0
    def test_epr_for_last_position(self):
        with CQCConnection("Alice") as alice:
            with CQCConnection("Bob") as bob:
                alice_qubits = []
                bob_qubits = []
                for _ in range(Settings.CONF_MAXQUBITS - 1):
                    q = qubit(alice)
                    alice_qubits.append(q)
                for _ in range(Settings.CONF_MAXQUBITS - 1):
                    q = qubit(bob)
                    bob_qubits.append(q)

                q = alice.createEPR("Bob", remote_appID=bob._appID)
                alice_qubits.append(q)
                q = bob.recvEPR()
                bob_qubits.append(q)

                with self.assertRaises(CQCNoQubitError):
                    alice.createEPR("Bob", remote_appID=bob._appID)

                    # remove one qubit from Alice
                alice_qubits[0].measure()

                with self.assertRaises(CQCNoQubitError):
                    alice.createEPR("Bob", remote_appID=bob._appID)

                    # remove one qubit from Bob
                bob_qubits[0].measure()

                alice.createEPR("Bob", remote_appID=bob._appID)
                bob.recvEPR()
Esempio n. 8
0
    def testSend(self):
        with CQCConnection("Alice", pend_messages=True) as alice:
            with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
                qA = qubit(alice)
                qAs = alice.flush_factory(10)
                self.assertIsNone(qA._qID)
                self.assertFalse(qA.check_active())

                for q in qAs:
                    self.assertTrue(q._active)
                    alice.sendQubit(q, name="Bob", remote_appID=1)
                    self.assertTrue(q._active)

                alice.flush()
                qB = bob.recvQubit()
                qBs = bob.flush_factory(10)
                self.assertIsNone(qB._qID)
                self.assertFalse(qB.check_active())

                for q in qAs:
                    self.assertFalse(q._active)

                for i in range(1, 10):
                    self.assertEqual(qBs[i - 1]._qID + 1, qBs[i]._qID)
                bob.set_pending(False)
                for q in qBs:
                    self.assertEqual(q.measure(), 0)
                bob.set_pending(True)
                self.assertEqual(alice.pending_messages, [])
                self.assertEqual(bob.pending_messages, [])
                alice.flush()
                bob.flush()
def generate_bell_pair():
    with CQCConnection("Alice") as Alice:
        qubit1 = qubit(Alice)
        with CQCConnection("Bob") as Bob:
            qubit2 = qubit(Alice)
            qubit1.H()
            qubit1.cnot(qubit2)
    return qubit1, qubit2
def send_recieve(bit = 0):
    with CQCConnection("Alice") as Alice:
        with CQCConnection("Bob") as Bob:
            qubit2 = qubit(Bob)
            qubit1 = qubit(Alice)
            qubit1, qubit2 = generate_bell_pair()
            classical_encoded_message = create_message(qubit1 = qubit1, message = bit)
    return message_reciever(classical_encoded_message, qubit2)
Esempio n. 11
0
 def __init__(self, name):
     self.conn = CQCConnection(name)
     self.name = name
     self.N = 0
     self.bases = []
     self.raw_key = []
     self.sifted_key = []
     self.remote_bases = []
Esempio n. 12
0
    def setUpClass(cls):
        simulaqron_settings.default_settings()
        simulaqron_settings._read_user = False
        simulaqron_settings.log_level = logging.CRITICAL
        cls.network = Network(nodes=["Alice", "Bob"], force=True)
        cls.network.start()

        cls.alice = CQCConnection("Alice")
        cls.bob = CQCConnection("Bob")
Esempio n. 13
0
 def testNoSequence(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             res = alice.flush()
             self.assertEqual(res, [])
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 14
0
 def test_without_context(self):
     for _ in range(Settings.CONF_MAXQUBITS):
         cqc = CQCConnection("Alice")
         self.cqcs.append(cqc)
         qubit(cqc)
     with self.assertRaises(CQCNoQubitError):
         cqc = CQCConnection("Alice")
         self.cqcs.append(cqc)
         qubit(cqc)
Esempio n. 15
0
 def test_without_context(self):
     for _ in range(simulaqron_settings.max_qubits):
         cqc = CQCConnection("Alice")
         self.cqcs.append(cqc)
         qubit(cqc)
     with self.assertRaises(CQCNoQubitError):
         cqc = CQCConnection("Alice")
         self.cqcs.append(cqc)
         qubit(cqc)
Esempio n. 16
0
 def testMeasuringMultipleQubits(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             qs = alice.create_qubits(10)
             for q in qs:
                 q.measure()
             ms = alice.flush()
             self.assertEqual(ms, [0] * 10)
             self.assertEqual(alice._pending_headers, [])
             self.assertEqual(bob._pending_headers, [])
             alice.flush()
             bob.flush()
Esempio n. 17
0
 def testSend(self):
     with CQCConnection("Alice", appID=0, pend_messages=True) as cqc:
         q = qubit(cqc)
         q.X()
         cqc.flush()
         with CQCConnection("Bob", appID=1) as bob:
             # Get receiving host
             cqc.sendQubit(q, "Bob", remote_appID=1)
             with self.assertRaises(CQCNoQubitError):
                 cqc.flush_factory(self.iterations)
             qB = bob.recvQubit()
             self.assertTrue(qB.measure(), 1)
             self.assertFalse(q._active)
         self.assertEqual(len(cqc.pending_messages), 0)
Esempio n. 18
0
 def testCNOT(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             qs = alice.create_qubits(10)
             qs[0].X()
             for i in range(1, 10):
                 qs[i - 1].cnot(qs[i])
             [q.measure() for q in qs]
             ms = alice.flush()
             self.assertEqual(ms, [1] * 10)  # all outcomes should be one
             self.assertEqual(alice._pending_headers, [])
             self.assertEqual(bob._pending_headers, [])
             alice.flush()
             bob.flush()
 def test_send(self):
     for sender_name in self.node_names:
         for receiver_name in self.node_names:
             with CQCConnection(sender_name) as sender:
                 with CQCConnection(receiver_name) as receiver:
                     q = qubit(sender)
                     if sender_name == receiver_name:
                         with self.assertRaises(CQCUnsuppError):
                             sender.sendQubit(q=q, name=receiver_name, remote_appID=receiver._appID)
                     else:
                         sender.sendQubit(q=q, name=receiver_name, remote_appID=receiver._appID)
                         q = receiver.recvQubit()
                     m = q.measure()
                     self.assertEqual(m, 0)
Esempio n. 20
0
 def testSimpleSequence(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             q = qubit(alice)
             q.H()
             q.Z()
             q.H()
             q.measure()
             r = alice.flush()[1]
             self.assertEqual(r, 1)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
 def test_EPR(self):
     for sender_name in self.node_names:
         for receiver_name in self.node_names:
             with CQCConnection(sender_name) as sender:
                 with CQCConnection(receiver_name) as receiver:
                     if sender_name == receiver_name:
                         with self.assertRaises(CQCUnsuppError):
                             sender.createEPR(name=receiver_name, remote_appID=receiver._appID)
                     else:
                         qs = sender.createEPR(name=receiver_name, remote_appID=receiver._appID)
                         qr = receiver.recvEPR()
                         ms = qs.measure()
                         mr = qr.measure()
                         self.assertEqual((ms + mr) % 2, 0)
Esempio n. 22
0
 def testMultipleNewQubits(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             qs = alice.create_qubits(10)
             self.assertEqual(len(qs), 10)
             for i in range(1, 10):
                 self.assertEqual(qs[i]._qID, qs[i - 1]._qID + 1)
             alice.set_pending(False)
             for q in qs:
                 self.assertEqual(q.measure(), 0)
             alice.set_pending(True)
             self.assertEqual(alice._pending_headers, [])
             self.assertEqual(bob._pending_headers, [])
             alice.flush()
             bob.flush()
Esempio n. 23
0
 def testMeasuringMultipleQubits(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             qA = qubit(alice)
             qs = alice.flush_factory(10)
             self.assertIsNone(qA._qID)
             self.assertFalse(qA.check_active())
             for q in qs:
                 q.measure()
             ms = alice.flush()
             self.assertEqual(ms, [0] * 10)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 24
0
 def testAlternating(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             q = qubit(alice)
             alice.flush()
             q.X()
             q.measure(inplace=True)
             res = alice.flush_factory(10)
             q.measure()
             alice.flush()
             self.assertEqual(res, [1, 0] * 5)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 25
0
def main():
    print('Bob init')
    # Initialize the connection
    with CQCConnection("Bob", backend="simulaqron",
                       network_name="triangle") as Bob:
        print('Bob?')
        # Make an EPR pair with Alice
        qB = Bob.recvEPR()

        # Receive info about corrections
        data = Bob.recvClassical()
        message = list(data)
        a = message[0]
        b = message[1]

        # Apply corrections
        if b == 1:
            qB.X()
        if a == 1:
            qB.Z()

            # Measure qubit
        m = qB.measure()
        to_print = "App {}: Measurement outcome is: {}".format(Bob.name, m)
        print("|" + "-" * (len(to_print) + 2) + "|")
        print("| " + to_print + " |")
        print("|" + "-" * (len(to_print) + 2) + "|")
    print('Bob end')
Esempio n. 26
0
def preparation_Bob():
    with CQCConnection("Bob") as Bob:
        for i in range(100):

            q = Bob.recvQubit()
            random_basis_bob = randint(0, 1)
            basis_bob.append(random_basis_bob)
            if random_basis_bob == 1:
                q.H()
            m = q.measure()
            if (random_basis_bob == 0 and m == 0):
                results.append(0)
            elif (random_basis_bob == 0 and m == 1):
                results.append(1)
            elif (random_basis_bob == 1 and m == 0):
                results.append(1)
            else:
                results.append(0)
            received.append(m)

    print("basis of bob ", basis_bob)
    print("measurement results of bob: ", received)
    print("results ", results)

    Bob.sendClassical("Alice", results)
Esempio n. 27
0
File: zwdz.py Progetto: rasa97/qAuth
    def sendRandom(self, random_key, receiver):
        """
        Method that sends the random_key generated
        before. It convert the string type to 
        suitable type so that we can send through
        the classical server provided by SimulaQron.

        :param random_key: Random key generated for this iteration for authentication.
        :type random_key: str
        :param receiver: Authenticator's name.
        :type receiver: str
        """

        message = []
        i = 0
        while i < len(random_key):
            if i + 8 <= len(random_key):
                temp = random_key[i:i + 8]
            else:
                temp = random_key[i:len(random_key)]
            message.append(temp)
            i = i + 8
        for i in range(len(message)):
            message[i] = int(message[i], 2)

        with CQCConnection(self.name) as User:
            User.sendClassical(receiver, message)
Esempio n. 28
0
    def authenticate(self, receiver):
        """
        Method that takes care of prover's job.

        :param receiver: Name of the Authenticator.
        :type receiver: str
        """

        with CQCConnection(self.name) as User:

            for i in range(self.number_tokens):

                # Create and distribute ID Tokens
                self.idToken.append(self.createEnt(qubit(User), qubit(User),
                                                   2))
                User.sendQubit(self.idToken[i][1], receiver)

                # Create and store Aux Pairs
                self.auxPairs.append(
                    self.createEnt(qubit(User), qubit(User), 2))

            # Apply CNOT Operation
            self.cnotS()

            # Send Auxiliary pairs to Authenticator
            for i in range(self.number_tokens):
                User.sendQubit(self.auxPairs[i][0], receiver)
                User.sendQubit(self.auxPairs[i][1], receiver)
Esempio n. 29
0
    def authenticate(self):
        """
        Method that takes care of authenticator's job.

        :return: Result of authentication Check.
        :rtype: Boolean
        """

        with CQCConnection(self.name) as User:

            # Receive ID Token
            for i in range(self.number_tokens):
                self.idToken.append(User.recvQubit())

            # Receive Auxiliary Pairs
            for i in range(self.number_tokens):
                q1 = User.recvQubit()
                q2 = User.recvQubit()
                self.auxPairs.append([q1, q2])

            # Apply CNOT Operation
            self.cnotR()

            #Bell Measurement
            result = self.bellMeasure()

            #Check Authentication result
            flag = 0
            for i in result:
                if i != [0, 0]:
                    flag = 1
                    break

        #Return Authentication result
        return flag == 0
Esempio n. 30
0
    def send(self, filename, receiver='Bob'):
        with CQCConnection(self.name) as self.cqc:
            self.cqc.closeClassicalServer()
            self.receiver = receiver
            self.receiver_pkey = auth.get_public_key(receiver)

            f = open(filename, 'rb')
            message = f.read()
            f.close()

            self.n = len(message) * 8
            self.N = math.ceil((4 + self.correctness_param) * self.n) + 25
            communication.send_message(
                self.cqc, self.receiver, self.skey,
                json.dumps({
                    'n': self.n,
                    'security_param': self.security_param,
                    'correctness_param': self.correctness_param,
                    'filename': filename
                }))
            self._send_qubits()
            self._perform_basis_sift()
            can_continue = self._perform_error_estimation()
            if not can_continue:
                print('Not enough min entropy :(')
                return
            self._perform_error_correction()
            self._perform_privacy_amplification()
            cyphertext = self._encrypt(message)
            communication.send_binary_list(self.cqc, self.receiver, self.skey,
                                           cyphertext)