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
use super::*;

enum Action {
    Shutdown,
    Reconnect,
}

pub(crate) struct Controller {
    client: Client,
    cpu_cores: usize,
    enonce1: Extranonce,
    enonce2: Arc<Mutex<Extranonce>>,
    hasher_cancel: Option<CancellationToken>,
    hashers: TaskTracker,
    hasher_handles: Vec<JoinHandle<()>>,
    metrics: Arc<Metrics>,
    notify_tx: watch::Sender<Option<(Notify, CancellationToken)>>,
    notify_rx: watch::Receiver<Option<(Notify, CancellationToken)>>,
    mode: Mode,
    pool_difficulty: Arc<Mutex<Difficulty>>,
    cancel: CancellationToken,
    share_tx: mpsc::Sender<(JobId, Header, Extranonce, Option<Version>)>,
    share_rx: mpsc::Receiver<(JobId, Header, Extranonce, Option<Version>)>,
    shares: Vec<Share>,
    throttle: f64,
    username: Username,
    version_mask: Option<Version>,
}

impl Controller {
    pub(crate) async fn run(
        client: Client,
        username: Username,
        cpu_cores: usize,
        throttle: Option<HashRate>,
        mode: Mode,
        disable_version_rolling: bool,
        cancel_token: CancellationToken,
    ) -> Result<Vec<Share>> {
        let (share_tx, share_rx) = mpsc::channel(256);
        let (notify_tx, notify_rx) = watch::channel(None);

        let throttle = throttle
            .map(|hash_rate| hash_rate.as_hps() / cpu_cores as f64)
            .unwrap_or(f64::MAX);

        let mut controller = Self {
            client,
            cpu_cores,
            enonce1: Extranonce::zeros(0),
            enonce2: Arc::new(Mutex::new(Extranonce::zeros(0))),
            hasher_cancel: None,
            hashers: TaskTracker::new(),
            hasher_handles: Vec::new(),
            metrics: Arc::new(Metrics::new()),
            notify_rx,
            notify_tx,
            mode,
            pool_difficulty: Arc::new(Mutex::new(Difficulty::default())),
            cancel: cancel_token.clone(),
            share_rx,
            share_tx,
            shares: Vec::new(),
            throttle,
            username,
            version_mask: None,
        };

        let mut events = controller.connect(disable_version_rolling).await?;

        info!("Controller initialized with {} CPU cores", cpu_cores);

        controller.spawn_hashers();
        controller.maybe_spawn_throbber(&cancel_token);

        loop {
            match controller.event_loop(events, cancel_token.clone()).await? {
                Action::Shutdown => break,
                Action::Reconnect => {
                    controller.cancel_hashers();
                    controller.notify_tx.send_replace(None);
                    controller.stop_hashers().await;
                    tokio::select! {
                        _ = controller.client.disconnect() => {}
                        _ = cancel_token.cancelled() => {
                            return Ok(controller.shares);
                        }
                    }

                    let mut backoff = Backoff::new();

                    events = loop {
                        match controller.connect(disable_version_rolling).await {
                            Ok(events) => break events,
                            Err(err) => {
                                warn!("upstream attempt failed: {err}");
                                controller.client.disconnect().await;
                            }
                        }

                        match backoff.wait(&cancel_token, "upstream").await {
                            Ok(()) => {}
                            Err(BackoffEnd::Cancelled) => return Ok(controller.shares),
                            Err(BackoffEnd::Exhausted) => {
                                bail!("Upstream unreachable after max backoff attempts")
                            }
                        }
                    };

                    controller.reset_hashers();
                    controller.spawn_hashers();
                    controller.maybe_spawn_throbber(&cancel_token);
                }
            }
        }

        controller.cancel.cancel();
        controller.stop_hashers().await;
        drop(controller.notify_tx);
        controller.client.disconnect().await;

        Ok(controller.shares)
    }

