-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
201 lines (166 loc) · 6.62 KB
/
server.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
from cryptography.hazmat.primitives import serialization
from fastapi import FastAPI, HTTPException, Request, UploadFile, File
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
import base64
import logging
import requests
import random
from io import BytesIO
from PIL import Image
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust this to the domains you want to allow
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load the private key from a file
with open("private_key.pem", "rb") as f:
private_key = serialization.load_pem_private_key(f.read(), password=None)
# Load the public key from a file
with open("public_key.pem", "rb") as f:
public_key = serialization.load_pem_public_key(f.read())
# Define the request body schema
class MessageRequest(BaseModel):
postfix: str
uid: int
# Define the request body schema for /forward_image
class ImageRequest(BaseModel):
image: str
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
validator_ip = '44.201.142.122'
validator_proxy_port = 47923
def get_public_key():
public_key_bytes = public_key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw
)
encoded_public_key = base64.b64encode(public_key_bytes).decode('utf-8')
return encoded_public_key
# Exception handler for request validation errors
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
logger.error(f"Validation error: {exc}")
return JSONResponse(
status_code=422,
content={"detail": exc.errors(), "body": exc.body},
)
@app.post("/get_credentials")
async def get_credentials(request: MessageRequest, client_request: Request):
try:
# Get the message from the request
message = b"This is a secure message"
# Sign the message with the private key
signature = private_key.sign(message)
encoded_signature = base64.b64encode(signature).decode('utf-8')
data = {
"message": message,
"signature": encoded_signature
}
return data
except Exception as e:
logger.error(f"Unexpected error: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.post("/checkimage")
async def spoof_response(request: ImageRequest):
try:
# Generate spoof response
boolean_response = random.choice([True, False])
float_list = [random.uniform(0, 1) for _ in range(10)]
return JSONResponse(
status_code=200,
content={
'ai-generated': boolean_response,
'predictions': float_list
}
)
except Exception as e:
logger.error(f"Failed to generate spoof response: {e}")
raise HTTPException(status_code=500, detail="Failed to generate spoof response")
@app.post("/forward_image")
async def test_image(file: UploadFile = File(...)):
try:
# Read the image file
contents = await file.read()
image = Image.open(BytesIO(contents))
# Convert the image to a base64 string
buffered = BytesIO()
image.save(buffered, format=image.format)
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
# Construct the URL for forwarding the request
forward_url = f"http://{validator_ip}:{validator_proxy_port}/validator_proxy"
# Forward the request to the last client
data = {"image": img_str}
data['authorization'] = get_public_key()
print(forward_url)
response = requests.post(forward_url, json=data)
predictions = response.json()
print('validator response', predictions)
# Ensure predictions are floats before comparison
predictions = [float(pred) for pred in predictions]
prediction = True if len([p for p in predictions if p > 0.5]) >= (len(predictions) / 2) else False
return JSONResponse(
status_code=response.status_code,
content={
'predictions': predictions,
'ai-generated': prediction
}
)
except Exception as e:
logger.error(f"Failed to forward request: {e}")
raise HTTPException(status_code=500, detail="Failed to forward the request")
@app.post("/forward_image_b64")
async def forward_image(request: ImageRequest):
try:
# Construct the URL for forwarding the request
forward_url = f"http://{validator_ip}:{validator_proxy_port}/validator_proxy"
# Forward the request to the last client
data = request.dict()
data['authorization'] = get_public_key()
print(forward_url)
response = requests.post(forward_url, json=data)
predictions = response.json()
print('validator response', predictions)
# Ensure predictions are floats before comparison
predictions = [float(pred) for pred in predictions]
prediction = True if len([p for p in predictions if p > 0.5]) >= (len(predictions) / 2) else False
return JSONResponse(
status_code=response.status_code,
content={
'predictions': predictions,
'ai-generated': prediction
}
)
except Exception as e:
logger.error(f"Failed to forward request: {e}")
raise HTTPException(status_code=500, detail="Failed to forward the request")
@app.get("/miner_performance")
async def miner_performance():
try:
# Construct the URL for forwarding the request
forward_url = f"http://{validator_ip}:{validator_proxy_port}/miner_performance"
print(forward_url)
# Forward the request to the last client
data = {}
data['authorization'] = get_public_key()
response = requests.get(forward_url, json=data)
predictions = response.json()
print('validator response', predictions)
return JSONResponse(
status_code=response.status_code,
content=response.json()
)
except Exception as e:
logger.error(f"Failed to forward request: {e}")
raise HTTPException(status_code=500, detail="Failed to forward the request")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=47927)