-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathkapi.cpp
More file actions
314 lines (256 loc) · 9.17 KB
/
Copy pathkapi.cpp
File metadata and controls
314 lines (256 loc) · 9.17 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <sstream>
#include <cstring>
#include <ctime>
#include <cerrno>
#include <openssl/buffer.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include "kapi.hpp"
#include "libjson/libjson.h"
using namespace std;
//------------------------------------------------------------------------------
namespace Kraken {
//------------------------------------------------------------------------------
// helper function to compute SHA256:
static std::vector<unsigned char>
sha256(const std::string& data)
{
std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, data.c_str(), data.length());
SHA256_Final(digest.data(), &ctx);
return digest;
}
//------------------------------------------------------------------------------
// helper function to decode a base64 string to a vector of bytes:
static std::vector<unsigned char>
b64_decode(const std::string& data)
{
BIO* b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO* bmem = BIO_new_mem_buf((void*)data.c_str(),data.length());
bmem = BIO_push(b64, bmem);
std::vector<unsigned char> output(data.length());
int decoded_size = BIO_read(bmem, output.data(), output.size());
BIO_free_all(bmem);
if (decoded_size < 0)
throw runtime_error("failed while decoding base64.");
return output;
}
//------------------------------------------------------------------------------
// helper function to encode a vector of bytes to a base64 string:
static std::string
b64_encode(const std::vector<unsigned char>& data)
{
BIO* b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO* bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, data.data(), data.size());
BIO_flush(b64);
BUF_MEM* bptr = NULL;
BIO_get_mem_ptr(b64, &bptr);
std::string output(bptr->data, bptr->length);
BIO_free_all(b64);
return output;
}
//------------------------------------------------------------------------------
// helper function to hash with HMAC algorithm:
static std::vector<unsigned char>
hmac_sha512(const std::vector<unsigned char>& data,
const std::vector<unsigned char>& key)
{
unsigned int len = EVP_MAX_MD_SIZE;
std::vector<unsigned char> digest(len);
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key.data(), key.size(), EVP_sha512(), NULL);
HMAC_Update(&ctx, data.data(), data.size());
HMAC_Final(&ctx, digest.data(), &len);
HMAC_CTX_cleanup(&ctx);
return digest;
}
//------------------------------------------------------------------------------
// constructor with all explicit parameters
KAPI::KAPI(const string& key, const string& secret,
const string& url, const string& version)
:key_(key), secret_(secret), url_(url), version_(version)
{
init();
}
//------------------------------------------------------------------------------
// default API base URL and API version
KAPI::KAPI(const string& key, const string& secret)
:key_(key), secret_(secret), url_("https://api.kraken.com"), version_("0")
{
init();
}
//------------------------------------------------------------------------------
// constructor with empty API key and API secret
KAPI::KAPI()
:key_(""), secret_(""), url_("https://api.kraken.com"), version_("0")
{
init();
}
//------------------------------------------------------------------------------
// initializes libcurl:
void KAPI::init()
{
curl_ = curl_easy_init();
if (curl_) {
curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curl_, CURLOPT_USERAGENT, "Kraken C++ API Client");
curl_easy_setopt(curl_, CURLOPT_POST, 1L);
// set callback function
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, KAPI::write_cb);
}
else
throw runtime_error("can't create curl handle");
}
//------------------------------------------------------------------------------
// distructor:
KAPI::~KAPI()
{
curl_easy_cleanup(curl_);
}
//------------------------------------------------------------------------------
// builds a query string from KAPI::Input:
std::string
KAPI::build_query(const KAPI::Input& input)
{
std::ostringstream oss;
KAPI::Input::const_iterator it = input.begin();
for (; it != input.end(); ++it) {
if (it != input.begin()) oss << '&'; // delimiter
oss << it->first <<'='<< it->second;
}
return oss.str();
}
//------------------------------------------------------------------------------
// helper function to create a nonce:
string KAPI::create_nonce()
{
ostringstream oss;
timeval tp;
if (gettimeofday(&tp, NULL) != 0) {
oss << "gettimeofday() failed: "
<< strerror(errno);
throw runtime_error(oss.str());
}
else {
// format output string
oss << std::setfill('0')
<< std::setw(10) << tp.tv_sec
<< std::setw(6) << tp.tv_usec;
}
return oss.str();
}
//------------------------------------------------------------------------------
// returns message signature generated from a URI path, a nonce
// and postdata, message signature is created as a follows:
//
// hmac_sha512(path + sha256(nonce + postdata), b64decode(secret))
//
// and the result is converted in a base64 string:
std::string
KAPI::message_signature(const std::string& path,
const std::string& nonce,
const std::string& postdata) const
{
// add path to data to encrypt
std::vector<unsigned char> data(path.begin(), path.end());
// concatenate nonce and postdata and compute SHA256
std::vector<unsigned char> nonce_postdata = sha256(nonce + postdata);
// concatenate path and nonce_postdata (path + sha256(nonce + postdata))
data.insert(data.end(), nonce_postdata.begin(), nonce_postdata.end());
// and compute HMAC
return b64_encode( hmac_sha512(data, b64_decode(secret_)) );
}
//------------------------------------------------------------------------------
// CURL write function callback:
size_t KAPI::write_cb(char* ptr, size_t size, size_t nmemb, void* userdata)
{
size_t real_size = size * nmemb;
string* response = reinterpret_cast<string*>(userdata);
string res(ptr, real_size);
response->swap(res);
return response->length();
}
//------------------------------------------------------------------------------
// deals with public API methods:
string KAPI::public_method(const string& method,
const KAPI::Input& input) const
{
// build method URL
string path = "/" + version_ + "/public/" + method;
string method_url = url_ + path;
curl_easy_setopt(curl_, CURLOPT_URL, method_url.c_str());
// build postdata
string postdata = build_query(input);
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, postdata.c_str());
// reset the http header
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, NULL);
// where CURL write callback function stores the response
string response;
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, static_cast<void*>(&response));
// perform CURL request
CURLcode result = curl_easy_perform(curl_);
if (result != CURLE_OK) {
ostringstream oss;
oss << "curl_easy_perform() failed: "
<< curl_easy_strerror(result);
throw runtime_error(oss.str());
}
return response;
}
//------------------------------------------------------------------------------
// deals with private API methods:
string KAPI::private_method(const string& method,
const KAPI::Input& input) const
{
// build method URL
string path = "/" + version_ + "/private/" + method;
string method_url = url_ + path;
curl_easy_setopt(curl_, CURLOPT_URL, method_url.c_str());
// create a nonce and and postdata
string nonce = create_nonce();
string postdata = "nonce=" + nonce;
// if 'input' is not empty generate other postdata
if (!input.empty())
postdata = postdata + "&" + build_query(input);
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, postdata.c_str());
// add custom header
curl_slist* chunk = NULL;
string header = "API-Key: " + key_;
chunk = curl_slist_append(chunk, header.c_str());
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, chunk);
// generate message signature
header = "API-Sign: " + message_signature(path, nonce, postdata);
chunk = curl_slist_append(chunk, header.c_str());
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, chunk);
// where CURL write callback function stores the response
string response;
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, static_cast<void*>(&response));
// perform CURL request
CURLcode result = curl_easy_perform(curl_);
// free the custom headers
curl_slist_free_all(chunk);
// check perform result
if (result != CURLE_OK) {
ostringstream oss;
oss << "curl_easy_perform() failed: "
<< curl_easy_strerror(result);
throw runtime_error(oss.str());
}
return response;
}
//------------------------------------------------------------------------------
}; //namespace Kraken
//------------------------------------------------------------------------------