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
use crate::router::Router;
use async_std::net::{SocketAddr, TcpStream};
use async_std::sync::{Arc, Mutex, RwLock};
use chrono::{NaiveDateTime, Utc};
use futures::io::BufReader;
use futures::io::{AsyncBufReadExt, AsyncWriteExt};
use futures::io::{ReadHalf, WriteHalf};
use log::{debug, info};
use serde::Serialize;
use serde_json::{Map, Value};
use std::time::SystemTime;
use stratum_types::params::{Params, Results, SetDiff};
use stratum_types::Result;
use stratum_types::{
    Error, MinerInfo, MinerJobStats, Request, Response, StratumError, StratumMethod, ID,
};
use uuid::Uuid;

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

//@todo Review which of these we need Mutexs/Arcs/etc. Might be over indulging here.
//@todo change the ID of this miner to the ID provided by the pool after subscribing/authing is
//done. Can just be a check in each one of those handles if the other one has already been
//completed.
#[derive(Debug)]
pub struct Connection {
    pub id: ID,
    pub write_half: Arc<Mutex<WriteHalf<TcpStream>>>,
    pub read_half: Arc<Mutex<BufReader<ReadHalf<TcpStream>>>>,
    pub authorized: Arc<Mutex<bool>>,
    pub session_start: SystemTime,
    pub connection_state: Mutex<ConnectionState>,
    pub subscribed: Arc<Mutex<bool>>,
    pub subscriber_id: Arc<Mutex<String>>,
    pub miner_info: Arc<RwLock<MinerInfo>>,
    //Possibly pull these out into their own var.
    //Makes it easier to operate on them.
    pub difficulty: Arc<Mutex<f64>>,
    pub submissions: Arc<Mutex<u64>>,
    pub last_retarget: Arc<Mutex<SystemTime>>,
    pub next_difficulty: Arc<Mutex<f64>>,
    pub job_stats: Arc<Mutex<JobStats>>,
    pub options: Arc<MinerOptions>,
    pub stats: Arc<Mutex<MinerStats>>,
    pub needs_ban: Arc<Mutex<bool>>,
    pub var_diff: bool,
    pub ban_stats: Arc<Mutex<BanStats>>,
    pub classic: Arc<Mutex<bool>>,
    pub last_message_id: Arc<Mutex<ID>>,
}

//@todo probably move these over to types.
#[derive(Debug, Default)]
pub struct JobStats {
    last_share_timestamp: i64,
    last_retarget: i64,
    times: Vec<i64>,
    current_difficulty: f64,
    job_difficulty: f64,
}

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

#[derive(Debug, Clone)]
pub struct MinerStats {
    accepted_shares: u64,
    rejected_shares: u64,
    last_active: NaiveDateTime,
}

#[derive(Debug)]
pub struct BanStats {
    accepted_shares: u64,
    rejected_shares: u64,
    last_active: NaiveDateTime,
}

impl Connection {
    pub fn new(
        addr: SocketAddr,
        rh: BufReader<ReadHalf<TcpStream>>,
        wh: WriteHalf<TcpStream>,
        var_diff: bool,
        initial_difficulty: f64,
        //@todo we should probably kill this, but for now it has to live here to make things
        //easier.
    ) -> Self {
        //@todo could store this as a UUID type as well.
        let id = Uuid::new_v4().to_string();

        info!("Accepting new miner. ID: {}", &id);

        let info = MinerInfo {
            ip: addr.ip(),
            auth: None,
            id: None,
            sid: None,
            job_stats: None,
            worker_name: None,
        };

        let options = MinerOptions {
            retarget_time: 120,
            target_time: 6.0,
            min_diff: 0.0001,
            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: 30,
            share_time_min: 4.2,
            share_time_max: 7.8,
        };

        //Make this an impl on stats same for each above. That way we can just do minerstats::new(current_time)
        let stats = MinerStats {
            accepted_shares: 0,
            rejected_shares: 0,
            last_active: Utc::now().naive_utc(),
        };

        let ban_stats = BanStats {
            accepted_shares: 0,
            rejected_shares: 0,
            last_active: Utc::now().naive_utc(),
        };

        Connection {
            id: ID::Str(id),
            write_half: Arc::new(Mutex::new(wh)),
            read_half: Arc::new(Mutex::new(rh)),
            authorized: Arc::new(Mutex::new(false)),
            session_start: SystemTime::now(),
            connection_state: Mutex::new(ConnectionState::Connected),
            subscribed: Arc::new(Mutex::new(false)),
            //@todo this should be passed in.
            difficulty: Arc::new(Mutex::new(initial_difficulty)),
            subscriber_id: Arc::new(Mutex::new(String::new())),
            miner_info: Arc::new(RwLock::new(info)),
            submissions: Arc::new(Mutex::new(0)),
            last_retarget: Arc::new(Mutex::new(SystemTime::now())),
            next_difficulty: Arc::new(Mutex::new(0.0)),
            job_stats: Arc::new(Mutex::new(Default::default())),
            options: Arc::new(options),
            stats: Arc::new(Mutex::new(stats)),
            var_diff,
            needs_ban: Arc::new(Mutex::new(false)),
            ban_stats: Arc::new(Mutex::new(ban_stats)),
            classic: Arc::new(Mutex::new(false)),
            last_message_id: Arc::new(Mutex::new(ID::Str(String::from("")))),
        }
    }

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

