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
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 std::time::SystemTime;
use stratum_types::params::{
    AuthorizeParam, CapabilitiesParam, GetTransactionsParam, SubmitParam, SubscribeParam,
    SuggestDifficultyParam, SuggestTargetParam,
};
use stratum_types::params::{ClientParams, PoolParams};
use stratum_types::traits::{StratumManager, StratumPackets};
use stratum_types::Result;
use stratum_types::{ClientRequest, 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 manager: Arc<SM>,
    pub session_start: SystemTime,
    pub state: Mutex<State>,
}

impl<SM> Connection<SM>
where
    SM: StratumManager,
{
    pub fn new(stream: TcpStream, manager: Arc<SM>) -> 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)),
            manager,
            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: ClientRequest<SM::Params> = self.next_message().await?;

            //@todo see if we can speed things up with "continues" underneath each match section
            if let ClientParams::Authorize(auth) = &msg.params {
                self.handle_authorize(auth).await?;
                continue;
            }

            let authorized = self.authorized.lock().await;
            if !*authorized {
                break;
            }

            match &msg.params {
                ClientParams::Capabilities(value) => self.handle_capabilites(value).await?,
                ClientParams::ExtraNonceSubscribe => self.handle_extra_nonce_subscribe().await?,
                ClientParams::GetTransactions(value) => self.handle_get_transactions(value).await?,
                ClientParams::Submit(value) => self.handle_submit(value).await?,
                ClientParams::Subscribe(value) => self.handle_subscribe(value).await?,
                ClientParams::SuggestDifficulty(value) => {
                    self.handle_suggest_difficulty(value).await?
                }
                ClientParams::SuggestTarget(value) => self.handle_suggest_target(value).await?,
                ClientParams::Unknown(value) => self.handle_unknown(value).await?,
                ClientParams::Authorize(_) => {
                    continue;
                } // _ => {
                  //     break;
                  // }
            }
        }

        Ok(())
    }

    pub async fn next_message(&self) -> Result<ClientRequest<SM::Params>> {
        let mut stream = self.read_half.lock().await;

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

        let response: ClientRequest<SM::Params> = serde_json::from_str(&buf)?;

        Ok(response)
    }

    pub async fn send(&self, message: &PoolResponse<SM::Params>) -> 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(())
    }

    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,
        msg: &AuthorizeParam<<SM::Params as StratumPackets>::Authorize>,
    ) -> Result<()> {
        let authorized = self.manager.authorize(&msg.credentials).await?;

        let response = PoolResponse {
            id: self.id.clone(),
            method: StratumMethod::Authorize,
            result: PoolParams::AuthorizeResult(authorized),
            error: None,
        };

        self.send(&response).await?;

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

        Ok(())
    }

    //@todo remove most likely.
    pub async fn handle_capabilites(
        &self,
        _msg: &CapabilitiesParam<<SM::Params as StratumPackets>::Capabilities>,
    ) -> Result<()> {
        Ok(())
    }

    //@todo remove most likely.
    pub async fn handle_extra_nonce_subscribe(&self) -> Result<()> {
        Ok(())
    }

    //@todo remove - unimplemented right now.
    pub async fn handle_get_transactions(&self, _msg: &GetTransactionsParam) -> Result<()> {
        Ok(())
    }

    pub async fn handle_submit(
        &self,
        msg: &SubmitParam<<SM::Params as StratumPackets>::Submit>,
    ) -> Result<()> {
        //@todo rename msg.submit to msg.share
        self.manager.submit(&msg.submit).await?;

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

    pub async fn handle_subscribe(
        &self,
        msg: &SubscribeParam<<SM::Params as StratumPackets>::Subscribe>,
    ) -> Result<()> {
        //@todo rename this to something that makes more sense
        self.manager.subscribe(&msg.subscribe).await?;

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

    //Unimplemented - @todo
    pub async fn handle_suggest_difficulty(
        &self,
        _msg: &SuggestDifficultyParam<<SM::Params as StratumPackets>::SuggestDifficulty>,
    ) -> Result<()> {
        Ok(())
    }

    //Unimplemented - @todo
    pub async fn handle_suggest_target(
        &self,
        _msg: &SuggestTargetParam<<SM::Params as StratumPackets>::SuggestTarget>,
    ) -> Result<()> {
        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(())
    }
}