USTC-Hackergame / hackergame2022-writeups

Hackergame 2022 的官方与非官方题解
Other
306 stars 55 forks source link

Unused classical register plus addition of extra one with `measure_all` #64

Closed MattePalte closed 8 months ago

MattePalte commented 8 months ago

Environment

What is happening?

In the Python file code.py the qc.measure_all() call creates a new classical register and does not use the one already provided during initialization via QuantumCircuit(129,128).

https://github.com/USTC-Hackergame/hackergame2022-writeups/blob/46e8478c0c89cc187133ee2dc8378ae2b8866784/players/cvhc/%E9%87%8F%E5%AD%90%E8%97%8F%E5%AE%9D%E5%9B%BE/code.py#L69

How can we reproduce the issue?

I demonstrate the issue at a smaller scale, becasue I cannot simulate such a large circuit, but the issue is even more important when the register allocated are bigger. Run the following code in the Python file:

from qiskit import QuantumCircuit, Aer

circuit = QuantumCircuit(5, 5)
circuit.x(0)
circuit.x(4)
circuit.measure_all()  # <-- this will create a new classical register

sim = Aer.get_backend('qasm_simulator')
counts = sim.run(circuit).result().get_counts()
print(counts)  # <-- you can see the output here

The output will be {'10001 00000': 1024}. There are double the number of bits in the output, because the classical register is not used.

What should happen?

I would have expected to use the classical register already provided during initialization.

Any suggestions?

What about using the add_bits=False flag in the measure_all method to reuse the existing classical register? Here is the suggested version:

qc.measure_all(add_bits=False)

Thanks in advance, I wish you a happy and productive day.

taoky commented 8 months ago

Please note that this is an archive repo for a CTF-like competition in 2022, including players' writeups. This part of code is inside a player's submitted writeup and we would not make any modifications.