    pub async fn is_disconnected(&self) -> bool {
        *self.connection_state.lock().await == ConnectionState::Disconnect
    }

    pub async fn next_message(
        &self,
    ) -> Result<(String, serde_json::map::Map<String, serde_json::Value>)> {
        //I don't actually think this has to loop here.
        loop {
            let mut stream = self.read_half.lock().await;

            let mut buf = String::new();
            let num_bytes = stream.read_line(&mut buf).await?;

            if num_bytes == 0 {
                self.shutdown().await?;
                return Err(Error::StreamClosed);
            }

            if !buf.is_empty() {
                //@smells
                buf = buf.trim().to_owned();
                debug!("Received Message: {}", &buf);
                dbg!(&buf);
                let msg: Map<String, Value> = serde_json::from_str(&buf)?;

                let method = if msg.contains_key("method") {
                    match msg.get("method") {
                        Some(method) => method.as_str(),
                        //@todo need better stratum erroring here.
                        None => return Err(Error::MethodDoesntExist),
                    }
                } else if msg.contains_key("messsage") {
                    match msg.get("message") {
                        Some(method) => method.as_str(),
                        //@todo need better stratum erroring here.
                        None => return Err(Error::MethodDoesntExist),
                    }
                } else {
                    return Err(Error::MethodDoesntExist);
                };

                if let Some(method_string) = method {
                    return Ok((method_string.to_owned(), msg));
                } else {
                    //@todo improper format
                    return Err(Error::MethodDoesntExist);
                }
            };
        }
    }

    async fn send<T: Serialize>(&self, message: T) -> Result<()> {
        let msg = serde_json::to_vec(&message)?;
        let msg_string = serde_json::to_string(&message)?;

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

        let mut stream = self.write_half.lock().await;

        stream.write_all(&msg).await?;
        stream.write_all(b"\n").await?;

        Ok(())
    }

    pub async fn shutdown(&self) -> Result<()> {
        *self.connection_state.lock().await = ConnectionState::Disconnect;

        //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.
        Ok(())
    }

    //Can probably not send avg here either.
    async fn retarget(&self, avg: f64, stats: &mut JobStats) -> Result<()> {
        // let mut stats = self.job_stats.lock().await;

        let mut new_difficulty = stats.current_difficulty * (self.options.target_time / avg);

        let delta = (new_difficulty - stats.current_difficulty).abs();

        if delta > self.options.max_delta {
            if new_difficulty > stats.current_difficulty {
                //@smells come back here later.
                new_difficulty = new_difficulty - (delta - self.options.max_delta);
            } else if new_difficulty < stats.current_difficulty {
                new_difficulty = new_difficulty + (delta - self.options.max_delta);
            }
        }

        if new_difficulty < self.options.min_diff {
            new_difficulty = self.options.min_diff;
        } else if new_difficulty > stats.job_difficulty {
            new_difficulty = stats.job_difficulty;
        }

        if new_difficulty < stats.current_difficulty || new_difficulty > stats.current_difficulty {
            stats.last_retarget = Utc::now().timestamp();

            //Clear some of the stats.
            stats.times = Vec::new();
            stats.current_difficulty = new_difficulty;
            let job_stats = MinerJobStats {
                expected_difficulty: new_difficulty,
            };
            self.miner_info.write().await.job_stats = Some(job_stats);

            // self.set_difficulty(stats.current_difficulty).await?;
        }

        Ok(())
    }

    //Unimplemented - Probably just log the value, and see what's going on.
    //Make a handle_unknown function that exists in stratum manager - then the pool can decide what
    //to do.
    pub async fn handle_unknown(&self, _msg: &serde_json::Value) -> Result<()> {
        Ok(())
    }

    pub async fn disconnect(&self) {
        *self.connection_state.lock().await = ConnectionState::Disconnect;
    }

    pub async fn ban(&self) {
        *self.needs_ban.lock().await = true;
    }

    pub async fn needs_ban(&self) -> bool {
        *self.needs_ban.lock().await
    }

    pub async fn get_stats(&self) -> MinerStats {
        self.stats.lock().await.clone()
    }
}