stratum-apps 0.7.0

Complete Stratum V2 application development kit - all utilities in one crate
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
//! Sv2 client monitoring types
//!
//! These types are for monitoring **Sv2 clients** (downstream connections).
//! Each client can have multiple channels opened with the app.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[cfg(feature = "asic-rs-telemetry")]
use std::net::IpAddr;
use utoipa::ToSchema;

#[cfg(feature = "asic-rs-telemetry")]
use super::miner_telemetry::{MinerTelemetry, MinerTelemetryStatus};

/// Kind of SV2 downstream client connected to this node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum Sv2ClientKind {
    /// A mining device connected directly as an SV2 downstream client.
    Miner,
    /// A Translator Proxy connected as the SV2 client for one or more SV1 miners.
    TranslatorProxy,
    /// The downstream client type could not be inferred from SetupConnection metadata.
    Unknown,
}

impl Default for Sv2ClientKind {
    fn default() -> Self {
        Self::Unknown
    }
}

impl Sv2ClientKind {
    /// Infer the downstream client kind from SetupConnection vendor and hardware version fields.
    pub fn from_setup_connection(vendor: &str, hardware_version: &str) -> Self {
        if vendor == "SRI" && hardware_version == "Translator Proxy" {
            Self::TranslatorProxy
        } else if vendor.is_empty() && hardware_version.is_empty() {
            Self::Unknown
        } else {
            Self::Miner
        }
    }
}

/// Information about an extended channel
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ExtendedChannelInfo {
    pub channel_id: u32,
    pub user_identity: String,
    pub nominal_hashrate: f32,
    pub stable_hashrate: bool,
    pub target_hex: String,
    pub requested_max_target_hex: String,
    pub extranonce_prefix_hex: String,
    pub full_extranonce_size: usize,
    pub rollable_extranonce_size: u16,
    pub expected_shares_per_minute: f32,
    pub shares_accepted: u32,
    pub shares_rejected: u32,
    pub shares_rejected_by_reason: HashMap<String, u32>,
    pub share_work_sum: f64,
    pub last_share_sequence_number: u32,
    pub best_diff: f64,
    pub last_batch_accepted: u32,
    pub last_batch_work_sum: u64,
    pub share_batch_size: usize,
    pub blocks_found: u32,
}

/// Information about a standard channel
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct StandardChannelInfo {
    pub channel_id: u32,
    pub user_identity: String,
    pub nominal_hashrate: f32,
    pub stable_hashrate: bool,
    pub target_hex: String,
    pub requested_max_target_hex: String,
    pub extranonce_prefix_hex: String,
    pub expected_shares_per_minute: f32,
    pub shares_accepted: u32,
    pub shares_rejected: u32,
    pub shares_rejected_by_reason: HashMap<String, u32>,
    pub share_work_sum: f64,
    pub last_share_sequence_number: u32,
    pub best_diff: f64,
    pub last_batch_accepted: u32,
    pub last_batch_work_sum: u64,
    pub share_batch_size: usize,
    pub blocks_found: u32,
}

/// Full information about a single Sv2 client including all channels
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Sv2ClientInfo {
    pub client_id: usize,
    /// Classification inferred from the client's SV2 SetupConnection metadata.
    pub client_kind: Sv2ClientKind,
    pub extended_channels: Vec<ExtendedChannelInfo>,
    pub standard_channels: Vec<StandardChannelInfo>,
    #[cfg(feature = "asic-rs-telemetry")]
    /// Miner management IP used for matched telemetry, if discovery found one.
    #[schema(value_type = Option<String>)]
    pub management_ip: Option<IpAddr>,
    #[cfg(feature = "asic-rs-telemetry")]
    /// Latest telemetry fetched from the matched miner management interface.
    pub miner_telemetry: Option<MinerTelemetry>,
    #[cfg(feature = "asic-rs-telemetry")]
    /// Current discovery and fetch status for miner telemetry matching.
    pub miner_telemetry_status: Option<MinerTelemetryStatus>,
}

impl Sv2ClientInfo {
    pub fn new(
        client_id: usize,
        extended_channels: Vec<ExtendedChannelInfo>,
        standard_channels: Vec<StandardChannelInfo>,
    ) -> Self {
        Self {
            client_id,
            client_kind: Sv2ClientKind::Unknown,
            extended_channels,
            standard_channels,
            #[cfg(feature = "asic-rs-telemetry")]
            management_ip: None,
            #[cfg(feature = "asic-rs-telemetry")]
            miner_telemetry: None,
            #[cfg(feature = "asic-rs-telemetry")]
            miner_telemetry_status: None,
        }
    }

    /// Get total number of channels for this client
    pub fn total_channels(&self) -> usize {
        self.extended_channels.len() + self.standard_channels.len()
    }

    /// Get total hashrate for this client
    pub fn total_hashrate(&self) -> f32 {
        self.extended_channels
            .iter()
            .map(|c| c.nominal_hashrate)
            .sum::<f32>()
            + self
                .standard_channels
                .iter()
                .map(|c| c.nominal_hashrate)
                .sum::<f32>()
    }

