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
use crate::{format_difficulty, server::VarDiffConfig, Miner, MinerList, Result};
use async_std::sync::{Arc, Mutex, RwLock};
use extended_primitives::Buffer;
use futures::{
    channel::mpsc::{UnboundedReceiver, UnboundedSender},
    SinkExt, StreamExt,
};
use log::{debug, trace};
use serde::Serialize;
use serde_json::json;
use std::time::SystemTime;
use stop_token::{StopSource, StopToken};
use uuid::Uuid;

#[derive(Debug, Clone)]
pub struct UserInfo {
    pub account_id: i32,
    pub mining_account: i32,
    pub worker_name: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ConnectionInfo {
    pub agent: bool,
    pub authorized: bool,
    pub subscribed: bool,
    pub client: Option<String>,
    pub session_start: SystemTime,
    pub state: ConnectionState,
    pub is_long_timeout: bool,
}

impl Default for ConnectionInfo {
    fn default() -> Self {
        Self::new()
    }
}

impl ConnectionInfo {
    pub fn new() -> Self {
        ConnectionInfo {
            agent: false,
            authorized: false,
            subscribed: false,
            client: None,
            session_start: SystemTime::now(),
            state: ConnectionState::Connected,
            is_long_timeout: false,
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum ConnectionState {
    Connected,
    Disconnect,
}

#[derive(Debug)]
pub enum SendInformation {
    Json(String),
    Raw(Buffer),
}

//@todo thought process -> Rather than have this boolean variables that slowly add up over time, we
//should add a new type of "ConnectionType". This will allow us to also incorporate other types of
//connections that are developed in the future or that are already here and enables a lot easier
//pattern matching imo.
//
//@todo also think about these enums for connectgion sttatus like authenticated/subscribed etc.
#[derive(Debug)]
pub struct Connection<State> {
    pub id: Uuid,
    pub session_id: u32,

    pub info: Arc<RwLock<ConnectionInfo>>,
    pub user_info: Arc<Mutex<UserInfo>>,

    pub sender: Arc<Mutex<UnboundedSender<SendInformation>>>,
    pub upstream_sender: Arc<Mutex<UnboundedSender<String>>>,
    pub upstream_receiver:
        Arc<Mutex<UnboundedReceiver<serde_json::map::Map<String, serde_json::Value>>>>,

    pub difficulty: Arc<Mutex<f64>>,
    pub next_difficulty: Arc<Mutex<Option<f64>>>,
    pub options: Arc<MinerOptions>,

    pub needs_ban: Arc<Mutex<bool>>,
    pub state: Arc<Mutex<State>>,
    pub stop_source: Arc<Mutex<Option<StopSource>>>,
    pub stop_token: StopToken,

    //@todo probably redo this quite a bit but for now it works.
    //@todo if we make Miner send/safe etc then we can rmeove all of the Arc shit.
    pub connection_miner: Arc<Mutex<Option<Miner>>>,
    pub miner_list: MinerList,
}

//@todo this should probably come from builder pattern
#[derive(Debug, Default)]
pub struct MinerOptions {
    pub retarget_time: u64, //300 Seconds
    pub target_time: u64,   //10 seconds
    pub min_diff: u64,
    pub max_diff: u64,
    pub max_delta: f64,
    pub variance_percent: f64,
    // share_time_min: f64,
    // share_time_max: f64,
}

impl<State: Clone + Send + Sync + 'static> Connection<State> {
    pub fn new(
        session_id: u32,
        sender: UnboundedSender<SendInformation>,
        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);

        //@todo one thing we might need here is difficulty scales (akak jumps we can do and send
        //over ExMessage). Also we should consider moving
        //to u64 for difficulty not f64.
        let options = MinerOptions {
            retarget_time: var_diff_config.retarget_time,
            target_time: var_diff_config.target_time,
            //@todo these values make no sense so let's trim them a bit.
            min_diff: var_diff_config.minimum_difficulty,
            max_diff: var_diff_config.maximum_difficulty,
            max_delta: 1.0, //@todo make this adjustable, not sure if this is solid or not.
            //@todo probably don't store, get from above and then calcualte the others.
            variance_percent: var_diff_config.variance_percent,
            // share_time_min: 4.2,
            // share_time_max: 7.8,
        };

        let stop_source = StopSource::new();
        let stop_token = stop_source.token();

        Connection {
            id,
            session_id,
            user_info: Arc::new(Mutex::new(UserInfo {
                account_id: 0,
                mining_account: 0,
                worker_name: None,
            })),
            info: Arc::new(RwLock::new(ConnectionInfo::new())),
            sender: Arc::new(Mutex::new(sender)),
            upstream_sender: Arc::new(Mutex::new(upstream_sender)),
            upstream_receiver: Arc::new(Mutex::new(upstream_receiver)),
            difficulty: Arc::new(Mutex::new(initial_difficulty)),
            next_difficulty: Arc::new(Mutex::new(None)),
            options: Arc::new(options),
            needs_ban: Arc::new(Mutex::new(false)),
            state: Arc::new(Mutex::new(state)),
            stop_source: Arc::new(Mutex::new(Some(stop_source))),
            stop_token,
            miner_list: MinerList::new(),
            connection_miner: Arc::new(Mutex::new(None)),
        }
    }

    pub async fn is_disconnected(&self) -> bool {
        self.info.read().await.state == ConnectionState::Disconnect
    }

    //@todo we have disabled last_active for now... Need to reimplement this desperately.
    pub async fn send<T: Serialize>(&self, message: T) -> Result<()> {
        //let last_active = self.stats.lock().await.last_active;

        //let last_active_ago = Utc::now().naive_utc() - last_active;

        ////@todo rewrite this comment
        ////If the miner has not been active (sending shares) for 5 minutes, we disconnect this dude.
        ////@todo before live, check this guy. Also should come from options.
        ////@todo make the last_active thing a config.
        //if last_active_ago > Duration::seconds(600) {
        //    warn!(
        //        "Miner: {} not active since {}. Disconnecting",
        //        self.id, last_active
        //    );
        //    self.ban().await;
        //    return Ok(());
        //}

        let msg_string = serde_json::to_string(&message)?;

        trace!("Sending message: {}", msg_string.clone());

        let mut sender = self.sender.lock().await;

        //@todo this feels inefficient, maybe we do send bytes here.
        sender.send(SendInformation::Json(msg_string)).await?;
        // stream.write_all(b"\n").await?;

        Ok(())
    }

    pub async fn send_raw(&self, message: Buffer) -> Result<()> {
        let mut sender = self.sender.lock().await;

        sender.send(SendInformation::Raw(message)).await?;

        Ok(())
    }

    pub async fn upstream_send<T: Serialize>(&self, message: T) -> Result<()> {
        //let last_active = self.stats.lock().await.last_active;

        //let last_active_ago = Utc::now().naive_utc() - last_active;

        ////@todo rewrite this comment
        ////If the miner has not been active (sending shares) for 5 minutes, we disconnect this dude.
        ////@todo before live, check this guy. Also should come from options.
        ////@todo make the last_active thing a config.
        //if last_active_ago > Duration::seconds(600) {
        //    warn!(
        //        "Miner: {} not active since {}. Disconnecting",
        //        self.id, last_active
        //    );
        //    self.ban().await;
        //    return Ok(());
        //}

        let msg_string = serde_json::to_string(&message)?;

        debug!("Sending message: {}", msg_string.clone());

        let mut upstream_sender = self.upstream_sender.lock().await;

        //@todo this feels inefficient, maybe we do send bytes here.
        upstream_sender.send(msg_string).await?;
        // stream.write_all(b"\n").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,
            //@todo return error here.
            None => return Ok((json!(false), serde_json::Value::Null)),
        };

        Ok((values["result"].clone(), values["error"].clone()))
    }

