use std::{
marker::PhantomData,
time::SystemTime,
};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::json;
use generic_api_client::{http::{*, header::HeaderValue}, websocket::*};
use crate::traits::*;
pub type CoincheckRequestResult<T> = Result<T, CoincheckRequestError>;
pub type CoincheckRequestError = RequestError<&'static str, CoincheckHandlerError>;
pub enum CoincheckOption {
Default,
Key(String),
Secret(String),
HttpUrl(CoincheckHttpUrl),
HttpAuth(bool),
RequestConfig(RequestConfig),
WebSocketUrl(CoincheckWebSocketUrl),
WebSocketChannels(Vec<String>),
WebSocketConfig(WebSocketConfig),
}
#[derive(Clone, Debug)]
pub struct CoincheckOptions {
pub key: Option<String>,
pub secret: Option<String>,
pub http_url: CoincheckHttpUrl,
pub http_auth: bool,
pub request_config: RequestConfig,
pub websocket_url: CoincheckWebSocketUrl,
pub websocket_channels: Vec<String>,
pub websocket_config: WebSocketConfig,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum CoincheckHttpUrl {
Default,
None,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[non_exhaustive]
pub enum CoincheckWebSocketUrl {
Default,
None,
}
#[derive(Debug)]
pub enum CoincheckHandlerError {
ApiError(serde_json::Value),
RequestLimitExceeded(serde_json::Value),
ParseError,
}
pub struct CoincheckRequestHandler<'a, R: DeserializeOwned> {
options: CoincheckOptions,
_phantom: PhantomData<&'a R>,
}
pub struct CoincheckWebSocketHandler {
message_handler: Box<dyn FnMut(serde_json::Value) + Send>,
options: CoincheckOptions,
}
impl<'a, B, R> RequestHandler<B> for CoincheckRequestHandler<'a, R>
where
B: Serialize,
R: DeserializeOwned,
{
type Successful = R;
type Unsuccessful = CoincheckHandlerError;
type BuildError = &'static str;
fn request_config(&self) -> RequestConfig {
let mut config = self.options.request_config.clone();
if self.options.http_url != CoincheckHttpUrl::None {
config.url_prefix = self.options.http_url.as_str().to_owned();
}
config
}
fn build_request(&self, mut builder: RequestBuilder, request_body: &Option<B>, _: u8) -> Result<Request, Self::BuildError> {
if let Some(body) = request_body {
let encoded = serde_urlencoded::to_string(body).or(Err("could not serialize body as application/x-www-form-urlencoded"))?;
builder = builder
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(encoded);
}
let mut request = builder.build().or(Err("failed to build request"))?;
if self.options.http_auth {
let time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); let nonce = time.as_millis() as u64;
let body = request.body()
.and_then(|body| body.as_bytes())
.map(String::from_utf8_lossy)
.unwrap_or_default();
let sign_contents = format!("{}{}{}", nonce, request.url(), body);
let secret = self.options.secret.as_deref().ok_or("API secret not set")?;
let mut hmac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
hmac.update(sign_contents.as_bytes());
let signature = hex::encode(hmac.finalize().into_bytes());
let key = HeaderValue::from_str(self.options.key.as_deref().ok_or("API key not set")?).or(
Err("invalid character in API key")
)?;
let headers = request.headers_mut();
headers.insert("ACCESS-KEY", key);
headers.insert("ACCESS-NONCE", HeaderValue::from(nonce));
headers.insert("ACCESS-SIGNATURE", HeaderValue::from_str(&signature).unwrap()); }
Ok(request)
}
fn handle_response(&self, status: StatusCode, _: HeaderMap, response_body: Bytes) -> Result<Self::Successful, Self::Unsuccessful> {
if status.is_success() {
serde_json::from_slice(&response_body).map_err(|error| {
log::debug!("Failed to parse response due to an error: {}", error);
CoincheckHandlerError::ParseError
})
} else {
let error = match serde_json::from_slice(&response_body) {
Ok(parsed_error) => {
if status == 429 {
CoincheckHandlerError::RequestLimitExceeded(parsed_error)
} else {
CoincheckHandlerError::ApiError(parsed_error)
}
},
Err(error) => {
log::debug!("Failed to parse error response due to an error: {}", error);
CoincheckHandlerError::ParseError
}
};
Err(error)
}
}
}
impl WebSocketHandler for CoincheckWebSocketHandler {
fn websocket_config(&self) -> WebSocketConfig {
let mut config = self.options.websocket_config.clone();
if self.options.websocket_url != CoincheckWebSocketUrl::None {
config.url_prefix = self.options.websocket_url.as_str().to_owned();
}
config
}
fn handle_start(&mut self) -> Vec<WebSocketMessage> {
self.options.websocket_channels.clone().into_iter().map(|channel| {
WebSocketMessage::Text(json!({ "type": "subscribe", "channel": channel }).to_string())
}).collect()
}
fn handle_message(&mut self, message: WebSocketMessage) -> Vec<WebSocketMessage> {
match message {
WebSocketMessage::Text(message) => {
match serde_json::from_str(&message) {
Ok(message) => (self.message_handler)(message),
Err(_) => log::debug!("Invalid JSON message received"),
};
},
WebSocketMessage::Binary(_) => log::debug!("Unexpected binary message received"),
WebSocketMessage::Ping(_) | WebSocketMessage::Pong(_) => (),
}
vec![]
}
}
impl CoincheckHttpUrl {
#[inline(always)]
fn as_str(&self) -> &'static str {
match self {
Self::Default => "https://coincheck.com",
Self::None => "",
}
}
}
impl CoincheckWebSocketUrl {
#[inline(always)]
fn as_str(&self) -> &'static str {
match self {
Self::Default => "wss://ws-api.coincheck.com/",
Self::None => "",
}
}
}
impl HandlerOptions for CoincheckOptions {
type OptionItem = CoincheckOption;
fn update(&mut self, option: Self::OptionItem) {
match option {
CoincheckOption::Default => (),
CoincheckOption::Key(v) => self.key = Some(v),
CoincheckOption::Secret(v) => self.secret = Some(v),
CoincheckOption::HttpUrl(v) => self.http_url = v,
CoincheckOption::HttpAuth(v) => self.http_auth = v,
CoincheckOption::RequestConfig(v) => self.request_config = v,
CoincheckOption::WebSocketUrl(v) => self.websocket_url = v,
CoincheckOption::WebSocketChannels(v) => self.websocket_channels = v,
CoincheckOption::WebSocketConfig(v) => self.websocket_config = v,
}
}
}
impl Default for CoincheckOptions {
fn default() -> Self {
let mut websocket_config = WebSocketConfig::new();
websocket_config.ignore_duplicate_during_reconnection = true;
Self {
key: None,
secret: None,
http_url: CoincheckHttpUrl::Default,
http_auth: false,
request_config: RequestConfig::default(),
websocket_url: CoincheckWebSocketUrl::Default,
websocket_channels: vec![],
websocket_config,
}
}
}
impl<'a, R, B> HttpOption<'a, R, B> for CoincheckOption
where
R: DeserializeOwned + 'a,
B: Serialize,
{
type RequestHandler = CoincheckRequestHandler<'a, R>;
#[inline(always)]
fn request_handler(options: Self::Options) -> Self::RequestHandler {
CoincheckRequestHandler::<'a, R> {
options,
_phantom: PhantomData,
}
}
}
impl<H: FnMut(serde_json::Value) + Send + 'static> WebSocketOption<H> for CoincheckOption {
type WebSocketHandler = CoincheckWebSocketHandler;
#[inline(always)]
fn websocket_handler(handler: H, options: Self::Options) -> Self::WebSocketHandler {
CoincheckWebSocketHandler {
message_handler: Box::new(handler),
options,
}
}
}
impl HandlerOption for CoincheckOption {
type Options = CoincheckOptions;
}
impl Default for CoincheckOption {
fn default() -> Self {
Self::Default
}
}