forked from tompetersen/threshold-crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
212 lines (162 loc) · 5.94 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import logging
import random
import uvicorn
from typing import Any, Generator, List, Dict
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from database import init_db
import models
from pydantic import BaseModel, Field
import threshold_crypto as tc
from threshold_crypto.data import CurveParameters, ThresholdParameters
import json
app = FastAPI()
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# These will be set up later
engine = None
SessionLocal = None
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def check_or_create_self_participant(db: Session):
self_participant = db.query(models.Participant).filter_by(is_self=True).first()
if self_participant:
logger.info(
f"Existing self participant found with ID: {self_participant.participant_id}"
)
else:
new_id = random.randint(1, 100000000)
logger.info(f"Creating a new self for key generation with ID: {new_id}")
db.add(models.Participant(participant_id=new_id, is_self=True))
db.commit()
### API endpoints ###
@app.get("/status")
def read_status() -> dict[str, str]:
return {"status": "OK"}
@app.get("/get_id")
def get_id(db: Session = Depends(get_db)):
self_participant = db.query(models.Participant).filter_by(is_self=True).first()
if not self_participant:
raise HTTPException(status_code=404, detail="Self participant not found")
return {"id": self_participant.participant_id}
class ParticipantList(BaseModel):
participants: List[int]
@app.post("/register_participants")
def register_participants(
participant_list: ParticipantList, db: Session = Depends(get_db)
):
for participant_id in participant_list.participants:
existing = (
db.query(models.Participant)
.filter_by(participant_id=participant_id)
.first()
)
if not existing:
new_participant = models.Participant(participant_id=participant_id)
db.add(new_participant)
db.commit()
return {"status": "Participants registered"}
@app.post("/start_dkg")
def start_dkg(db: Session = Depends(get_db)):
# Here you would implement the actual DKG logic
# This is a placeholder for now
return {"status": "DKG process started"}
@app.get("/participants")
def get_all_participants(
db: Session = Depends(get_db),
) -> Dict[str, List[Dict[str, Any]]]:
participants = db.query(models.Participant).all()
return {
"participants": [
{
"participant_id": p.participant_id,
"is_self": p.is_self,
"closed_commitment": p.closed_commitment,
}
for p in participants
]
}
# Add this new class for the request body
class CommitmentRequest(BaseModel):
t: int
n: int
@app.post("/generate_closed_commitment")
def generate_closed_commitment(
request: CommitmentRequest, db: Session = Depends(get_db)
):
threshold_parameters = ThresholdParameters(request.t, request.n)
curve_parameters = CurveParameters()
me = db.query(models.Participant).filter_by(is_self=True).first()
if not me:
raise HTTPException(status_code=404, detail="Self participant not found")
all_participants = db.query(models.Participant).all()
all_participant_ids = [p.participant_id for p in all_participants]
participant = tc.participant.Participant(
me.participant_id,
all_participant_ids,
curve_parameters,
threshold_parameters,
)
commitment = participant.closed_commitment()
commitment_json = commitment.to_json()
logger.info(f"Generated closed commitment: {commitment_json}")
return {"participant_id": me.participant_id, "commitment": commitment_json}
class ClosedCommitment(BaseModel):
participant_id: int
commitment: str
class ClosedCommitmentList(BaseModel):
commitments: List[ClosedCommitment]
@app.post("/receive_closed_commitments")
def receive_closed_commitments(
commitment_list: ClosedCommitmentList, db: Session = Depends(get_db)
):
for commitment in commitment_list.commitments:
# Create a JSON string from the commitment data
commitment_json = json.dumps(
{
"participant_id": commitment.participant_id,
"commitment": commitment.commitment,
}
)
# Use DkgClosedCommitment.from_json to create the object
try:
dkg_commitment = tc.data.DkgClosedCommitment.from_json(commitment_json)
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Invalid commitment data for participant {commitment.participant_id}: {str(e)}",
)
# Find the participant and update their closed_commitment
participant = (
db.query(models.Participant)
.filter_by(participant_id=dkg_commitment.participant_id)
.first()
)
if not participant:
raise HTTPException(
status_code=404,
detail=f"Participant {dkg_commitment.participant_id} not found",
)
# Serialize the DkgClosedCommitment object back to JSON string
# Improvement: It'd be better to just store the commitment bytes directly.
participant.closed_commitment = dkg_commitment.to_json()
db.add(participant)
db.commit()
return {"status": "Closed commitments received and stored"}
### Entrypoint & Event Handlers ###
@app.on_event("startup")
async def startup_event():
db = next(get_db())
check_or_create_self_participant(db)
def start(port: int = 8000, db_file: str = "keyholder.db") -> None:
global engine, SessionLocal
engine, SessionLocal = init_db(db_file)
models.Base.metadata.create_all(bind=engine)
uvicorn.run(app, host="0.0.0.0", port=port)
if __name__ == "__main__":
start()