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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use {
    super::*,
    stratum::client::{Client, ClientError, Event},
};

pub(crate) const NOTIFY_TIMEOUT: Duration = Duration::from_secs(600);

pub(crate) struct UpstreamSubmit {
    pub(crate) job_id: JobId,
    pub(crate) enonce2: Extranonce,
    pub(crate) nonce: Nonce,
    pub(crate) ntime: Ntime,
    pub(crate) version_bits: Option<Version>,
    pub(crate) share_diff: Difficulty,
}

pub(crate) struct Upstream {
    id: u32,
    client: Client,
    endpoint: String,
    enonce1: Extranonce,
    enonce2_size: usize,
    version_mask: Option<Version>,
    metatron: Arc<Metatron>,
    upstream_address: Option<SocketAddr>,
    connected: watch::Sender<bool>,
    ping: Arc<RwLock<Duration>>,
    difficulty: Arc<RwLock<Difficulty>>,
    workbase_rx: watch::Receiver<Arc<Notify>>,
    tasks: TaskTracker,
}

struct Disconnect(watch::Sender<bool>);

impl Drop for Disconnect {
    fn drop(&mut self) {
        self.0.send_if_modified(|connected| {
            if !*connected {
                return false;
            }
            *connected = false;
            true
        });
    }
}

impl Upstream {
    pub(crate) async fn connect(
        id: u32,
        target: &UpstreamTarget,
        timeout: Duration,
        notify_timeout: Duration,
        cancel: CancellationToken,
        tasks: &TaskTracker,
        metatron: Arc<Metatron>,
    ) -> Result<Arc<Self>> {
        info!(
            "Connecting to upstream {} as {}",
            target.endpoint(),
            target.username()
        );

        let client = Client::with_cancel(
            target.endpoint().into(),
            target.username().clone(),
            target.password().map(String::from),
            USER_AGENT.into(),
            timeout,
            cancel.clone(),
        );

        let mut events = client
            .connect()
            .await
            .context("failed to connect to upstream")?;

        let upstream_address = client.upstream_address().await.ok();

        if let Some(upstream_address) = upstream_address {
            info!("Connected to upstream at {upstream_address}");
        }

        let version_mask = match client
            .configure(
                vec!["version-rolling".to_string()],
                Some(Version::from_str("1fffe000").expect("valid hex")),
            )
            .await
        {
            Ok((response, ..)) => {
                if response.version_rolling {
                    if let Some(mask) = response.version_rolling_mask {
                        info!("Upstream supports version rolling: mask={mask}",);
                    }
                    response.version_rolling_mask
                } else {
                    info!("Upstream does not support version rolling");
                    None
                }
            }
            Err(e) => {
                warn!("Failed to negotiate version rolling with upstream: {e}");
                None
            }
        };

        let (subscribe, ..) = client
            .subscribe()
            .await
            .context("failed to subscribe to upstream")?;

        info!(
            "Subscribed to upstream: enonce1={}, enonce2_size={}",
            subscribe.enonce1, subscribe.enonce2_size
        );

        let (ping, _) = client
            .authorize()
            .await
            .context("failed to authorize with upstream")?;

        info!(
            "Authorized to upstream {} with {}",
            client.address(),
            client.username()
        );

        let (initial_difficulty, first_notify) = tokio::time::timeout(timeout, async {
            let mut initial_difficulty: Option<Difficulty> = None;
            let mut first_notify: Option<Notify> = None;

            Ok(loop {
                match events.recv().await {
                    Ok(Event::SetDifficulty(diff)) => {
                        info!("Received initial difficulty: {}", diff);
                        initial_difficulty = Some(diff);
                    }
                    Ok(Event::Notify(notify)) => {
                        info!(
                            "Received job: job_id={}, clean_jobs={}",
                            notify.job_id, notify.clean_jobs
                        );
                        first_notify = Some(notify);
                    }
                    Ok(Event::Reconnect(_)) | Ok(Event::Disconnected) => {
                        bail!("Disconnected from upstream before initialization complete");
                    }
                    Err(e) => {
                        bail!("Upstream error during initialization: {e}");
                    }
                }

                if let Some(diff) = initial_difficulty
                    && let Some(notify) = first_notify.take()
                {
                    break (diff, notify);
                }
            })
        })
        .await
        .context("timed out waiting for initial difficulty and job from upstream")??;

        let difficulty = Arc::new(RwLock::new(initial_difficulty));
        let (connected, _) = watch::channel(true);
        let (workbase_tx, workbase_rx) = watch::channel(Arc::new(first_notify));

        let difficulty_clone = difficulty.clone();
        let connections = metatron.connections().clone();
        let disconnect = Disconnect(connected.clone());
        let mut notify_deadline = tokio::time::Instant::now() + notify_timeout;

        tasks.spawn(async move {
            let _disconnect = disconnect;

            loop {
                tokio::select! {
                    biased;

                    _ = cancel.cancelled() => {
                        break;
                    }

                    _ = tokio::time::sleep_until(notify_deadline) => {
                        warn!(
                            "No work received from upstream for {}s, disconnecting",
                            notify_timeout.as_secs()
                        );
                        connections.record_upstream_disconnect(id);
                        break;
                    }

                    event = events.recv() => {
                        match event {
                            Ok(Event::Notify(notify)) => {
                                debug!(
                                    "Received notify: job_id={}, clean_jobs={}",
                                    notify.job_id, notify.clean_jobs
                                );
                                notify_deadline = tokio::time::Instant::now() + notify_timeout;
                                workbase_tx.send_replace(Arc::new(notify));
                            }
                            Ok(Event::SetDifficulty(diff)) => {
                                info!("Received set_difficulty: {}", diff);
                                *difficulty_clone.write() = diff;
                            }
                            Ok(Event::Reconnect(_)) | Ok(Event::Disconnected) => {
                                warn!("Disconnected from upstream");
                                connections.record_upstream_disconnect(id);
                                break;
                            }
                            Err(err) => {
                                error!("Upstream event error: {}", err);
                                connections.record_upstream_disconnect(id);
                                break;
                            }
                        }
                    }
                }
            }
        });

        Ok(Arc::new(Self {
            id,
            client,
            endpoint: target.endpoint().to_string(),
            enonce1: subscribe.enonce1,
            enonce2_size: subscribe.enonce2_size,
            connected,
            ping: Arc::new(RwLock::new(ping)),
            difficulty,
            metatron,
            upstream_address,
            version_mask,
            workbase_rx,
            tasks: tasks.clone(),
        }))
    }

