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 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()
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
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()
def test_without_context(self): for _ in range(Settings.CONF_MAXQUBITS): cqc = CQCConnection("Alice") self.qubits.append(qubit(cqc)) with self.assertRaises(CQCNoQubitError): cqc = CQCConnection("Alice") qubit(cqc)
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()
def testCNotRemote(self): with CQCConnection("Alice", appID=1) as alice: # The appId in xtra_header['app_id'] is not 2 when testing. # In fact, doing this code in a real application result in an error as of 2018-03-12 with CQCConnection("Bob", appID=2) as bob: q1 = qubit(alice) q2 = qubit(bob) with self.assertRaises(CQCUnsuppError): q1.cnot(q2)
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 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)
def test_EPR(self): for sender_name, receiver_name in self.edges: with CQCConnection(sender_name) as sender: with CQCConnection(receiver_name) as receiver: 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) for sender_name, receiver_name in self.non_edges: with CQCConnection(sender_name) as sender: with CQCConnection(receiver_name) as receiver: with self.assertRaises(CQCUnsuppError): sender.createEPR(name=receiver_name, remote_appID=receiver._appID)
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()
def main(): connection = CQCConnection('Alice') q_channel = QChannel(connection, qubit, 'Eve') ca_channel = CAChannel(ipcCacClient('Alice'), 'Bob') node = BB84SenderNode(q_channel, ca_channel, 0, 1000) # perform QKD protocol node.share_q_states() if not node.should_abort(): k = node.generate_key() print("Alice generated key:", k) print("Alice calculated error:", node.matching_error) connection.close()
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()
def main(): n = parse_arguments() basis_string = '' bitstring = '' # Initialize the connection with CQCConnection("Bob") as Bob: for i in range(0, n): # Receive qubit from Alice (via Eve) q = Bob.recvQubit() # Choose a random basis chosen_basis = random.randint(0, 1) basis_string += str(chosen_basis) if chosen_basis == 1: q.H() # Retrieve key bit k = q.measure() bitstring += str(k) send_message(Bob, 'Alice', 'ok'.encode('UTF-8')) # Receive classical encoded message from Alice # enc = Bob.recvClassical()[0] # Calculate message # m = (enc + k) % 2 print("\nBob basis={}".format(basis_string)) print("Bob retrieved the key k={} from Alice.".format(bitstring))
def main(): # Initialize the connection with CQCConnection("Alice") as Alice: # Make an EPR pair with Bob qA = Alice.createEPR("Bob") # Create a qubit to teleport q = qubit(Alice) # Prepare the qubit to teleport in |+> q.H() # Apply the local teleportation operations q.cnot(qA) q.H() # Measure the qubits a = q.measure() b = qA.measure() to_print = "App {}: Measurement outcomes are: a={}, b={}".format( Alice.name, a, b) print("|" + "-" * (len(to_print) + 2) + "|") print("| " + to_print + " |") print("|" + "-" * (len(to_print) + 2) + "|") # Send corrections to Bob Alice.sendClassical("Bob", [a, b])
def main(nr_runs): meas_outcomes = {} # Initialize the connection with CQCConnection("Bob") as Bob: for _ in range(nr_runs): # Create an EPR pair q = Bob.recvEPR() # Get the identifier of this EPR pair such that Alice can relate the measuement outcomes to hers sequence_nr = q.get_entInfo().id_AB if (sequence_nr % 3) == 0: # Measure in Z pass elif (sequence_nr % 3) == 1: # Measure in X q.H() else: # Measure in Y q.K() m = q.measure() meas_outcomes[sequence_nr] = m # Encode the measurement outcomes to bytes, such that we can send them msg = json.dumps(meas_outcomes).encode("utf-8") # Send the measurement outcomes to Alice Bob.sendClassical(name="Alice", msg=msg)
def testFactoryNew(self): with CQCConnection("Alice", appID=1) as alice: # Should return a list of qubits with consecutive qubit ids alice.set_pending(True) qubit(alice) qubits = alice.flush_factory(10, do_sequence=False) # It is preferable to use the following however: # qubits = alice.allocate_qubits(10) alice.set_pending(False) # Checking the factory and the measure, factory should not log any commands lastEntries = get_last_entries(11) factoryEntry = lastEntries[0] self.assertEqual(factoryEntry["node_name"], "Alice") factory_cqc_header = factoryEntry["cqc_header"] self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY) expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH self.assertEqual(factory_cqc_header["header_length"], expected_length) self.assertEqual(factoryEntry["factory_iterations"], 10) for i in range(1, 11): xEntry = lastEntries[i] x_cmd_cmd_header = xEntry["cmd_header"] self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_NEW) curID = qubits[0]._qID for q in qubits[1:]: self.assertEqual(q._qID, curID + 1) curID = q._qID
def testCNOTFactory(self): with CQCConnection("Alice", appID=1) as cqc: # Test CNOT Factory Control even sys.stdout.write("Testing CNOT factory control even:") exp_values = calc_exp_values_single(prep_H_qutip()) ans = cqc.test_preparation(prep_CNOT_control_CQC_FACTORY_even, exp_values, iterations=self.iterations) # for _ in range(1): # freqs = cqc.tomography(prep_CNOT_control_CQC_FACTORY_even, 1, progress=False) # print("\nfreqs: {}".format(freqs)) sys.stdout.write("\r") # print("exp_values: {}".format(exp_values)) self.assertTrue(ans) # raise RuntimeError() # Test CNOT Factory Control odd sys.stdout.write("Testing CNOT factory control odd:") exp_values = calc_exp_values_two(prep_mixed_qutip()) ans = cqc.test_preparation(prep_CNOT_control_CQC_FACTORY_odd, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans) # Test CNOT Factory target even sys.stdout.write("Testing CNOT factory target even:") exp_values = calc_exp_values_single(prep_I_qutip()) ans = cqc.test_preparation(prep_CNOT_target_CQC_FACTORY_even, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans) # Test CNOT Factory target odd sys.stdout.write("Testing CNOT factory target odd:") exp_values = calc_exp_values_two(prep_mixed_qutip()) ans = cqc.test_preparation(prep_CNOT_target_CQC_FACTORY_odd, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans)
def main(): # Initialize the connection with CQCConnection("S1") as S1: # Make EPR-pairs with R1 and T2 q2 = S1.createEPR("R1") q0 = S1.createEPR("T2") # Make Bell measurement (step 1) q0.cnot(q2) m = q2.measure() # Send corrections to R1 (including sender) (step 1) msg = "S1".encode("utf-8") + bytes([m]) S1.sendClassical("R1", msg) # Receive correction from R1 (step 7) m = S1.recvClassical() if m == 1: q0.Z() # Measure out m = q0.measure() to_print = "0: Measurement outcome: {}".format(m) print("|" + "-" * (len(to_print) + 2) + "|") print("| " + to_print + " |") print("|" + "-" * (len(to_print) + 2) + "|")
def testFactorySend(self): with CQCConnection("Alice", appID=1) as alice: q1 = qubit(alice) alice.set_pending(True) alice.sendQubit(q1, name="Bob", remote_appID=5) res = alice.flush_factory(10, do_sequence=False) alice.set_pending(False) self.assertListEqual(res, []) lastEntries = get_last_entries(11) factoryEntry = lastEntries[0] self.assertEqual(factoryEntry["node_name"], "Alice") factory_cqc_header = factoryEntry["cqc_header"] self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY) expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCCommunicationHeader.HDR_LENGTH self.assertEqual(factory_cqc_header["header_length"], expected_length) self.assertEqual(factoryEntry["factory_iterations"], 10) for i in range(1, 11): xEntry = lastEntries[i] x_cmd_cmd_header = xEntry["cmd_header"] self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_SEND) self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID) xtra_header = xEntry["xtra_header"] self.assertEqual(xtra_header["remote_app_id"], 5) self.assertGreater(xtra_header["remote_node"], 1) self.assertGreater(xtra_header["remote_port"], 1)
def testFactoryEPR_RECV(self): with CQCConnection("Alice", appID=1) as alice: alice.set_pending(True) alice.recvEPR() qubits = alice.flush_factory(10, do_sequence=False) alice.set_pending(False) curID = qubits[0]._qID for q in qubits[1:]: self.assertEqual(q._qID, curID + 1) curID = q._qID lastEntries = get_last_entries(11) factoryEntry = lastEntries[0] self.assertEqual(factoryEntry["node_name"], "Alice") factory_cqc_header = factoryEntry["cqc_header"] self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY) expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH self.assertEqual(factory_cqc_header["header_length"], expected_length) self.assertEqual(factoryEntry["factory_iterations"], 10) for i in range(1, 11): xEntry = lastEntries[i] x_cmd_cmd_header = xEntry["cmd_header"] self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_EPR_RECV)
def testReleaseWhenAlreadyReleased(self): with CQCConnection("Alice", appID=1) as alice: qubits = alice.allocate_qubits(10) qubits[0].measure() with self.assertRaises(QubitNotActiveError): alice.release_qubits(qubits) self.assertTrue(qubits[1]._active)
def main(): n = parse_arguments() basis_string = '' bitstring = '' # Initialize the connection with CQCConnection("Alice") as Alice: for i in range(0, n): # Generate a key k = random.randint(0, 1) bitstring += str(k) chosen_basis = random.randint(0, 1) basis_string += str(chosen_basis) # Create a qubit q = qubit(Alice) # Encode the key in the qubit if k == 1: q.X() # Encode in H basis if basis = 1 if chosen_basis == 1: q.H() # Send qubit to Bob (via Eve) Alice.sendQubit(q, "Eve") receive_message(Alice) print("\nAlice basis={}".format(basis_string)) print("Alice sent the key k={} to Bob".format(bitstring))
def testCPhaseFactory(self): with CQCConnection("Alice", appID=1) as cqc: # Test CPHASE Factory Control even sys.stdout.write("Testing CPHASE factory control even:") exp_values = calc_exp_values_single(prep_H_qutip()) ans = cqc.test_preparation(prep_CPHASE_control_CQC_FACTORY_even, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans) # Test CPHASE Factory Control odd sys.stdout.write("Testing CPHASE factory control odd:") exp_values = calc_exp_values_two(prep_mixed_qutip()) ans = cqc.test_preparation(prep_CPHASE_control_CQC_FACTORY_odd, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans) # Test CPHASE Factory target even sys.stdout.write("Testing CPHASE factory target even:") exp_values = calc_exp_values_single(prep_I_qutip()) ans = cqc.test_preparation(prep_CPHASE_target_CQC_FACTORY_even, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans) # Test CPHASE Factory target odd sys.stdout.write("Testing CPHASE factory target odd:") exp_values = calc_exp_values_two(prep_mixed_qutip()) ans = cqc.test_preparation(prep_CPHASE_target_CQC_FACTORY_odd, exp_values, iterations=self.iterations) sys.stdout.write("\r") self.assertTrue(ans)
def main(): # Initialize the connection with CQCConnection("Alice") as Alice: Alice.closeClassicalServer() # Generate a key k = random.randint(0, 1) chosen_basis = random.randint(0, 1) # Create a qubit q = qubit(Alice) # Encode the key in the qubit if k == 1: q.X() # Encode in H basis if basis = 1 if chosen_basis == 1: q.H() # Send qubit to Bob (via Eve) Alice.sendQubit(q, "Eve") # Encode and send a classical message m to Bob m = 1 enc = (m + k) % 2 send_message(Alice, "Bob", bytes([enc])) print("\nAlice basis={}".format(BASIS[chosen_basis])) print("Alice key={}".format(k)) print("Alice sent the message m={} to Bob".format(m))
def testFactoryReset(self): with CQCConnection("Alice", appID=1) as alice: q1 = qubit(alice) alice.set_pending(True) q1.reset() res = alice.flush_factory(10, do_sequence=False) alice.set_pending(False) self.assertListEqual(res, []) lastEntries = get_last_entries(11) factoryEntry = lastEntries[0] self.assertEqual(factoryEntry["node_name"], "Alice") factory_cqc_header = factoryEntry["cqc_header"] self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY) expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH self.assertEqual(factory_cqc_header["header_length"], expected_length) self.assertEqual(factoryEntry["factory_iterations"], 10) for i in range(1, 11): xEntry = lastEntries[i] x_cmd_cmd_header = xEntry["cmd_header"] self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_RESET) self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)
def testFactoryROTX(self): with CQCConnection("Alice", appID=1) as alice: q1 = qubit(alice) alice.set_pending(True) q1.rot_X(step=5) alice.flush_factory(10, do_sequence=False) alice.set_pending(False) q1.measure(inplace=True) # Checking the factory and the measure, factory should not log any commands lastEntries = get_last_entries(12) factoryEntry = lastEntries[0] self.assertEqual(factoryEntry["node_name"], "Alice") factory_cqc_header = factoryEntry["cqc_header"] self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY) expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCRotationHeader.HDR_LENGTH self.assertEqual(factory_cqc_header["header_length"], expected_length) self.assertEqual(factoryEntry["factory_iterations"], 10) for i in range(1, 11): xEntry = lastEntries[i] x_cmd_cmd_header = xEntry["cmd_header"] self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_ROT_X) self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID) xtra_header = xEntry["xtra_header"] self.assertEqual(xtra_header["step"], 5) # cqc header is the same as the first. measureEntry = lastEntries[11] self.assertEqual(measureEntry["cmd_header"]["instruction"], CQC_CMD_MEASURE_INPLACE) self.assertEqual(measureEntry["cmd_header"]["qubit_id"], q1._qID)
def testFactoryMeasureInplace(self): with CQCConnection("Alice", appID=1) as alice: # should give the same results as inplace = false q1 = qubit(alice) alice.set_pending(True) q1.measure(inplace=True) measurements = alice.flush_factory(10, do_sequence=False) alice.set_pending(False) # All measurements should be equal to 2 self.assertTrue(all(x == 2 for x in measurements)) lastEntries = get_last_entries(11) factoryEntry = lastEntries[0] self.assertEqual(factoryEntry["node_name"], "Alice") factory_cqc_header = factoryEntry["cqc_header"] self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY) expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH self.assertEqual(factory_cqc_header["header_length"], expected_length) self.assertEqual(factoryEntry["factory_iterations"], 10) for i in range(1, 11): xEntry = lastEntries[i] x_cmd_cmd_header = xEntry["cmd_header"] self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_MEASURE_INPLACE) self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)
def prep_recv_CQC(cqc): with CQCConnection("Alice", appID=1) as Alice: qA = qubit(Alice) qA.H() Alice.sendQubit(qA, "Bob") qB = cqc.recvQubit() return qB
def main(): # Initialize the connection with CQCConnection("Bob") as Bob: Bob.closeClassicalServer() # Receive qubit from Alice (via Eve) q = Bob.recvQubit() # Choose a random basis chosen_basis = random.randint(0, 1) if chosen_basis == 1: q.H() # Retrieve key k = q.measure() # Receive classical encoded message from Alice enc = receive_message(Bob)[0] # Calculate message m = (enc + k) % 2 print("\nBob basis={}".format(BASIS[chosen_basis])) print("Bob key={}".format(k)) print("Bob retrieved the message m={} from Alice.".format(m))