1use {
2 super::*,
3 crate::http_server::auth::{ApiAuth, NavbarAuth},
4 axum::extract::RawQuery,
5};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct UserSummary {
9 pub address: Address<NetworkUnchecked>,
10 pub worker_count: usize,
11 pub session_count: usize,
12 pub hashrate: HashRate,
13 pub delivered_hash_days: HashDays,
14 pub best_share: Option<Difficulty>,
15 pub last_share: Option<u64>,
16}
17
18impl UserSummary {
19 pub(crate) fn from_user(user: &User, now: Instant) -> Self {
20 let stats = user.snapshot();
21 Self {
22 address: user.address.as_unchecked().clone(),
23 worker_count: user.worker_count(),
24 session_count: user.session_count(),
25 hashrate: stats.hashrate_1m(now),
26 delivered_hash_days: stats.delivered_work().to_hash_days(),
27 best_share: stats.best_share,
28 last_share: stats.last_share_epoch_secs(now),
29 }
30 }
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct UserDetail {
35 pub address: Address<NetworkUnchecked>,
36 pub session_count: usize,
37 pub authorized_at: u64,
38 pub workers: Vec<WorkerDetail>,
39 pub sessions: Vec<SessionDetail>,
40 pub stats: MiningStats,
41}
42
43impl UserDetail {
44 pub(crate) fn from_user(user: &User, now: Instant) -> Self {
45 let mut workers = Vec::new();
46 let mut sessions = Vec::new();
47
48 for worker in user.workers() {
49 sessions.extend(
50 worker
51 .sessions()
52 .map(|s| SessionDetail::from_session(&s, now)),
53 );
54 workers.push(WorkerDetail::from_worker(&worker, now));
55 }
56
57 let user_stats = user.snapshot();
58
59 Self {
60 address: user.address.as_unchecked().clone(),
61 session_count: user.session_count(),
62 authorized_at: user.authorized,
63 workers,
64 sessions,
65 stats: MiningStats::from_stats(&user_stats, now),
66 }
67 }
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct WorkerDetail {
72 pub name: String,
73 pub session_count: usize,
74 pub stats: MiningStats,
75}
76
77impl WorkerDetail {
78 pub(crate) fn from_worker(worker: &Worker, now: Instant) -> Self {
79 let stats = worker.snapshot();
80 Self {
81 name: worker.workername().to_string(),
82 session_count: worker.session_count(),
83 stats: MiningStats::from_stats(&stats, now),
84 }
85 }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct SessionDetail {
90 pub id: SessionId,
91 pub order_id: u32,
92 pub address: Address<NetworkUnchecked>,
93 pub worker_name: String,
94 pub username: String,
95 pub enonce1: Extranonce,
96 pub version_mask: Option<Version>,
97 pub remote_address: IpAddr,
98 pub stats: MiningStats,
99}
100
101impl SessionDetail {
102 pub(crate) fn from_session(session: &Session, now: Instant) -> Self {
103 let stats = session.snapshot();
104 Self {
105 id: session.id(),
106 order_id: session.id().order_id(),
107 address: session.address().as_unchecked().clone(),
108 worker_name: session.workername().to_string(),
109 username: session.username().to_string(),
110 enonce1: session.enonce1().clone(),
111 version_mask: session.version_mask(),
112 remote_address: session.socket_addr().ip(),
113 stats: MiningStats::from_stats(&stats, now),
114 }
115 }
116}
117
118#[derive(Copy, Clone)]
119pub(crate) enum Service {
120 Pool,
121 Proxy,
122 Router,
123}
124
125impl Service {
126 fn api_base(self) -> &'static str {
127 match self {
128 Self::Pool => "/api/pool",
129 Self::Proxy => "/api/proxy",
130 Self::Router => "/api/router",
131 }
132 }
133
134 fn users_title(self) -> &'static str {
135 match self {
136 Self::Pool => "Pool | Users",
137 Self::Proxy => "Proxy | Users",
138 Self::Router => "Router | Users",
139 }
140 }
141
142 fn user_title(self) -> &'static str {
143 match self {
144 Self::Pool => "Pool | User",
145 Self::Proxy => "Proxy | User",
146 Self::Router => "Router | User",
147 }
148 }
149}
150
151#[derive(Clone)]
152struct UsersState {
153 service: Service,
154 metatron: Arc<Metatron>,
155}
156
157pub(crate) fn routes(service: Service, metatron: Arc<Metatron>) -> axum::Router {
158 axum::Router::new()
159 .route("/users", get(users_page))
160 .route("/user/{address}", get(user_page))
161 .route(&format!("{}/users", service.api_base()), get(users))
162 .route(
163 &format!("{}/users/count", service.api_base()),
164 get(count_users),
165 )
166 .route(
167 &format!("{}/user/{{address}}", service.api_base()),
168 get(user),
169 )
170 .with_state(UsersState { service, metatron })
171}
172
173async fn users_page(
174 State(state): State<UsersState>,
175 Extension(chain): Extension<Chain>,
176 auth: NavbarAuth,
177) -> Response {
178 render_page(
179 UsersHtml {
180 title: state.service.users_title(),
181 api_base: state.service.api_base(),
182 },
183 chain,
184 auth,
185 )
186}
187
188async fn user_page(
189 State(state): State<UsersState>,
190 Extension(chain): Extension<Chain>,
191 auth: NavbarAuth,
192) -> Response {
193 render_page(
194 UserHtml {
195 title: state.service.user_title(),
196 api_base: state.service.api_base(),
197 },
198 chain,
199 auth,
200 )
201}
202
203#[derive(Copy, Clone, Default, PartialEq, Eq)]
204enum UserSort {
205 #[default]
206 Hashrate,
207 Address,
208}
209
210#[derive(Default)]
211struct UsersQuery {
212 search: Option<String>,
213 sort: UserSort,
214 cursor: Option<String>,
215 limit: Option<usize>,
216}
217
218impl UsersQuery {
219 fn parse(raw: Option<&str>) -> ServerResult<Self> {
220 let mut query = Self::default();
221
222 for (key, value) in parse_query_pairs(raw)? {
223 match key.as_str() {
224 "search" if !value.trim().is_empty() => {
225 query.search = Some(value.trim().to_lowercase());
226 }
227 "search" => query.search = None,
228 "sort" if !value.trim().is_empty() => {
229 query.sort = match value.as_str() {
230 "hashrate" => UserSort::Hashrate,
231 "address" => UserSort::Address,
232 _ => {
233 return Err(ServerError::BadRequest(format!(
234 "invalid user sort `{value}`"
235 )));
236 }
237 };
238 }
239 "sort" => query.sort = UserSort::Hashrate,
240 "cursor" if !value.trim().is_empty() => {
241 let address = value.parse::<Address<NetworkUnchecked>>().map_err(|err| {
242 ServerError::BadRequest(format!("invalid address cursor `{value}`: {err}"))
243 })?;
244 query.cursor = Some(address.assume_checked().to_string());
245 }
246 "cursor" => query.cursor = None,
247 "limit" if !value.trim().is_empty() => {
248 query.limit = Some(parse_usize_query_param("limit", &value)?);
249 }
250 "limit" => query.limit = None,
251 _ => {}
252 }
253 }
254
255 if query.sort != UserSort::Address && query.cursor.is_some() {
256 return Err(ServerError::BadRequest(
257 "address cursor requires sort=address".into(),
258 ));
259 }
260
261 Ok(query)
262 }
263
264 fn matches(&self, user: &User) -> bool {
265 if let Some(search) = &self.search
266 && !user_matches_search(user, search)
267 {
268 return false;
269 }
270
271 true
272 }
273}
274
275fn user_matches_search(user: &User, search: &str) -> bool {
276 user.address.to_string().to_lowercase().contains(search)
277 || user
278 .workers
279 .iter()
280 .any(|worker| worker.key().to_lowercase().contains(search))
281}
282
283async fn users(
284 _: ApiAuth,
285 State(state): State<UsersState>,
286 RawQuery(raw_query): RawQuery,
287) -> ServerResult<Response> {
288 let now = Instant::now();
289 let query = UsersQuery::parse(raw_query.as_deref())?;
290 let limit = effective_limit(query.limit)?;
291
292 let mut users = Vec::new();
293
294 for entry in state.metatron.users().iter() {
295 let user = entry.value();
296
297 if query.matches(user) {
298 users.push(UserSummary::from_user(user, now));
299 }
300 }
301
302 let address = |user: &UserSummary| user.address.clone().assume_checked().to_string();
303
304 match query.sort {
305 UserSort::Hashrate => {
306 users.sort_by_cached_key(|user| (Reverse(user.hashrate), address(user)));
307 }
308 UserSort::Address => {
309 users.sort_by_cached_key(address);
310
311 if let Some(cursor) = &query.cursor {
312 let start = users.partition_point(|user| address(user).as_str() <= cursor.as_str());
313 users.drain(..start);
314 }
315 }
316 }
317
318 let has_more = users.len() > limit;
319 users.truncate(limit);
320
321 let next_cursor = (query.sort == UserSort::Address && has_more)
322 .then(|| users.last().map(address))
323 .flatten();
324
325 Ok(page_response(users, limit, next_cursor))
326}
327
328async fn count_users(
329 _: ApiAuth,
330 State(state): State<UsersState>,
331 RawQuery(raw_query): RawQuery,
332) -> ServerResult<Response> {
333 let query = UsersQuery::parse(raw_query.as_deref())?;
334
335 if query.cursor.is_some() {
336 return Err(ServerError::BadRequest(
337 "cursor is not supported for user counts".into(),
338 ));
339 }
340
341 let count = state
342 .metatron
343 .users()
344 .iter()
345 .filter(|entry| query.matches(entry.value()))
346 .count() as u64;
347
348 Ok(Json(CountResponse { count }).into_response())
349}
350
351async fn user(
352 _: ApiAuth,
353 State(state): State<UsersState>,
354 Path(address): Path<Address<NetworkUnchecked>>,
355) -> ServerResult<Response> {
356 let address = address.assume_checked();
357
358 let user = state
359 .metatron
360 .users()
361 .get(&address)
362 .ok_or_not_found(|| format!("User {address}"))?;
363
364 Ok(Json(UserDetail::from_user(&user, Instant::now())).into_response())
365}
366
367#[cfg(test)]
368mod tests {
369 use {
370 super::*,
371 axum::{body::to_bytes, extract::State},
372 };
373
374 fn address(value: &str) -> Address {
375 value
376 .parse::<Address<NetworkUnchecked>>()
377 .unwrap()
378 .assume_checked()
379 }
380
381 async fn request_page(state: &UsersState, query: &str) -> Response {
382 users(
383 ApiAuth,
384 State(state.clone()),
385 RawQuery(Some(query.to_string())),
386 )
387 .await
388 .ok()
389 .expect("users handler failed")
390 }
391
392 async fn decode_page(response: Response) -> Vec<UserSummary> {
393 let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
394 serde_json::from_slice(&body).unwrap()
395 }
396
397 async fn page(state: &UsersState, query: &str) -> Vec<UserSummary> {
398 decode_page(request_page(state, query).await).await
399 }
400
401 async fn count(state: &UsersState, query: &str) -> u64 {
402 let response = count_users(
403 ApiAuth,
404 State(state.clone()),
405 RawQuery(Some(query.to_string())),
406 )
407 .await
408 .ok()
409 .expect("count_users handler failed");
410 let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
411 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
412
413 value["count"].as_u64().unwrap()
414 }
415
416 fn addresses(users: &[UserSummary]) -> Vec<String> {
417 users
418 .iter()
419 .map(|user| user.address.clone().assume_checked().to_string())
420 .collect()
421 }
422
423 #[test]
424 fn address_cursor_requires_address_sort() {
425 assert!(
426 UsersQuery::parse(Some("cursor=tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc")).is_err()
427 );
428 assert!(
429 UsersQuery::parse(Some(
430 "sort=address&cursor=tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc"
431 ))
432 .is_ok()
433 );
434 assert!(UsersQuery::parse(Some("sort=unknown")).is_err());
435 }
436
437 #[tokio::test]
438 async fn address_sort_paginates_all_users() {
439 let (metatron, _directory) = Metatron::test();
440 let metatron = Arc::new(metatron);
441
442 let expected = [
443 "tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc",
444 "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx",
445 "tb1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqaqh7jw",
446 ]
447 .map(address);
448
449 for address in &expected {
450 metatron
451 .users()
452 .insert(address.clone(), Arc::new(User::new(address.clone())));
453 }
454
455 let mut expected = expected.iter().map(ToString::to_string).collect::<Vec<_>>();
456 expected.sort();
457
458 let state = UsersState {
459 service: Service::Router,
460 metatron,
461 };
462
463 let first_response = request_page(&state, "sort=address&limit=2").await;
464 assert_eq!(first_response.headers()["x-limit"], "2");
465 assert_eq!(first_response.headers()["x-next-cursor"], expected[1]);
466 let first = decode_page(first_response).await;
467 assert_eq!(addresses(&first), expected[..2]);
468
469 let second_response = request_page(
470 &state,
471 &format!("sort=address&limit=2&cursor={}", expected[1]),
472 )
473 .await;
474 assert!(!second_response.headers().contains_key("x-next-cursor"));
475 let second = decode_page(second_response).await;
476 assert_eq!(addresses(&second), expected[2..]);
477
478 let after_last = page(
479 &state,
480 &format!("sort=address&limit=2&cursor={}", expected[2]),
481 )
482 .await;
483 assert!(after_last.is_empty());
484
485 let narrowed_address = address("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx").to_string();
486
487 let narrowed = page(&state, "search=w508&sort=address&limit=2").await;
488 assert_eq!(addresses(&narrowed), vec![narrowed_address.clone()]);
489
490 let narrowed_after = page(
491 &state,
492 &format!("search=w508&sort=address&cursor={narrowed_address}"),
493 )
494 .await;
495 assert!(narrowed_after.is_empty());
496
497 let top_by_hashrate = request_page(&state, "limit=2").await;
498 assert!(!top_by_hashrate.headers().contains_key("x-next-cursor"));
499 assert_eq!(decode_page(top_by_hashrate).await.len(), 2);
500
501 let clamped = request_page(&state, "limit=999").await;
502 assert_eq!(clamped.headers()["x-limit"], "500");
503
504 assert_eq!(count(&state, "").await, 3);
505 assert_eq!(count(&state, "search=w508").await, 1);
506
507 let count_with_cursor = count_users(
508 ApiAuth,
509 State(state.clone()),
510 RawQuery(Some(format!("sort=address&cursor={}", expected[0]))),
511 )
512 .await;
513 assert!(count_with_cursor.is_err());
514 }
515}