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
//! Bittrex API.

#![forbid(anonymous_parameters)]
#![warn(clippy::pedantic)]
#![deny(
    clippy::all,
    variant_size_differences,
    unused_results,
    unused_qualifications,
    unused_import_braces,
    unsafe_code,
    trivial_numeric_casts,
    trivial_casts,
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    unused_extern_crates
)]
// Allowing these for now.
#![allow(clippy::similar_names)]

mod private;
mod public;
pub mod types;

use chrono::Utc;
use failure::{format_err, Error};
use lazy_static::lazy_static;
use reqwest::{
    header::{HeaderMap, HeaderValue},
    Url,
};
use serde::Deserialize;

pub use crate::public::OrderBookType;

/// API URL.
lazy_static! {
    static ref API_URL: Url = Url::parse("https://bittrex.com/api/v1.1/").unwrap();
}

/// Bittrex API client.
#[derive(Debug)]
pub struct Client {
    /// Inner reqwest client.
    inner: reqwest::Client,
    /// API key.
    api_key: Option<String>,
    /// API secret.
    api_secret: Option<String>,
}

impl Default for Client {
    fn default() -> Self {
        Self {
            inner: reqwest::Client::new(),
            api_key: None,
            api_secret: None,
        }
    }
}

impl Client {
    /// Logs the client in for future private method access.
    ///
    /// Note: This will not perform any request to Bittrex, it will only store the API key and the
    /// secret for future use.
    pub fn login<K: Into<String>, S: Into<String>>(&mut self, api_key: K, api_secret: S) {
        self.api_key = Some(api_key.into());
        self.api_secret = Some(api_secret.into());
    }

    /// Appends the login information to the query string.
    ///
    /// **Note: it will panic if not logged in.**
    fn append_login(&self, url: &mut Url) {
        let api_key = self.api_key.as_ref().unwrap();
        let nonce = Utc::now().timestamp();
        let _ = url
            .query_pairs_mut()
            .append_pair("apikey", api_key)
            .append_pair("nonce", &format!("{}", nonce));
    }

    /// Gets the headers for the given URL.
    ///
    /// **Note: it will panic if not logged in.**
    fn get_headers(&self, url: &Url) -> Result<HeaderMap, Error> {
        let mut headers = HeaderMap::new();
        let hash = self.hash_uri(url);
        let _ = headers.insert("apisign", HeaderValue::from_str(&hash?)?);
        Ok(headers)
    }

    /// Hash the given URI with the logged in API secret.
    ///
    /// **Note: it will panic if not logged in.**
    fn hash_uri(&self, url: &Url) -> Result<String, Error> {
        use hex::ToHex;
        use hmac::{Hmac, Mac};
        use sha2::Sha512;

        let api_secret = self
            .api_secret
            .as_ref()
            .expect("the client was not logged in");
        let mut hmac = Hmac::<Sha512>::new_varkey(api_secret.as_bytes())
            .map_err(|_| format_err!("invalid key length"))?;
        hmac.input(url.as_str().as_ref());

        let mut res = String::new();
        hmac.result().code().as_slice().write_hex(&mut res)?;
        Ok(res)
    }
}

/// API result structure.
#[derive(Debug, Clone, Deserialize)]
struct ApiResult<R> {
    /// Wether the API call was successful.
    success: bool,
    /// The message returned in the API call.
    message: String,
    /// The result of the API call.
    result: Option<R>,
}

impl<R> ApiResult<R>
where
    R: for<'r> Deserialize<'r>,
{
    /// Converts the API result to a generic result, returning an error if the request was not
    /// successful.
    fn into_result(self) -> Result<R, Error> {
        if self.success {
            if let Some(r) = self.result {
                Ok(r)
            } else {
                Err(format_err!("invalid result in success response"))
            }
        } else {
            Err(format_err!("{}", self.message))
        }
    }
}