Documentation
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
503
504
505
506
507
508
509
510
511
512
513
514
515
use {
    super::*,
    crate::http_server::auth::{ApiAuth, NavbarAuth},
    axum::extract::RawQuery,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserSummary {
    pub address: Address<NetworkUnchecked>,
    pub worker_count: usize,
    pub session_count: usize,
    pub hashrate: HashRate,
    pub delivered_hash_days: HashDays,
    pub best_share: Option<Difficulty>,
    pub last_share: Option<u64>,
}

impl UserSummary {
    pub(crate) fn from_user(user: &User, now: Instant) -> Self {
        let stats = user.snapshot();
        Self {
            address: user.address.as_unchecked().clone(),
            worker_count: user.worker_count(),
            session_count: user.session_count(),
            hashrate: stats.hashrate_1m(now),
            delivered_hash_days: stats.delivered_work().to_hash_days(),
            best_share: stats.best_share,
            last_share: stats.last_share_epoch_secs(now),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserDetail {
    pub address: Address<NetworkUnchecked>,
    pub session_count: usize,
    pub authorized_at: u64,
    pub workers: Vec<WorkerDetail>,
    pub sessions: Vec<SessionDetail>,
    pub stats: MiningStats,
}

impl UserDetail {
    pub(crate) fn from_user(user: &User, now: Instant) -> Self {
        let mut workers = Vec::new();
        let mut sessions = Vec::new();

        for worker in user.workers() {
            sessions.extend(
                worker
                    .sessions()
                    .map(|s| SessionDetail::from_session(&s, now)),
            );
            workers.push(WorkerDetail::from_worker(&worker, now));
        }

        let user_stats = user.snapshot();

        Self {
            address: user.address.as_unchecked().clone(),
            session_count: user.session_count(),
            authorized_at: user.authorized,
            workers,
            sessions,
            stats: MiningStats::from_stats(&user_stats, now),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerDetail {
    pub name: String,
    pub session_count: usize,
    pub stats: MiningStats,
}

impl WorkerDetail {
    pub(crate) fn from_worker(worker: &Worker, now: Instant) -> Self {
        let stats = worker.snapshot();
        Self {
            name: worker.workername().to_string(),
            session_count: worker.session_count(),
            stats: MiningStats::from_stats(&stats, now),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionDetail {
    pub id: SessionId,
    pub order_id: u32,
    pub address: Address<NetworkUnchecked>,
    pub worker_name: String,
    pub username: String,
    pub enonce1: Extranonce,
    pub version_mask: Option<Version>,
    pub remote_address: IpAddr,
    pub stats: MiningStats,
}

impl SessionDetail {
    pub(crate) fn from_session(session: &Session, now: Instant) -> Self {
        let stats = session.snapshot();
        Self {
            id: session.id(),
            order_id: session.id().order_id(),
            address: session.address().as_unchecked().clone(),
            worker_name: session.workername().to_string(),
            username: session.username().to_string(),
            enonce1: session.enonce1().clone(),
            version_mask: session.version_mask(),
            remote_address: session.socket_addr().ip(),
            stats: MiningStats::from_stats(&stats, now),
        }
    }
}

#[derive(Copy, Clone)]
pub(crate) enum Service {
    Pool,
    Proxy,
    Router,
}

impl Service {
    fn api_base(self) -> &'static str {
        match self {
            Self::Pool => "/api/pool",
            Self::Proxy => "/api/proxy",
            Self::Router => "/api/router",
        }
    }

    fn users_title(self) -> &'static str {
        match self {
            Self::Pool => "Pool | Users",
            Self::Proxy => "Proxy | Users",
            Self::Router => "Router | Users",
        }
    }

    fn user_title(self) -> &'static str {
        match self {
            Self::Pool => "Pool | User",
            Self::Proxy => "Proxy | User",
            Self::Router => "Router | User",
        }
    }
}

#[derive(Clone)]
struct UsersState {
    service: Service,
    metatron: Arc<Metatron>,
}

pub(crate) fn routes(service: Service, metatron: Arc<Metatron>) -> axum::Router {
    axum::Router::new()
        .route("/users", get(users_page))
        .route("/user/{address}", get(user_page))
        .route(&format!("{}/users", service.api_base()), get(users))
        .route(
            &format!("{}/users/count", service.api_base()),
            get(count_users),
        )
        .route(
            &format!("{}/user/{{address}}", service.api_base()),
            get(user),
        )
        .with_state(UsersState { service, metatron })
}

async fn users_page(
    State(state): State<UsersState>,
    Extension(chain): Extension<Chain>,
    auth: NavbarAuth,
) -> Response {
    render_page(
        UsersHtml {
            title: state.service.users_title(),
            api_base: state.service.api_base(),
        },
        chain,
        auth,
    )
}

async fn user_page(
    State(state): State<UsersState>,
    Extension(chain): Extension<Chain>,
    auth: NavbarAuth,
) -> Response {
    render_page(
        UserHtml {
            title: state.service.user_title(),
            api_base: state.service.api_base(),
        },
        chain,
        auth,
    )
}

#[derive(Copy, Clone, Default, PartialEq, Eq)]
enum UserSort {
    #[default]
    Hashrate,
    Address,
}

#[derive(Default)]
struct UsersQuery {
    search: Option<String>,
    sort: UserSort,
    cursor: Option<String>,
    limit: Option<usize>,
}

impl UsersQuery {
    fn parse(raw: Option<&str>) -> ServerResult<Self> {
        let mut query = Self::default();

        for (key, value) in parse_query_pairs(raw)? {
            match key.as_str() {
                "search" if !value.trim().is_empty() => {
                    query.search = Some(value.trim().to_lowercase());
                }
                "search" => query.search = None,
                "sort" if !value.trim().is_empty() => {
                    query.sort = match value.as_str() {
                        "hashrate" => UserSort::Hashrate,
                        "address" => UserSort::Address,
                        _ => {
                            return Err(ServerError::BadRequest(format!(
                                "invalid user sort `{value}`"
                            )));
                        }
                    };
                }
                "sort" => query.sort = UserSort::Hashrate,
                "cursor" if !value.trim().is_empty() => {
                    let address = value.parse::<Address<NetworkUnchecked>>().map_err(|err| {
                        ServerError::BadRequest(format!("invalid address cursor `{value}`: {err}"))
                    })?;
                    query.cursor = Some(address.assume_checked().to_string());
                }
                "cursor" => query.cursor = None,
                "limit" if !value.trim().is_empty() => {
                    query.limit = Some(parse_usize_query_param("limit", &value)?);
                }
                "limit" => query.limit = None,
                _ => {}
            }
        }

        if query.sort != UserSort::Address && query.cursor.is_some() {
            return Err(ServerError::BadRequest(
                "address cursor requires sort=address".into(),
            ));
        }

        Ok(query)
    }

    fn matches(&self, user: &User) -> bool {
        if let Some(search) = &self.search
            && !user_matches_search(user, search)
        {
            return false;
        }

        true
    }
}

fn user_matches_search(user: &User, search: &str) -> bool {
    user.address.to_string().to_lowercase().contains(search)
        || user
            .workers
            .iter()
            .any(|worker| worker.key().to_lowercase().contains(search))
}

async fn users(
    _: ApiAuth,
    State(state): State<UsersState>,
    RawQuery(raw_query): RawQuery,
) -> ServerResult<Response> {
    let now = Instant::now();
    let query = UsersQuery::parse(raw_query.as_deref())?;
    let limit = effective_limit(query.limit)?;

    let mut users = Vec::new();

    for entry in state.metatron.users().iter() {
        let user = entry.value();

        if query.matches(user) {
            users.push(UserSummary::from_user(user, now));
        }
    }

    let address = |user: &UserSummary| user.address.clone().assume_checked().to_string();

    match query.sort {
        UserSort::Hashrate => {
            users.sort_by_cached_key(|user| (Reverse(user.hashrate), address(user)));
        }
        UserSort::Address => {
            users.sort_by_cached_key(address);

            if let Some(cursor) = &query.cursor {
                let start = users.partition_point(|user| address(user).as_str() <= cursor.as_str());
                users.drain(..start);
            }
        }
    }

    let has_more = users.len() > limit;
    users.truncate(limit);

    let next_cursor = (query.sort == UserSort::Address && has_more)
        .then(|| users.last().map(address))
        .flatten();

    Ok(page_response(users, limit, next_cursor))
}

async fn count_users(
    _: ApiAuth,
    State(state): State<UsersState>,
    RawQuery(raw_query): RawQuery,
) -> ServerResult<Response> {
    let query = UsersQuery::parse(raw_query.as_deref())?;

    if query.cursor.is_some() {
        return Err(ServerError::BadRequest(
            "cursor is not supported for user counts".into(),
        ));
    }

    let count = state
        .metatron
        .users()
        .iter()
        .filter(|entry| query.matches(entry.value()))
        .count() as u64;

    Ok(Json(CountResponse { count }).into_response())
}

async fn user(
    _: ApiAuth,
    State(state): State<UsersState>,
    Path(address): Path<Address<NetworkUnchecked>>,
) -> ServerResult<Response> {
    let address = address.assume_checked();

    let user = state
        .metatron
        .users()
        .get(&address)
        .ok_or_not_found(|| format!("User {address}"))?;

    Ok(Json(UserDetail::from_user(&user, Instant::now())).into_response())
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        axum::{body::to_bytes, extract::State},
    };

    fn address(value: &str) -> Address {
        value
            .parse::<Address<NetworkUnchecked>>()
            .unwrap()
            .assume_checked()
    }

    async fn request_page(state: &UsersState, query: &str) -> Response {
        users(
            ApiAuth,
            State(state.clone()),
            RawQuery(Some(query.to_string())),
        )
        .await
        .ok()
        .expect("users handler failed")
    }

    async fn decode_page(response: Response) -> Vec<UserSummary> {
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        serde_json::from_slice(&body).unwrap()
    }

    async fn page(state: &UsersState, query: &str) -> Vec<UserSummary> {
        decode_page(request_page(state, query).await).await
    }

    async fn count(state: &UsersState, query: &str) -> u64 {
        let response = count_users(
            ApiAuth,
            State(state.clone()),
            RawQuery(Some(query.to_string())),
        )
        .await
        .ok()
        .expect("count_users handler failed");
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();

        value["count"].as_u64().unwrap()
    }

    fn addresses(users: &[UserSummary]) -> Vec<String> {
        users
            .iter()
            .map(|user| user.address.clone().assume_checked().to_string())
            .collect()
    }

    #[test]
    fn address_cursor_requires_address_sort() {
        assert!(
            UsersQuery::parse(Some("cursor=tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc")).is_err()
        );
        assert!(
            UsersQuery::parse(Some(
                "sort=address&cursor=tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc"
            ))
            .is_ok()
        );
        assert!(UsersQuery::parse(Some("sort=unknown")).is_err());
    }

    #[tokio::test]
    async fn address_sort_paginates_all_users() {
        let (metatron, _directory) = Metatron::test();
        let metatron = Arc::new(metatron);

        let expected = [
            "tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc",
            "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx",
            "tb1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqaqh7jw",
        ]
        .map(address);

        for address in &expected {
            metatron
                .users()
                .insert(address.clone(), Arc::new(User::new(address.clone())));
        }

        let mut expected = expected.iter().map(ToString::to_string).collect::<Vec<_>>();
        expected.sort();

        let state = UsersState {
            service: Service::Router,
            metatron,
        };

        let first_response = request_page(&state, "sort=address&limit=2").await;
        assert_eq!(first_response.headers()["x-limit"], "2");
        assert_eq!(first_response.headers()["x-next-cursor"], expected[1]);
        let first = decode_page(first_response).await;
        assert_eq!(addresses(&first), expected[..2]);

        let second_response = request_page(
            &state,
            &format!("sort=address&limit=2&cursor={}", expected[1]),
        )
        .await;
        assert!(!second_response.headers().contains_key("x-next-cursor"));
        let second = decode_page(second_response).await;
        assert_eq!(addresses(&second), expected[2..]);

        let after_last = page(
            &state,
            &format!("sort=address&limit=2&cursor={}", expected[2]),
        )
        .await;
        assert!(after_last.is_empty());

        let narrowed_address = address("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx").to_string();

        let narrowed = page(&state, "search=w508&sort=address&limit=2").await;
        assert_eq!(addresses(&narrowed), vec![narrowed_address.clone()]);

        let narrowed_after = page(
            &state,
            &format!("search=w508&sort=address&cursor={narrowed_address}"),
        )
        .await;
        assert!(narrowed_after.is_empty());

        let top_by_hashrate = request_page(&state, "limit=2").await;
        assert!(!top_by_hashrate.headers().contains_key("x-next-cursor"));
        assert_eq!(decode_page(top_by_hashrate).await.len(), 2);

        let clamped = request_page(&state, "limit=999").await;
        assert_eq!(clamped.headers()["x-limit"], "500");

        assert_eq!(count(&state, "").await, 3);
        assert_eq!(count(&state, "search=w508").await, 1);

        let count_with_cursor = count_users(
            ApiAuth,
            State(state.clone()),
            RawQuery(Some(format!("sort=address&cursor={}", expected[0]))),
        )
        .await;
        assert!(count_with_cursor.is_err());
    }
}