-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathhttp.rs
More file actions
502 lines (434 loc) · 18.1 KB
/
http.rs
File metadata and controls
502 lines (434 loc) · 18.1 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use std::{
str::FromStr,
sync::Arc,
time::{Instant, SystemTime, UNIX_EPOCH},
};
#[cfg(feature = "tls")]
use rustls::{
pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer},
ServerConfig,
};
use actix_multipart::form::MultipartForm;
use actix_web::{
web::{self, Data},
App, HttpRequest, HttpResponse, HttpServer, Responder,
};
use actix_web_prometheus::PrometheusMetricsBuilder;
use agg_mode_sdk::{blockchain::AggregationModeProvingSystem, types::Network};
use alloy::signers::Signature;
use sp1_sdk::{SP1ProofWithPublicValues, SP1VerifyingKey};
use sqlx::types::BigDecimal;
use super::{
helpers::format_merkle_path,
types::{AppResponse, GetReceiptsQueryParams},
};
use crate::{
config::Config,
db::Db,
helpers::get_time_left_day_formatted,
metrics::GatewayMetrics,
types::{GetReceiptsResponse, SubmitProofRequestRisc0, SubmitProofRequestSP1},
verifiers::{verify_sp1_proof, VerificationError},
};
#[derive(Clone, Debug)]
pub struct GatewayServer {
db: Db,
config: Config,
network: Network,
metrics: Arc<GatewayMetrics>,
}
impl GatewayServer {
pub fn new(db: Db, config: Config) -> Self {
let network = Network::from_str(&config.network).expect("A valid network in config file");
tracing::info!(
"Starting metrics server on port {}",
config.gateway_metrics_port
);
let metrics = GatewayMetrics::start(config.gateway_metrics_port)
.expect("Failed to start metrics server");
Self {
db,
config,
network,
metrics,
}
}
#[cfg(feature = "tls")]
fn load_tls_config(
cert_path: &str,
key_path: &str,
) -> Result<ServerConfig, Box<dyn std::error::Error>> {
// Install the default crypto provider
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
// Load certificate chain
let certs: Vec<CertificateDer> =
CertificateDer::pem_file_iter(cert_path)?.collect::<Result<Vec<_>, _>>()?;
// Load private key
let private_key = PrivateKeyDer::from_pem_file(key_path)?;
let config = ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, private_key)?;
Ok(config)
}
pub async fn start(&self) {
// Note: GatewayServer is thread safe so we can just clone it (no need to add mutexes)
let http_port = self.config.port;
let state = self.clone();
// Note: This creates a new Prometheus server different from the one created in GatewayServer::new. The created
// server exposes metrics related to the actix HTTP server, like response codes and response times
let prometheus = PrometheusMetricsBuilder::new("api")
.endpoint("/metrics")
.build()
.unwrap();
let server = HttpServer::new(move || {
App::new()
.app_data(Data::new(state.clone()))
.wrap(prometheus.clone())
.route("/", web::get().to(Self::get_root))
.route("/nonce/{address}", web::get().to(Self::get_nonce))
.route("/receipts", web::get().to(Self::get_receipts))
.route("/proof/sp1", web::post().to(Self::post_proof_sp1))
.route("/proof/risc0", web::post().to(Self::post_proof_risc0))
.route("/quotas/{address}", web::get().to(Self::get_quotas))
});
#[cfg(feature = "tls")]
{
let tls_port = self.config.tls_port;
tracing::info!(
"Starting HTTP server at http://{}:{}",
self.config.ip,
http_port
);
tracing::info!(
"Starting HTTPS server at https://{}:{}",
self.config.ip,
tls_port
);
let tls_config =
Self::load_tls_config(&self.config.tls_cert_path, &self.config.tls_key_path)
.expect("Failed to load TLS configuration");
server
.bind((self.config.ip.as_str(), http_port))
.expect("To bind HTTP socket correctly")
.bind_rustls_0_23((self.config.ip.as_str(), tls_port), tls_config)
.expect("To bind HTTPS socket correctly with TLS")
.run()
.await
.expect("Server to never end");
}
#[cfg(not(feature = "tls"))]
{
tracing::info!(
"Starting HTTP server at http://{}:{}",
self.config.ip,
http_port
);
server
.bind((self.config.ip.as_str(), http_port))
.expect("To bind HTTP socket correctly")
.run()
.await
.expect("Server to never end");
}
}
// Returns an OK response (code 200), no matters what receives in the request
async fn get_root(_req: HttpRequest) -> impl Responder {
HttpResponse::Ok().json(AppResponse::new_sucessfull(serde_json::json!({})))
}
// Returns the nonce (number of submitted tasks) for a given address
async fn get_nonce(req: HttpRequest) -> impl Responder {
let Some(address_raw) = req.match_info().get("address") else {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Missing address", 400));
};
// Check that the address is a valid ethereum address
if alloy::primitives::Address::from_str(address_raw.trim()).is_err() {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Invalid address", 400));
}
let address = address_raw.to_lowercase();
let Some(state) = req.app_data::<Data<GatewayServer>>() else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
let state = state.get_ref();
match state.db.count_tasks_by_address(&address).await {
Ok(count) => HttpResponse::Ok().json(AppResponse::new_sucessfull(serde_json::json!(
{
"nonce": count
}
))),
Err(_) => HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500)),
}
}
// Posts an SP1 proof to the gateway, recovering the address from the signature
async fn post_proof_sp1(
req: HttpRequest,
MultipartForm(data): MultipartForm<SubmitProofRequestSP1>,
) -> impl Responder {
let Some(state) = req.app_data::<Data<GatewayServer>>() else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
let state = state.get_ref();
let Ok(signature) = Signature::from_str(&data.signature_hex.0) else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Invalid signature", 500));
};
let Ok(proof_content) = tokio::fs::read(data.proof.file.path()).await else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
let Ok(vk_content) = tokio::fs::read(data.program_vk.file.path()).await else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
// reconstruct message and recover address
let msg = agg_mode_sdk::gateway::types::SubmitSP1ProofMessage::new(
data.nonce.0,
proof_content.clone(),
vk_content.clone(),
);
let Ok(recovered_address) =
signature.recover_address_from_prehash(&msg.eip712_hash(&state.network).into())
else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
let recovered_address = recovered_address.to_string().to_lowercase();
// Checking if this address has submited more proofs than the ones allowed per day
let Ok(daily_tasks_by_address) = state
.db
.get_daily_tasks_by_address(&recovered_address)
.await
else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
if daily_tasks_by_address >= state.config.max_daily_proofs_per_user {
let formatted_time_left = get_time_left_day_formatted();
return HttpResponse::BadRequest().json(AppResponse::new_unsucessfull(
format!(
"Request denied: Query limit exceeded. Quotas renew in {formatted_time_left}"
)
.as_str(),
400,
));
}
let Ok(count) = state.db.count_tasks_by_address(&recovered_address).await else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
if data.nonce.0 != (count as u64) {
return HttpResponse::BadRequest().json(AppResponse::new_unsucessfull(
&format!("Invalid nonce, expected nonce = {count}"),
400,
));
}
let now_epoch = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(duration) => duration.as_secs(),
Err(_) => {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
}
};
let has_payment = match state
.db
.has_active_payment_event(
&recovered_address,
// safe unwrap the number comes from a valid u64 primitive
BigDecimal::from_str(&now_epoch.to_string()).unwrap(),
)
.await
{
Ok(result) => result,
Err(_) => {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
}
};
if !has_payment {
return HttpResponse::BadRequest().json(AppResponse::new_unsucessfull(
"You have to pay before submitting a proof",
400,
));
}
let Ok(proof) = bincode::deserialize::<SP1ProofWithPublicValues>(&proof_content) else {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Invalid SP1 proof", 400));
};
let Ok(vk) = bincode::deserialize::<SP1VerifyingKey>(&vk_content) else {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Invalid vk", 400));
};
if let Err(e) = verify_sp1_proof(&proof, &vk) {
let message = match e {
VerificationError::InvalidProof => "Proof verification failed",
VerificationError::UnsupportedProof => "Unsupported proof",
};
return HttpResponse::BadRequest().json(AppResponse::new_unsucessfull(message, 400));
};
let query_started_at = Instant::now();
match state
.db
.insert_task(
&recovered_address,
AggregationModeProvingSystem::SP1.as_u16() as i32,
&proof_content,
&vk_content,
None,
data.nonce.0 as i64,
)
.await
{
Ok(task_id) => {
let time_elapsed_db_call = query_started_at.elapsed();
state
.metrics
.register_db_response_time_post("sp1-post", time_elapsed_db_call.as_secs_f64());
HttpResponse::Ok().json(AppResponse::new_sucessfull(
serde_json::json!({ "task_id": task_id.to_string() }),
))
}
Err(_) => HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500)),
}
}
/// TODO: complete for risc0 (see `post_proof_sp1`)
// Posts a Risc0 proof to the gateway, recovering the address from the signature
async fn post_proof_risc0(
_req: HttpRequest,
MultipartForm(_): MultipartForm<SubmitProofRequestRisc0>,
) -> impl Responder {
HttpResponse::Ok().json(AppResponse::new_sucessfull(serde_json::json!({})))
}
// Returns the last 100 receipt merkle proofs for the address received in the URL.
// In case of also receiving a nonce on the query param, it returns only the merkle proof for that nonce.
async fn get_receipts(
req: HttpRequest,
params: web::Query<GetReceiptsQueryParams>,
) -> impl Responder {
let Some(state) = req.app_data::<Data<GatewayServer>>() else {
return HttpResponse::InternalServerError().json(AppResponse::new_unsucessfull(
"Internal server error: Failed to get app data",
500,
));
};
let state = state.get_ref();
if alloy::primitives::Address::from_str(params.address.clone().trim()).is_err() {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Invalid address", 400));
}
let limit = match params.limit {
Some(received_limit) => received_limit.min(100),
None => 100,
};
let address = params.address.to_lowercase();
let query = if let Some(nonce) = params.nonce {
state
.db
.get_tasks_by_address_and_nonce(&address, nonce)
.await
} else {
state
.db
.get_tasks_by_address_with_limit(&address, limit)
.await
};
let Ok(receipts) = query else {
return HttpResponse::InternalServerError().json(AppResponse::new_unsucessfull(
"Internal server error: Failed to get tasks by address and nonce",
500,
));
};
let responses: Result<Vec<GetReceiptsResponse>, String> = receipts
.into_iter()
.map(|receipt| {
let Some(merkle_path) = receipt.merkle_path else {
return Ok(GetReceiptsResponse {
status: receipt.status,
merkle_path: Vec::new(),
nonce: receipt.nonce,
address: receipt.address,
});
};
let Ok(formatted) = format_merkle_path(&merkle_path) else {
return Err("Error formatting merkle path".into());
};
Ok(GetReceiptsResponse {
status: receipt.status,
merkle_path: formatted,
nonce: receipt.nonce,
address: receipt.address,
})
})
.collect();
match responses {
Ok(resp) => HttpResponse::Ok().json(AppResponse::new_sucessfull(serde_json::json!({
"receipts": resp
}))),
Err(_) => HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500)),
}
}
async fn get_quotas(req: HttpRequest) -> impl Responder {
let Some(state) = req.app_data::<Data<GatewayServer>>() else {
return HttpResponse::InternalServerError().json(AppResponse::new_unsucessfull(
"Internal server error: Failed to get app data",
500,
));
};
let state = state.get_ref();
let Some(address_raw) = req.match_info().get("address") else {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Missing address", 400));
};
// Check that the address is a valid ethereum address
if alloy::primitives::Address::from_str(address_raw.trim()).is_err() {
return HttpResponse::BadRequest()
.json(AppResponse::new_unsucessfull("Invalid address", 400));
}
let address = address_raw.trim().to_lowercase();
let Ok(daily_tasks_by_address) = state.db.get_daily_tasks_by_address(&address).await else {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
};
let formatted_time_left = get_time_left_day_formatted();
let now_epoch = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(duration) => duration.as_secs(),
Err(_) => {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
}
};
let has_payment = match state
.db
.has_active_payment_event(
&address,
// safe unwrap the number comes from a valid u64 primitive
BigDecimal::from_str(&now_epoch.to_string()).unwrap(),
)
.await
{
Ok(result) => result,
Err(_) => {
return HttpResponse::InternalServerError()
.json(AppResponse::new_unsucessfull("Internal server error", 500));
}
};
if has_payment {
HttpResponse::Ok().json(AppResponse::new_sucessfull(serde_json::json!({
"proofs_submitted": daily_tasks_by_address,
"quota_limit": state.config.max_daily_proofs_per_user,
"quota_remaining": (state.config.max_daily_proofs_per_user - daily_tasks_by_address),
"quota_resets_in": formatted_time_left.as_str()
})))
} else {
HttpResponse::Ok().json(AppResponse::new_unsucessfull(
"The address doesn't have an active subscription",
404,
))
}
}
}