    pub async fn shutdown(&self) {
        //@todo this should also have an internal stop_token, and each one of these should get
        //killed?
        self.info.write().await.state = ConnectionState::Disconnect;

        //This will kill everything that uses are own stop_token.
        //@todo might be able to get rid of connection state with this.
        *self.stop_source.lock().await = None;

        //Only returning a result here because we might want to add more functionality in the
        //future.
        //Here is where we actually will write upstream to KILL the connection if we are using that
        //proxy.
    }

    pub async fn disconnect(&self) {
        self.info.write().await.state = 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 fn id(&self) -> Uuid {
        self.id
    }

    //@todo logging in most of these functions is probably a large todo.
    pub async fn add_main_worker(&self, worker_id: Uuid) {
        let conn_info = self.get_connection_info().await;
        let user_info = self.get_user_info().await;
        let session_id = self.session_id;

        //@todo we can not be as strict on difficulty here, but I suppose might as well keep it too
        //doesn't matter.
        let worker = Miner::new(
            worker_id,
            conn_info.client.to_owned(),
            user_info.worker_name.to_owned(),
            Buffer::from(session_id.to_le_bytes().to_vec()),
            self.options.clone(),
            format_difficulty(self.difficulty.lock().await.clone()),
        );

        *self.connection_miner.lock().await = Some(worker);
    }

    pub async fn get_main_worker(&self) -> Option<Miner> {
        self.connection_miner.lock().await.clone()
    }

    pub async fn register_worker(
        &self,
        session_id: u32,
        client_agent: &str,
        worker_name: &str,
        worker_id: Uuid,
    ) {
        let worker = Miner::new(
            worker_id,
            Some(client_agent.to_owned()),
            Some(worker_name.to_owned()),
            Buffer::from(session_id.to_le_bytes().to_vec()),
            self.options.clone(),
            format_difficulty(self.difficulty.lock().await.clone()),
        );

        self.miner_list.add_miner(session_id, worker).await;

        //@todo one large thing we are missing here, and it's probs just for the above library but
        //EVENTS so new event for new worker.
    }

    pub async fn unregister_worker(&self, session_id: u32) -> Option<Miner> {
        self.miner_list.remove_miner(session_id).await
    }

    pub async fn get_worker_list(&self) -> MinerList {
        self.miner_list.clone()
    }

    pub async fn get_worker_by_session_id(&self, session_id: u32) -> Option<Miner> {
        self.miner_list.get_miner_by_id(session_id).await
    }

    pub async fn update_worker_by_session_id(&self, session_id: u32, miner: Miner) {
        self.miner_list
            .update_miner_by_session_id(session_id, miner)
            .await;
    }

    // ===== Worker Helper functions ===== //
    pub async fn set_user_info(
        &self,
        account_id: i32,
        mining_account_id: i32,
        worker_name: Option<String>,
    ) {
        let mut user_info = self.user_info.lock().await;
        user_info.account_id = account_id;
        user_info.mining_account = mining_account_id;
        //@tood idk if we need this here actually.
        user_info.worker_name = worker_name;
    }

    pub async fn get_user_info(&self) -> UserInfo {
        self.user_info.lock().await.clone()
    }

    pub async fn set_client(&self, client: &str) {
        let mut agent = false;
        let mut long_timeout = false;
        //@todo we need to do some checking/pruning etc of this client string.

        if client.starts_with("btccom-agent/") {
            //Agent
            agent = true;
            long_timeout = true;
        }

        let mut info = self.info.write().await;
        info.agent = agent;
        info.client = Some(client.to_string());
        info.is_long_timeout = long_timeout;
    }

    pub async fn get_connection_info(&self) -> ConnectionInfo {
        self.info.read().await.clone()
    }

    pub async fn is_long_timeout(&self) -> bool {
        self.info.read().await.is_long_timeout
    }

    pub fn get_session_id(&self) -> u32 {
        self.session_id
    }

    pub async fn authorized(&self) -> bool {
        self.info.read().await.authorized
    }

    pub async fn authorize(&self) {
        self.info.write().await.authorized = true;
    }

    pub async fn subscribed(&self) -> bool {
        self.info.read().await.subscribed
    }

    pub async fn subscribe(&self) {
        self.info.write().await.subscribed = true;
    }

    pub async fn is_agent(&self) -> bool {
        self.info.read().await.agent
    }

    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 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
        }
    }

    //Consider making this pub(crate)? Although, I think it could be useful for other things.
    pub fn get_stop_token(&self) -> StopToken {
        self.stop_token.clone()
    }
}