    /// Convert to metadata (without channel arrays)
    pub fn to_metadata(&self) -> Sv2ClientMetadata {
        Sv2ClientMetadata {
            client_id: self.client_id,
            client_kind: self.client_kind,
            extended_channels_count: self.extended_channels.len(),
            standard_channels_count: self.standard_channels.len(),
            total_hashrate: self.total_hashrate(),
            #[cfg(feature = "asic-rs-telemetry")]
            management_ip: self.management_ip,
            #[cfg(feature = "asic-rs-telemetry")]
            miner_telemetry: self.miner_telemetry.clone(),
            #[cfg(feature = "asic-rs-telemetry")]
            miner_telemetry_status: self.miner_telemetry_status,
        }
    }
}

/// Sv2 client metadata without channel arrays (for listings)
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Sv2ClientMetadata {
    pub client_id: usize,
    /// Classification inferred from the client's SV2 SetupConnection metadata.
    pub client_kind: Sv2ClientKind,
    pub extended_channels_count: usize,
    pub standard_channels_count: usize,
    pub total_hashrate: f32,
    #[cfg(feature = "asic-rs-telemetry")]
    /// Miner management IP used for matched telemetry, if discovery found one.
    #[schema(value_type = Option<String>)]
    pub management_ip: Option<IpAddr>,
    #[cfg(feature = "asic-rs-telemetry")]
    /// Latest telemetry fetched from the matched miner management interface.
    pub miner_telemetry: Option<MinerTelemetry>,
    #[cfg(feature = "asic-rs-telemetry")]
    /// Current discovery and fetch status for miner telemetry matching.
    pub miner_telemetry_status: Option<MinerTelemetryStatus>,
}

/// Aggregate information about all Sv2 clients
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Sv2ClientsSummary {
    pub total_clients: usize,
    pub total_channels: usize,
    pub extended_channels: usize,
    pub standard_channels: usize,
    pub total_hashrate: f32,
}

/// Trait for monitoring Sv2 clients (downstream connections)
pub trait Sv2ClientsMonitoring: Send + Sync {
    /// Get all Sv2 clients with their channels
    fn get_sv2_clients(&self) -> Vec<Sv2ClientInfo>;

    /// Get a single Sv2 client by client_id
    ///
    /// Default implementation does O(n) scan. Override for O(1) lookup
    /// if your implementation uses a HashMap internally.
    fn get_sv2_client_by_id(&self, client_id: usize) -> Option<Sv2ClientInfo> {
        self.get_sv2_clients()
            .into_iter()
            .find(|c| c.client_id == client_id)
    }

