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
use std::collections::HashMap;
use reqwest;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde_json::json;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use base64::encode;
use failure;

use super::error::APIError;
use super::utils::get_time;
use super::model::Method;

// Alias for HMAC-SHA256
type HmacSha256 = Hmac<Sha256>;

#[derive(Debug, Clone)]
pub struct Credentials {
    api_key: String,
    secret_key: String,
    passphrase: String,
}

impl Credentials {
    pub fn new(api_key: &str, secret_key: &str, passphrase: &str) -> Self {
        Credentials{
            api_key: api_key.to_string(),
            secret_key: secret_key.to_string(),
            passphrase: passphrase.to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub enum KucoinEnv {
    Live,
    Sandbox,
}

#[derive(Debug, Clone)]
pub struct Kucoin {
    credentials: Option<Credentials>,
    environment: KucoinEnv,
    pub prefix: String,
    pub client: reqwest::Client,
}

impl Kucoin {
    pub fn new(environment: KucoinEnv, credentials: Option<Credentials>) -> Result<Self, failure::Error> {
        let client = reqwest::Client::builder()
            .use_rustls_tls()
            .build()?;
        let prefix = match environment {
            KucoinEnv::Live => String::from("https://openapi-v2.kucoin.com"),
            KucoinEnv::Sandbox => String::from("https://openapi-sandbox.kucoin.com"),
        };
        Ok(Kucoin {
            credentials,
            environment,
            prefix,
            client,
        })
    }

    // Generic get request for internal library use.
    // Matches credentials for signed vs. unsigned API calls
    pub async fn get(&self, url: String, sign: Option<HeaderMap>) -> Result<reqwest::Response, APIError> {
        let req_url = reqwest::Url::parse(&url).unwrap();
        match sign {
            Some(sign) => {
                let resp = self.client.get(req_url)
                    .headers(sign)
                    .send()
                    .await?;
                if resp.status().is_success() {
                    Ok(resp)
                } else {
                    Ok(resp)
                }
            },
            None => {
                let resp = self.client.get(req_url).send().await?;
                if resp.status().is_success() {
                    Ok(resp)
                } else {
                    Ok(resp)
                }
            }
        }
    }

    pub async fn post(&self, 
        url: String, 
        sign: Option<HeaderMap>, 
        params: Option<HashMap<String, String>>) 
    -> Result<reqwest::Response, APIError> {
        let req_url = reqwest::Url::parse(&url).unwrap();
        if let Some(s) = sign {
            if let Some(p) = params {
                let resp = self.client.post(req_url)
                    .headers(s)
                    .json(&json!(p))
                    .send()
                    .await?;
                if resp.status().is_success() {
                    Ok(resp)
                } else {
                    Ok(resp)
                }
            } else {
                let resp = self.client.post(req_url)
                    .headers(s)
                    .send()
                    .await?;
                 if resp.status().is_success() {
                    Ok(resp)
                } else if resp.status().is_server_error() {
                    Ok(resp)
                } else {
                    Ok(resp)
                }
            }
        } else {
            panic!("Unsigned POST request...")
        }
    }

    pub async fn delete(&self, 
        url: String, 
        sign: Option<HeaderMap>)
    -> Result<reqwest::Response, APIError> {
        let req_url = reqwest::Url::parse(&url).unwrap();
        if let Some(s) = sign {
            let resp = self.client.delete(req_url)
                .headers(s)
                .send()
                .await?;
            if resp.status().is_success() {
                Ok(resp)
            } else if resp.status().is_server_error() {
                Ok(resp)
            } else {
                Ok(resp)
            }
        } else {
            panic!("Unsigned DELETE request...")
        }
    }

    pub fn sign_headers(&self, 
        endpoint: String, 
        params: Option<&HashMap<String, String>>, 
        query: Option<String>,
        method: Method) 
    -> Result<HeaderMap, failure::Error> {
        let mut headers = HeaderMap::new();
        let nonce = get_time().to_string();
        let mut api_key: &str = "";
        let mut secret_key: &str = "";
        let mut passphrase: &str = "";
        let mut str_to_sign: String = String::new();
        match &self.credentials {
            Some(c) => {
                api_key = &c.api_key;
                secret_key = &c.secret_key;
                passphrase = &c.passphrase;
            },
            None => (),
        }
        match method {
            Method::GET => { 
                let meth = "GET";
                if let Some(q) = query {
                    // let query = format_query(&p);
                    str_to_sign = format!("{}{}{}{}", nonce, meth, endpoint, q);
                } else {
                    str_to_sign = format!("{}{}{}", nonce, meth, endpoint)  
                }
            },
            Method::POST => {
                let meth = "POST";
                if let Some(p) = params {
                    let q = json!(&p);
                    str_to_sign = format!("{}{}{}{}", nonce, meth, endpoint, q);
                } else {
                    str_to_sign = format!("{}{}{}", nonce, meth, endpoint) 
                }
            },
            Method::PUT => {},
            Method::DELETE => {
                let meth = "DELETE";
                if let Some(q) = query {
                    // let query = format_query(&p);
                    str_to_sign = format!("{}{}{}{}", nonce, meth, endpoint, q);
                } else {
                    str_to_sign = format!("{}{}{}", nonce, meth, endpoint)  
                }
            }
        }
        let mut mac = HmacSha256::new_varkey(secret_key.as_bytes())
            .expect("HMAC can take key of any size");
        mac.input(str_to_sign.as_bytes());
        let result = mac.result();
        let code_bytes = result.code();
        let digest = encode(&code_bytes);
        headers.insert(HeaderName::from_static("kc-api-key"), HeaderValue::from_str(&api_key).unwrap());
        headers.insert(HeaderName::from_static("kc-api-sign"), HeaderValue::from_str(&digest).unwrap());
        headers.insert(HeaderName::from_static("kc-api-timestamp"), HeaderValue::from_str(&nonce).unwrap());
        headers.insert(HeaderName::from_static("kc-api-passphrase"), HeaderValue::from_str(&passphrase).unwrap());
        Ok(headers)
    }
}