|
1 | 1 | from fastapi import FastAPI, WebSocket, HTTPException, WebSocketDisconnect
|
| 2 | +from pydantic import BaseModel |
| 3 | +from fastapi.middleware.cors import CORSMiddleware |
2 | 4 | 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 |
4 | 95 |
|
5 | 96 | class WebSocketConnectionManager:
|
6 | 97 | def __init__(self) -> None:
|
7 | 98 | self.active_connections: List[WebSocket] = []
|
| 99 | + self.token = 0 |
| 100 | + self.sentTokenTimes: int = 0 |
8 | 101 |
|
9 | 102 | async def connect(self, ws: WebSocket):
|
10 | 103 | await ws.accept()
|
11 | 104 | if len(self.active_connections) > 2:
|
12 | 105 | return 500
|
13 | 106 | 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) |
14 | 111 |
|
15 | 112 | async def disconnect(self):
|
16 | 113 | for connection in self.active_connections:
|
17 | 114 | self.active_connections.remove(connection)
|
18 | 115 |
|
19 | 116 | for connection in self.active_connections:
|
20 | 117 | await connection.close()
|
| 118 | + |
| 119 | + self.token = 0 |
21 | 120 |
|
22 |
| - |
23 | 121 | async def broadcast(self, message: str):
|
24 | 122 | 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) |
26 | 129 |
|
27 | 130 | mananger: WebSocketConnectionManager = WebSocketConnectionManager()
|
28 | 131 |
|
| 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 | + |
29 | 143 | @app.get("/")
|
30 | 144 | 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 | + |
32 | 175 |
|
33 | 176 | @app.websocket("/ws")
|
34 | 177 | 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) |
38 | 179 | try:
|
39 | 180 | while True:
|
40 | 181 | data = await websocket.receive_text()
|
41 | 182 | print(data)
|
42 | 183 | await mananger.broadcast(data)
|
43 | 184 | except WebSocketDisconnect:
|
44 | 185 | await mananger.disconnect()
|
45 |
| - # await mananger.broadcast(json.dumps({"text": "aborted"})) |
| 186 | + |
0 commit comments