    pub(crate) fn workbase_rx(&self) -> watch::Receiver<Arc<Notify>> {
        self.workbase_rx.clone()
    }

    pub(crate) async fn submit_share(&self, submit: UpstreamSubmit) {
        let upstream_diff = *self.difficulty.read();
        if submit.share_diff < upstream_diff {
            debug!(
                "Share below upstream difficulty: share_diff={} < upstream_diff={}",
                submit.share_diff, upstream_diff
            );
            return;
        }

        debug!(
            "Submitting share to upstream: job_id={}, share_diff={}, upstream_diff={}",
            submit.job_id, submit.share_diff, upstream_diff
        );

        let client = self.client.clone();
        let metatron = self.metatron.clone();
        let id = self.id;
        let share_diff = submit.share_diff;
        let ping = self.ping.clone();

        self.tasks.spawn(async move {
            match client
                .submit(
                    submit.job_id,
                    submit.enonce2,
                    submit.ntime,
                    submit.nonce,
                    submit.version_bits,
                )
                .await
            {
                Ok(duration) => {
                    metatron.record_order_accepted(id, upstream_diff, share_diff);
                    *ping.write() = duration;

                    debug!("Upstream accepted share");
                }
                Err(err) => {
                    metatron.record_order_rejected(id, upstream_diff);
                    match err {
                        ClientError::SubmitFalse => warn!("Upstream rejected share"),
                        ClientError::Rejected { reason, .. } => {
                            warn!("Upstream rejected share: {reason}")
                        }
                        err => warn!("Upstream submit error: {err}"),
                    }
                }
            }
        });
    }

