Skip to content

Commit 2f858ad

Browse files
authored
add quantum token generation
1 parent 5c9fdc8 commit 2f858ad

File tree

1 file changed

+149
-8
lines changed

1 file changed

+149
-8
lines changed

backend/main.py

+149-8
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,186 @@
11
from fastapi import FastAPI, WebSocket, HTTPException, WebSocketDisconnect
2+
from pydantic import BaseModel
3+
from fastapi.middleware.cors import CORSMiddleware
24
import json
3-
app = FastAPI()
5+
from qiskit import QuantumCircuit
6+
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
7+
from math import pi
8+
from qiskit import Aer, execute
9+
import random
10+
11+
12+
def binaryToDecimal(binary):
13+
decimal, i = 0, 0
14+
while(binary != 0):
15+
dec = binary % 10
16+
decimal = decimal + dec * pow(2, i)
17+
binary = binary//10
18+
i += 1
19+
return decimal
20+
21+
def createCircuit(numUsers, QECQubits, registers):
22+
users = QuantumRegister(numUsers, "user")
23+
ancillas = QuantumRegister(QECQubits, "ancilla")
24+
cr = ClassicalRegister(registers, 'c')
25+
qc = QuantumCircuit(users, ancillas, cr)
26+
return qc
27+
28+
numUsers = 3
29+
QECQubits = 1
30+
registers = 3
31+
def initializeDialog(userIn):
32+
qc = createCircuit(numUsers, QECQubits, registers)
33+
qc.h(userIn)
34+
return qc
35+
36+
def enterDialog(userIn, userEn):
37+
qc = initializeDialog(userIn)
38+
qc.cnot(userIn, userEn)
39+
return qc
40+
41+
def closeDialog(qc, userIn, userEn):
42+
qc.reset(userIn)
43+
qc.reset(userEn)
44+
return qc
45+
46+
def errorX(qc, userIn, userEn):
47+
qc.rx(random.random()*pi/2, userIn)
48+
qc.rx(random.random()*pi/2, userEn)
49+
return qc
50+
51+
def errorCorrection(qc, userIn, userEn, QECQubit):
52+
qc.cnot(userIn, QECQubit)
53+
qc.cnot(userEn, QECQubit)
54+
return qc
55+
56+
def getPrivateKeys(userIn, userEn, QECQubit, keyLength):
57+
qc = enterDialog(userIn, userEn)
58+
59+
qc.barrier()
60+
qc = errorX(qc, userIn, userEn)
61+
qc.barrier()
62+
63+
qc = errorCorrection(qc, userIn, userEn, QECQubit)
64+
qc.barrier()
65+
qc.measure([userIn, userEn, QECQubit], [0,1,2])
66+
67+
lstIn = []
68+
lstEn = []
69+
counts = []
70+
71+
72+
while len(lstEn) <= keyLength:
73+
backend = Aer.get_backend('qasm_simulator')
74+
job_sim = execute(qc, backend, shots = 1)
75+
result = job_sim.result()
76+
count = result.get_counts(qc)
77+
counts.append(count)
78+
if (int(list(count.keys())[0][0]) == 0):
79+
lstIn.append(list(count.keys())[0][registers-userIn-1])
80+
lstEn.append(list(count.keys())[0][registers-userEn-1])
81+
82+
83+
if (len(lstIn) != 0 and len(lstEn) != 0):
84+
if lstIn[0] == 0:
85+
lstIn = lstIn[1:]
86+
if lstEn[0] == 0:
87+
lstEn = lstEn[1:]
88+
keyIn = binaryToDecimal(int("".join(lstIn)))
89+
keyEn = binaryToDecimal(int("".join(lstEn)))
90+
91+
if keyIn != keyEn:
92+
return 0
93+
else:
94+
return keyIn
495

596
class WebSocketConnectionManager:
697
def __init__(self) -> None:
798
self.active_connections: List[WebSocket] = []
99+
self.token = 0
100+
self.sentTokenTimes: int = 0
8101

9102
async def connect(self, ws: WebSocket):
10103
await ws.accept()
11104
if len(self.active_connections) > 2:
12105
return 500
13106
self.active_connections.append(ws)
107+
if len(self.active_connections) == 2:
108+
if self.token == 0:
109+
self.token = getPrivateKeys(0, 1, 3, 16)
110+
print(self.token)
14111

15112
async def disconnect(self):
16113
for connection in self.active_connections:
17114
self.active_connections.remove(connection)
18115

19116
for connection in self.active_connections:
20117
await connection.close()
118+
119+
self.token = 0
21120

22-
23121
async def broadcast(self, message: str):
24122
for connection in self.active_connections:
25-
await connection.send_text(message)
123+
if len(self.active_connections) == 2 and self.sentTokenTimes<2:
124+
# await connection.send_text(json.dumps({"token":str(self.token)}))
125+
await connection.send_text(json.dumps({"text":str(self.token)}))
126+
self.sentTokenTimes += 1
127+
else:
128+
await connection.send_text(message)
26129

27130
mananger: WebSocketConnectionManager = WebSocketConnectionManager()
28131

132+
133+
app = FastAPI()
134+
135+
app.add_middleware(
136+
CORSMiddleware,
137+
allow_origins=["*"],
138+
allow_credentials=True,
139+
allow_methods=["*"],
140+
allow_headers=["*"],
141+
)
142+
29143
@app.get("/")
30144
async def root():
31-
return {"message": "Hello World"}
145+
result = getPrivateKeys(0, 1, 3, 128)
146+
print(result)
147+
raise HTTPException(status_code=500, detail="Oops")
148+
149+
roomCreated:bool = False
150+
roomJoined: bool = False
151+
152+
class RoomCreator(BaseModel):
153+
id: str
154+
155+
class RoomVisitor(BaseModel):
156+
id: str
157+
158+
@app.post("/create/room")
159+
async def main(req: RoomCreator):
160+
print(req)
161+
if not roomCreated:
162+
roomCreated = True
163+
return {"message": "Room created. Waiting for your buddy to join."}
164+
else:
165+
raise HTTPException(status_code=500, detail="")
166+
167+
@app.get("/join/room")
168+
async def join():
169+
if not roomCreated:
170+
return {"message": "Sorry, no room is created yet"}
171+
roomJoined = True
172+
return {"message": "You want to enter the room!"}
173+
174+
32175

33176
@app.websocket("/ws")
34177
async def websocket_endpoint(websocket: WebSocket):
35-
if await mananger.connect(websocket) == 500:
36-
raise HTTPException(status_code=500, details="Connection limit exceeded")
37-
178+
await mananger.connect(websocket)
38179
try:
39180
while True:
40181
data = await websocket.receive_text()
41182
print(data)
42183
await mananger.broadcast(data)
43184
except WebSocketDisconnect:
44185
await mananger.disconnect()
45-
# await mananger.broadcast(json.dumps({"text": "aborted"}))
186+

0 commit comments

Comments
 (0)