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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use crate::server::VarDiffConfig;
use crate::{Result, ID};
use async_std::net::SocketAddr;
use async_std::sync::{Arc, Mutex, RwLock};
use chrono::{NaiveDateTime, Utc};
use encodings::{FromHex, ToHex};
use extended_primitives::Buffer;
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
use futures::SinkExt;
use futures::StreamExt;
use log::{debug, trace, warn};
use rand::prelude::*;
use serde::Serialize;
use serde_json::json;
use std::collections::HashMap;
use std::net::IpAddr;
use std::time::SystemTime;
use stop_token::{StopSource, StopToken};
use uuid::Uuid;
#[derive(PartialEq, Debug)]
pub enum ConnectionState {
Connected,
Disconnect,
}
#[derive(Debug)]
pub struct Connection<State> {
pub session_id: u32,
pub sender: Arc<Mutex<UnboundedSender<String>>>,
pub upstream_sender: Arc<Mutex<UnboundedSender<String>>>,
pub upstream_receiver:
Arc<Mutex<UnboundedReceiver<serde_json::map::Map<String, serde_json::Value>>>>,
pub authorized: Arc<Mutex<bool>>,
pub subscribed: Arc<Mutex<bool>>,
pub agent: Arc<Mutex<bool>>,
pub session_start: SystemTime,
pub connection_state: Mutex<ConnectionState>,
pub difficulty: Arc<Mutex<f64>>,
pub stats: Arc<Mutex<MinerStats>>,
pub needs_ban: Arc<Mutex<bool>>,
pub next_difficulty: Arc<Mutex<Option<f64>>>,
pub id: Uuid,
pub job_stats: Arc<Mutex<JobStats>>,
pub options: Arc<MinerOptions>,
pub var_diff: Arc<Mutex<bool>>,
pub last_message_id: Arc<Mutex<ID>>,
pub worker_info: Arc<Mutex<WorkerInfo>>,
pub state: Arc<Mutex<State>>,
pub stop_source: Arc<Mutex<Option<StopSource>>>,
pub stop_token: StopToken,
pub worker_list: Arc<Mutex<HashMap<u16, AgentWorkerInfo>>>,
}
#[derive(Clone, Debug)]
pub struct MinerJobStats {
pub expected_difficulty: f64,
}
#[derive(Debug)]
pub struct JobStats {
last_timestamp: i64,
last_share_timestamp: i64,
last_retarget: i64,
times: Vec<i64>,
current_difficulty: f64,
job_difficulty: f64,
}
#[derive(Debug, Default)]
pub struct MinerOptions {
retarget_time: i64,
target_time: f64,
min_diff: f64,
max_diff: f64,
max_delta: f64,
variance_percent: f64,
}
#[derive(Debug, Clone)]
pub struct MinerStats {
accepted_shares: u64,
rejected_shares: u64,
last_active: NaiveDateTime,
}
#[derive(Debug, Clone, Default)]
pub struct WorkerInfo {
pub client: Option<String>,
pub name: Option<String>,
pub sid: Option<Buffer>,
pub account_id: i32,
pub miner_account: Option<i32>,
pub id: Uuid,
}
#[derive(Debug, Clone)]
pub struct AgentWorkerInfo {
pub client: Option<String>,
pub name: Option<String>,
pub sid: Option<Buffer>,
pub account_id: i32,
pub miner_account: Option<i32>,
pub id: Uuid,
pub stats: Arc<Mutex<MinerStats>>,
pub job_stats: Arc<Mutex<JobStats>>,
}
impl<State: Clone + Send + Sync + 'static> Connection<State> {
pub fn new(
session_id: u32,
addr: SocketAddr,
sender: UnboundedSender<String>,
upstream_sender: UnboundedSender<String>,
upstream_receiver: UnboundedReceiver<serde_json::map::Map<String, serde_json::Value>>,
initial_difficulty: f64,
var_diff_config: VarDiffConfig,
state: State,
) -> Self {
let id = Uuid::new_v4();
debug!("Accepting new miner. ID: {}", &id);
let options = MinerOptions {
retarget_time: var_diff_config.retarget_time,
target_time: var_diff_config.target_time,
min_diff: var_diff_config.minimum_difficulty,
max_diff: var_diff_config.maximum_difficulty,
max_delta: 1.0,
variance_percent: var_diff_config.variance_percent,
};
let stats = MinerStats {
accepted_shares: 0,
rejected_shares: 0,
last_active: Utc::now().naive_utc(),
};
let job_stats = JobStats {
last_share_timestamp: 0,
last_timestamp: Utc::now().naive_utc().timestamp(),
last_retarget: Utc::now().naive_utc().timestamp() - options.retarget_time / 2,
times: Vec::new(),
current_difficulty: initial_difficulty,
job_difficulty: 0.0,
};
let stop_source = StopSource::new();
let stop_token = stop_source.stop_token();
Connection {
session_id,
id,
sender: Arc::new(Mutex::new(sender)),
upstream_sender: Arc::new(Mutex::new(upstream_sender)),
upstream_receiver: Arc::new(Mutex::new(upstream_receiver)),
authorized: Arc::new(Mutex::new(false)),
session_start: SystemTime::now(),
connection_state: Mutex::new(ConnectionState::Connected),
subscribed: Arc::new(Mutex::new(false)),
agent: Arc::new(Mutex::new(false)),
difficulty: Arc::new(Mutex::new(initial_difficulty)),
next_difficulty: Arc::new(Mutex::new(None)),
job_stats: Arc::new(Mutex::new(job_stats)),
options: Arc::new(options),
stats: Arc::new(Mutex::new(stats)),
var_diff: Arc::new(Mutex::new(var_diff_config.var_diff)),
needs_ban: Arc::new(Mutex::new(false)),
last_message_id: Arc::new(Mutex::new(ID::Str(String::from("")))),
worker_info: Arc::new(Mutex::new(Default::default())),
state: Arc::new(Mutex::new(state)),
stop_source: Arc::new(Mutex::new(Some(stop_source))),
stop_token,
worker_list: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn is_disconnected(&self) -> bool {
*self.connection_state.lock().await == ConnectionState::Disconnect
}
pub async fn send<T: Serialize>(&self, message: T) -> Result<()> {
let msg_string = serde_json::to_string(&message)?;
trace!("Sending message: {}", msg_string.clone());
let mut sender = self.sender.lock().await;
sender.send(msg_string).await?;
Ok(())
}
pub async fn upstream_send<T: Serialize>(&self, message: T) -> Result<()> {
let msg_string = serde_json::to_string(&message)?;
debug!("Sending message: {}", msg_string.clone());
let mut upstream_sender = self.upstream_sender.lock().await;
upstream_sender.send(msg_string).await?;
Ok(())
}
pub async fn upstream_result(&self) -> Result<(serde_json::Value, serde_json::Value)> {
let mut upstream_receiver = self.upstream_receiver.lock().await;
let values = match upstream_receiver.next().await {
Some(values) => values,
None => return Ok((json!(false), serde_json::Value::Null)),
};
Ok((values["result"].clone(), values["error"].clone()))
}
pub async fn shutdown(&self) -> Result<()> {
*self.connection_state.lock().await = ConnectionState::Disconnect;
*self.stop_source.lock().await = None;
Ok(())
}
async fn retarget(&self) {
let now = Utc::now().naive_utc().timestamp();
let mut job_stats = self.job_stats.lock().await;
job_stats.current_difficulty = *self.difficulty.lock().await;
let since_last = now - job_stats.last_timestamp;
job_stats.times.push(since_last);
job_stats.last_timestamp = now;
if now - job_stats.last_retarget < self.options.retarget_time {
return;
}
let variance = self.options.target_time * (self.options.variance_percent as f64 / 100.0);
let time_min = self.options.target_time - variance;
let time_max = self.options.target_time + variance;
job_stats.last_retarget = now;
let avg: i64 = job_stats.times.iter().sum::<i64>() / job_stats.times.len() as i64;
let mut d_dif = self.options.target_time / avg as f64;
if avg as f64 > time_max && job_stats.current_difficulty > self.options.min_diff {
if d_dif * job_stats.current_difficulty < self.options.min_diff {
d_dif = self.options.min_diff / job_stats.current_difficulty;
}
} else if (avg as f64) < time_min {
if d_dif * job_stats.current_difficulty > self.options.max_diff {
d_dif = self.options.max_diff / job_stats.current_difficulty;
}
} else {
return;
}
let new_diff = job_stats.current_difficulty * d_dif;
*self.next_difficulty.lock().await = Some(new_diff.floor());
job_stats.times.clear();
}
pub async fn disconnect(&self) {
*self.connection_state.lock().await = ConnectionState::Disconnect;
}
pub async fn ban(&self) {
*self.needs_ban.lock().await = true;
self.disconnect().await;
}
pub async fn needs_ban(&self) -> bool {
*self.needs_ban.lock().await
}
pub async fn get_stats(&self) -> MinerStats {
self.stats.lock().await.clone()
}
pub fn id(&self) -> Uuid {
self.id
}
pub async fn set_sid(&self, sid: Option<String>, sid_size: usize) -> String {
let sid = match sid {
Some(sid) => Buffer::from_hex(sid).unwrap(),
None => {
let mut id = vec![0; sid_size];
let mut rng = rand::thread_rng();
rng.fill_bytes(&mut id);
Buffer::from(id)
}
};
self.worker_info.lock().await.sid = Some(sid.clone());
sid.to_hex()
}
pub async fn register_worker(
&self,
session_id: u16,
client_agent: &str,
worker_name: &str,
worker_id: Uuid,
) {
let worker = AgentWorkerInfo {
client: Some(client_agent.to_owned()),
name: Some(worker_name.to_owned()),
sid: Some(Buffer::from(session_id.to_le_bytes().to_vec())),
account_id: self.get_account_id().await,
miner_account: self.get_miner_account().await,
id: worker_id,
stats: Arc::new(Mutex::new(MinerStats {
accepted_shares: 0,
rejected_shares: 0,
last_active: Utc::now().naive_utc(),
})),
job_stats: Arc::new(Mutex::new(JobStats {
last_timestamp: Utc::now().naive_utc().timestamp(),
last_share_timestamp: 0,
last_retarget: Utc::now().naive_utc().timestamp() - self.options.retarget_time / 2,
times: Vec::new(),
current_difficulty: self.difficulty.lock().await.clone(),
job_difficulty: 0.0,
})),
};
self.worker_list.lock().await.insert(session_id, worker);
}
pub async fn unregister_worker(&self, session_id: u16) {
self.worker_list.lock().await.remove(&session_id);
}
pub async fn get_worker_list(&self) -> HashMap<u16, AgentWorkerInfo> {
self.worker_list.lock().await.clone()
}
pub async fn get_worker_by_session_id(&self, session_id: u16) -> Option<AgentWorkerInfo> {
self.worker_list
.lock()
.await
.get(&session_id)
.map(|w| w.clone())
}
pub async fn update_worker_by_session_id(&self, session_id: u16, worker: AgentWorkerInfo) {
self.worker_list.lock().await.insert(session_id, worker);
}
pub async fn set_var_diff(&self, var_diff: bool) {
*self.var_diff.lock().await = var_diff;
}
pub async fn set_worker_name(&self, name: Option<String>) {
self.worker_info.lock().await.name = name;
}
pub async fn set_account_id(&self, id: i32) {
self.worker_info.lock().await.account_id = id;
}
pub async fn get_account_id(&self) -> i32 {
self.worker_info.lock().await.account_id
}
pub async fn set_miner_account(&self, id: Option<i32>) {
self.worker_info.lock().await.miner_account = id;
}
pub async fn get_miner_account(&self) -> Option<i32> {
self.worker_info.lock().await.miner_account
}
pub async fn set_client(&self, client: &str) {
self.worker_info.lock().await.client = Some(client.to_owned());
}
pub async fn get_client(&self) -> Option<String> {
self.worker_info.lock().await.client.clone()
}
pub async fn set_worker_id(&self, id: Uuid) {
self.worker_info.lock().await.id = id;
}
pub async fn get_sid(&self) -> Option<Buffer> {
self.worker_info.lock().await.sid.clone()
}
pub fn get_session_id(&self) -> u32 {
self.session_id
}
pub async fn get_worker(&self) -> WorkerInfo {
self.worker_info.lock().await.clone()
}
pub async fn authorized(&self) -> bool {
*self.authorized.lock().await
}
pub async fn authorize(&self) {
*self.authorized.lock().await = true;
}
pub async fn subscribed(&self) -> bool {
*self.subscribed.lock().await
}
pub async fn subscribe(&self) {
*self.subscribed.lock().await = true;
}
pub async fn set_difficulty(&self, difficulty: f64) {
*self.difficulty.lock().await = difficulty;
}
pub async fn get_difficulty(&self) -> f64 {
*self.difficulty.lock().await
}
pub async fn get_state(&self) -> State {
self.state.lock().await.clone()
}
pub async fn set_state(&self, state: State) {
*self.state.lock().await = state;
}
pub async fn valid_share(&self) {
self.stats.lock().await.accepted_shares += 1;
self.stats.lock().await.last_active = Utc::now().naive_utc();
self.consider_ban().await;
if *self.var_diff.lock().await {
self.retarget().await;
}
}
pub async fn valid_share_by_session_id(&self, session_id: u16) {
match self.get_worker_by_session_id(session_id).await {
Some(worker) => {
worker.stats.lock().await.accepted_shares += 1;
worker.stats.lock().await.last_active = Utc::now().naive_utc();
self.consider_ban().await;
if *self.var_diff.lock().await {
self.retarget().await;
}
}
None => {}
}
}
pub async fn update_difficulty(&self) -> Option<f64> {
let next_difficulty = *self.next_difficulty.lock().await;
if let Some(next_difficulty) = next_difficulty {
*self.difficulty.lock().await = next_difficulty;
*self.next_difficulty.lock().await = None;
Some(next_difficulty)
} else {
None
}
}
pub async fn invalid_share(&self) {
self.stats.lock().await.rejected_shares += 1;
self.consider_ban().await;
}
pub fn get_stop_token(&self) -> StopToken {
self.stop_token.clone()
}
pub async fn consider_ban(&self) {
let accepted = self.stats.lock().await.accepted_shares;
let rejected = self.stats.lock().await.rejected_shares;
let total = accepted + rejected;
let check_threshold = 500;
let invalid_percent = 50.0;
if total >= check_threshold {
let percent_bad: f64 = (rejected as f64 / total as f64) * 100.0;
if percent_bad < invalid_percent {
} else {
warn!(
"Miner: {} banned. {} out of the last {} shares were invalid",
self.id, rejected, total
);
self.ban().await;
}
}
}
}