    /// Get summary of all Sv2 clients
    fn get_sv2_clients_summary(&self) -> Sv2ClientsSummary {
        let clients = self.get_sv2_clients();
        let extended: usize = clients.iter().map(|c| c.extended_channels.len()).sum();
        let standard: usize = clients.iter().map(|c| c.standard_channels.len()).sum();

        Sv2ClientsSummary {
            total_clients: clients.len(),
            total_channels: extended + standard,
            extended_channels: extended,
            standard_channels: standard,
            total_hashrate: clients.iter().map(|c| c.total_hashrate()).sum(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use stratum_core::mining_sv2::ERROR_CODE_SUBMIT_SHARES_DUPLICATE_SHARE;

    // ── helpers ──────────────────────────────────────────────────────

    fn create_extended_channel_info(channel_id: u32, hashrate: f32) -> ExtendedChannelInfo {
        ExtendedChannelInfo {
            channel_id,
            user_identity: format!("user-ext-{}", channel_id),
            nominal_hashrate: hashrate,
            stable_hashrate: false,
            target_hex: "00ff".into(),
            requested_max_target_hex: "00ff".into(),
            extranonce_prefix_hex: "aa".into(),
            full_extranonce_size: 16,
            rollable_extranonce_size: 4,
            expected_shares_per_minute: 1.0,
            shares_accepted: 10,
            shares_rejected: 0,
            shares_rejected_by_reason: HashMap::new(),
            share_work_sum: 100.0,
            last_share_sequence_number: 5,
            best_diff: 50.0,
            last_batch_accepted: 3,
            last_batch_work_sum: 30,
            share_batch_size: 10,
            blocks_found: 0,
        }
    }

    fn create_standard_channel_info(channel_id: u32, hashrate: f32) -> StandardChannelInfo {
        StandardChannelInfo {
            channel_id,
            user_identity: format!("user-std-{}", channel_id),
            nominal_hashrate: hashrate,
            stable_hashrate: false,
            target_hex: "00ff".into(),
            requested_max_target_hex: "00ff".into(),
            extranonce_prefix_hex: "bb".into(),
            expected_shares_per_minute: 2.0,
            shares_accepted: 20,
            shares_rejected: 1,
            shares_rejected_by_reason: HashMap::from([(
                ERROR_CODE_SUBMIT_SHARES_DUPLICATE_SHARE.to_string(),
                1,
            )]),
            share_work_sum: 200.0,
            last_share_sequence_number: 8,
            best_diff: 80.0,
            last_batch_accepted: 5,
            last_batch_work_sum: 50,
            share_batch_size: 20,
            blocks_found: 0,
        }
    }

    fn create_sv2_client_info(
        id: usize,
        ext: Vec<ExtendedChannelInfo>,
        std: Vec<StandardChannelInfo>,
    ) -> Sv2ClientInfo {
        Sv2ClientInfo {
            client_id: id,
            client_kind: Sv2ClientKind::Miner,
            extended_channels: ext,
            standard_channels: std,
            #[cfg(feature = "asic-rs-telemetry")]
            management_ip: None,
            #[cfg(feature = "asic-rs-telemetry")]
            miner_telemetry: None,
            #[cfg(feature = "asic-rs-telemetry")]
            miner_telemetry_status: None,
        }
    }

    // ── ClientInfo unit tests ───────────────────────────────────────

    #[test]
    fn client_info_empty_channels() {
        let client = create_sv2_client_info(1, vec![], vec![]);
        assert_eq!(client.total_channels(), 0);
        assert_eq!(client.total_hashrate(), 0.0);
    }

    #[test]
    fn client_info_aggregates_both_channel_types() {
        let client = create_sv2_client_info(
            1,
            vec![
                create_extended_channel_info(1, 100.0),
                create_extended_channel_info(2, 200.0),
            ],
            vec![create_standard_channel_info(3, 50.0)],
        );
        assert_eq!(client.total_channels(), 3);
        assert_eq!(client.total_hashrate(), 350.0);
    }

    #[test]
    fn client_info_to_metadata() {
        let client = create_sv2_client_info(
            42,
            vec![create_extended_channel_info(1, 100.0)],
            vec![
                create_standard_channel_info(2, 50.0),
                create_standard_channel_info(3, 75.0),
            ],
        );
        let meta = client.to_metadata();

        assert_eq!(meta.client_id, 42);
        assert_eq!(meta.extended_channels_count, 1);
        assert_eq!(meta.standard_channels_count, 2);
        assert_eq!(meta.total_hashrate, 225.0);
        assert_eq!(meta.client_kind, Sv2ClientKind::Miner);
        #[cfg(feature = "asic-rs-telemetry")]
        assert!(meta.miner_telemetry.is_none());
    }

    #[test]
    fn client_kind_from_setup_connection_classifies_known_clients() {
        assert_eq!(
            Sv2ClientKind::from_setup_connection("SRI", "Translator Proxy"),
            Sv2ClientKind::TranslatorProxy
        );
        assert_eq!(
            Sv2ClientKind::from_setup_connection("Bitaxe", "Gamma"),
            Sv2ClientKind::Miner
        );
        assert_eq!(
            Sv2ClientKind::from_setup_connection("", ""),
            Sv2ClientKind::Unknown
        );
    }

    // ── ClientsMonitoring trait default implementations ─────────────

    struct MockClients(Vec<Sv2ClientInfo>);
    impl Sv2ClientsMonitoring for MockClients {
        fn get_sv2_clients(&self) -> Vec<Sv2ClientInfo> {
            self.0.clone()
        }
    }

    #[test]
    fn clients_monitoring_get_client_by_id_found() {
        let monitor = MockClients(vec![
            create_sv2_client_info(1, vec![create_extended_channel_info(1, 10.0)], vec![]),
            create_sv2_client_info(2, vec![], vec![create_standard_channel_info(1, 20.0)]),
        ]);
        let found = monitor.get_sv2_client_by_id(2);
        assert!(found.is_some());
        assert_eq!(found.unwrap().client_id, 2);
    }

    #[test]
    fn clients_monitoring_get_client_by_id_not_found() {
        let monitor = MockClients(vec![create_sv2_client_info(1, vec![], vec![])]);
        assert!(monitor.get_sv2_client_by_id(999).is_none());
    }

    #[test]
    fn clients_monitoring_summary_empty() {
        let monitor = MockClients(vec![]);
        let summary = monitor.get_sv2_clients_summary();

        assert_eq!(summary.total_clients, 0);
        assert_eq!(summary.total_channels, 0);
        assert_eq!(summary.extended_channels, 0);
        assert_eq!(summary.standard_channels, 0);
        assert_eq!(summary.total_hashrate, 0.0);
    }

    #[test]
    fn clients_monitoring_summary_aggregates_correctly() {
        let monitor = MockClients(vec![
            create_sv2_client_info(
                1,
                vec![create_extended_channel_info(1, 100.0)],
                vec![create_standard_channel_info(2, 50.0)],
            ),
            create_sv2_client_info(
                2,
                vec![
                    create_extended_channel_info(3, 200.0),
                    create_extended_channel_info(4, 300.0),
                ],
                vec![],
            ),
        ]);
        let summary = monitor.get_sv2_clients_summary();

        assert_eq!(summary.total_clients, 2);
        assert_eq!(summary.extended_channels, 3);
        assert_eq!(summary.standard_channels, 1);
        assert_eq!(summary.total_channels, 4);
        assert_eq!(summary.total_hashrate, 650.0);
    }
}