    pub(crate) fn id(&self) -> u32 {
        self.id
    }

    pub(crate) fn enonce1(&self) -> &Extranonce {
        &self.enonce1
    }

    pub(crate) fn enonce2_size(&self) -> usize {
        self.enonce2_size
    }

    pub(crate) fn difficulty(&self) -> Difficulty {
        *self.difficulty.read()
    }

    pub(crate) fn is_connected(&self) -> bool {
        *self.connected.borrow()
    }

    pub(crate) async fn disconnected(&self) {
        let mut rx = self.connected.subscribe();
        while *rx.borrow_and_update() {
            if rx.changed().await.is_err() {
                return;
            }
        }
    }

    pub(crate) fn endpoint(&self) -> &str {
        &self.endpoint
    }

    pub(crate) fn upstream_address(&self) -> Option<SocketAddr> {
        self.upstream_address
    }

    pub(crate) fn username(&self) -> &Username {
        self.client.username()
    }

    pub(crate) fn version_mask(&self) -> Option<Version> {
        self.version_mask
    }

    pub(crate) fn ping_ms(&self) -> u128 {
        self.ping.read().as_millis()
    }

    #[cfg(test)]
    pub(crate) fn set_connected(&self, value: bool) {
        self.connected.send_replace(value);
    }

    #[cfg(test)]
    pub(crate) fn test(id: u32, metatron: Arc<Metatron>) -> Arc<Self> {
        fn runtime() -> &'static tokio::runtime::Runtime {
            static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> =
                std::sync::OnceLock::new();

            RUNTIME.get_or_init(|| tokio::runtime::Runtime::new().unwrap())
        }

        let notify = Notify {
            job_id: "bf".parse().unwrap(),
            prevhash: "4d16b6f85af6e2198f44ae2a6de67f78487ae5611b77c6c0440b921e00000000"
                .parse()
                .unwrap(),
            coinb1: "aa".into(),
            coinb2: "bb".into(),
            merkle_branches: Vec::new(),
            version: Version(block::Version::TWO),
            nbits: "1c2ac4af".parse().unwrap(),
            ntime: "504e86b9".parse().unwrap(),
            clean_jobs: false,
        };
        let (_, workbase_rx) = watch::channel(Arc::new(notify));
        let _guard = runtime().enter();