    async fn connect(
        &mut self,
        disable_version_rolling: bool,
    ) -> Result<stratum::client::EventReceiver> {
        let events = self
            .client
            .connect()
            .await
            .context("failed to connect to stratum server")?;

        self.version_mask = if disable_version_rolling {
            info!("Version rolling disabled");
            None
        } else {
            match self
                .client
                .configure(
                    vec!["version-rolling".to_string()],
                    Some(Version::from_str("ffffffff")?),
                )
                .await
            {
                Ok((response, _, _)) => {
                    if response.version_rolling {
                        info!(
                            "Version rolling enabled: mask={:?}",
                            response.version_rolling_mask
                        );
                        response.version_rolling_mask
                    } else {
                        info!("Server does not support version rolling");
                        None
                    }
                }
                Err(err) => {
                    warn!("Failed to configure version rolling: {err}");
                    None
                }
            }
        };

        let (subscribe, _, _) = self
            .client
            .subscribe()
            .await
            .context("stratum mining.subscribe failed")?;

        self.client
            .authorize()
            .await
            .context("stratum mining.authorize failed")?;

        info!(
            "Authorized: enonce1={}, enonce2_size={}",
            subscribe.enonce1, subscribe.enonce2_size
        );

        self.enonce1 = subscribe.enonce1;
        self.enonce2 = Arc::new(Mutex::new(Extranonce::zeros(subscribe.enonce2_size)));

        Ok(events)
    }

    async fn event_loop(
        &mut self,
        mut events: stratum::client::EventReceiver,
        cancel_token: CancellationToken,
    ) -> Result<Action> {
        loop {
            tokio::select! {
                biased;
                _ = cancel_token.cancelled() => {
                    info!("Shutting down stratum client and hasher");
                    return Ok(Action::Shutdown);
                },
                event = events.recv() => {
                    match event {
                        Ok(stratum::client::Event::Notify(notify)) => {
                            self.handle_notify(notify).await?;
                        }
                        Ok(stratum::client::Event::SetDifficulty(difficulty)) => {
                            self.handle_set_difficulty(difficulty);
                        }
                        Ok(stratum::client::Event::Reconnect(_)) => {
                            info!("Received client.reconnect from server");
                            self.cancel_hashers();
                            return Ok(Action::Reconnect);
                        }
                        Ok(stratum::client::Event::Disconnected) => {
                            info!("Disconnected from stratum server");
                            self.cancel_hashers();
                            return Ok(Action::Reconnect);
                        }
                        Err(stratum::client::ClientError::EventsLagged { count }) => {
                            warn!("Event loop lagged, missed {count} messages");
                        }
                        Err(stratum::client::ClientError::EventChannelClosed) => {
                            info!("Client event channel closed, shutting down");
                            return Ok(Action::Shutdown);
                        }
                        Err(e) => {
                            warn!("Unexpected event error: {e}");
                        }
                    }
                },
                maybe = self.share_rx.recv() => match maybe {
                    Some((job_id, header, enonce2, version_bits)) => {
                        info!(
                            "Valid share found with difficulty={} version_bits={:?}",
                            Difficulty::from(header.block_hash()),
                            version_bits
                        );

                        let share = Share {
                            enonce1: self.enonce1.clone(),
                            enonce2: enonce2.clone(),
                            job_id,
                            nonce: header.nonce.into(),
                            ntime: header.time.into(),
                            username: self.username.clone(),
                            version_bits,
                        };

                        self.shares.push(share);

                        match self.client.submit(job_id, enonce2, header.time.into(), header.nonce.into(), version_bits).await {
                            Err(err) => warn!("Failed to submit share for job {job_id}: {err}"),
                            Ok(_) => info!("Share for job {job_id} submitted successfully"),
                        }

                        match self.mode {
                            Mode::ShareFound => {
                                info!("Share found, exiting");
                                return Ok(Action::Shutdown);
                            },
                            Mode::BlockFound => {
                                if header.validate_pow(header.bits.into()).is_ok() {
                                    info!("Block found, exiting");
                                    return Ok(Action::Shutdown);
                                }
                            }
                            Mode::Continuous => continue,
                        }
                    }
                    None => {
                        info!("Share channel closed");
                        return Ok(Action::Shutdown);
                    }
                }
            }
        }
    }

