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
use async_std::net::TcpStream;
use async_std::sync::{Arc, Mutex};
use futures::io::BufReader;
use futures::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
use futures::io::{ReadHalf, WriteHalf};
use serde::Serialize;
use std::time::SystemTime;
use stratum_types::params::{ClientParam, PoolParam};
use stratum_types::traits::{AuthManager, BlockValidator, DataProvider, StratumManager};
use stratum_types::traits::{PoolParams, StratumParams};
use stratum_types::Result;
use stratum_types::{
    ClientPacket, ClientRequest, ClientResponse, MinerInfo, PoolRequest, PoolResponse,
    StratumMethod,
};
use uuid::Uuid;

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

#[derive(Debug)]
pub struct Connection<SM: StratumManager> {
    pub id: String,
    pub write_half: Arc<Mutex<WriteHalf<TcpStream>>>,
    pub read_half: Arc<Mutex<BufReader<ReadHalf<TcpStream>>>>,
    pub authorized: Arc<Mutex<bool>>,
    pub data_provider: Arc<SM::DataProvider>,
    pub block_validator: Arc<SM::BlockValidator>,
    pub auth_manager: Arc<SM::AuthManager>,
    pub session_start: SystemTime,
    pub state: Mutex<State>,
}

impl<SM> Connection<SM>
where
    SM: StratumManager,
{
    pub fn new(
        stream: TcpStream,
        data_provider: Arc<SM::DataProvider>,
        auth_manager: Arc<SM::AuthManager>,
        block_validator: Arc<SM::BlockValidator>,
    ) -> Self {
        //@todo could store this as a UUID type as well.
        let id = Uuid::new_v4().to_string();

        let (rh, wh) = stream.split();
        Connection {
            id,
            write_half: Arc::new(Mutex::new(wh)),
            read_half: Arc::new(Mutex::new(BufReader::new(rh))),
            authorized: Arc::new(Mutex::new(false)),
            data_provider,
            auth_manager,
            block_validator,
            session_start: SystemTime::now(),
            state: Mutex::new(State::Connected),
        }
    }

    pub async fn start(&self) -> Result<()> {
        loop {
            if *self.state.lock().await == State::Disconnect {
                break;
            }

            let msg: ClientPacket<SM::PoolParams, SM::StratumParams> = self.next_message().await?;

            match msg {
                ClientPacket::Request(req) => self.handle_requests(req).await?,
                ClientPacket::Response(res) => self.handle_responses(res).await?,
            };
        }

        Ok(())
    }

    pub async fn handle_requests(
        &self,
        req: ClientRequest<SM::PoolParams, SM::StratumParams>,
    ) -> Result<()> {
        if let ClientParam::Authorize(auth) = &req.params {
            return Ok(self.handle_authorize(auth).await?);
        }

        let authorized = self.authorized.lock().await;
        if !*authorized {
            //This would be a huge ban
            // return Err(Error::;
            //@todo needs to return an error here.
            return Ok(());
        }

        match &req.params {
            ClientParam::Submit(value) => self.handle_submit(value).await?,
            ClientParam::Subscribe(value) => self.handle_subscribe(value).await?,
            ClientParam::Unknown(value) => self.handle_unknown(value).await?,
            ClientParam::Authorize(_) => {}
        };
        Ok(())
    }

    pub async fn handle_responses(
        &self,
        res: ClientResponse<SM::PoolParams, SM::StratumParams>,
    ) -> Result<()> {
        //@todo maybe throw this into a function - "checkAuth" then error is easier to throw
        let authorized = self.authorized.lock().await;
        if !*authorized {
            //This would be a huge ban
            // return Err(Error::;
            //@todo needs to return an error here.
            return Ok(());
        }

        Ok(())
    }

    //This needs to be either clientRequest OR clientResponse
    // pub async fn next_message(&self) -> Result<ClientRequest<SM::PoolParams, SM::StratumParams>> {
    pub async fn next_message(&self) -> Result<ClientPacket<SM::PoolParams, SM::StratumParams>> {
        loop {
            let mut stream = self.read_half.lock().await;

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

            if !buf.is_empty() {
                //@smells
                buf = buf.trim().to_owned();
                let msg: ClientPacket<SM::PoolParams, SM::StratumParams> =
                    serde_json::from_str(&buf)?;

                return Ok(msg);
            };
        }
    }

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

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

        stream.write_all(&msg).await?;

        //End the message here @todo not sure if this works.
        stream.write_all(b"\n").await?;

        Ok(())
    }

    //Helper function to make sending requests more simple.
    async fn send_request(
        &self,
        method: StratumMethod,
        params: PoolParam<SM::PoolParams, SM::StratumParams>,
    ) -> Result<()> {
        let request = PoolRequest {
            //@todo
            id: "".to_owned(),
            method,
            params,
        };

        Ok(self.send(request).await?)
    }

    async fn send_response(
        &self,
        method: StratumMethod,
        result: PoolParam<SM::PoolParams, SM::StratumParams>,
    ) -> Result<()> {
        let response = PoolResponse {
            id: self.id.clone(),
            method,
            result,
            error: None,
        };

        Ok(self.send(response).await?)
    }

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

        //Only returning a result here because we might want to add more functionality in the
        //future.
        Ok(())
    }

    // ===== Handler Functions ===== //
    pub async fn handle_authorize(
        &self,
        auth: &<SM::PoolParams as PoolParams>::Authorize,
    ) -> Result<()> {
        //@todo put this above into the struct
        let miner_info = Arc::new(MinerInfo {
            ip: "127.0.0.1".parse().unwrap(),
        });

        //@todo this needs to be either be forced to be a bool, or we need ot add a function here
        //that is authorized.is_authorized() so that we can set the internal auth to true.
        let authorized = self.auth_manager.authorize(miner_info, &auth).await?;

        self.send_response(
            StratumMethod::Authorize,
            PoolParam::AuthorizeResult(authorized),
        )
        .await?;

        // if authorized {
        //     *self.authorized.lock().await = authorized;
        // } else {
        //     self.shutdown().await?;
        // }
        // if authorized {
        *self.authorized.lock().await = true;
        // } else {
        //     self.shutdown().await?;
        // }

        //Send work @todo this should probably be "init subscribe or something like that".
        //But this is just to get it working on the client.
        self.send_work().await?;

        Ok(())
    }

    pub async fn send_work(&self) -> Result<()> {
        let job = self.data_provider.get_job().await?;

        self.send_request(StratumMethod::Notify, PoolParam::Notify(job))
            .await?;

        Ok(())
    }

    pub async fn handle_submit(
        &self,
        share: &<SM::StratumParams as StratumParams>::Submit,
    ) -> Result<()> {
        //@todo put this above into the struct
        let miner_info = Arc::new(MinerInfo {
            ip: "127.0.0.1".parse().unwrap(),
        });

        dbg!("Handling submit message");

        let valid = self
            .block_validator
            .validate_share(miner_info, share.clone())
            .await?;

        dbg!("Called validate share");

        // let response = PoolResponse {
        //     id: self.id.clone(),
        //     method: StratumMethod::Submit,
        //     result: PoolParams::SubmitResult(valid),
        //     error: None,
        // };

        // self.send(&response).await?;

        //Send a response to the miner @todo
        Ok(())
    }

    pub async fn handle_subscribe(
        &self,
        subscribe: &<SM::StratumParams as StratumParams>::Subscribe,
    ) -> Result<()> {
        //@todo put this above into the struct
        let miner_info = Arc::new(MinerInfo {
            ip: "127.0.0.1".parse().unwrap(),
        });

        //@todo rename this to something that makes more sense
        // self..subscribe(miner_info, &subscribe).await?;

        //Send a response to the miner @todo
        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(())
    }
}