        Arc::new(Self {
            id,
            client: Client::new(
                "foo:3333".into(),
                "tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc.worker"
                    .parse()
                    .unwrap(),
                None,
                "baz".into(),
                Duration::from_secs(1),
            ),
            endpoint: "foo:3333".into(),
            enonce1: Extranonce::random(4),
            enonce2_size: 4,
            connected: watch::channel(true).0,
            ping: Arc::new(RwLock::new(Duration::ZERO)),
            difficulty: Arc::new(RwLock::new(Difficulty::from(1u64))),
            metatron,
            upstream_address: Some("127.0.0.1:3333".parse().unwrap()),
            version_mask: None,
            workbase_rx,
            tasks: TaskTracker::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        std::net::SocketAddr,
        tokio::{
            io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
            net::TcpListener,
        },
    };

    async fn mock_upstream(with_work: bool) -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        tokio::spawn(async move {
            let (socket, _) = listener.accept().await.unwrap();
            let (read_half, mut write_half) = socket.into_split();
            let mut reader = BufReader::new(read_half);
            let mut line = String::new();

            loop {
                line.clear();
                if reader.read_line(&mut line).await.unwrap_or(0) == 0 {
                    break;
                }

                let Ok(request) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
                    continue;
                };
                let id = request["id"].clone();

                let response = match request["method"].as_str() {
                    Some("mining.configure") => {
                        serde_json::json!({"id": id, "result": {}, "error": null})
                    }
                    Some("mining.subscribe") => serde_json::json!({
                        "id": id,
                        "result": [[["mining.notify", "ae6812eb4cd7735a302a8a9dd95cf71f"]], "08000002", 4],
                        "error": null,
                    }),
                    Some("mining.authorize") => {
                        write_half
                            .write_all(
                                format!(
                                    "{}\n",
                                    serde_json::json!({"id": id, "result": true, "error": null})
                                )
                                .as_bytes(),
                            )
                            .await
                            .unwrap();

                        if with_work {
                            write_half
                                .write_all(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[2]}\n")
                                .await
                                .unwrap();
                            write_half
                                .write_all(
                                    b"{\"id\":null,\"method\":\"mining.notify\",\"params\":[\"bf\",\"4d16b6f85af6e2198f44ae2a6de67f78487ae5611b77c6c0440b921e00000000\",\"01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff20020862062f503253482f04b8864e5008\",\"072f736c7573682f000000000100f2052a010000001976a914d23fcdf86f7e756a64a7a9688ef9903327048ed988ac00000000\",[],\"00000002\",\"1c2ac4af\",\"504e86b9\",false]}\n",
                                )
                                .await
                                .unwrap();
                        }

                        break;
                    }
                    _ => continue,
                };

                write_half
                    .write_all(format!("{response}\n").as_bytes())
                    .await
                    .unwrap();
            }

            tokio::time::sleep(Duration::from_secs(60)).await;
        });

        addr
    }

    fn test_target(addr: SocketAddr) -> UpstreamTarget {
        format!("tb1qkrrl75qekv9ree0g2qt49j8vdynsvlc4kuctrc.worker@{addr}")
            .parse()
            .unwrap()
    }

    #[tokio::test]
    async fn connect_times_out_without_initial_job() {
        let (metatron, _dir) = Metatron::test();
        let addr = mock_upstream(false).await;
        let tasks = TaskTracker::new();

        let err = match Upstream::connect(
            0,
            &test_target(addr),
            Duration::from_millis(300),
            Duration::from_millis(300),
            CancellationToken::new(),
            &tasks,
            Arc::new(metatron),
        )
        .await
        {
            Ok(_) => panic!("connect must time out without an initial job"),
            Err(err) => err,
        };

        assert!(err.to_string().contains("timed out"), "{err:#}");
    }

    #[tokio::test]
    async fn upstream_disconnects_when_notifies_stall() {
        let (metatron, _dir) = Metatron::test();
        let addr = mock_upstream(true).await;
        let tasks = TaskTracker::new();
        let connections = metatron.connections().clone();

        let upstream = Upstream::connect(
            0,
            &test_target(addr),
            Duration::from_secs(5),
            Duration::from_millis(200),
            CancellationToken::new(),
            &tasks,
            Arc::new(metatron),
        )
        .await
        .unwrap();

        timeout(Duration::from_secs(2), upstream.disconnected())
            .await
            .expect("upstream must disconnect when notifies stall");

        assert_eq!(connections.order_disconnects(0), 1);
        assert_eq!(connections.upstream_disconnects(Instant::now()), 1);
    }

    #[tokio::test]
    async fn disconnected_returns_immediately_when_already_disconnected() {
        let (metatron, _dir) = Metatron::test();
        let upstream = Upstream::test(0, Arc::new(metatron));

        upstream.set_connected(false);

        timeout(Duration::from_millis(100), upstream.disconnected())
            .await
            .expect("disconnected() must return immediately when not connected");
    }

    #[tokio::test]
    async fn disconnected_resolves_when_set_connected_flips_to_false() {
        let (metatron, _dir) = Metatron::test();
        let upstream = Upstream::test(0, Arc::new(metatron));
        let flipper = upstream.clone();

        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            flipper.set_connected(false);
        });

        timeout(Duration::from_millis(500), upstream.disconnected())
            .await
            .expect("disconnected() must resolve once set_connected flips to false");
    }
}