    fn spawn_hashers(&mut self) {
        for core_id in 0..self.cpu_cores {
            let mut notify_rx = self.notify_rx.clone();
            let share_tx = self.share_tx.clone();
            let enonce1 = self.enonce1.clone();
            let enonce2 = self.enonce2.clone();
            let pool_difficulty = self.pool_difficulty.clone();
            let metrics = self.metrics.clone();
            let throttle = self.throttle;
            let version_mask = self.version_mask;

            info!("Starting hasher for core {core_id}",);
            let handle = self.hashers.spawn(async move {
                loop {
                    if notify_rx.changed().await.is_err() {
                        break;
                    }

                    let Some((notify, cancel)) = notify_rx.borrow().clone() else {
                        continue;
                    };

                    loop {
                        if cancel.is_cancelled() {
                            break;
                        }

                        let enonce2 = {
                            let mut guard = enonce2.lock();
                            let enonce2 = guard.clone();
                            guard.increment_wrapping();
                            enonce2
                        };

                        let merkle_root = match stratum::merkle_root(
                            &notify.coinb1,
                            &notify.coinb2,
                            &enonce1,
                            &enonce2,
                            &notify.merkle_branches,
                        ) {
                            Ok(merkle_root) => merkle_root,
                            Err(err) => {
                                warn!("Skipping job {}: {err}", notify.job_id);
                                break;
                            }
                        };

                        let header = Header {
                            version: notify.version.into(),
                            prev_blockhash: notify.prevhash.clone().into(),
                            merkle_root: merkle_root.into(),
                            time: notify.ntime.into(),
                            bits: notify.nbits.into(),
                            nonce: 0,
                        };

                        let pool_target = { pool_difficulty.lock().to_target() };

                        let mut hasher = Hasher {
                            version: notify.version,
                            header,
                            pool_target,
                            enonce2: enonce2.clone(),
                            job_id: notify.job_id,
                            version_mask,
                        };

                        let cancel_clone = cancel.clone();
                        let metrics_clone = metrics.clone();

                        let result = task::spawn_blocking(move || {
                            hasher.hash(cancel_clone, metrics_clone, throttle)
                        })
                        .await;

                        match result {
                            Ok(Ok(share)) => {
                                let _ = share_tx.send(share).await;
                            }
                            Ok(Err(err)) => {
                                warn!("Hasher failed on core {core_id}: {err}");
                                if cancel.is_cancelled() {
                                    break;
                                }
                                continue;
                            }
                            Err(_) => break,
                        }
                    }
                }
            });
            self.hasher_handles.push(handle);
        }
    }

    async fn handle_notify(&mut self, notify: Notify) -> Result {
        info!("New job: job_id={}", notify.job_id,);

        let cancel = if notify.clean_jobs {
            self.cancel_hashers()
        } else {
            self.hasher_cancel
                .clone()
                .unwrap_or_else(|| self.cancel_hashers())
        };

        self.notify_tx.send_replace(Some((notify, cancel)));
        Ok(())
    }

    fn handle_set_difficulty(&mut self, difficulty: Difficulty) {
        *self.pool_difficulty.lock() = difficulty;
        info!("Updated pool difficulty: {difficulty}");
        info!(
            "Updated pool target:\t{}",
            target_as_block_hash(difficulty.to_target())
        );
    }

    fn maybe_spawn_throbber(&mut self, cancel_token: &CancellationToken) {
        if !integration_test() && !logs_enabled() {
            let handle = spawn_throbber(self.metrics.clone(), cancel_token.clone(), &self.hashers);
            self.hasher_handles.push(handle);
        }
    }

    fn reset_hashers(&mut self) {
        self.hashers.close();
        self.hashers = TaskTracker::new();
        self.hasher_handles.clear();
    }

    async fn stop_hashers(&mut self) {
        self.hashers.close();

        for handle in &self.hasher_handles {
            handle.abort();
        }

        self.hashers.wait().await;
        self.hasher_handles.clear();
    }

    fn cancel_hashers(&mut self) -> CancellationToken {
        if let Some(cancel) = &self.hasher_cancel {
            cancel.cancel();
        }
        let cancel = self.cancel.child_token();
        self.hasher_cancel = Some(cancel.clone());
        cancel
    }
}