diff --git a/linux/include/ccapi_cpp/ccapi_decimal.h b/linux/include/ccapi_cpp/ccapi_decimal.h deleted file mode 100644 index a5f8fd60c..000000000 --- a/linux/include/ccapi_cpp/ccapi_decimal.h +++ /dev/null @@ -1,233 +0,0 @@ -#ifndef INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_ -#define INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_ -#include - -#include "ccapi_cpp/ccapi_logger.h" -#include "ccapi_cpp/ccapi_util_private.h" -namespace ccapi { -/** - * This class provides a numeric type for representing an arbitrary precision decimal number. It is minimalistic for the purpose of high performance. - * Furthermore, unlike double, it is suitable for being used as the key of a map. - */ -class Decimal CCAPI_FINAL { - public: - Decimal() {} - explicit Decimal(const std::string& originalValue, bool keepTrailingZero = false) { - if (originalValue.empty()) { - CCAPI_LOGGER_FATAL("Decimal constructor input value cannot be empty"); - } - // std::string originalValue = originalValue; - // this->sign = true; - if (originalValue.at(0) == '-') { - // originalValue.erase(0, 1); - this->sign = false; - } - auto foundE = originalValue.find('E'); - if (foundE != std::string::npos || originalValue.find('e') != std::string::npos) { - if (foundE == std::string::npos) { - foundE = originalValue.find('e'); - } - std::string fixedPointValue = originalValue.substr(this->sign ? 0 : 1, this->sign ? foundE : foundE - 1); - auto foundDot = fixedPointValue.find('.'); - if (foundDot != std::string::npos) { - fixedPointValue.erase(fixedPointValue.find_last_not_of('0') + 1); - fixedPointValue.erase(fixedPointValue.find_last_not_of('.') + 1); - } - std::string exponent = originalValue.substr(foundE + 1); - if (exponent.at(0) == '+') { - exponent.erase(0, 1); - } - exponent.erase(0, exponent.find_first_not_of('0')); - if (exponent.empty()) { - exponent = "0"; - } - if (exponent != "0") { - foundDot = fixedPointValue.find('.'); - if (foundDot != std::string::npos) { - if (exponent.at(0) != '-') { - if (std::stoi(exponent) < fixedPointValue.substr(foundDot + 1).length()) { - fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1).substr(0, std::stoi(exponent)) + "." + - fixedPointValue.substr(foundDot + 1).substr(std::stoi(exponent)); - } else { - fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1) + - std::string(std::stoi(exponent) - fixedPointValue.substr(foundDot + 1).length(), '0'); - } - } else { - fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1); - } - } else { - if (exponent.at(0) != '-') { - fixedPointValue += std::string(std::stoi(exponent), '0'); - } else { - fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue; - } - } - } - foundDot = fixedPointValue.find('.'); - // TODO(cryptochassis): replace with std::from_chars() once upgrade to C++17 - this->before = std::stoull(fixedPointValue.substr(0, foundDot)); - if (foundDot != std::string::npos) { - this->frac = fixedPointValue.substr(foundDot + 1); - if (!keepTrailingZero) { - this->frac.erase(this->frac.find_last_not_of('0') + 1); - } - } - } else { - auto found = originalValue.find('.'); - // TODO(cryptochassis): replace with std::from_chars() once upgrade to C++17 - this->before = std::stoull(originalValue.substr(this->sign ? 0 : 1, found)); - if (found != std::string::npos) { - this->frac = originalValue.substr(found + 1); - if (!keepTrailingZero) { - this->frac.erase(this->frac.find_last_not_of('0') + 1); - } - } - } - } - std::string toString() const { - std::string stringValue; - if (!this->sign) { - stringValue += "-"; - } - stringValue += std::to_string(this->before); - if (!this->frac.empty()) { - stringValue += "."; - stringValue += this->frac; - } - return stringValue; - } - double toDouble() const { return std::stod(this->toString()); } - friend bool operator<(const Decimal& l, const Decimal& r) { - if (l.sign && r.sign) { - if (l.before < r.before) { - return true; - } else if (l.before > r.before) { - return false; - } else { - return l.frac < r.frac; - } - } else if (l.sign && !r.sign) { - return false; - } else if (!l.sign && r.sign) { - if (l.before == 0 && l.frac.empty() && r.before == 0 && r.frac.empty()) { - return false; - } else { - return true; - } - } else { - Decimal nl = l; - nl.sign = true; - Decimal nr = r; - nr.sign = true; - return nl > nr; - } - } - friend bool operator>(const Decimal& l, const Decimal& r) { return r < l; } - friend bool operator<=(const Decimal& l, const Decimal& r) { return !(l > r); } - friend bool operator>=(const Decimal& l, const Decimal& r) { return !(l < r); } - friend bool operator==(const Decimal& l, const Decimal& r) { return !(l > r) && !(l < r); } - friend bool operator!=(const Decimal& l, const Decimal& r) { return !(l == r); } - Decimal negate() const { - Decimal o; - o.before = this->before; - o.frac = this->frac; - o.sign = !this->sign; - return o; - } - Decimal add(const Decimal& x) const { - if (this->sign && x.sign) { - Decimal o; - o.sign = true; - o.before = this->before + x.before; - if (this->frac.empty()) { - o.frac = x.frac; - } else if (x.frac.empty()) { - o.frac = this->frac; - } else { - auto l1 = this->frac.length(); - auto l2 = x.frac.length(); - if (l1 > l2) { - auto a = std::to_string(std::stoull(this->frac) + std::stoull(UtilString::rightPadTo(x.frac, l1, '0'))); - if (a.length() < l1) { - a = UtilString::leftPadTo(a, l1, '0'); - } - if (a.length() == l1) { - o.frac = UtilString::rtrim(a, "0"); - } else { - o.frac = UtilString::rtrim(a.substr(a.length() - l1), "0"); - o.before += std::stoull(a.substr(0, a.length() - l1)); - } - } else if (l1 < l2) { - auto a = std::to_string(std::stoull(UtilString::rightPadTo(this->frac, l2, '0')) + std::stoull(x.frac)); - if (a.length() < l2) { - a = UtilString::leftPadTo(a, l2, '0'); - } - if (a.length() == l2) { - o.frac = UtilString::rtrim(a, "0"); - } else { - o.frac = UtilString::rtrim(a.substr(a.length() - l2), "0"); - o.before += std::stoull(a.substr(0, a.length() - l2)); - } - } else { - auto a = std::to_string(std::stoull(this->frac) + std::stoull(x.frac)); - if (a.length() < l1) { - a = UtilString::leftPadTo(a, l1, '0'); - } - if (a.length() == l1) { - o.frac = UtilString::rtrim(a, "0"); - } else { - o.frac = UtilString::rtrim(a.substr(a.length() - l1), "0"); - o.before += std::stoull(a.substr(0, a.length() - l1)); - } - } - } - return o; - } else if (!this->sign && x.sign) { - return x.subtract(this->negate()); - } else if (this->sign && !x.sign) { - return this->subtract(x.negate()); - } else { - return (this->negate().add(x.negate())).negate(); - } - } - Decimal subtract(const Decimal& x) const { - if (this->sign && x.sign) { - if (*this >= x) { - Decimal o; - o.sign = true; - if (this->frac >= x.frac) { - o.before = this->before - x.before; - } else { - o.before = this->before - 1 - x.before; - } - auto l1 = this->frac.length(); - auto l2 = x.frac.length(); - auto lmax = std::max(l1, l2); - auto a = lmax > 0 ? std::to_string(std::stoull(UtilString::rightPadTo(this->frac, lmax, '0')) + - (this->frac >= x.frac ? (unsigned)0 : std::stoull(UtilString::rightPadTo("1", 1 + lmax, '0'))) - - std::stoull(UtilString::rightPadTo(x.frac, lmax, '0'))) - : ""; - if (a.length() < lmax) { - a = UtilString::leftPadTo(a, lmax, '0'); - } - o.frac = UtilString::rtrim(a, "0"); - return o; - } else { - return x.subtract(*this).negate(); - } - } else if (!this->sign && x.sign) { - return x.subtract(this->negate()); - } else if (this->sign && !x.sign) { - return this->subtract(x.negate()); - } else { - return x.negate().subtract(this->negate()); - } - } - // {-}bbbb.aaaa - unsigned long long before{}; - std::string frac; - // false means negative sign needed - bool sign{true}; -}; -} /* namespace ccapi */ -#endif // INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_ diff --git a/linux/include/ccapi_cpp/ccapi_element.h b/linux/include/ccapi_cpp/ccapi_element.h index 8286d575f..9fb90c6c0 100644 --- a/linux/include/ccapi_cpp/ccapi_element.h +++ b/linux/include/ccapi_cpp/ccapi_element.h @@ -4,51 +4,125 @@ #include #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * Element represents an item in a message. The value(s) in an Element can be queried in a number of ways. Use the getValue() functions to retrieve a single - * value. Use the getNameValueMap() function (or getTagValueMap() function for FIX API) to retrieve all the values. + * value. Use the getNameValueMap() function (or getTagValueList() function for FIX API) to retrieve all the values. */ -class Element CCAPI_FINAL { +class Element { public: explicit Element(bool isFix = false) : isFix(isFix) {} - void insert(const std::string& name, const std::string& value) { this->nameValueMap.insert(std::pair(name, value)); } - void insert(int tag, const std::string& value) { this->tagValueMap.insert(std::pair(tag, value)); } - void emplace(std::string& name, std::string& value) { this->nameValueMap.emplace(std::move(name), std::move(value)); } - void emplace(int tag, std::string& value) { this->tagValueMap.emplace(std::move(tag), std::move(value)); } - bool has(const std::string& name) const { return this->nameValueMap.find(name) != this->nameValueMap.end(); } - bool has(int tag) const { return this->tagValueMap.find(tag) != this->tagValueMap.end(); } - std::string getValue(const std::string& name, const std::string valueDefault = "") const { + + // Template insert: accept any string-like value + template + void insert(std::string_view name, S&& value) { + // Construct std::string only if necessary + if constexpr (std::is_same_v, std::string>) { + // If value is std::string, move it in to avoid copy + nameValueMap.emplace(name, std::forward(value)); + } else { + // Otherwise, construct std::string from value (string_view, const char*) + nameValueMap.emplace(name, std::string(std::forward(value))); + } + } + + template + void insert(int tag, S&& value) { + if constexpr (std::is_same_v, std::string>) { + // Already a std::string — emplace directly + tagValueList.emplace_back(tag, std::forward(value)); + } else { + // Convert to std::string + tagValueList.emplace_back(tag, std::string(std::forward(value))); + } + } + + // Template insert: accept any string-like value + template + void insert_or_assign(std::string_view name, S&& value) { + // Construct std::string only if necessary + if constexpr (std::is_same_v, std::string>) { + // If value is std::string, move it in to avoid copy + nameValueMap.insert_or_assign(name, std::forward(value)); + } else { + // Otherwise, construct std::string from value (string_view, const char*) + nameValueMap.insert_or_assign(name, std::string(std::forward(value))); + } + } + + // template + // void insert_or_assign(int tag, S&& value) { + // if constexpr (std::is_same_v, std::string>) { + // // If already std::string, move to avoid copy + // tagValueList.insert_or_assign(tag, std::forward(value)); + // } else { + // // Otherwise, construct std::string from value (string_view, literal, etc.) + // tagValueList.insert_or_assign(tag, std::string(std::forward(value))); + // } + // } + + // void emplace(std::string& name, std::string& value) { this->nameValueMap.emplace(std::move(name), std::move(value)); } + + // void emplace(int tag, std::string& value) { this->tagValueList.emplace(std::move(tag), std::move(value)); } + + bool has(std::string_view name) const { return this->nameValueMap.find(name) != this->nameValueMap.end(); } + + bool has(int tag) const { + return std::any_of(tagValueList.begin(), tagValueList.end(), [tag](const auto& pair) { return pair.first == tag; }); + } + + std::string getValue(std::string_view name, const std::string& valueDefault = "") const { auto it = this->nameValueMap.find(name); return it == this->nameValueMap.end() ? valueDefault : it->second; } - std::string getValue(int tag, const std::string valueDefault = "") const { - auto it = this->tagValueMap.find(tag); - return it == this->tagValueMap.end() ? valueDefault : it->second; + + std::string getValue(int tag, const std::string& valueDefault = "") const { + for (const auto& [key, value] : tagValueList) { + if (key == tag) return value; + } + return valueDefault; } + std::string toString() const { - std::string output = - isFix ? "Element [tagValueMap = " + ccapi::toString(tagValueMap) + "]" : "Element [nameValueMap = " + ccapi::toString(nameValueMap) + "]"; + std::string output = isFix ? "Element [tagValueList = " + ccapi::toString(tagValueList) + ", nameValueMap = " + ccapi::toString(nameValueMap) + "]" + : "Element [nameValueMap = " + ccapi::toString(nameValueMap) + "]"; return output; } - std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { + + std::string toPrettyString(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { std::string sl(leftToIndent, ' '); std::string ss(leftToIndent + space, ' '); std::string output = isFix ? (indentFirstLine ? sl : "") + "Element [\n" + ss + - "tagValueMap = " + ccapi::toStringPretty(tagValueMap, space, space + leftToIndent, false) + "\n" + sl + "]" + "tagValueList = " + ccapi::toPrettyString(tagValueList, space, space + leftToIndent, false) + ",\n" + ss + + "nameValueMap = " + ccapi::toPrettyString(nameValueMap, space, space + leftToIndent, false) + "\n" + sl + "]" : (indentFirstLine ? sl : "") + "Element [\n" + ss + - "nameValueMap = " + ccapi::toStringPretty(nameValueMap, space, space + leftToIndent, false) + "\n" + sl + "]"; + "nameValueMap = " + ccapi::toPrettyString(nameValueMap, space, space + leftToIndent, false) + "\n" + sl + "]"; return output; } - const std::map& getNameValueMap() const { return nameValueMap; } - const std::map& getTagValueMap() const { return tagValueMap; } +#ifdef SWIG + std::map getNameValueMap() const { + std::map result; + for (const auto& [key, value] : nameValueMap) { + result.emplace(std::string(key), value); + } + return result; +} +#else + const std::map& getNameValueMap() const { return nameValueMap; } +#endif + + const std::vector>& getTagValueList() const { return tagValueList; } #ifndef CCAPI_EXPOSE_INTERNAL private: #endif - bool isFix; - std::map nameValueMap; - std::map tagValueMap; + bool isFix{}; + std::map nameValueMap; // They key std::string_view is created from a string literal and therefore is safe, because string + // literals have static storage duration, meaning they live for the entire duration of the program. + std::vector> tagValueList; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_ELEMENT_H_ diff --git a/linux/include/ccapi_cpp/ccapi_event.h b/linux/include/ccapi_cpp/ccapi_event.h index c8dd33c01..745093e67 100644 --- a/linux/include/ccapi_cpp/ccapi_event.h +++ b/linux/include/ccapi_cpp/ccapi_event.h @@ -4,14 +4,16 @@ #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_message.h" + namespace ccapi { + /** ** A single event resulting from a subscription or a request. Event objects are created by the API and passed to the application either through a registered *EventHandler or EventQueue. Event objects contain Message objects which can be accessed using the getMessageList() function. The Event object is a handle to an *event. The event is the basic unit of work provided to applications. Each Event object consists of an Type attribute and zero or more Message objects. */ -class Event CCAPI_FINAL { +class Event { public: enum class Type { UNKNOWN, @@ -23,7 +25,9 @@ class Event CCAPI_FINAL { AUTHORIZATION_STATUS, FIX, FIX_STATUS, + HEARTBEAT, }; + static std::string typeToString(Type type) { std::string output; switch (type) { @@ -54,26 +58,34 @@ class Event CCAPI_FINAL { case Type::FIX_STATUS: output = "FIX_STATUS"; break; + case Type::HEARTBEAT: + output = "HEARTBEAT"; + break; default: CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } return output; } + std::string toString() const { std::string output = "Event [type = " + typeToString(type) + ", messageList = " + ccapi::toString(messageList) + "]"; return output; } - std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { + + std::string toPrettyString(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { std::string sl(leftToIndent, ' '); std::string ss(leftToIndent + space, ' '); std::string output = (indentFirstLine ? sl : "") + "Event [\n" + ss + "type = " + typeToString(type) + ",\n" + ss + - "messageList = " + ccapi::toStringPretty(messageList, space, leftToIndent + space, false) + "\n" + sl + "]"; + "messageList = " + ccapi::toPrettyString(messageList, space, leftToIndent + space, false) + "\n" + sl + "]"; return output; } + const std::vector& getMessageList() const { return messageList; } + void addMessages(const std::vector& newMessageList) { this->messageList.insert(std::end(this->messageList), std::begin(newMessageList), std::end(newMessageList)); } + void addMessages(std::vector& newMessageList) { if (this->messageList.empty()) { this->messageList = std::move(newMessageList); @@ -82,11 +94,17 @@ class Event CCAPI_FINAL { std::move(std::begin(newMessageList), std::end(newMessageList), std::back_inserter(this->messageList)); } } + void addMessage(const Message& newMessage) { this->messageList.push_back(newMessage); } + void addMessage(Message& newMessage) { this->messageList.emplace_back(std::move(newMessage)); } + void setMessageList(const std::vector& messageList) { this->messageList = messageList; } + void setMessageList(std::vector& messageList) { this->messageList = std::move(messageList); } + Type getType() const { return type; } + void setType(Type type) { this->type = type; } #ifndef CCAPI_EXPOSE_INTERNAL @@ -95,5 +113,6 @@ class Event CCAPI_FINAL { Type type{Type::UNKNOWN}; std::vector messageList; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_EVENT_H_ diff --git a/linux/include/ccapi_cpp/ccapi_event_dispatcher.h b/linux/include/ccapi_cpp/ccapi_event_dispatcher.h index d4e63cafe..5d21395b3 100644 --- a/linux/include/ccapi_cpp/ccapi_event_dispatcher.h +++ b/linux/include/ccapi_cpp/ccapi_event_dispatcher.h @@ -12,14 +12,16 @@ #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * Dispatches events from one or more Sessions through callbacks. EventDispatcher objects are optionally specified when Session objects are constructed. A * single EventDispatcher can be shared by multiple Session objects. The EventDispatcher provides an event-driven interface, generating callbacks from one or * more internal threads for one or more sessions. */ -class EventDispatcher CCAPI_FINAL { +class EventDispatcher { public: explicit EventDispatcher(const int numDispatcherThreads = 1) : numDispatcherThreads(numDispatcherThreads) { CCAPI_LOGGER_FUNCTION_ENTER; @@ -27,10 +29,12 @@ class EventDispatcher CCAPI_FINAL { this->start(); CCAPI_LOGGER_FUNCTION_EXIT; } + ~EventDispatcher() { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_FUNCTION_EXIT; } + void dispatch(const std::function& op) { CCAPI_LOGGER_FUNCTION_ENTER; if (this->shouldContinue.load()) { @@ -46,14 +50,18 @@ class EventDispatcher CCAPI_FINAL { } CCAPI_LOGGER_FUNCTION_EXIT; } + void start() { this->shouldContinue = true; for (size_t i = 0; i < numDispatcherThreads; i++) { this->dispatcherThreads.push_back(std::thread(&EventDispatcher::dispatch_thread_handler, this)); } } + void resume() { this->shouldContinue = true; } + void pause() { this->shouldContinue = false; } + void stop() { std::unique_lock lock(this->lock); this->quit = true; @@ -85,13 +93,15 @@ class EventDispatcher CCAPI_FINAL { } while (!this->quit); CCAPI_LOGGER_FUNCTION_EXIT; } - size_t numDispatcherThreads; + + size_t numDispatcherThreads{}; std::atomic shouldContinue{}; std::vector dispatcherThreads; std::mutex lock; - std::queue > queue; + std::queue> queue; std::condition_variable cv; bool quit{}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_EVENT_DISPATCHER_H_ diff --git a/linux/include/ccapi_cpp/ccapi_event_handler.h b/linux/include/ccapi_cpp/ccapi_event_handler.h index 034c06bdc..0abacc1a3 100644 --- a/linux/include/ccapi_cpp/ccapi_event_handler.h +++ b/linux/include/ccapi_cpp/ccapi_event_handler.h @@ -1,8 +1,11 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_EVENT_HANDLER_H_ #define INCLUDE_CCAPI_CPP_CCAPI_EVENT_HANDLER_H_ #include "ccapi_cpp/ccapi_event.h" + namespace ccapi { + class Session; + /** * Defines the callback supplied by the application to process Events. Applications which use event driven programming supply instances of their own subclass of * this class to the Session to receive callbacks when an Event is available. @@ -10,11 +13,11 @@ class Session; class EventHandler { public: virtual ~EventHandler() {} - virtual bool processEvent(const Event& event, Session* sessionPtr) { return true; } + + virtual void processEvent(const Event& event, Session* sessionPtr) {} + // An implementation of processEvent should process the specified - // 'event' which originates from the specified 'session' and - // return true to indicate events should continue to be delivered - // or false to terminate dispatching of events. + // 'event' which originates from the specified 'session'. // // If the application wishes to process the event further // after returning from the processEvents() call it must make @@ -22,5 +25,6 @@ class EventHandler { // freed. // Note: no exceptions are thrown }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_EVENT_HANDLER_H_ diff --git a/linux/include/ccapi_cpp/ccapi_fix_connection.h b/linux/include/ccapi_cpp/ccapi_fix_connection.h index 4fe4ee3ea..ca6e7e03f 100644 --- a/linux/include/ccapi_cpp/ccapi_fix_connection.h +++ b/linux/include/ccapi_cpp/ccapi_fix_connection.h @@ -1,27 +1,52 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_FIX_CONNECTION_H_ #define INCLUDE_CCAPI_CPP_CCAPI_FIX_CONNECTION_H_ #include +#include #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_subscription.h" namespace beast = boost::beast; + namespace ccapi { + /** * This class represents a TCP socket connection for the FIX API. */ -template -class FixConnection CCAPI_FINAL { + +class FixConnection { public: - FixConnection(std::string host, std::string port, Subscription subscription, std::shared_ptr streamPtr) - : host(host), port(port), subscription(subscription), streamPtr(streamPtr) { - this->id = subscription.getCorrelationId(); - this->url = host + ":" + port; + FixConnection(const FixConnection&) = delete; + FixConnection& operator=(const FixConnection&) = delete; + + FixConnection(const std::string& url, const Subscription& subscription, const std::map& credential) + : url(url), subscription(subscription), credential(credential) { + std::map shortCredential; + for (const auto& x : credential) { + shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); + } + this->longId = this->url + "||" + ccapi::toString(this->subscription) + "||" + ccapi::toString(shortCredential); + this->id = UtilAlgorithm::shortBase62Hash(this->longId); + this->setUrlParts(); } + std::string toString() const { + std::map shortCredential; + for (const auto& x : credential) { + shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); + } std::ostringstream oss; - oss << streamPtr; - std::string output = "FixConnection [id = " + id + ", host = " + host + ", port = " + port + ", subscription = " + ccapi::toString(subscription) + - ", status = " + statusToString(status) + ", streamPtr = " + oss.str() + "]"; + std::visit( + [&oss](auto&& streamPtr) { + if (streamPtr) { + oss << streamPtr.get(); + } else { + oss << "nullptr"; + } + }, + streamPtr); + std::string output = "FixConnection [longId = " + longId + ", id = " + id + ", url = " + url + ", subscription = " + ccapi::toString(subscription) + + ", credential = " + ccapi::toString(shortCredential) + ", status = " + statusToString(status) + ", streamPtr = " + oss.str() + + ", host = " + ccapi::toString(host) + ", port = " + ccapi::toString(port) + ", isSecure = " + ccapi::toString(isSecure) + "]"; return output; } enum class Status { @@ -32,6 +57,7 @@ class FixConnection CCAPI_FINAL { CLOSING, CLOSED, }; + static std::string statusToString(Status status) { std::string output; switch (status) { @@ -58,13 +84,45 @@ class FixConnection CCAPI_FINAL { } return output; } + + std::string getUrl() const { return url; } + + void setUrl(const std::string& url) { + this->url = url; + this->setUrlParts(); + } + + void setUrlParts() { + auto splitted1 = UtilString::split(url, "://"); + if (splitted1.size() >= 2) { + auto splitted2 = UtilString::split(splitted1.at(1), ":"); + this->host = splitted2.at(0); + if (splitted2.size() == 2) { + this->port = splitted2.at(1); + } else { + if (splitted1.at(0) == "tcp+tls" || splitted1.at(0) == "tcp+ssl") { + this->port = CCAPI_HTTPS_PORT_DEFAULT; + } else { + this->port = CCAPI_HTTP_PORT_DEFAULT; + } + } + if (splitted1.at(0) == "tcp+tls" || splitted1.at(0) == "tcp+ssl") { + this->isSecure = true; + } + } + } + + std::string longId; std::string id; - std::string host; - std::string port; std::string url; Subscription subscription; Status status{Status::UNKNOWN}; - std::shared_ptr streamPtr; + std::map credential; + std::variant>, std::shared_ptr> streamPtr; + std::string host; + std::string port; + bool isSecure{}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_FIX_CONNECTION_H_ diff --git a/linux/include/ccapi_cpp/ccapi_hmac.h b/linux/include/ccapi_cpp/ccapi_hmac.h index 0dc012d46..edd1544e9 100644 --- a/linux/include/ccapi_cpp/ccapi_hmac.h +++ b/linux/include/ccapi_cpp/ccapi_hmac.h @@ -1,2503 +1,16 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_HMAC_H_ #define INCLUDE_CCAPI_CPP_CCAPI_HMAC_H_ -// https://github.com/Yubico/yubico-c-client/blob/ykclient-2.15/hmac.c -/**************************** hmac.c ****************************/ -/******************** See RFC 4634 for details ******************/ -/* - * Description: - * This file implements the HMAC algorithm (Keyed-Hashing for - * Message Authentication, RFC2104), expressed in terms of the - * various SHA algorithms. - */ - -//#include "sha.h" -/**************************** sha.h ****************************/ -/******************* See RFC 4634 for details ******************/ -#ifndef _SHA_H_ -#define _SHA_H_ - -/* - * Description: - * This file implements the Secure Hash Signature Standard - * algorithms as defined in the National Institute of Standards - * and Technology Federal Information Processing Standards - * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 - * published on August 1, 2002, and the FIPS PUB 180-2 Change - * Notice published on February 28, 2004. - * - * A combined document showing all algorithms is available at - * http://csrc.nist.gov/publications/fips/ - * fips180-2/fips180-2withchangenotice.pdf - * - * The five hashes are defined in these sizes: - * SHA-1 20 byte / 160 bit - * SHA-224 28 byte / 224 bit - * SHA-256 32 byte / 256 bit - * SHA-384 48 byte / 384 bit - * SHA-512 64 byte / 512 bit - */ #include #include #include + #include -/* - * If you do not have the ISO standard stdint.h header file, then you - * must typedef the following: - * name meaning - * uint64_t unsigned 64 bit integer - * uint32_t unsigned 32 bit integer - * uint8_t unsigned 8 bit integer (i.e., unsigned char) - * int_least16_t integer of >= 16 bits - * - */ -namespace yubico { -#ifndef _SHA_enum_ -#define _SHA_enum_ -/* - * All SHA functions return one of these values. - */ -enum { - shaSuccess = 0, - shaNull, /* Null pointer parameter */ - shaInputTooLong, /* input data too long */ - shaStateError, /* called Input after FinalBits or Result */ - shaBadParam /* passed a bad parameter */ -}; -#endif /* _SHA_enum_ */ +#include -/* - * These constants hold size information for each of the SHA - * hashing operations - */ -enum { - SHA1_Message_Block_Size = 64, - SHA224_Message_Block_Size = 64, - SHA256_Message_Block_Size = 64, - SHA384_Message_Block_Size = 128, - SHA512_Message_Block_Size = 128, - USHA_Max_Message_Block_Size = SHA512_Message_Block_Size, - - SHA1HashSize = 20, - SHA224HashSize = 28, - SHA256HashSize = 32, - SHA384HashSize = 48, - SHA512HashSize = 64, - USHAMaxHashSize = SHA512HashSize, - - SHA1HashSizeBits = 160, - SHA224HashSizeBits = 224, - SHA256HashSizeBits = 256, - SHA384HashSizeBits = 384, - SHA512HashSizeBits = 512, - USHAMaxHashSizeBits = SHA512HashSizeBits -}; - -/* - * These constants are used in the USHA (unified sha) functions. - */ -typedef enum SHAversion { SHA1, SHA224, SHA256, SHA384, SHA512 } SHAversion; - -/* - * This structure will hold context information for the SHA-1 - * hashing operation. - */ -typedef struct SHA1Context { - uint32_t Intermediate_Hash[SHA1HashSize / 4]; /* Message Digest */ - - uint32_t Length_Low; /* Message length in bits */ - uint32_t Length_High; /* Message length in bits */ - - int_least16_t Message_Block_Index; /* Message_Block array index */ - /* 512-bit message blocks */ - uint8_t Message_Block[SHA1_Message_Block_Size]; - - int Computed; /* Is the digest computed? */ - int Corrupted; /* Is the digest corrupted? */ -} SHA1Context; - -/* - * This structure will hold context information for the SHA-256 - * hashing operation. - */ -typedef struct SHA256Context { - uint32_t Intermediate_Hash[SHA256HashSize / 4]; /* Message Digest */ - - uint32_t Length_Low; /* Message length in bits */ - uint32_t Length_High; /* Message length in bits */ - - int_least16_t Message_Block_Index; /* Message_Block array index */ - /* 512-bit message blocks */ - uint8_t Message_Block[SHA256_Message_Block_Size]; - - int Computed; /* Is the digest computed? */ - int Corrupted; /* Is the digest corrupted? */ -} SHA256Context; - -/* - * This structure will hold context information for the SHA-512 - * hashing operation. - */ -typedef struct SHA512Context { -#ifdef USE_32BIT_ONLY - uint32_t Intermediate_Hash[SHA512HashSize / 4]; /* Message Digest */ - uint32_t Length[4]; /* Message length in bits */ -#else /* !USE_32BIT_ONLY */ - uint64_t Intermediate_Hash[SHA512HashSize / 8]; /* Message Digest */ - uint64_t Length_Low, Length_High; /* Message length in bits */ -#endif /* USE_32BIT_ONLY */ - int_least16_t Message_Block_Index; /* Message_Block array index */ - /* 1024-bit message blocks */ - uint8_t Message_Block[SHA512_Message_Block_Size]; - - int Computed; /* Is the digest computed? */ - int Corrupted; /* Is the digest corrupted? */ -} SHA512Context; - -/* - * This structure will hold context information for the SHA-224 - * hashing operation. It uses the SHA-256 structure for computation. - */ -typedef struct SHA256Context SHA224Context; - -/* - * This structure will hold context information for the SHA-384 - * hashing operation. It uses the SHA-512 structure for computation. - */ -typedef struct SHA512Context SHA384Context; - -/* - * This structure holds context information for all SHA - * hashing operations. - */ -typedef struct USHAContext { - int whichSha; /* which SHA is being used */ - union { - SHA1Context sha1Context; - SHA224Context sha224Context; - SHA256Context sha256Context; - SHA384Context sha384Context; - SHA512Context sha512Context; - } ctx; -} USHAContext; - -/* - * This structure will hold context information for the HMAC - * keyed hashing operation. - */ -typedef struct HMACContext { - int whichSha; /* which SHA is being used */ - int hashSize; /* hash size of SHA being used */ - int blockSize; /* block size of SHA being used */ - USHAContext shaContext; /* SHA context */ - unsigned char k_opad[USHA_Max_Message_Block_Size]; - /* outer padding - key XORd with opad */ -} HMACContext; -/* - * Function Prototypes - */ - -/* SHA-1 */ -int SHA1Reset(SHA1Context *); -int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount); -int SHA1FinalBits(SHA1Context *, const uint8_t bits, unsigned int bitcount); -int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize]); - -/* SHA-224 */ -int SHA224Reset(SHA224Context *); -int SHA224Input(SHA224Context *, const uint8_t *bytes, unsigned int bytecount); -int SHA224FinalBits(SHA224Context *, const uint8_t bits, unsigned int bitcount); -int SHA224Result(SHA224Context *, uint8_t Message_Digest[SHA224HashSize]); - -/* SHA-256 */ -int SHA256Reset(SHA256Context *); -int SHA256Input(SHA256Context *, const uint8_t *bytes, unsigned int bytecount); -int SHA256FinalBits(SHA256Context *, const uint8_t bits, unsigned int bitcount); -int SHA256Result(SHA256Context *, uint8_t Message_Digest[SHA256HashSize]); - -/* SHA-384 */ -int SHA384Reset(SHA384Context *); -int SHA384Input(SHA384Context *, const uint8_t *bytes, unsigned int bytecount); -int SHA384FinalBits(SHA384Context *, const uint8_t bits, unsigned int bitcount); -int SHA384Result(SHA384Context *, uint8_t Message_Digest[SHA384HashSize]); - -/* SHA-512 */ -int SHA512Reset(SHA512Context *); -int SHA512Input(SHA512Context *, const uint8_t *bytes, unsigned int bytecount); -int SHA512FinalBits(SHA512Context *, const uint8_t bits, unsigned int bitcount); -int SHA512Result(SHA512Context *, uint8_t Message_Digest[SHA512HashSize]); - -/* Unified SHA functions, chosen by whichSha */ -int USHAReset(USHAContext *, SHAversion whichSha); -int USHAInput(USHAContext *, const uint8_t *bytes, unsigned int bytecount); -int USHAFinalBits(USHAContext *, const uint8_t bits, unsigned int bitcount); -int USHAResult(USHAContext *, uint8_t Message_Digest[USHAMaxHashSize]); -int USHABlockSize(enum SHAversion whichSha); -int USHAHashSize(enum SHAversion whichSha); -int USHAHashSizeBits(enum SHAversion whichSha); - -/* - * HMAC Keyed-Hashing for Message Authentication, RFC2104, - * for all SHAs. - * This interface allows a fixed-length text input to be used. - */ -int hmac(SHAversion whichSha, /* which SHA algorithm to use */ - const unsigned char *text, /* pointer to data stream */ - int text_len, /* length of data stream */ - const unsigned char *key, /* pointer to authentication key */ - int key_len, /* length of authentication key */ - uint8_t digest[USHAMaxHashSize]); /* caller digest to fill in */ - -/* - * HMAC Keyed-Hashing for Message Authentication, RFC2104, - * for all SHAs. - * This interface allows any length of text input to be used. - */ -int hmacReset(HMACContext *ctx, enum SHAversion whichSha, const unsigned char *key, int key_len); -int hmacInput(HMACContext *ctx, const unsigned char *text, int text_len); - -int hmacFinalBits(HMACContext *ctx, const uint8_t bits, unsigned int bitcount); -int hmacResult(HMACContext *ctx, uint8_t digest[USHAMaxHashSize]); - -#endif /* _SHA_H_ */ -/*************************** sha-private.h ***************************/ -/********************** See RFC 4634 for details *********************/ -#ifndef _SHA_PRIVATE__H -#define _SHA_PRIVATE__H -/* - * These definitions are defined in FIPS-180-2, section 4.1. - * Ch() and Maj() are defined identically in sections 4.1.1, - * 4.1.2 and 4.1.3. - * - * The definitions used in FIPS-180-2 are as follows: - */ - -#ifndef USE_MODIFIED_MACROS -#define SHA_Ch(x, y, z) (((x) & (y)) ^ ((~(x)) & (z))) -#define SHA_Maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) - -#else /* USE_MODIFIED_MACROS */ - /* - * The following definitions are equivalent and potentially faster. - */ - -#define SHA_Ch(x, y, z) (((x) & ((y) ^ (z))) ^ (z)) -#define SHA_Maj(x, y, z) (((x) & ((y) | (z))) | ((y) & (z))) -#endif /* USE_MODIFIED_MACROS */ - -#define SHA_Parity(x, y, z) ((x) ^ (y) ^ (z)) - -#endif /* _SHA_PRIVATE__H */ -/**************************** sha1.c ****************************/ -/******************** See RFC 4634 for details ******************/ -/* - * Description: - * This file implements the Secure Hash Signature Standard - * algorithms as defined in the National Institute of Standards - * and Technology Federal Information Processing Standards - * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 - * published on August 1, 2002, and the FIPS PUB 180-2 Change - * Notice published on February 28, 2004. - * - * A combined document showing all algorithms is available at - * http://csrc.nist.gov/publications/fips/ - * fips180-2/fips180-2withchangenotice.pdf - * - * The SHA-1 algorithm produces a 160-bit message digest for a - * given data stream. It should take about 2**n steps to find a - * message with the same digest as a given message and - * 2**(n/2) to find any two messages with the same digest, - * when n is the digest size in bits. Therefore, this - * algorithm can serve as a means of providing a - * "fingerprint" for a message. - * - * Portability Issues: - * SHA-1 is defined in terms of 32-bit "words". This code - * uses (included via "sha.h") to define 32 and 8 - * bit unsigned integer types. If your C compiler does not - * support 32 bit unsigned integers, this code is not - * appropriate. - * - * Caveats: - * SHA-1 is designed to work with messages less than 2^64 bits - * long. This implementation uses SHA1Input() to hash the bits - * that are a multiple of the size of an 8-bit character, and then - * uses SHA1FinalBits() to hash the final few bits of the input. - */ - -//#include "sha.h" -//#include "sha-private.h" - -/* - * Define the SHA1 circular left shift macro - */ -#define SHA1_ROTL(bits, word) (((word) << (bits)) | ((word) >> (32 - (bits)))) - -/* - * add "length" to the length - */ -static uint32_t addTemp1; -#define SHA1AddLength(context, length) \ - (addTemp1 = (context)->Length_Low, (context)->Corrupted = (((context)->Length_Low += (length)) < addTemp1) && (++(context)->Length_High == 0) ? 1 : 0) - -/* Local Function Prototypes */ -static void SHA1Finalize(SHA1Context *context, uint8_t Pad_Byte); -static void SHA1PadMessage(SHA1Context *, uint8_t Pad_Byte); -static void SHA1ProcessMessageBlock(SHA1Context *); - -/* - * SHA1Reset - * - * Description: - * This function will initialize the SHA1Context in preparation - * for computing a new SHA1 message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA1Reset(SHA1Context *context) { - if (!context) return shaNull; - - context->Length_Low = 0; - context->Length_High = 0; - context->Message_Block_Index = 0; - - /* Initial Hash Values: FIPS-180-2 section 5.3.1 */ - context->Intermediate_Hash[0] = 0x67452301; - context->Intermediate_Hash[1] = 0xEFCDAB89; - context->Intermediate_Hash[2] = 0x98BADCFE; - context->Intermediate_Hash[3] = 0x10325476; - context->Intermediate_Hash[4] = 0xC3D2E1F0; - - context->Computed = 0; - context->Corrupted = 0; - - return shaSuccess; -} - -/* - * SHA1Input - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - * - */ -inline int SHA1Input(SHA1Context *context, const uint8_t *message_array, unsigned length) { - if (!length) return shaSuccess; - - if (!context || !message_array) return shaNull; - - if (context->Computed) { - context->Corrupted = shaStateError; - return shaStateError; - } - - if (context->Corrupted) return context->Corrupted; - - while (length-- && !context->Corrupted) { - context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); - - if (!SHA1AddLength(context, 8) && (context->Message_Block_Index == SHA1_Message_Block_Size)) SHA1ProcessMessageBlock(context); - - message_array++; - } - - return shaSuccess; -} - -/* - * SHA1FinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - */ -inline int SHA1FinalBits(SHA1Context *context, const uint8_t message_bits, unsigned int length) { - uint8_t masks[8] = {/* 0 0b00000000 */ 0x00, /* 1 0b10000000 */ 0x80, - /* 2 0b11000000 */ 0xC0, /* 3 0b11100000 */ 0xE0, - /* 4 0b11110000 */ 0xF0, /* 5 0b11111000 */ 0xF8, - /* 6 0b11111100 */ 0xFC, /* 7 0b11111110 */ 0xFE}; - uint8_t markbit[8] = {/* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40, - /* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10, - /* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04, - /* 6 0b00000010 */ 0x02, /* 7 0b00000001 */ 0x01}; - - if (!length) return shaSuccess; - - if (!context) return shaNull; - - if (context->Computed || (length >= 8) || (length == 0)) { - context->Corrupted = shaStateError; - return shaStateError; - } - - if (context->Corrupted) return context->Corrupted; - - SHA1AddLength(context, length); - SHA1Finalize(context, (uint8_t)((message_bits & masks[length]) | markbit[length])); - - return shaSuccess; -} - -/* - * SHA1Result - * - * Description: - * This function will return the 160-bit message digest into the - * Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 19th element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA-1 hash. - * Message_Digest: [out] - * Where the digest is returned. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA1Result(SHA1Context *context, uint8_t Message_Digest[SHA1HashSize]) { - int i; - - if (!context || !Message_Digest) return shaNull; - - if (context->Corrupted) return context->Corrupted; - - if (!context->Computed) SHA1Finalize(context, 0x80); - - for (i = 0; i < SHA1HashSize; ++i) Message_Digest[i] = (uint8_t)(context->Intermediate_Hash[i >> 2] >> 8 * (3 - (i & 0x03))); - - return shaSuccess; -} - -/* - * SHA1Finalize - * - * Description: - * This helper function finishes off the digest calculations. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * Pad_Byte: [in] - * The last byte to add to the digest before the 0-padding - * and length. This will contain the last bits of the message - * followed by another single bit. If the message was an - * exact multiple of 8-bits long, Pad_Byte will be 0x80. - * - * Returns: - * sha Error Code. - * - */ -static void SHA1Finalize(SHA1Context *context, uint8_t Pad_Byte) { - int i; - SHA1PadMessage(context, Pad_Byte); - /* message may be sensitive, clear it out */ - for (i = 0; i < SHA1_Message_Block_Size; ++i) context->Message_Block[i] = 0; - context->Length_Low = 0; /* and clear length */ - context->Length_High = 0; - context->Computed = 1; -} - -/* - * SHA1PadMessage - * - * Description: - * According to the standard, the message must be padded to an - * even 512 bits. The first padding bit must be a '1'. The last - * 64 bits represent the length of the original message. All bits - * in between should be 0. This helper function will pad the - * message according to those rules by filling the Message_Block - * array accordingly. When it returns, it can be assumed that the - * message digest has been computed. - * - * Parameters: - * context: [in/out] - * The context to pad - * Pad_Byte: [in] - * The last byte to add to the digest before the 0-padding - * and length. This will contain the last bits of the message - * followed by another single bit. If the message was an - * exact multiple of 8-bits long, Pad_Byte will be 0x80. - * - * Returns: - * Nothing. - */ -static void SHA1PadMessage(SHA1Context *context, uint8_t Pad_Byte) { - /* - * Check to see if the current message block is too small to hold - * the initial padding bits and length. If so, we will pad the - * block, process it, and then continue padding into a second - * block. - */ - if (context->Message_Block_Index >= (SHA1_Message_Block_Size - 8)) { - context->Message_Block[context->Message_Block_Index++] = Pad_Byte; - while (context->Message_Block_Index < SHA1_Message_Block_Size) context->Message_Block[context->Message_Block_Index++] = 0; - - SHA1ProcessMessageBlock(context); - } else - context->Message_Block[context->Message_Block_Index++] = Pad_Byte; - - while (context->Message_Block_Index < (SHA1_Message_Block_Size - 8)) context->Message_Block[context->Message_Block_Index++] = 0; - - /* - * Store the message length as the last 8 octets - */ - context->Message_Block[56] = (uint8_t)(context->Length_High >> 24); - context->Message_Block[57] = (uint8_t)(context->Length_High >> 16); - context->Message_Block[58] = (uint8_t)(context->Length_High >> 8); - context->Message_Block[59] = (uint8_t)(context->Length_High); - context->Message_Block[60] = (uint8_t)(context->Length_Low >> 24); - context->Message_Block[61] = (uint8_t)(context->Length_Low >> 16); - context->Message_Block[62] = (uint8_t)(context->Length_Low >> 8); - context->Message_Block[63] = (uint8_t)(context->Length_Low); - - SHA1ProcessMessageBlock(context); -} - -/* - * SHA1ProcessMessageBlock - * - * Description: - * This helper function will process the next 512 bits of the - * message stored in the Message_Block array. - * - * Parameters: - * None. - * - * Returns: - * Nothing. - * - * Comments: - * Many of the variable names in this code, especially the - * single character names, were used because those were the - * names used in the publication. - */ -static void SHA1ProcessMessageBlock(SHA1Context *context) { - /* Constants defined in FIPS-180-2, section 4.2.1 */ - const uint32_t K[4] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6}; - int t; /* Loop counter */ - uint32_t temp; /* Temporary word value */ - uint32_t W[80]; /* Word sequence */ - uint32_t A, B, C, D, E; /* Word buffers */ - - /* - * Initialize the first 16 words in the array W - */ - for (t = 0; t < 16; t++) { - W[t] = ((uint32_t)context->Message_Block[t * 4]) << 24; - W[t] |= ((uint32_t)context->Message_Block[t * 4 + 1]) << 16; - W[t] |= ((uint32_t)context->Message_Block[t * 4 + 2]) << 8; - W[t] |= ((uint32_t)context->Message_Block[t * 4 + 3]); - } - for (t = 16; t < 80; t++) W[t] = SHA1_ROTL(1, W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16]); - - A = context->Intermediate_Hash[0]; - B = context->Intermediate_Hash[1]; - C = context->Intermediate_Hash[2]; - D = context->Intermediate_Hash[3]; - E = context->Intermediate_Hash[4]; - - for (t = 0; t < 20; t++) { - temp = SHA1_ROTL(5, A) + SHA_Ch(B, C, D) + E + W[t] + K[0]; - E = D; - D = C; - C = SHA1_ROTL(30, B); - B = A; - A = temp; - } - - for (t = 20; t < 40; t++) { - temp = SHA1_ROTL(5, A) + SHA_Parity(B, C, D) + E + W[t] + K[1]; - E = D; - D = C; - C = SHA1_ROTL(30, B); - B = A; - A = temp; - } - - for (t = 40; t < 60; t++) { - temp = SHA1_ROTL(5, A) + SHA_Maj(B, C, D) + E + W[t] + K[2]; - E = D; - D = C; - C = SHA1_ROTL(30, B); - B = A; - A = temp; - } - - for (t = 60; t < 80; t++) { - temp = SHA1_ROTL(5, A) + SHA_Parity(B, C, D) + E + W[t] + K[3]; - E = D; - D = C; - C = SHA1_ROTL(30, B); - B = A; - A = temp; - } - - context->Intermediate_Hash[0] += A; - context->Intermediate_Hash[1] += B; - context->Intermediate_Hash[2] += C; - context->Intermediate_Hash[3] += D; - context->Intermediate_Hash[4] += E; - - context->Message_Block_Index = 0; -} -/*************************** sha224-256.c ***************************/ -/********************* See RFC 4634 for details *********************/ -/* - * Description: - * This file implements the Secure Hash Signature Standard - * algorithms as defined in the National Institute of Standards - * and Technology Federal Information Processing Standards - * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 - * published on August 1, 2002, and the FIPS PUB 180-2 Change - * Notice published on February 28, 2004. - * - * A combined document showing all algorithms is available at - * http://csrc.nist.gov/publications/fips/ - * fips180-2/fips180-2withchangenotice.pdf - * - * The SHA-224 and SHA-256 algorithms produce 224-bit and 256-bit - * message digests for a given data stream. It should take about - * 2**n steps to find a message with the same digest as a given - * message and 2**(n/2) to find any two messages with the same - * digest, when n is the digest size in bits. Therefore, this - * algorithm can serve as a means of providing a - * "fingerprint" for a message. - * - * Portability Issues: - * SHA-224 and SHA-256 are defined in terms of 32-bit "words". - * This code uses (included via "sha.h") to define 32 - * and 8 bit unsigned integer types. If your C compiler does not - * support 32 bit unsigned integers, this code is not - * appropriate. - * - * Caveats: - * SHA-224 and SHA-256 are designed to work with messages less - * than 2^64 bits long. This implementation uses SHA224/256Input() - * to hash the bits that are a multiple of the size of an 8-bit - * character, and then uses SHA224/256FinalBits() to hash the - * final few bits of the input. - */ - -//#include "sha.h" -//#include "sha-private.h" -/* Define the SHA shift, rotate left and rotate right macro */ -#define SHA256_SHR(bits, word) ((word) >> (bits)) -#define SHA256_ROTL(bits, word) (((word) << (bits)) | ((word) >> (32 - (bits)))) -#define SHA256_ROTR(bits, word) (((word) >> (bits)) | ((word) << (32 - (bits)))) - -/* Define the SHA SIGMA and sigma macros */ -#define SHA256_SIGMA0(word) (SHA256_ROTR(2, word) ^ SHA256_ROTR(13, word) ^ SHA256_ROTR(22, word)) -#define SHA256_SIGMA1(word) (SHA256_ROTR(6, word) ^ SHA256_ROTR(11, word) ^ SHA256_ROTR(25, word)) -#define SHA256_sigma0(word) (SHA256_ROTR(7, word) ^ SHA256_ROTR(18, word) ^ SHA256_SHR(3, word)) -#define SHA256_sigma1(word) (SHA256_ROTR(17, word) ^ SHA256_ROTR(19, word) ^ SHA256_SHR(10, word)) - -/* - * add "length" to the length - */ -static uint32_t addTemp2; -#define SHA224_256AddLength(context, length) \ - (addTemp2 = (context)->Length_Low, (context)->Corrupted = (((context)->Length_Low += (length)) < addTemp2) && (++(context)->Length_High == 0) ? 1 : 0) - -/* Local Function Prototypes */ -static void SHA224_256Finalize(SHA256Context *context, uint8_t Pad_Byte); -static void SHA224_256PadMessage(SHA256Context *context, uint8_t Pad_Byte); -static void SHA224_256ProcessMessageBlock(SHA256Context *context); -static int SHA224_256Reset(SHA256Context *context, uint32_t *H0); -static int SHA224_256ResultN(SHA256Context *context, uint8_t Message_Digest[], int HashSize); - -/* Initial Hash Values: FIPS-180-2 Change Notice 1 */ -static uint32_t SHA224_H0[SHA256HashSize / 4] = {0xC1059ED8, 0x367CD507, 0x3070DD17, 0xF70E5939, 0xFFC00B31, 0x68581511, 0x64F98FA7, 0xBEFA4FA4}; - -/* Initial Hash Values: FIPS-180-2 section 5.3.2 */ -static uint32_t SHA256_H0[SHA256HashSize / 4] = {0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19}; - -/* - * SHA224Reset - * - * Description: - * This function will initialize the SHA384Context in preparation - * for computing a new SHA224 message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * - * Returns: - * sha Error Code. - */ -inline int SHA224Reset(SHA224Context *context) { return SHA224_256Reset(context, SHA224_H0); } - -/* - * SHA224Input - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - * - */ -inline int SHA224Input(SHA224Context *context, const uint8_t *message_array, unsigned int length) { return SHA256Input(context, message_array, length); } - -/* - * SHA224FinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - */ -inline int SHA224FinalBits(SHA224Context *context, const uint8_t message_bits, unsigned int length) { return SHA256FinalBits(context, message_bits, length); } - -/* - * SHA224Result - * - * Description: - * This function will return the 224-bit message - * digest into the Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 28th element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA hash. - * Message_Digest: [out] - * Where the digest is returned. - * - * Returns: - * sha Error Code. - */ -inline int SHA224Result(SHA224Context *context, uint8_t Message_Digest[SHA224HashSize]) { return SHA224_256ResultN(context, Message_Digest, SHA224HashSize); } - -/* - * SHA256Reset - * - * Description: - * This function will initialize the SHA256Context in preparation - * for computing a new SHA256 message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * - * Returns: - * sha Error Code. - */ -inline int SHA256Reset(SHA256Context *context) { return SHA224_256Reset(context, SHA256_H0); } - -/* - * SHA256Input - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - */ -inline int SHA256Input(SHA256Context *context, const uint8_t *message_array, unsigned int length) { - if (!length) return shaSuccess; - - if (!context || !message_array) return shaNull; - - if (context->Computed) { - context->Corrupted = shaStateError; - return shaStateError; - } - - if (context->Corrupted) return context->Corrupted; - - while (length-- && !context->Corrupted) { - context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); - - if (!SHA224_256AddLength(context, 8) && (context->Message_Block_Index == SHA256_Message_Block_Size)) SHA224_256ProcessMessageBlock(context); - - message_array++; - } - - return shaSuccess; -} - -/* - * SHA256FinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - */ -inline int SHA256FinalBits(SHA256Context *context, const uint8_t message_bits, unsigned int length) { - uint8_t masks[8] = {/* 0 0b00000000 */ 0x00, /* 1 0b10000000 */ 0x80, - /* 2 0b11000000 */ 0xC0, /* 3 0b11100000 */ 0xE0, - /* 4 0b11110000 */ 0xF0, /* 5 0b11111000 */ 0xF8, - /* 6 0b11111100 */ 0xFC, /* 7 0b11111110 */ 0xFE}; - uint8_t markbit[8] = {/* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40, - /* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10, - /* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04, - /* 6 0b00000010 */ 0x02, /* 7 0b00000001 */ 0x01}; - - if (!length) return shaSuccess; - - if (!context) return shaNull; - - if ((context->Computed) || (length >= 8) || (length == 0)) { - context->Corrupted = shaStateError; - return shaStateError; - } - - if (context->Corrupted) return context->Corrupted; - - SHA224_256AddLength(context, length); - SHA224_256Finalize(context, (uint8_t)((message_bits & masks[length]) | markbit[length])); - - return shaSuccess; -} - -/* - * SHA256Result - * - * Description: - * This function will return the 256-bit message - * digest into the Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 32nd element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA hash. - * Message_Digest: [out] - * Where the digest is returned. - * - * Returns: - * sha Error Code. - */ -inline int SHA256Result(SHA256Context *context, uint8_t Message_Digest[]) { return SHA224_256ResultN(context, Message_Digest, SHA256HashSize); } - -/* - * SHA224_256Finalize - * - * Description: - * This helper function finishes off the digest calculations. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * Pad_Byte: [in] - * The last byte to add to the digest before the 0-padding - * and length. This will contain the last bits of the message - * followed by another single bit. If the message was an - * exact multiple of 8-bits long, Pad_Byte will be 0x80. - * - * Returns: - * sha Error Code. - */ -static void SHA224_256Finalize(SHA256Context *context, uint8_t Pad_Byte) { - int i; - SHA224_256PadMessage(context, Pad_Byte); - /* message may be sensitive, so clear it out */ - for (i = 0; i < SHA256_Message_Block_Size; ++i) context->Message_Block[i] = 0; - context->Length_Low = 0; /* and clear length */ - context->Length_High = 0; - context->Computed = 1; -} - -/* - * SHA224_256PadMessage - * - * Description: - * According to the standard, the message must be padded to an - * even 512 bits. The first padding bit must be a '1'. The - * last 64 bits represent the length of the original message. - * All bits in between should be 0. This helper function will pad - * the message according to those rules by filling the - * Message_Block array accordingly. When it returns, it can be - * assumed that the message digest has been computed. - * - * Parameters: - * context: [in/out] - * The context to pad - * Pad_Byte: [in] - * The last byte to add to the digest before the 0-padding - * and length. This will contain the last bits of the message - * followed by another single bit. If the message was an - * exact multiple of 8-bits long, Pad_Byte will be 0x80. - * - * Returns: - * Nothing. - */ -static void SHA224_256PadMessage(SHA256Context *context, uint8_t Pad_Byte) { - /* - * Check to see if the current message block is too small to hold - * the initial padding bits and length. If so, we will pad the - * block, process it, and then continue padding into a second - * block. - */ - if (context->Message_Block_Index >= (SHA256_Message_Block_Size - 8)) { - context->Message_Block[context->Message_Block_Index++] = Pad_Byte; - while (context->Message_Block_Index < SHA256_Message_Block_Size) context->Message_Block[context->Message_Block_Index++] = 0; - SHA224_256ProcessMessageBlock(context); - } else - context->Message_Block[context->Message_Block_Index++] = Pad_Byte; - - while (context->Message_Block_Index < (SHA256_Message_Block_Size - 8)) context->Message_Block[context->Message_Block_Index++] = 0; - - /* - * Store the message length as the last 8 octets - */ - context->Message_Block[56] = (uint8_t)(context->Length_High >> 24); - context->Message_Block[57] = (uint8_t)(context->Length_High >> 16); - context->Message_Block[58] = (uint8_t)(context->Length_High >> 8); - context->Message_Block[59] = (uint8_t)(context->Length_High); - context->Message_Block[60] = (uint8_t)(context->Length_Low >> 24); - context->Message_Block[61] = (uint8_t)(context->Length_Low >> 16); - context->Message_Block[62] = (uint8_t)(context->Length_Low >> 8); - context->Message_Block[63] = (uint8_t)(context->Length_Low); - - SHA224_256ProcessMessageBlock(context); -} - -/* - * SHA224_256ProcessMessageBlock - * - * Description: - * This function will process the next 512 bits of the message - * stored in the Message_Block array. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * - * Returns: - * Nothing. - * - * Comments: - * Many of the variable names in this code, especially the - * single character names, were used because those were the - * names used in the publication. - */ -static void SHA224_256ProcessMessageBlock(SHA256Context *context) { - /* Constants defined in FIPS-180-2, section 4.2.2 */ - static const uint32_t K[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, - 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, - 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, - 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; - int t, t4; /* Loop counter */ - uint32_t temp1, temp2; /* Temporary word value */ - uint32_t W[64]; /* Word sequence */ - uint32_t A, B, C, D, E, F, G, H; /* Word buffers */ - - /* - * Initialize the first 16 words in the array W - */ - for (t = t4 = 0; t < 16; t++, t4 += 4) - W[t] = (((uint32_t)context->Message_Block[t4]) << 24) | (((uint32_t)context->Message_Block[t4 + 1]) << 16) | - (((uint32_t)context->Message_Block[t4 + 2]) << 8) | (((uint32_t)context->Message_Block[t4 + 3])); - - for (t = 16; t < 64; t++) W[t] = SHA256_sigma1(W[t - 2]) + W[t - 7] + SHA256_sigma0(W[t - 15]) + W[t - 16]; - - A = context->Intermediate_Hash[0]; - B = context->Intermediate_Hash[1]; - C = context->Intermediate_Hash[2]; - D = context->Intermediate_Hash[3]; - E = context->Intermediate_Hash[4]; - F = context->Intermediate_Hash[5]; - G = context->Intermediate_Hash[6]; - H = context->Intermediate_Hash[7]; - - for (t = 0; t < 64; t++) { - temp1 = H + SHA256_SIGMA1(E) + SHA_Ch(E, F, G) + K[t] + W[t]; - temp2 = SHA256_SIGMA0(A) + SHA_Maj(A, B, C); - H = G; - G = F; - F = E; - E = D + temp1; - D = C; - C = B; - B = A; - A = temp1 + temp2; - } - - context->Intermediate_Hash[0] += A; - context->Intermediate_Hash[1] += B; - context->Intermediate_Hash[2] += C; - context->Intermediate_Hash[3] += D; - context->Intermediate_Hash[4] += E; - context->Intermediate_Hash[5] += F; - context->Intermediate_Hash[6] += G; - context->Intermediate_Hash[7] += H; - - context->Message_Block_Index = 0; -} - -/* - * SHA224_256Reset - * - * Description: - * This helper function will initialize the SHA256Context in - * preparation for computing a new SHA256 message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * H0 - * The initial hash value to use. - * - * Returns: - * sha Error Code. - */ -static int SHA224_256Reset(SHA256Context *context, uint32_t *H0) { - if (!context) return shaNull; - - context->Length_Low = 0; - context->Length_High = 0; - context->Message_Block_Index = 0; - - context->Intermediate_Hash[0] = H0[0]; - context->Intermediate_Hash[1] = H0[1]; - context->Intermediate_Hash[2] = H0[2]; - context->Intermediate_Hash[3] = H0[3]; - context->Intermediate_Hash[4] = H0[4]; - context->Intermediate_Hash[5] = H0[5]; - context->Intermediate_Hash[6] = H0[6]; - context->Intermediate_Hash[7] = H0[7]; - - context->Computed = 0; - context->Corrupted = 0; - - return shaSuccess; -} - -/* - * SHA224_256ResultN - * - * Description: - * This helper function will return the 224-bit or 256-bit message - * digest into the Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 28th/32nd element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA hash. - * Message_Digest: [out] - * Where the digest is returned. - * HashSize: [in] - * The size of the hash, either 28 or 32. - * - * Returns: - * sha Error Code. - */ -static int SHA224_256ResultN(SHA256Context *context, uint8_t Message_Digest[], int HashSize) { - int i; - - if (!context || !Message_Digest) return shaNull; - - if (context->Corrupted) return context->Corrupted; - - if (!context->Computed) SHA224_256Finalize(context, 0x80); - - for (i = 0; i < HashSize; ++i) Message_Digest[i] = (uint8_t)(context->Intermediate_Hash[i >> 2] >> 8 * (3 - (i & 0x03))); - - return shaSuccess; -} -/*************************** sha384-512.c ***************************/ -/********************* See RFC 4634 for details *********************/ -/* - * Description: - * This file implements the Secure Hash Signature Standard - * algorithms as defined in the National Institute of Standards - * and Technology Federal Information Processing Standards - * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 - * published on August 1, 2002, and the FIPS PUB 180-2 Change - * Notice published on February 28, 2004. - * - * A combined document showing all algorithms is available at - * http://csrc.nist.gov/publications/fips/ - * fips180-2/fips180-2withchangenotice.pdf - * - * The SHA-384 and SHA-512 algorithms produce 384-bit and 512-bit - * message digests for a given data stream. It should take about - * 2**n steps to find a message with the same digest as a given - * message and 2**(n/2) to find any two messages with the same - * digest, when n is the digest size in bits. Therefore, this - * algorithm can serve as a means of providing a - * "fingerprint" for a message. - * - * Portability Issues: - * SHA-384 and SHA-512 are defined in terms of 64-bit "words", - * but if USE_32BIT_ONLY is #defined, this code is implemented in - * terms of 32-bit "words". This code uses (included - * via "sha.h") to define the 64, 32 and 8 bit unsigned integer - * types. If your C compiler does not support 64 bit unsigned - * integers, and you do not #define USE_32BIT_ONLY, this code is - * not appropriate. - * - * Caveats: - * SHA-384 and SHA-512 are designed to work with messages less - * than 2^128 bits long. This implementation uses - * SHA384/512Input() to hash the bits that are a multiple of the - * size of an 8-bit character, and then uses SHA384/256FinalBits() - * to hash the final few bits of the input. - * - */ - -//#include "sha.h" -//#include "sha-private.h" - -#ifdef USE_32BIT_ONLY -/* - * Define 64-bit arithmetic in terms of 32-bit arithmetic. - * Each 64-bit number is represented in a 2-word array. - * All macros are defined such that the result is the last parameter. - */ - -/* - * Define shift, rotate left and rotate right functions - */ -#define SHA512_SHR(bits, word, ret) \ - (/* (((uint64_t)((word))) >> (bits)) */ \ - (ret)[0] = (((bits) < 32) && ((bits) >= 0)) ? ((word)[0] >> (bits)) : 0, \ - (ret)[1] = \ - ((bits) > 32) ? ((word)[0] >> ((bits)-32)) : ((bits) == 32) ? (word)[0] : ((bits) >= 0) ? (((word)[0] << (32 - (bits))) | ((word)[1] >> (bits))) : 0) - -#define SHA512_SHL(bits, word, ret) \ - (/* (((uint64_t)(word)) << (bits)) */ \ - (ret)[0] = \ - ((bits) > 32) ? ((word)[1] << ((bits)-32)) : ((bits) == 32) ? (word)[1] : ((bits) >= 0) ? (((word)[0] << (bits)) | ((word)[1] >> (32 - (bits)))) : 0, \ - (ret)[1] = (((bits) < 32) && ((bits) >= 0)) ? ((word)[1] << (bits)) : 0) - -/* - * Define 64-bit OR - */ -#define SHA512_OR(word1, word2, ret) ((ret)[0] = (word1)[0] | (word2)[0], (ret)[1] = (word1)[1] | (word2)[1]) - -/* - * Define 64-bit XOR - */ -#define SHA512_XOR(word1, word2, ret) ((ret)[0] = (word1)[0] ^ (word2)[0], (ret)[1] = (word1)[1] ^ (word2)[1]) - -/* - * Define 64-bit AND - */ -#define SHA512_AND(word1, word2, ret) ((ret)[0] = (word1)[0] & (word2)[0], (ret)[1] = (word1)[1] & (word2)[1]) - -/* - * Define 64-bit TILDA - */ -#define SHA512_TILDA(word, ret) ((ret)[0] = ~(word)[0], (ret)[1] = ~(word)[1]) - -/* - * Define 64-bit ADD - */ -#define SHA512_ADD(word1, word2, ret) ((ret)[1] = (word1)[1], (ret)[1] += (word2)[1], (ret)[0] = (word1)[0] + (word2)[0] + ((ret)[1] < (word1)[1])) - -/* - * Add the 4word value in word2 to word1. - */ -static uint32_t ADDTO4_temp, ADDTO4_temp2; -#define SHA512_ADDTO4(word1, word2) \ - (ADDTO4_temp = (word1)[3], (word1)[3] += (word2)[3], ADDTO4_temp2 = (word1)[2], (word1)[2] += (word2)[2] + ((word1)[3] < ADDTO4_temp), \ - ADDTO4_temp = (word1)[1], (word1)[1] += (word2)[1] + ((word1)[2] < ADDTO4_temp2), (word1)[0] += (word2)[0] + ((word1)[1] < ADDTO4_temp)) - -/* - * Add the 2word value in word2 to word1. - */ -static uint32_t ADDTO2_temp; -#define SHA512_ADDTO2(word1, word2) (ADDTO2_temp = (word1)[1], (word1)[1] += (word2)[1], (word1)[0] += (word2)[0] + ((word1)[1] < ADDTO2_temp)) - -/* - * SHA rotate ((word >> bits) | (word << (64-bits))) - */ -static uint32_t ROTR_temp1[2], ROTR_temp2[2]; -#define SHA512_ROTR(bits, word, ret) \ - (SHA512_SHR((bits), (word), ROTR_temp1), SHA512_SHL(64 - (bits), (word), ROTR_temp2), SHA512_OR(ROTR_temp1, ROTR_temp2, (ret))) - -/* - * Define the SHA SIGMA and sigma macros - * SHA512_ROTR(28,word) ^ SHA512_ROTR(34,word) ^ SHA512_ROTR(39,word) - */ -static uint32_t SIGMA0_temp1[2], SIGMA0_temp2[2], SIGMA0_temp3[2], SIGMA0_temp4[2]; -#define SHA512_SIGMA0(word, ret) \ - (SHA512_ROTR(28, (word), SIGMA0_temp1), SHA512_ROTR(34, (word), SIGMA0_temp2), SHA512_ROTR(39, (word), SIGMA0_temp3), \ - SHA512_XOR(SIGMA0_temp2, SIGMA0_temp3, SIGMA0_temp4), SHA512_XOR(SIGMA0_temp1, SIGMA0_temp4, (ret))) - -/* - * SHA512_ROTR(14,word) ^ SHA512_ROTR(18,word) ^ SHA512_ROTR(41,word) - */ -static uint32_t SIGMA1_temp1[2], SIGMA1_temp2[2], SIGMA1_temp3[2], SIGMA1_temp4[2]; -#define SHA512_SIGMA1(word, ret) \ - (SHA512_ROTR(14, (word), SIGMA1_temp1), SHA512_ROTR(18, (word), SIGMA1_temp2), SHA512_ROTR(41, (word), SIGMA1_temp3), \ - SHA512_XOR(SIGMA1_temp2, SIGMA1_temp3, SIGMA1_temp4), SHA512_XOR(SIGMA1_temp1, SIGMA1_temp4, (ret))) - -/* - * (SHA512_ROTR( 1,word) ^ SHA512_ROTR( 8,word) ^ SHA512_SHR( 7,word)) - */ -static uint32_t sigma0_temp1[2], sigma0_temp2[2], sigma0_temp3[2], sigma0_temp4[2]; -#define SHA512_sigma0(word, ret) \ - (SHA512_ROTR(1, (word), sigma0_temp1), SHA512_ROTR(8, (word), sigma0_temp2), SHA512_SHR(7, (word), sigma0_temp3), \ - SHA512_XOR(sigma0_temp2, sigma0_temp3, sigma0_temp4), SHA512_XOR(sigma0_temp1, sigma0_temp4, (ret))) - -/* - * (SHA512_ROTR(19,word) ^ SHA512_ROTR(61,word) ^ SHA512_SHR( 6,word)) - */ -static uint32_t sigma1_temp1[2], sigma1_temp2[2], sigma1_temp3[2], sigma1_temp4[2]; -#define SHA512_sigma1(word, ret) \ - (SHA512_ROTR(19, (word), sigma1_temp1), SHA512_ROTR(61, (word), sigma1_temp2), SHA512_SHR(6, (word), sigma1_temp3), \ - SHA512_XOR(sigma1_temp2, sigma1_temp3, sigma1_temp4), SHA512_XOR(sigma1_temp1, sigma1_temp4, (ret))) - -#undef SHA_Ch -#undef SHA_Maj - -#ifndef USE_MODIFIED_MACROS -/* - * These definitions are the ones used in FIPS-180-2, section 4.1.3 - * Ch(x,y,z) ((x & y) ^ (~x & z)) - */ -static uint32_t Ch_temp1[2], Ch_temp2[2], Ch_temp3[2]; -#define SHA_Ch(x, y, z, ret) (SHA512_AND(x, y, Ch_temp1), SHA512_TILDA(x, Ch_temp2), SHA512_AND(Ch_temp2, z, Ch_temp3), SHA512_XOR(Ch_temp1, Ch_temp3, (ret))) -/* - * Maj(x,y,z) (((x)&(y)) ^ ((x)&(z)) ^ ((y)&(z))) - */ -static uint32_t Maj_temp1[2], Maj_temp2[2], Maj_temp3[2], Maj_temp4[2]; -#define SHA_Maj(x, y, z, ret) \ - (SHA512_AND(x, y, Maj_temp1), SHA512_AND(x, z, Maj_temp2), SHA512_AND(y, z, Maj_temp3), SHA512_XOR(Maj_temp2, Maj_temp3, Maj_temp4), \ - SHA512_XOR(Maj_temp1, Maj_temp4, (ret))) - -#else /* !USE_32BIT_ONLY */ - /* - * These definitions are potentially faster equivalents for the ones - * used in FIPS-180-2, section 4.1.3. - * ((x & y) ^ (~x & z)) becomes - * ((x & (y ^ z)) ^ z) - */ -#define SHA_Ch(x, y, z, ret) ((ret)[0] = (((x)[0] & ((y)[0] ^ (z)[0])) ^ (z)[0]), (ret)[1] = (((x)[1] & ((y)[1] ^ (z)[1])) ^ (z)[1])) - -/* - * ((x & y) ^ (x & z) ^ (y & z)) becomes - * ((x & (y | z)) | (y & z)) - */ -#define SHA_Maj(x, y, z, ret) (ret[0] = (((x)[0] & ((y)[0] | (z)[0])) | ((y)[0] & (z)[0])), ret[1] = (((x)[1] & ((y)[1] | (z)[1])) | ((y)[1] & (z)[1]))) -#endif /* USE_MODIFIED_MACROS */ - -/* - * add "length" to the length - */ -static uint32_t addTemp3[4] = {0, 0, 0, 0}; - -#define SHA384_512AddLength(context, length) \ - (addTemp3[3] = (length), SHA512_ADDTO4((context)->Length, addTemp3), \ - (context)->Corrupted = (((context)->Length[3] == 0) && ((context)->Length[2] == 0) && ((context)->Length[1] == 0) && ((context)->Length[0] < 8)) ? 1 : 0) - -/* Local Function Prototypes */ -static void SHA384_512Finalize(SHA512Context *context, uint8_t Pad_Byte); -static void SHA384_512PadMessage(SHA512Context *context, uint8_t Pad_Byte); -static void SHA384_512ProcessMessageBlock(SHA512Context *context); -static int SHA384_512Reset(SHA512Context *context, uint32_t H0[]); -static int SHA384_512ResultN(SHA512Context *context, uint8_t Message_Digest[], int HashSize); - -/* Initial Hash Values: FIPS-180-2 sections 5.3.3 and 5.3.4 */ -static uint32_t SHA384_H0[SHA512HashSize / 4] = {0xCBBB9D5D, 0xC1059ED8, 0x629A292A, 0x367CD507, 0x9159015A, 0x3070DD17, 0x152FECD8, 0xF70E5939, - 0x67332667, 0xFFC00B31, 0x8EB44A87, 0x68581511, 0xDB0C2E0D, 0x64F98FA7, 0x47B5481D, 0xBEFA4FA4}; - -static uint32_t SHA512_H0[SHA512HashSize / 4] = {0x6A09E667, 0xF3BCC908, 0xBB67AE85, 0x84CAA73B, 0x3C6EF372, 0xFE94F82B, 0xA54FF53A, 0x5F1D36F1, - 0x510E527F, 0xADE682D1, 0x9B05688C, 0x2B3E6C1F, 0x1F83D9AB, 0xFB41BD6B, 0x5BE0CD19, 0x137E2179}; - -#else /* !USE_32BIT_ONLY */ - -/* Define the SHA shift, rotate left and rotate right macro */ -#define SHA512_SHR(bits, word) (((uint64_t)(word)) >> (bits)) -#define SHA512_ROTR(bits, word) ((((uint64_t)(word)) >> (bits)) | (((uint64_t)(word)) << (64 - (bits)))) - -/* Define the SHA SIGMA and sigma macros */ -#define SHA512_SIGMA0(word) (SHA512_ROTR(28, word) ^ SHA512_ROTR(34, word) ^ SHA512_ROTR(39, word)) -#define SHA512_SIGMA1(word) (SHA512_ROTR(14, word) ^ SHA512_ROTR(18, word) ^ SHA512_ROTR(41, word)) -#define SHA512_sigma0(word) (SHA512_ROTR(1, word) ^ SHA512_ROTR(8, word) ^ SHA512_SHR(7, word)) -#define SHA512_sigma1(word) (SHA512_ROTR(19, word) ^ SHA512_ROTR(61, word) ^ SHA512_SHR(6, word)) - -/* - * add "length" to the length - */ -static uint64_t addTemp4; -#define SHA384_512AddLength(context, length) \ - (addTemp4 = context->Length_Low, context->Corrupted = ((context->Length_Low += length) < addTemp4) && (++context->Length_High == 0) ? 1 : 0) - -/* Local Function Prototypes */ -static void SHA384_512Finalize(SHA512Context *context, uint8_t Pad_Byte); -static void SHA384_512PadMessage(SHA512Context *context, uint8_t Pad_Byte); -static void SHA384_512ProcessMessageBlock(SHA512Context *context); -static int SHA384_512Reset(SHA512Context *context, uint64_t H0[]); -static int SHA384_512ResultN(SHA512Context *context, uint8_t Message_Digest[], int HashSize); - -/* Initial Hash Values: FIPS-180-2 sections 5.3.3 and 5.3.4 */ -static uint64_t SHA384_H0[] = {0xCBBB9D5DC1059ED8ll, 0x629A292A367CD507ll, 0x9159015A3070DD17ll, 0x152FECD8F70E5939ll, - 0x67332667FFC00B31ll, 0x8EB44A8768581511ll, 0xDB0C2E0D64F98FA7ll, 0x47B5481DBEFA4FA4ll}; - -static uint64_t SHA512_H0[] = {0x6A09E667F3BCC908ll, 0xBB67AE8584CAA73Bll, 0x3C6EF372FE94F82Bll, 0xA54FF53A5F1D36F1ll, - 0x510E527FADE682D1ll, 0x9B05688C2B3E6C1Fll, 0x1F83D9ABFB41BD6Bll, 0x5BE0CD19137E2179ll}; - -#endif /* USE_32BIT_ONLY */ - -/* - * SHA384Reset - * - * Description: - * This function will initialize the SHA384Context in preparation - * for computing a new SHA384 message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA384Reset(SHA384Context *context) { return SHA384_512Reset(context, SHA384_H0); } - -/* - * SHA384Input - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - * - */ -inline int SHA384Input(SHA384Context *context, const uint8_t *message_array, unsigned int length) { return SHA512Input(context, message_array, length); } - -/* - * SHA384FinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA384FinalBits(SHA384Context *context, const uint8_t message_bits, unsigned int length) { return SHA512FinalBits(context, message_bits, length); } - -/* - * SHA384Result - * - * Description: - * This function will return the 384-bit message - * digest into the Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 48th element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA hash. - * Message_Digest: [out] - * Where the digest is returned. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA384Result(SHA384Context *context, uint8_t Message_Digest[SHA384HashSize]) { return SHA384_512ResultN(context, Message_Digest, SHA384HashSize); } - -/* - * SHA512Reset - * - * Description: - * This function will initialize the SHA512Context in preparation - * for computing a new SHA512 message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA512Reset(SHA512Context *context) { return SHA384_512Reset(context, SHA512_H0); } - -/* - * SHA512Input - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - * - */ -inline int SHA512Input(SHA512Context *context, const uint8_t *message_array, unsigned int length) { - if (!length) return shaSuccess; - - if (!context || !message_array) return shaNull; - - if (context->Computed) { - context->Corrupted = shaStateError; - return shaStateError; - } - - if (context->Corrupted) return context->Corrupted; - - while (length-- && !context->Corrupted) { - context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); - - if (!SHA384_512AddLength(context, 8) && (context->Message_Block_Index == SHA512_Message_Block_Size)) SHA384_512ProcessMessageBlock(context); - - message_array++; - } - - return shaSuccess; -} - -/* - * SHA512FinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA512FinalBits(SHA512Context *context, const uint8_t message_bits, unsigned int length) { - uint8_t masks[8] = {/* 0 0b00000000 */ 0x00, /* 1 0b10000000 */ 0x80, - /* 2 0b11000000 */ 0xC0, /* 3 0b11100000 */ 0xE0, - /* 4 0b11110000 */ 0xF0, /* 5 0b11111000 */ 0xF8, - /* 6 0b11111100 */ 0xFC, /* 7 0b11111110 */ 0xFE}; - uint8_t markbit[8] = {/* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40, - /* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10, - /* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04, - /* 6 0b00000010 */ 0x02, /* 7 0b00000001 */ 0x01}; - - if (!length) return shaSuccess; - - if (!context) return shaNull; - - if ((context->Computed) || (length >= 8) || (length == 0)) { - context->Corrupted = shaStateError; - return shaStateError; - } - - if (context->Corrupted) return context->Corrupted; - - SHA384_512AddLength(context, length); - SHA384_512Finalize(context, (uint8_t)((message_bits & masks[length]) | markbit[length])); - - return shaSuccess; -} - -/* - * SHA384_512Finalize - * - * Description: - * This helper function finishes off the digest calculations. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * Pad_Byte: [in] - * The last byte to add to the digest before the 0-padding - * and length. This will contain the last bits of the message - * followed by another single bit. If the message was an - * exact multiple of 8-bits long, Pad_Byte will be 0x80. - * - * Returns: - * sha Error Code. - * - */ -static void SHA384_512Finalize(SHA512Context *context, uint8_t Pad_Byte) { - int_least16_t i; - SHA384_512PadMessage(context, Pad_Byte); - /* message may be sensitive, clear it out */ - for (i = 0; i < SHA512_Message_Block_Size; ++i) context->Message_Block[i] = 0; -#ifdef USE_32BIT_ONLY /* and clear length */ - context->Length[0] = context->Length[1] = 0; - context->Length[2] = context->Length[3] = 0; -#else /* !USE_32BIT_ONLY */ - context->Length_Low = 0; - context->Length_High = 0; -#endif /* USE_32BIT_ONLY */ - context->Computed = 1; -} - -/* - * SHA512Result - * - * Description: - * This function will return the 512-bit message - * digest into the Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 64th element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA hash. - * Message_Digest: [out] - * Where the digest is returned. - * - * Returns: - * sha Error Code. - * - */ -inline int SHA512Result(SHA512Context *context, uint8_t Message_Digest[SHA512HashSize]) { return SHA384_512ResultN(context, Message_Digest, SHA512HashSize); } - -/* - * SHA384_512PadMessage - * - * Description: - * According to the standard, the message must be padded to an - * even 1024 bits. The first padding bit must be a '1'. The - * last 128 bits represent the length of the original message. - * All bits in between should be 0. This helper function will - * pad the message according to those rules by filling the - * Message_Block array accordingly. When it returns, it can be - * assumed that the message digest has been computed. - * - * Parameters: - * context: [in/out] - * The context to pad - * Pad_Byte: [in] - * The last byte to add to the digest before the 0-padding - * and length. This will contain the last bits of the message - * followed by another single bit. If the message was an - * exact multiple of 8-bits long, Pad_Byte will be 0x80. - * - * Returns: - * Nothing. - * - */ -static void SHA384_512PadMessage(SHA512Context *context, uint8_t Pad_Byte) { - /* - * Check to see if the current message block is too small to hold - * the initial padding bits and length. If so, we will pad the - * block, process it, and then continue padding into a second - * block. - */ - if (context->Message_Block_Index >= (SHA512_Message_Block_Size - 16)) { - context->Message_Block[context->Message_Block_Index++] = Pad_Byte; - while (context->Message_Block_Index < SHA512_Message_Block_Size) context->Message_Block[context->Message_Block_Index++] = 0; - - SHA384_512ProcessMessageBlock(context); - } else - context->Message_Block[context->Message_Block_Index++] = Pad_Byte; - - while (context->Message_Block_Index < (SHA512_Message_Block_Size - 16)) context->Message_Block[context->Message_Block_Index++] = 0; - - /* - * Store the message length as the last 16 octets - */ -#ifdef USE_32BIT_ONLY - context->Message_Block[112] = (uint8_t)(context->Length[0] >> 24); - context->Message_Block[113] = (uint8_t)(context->Length[0] >> 16); - context->Message_Block[114] = (uint8_t)(context->Length[0] >> 8); - context->Message_Block[115] = (uint8_t)(context->Length[0]); - context->Message_Block[116] = (uint8_t)(context->Length[1] >> 24); - context->Message_Block[117] = (uint8_t)(context->Length[1] >> 16); - context->Message_Block[118] = (uint8_t)(context->Length[1] >> 8); - context->Message_Block[119] = (uint8_t)(context->Length[1]); - - context->Message_Block[120] = (uint8_t)(context->Length[2] >> 24); - context->Message_Block[121] = (uint8_t)(context->Length[2] >> 16); - context->Message_Block[122] = (uint8_t)(context->Length[2] >> 8); - context->Message_Block[123] = (uint8_t)(context->Length[2]); - context->Message_Block[124] = (uint8_t)(context->Length[3] >> 24); - context->Message_Block[125] = (uint8_t)(context->Length[3] >> 16); - context->Message_Block[126] = (uint8_t)(context->Length[3] >> 8); - context->Message_Block[127] = (uint8_t)(context->Length[3]); -#else /* !USE_32BIT_ONLY */ - context->Message_Block[112] = (uint8_t)(context->Length_High >> 56); - context->Message_Block[113] = (uint8_t)(context->Length_High >> 48); - context->Message_Block[114] = (uint8_t)(context->Length_High >> 40); - context->Message_Block[115] = (uint8_t)(context->Length_High >> 32); - context->Message_Block[116] = (uint8_t)(context->Length_High >> 24); - context->Message_Block[117] = (uint8_t)(context->Length_High >> 16); - context->Message_Block[118] = (uint8_t)(context->Length_High >> 8); - context->Message_Block[119] = (uint8_t)(context->Length_High); - - context->Message_Block[120] = (uint8_t)(context->Length_Low >> 56); - context->Message_Block[121] = (uint8_t)(context->Length_Low >> 48); - context->Message_Block[122] = (uint8_t)(context->Length_Low >> 40); - context->Message_Block[123] = (uint8_t)(context->Length_Low >> 32); - context->Message_Block[124] = (uint8_t)(context->Length_Low >> 24); - context->Message_Block[125] = (uint8_t)(context->Length_Low >> 16); - context->Message_Block[126] = (uint8_t)(context->Length_Low >> 8); - context->Message_Block[127] = (uint8_t)(context->Length_Low); -#endif /* USE_32BIT_ONLY */ - - SHA384_512ProcessMessageBlock(context); -} - -/* - * SHA384_512ProcessMessageBlock - * - * Description: - * This helper function will process the next 1024 bits of the - * message stored in the Message_Block array. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * - * Returns: - * Nothing. - * - * Comments: - * Many of the variable names in this code, especially the - * single character names, were used because those were the - * names used in the publication. - * - * - */ -static void SHA384_512ProcessMessageBlock(SHA512Context *context) { - /* Constants defined in FIPS-180-2, section 4.2.3 */ -#ifdef USE_32BIT_ONLY - static const uint32_t K[80 * 2] = { - 0x428A2F98, 0xD728AE22, 0x71374491, 0x23EF65CD, 0xB5C0FBCF, 0xEC4D3B2F, 0xE9B5DBA5, 0x8189DBBC, 0x3956C25B, 0xF348B538, 0x59F111F1, 0xB605D019, - 0x923F82A4, 0xAF194F9B, 0xAB1C5ED5, 0xDA6D8118, 0xD807AA98, 0xA3030242, 0x12835B01, 0x45706FBE, 0x243185BE, 0x4EE4B28C, 0x550C7DC3, 0xD5FFB4E2, - 0x72BE5D74, 0xF27B896F, 0x80DEB1FE, 0x3B1696B1, 0x9BDC06A7, 0x25C71235, 0xC19BF174, 0xCF692694, 0xE49B69C1, 0x9EF14AD2, 0xEFBE4786, 0x384F25E3, - 0x0FC19DC6, 0x8B8CD5B5, 0x240CA1CC, 0x77AC9C65, 0x2DE92C6F, 0x592B0275, 0x4A7484AA, 0x6EA6E483, 0x5CB0A9DC, 0xBD41FBD4, 0x76F988DA, 0x831153B5, - 0x983E5152, 0xEE66DFAB, 0xA831C66D, 0x2DB43210, 0xB00327C8, 0x98FB213F, 0xBF597FC7, 0xBEEF0EE4, 0xC6E00BF3, 0x3DA88FC2, 0xD5A79147, 0x930AA725, - 0x06CA6351, 0xE003826F, 0x14292967, 0x0A0E6E70, 0x27B70A85, 0x46D22FFC, 0x2E1B2138, 0x5C26C926, 0x4D2C6DFC, 0x5AC42AED, 0x53380D13, 0x9D95B3DF, - 0x650A7354, 0x8BAF63DE, 0x766A0ABB, 0x3C77B2A8, 0x81C2C92E, 0x47EDAEE6, 0x92722C85, 0x1482353B, 0xA2BFE8A1, 0x4CF10364, 0xA81A664B, 0xBC423001, - 0xC24B8B70, 0xD0F89791, 0xC76C51A3, 0x0654BE30, 0xD192E819, 0xD6EF5218, 0xD6990624, 0x5565A910, 0xF40E3585, 0x5771202A, 0x106AA070, 0x32BBD1B8, - 0x19A4C116, 0xB8D2D0C8, 0x1E376C08, 0x5141AB53, 0x2748774C, 0xDF8EEB99, 0x34B0BCB5, 0xE19B48A8, 0x391C0CB3, 0xC5C95A63, 0x4ED8AA4A, 0xE3418ACB, - 0x5B9CCA4F, 0x7763E373, 0x682E6FF3, 0xD6B2B8A3, 0x748F82EE, 0x5DEFB2FC, 0x78A5636F, 0x43172F60, 0x84C87814, 0xA1F0AB72, 0x8CC70208, 0x1A6439EC, - 0x90BEFFFA, 0x23631E28, 0xA4506CEB, 0xDE82BDE9, 0xBEF9A3F7, 0xB2C67915, 0xC67178F2, 0xE372532B, 0xCA273ECE, 0xEA26619C, 0xD186B8C7, 0x21C0C207, - 0xEADA7DD6, 0xCDE0EB1E, 0xF57D4F7F, 0xEE6ED178, 0x06F067AA, 0x72176FBA, 0x0A637DC5, 0xA2C898A6, 0x113F9804, 0xBEF90DAE, 0x1B710B35, 0x131C471B, - 0x28DB77F5, 0x23047D84, 0x32CAAB7B, 0x40C72493, 0x3C9EBE0A, 0x15C9BEBC, 0x431D67C4, 0x9C100D4C, 0x4CC5D4BE, 0xCB3E42B6, 0x597F299C, 0xFC657E2A, - 0x5FCB6FAB, 0x3AD6FAEC, 0x6C44198C, 0x4A475817}; - int t, t2, t8; /* Loop counter */ - uint32_t temp1[2], temp2[2], /* Temporary word values */ - temp3[2], temp4[2], temp5[2]; - uint32_t W[2 * 80]; /* Word sequence */ - uint32_t A[2], B[2], C[2], D[2], /* Word buffers */ - E[2], F[2], G[2], H[2]; - - /* Initialize the first 16 words in the array W */ - for (t = t2 = t8 = 0; t < 16; t++, t8 += 8) { - W[t2++] = ((((uint32_t)context->Message_Block[t8])) << 24) | ((((uint32_t)context->Message_Block[t8 + 1])) << 16) | - ((((uint32_t)context->Message_Block[t8 + 2])) << 8) | ((((uint32_t)context->Message_Block[t8 + 3]))); - W[t2++] = ((((uint32_t)context->Message_Block[t8 + 4])) << 24) | ((((uint32_t)context->Message_Block[t8 + 5])) << 16) | - ((((uint32_t)context->Message_Block[t8 + 6])) << 8) | ((((uint32_t)context->Message_Block[t8 + 7]))); - } - - for (t = 16; t < 80; t++, t2 += 2) { - /* W[t] = SHA512_sigma1(W[t-2]) + W[t-7] + - SHA512_sigma0(W[t-15]) + W[t-16]; */ - uint32_t *Wt2 = &W[t2 - 2 * 2]; - uint32_t *Wt7 = &W[t2 - 7 * 2]; - uint32_t *Wt15 = &W[t2 - 15 * 2]; - uint32_t *Wt16 = &W[t2 - 16 * 2]; - SHA512_sigma1(Wt2, temp1); - SHA512_ADD(temp1, Wt7, temp2); - SHA512_sigma0(Wt15, temp1); - SHA512_ADD(temp1, Wt16, temp3); - SHA512_ADD(temp2, temp3, &W[t2]); - } - - A[0] = context->Intermediate_Hash[0]; - A[1] = context->Intermediate_Hash[1]; - B[0] = context->Intermediate_Hash[2]; - B[1] = context->Intermediate_Hash[3]; - C[0] = context->Intermediate_Hash[4]; - C[1] = context->Intermediate_Hash[5]; - D[0] = context->Intermediate_Hash[6]; - D[1] = context->Intermediate_Hash[7]; - E[0] = context->Intermediate_Hash[8]; - E[1] = context->Intermediate_Hash[9]; - F[0] = context->Intermediate_Hash[10]; - F[1] = context->Intermediate_Hash[11]; - G[0] = context->Intermediate_Hash[12]; - G[1] = context->Intermediate_Hash[13]; - H[0] = context->Intermediate_Hash[14]; - H[1] = context->Intermediate_Hash[15]; - - for (t = t2 = 0; t < 80; t++, t2 += 2) { - /* - * temp1 = H + SHA512_SIGMA1(E) + SHA_Ch(E,F,G) + K[t] + W[t]; - */ - SHA512_SIGMA1(E, temp1); - SHA512_ADD(H, temp1, temp2); - SHA_Ch(E, F, G, temp3); - SHA512_ADD(temp2, temp3, temp4); - SHA512_ADD(&K[t2], &W[t2], temp5); - SHA512_ADD(temp4, temp5, temp1); - /* - * temp2 = SHA512_SIGMA0(A) + SHA_Maj(A,B,C); - */ - SHA512_SIGMA0(A, temp3); - SHA_Maj(A, B, C, temp4); - SHA512_ADD(temp3, temp4, temp2); - H[0] = G[0]; - H[1] = G[1]; - G[0] = F[0]; - G[1] = F[1]; - F[0] = E[0]; - F[1] = E[1]; - SHA512_ADD(D, temp1, E); - D[0] = C[0]; - D[1] = C[1]; - C[0] = B[0]; - C[1] = B[1]; - B[0] = A[0]; - B[1] = A[1]; - SHA512_ADD(temp1, temp2, A); - } - - SHA512_ADDTO2(&context->Intermediate_Hash[0], A); - SHA512_ADDTO2(&context->Intermediate_Hash[2], B); - SHA512_ADDTO2(&context->Intermediate_Hash[4], C); - SHA512_ADDTO2(&context->Intermediate_Hash[6], D); - SHA512_ADDTO2(&context->Intermediate_Hash[8], E); - SHA512_ADDTO2(&context->Intermediate_Hash[10], F); - SHA512_ADDTO2(&context->Intermediate_Hash[12], G); - SHA512_ADDTO2(&context->Intermediate_Hash[14], H); - -#else /* !USE_32BIT_ONLY */ - static const uint64_t K[80] = { - 0x428A2F98D728AE22ll, 0x7137449123EF65CDll, 0xB5C0FBCFEC4D3B2Fll, 0xE9B5DBA58189DBBCll, 0x3956C25BF348B538ll, 0x59F111F1B605D019ll, 0x923F82A4AF194F9Bll, - 0xAB1C5ED5DA6D8118ll, 0xD807AA98A3030242ll, 0x12835B0145706FBEll, 0x243185BE4EE4B28Cll, 0x550C7DC3D5FFB4E2ll, 0x72BE5D74F27B896Fll, 0x80DEB1FE3B1696B1ll, - 0x9BDC06A725C71235ll, 0xC19BF174CF692694ll, 0xE49B69C19EF14AD2ll, 0xEFBE4786384F25E3ll, 0x0FC19DC68B8CD5B5ll, 0x240CA1CC77AC9C65ll, 0x2DE92C6F592B0275ll, - 0x4A7484AA6EA6E483ll, 0x5CB0A9DCBD41FBD4ll, 0x76F988DA831153B5ll, 0x983E5152EE66DFABll, 0xA831C66D2DB43210ll, 0xB00327C898FB213Fll, 0xBF597FC7BEEF0EE4ll, - 0xC6E00BF33DA88FC2ll, 0xD5A79147930AA725ll, 0x06CA6351E003826Fll, 0x142929670A0E6E70ll, 0x27B70A8546D22FFCll, 0x2E1B21385C26C926ll, 0x4D2C6DFC5AC42AEDll, - 0x53380D139D95B3DFll, 0x650A73548BAF63DEll, 0x766A0ABB3C77B2A8ll, 0x81C2C92E47EDAEE6ll, 0x92722C851482353Bll, 0xA2BFE8A14CF10364ll, 0xA81A664BBC423001ll, - 0xC24B8B70D0F89791ll, 0xC76C51A30654BE30ll, 0xD192E819D6EF5218ll, 0xD69906245565A910ll, 0xF40E35855771202All, 0x106AA07032BBD1B8ll, 0x19A4C116B8D2D0C8ll, - 0x1E376C085141AB53ll, 0x2748774CDF8EEB99ll, 0x34B0BCB5E19B48A8ll, 0x391C0CB3C5C95A63ll, 0x4ED8AA4AE3418ACBll, 0x5B9CCA4F7763E373ll, 0x682E6FF3D6B2B8A3ll, - 0x748F82EE5DEFB2FCll, 0x78A5636F43172F60ll, 0x84C87814A1F0AB72ll, 0x8CC702081A6439ECll, 0x90BEFFFA23631E28ll, 0xA4506CEBDE82BDE9ll, 0xBEF9A3F7B2C67915ll, - 0xC67178F2E372532Bll, 0xCA273ECEEA26619Cll, 0xD186B8C721C0C207ll, 0xEADA7DD6CDE0EB1Ell, 0xF57D4F7FEE6ED178ll, 0x06F067AA72176FBAll, 0x0A637DC5A2C898A6ll, - 0x113F9804BEF90DAEll, 0x1B710B35131C471Bll, 0x28DB77F523047D84ll, 0x32CAAB7B40C72493ll, 0x3C9EBE0A15C9BEBCll, 0x431D67C49C100D4Cll, 0x4CC5D4BECB3E42B6ll, - 0x597F299CFC657E2All, 0x5FCB6FAB3AD6FAECll, 0x6C44198C4A475817ll}; - int t, t8; /* Loop counter */ - uint64_t temp1, temp2; /* Temporary word value */ - uint64_t W[80]; /* Word sequence */ - uint64_t A, B, C, D, E, F, G, H; /* Word buffers */ - - /* - * Initialize the first 16 words in the array W - */ - for (t = t8 = 0; t < 16; t++, t8 += 8) - W[t] = ((uint64_t)(context->Message_Block[t8]) << 56) | ((uint64_t)(context->Message_Block[t8 + 1]) << 48) | - ((uint64_t)(context->Message_Block[t8 + 2]) << 40) | ((uint64_t)(context->Message_Block[t8 + 3]) << 32) | - ((uint64_t)(context->Message_Block[t8 + 4]) << 24) | ((uint64_t)(context->Message_Block[t8 + 5]) << 16) | - ((uint64_t)(context->Message_Block[t8 + 6]) << 8) | ((uint64_t)(context->Message_Block[t8 + 7])); - - for (t = 16; t < 80; t++) W[t] = SHA512_sigma1(W[t - 2]) + W[t - 7] + SHA512_sigma0(W[t - 15]) + W[t - 16]; - - A = context->Intermediate_Hash[0]; - B = context->Intermediate_Hash[1]; - C = context->Intermediate_Hash[2]; - D = context->Intermediate_Hash[3]; - E = context->Intermediate_Hash[4]; - F = context->Intermediate_Hash[5]; - G = context->Intermediate_Hash[6]; - H = context->Intermediate_Hash[7]; - - for (t = 0; t < 80; t++) { - temp1 = H + SHA512_SIGMA1(E) + SHA_Ch(E, F, G) + K[t] + W[t]; - temp2 = SHA512_SIGMA0(A) + SHA_Maj(A, B, C); - H = G; - G = F; - F = E; - E = D + temp1; - D = C; - C = B; - B = A; - A = temp1 + temp2; - } - - context->Intermediate_Hash[0] += A; - context->Intermediate_Hash[1] += B; - context->Intermediate_Hash[2] += C; - context->Intermediate_Hash[3] += D; - context->Intermediate_Hash[4] += E; - context->Intermediate_Hash[5] += F; - context->Intermediate_Hash[6] += G; - context->Intermediate_Hash[7] += H; -#endif /* USE_32BIT_ONLY */ - - context->Message_Block_Index = 0; -} - -/* - * SHA384_512Reset - * - * Description: - * This helper function will initialize the SHA512Context in - * preparation for computing a new SHA384 or SHA512 message - * digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * H0 - * The initial hash value to use. - * - * Returns: - * sha Error Code. - * - */ -#ifdef USE_32BIT_ONLY -static int SHA384_512Reset(SHA512Context *context, uint32_t H0[]) -#else /* !USE_32BIT_ONLY */ -static int SHA384_512Reset(SHA512Context *context, uint64_t H0[]) -#endif /* USE_32BIT_ONLY */ -{ - int i; - if (!context) return shaNull; - - context->Message_Block_Index = 0; - -#ifdef USE_32BIT_ONLY - context->Length[0] = context->Length[1] = 0; - context->Length[2] = context->Length[3] = 0; - - for (i = 0; i < SHA512HashSize / 4; i++) context->Intermediate_Hash[i] = H0[i]; -#else /* !USE_32BIT_ONLY */ - context->Length_High = context->Length_Low = 0; - - for (i = 0; i < SHA512HashSize / 8; i++) context->Intermediate_Hash[i] = H0[i]; -#endif /* USE_32BIT_ONLY */ - - context->Computed = 0; - context->Corrupted = 0; - - return shaSuccess; -} - -/* - * SHA384_512ResultN - * - * Description: - * This helper function will return the 384-bit or 512-bit message - * digest into the Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 48th/64th element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA hash. - * Message_Digest: [out] - * Where the digest is returned. - * HashSize: [in] - * The size of the hash, either 48 or 64. - * - * Returns: - * sha Error Code. - * - */ -static int SHA384_512ResultN(SHA512Context *context, uint8_t Message_Digest[], int HashSize) { - int i; - -#ifdef USE_32BIT_ONLY - int i2; -#endif /* USE_32BIT_ONLY */ - - if (!context || !Message_Digest) return shaNull; - - if (context->Corrupted) return context->Corrupted; - - if (!context->Computed) SHA384_512Finalize(context, 0x80); - -#ifdef USE_32BIT_ONLY - for (i = i2 = 0; i < HashSize;) { - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2] >> 24); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2] >> 16); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2] >> 8); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2++]); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2] >> 24); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2] >> 16); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2] >> 8); - Message_Digest[i++] = (uint8_t)(context->Intermediate_Hash[i2++]); - } -#else /* !USE_32BIT_ONLY */ - for (i = 0; i < HashSize; ++i) Message_Digest[i] = (uint8_t)(context->Intermediate_Hash[i >> 3] >> 8 * (7 - (i % 8))); -#endif /* USE_32BIT_ONLY */ - - return shaSuccess; -} -/**************************** usha.c ****************************/ -/******************** See RFC 4634 for details ******************/ -/* - * Description: - * This file implements a unified interface to the SHA algorithms. - */ - -//#include "sha.h" - -/* - * USHAReset - * - * Description: - * This function will initialize the SHA Context in preparation - * for computing a new SHA message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * whichSha: [in] - * Selects which SHA reset to call - * - * Returns: - * sha Error Code. - * - */ -inline int USHAReset(USHAContext *ctx, enum SHAversion whichSha) { - if (ctx) { - ctx->whichSha = whichSha; - switch (whichSha) { - case SHA1: - return SHA1Reset((SHA1Context *)&ctx->ctx); - case SHA224: - return SHA224Reset((SHA224Context *)&ctx->ctx); - case SHA256: - return SHA256Reset((SHA256Context *)&ctx->ctx); - case SHA384: - return SHA384Reset((SHA384Context *)&ctx->ctx); - case SHA512: - return SHA512Reset((SHA512Context *)&ctx->ctx); - default: - return shaBadParam; - } - } else { - return shaNull; - } -} - -/* - * USHAInput - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - * - */ -inline int USHAInput(USHAContext *ctx, const uint8_t *bytes, unsigned int bytecount) { - if (ctx) { - switch (ctx->whichSha) { - case SHA1: - return SHA1Input((SHA1Context *)&ctx->ctx, bytes, bytecount); - case SHA224: - return SHA224Input((SHA224Context *)&ctx->ctx, bytes, bytecount); - case SHA256: - return SHA256Input((SHA256Context *)&ctx->ctx, bytes, bytecount); - case SHA384: - return SHA384Input((SHA384Context *)&ctx->ctx, bytes, bytecount); - case SHA512: - return SHA512Input((SHA512Context *)&ctx->ctx, bytes, bytecount); - default: - return shaBadParam; - } - } else { - return shaNull; - } -} - -/* - * USHAFinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The SHA context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - */ -inline int USHAFinalBits(USHAContext *ctx, const uint8_t bits, unsigned int bitcount) { - if (ctx) { - switch (ctx->whichSha) { - case SHA1: - return SHA1FinalBits((SHA1Context *)&ctx->ctx, bits, bitcount); - case SHA224: - return SHA224FinalBits((SHA224Context *)&ctx->ctx, bits, bitcount); - case SHA256: - return SHA256FinalBits((SHA256Context *)&ctx->ctx, bits, bitcount); - case SHA384: - return SHA384FinalBits((SHA384Context *)&ctx->ctx, bits, bitcount); - case SHA512: - return SHA512FinalBits((SHA512Context *)&ctx->ctx, bits, bitcount); - default: - return shaBadParam; - } - } else { - return shaNull; - } -} - -/* - * USHAResult - * - * Description: - * This function will return the 160-bit message digest into the - * Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the 19th element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the SHA-1 hash. - * Message_Digest: [out] - * Where the digest is returned. - * - * Returns: - * sha Error Code. - * - */ -inline int USHAResult(USHAContext *ctx, uint8_t Message_Digest[USHAMaxHashSize]) { - if (ctx) { - switch (ctx->whichSha) { - case SHA1: - return SHA1Result((SHA1Context *)&ctx->ctx, Message_Digest); - case SHA224: - return SHA224Result((SHA224Context *)&ctx->ctx, Message_Digest); - case SHA256: - return SHA256Result((SHA256Context *)&ctx->ctx, Message_Digest); - case SHA384: - return SHA384Result((SHA384Context *)&ctx->ctx, Message_Digest); - case SHA512: - return SHA512Result((SHA512Context *)&ctx->ctx, Message_Digest); - default: - return shaBadParam; - } - } else { - return shaNull; - } -} - -/* - * USHABlockSize - * - * Description: - * This function will return the blocksize for the given SHA - * algorithm. - * - * Parameters: - * whichSha: - * which SHA algorithm to query - * - * Returns: - * block size - * - */ -inline int USHABlockSize(enum SHAversion whichSha) { - switch (whichSha) { - case SHA1: - return SHA1_Message_Block_Size; - case SHA224: - return SHA224_Message_Block_Size; - case SHA256: - return SHA256_Message_Block_Size; - case SHA384: - return SHA384_Message_Block_Size; - default: - case SHA512: - return SHA512_Message_Block_Size; - } -} - -/* - * USHAHashSize - * - * Description: - * This function will return the hashsize for the given SHA - * algorithm. - * - * Parameters: - * whichSha: - * which SHA algorithm to query - * - * Returns: - * hash size - * - */ -inline int USHAHashSize(enum SHAversion whichSha) { - switch (whichSha) { - case SHA1: - return SHA1HashSize; - case SHA224: - return SHA224HashSize; - case SHA256: - return SHA256HashSize; - case SHA384: - return SHA384HashSize; - default: - case SHA512: - return SHA512HashSize; - } -} - -/* - * USHAHashSizeBits - * - * Description: - * This function will return the hashsize for the given SHA - * algorithm, expressed in bits. - * - * Parameters: - * whichSha: - * which SHA algorithm to query - * - * Returns: - * hash size in bits - * - */ -inline int USHAHashSizeBits(enum SHAversion whichSha) { - switch (whichSha) { - case SHA1: - return SHA1HashSizeBits; - case SHA224: - return SHA224HashSizeBits; - case SHA256: - return SHA256HashSizeBits; - case SHA384: - return SHA384HashSizeBits; - default: - case SHA512: - return SHA512HashSizeBits; - } -} -/* - * hmac - * - * Description: - * This function will compute an HMAC message digest. - * - * Parameters: - * whichSha: [in] - * One of SHA1, SHA224, SHA256, SHA384, SHA512 - * key: [in] - * The secret shared key. - * key_len: [in] - * The length of the secret shared key. - * message_array: [in] - * An array of characters representing the message. - * length: [in] - * The length of the message in message_array - * digest: [out] - * Where the digest is returned. - * NOTE: The length of the digest is determined by - * the value of whichSha. - * - * Returns: - * sha Error Code. - * - */ -inline int hmac(SHAversion whichSha, const unsigned char *text, int text_len, const unsigned char *key, int key_len, uint8_t digest[USHAMaxHashSize]) { - HMACContext ctx; - return hmacReset(&ctx, whichSha, key, key_len) || hmacInput(&ctx, text, text_len) || hmacResult(&ctx, digest); -} - -/* - * hmacReset - * - * Description: - * This function will initialize the hmacContext in preparation - * for computing a new HMAC message digest. - * - * Parameters: - * context: [in/out] - * The context to reset. - * whichSha: [in] - * One of SHA1, SHA224, SHA256, SHA384, SHA512 - * key: [in] - * The secret shared key. - * key_len: [in] - * The length of the secret shared key. - * - * Returns: - * sha Error Code. - * - */ -inline int hmacReset(HMACContext *ctx, enum SHAversion whichSha, const unsigned char *key, int key_len) { - int i, blocksize, hashsize; - - /* inner padding - key XORd with ipad */ - unsigned char k_ipad[USHA_Max_Message_Block_Size]; - - /* temporary buffer when keylen > blocksize */ - unsigned char tempkey[USHAMaxHashSize]; - - if (!ctx) return shaNull; - - blocksize = ctx->blockSize = USHABlockSize(whichSha); - hashsize = ctx->hashSize = USHAHashSize(whichSha); - - ctx->whichSha = whichSha; - - /* - * If key is longer than the hash blocksize, - * reset it to key = HASH(key). - */ - if (key_len > blocksize) { - USHAContext tctx; - int err = USHAReset(&tctx, whichSha) || USHAInput(&tctx, key, key_len) || USHAResult(&tctx, tempkey); - if (err != shaSuccess) return err; - - key = tempkey; - key_len = hashsize; - } - - /* - * The HMAC transform looks like: - * - * SHA(K XOR opad, SHA(K XOR ipad, text)) - * - * where K is an n byte key. - * ipad is the byte 0x36 repeated blocksize times - * opad is the byte 0x5c repeated blocksize times - * and text is the data being protected. - */ - - /* store key into the pads, XOR'd with ipad and opad values */ - for (i = 0; i < key_len; i++) { - k_ipad[i] = key[i] ^ 0x36; - ctx->k_opad[i] = key[i] ^ 0x5c; - } - /* remaining pad bytes are '\0' XOR'd with ipad and opad values */ - for (; i < blocksize; i++) { - k_ipad[i] = 0x36; - ctx->k_opad[i] = 0x5c; - } - - /* perform inner hash */ - /* init context for 1st pass */ - return USHAReset(&ctx->shaContext, whichSha) || - /* and start with inner pad */ - USHAInput(&ctx->shaContext, k_ipad, blocksize); -} - -/* - * hmacInput - * - * Description: - * This function accepts an array of octets as the next portion - * of the message. - * - * Parameters: - * context: [in/out] - * The HMAC context to update - * message_array: [in] - * An array of characters representing the next portion of - * the message. - * length: [in] - * The length of the message in message_array - * - * Returns: - * sha Error Code. - * - */ -inline int hmacInput(HMACContext *ctx, const unsigned char *text, int text_len) { - if (!ctx) return shaNull; - /* then text of datagram */ - return USHAInput(&ctx->shaContext, text, text_len); -} - -/* - * HMACFinalBits - * - * Description: - * This function will add in any final bits of the message. - * - * Parameters: - * context: [in/out] - * The HMAC context to update - * message_bits: [in] - * The final bits of the message, in the upper portion of the - * byte. (Use 0b###00000 instead of 0b00000### to input the - * three bits ###.) - * length: [in] - * The number of bits in message_bits, between 1 and 7. - * - * Returns: - * sha Error Code. - */ -inline int hmacFinalBits(HMACContext *ctx, const uint8_t bits, unsigned int bitcount) { - if (!ctx) return shaNull; - /* then final bits of datagram */ - return USHAFinalBits(&ctx->shaContext, bits, bitcount); -} - -/* - * HMACResult - * - * Description: - * This function will return the N-byte message digest into the - * Message_Digest array provided by the caller. - * NOTE: The first octet of hash is stored in the 0th element, - * the last octet of hash in the Nth element. - * - * Parameters: - * context: [in/out] - * The context to use to calculate the HMAC hash. - * digest: [out] - * Where the digest is returned. - * NOTE 2: The length of the hash is determined by the value of - * whichSha that was passed to hmacReset(). - * - * Returns: - * sha Error Code. - * - */ -inline int hmacResult(HMACContext *ctx, uint8_t *digest) { - if (!ctx) return shaNull; - - /* finish up 1st pass */ - /* (Use digest here as a temporary buffer.) */ - return USHAResult(&ctx->shaContext, digest) || - /* perform outer SHA */ - /* init context for 2nd pass */ - USHAReset(&ctx->shaContext, (SHAversion)ctx->whichSha) || - /* start with outer pad */ - USHAInput(&ctx->shaContext, ctx->k_opad, ctx->blockSize) || - /* then results of 1st hash */ - USHAInput(&ctx->shaContext, digest, ctx->hashSize) || - /* finish up 2nd pass */ - USHAResult(&ctx->shaContext, digest); -} -} -#include "ccapi_cpp/ccapi_logger.h" -#include "ccapi_cpp/ccapi_macro.h" namespace ccapi { -class Hmac CCAPI_FINAL { - // https://github.com/Yubico/yubico-c-client/blob/ykclient-2.15/sha384-512.c + +class Hmac { public: enum class ShaVersion { UNKNOWN, @@ -2507,81 +20,54 @@ class Hmac CCAPI_FINAL { SHA384, SHA512, }; - static std::string hmacYubico(const ShaVersion shaVersion, const std::string &key, const std::string &msg, bool returnHex = false) { - yubico::SHAversion whichSha{}; - int shaHashSize{}; + + static std::string hmac(const ShaVersion shaVersion, const std::string& key, const std::string& msg, bool returnHex = false) { + const EVP_MD* md = nullptr; + switch (shaVersion) { case ShaVersion::SHA1: - whichSha = yubico::SHAversion::SHA1; - shaHashSize = yubico::SHA1HashSize; + md = EVP_sha1(); break; case ShaVersion::SHA224: - whichSha = yubico::SHAversion::SHA224; - shaHashSize = yubico::SHA224HashSize; + md = EVP_sha224(); break; case ShaVersion::SHA256: - whichSha = yubico::SHAversion::SHA256; - shaHashSize = yubico::SHA256HashSize; + md = EVP_sha256(); break; case ShaVersion::SHA384: - whichSha = yubico::SHAversion::SHA384; - shaHashSize = yubico::SHA384HashSize; + md = EVP_sha384(); break; case ShaVersion::SHA512: - whichSha = yubico::SHAversion::SHA512; - shaHashSize = yubico::SHA512HashSize; + md = EVP_sha512(); break; default: - CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); - } - uint8_t digest[yubico::USHAMaxHashSize]; - int err = yubico::hmac(whichSha, reinterpret_cast(const_cast(msg.c_str())), msg.length(), - reinterpret_cast(const_cast(key.c_str())), key.length(), digest); - if (err != yubico::shaSuccess) { - throw std::runtime_error("hmac sha error"); + return ""; // Optionally throw or log unsupported algorithm } + + unsigned char hash[EVP_MAX_MD_SIZE]; + unsigned int len = 0; + + HMAC_CTX* hmac = HMAC_CTX_new(); + HMAC_Init_ex(hmac, key.data(), static_cast(key.size()), md, nullptr); + HMAC_Update(hmac, reinterpret_cast(msg.data()), msg.size()); + HMAC_Final(hmac, hash, &len); + HMAC_CTX_free(hmac); + std::stringstream ss; if (returnHex) { ss << std::hex << std::setfill('0'); - for (int i = 0; i < shaHashSize; i++) { - ss << std::hex << std::setw(2) << (unsigned int)digest[i]; + for (unsigned int i = 0; i < len; ++i) { + ss << std::setw(2) << static_cast(hash[i]); } } else { - for (int i = 0; i < shaHashSize; i++) { - ss << (char)digest[i]; + for (unsigned int i = 0; i < len; ++i) { + ss << static_cast(hash[i]); } } + return ss.str(); } - static std::string hmac(const ShaVersion shaVersion, const std::string &key, const std::string &msg, bool returnHex = false) { -#ifdef CCAPI_SHA_USE_OPENSSL - if (shaVersion == ShaVersion::SHA256) { - unsigned char hash[32]; - HMAC_CTX *hmac = HMAC_CTX_new(); - HMAC_Init_ex(hmac, &key[0], key.length(), EVP_sha256(), NULL); - HMAC_Update(hmac, (unsigned char *)&msg[0], msg.length()); - unsigned int len = 32; - HMAC_Final(hmac, hash, &len); - HMAC_CTX_free(hmac); - std::stringstream ss; - if (returnHex) { - ss << std::hex << std::setfill('0'); - for (int i = 0; i < len; i++) { - ss << std::hex << std::setw(2) << (unsigned int)hash[i]; - } - } else { - for (int i = 0; i < len; i++) { - ss << (char)hash[i]; - } - } - return (ss.str()); - } else { - return hmacYubico(shaVersion, key, msg, returnHex); - } -#else - return hmacYubico(shaVersion, key, msg, returnHex); -#endif - } }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_HMAC_H_ diff --git a/linux/include/ccapi_cpp/ccapi_http_connection.h b/linux/include/ccapi_cpp/ccapi_http_connection.h index 95f38623a..ffc395f13 100644 --- a/linux/include/ccapi_cpp/ccapi_http_connection.h +++ b/linux/include/ccapi_cpp/ccapi_http_connection.h @@ -4,14 +4,20 @@ #include "ccapi_cpp/ccapi_logger.h" namespace beast = boost::beast; + namespace ccapi { -class HttpConnection CCAPI_FINAL { + +class HttpConnection { /** * This class represents a TCP socket connection for the REST API. */ public: - HttpConnection(std::string host, std::string port, std::shared_ptr > streamPtr) + HttpConnection(const HttpConnection&) = delete; + HttpConnection& operator=(const HttpConnection&) = delete; + + HttpConnection(std::string host, std::string port, std::shared_ptr> streamPtr) : host(host), port(port), streamPtr(streamPtr) {} + std::string toString() const { std::ostringstream oss; oss << streamPtr; @@ -19,10 +25,16 @@ class HttpConnection CCAPI_FINAL { ", lastReceiveDataTp = " + UtilTime::getISOTimestamp(lastReceiveDataTp) + "]"; return output; } + + void clearBuffer() { this->buffer.consume(this->buffer.size()); } + std::string host; std::string port; - std::shared_ptr > streamPtr; + std::shared_ptr> streamPtr{nullptr}; TimePoint lastReceiveDataTp{std::chrono::seconds{0}}; + + boost::beast::flat_buffer buffer; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_HTTP_CONNECTION_H_ diff --git a/linux/include/ccapi_cpp/ccapi_http_retry.h b/linux/include/ccapi_cpp/ccapi_http_retry.h index 27f3a0f35..92d9d84f8 100644 --- a/linux/include/ccapi_cpp/ccapi_http_retry.h +++ b/linux/include/ccapi_cpp/ccapi_http_retry.h @@ -2,25 +2,29 @@ #define INCLUDE_CCAPI_CPP_CCAPI_HTTP_RETRY_H_ #include #include + namespace ccapi { + /** * This class is used for retrying http requests for the REST API. */ -class HttpRetry CCAPI_FINAL { +class HttpRetry { public: explicit HttpRetry(int numRetry = 0, int numRedirect = 0, std::string redirectUrlStr = "", - std::shared_ptr > promisePtr = std::shared_ptr >(nullptr)) + std::shared_ptr> promisePtr = std::shared_ptr>(nullptr)) : numRetry(numRetry), numRedirect(numRedirect), promisePtr(promisePtr) {} + std::string toString() const { std::ostringstream oss; oss << promisePtr; std::string output = - "HttpConnection [numRetry = " + ccapi::toString(numRetry) + ", numRedirect = " + ccapi::toString(numRedirect) + ", promisePtr = " + oss.str() + "]"; + "HttpRetry [numRetry = " + ccapi::toString(numRetry) + ", numRedirect = " + ccapi::toString(numRedirect) + ", promisePtr = " + oss.str() + "]"; return output; } + int numRetry; int numRedirect; - std::shared_ptr > promisePtr; + std::shared_ptr> promisePtr; }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/ccapi_inflate_stream.h b/linux/include/ccapi_cpp/ccapi_inflate_stream.h index 6a7156730..80d646eb6 100644 --- a/linux/include/ccapi_cpp/ccapi_inflate_stream.h +++ b/linux/include/ccapi_cpp/ccapi_inflate_stream.h @@ -1,14 +1,16 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_INFLATE_STREAM_H_ #define INCLUDE_CCAPI_CPP_CCAPI_INFLATE_STREAM_H_ #ifndef CCAPI_DECOMPRESS_BUFFER_SIZE -#define CCAPI_DECOMPRESS_BUFFER_SIZE 1 << 20 +#define CCAPI_DECOMPRESS_BUFFER_SIZE (1 << 20) #endif #include "zlib.h" + namespace ccapi { + /** * Due to Huobi using gzip instead of zip in data compression, we cannot use beast::zboost::system::inflate_stream. Therefore we have to create our own. */ -class InflateStream CCAPI_FINAL { +class InflateStream { public: explicit InflateStream() { this->windowBits = 15; @@ -20,10 +22,12 @@ class InflateStream CCAPI_FINAL { this->istate.next_in = Z_NULL; this->decompressBufferSize = CCAPI_DECOMPRESS_BUFFER_SIZE; } + std::string toString() const { std::string output = "InflateStream [windowBits = " + ccapi::toString(windowBits) + "]"; return output; } + virtual ~InflateStream() { if (!this->initialized) { return; @@ -33,7 +37,9 @@ class InflateStream CCAPI_FINAL { CCAPI_LOGGER_ERROR("error cleaning up zlib decompression state"); } } + void setWindowBitsOverride(int windowBitsOverride) { this->windowBitsOverride = windowBitsOverride; } + boost::system::error_code init() { int ret; if (this->windowBitsOverride == 0) { @@ -51,14 +57,15 @@ class InflateStream CCAPI_FINAL { this->initialized = true; return boost::system::error_code(); } - boost::system::error_code decompress(uint8_t const *buf, size_t len, std::string &out) { + + boost::system::error_code decompress(uint8_t const* buf, size_t len, std::string& out) { if (!this->initialized) { CCAPI_LOGGER_ERROR("decompress error"); return boost::system::error_code(); } - int ret; + this->istate.avail_in = len; - this->istate.next_in = const_cast(buf); + this->istate.next_in = const_cast(buf); do { this->istate.avail_out = this->decompressBufferSize; this->istate.next_out = this->buffer.get(); @@ -67,10 +74,11 @@ class InflateStream CCAPI_FINAL { CCAPI_LOGGER_ERROR("decompress error"); return boost::system::error_code(); } - out.append(reinterpret_cast(this->buffer.get()), this->decompressBufferSize - this->istate.avail_out); + out.append(reinterpret_cast(this->buffer.get()), this->decompressBufferSize - this->istate.avail_out); } while (this->istate.avail_out == 0); return boost::system::error_code(); } + boost::system::error_code inflate_reset() { int ret = inflateReset(&this->istate); if (ret != Z_OK) { @@ -83,12 +91,12 @@ class InflateStream CCAPI_FINAL { private: #endif - int windowBits; - int windowBitsOverride; - bool initialized; - std::unique_ptr buffer; + int windowBits{}; + int windowBitsOverride{}; + bool initialized{}; + std::unique_ptr buffer{nullptr}; z_stream istate; - size_t decompressBufferSize; + size_t decompressBufferSize{}; }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/ccapi_jwt.h b/linux/include/ccapi_cpp/ccapi_jwt.h index 0df2a7419..e45c5e392 100644 --- a/linux/include/ccapi_cpp/ccapi_jwt.h +++ b/linux/include/ccapi_cpp/ccapi_jwt.h @@ -1,13 +1,16 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_JWT_H_ #define INCLUDE_CCAPI_CPP_CCAPI_JWT_H_ #include "ccapi_cpp/ccapi_hmac.h" +#include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * This class is used for handling jwt tokens. */ -class Jwt CCAPI_FINAL { +class Jwt { public: static std::string generate(const Hmac::ShaVersion shaVersion, const std::string& secret, const std::string& payload) { std::string output; diff --git a/linux/include/ccapi_cpp/ccapi_logger.h b/linux/include/ccapi_cpp/ccapi_logger.h index aad4748b8..afe7ac965 100644 --- a/linux/include/ccapi_cpp/ccapi_logger.h +++ b/linux/include/ccapi_cpp/ccapi_logger.h @@ -10,7 +10,7 @@ #define CCAPI_LOGGER_THREAD_ID std::this_thread::get_id() #define CCAPI_LOGGER_NOW std::chrono::system_clock::now() #if defined(CCAPI_ENABLE_LOG_FATAL) || defined(CCAPI_ENABLE_LOG_ERROR) || defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || \ - defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) + defined(CCAPI_ENABLE_LOG_DETAIL) || defined(CCAPI_ENABLE_LOG_FINE) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) #define CCAPI_LOGGER_FATAL(message) \ if (::ccapi::Logger::logger) { \ ::ccapi::Logger::logger->fatal(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \ @@ -19,8 +19,8 @@ #else #define CCAPI_LOGGER_FATAL(message) throw std::runtime_error(message) #endif -#if defined(CCAPI_ENABLE_LOG_ERROR) || defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DEBUG) || \ - defined(CCAPI_ENABLE_LOG_TRACE) +#if defined(CCAPI_ENABLE_LOG_ERROR) || defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DETAIL) || \ + defined(CCAPI_ENABLE_LOG_FINE) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) #define CCAPI_LOGGER_ERROR(message) \ if (::ccapi::Logger::logger) { \ ::ccapi::Logger::logger->error(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \ @@ -28,7 +28,8 @@ #else #define CCAPI_LOGGER_ERROR(message) #endif -#if defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) +#if defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DETAIL) || defined(CCAPI_ENABLE_LOG_FINE) || \ + defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) #define CCAPI_LOGGER_WARN(message) \ if (::ccapi::Logger::logger) { \ ::ccapi::Logger::logger->warn(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \ @@ -36,7 +37,8 @@ #else #define CCAPI_LOGGER_WARN(message) #endif -#if defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) +#if defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DETAIL) || defined(CCAPI_ENABLE_LOG_FINE) || defined(CCAPI_ENABLE_LOG_DEBUG) || \ + defined(CCAPI_ENABLE_LOG_TRACE) #define CCAPI_LOGGER_INFO(message) \ if (::ccapi::Logger::logger) { \ ::ccapi::Logger::logger->info(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \ @@ -44,6 +46,22 @@ #else #define CCAPI_LOGGER_INFO(message) #endif +#if defined(CCAPI_ENABLE_LOG_DETAIL) || defined(CCAPI_ENABLE_LOG_FINE) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) +#define CCAPI_LOGGER_DETAIL(message) \ + if (::ccapi::Logger::logger) { \ + ::ccapi::Logger::logger->detail(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \ + } +#else +#define CCAPI_LOGGER_DETAIL(message) +#endif +#if defined(CCAPI_ENABLE_LOG_FINE) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) +#define CCAPI_LOGGER_FINE(message) \ + if (::ccapi::Logger::logger) { \ + ::ccapi::Logger::logger->fine(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \ + } +#else +#define CCAPI_LOGGER_FINE(message) +#endif #if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) #define CCAPI_LOGGER_DEBUG(message) \ if (::ccapi::Logger::logger) { \ @@ -74,7 +92,9 @@ #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * This class is used for library logging. */ @@ -84,33 +104,53 @@ class Logger { std::string LOG_SEVERITY_ERROR = "ERROR"; std::string LOG_SEVERITY_WARN = "WARN"; std::string LOG_SEVERITY_INFO = "INFO"; + std::string LOG_SEVERITY_DETAIL = "DETAIL"; + std::string LOG_SEVERITY_FINE = "FINE"; std::string LOG_SEVERITY_DEBUG = "DEBUG"; std::string LOG_SEVERITY_TRACE = "TRACE"; + virtual ~Logger() {} + void fatal(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, const std::string& message) { this->logMessagePrivate(LOG_SEVERITY_FATAL, threadId, time, fileName, lineNumber, message); } + void error(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, const std::string& message) { this->logMessagePrivate(LOG_SEVERITY_ERROR, threadId, time, fileName, lineNumber, message); } + void warn(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, const std::string& message) { this->logMessagePrivate(LOG_SEVERITY_WARN, threadId, time, fileName, lineNumber, message); } + void info(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, const std::string& message) { this->logMessagePrivate(LOG_SEVERITY_INFO, threadId, time, fileName, lineNumber, message); } + + void detail(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, + const std::string& message) { + this->logMessagePrivate(LOG_SEVERITY_DETAIL, threadId, time, fileName, lineNumber, message); + } + + void fine(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, + const std::string& message) { + this->logMessagePrivate(LOG_SEVERITY_FINE, threadId, time, fileName, lineNumber, message); + } + void debug(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, const std::string& message) { this->logMessagePrivate(LOG_SEVERITY_DEBUG, threadId, time, fileName, lineNumber, message); } + void trace(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber, const std::string& message) { this->logMessagePrivate(LOG_SEVERITY_TRACE, threadId, time, fileName, lineNumber, message); } + static Logger* logger; virtual void logMessage(const std::string& severity, const std::string& threadId, const std::string& timeISO, const std::string& fileName, @@ -126,5 +166,6 @@ class Logger { this->logMessage(severity, ss.str(), UtilTime::getISOTimestamp(time), fileName, lineNumber, message); } }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_LOGGER_H_ diff --git a/linux/include/ccapi_cpp/ccapi_macro.h b/linux/include/ccapi_cpp/ccapi_macro.h index fe1307b00..39bbe9c23 100644 --- a/linux/include/ccapi_cpp/ccapi_macro.h +++ b/linux/include/ccapi_cpp/ccapi_macro.h @@ -1,285 +1,397 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_ #define INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_ -#ifdef SWIG -#ifndef CCAPI_FINAL -#define CCAPI_FINAL -#endif -#else -#ifndef CCAPI_FINAL -#define CCAPI_FINAL final -#endif -#endif + #ifndef CCAPI_PRINT_DOUBLE_PRECISION_DEFAULT #define CCAPI_PRINT_DOUBLE_PRECISION_DEFAULT 10 #endif + #ifndef CCAPI_DOUBLE_ERROR_DEFAULT #define CCAPI_DOUBLE_ERROR_DEFAULT 1e-10 #endif + +#ifndef CCAPI_HEARTBEAT +#define CCAPI_HEARTBEAT "HEARTBEAT" +#endif + +#ifndef CCAPI_HEARTBEAT_INTERVAL_MILLISECONDS +#define CCAPI_HEARTBEAT_INTERVAL_MILLISECONDS "HEARTBEAT_INTERVAL_MILLISECONDS" +#endif + #ifndef CCAPI_GENERIC_PUBLIC_SUBSCRIPTION #define CCAPI_GENERIC_PUBLIC_SUBSCRIPTION "GENERIC_PUBLIC_SUBSCRIPTION" #endif + #ifndef CCAPI_MARKET_DEPTH #define CCAPI_MARKET_DEPTH "MARKET_DEPTH" #endif + #ifndef CCAPI_TRADE #define CCAPI_TRADE "TRADE" #endif + #ifndef CCAPI_AGG_TRADE #define CCAPI_AGG_TRADE "AGG_TRADE" #endif + #ifndef CCAPI_CANDLESTICK #define CCAPI_CANDLESTICK "CANDLESTICK" #endif + #ifndef CCAPI_MARKET_DEPTH_MAX #define CCAPI_MARKET_DEPTH_MAX CCAPI_MARKET_DEPTH "_MAX" #endif + #define CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE CCAPI_MARKET_DEPTH "_SUBSCRIBED_TO_EXCHANGE" #define CCAPI_MARKET_DEPTH_MAX_DEFAULT "1" #ifndef CCAPI_CONFLATE_INTERVAL_MILLISECONDS #define CCAPI_CONFLATE_INTERVAL_MILLISECONDS "CONFLATE_INTERVAL_MILLISECONDS" #endif + #define CCAPI_CONFLATE_INTERVAL_MILLISECONDS_DEFAULT "0" #ifndef CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS #define CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS "CONFLATE_GRACE_PERIOD_MILLISECONDS" #endif + #define CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS_DEFAULT "-1" #ifndef CCAPI_MARKET_DEPTH_RETURN_UPDATE #define CCAPI_MARKET_DEPTH_RETURN_UPDATE "MARKET_DEPTH_RETURN_UPDATE" #endif + #define CCAPI_MARKET_DEPTH_RETURN_UPDATE_DEFAULT "0" #define CCAPI_MARKET_DEPTH_RETURN_UPDATE_ENABLE "1" #ifndef CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS #define CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS "FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS" #endif + #define CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS_DEFAULT "0" #ifndef CCAPI_CANDLESTICK_INTERVAL_SECONDS #define CCAPI_CANDLESTICK_INTERVAL_SECONDS CCAPI_CANDLESTICK "_INTERVAL_SECONDS" #endif + #ifndef CCAPI_CANDLESTICK_INTERVAL_SECONDS_DEFAULT #define CCAPI_CANDLESTICK_INTERVAL_SECONDS_DEFAULT "60" #endif + #ifndef CCAPI_EXCHANGE_NAME_COINBASE #define CCAPI_EXCHANGE_NAME_COINBASE "coinbase" #endif + #ifndef CCAPI_EXCHANGE_NAME_GEMINI #define CCAPI_EXCHANGE_NAME_GEMINI "gemini" #endif + #ifndef CCAPI_EXCHANGE_NAME_KRAKEN #define CCAPI_EXCHANGE_NAME_KRAKEN "kraken" #endif + #ifndef CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES #define CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES "kraken-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_BITSTAMP #define CCAPI_EXCHANGE_NAME_BITSTAMP "bitstamp" #endif + #ifndef CCAPI_EXCHANGE_NAME_BITFINEX #define CCAPI_EXCHANGE_NAME_BITFINEX "bitfinex" #endif + #ifndef CCAPI_EXCHANGE_NAME_BITMEX #define CCAPI_EXCHANGE_NAME_BITMEX "bitmex" #endif + #ifndef CCAPI_EXCHANGE_NAME_BINANCE_US #define CCAPI_EXCHANGE_NAME_BINANCE_US "binance-us" #endif + #ifndef CCAPI_EXCHANGE_NAME_BINANCE #define CCAPI_EXCHANGE_NAME_BINANCE "binance" #endif + // #ifndef CCAPI_EXCHANGE_NAME_BINANCE_MARGIN // #define CCAPI_EXCHANGE_NAME_BINANCE_MARGIN "binance-margin" // #endif + #ifndef CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES #define CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES "binance-usds-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES #define CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES "binance-coin-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_HUOBI #define CCAPI_EXCHANGE_NAME_HUOBI "huobi" #endif + #ifndef CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP #define CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP "huobi-usdt-swap" #endif + #ifndef CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP #define CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP "huobi-coin-swap" #endif + #ifndef CCAPI_EXCHANGE_NAME_OKX #define CCAPI_EXCHANGE_NAME_OKX "okx" #endif + #ifndef CCAPI_EXCHANGE_NAME_ERISX #define CCAPI_EXCHANGE_NAME_ERISX "erisx" #endif + #ifndef CCAPI_EXCHANGE_NAME_KUCOIN #define CCAPI_EXCHANGE_NAME_KUCOIN "kucoin" #endif + #ifndef CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES #define CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES "kucoin-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_FTX #define CCAPI_EXCHANGE_NAME_FTX "ftx" #endif + #ifndef CCAPI_EXCHANGE_NAME_FTX_US #define CCAPI_EXCHANGE_NAME_FTX_US "ftx-us" #endif + #ifndef CCAPI_EXCHANGE_NAME_DERIBIT #define CCAPI_EXCHANGE_NAME_DERIBIT "deribit" #endif + #ifndef CCAPI_EXCHANGE_NAME_GATEIO #define CCAPI_EXCHANGE_NAME_GATEIO "gateio" #endif + #ifndef CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES #define CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES "gateio-perpetual-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_CRYPTOCOM #define CCAPI_EXCHANGE_NAME_CRYPTOCOM "cryptocom" #endif + #ifndef CCAPI_EXCHANGE_NAME_BYBIT #define CCAPI_EXCHANGE_NAME_BYBIT "bybit" #endif + #ifndef CCAPI_EXCHANGE_NAME_ASCENDEX #define CCAPI_EXCHANGE_NAME_ASCENDEX "ascendex" #endif + #ifndef CCAPI_EXCHANGE_NAME_BITGET #define CCAPI_EXCHANGE_NAME_BITGET "bitget" #endif + #ifndef CCAPI_EXCHANGE_NAME_BITGET_FUTURES #define CCAPI_EXCHANGE_NAME_BITGET_FUTURES "bitget-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_BITMART #define CCAPI_EXCHANGE_NAME_BITMART "bitmart" #endif + #ifndef CCAPI_EXCHANGE_NAME_MEXC #define CCAPI_EXCHANGE_NAME_MEXC "mexc" #endif + #ifndef CCAPI_EXCHANGE_NAME_MEXC_FUTURES #define CCAPI_EXCHANGE_NAME_MEXC_FUTURES "mexc-futures" #endif + #ifndef CCAPI_EXCHANGE_NAME_WHITEBIT #define CCAPI_EXCHANGE_NAME_WHITEBIT "whitebit" #endif + #ifndef CCAPI_LAST_PRICE #define CCAPI_LAST_PRICE "LAST_PRICE" #endif + #ifndef CCAPI_LAST_SIZE #define CCAPI_LAST_SIZE "LAST_SIZE" #endif + #ifndef CCAPI_TRADE_ID #define CCAPI_TRADE_ID "TRADE_ID" #endif + #ifndef CCAPI_AGG_TRADE_ID #define CCAPI_AGG_TRADE_ID "AGG_TRADE_ID" #endif + #ifndef CCAPI_IS_BUYER_MAKER #define CCAPI_IS_BUYER_MAKER "IS_BUYER_MAKER" #endif + #ifndef CCAPI_SEQUENCE_NUMBER #define CCAPI_SEQUENCE_NUMBER "SEQUENCE_NUMBER" #endif + #ifndef CCAPI_IS_MAKER #define CCAPI_IS_MAKER "IS_MAKER" #endif + #ifndef CCAPI_BEST_BID_N_PRICE #define CCAPI_BEST_BID_N_PRICE "BID_PRICE" #endif + #ifndef CCAPI_BEST_BID_N_PRICE_EMPTY #define CCAPI_BEST_BID_N_PRICE_EMPTY "" #endif + #ifndef CCAPI_BEST_BID_N_SIZE #define CCAPI_BEST_BID_N_SIZE "BID_SIZE" #endif + #ifndef CCAPI_BEST_BID_N_SIZE_EMPTY #define CCAPI_BEST_BID_N_SIZE_EMPTY "" #endif + #ifndef CCAPI_BEST_ASK_N_PRICE #define CCAPI_BEST_ASK_N_PRICE "ASK_PRICE" #endif + #ifndef CCAPI_BEST_ASK_N_PRICE_EMPTY #define CCAPI_BEST_ASK_N_PRICE_EMPTY "" #endif + #ifndef CCAPI_BEST_ASK_N_SIZE #define CCAPI_BEST_ASK_N_SIZE "ASK_SIZE" #endif + #ifndef CCAPI_BEST_ASK_N_SIZE_EMPTY #define CCAPI_BEST_ASK_N_SIZE_EMPTY "" #endif + #ifndef CCAPI_CANDLESTICK_EMPTY #define CCAPI_CANDLESTICK_EMPTY "" #endif + #ifndef CCAPI_OPEN_PRICE #define CCAPI_OPEN_PRICE "OPEN_PRICE" #endif + #ifndef CCAPI_HIGH_PRICE #define CCAPI_HIGH_PRICE "HIGH_PRICE" #endif + #ifndef CCAPI_LOW_PRICE #define CCAPI_LOW_PRICE "LOW_PRICE" #endif + #ifndef CCAPI_CLOSE_PRICE #define CCAPI_CLOSE_PRICE "CLOSE_PRICE" #endif + #ifndef CCAPI_VOLUME #define CCAPI_VOLUME "VOLUME" #endif + #ifndef CCAPI_QUOTE_VOLUME #define CCAPI_QUOTE_VOLUME "QUOTE_VOLUME" #endif + +#ifndef CCAPI_OPEN_24H_PRICE +#define CCAPI_OPEN_24H_PRICE "OPEN_24H_PRICE" +#endif + +#ifndef CCAPI_HIGH_24H_PRICE +#define CCAPI_HIGH_24H_PRICE "HIGH_24H_PRICE" +#endif + +#ifndef CCAPI_LOW_24H_PRICE +#define CCAPI_LOW_24H_PRICE "LOW_24H_PRICE" +#endif + +#ifndef CCAPI_VOLUME_24H +#define CCAPI_VOLUME_24H "VOLUME_24H" +#endif + +#ifndef CCAPI_QUOTE_VOLUME_24H +#define CCAPI_QUOTE_VOLUME_24H "QUOTE_VOLUME_24H" +#endif + #ifndef CCAPI_LIMIT #define CCAPI_LIMIT "LIMIT" #endif + #ifndef CCAPI_START_TRADE_ID #define CCAPI_START_TRADE_ID "START_TRADE_ID" #endif + #ifndef CCAPI_END_TRADE_ID #define CCAPI_END_TRADE_ID "END_TRADE_ID" #endif + #ifndef CCAPI_START_AGG_TRADE_ID #define CCAPI_START_AGG_TRADE_ID "START_AGG_TRADE_ID" #endif + #ifndef CCAPI_START_TIME_SECONDS #define CCAPI_START_TIME_SECONDS "START_TIME_SECONDS" #endif + #ifndef CCAPI_END_TIME_SECONDS #define CCAPI_END_TIME_SECONDS "END_TIME_SECONDS" #endif + #ifndef CCAPI_LAST_UPDATED_TIME_SECONDS #define CCAPI_LAST_UPDATED_TIME_SECONDS "LAST_UPDATED_TIME_SECONDS" #endif + #ifndef CCAPI_BASE_ASSET #define CCAPI_BASE_ASSET "BASE_ASSET" #endif + #ifndef CCAPI_QUOTE_ASSET #define CCAPI_QUOTE_ASSET "QUOTE_ASSET" #endif + #ifndef CCAPI_MARGIN_ASSET #define CCAPI_MARGIN_ASSET "MARGIN_ASSET" #endif + #ifndef CCAPI_SETTLE_ASSET #define CCAPI_SETTLE_ASSET "SETTLE_ASSET" #endif + #ifndef CCAPI_ORDER_PRICE_INCREMENT #define CCAPI_ORDER_PRICE_INCREMENT "PRICE_INCREMENT" #endif + #ifndef CCAPI_ORDER_QUANTITY_INCREMENT #define CCAPI_ORDER_QUANTITY_INCREMENT "QUANTITY_INCREMENT" #endif + #ifndef CCAPI_ORDER_QUANTITY_MIN #define CCAPI_ORDER_QUANTITY_MIN "QUANTITY_MIN" #endif + #ifndef CCAPI_ORDER_QUANTITY_MAX #define CCAPI_ORDER_QUANTITY_MAX "QUANTITY_MAX" #endif -#ifndef CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN -#define CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN "PRICE_TIMES_QUANTITY_MIN" + +#ifndef CCAPI_ORDER_QUOTE_QUANTITY_MIN +#define CCAPI_ORDER_QUOTE_QUANTITY_MIN "QUOTE_QUANTITY_MIN" #endif + +#ifndef CCAPI_ORDER_QUOTE_QUANTITY_MAX +#define CCAPI_ORDER_QUOTE_QUANTITY_MAX "QUOTE_QUANTITY_MAX" +#endif + #ifndef CCAPI_INSTRUMENT_STATUS #define CCAPI_INSTRUMENT_STATUS "INSTRUMENT_STATUS" #endif + #ifndef CCAPI_CONTRACT_SIZE #define CCAPI_CONTRACT_SIZE "CONTRACT_SIZE" #endif + #ifndef CCAPI_CONTRACT_MULTIPLIER #define CCAPI_CONTRACT_MULTIPLIER "CONTRACT_MULTIPLIER" #endif + #define CCAPI_WEBSOCKET_COINBASE_CHANNEL_MATCH "matches" #define CCAPI_WEBSOCKET_COINBASE_CHANNEL_LEVEL2 "level2" #define CCAPI_WEBSOCKET_GEMINI_PARAMETER_TRADES "trades" @@ -306,6 +418,7 @@ #define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH "depth" #define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE "aggTrade" #define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE "kline" +#define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_DIFF_DEPTH "depth" #define CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL "market.$symbol.trade.detail" #define CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL_REGEX "market\\.(.+)\\.trade\\.detail" #define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO "market.$symbol.bbo" @@ -378,226 +491,320 @@ #ifndef CCAPI_CHANNEL_ID #define CCAPI_CHANNEL_ID "channelId" #endif + #ifndef CCAPI_SYMBOL_ID #define CCAPI_SYMBOL_ID "symbolId" #endif + #ifndef CCAPI_CONNECTION_ID #define CCAPI_CONNECTION_ID "CONNECTION_ID" #endif + #ifndef CCAPI_CONNECTION_URL #define CCAPI_CONNECTION_URL "CONNECTION_URL" #endif + #ifndef CCAPI_REASON #define CCAPI_REASON "REASON" #endif + #ifndef CCAPI_MARKET_DATA #define CCAPI_MARKET_DATA "market_data" #endif + #ifndef CCAPI_EXECUTION_MANAGEMENT #define CCAPI_EXECUTION_MANAGEMENT "execution_management" #endif + #ifndef CCAPI_FIX #define CCAPI_FIX "FIX" #endif + #ifndef CCAPI_FIX_MARKET_DATA #define CCAPI_FIX_MARKET_DATA "FIX_MARKET_DATA" #endif -#ifndef CCAPI_FIX_EXECUTION_MANAGEMENT -#define CCAPI_FIX_EXECUTION_MANAGEMENT "FIX_EXECUTION_MANAGEMENT" -#endif + #ifndef CCAPI_UNKNOWN #define CCAPI_UNKNOWN "unknown" #endif + #ifndef CCAPI_EM_ORDER_UPDATE #define CCAPI_EM_ORDER_UPDATE "ORDER_UPDATE" #endif + #ifndef CCAPI_EM_PRIVATE_TRADE #define CCAPI_EM_PRIVATE_TRADE "PRIVATE_TRADE" #endif + +#ifndef CCAPI_EM_PRIVATE_TRADE_LITE +#define CCAPI_EM_PRIVATE_TRADE_LITE "PRIVATE_TRADE_LITE" +#endif + #ifndef CCAPI_EM_BALANCE_UPDATE #define CCAPI_EM_BALANCE_UPDATE "BALANCE_UPDATE" #endif + #ifndef CCAPI_EM_POSITION_UPDATE #define CCAPI_EM_POSITION_UPDATE "POSITION_UPDATE" #endif + +#ifndef CCAPI_EM_WEBSOCKET_ORDER_ENTRY +#define CCAPI_EM_WEBSOCKET_ORDER_ENTRY "WEBSOCKET_ORDER_ENTRY" +#endif + #ifndef CCAPI_EM_ORDER_SIDE #define CCAPI_EM_ORDER_SIDE "SIDE" #endif + #ifndef CCAPI_EM_ORDER_SIDE_BUY #define CCAPI_EM_ORDER_SIDE_BUY "BUY" #endif + #ifndef CCAPI_EM_ORDER_SIDE_SELL #define CCAPI_EM_ORDER_SIDE_SELL "SELL" #endif + #ifndef CCAPI_EM_ORDER_TYPE #define CCAPI_EM_ORDER_TYPE "TYPE" #endif + #ifndef CCAPI_EM_ORDER_QUANTITY #define CCAPI_EM_ORDER_QUANTITY "QUANTITY" #endif + #ifndef CCAPI_EM_ORDER_LIMIT_PRICE #define CCAPI_EM_ORDER_LIMIT_PRICE "LIMIT_PRICE" #endif + #ifndef CCAPI_EM_ORDER_LAST_EXECUTED_PRICE #define CCAPI_EM_ORDER_LAST_EXECUTED_PRICE "LAST_EXECUTED_PRICE" #endif + #ifndef CCAPI_EM_ORDER_LAST_EXECUTED_SIZE #define CCAPI_EM_ORDER_LAST_EXECUTED_SIZE "LAST_EXECUTED_SIZE" #endif + #ifndef CCAPI_EM_ORDER_FEE_QUANTITY #define CCAPI_EM_ORDER_FEE_QUANTITY "FEE_QUANTITY" #endif + #ifndef CCAPI_EM_ORDER_CUMULATIVE_FEE_QUANTITY #define CCAPI_EM_ORDER_CUMULATIVE_FEE_QUANTITY "CUMULATIVE_FEE_QUANTITY" #endif + #ifndef CCAPI_EM_ORDER_FEE_ASSET #define CCAPI_EM_ORDER_FEE_ASSET "FEE_ASSET" #endif + #ifndef CCAPI_EM_ACCOUNT_ID #define CCAPI_EM_ACCOUNT_ID "ACCOUNT_ID" #endif + #ifndef CCAPI_EM_ACCOUNT_TYPE #define CCAPI_EM_ACCOUNT_TYPE "ACCOUNT_TYPE" #endif + #ifndef CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN #define CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN "CROSS_MARGIN" #endif + #ifndef CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN #define CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN "ISOLATED_MARGIN" #endif + #ifndef CCAPI_EM_ASSET #define CCAPI_EM_ASSET "ASSET" #endif + #ifndef CCAPI_EM_QUANTITY_TOTAL #define CCAPI_EM_QUANTITY_TOTAL "QUANTITY_TOTAL" #endif + #ifndef CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING #define CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING "QUANTITY_AVAILABLE_FOR_TRADING" #endif + #ifndef CCAPI_EM_QUANTITY_LIABILITY #define CCAPI_EM_QUANTITY_LIABILITY "QUANTITY_LIABILITY" #endif + #ifndef CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL #define CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL "BASE_ASSET_QUANTITY_TOTAL" #endif + #ifndef CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING #define CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING "BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING" #endif + #ifndef CCAPI_EM_QUOTE_ASSET_QUANTITY_TOTAL #define CCAPI_EM_QUOTE_ASSET_QUANTITY_TOTAL "QUOTE_ASSET_QUANTITY_TOTAL" #endif + #ifndef CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING #define CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING "QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING" #endif + #ifndef CCAPI_EM_INSTRUMENT #define CCAPI_EM_INSTRUMENT "INSTRUMENT" #endif + #ifndef CCAPI_EM_SYMBOL #define CCAPI_EM_SYMBOL "SYMBOL" #endif + #ifndef CCAPI_UNDERLYING_SYMBOL #define CCAPI_UNDERLYING_SYMBOL "UNDERLYING_SYMBOL" #endif + +#ifndef CCAPI_ALT_NAME +#define CCAPI_ALT_NAME "ALTNAME" +#endif + +#ifndef CCAPI_WS_NAME +#define CCAPI_WS_NAME "WSNAME" +#endif + #ifndef CCAPI_EM_POSITION_SIDE #define CCAPI_EM_POSITION_SIDE "POSITION_SIDE" #endif + #ifndef CCAPI_EM_POSITION_QUANTITY #define CCAPI_EM_POSITION_QUANTITY "QUANTITY" #endif + +#ifndef CCAPI_EM_POSITION_ASSET +#define CCAPI_EM_POSITION_ASSET "POSITION_ASSET" +#endif + +#ifndef CCAPI_EM_POSITION_MARGIN_TYPE +#define CCAPI_EM_POSITION_MARGIN_TYPE "MARGIN_TYPE" +#endif + #ifndef CCAPI_EM_POSITION_COST #define CCAPI_EM_POSITION_COST "COST" #endif + #ifndef CCAPI_EM_POSITION_ENTRY_PRICE #define CCAPI_EM_POSITION_ENTRY_PRICE "ENTRY_PRICE" #endif + #ifndef CCAPI_EM_PARTY_ID #define CCAPI_EM_PARTY_ID "PARTY_ID" #endif + #ifndef CCAPI_EM_ORDER_ID #define CCAPI_EM_ORDER_ID "ORDER_ID" #endif + #ifndef CCAPI_EM_CLIENT_ORDER_ID #define CCAPI_EM_CLIENT_ORDER_ID "CLIENT_ORDER_ID" #endif + #ifndef CCAPI_EM_ORIGINAL_CLIENT_ORDER_ID #define CCAPI_EM_ORIGINAL_CLIENT_ORDER_ID "ORIGINAL_CLIENT_ORDER_ID" #endif + #ifndef CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY #define CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY "CUMULATIVE_FILLED_QUANTITY" #endif + #ifndef CCAPI_EM_ORDER_REMAINING_QUANTITY #define CCAPI_EM_ORDER_REMAINING_QUANTITY "REMAINING_QUANTITY" #endif -#ifndef CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY -#define CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY "CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY" + +#ifndef CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUOTE_QUANTITY +#define CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUOTE_QUANTITY "CUMULATIVE_FILLED_QUOTE_QUANTITY" #endif + #ifndef CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE #define CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE "AVERAGE_FILLED_PRICE" #endif + #ifndef CCAPI_EM_ORDER_INSTRUMENT #define CCAPI_EM_ORDER_INSTRUMENT "INSTRUMENT" #endif + #ifndef CCAPI_INSTRUMENT_TYPE #define CCAPI_INSTRUMENT_TYPE "INSTRUMENT_TYPE" #endif + #ifndef CCAPI_INSTRUMENT #define CCAPI_INSTRUMENT "INSTRUMENT" #endif + #ifndef CCAPI_MARGIN_MODE #define CCAPI_MARGIN_MODE "MARGIN_MODE" #endif + #ifndef CCAPI_EM_ORDER_STATUS #define CCAPI_EM_ORDER_STATUS "STATUS" #endif + #ifndef CCAPI_EM_ORDER_LEVERAGE #define CCAPI_EM_ORDER_LEVERAGE "LEVERAGE" #endif + #ifndef CCAPI_EM_POSITION_LEVERAGE #define CCAPI_EM_POSITION_LEVERAGE "LEVERAGE" #endif + #ifndef CCAPI_EM_UNREALIZED_PNL #define CCAPI_EM_UNREALIZED_PNL "UNREALIZED_PNL" #endif + #ifndef CCAPI_HTTP_STATUS_CODE #define CCAPI_HTTP_STATUS_CODE "HTTP_STATUS_CODE" #endif + #ifndef CCAPI_HTTP_PROTOCOL #define CCAPI_HTTP_PROTOCOL "HTTP_PROTOCOL" #endif + #ifndef CCAPI_HTTP_HOST #define CCAPI_HTTP_HOST "HTTP_HOST" #endif + #ifndef CCAPI_HTTP_PORT #define CCAPI_HTTP_PORT "HTTP_PORT" #endif + #ifndef CCAPI_HTTP_PATH #define CCAPI_HTTP_PATH "HTTP_PATH" #endif + #ifndef CCAPI_HTTP_METHOD #define CCAPI_HTTP_METHOD "HTTP_METHOD" #endif + #ifndef CCAPI_HTTP_HEADERS #define CCAPI_HTTP_HEADERS "HTTP_HEADERS" #endif + #ifndef CCAPI_HTTP_BODY #define CCAPI_HTTP_BODY "HTTP_BODY" #endif + #ifndef CCAPI_HTTP_QUERY_STRING #define CCAPI_HTTP_QUERY_STRING "HTTP_QUERY_STRING" #endif + #ifndef CCAPI_WEBSOCKET_MESSAGE_PAYLOAD #define CCAPI_WEBSOCKET_MESSAGE_PAYLOAD "WEBSOCKET_MESSAGE_PAYLOAD" #endif + #ifndef CCAPI_ERROR_MESSAGE #define CCAPI_ERROR_MESSAGE "ERROR_MESSAGE" #endif + #ifndef CCAPI_INFO_MESSAGE #define CCAPI_INFO_MESSAGE "INFO_MESSAGE" #endif + #define CCAPI_UNSUPPORTED_VALUE "UNSUPPORTED VALUE" #ifndef CCAPI_CORRELATION_ID_GENERATED_LENGTH #define CCAPI_CORRELATION_ID_GENERATED_LENGTH 8 #endif + #ifndef CCAPI_CREDENTIAL_DISPLAY_LENGTH #define CCAPI_CREDENTIAL_DISPLAY_LENGTH 4 #endif @@ -606,327 +813,477 @@ #ifndef CCAPI_COINBASE_URL_REST_BASE #define CCAPI_COINBASE_URL_REST_BASE "https://api.exchange.coinbase.com" #endif + #ifndef CCAPI_GEMINI_URL_REST_BASE #define CCAPI_GEMINI_URL_REST_BASE "https://api.gemini.com" #endif + #ifndef CCAPI_KRAKEN_URL_REST_BASE #define CCAPI_KRAKEN_URL_REST_BASE "https://api.kraken.com" #endif + #ifndef CCAPI_KRAKEN_FUTURES_URL_REST_BASE #define CCAPI_KRAKEN_FUTURES_URL_REST_BASE "https://futures.kraken.com" #endif + #ifndef CCAPI_BITSTAMP_URL_REST_BASE #define CCAPI_BITSTAMP_URL_REST_BASE "https://www.bitstamp.net" #endif + #ifndef CCAPI_BITFINEX_PUBLIC_URL_REST_BASE #define CCAPI_BITFINEX_PUBLIC_URL_REST_BASE "https://api-pub.bitfinex.com" #endif + #ifndef CCAPI_BITFINEX_PRIVATE_URL_REST_BASE #define CCAPI_BITFINEX_PRIVATE_URL_REST_BASE "https://api.bitfinex.com" #endif + #ifndef CCAPI_BITFINEX_GET_INSTRUMENTS_PATH #define CCAPI_BITFINEX_GET_INSTRUMENTS_PATH "/v2/conf/pub:info:pair" // use conf/pub:info:pair:futures for futures #endif + #ifndef CCAPI_BITMEX_URL_REST_BASE #define CCAPI_BITMEX_URL_REST_BASE "https://www.bitmex.com" #endif + #ifndef CCAPI_BINANCE_US_URL_REST_BASE #define CCAPI_BINANCE_US_URL_REST_BASE "https://api.binance.us" #endif + #ifndef CCAPI_BINANCE_US_CREATE_ORDER_PATH #define CCAPI_BINANCE_US_CREATE_ORDER_PATH "/api/v3/order" #endif + #ifndef CCAPI_BINANCE_US_LISTEN_KEY_PATH #define CCAPI_BINANCE_US_LISTEN_KEY_PATH "/api/v3/userDataStream" #endif + #ifndef CCAPI_BINANCE_URL_REST_BASE #define CCAPI_BINANCE_URL_REST_BASE "https://api.binance.com" #endif + #ifndef CCAPI_BINANCE_CREATE_ORDER_PATH #define CCAPI_BINANCE_CREATE_ORDER_PATH "/api/v3/order" #endif + #ifndef CCAPI_BINANCE_LISTEN_KEY_PATH #define CCAPI_BINANCE_LISTEN_KEY_PATH "/api/v3/userDataStream" #endif + #ifndef CCAPI_BINANCE_LISTEN_KEY_CROSS_MARGIN_PATH #define CCAPI_BINANCE_LISTEN_KEY_CROSS_MARGIN_PATH "/sapi/v1/userDataStream" #endif + #ifndef CCAPI_BINANCE_LISTEN_KEY_ISOLATED_MARGIN_PATH #define CCAPI_BINANCE_LISTEN_KEY_ISOLATED_MARGIN_PATH "/sapi/v1/userDataStream/isolated" #endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE #define CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE "https://fapi.binance.com" #endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_CREATE_ORDER_PATH #define CCAPI_BINANCE_USDS_FUTURES_CREATE_ORDER_PATH "/fapi/v1/order" #endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH #define CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH "/fapi/v1/listenKey" #endif + #ifndef CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE #define CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE "https://dapi.binance.com" #endif + #ifndef CCAPI_BINANCE_COIN_FUTURES_CREATE_ORDER_PATH #define CCAPI_BINANCE_COIN_FUTURES_CREATE_ORDER_PATH "/dapi/v1/order" #endif + #ifndef CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH #define CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH "/dapi/v1/listenKey" #endif + #ifndef CCAPI_HUOBI_URL_REST_BASE #define CCAPI_HUOBI_URL_REST_BASE "https://api.huobi.pro" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_URL_REST_BASE #define CCAPI_HUOBI_USDT_SWAP_URL_REST_BASE "https://api.hbdm.com" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_URL_REST_BASE #define CCAPI_HUOBI_COIN_SWAP_URL_REST_BASE "https://api.hbdm.com" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_CREATE_ORDER_PATH #define CCAPI_HUOBI_USDT_SWAP_CREATE_ORDER_PATH "/linear-swap-api/v1/swap_cross_order" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_CREATE_ORDER_PATH #define CCAPI_HUOBI_COIN_SWAP_CREATE_ORDER_PATH "/swap-api/v1/swap_order" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_CANCEL_ORDER_PATH #define CCAPI_HUOBI_USDT_SWAP_CANCEL_ORDER_PATH "/linear-swap-api/v1/swap_cross_cancel" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_CANCEL_ORDER_PATH #define CCAPI_HUOBI_COIN_SWAP_CANCEL_ORDER_PATH "/swap-api/v1/swap_cancel" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_GET_ORDER_PATH #define CCAPI_HUOBI_USDT_SWAP_GET_ORDER_PATH "/linear-swap-api/v1/swap_cross_order_info" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_GET_ORDER_PATH #define CCAPI_HUOBI_COIN_SWAP_GET_ORDER_PATH "/swap-api/v1/swap_order_info" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_GET_OPEN_ORDERS_PATH #define CCAPI_HUOBI_USDT_SWAP_GET_OPEN_ORDERS_PATH "/linear-swap-api/v1/swap_cross_openorders" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_GET_OPEN_ORDERS_PATH #define CCAPI_HUOBI_COIN_SWAP_GET_OPEN_ORDERS_PATH "/swap-api/v1/swap_openorders" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_CANCEL_ALL_ORDERS_PATH #define CCAPI_HUOBI_USDT_SWAP_CANCEL_ALL_ORDERS_PATH "/linear-swap-api/v1/swap_cross_cancelall" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_CANCEL_ALL_ORDERS_PATH #define CCAPI_HUOBI_COIN_SWAP_CANCEL_ALL_ORDERS_PATH "/swap-api/v1/swap_cancelall" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_BALANCES_PATH #define CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_BALANCES_PATH "/linear-swap-api/v1/swap_cross_account_info" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_BALANCES_PATH #define CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_BALANCES_PATH "/swap-api/v1/swap_account_info" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_POSITIONS_PATH #define CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_POSITIONS_PATH "/linear-swap-api/v1/swap_cross_position_info" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_POSITIONS_PATH #define CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_POSITIONS_PATH "/swap-api/v1/swap_position_info" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH #define CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH "/linear-swap-ex/market/history/trade" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH #define CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH "/swap-ex/market/history/trade" #endif + #ifndef CCAPI_OKX_URL_REST_BASE #define CCAPI_OKX_URL_REST_BASE "https://www.okx.com" #endif + #ifndef CCAPI_ERISX_URL_REST_BASE #define CCAPI_ERISX_URL_REST_BASE "https://trade-api.erisx.com" #endif + #ifndef CCAPI_KUCOIN_URL_REST_BASE #define CCAPI_KUCOIN_URL_REST_BASE "https://api.kucoin.com" #endif + #ifndef CCAPI_KUCOIN_FUTURES_URL_REST_BASE #define CCAPI_KUCOIN_FUTURES_URL_REST_BASE "https://api-futures.kucoin.com" #endif + #ifndef CCAPI_FTX_URL_REST_BASE #define CCAPI_FTX_URL_REST_BASE "https://ftx.com" #endif + #ifndef CCAPI_FTX_US_URL_REST_BASE #define CCAPI_FTX_US_URL_REST_BASE "https://ftx.us" #endif + #ifndef CCAPI_DERIBIT_URL_REST_BASE #define CCAPI_DERIBIT_URL_REST_BASE "https://www.deribit.com" #endif + #ifndef CCAPI_GATEIO_URL_REST_BASE #define CCAPI_GATEIO_URL_REST_BASE "https://api.gateio.ws" #endif + #ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE #define CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE "https://fx-api.gateio.ws" #endif + #ifndef CCAPI_CRYPTOCOM_URL_REST_BASE #define CCAPI_CRYPTOCOM_URL_REST_BASE "https://api.crypto.com" #endif + #ifndef CCAPI_BYBIT_URL_REST_BASE #define CCAPI_BYBIT_URL_REST_BASE "https://api.bybit.com" #endif + #ifndef CCAPI_ASCENDEX_URL_REST_BASE #define CCAPI_ASCENDEX_URL_REST_BASE "https://ascendex.com" #endif + #ifndef CCAPI_BITGET_URL_REST_BASE #define CCAPI_BITGET_URL_REST_BASE "https://api.bitget.com" #endif + #ifndef CCAPI_BITGET_FUTURES_URL_REST_BASE #define CCAPI_BITGET_FUTURES_URL_REST_BASE "https://api.bitget.com" #endif + #ifndef CCAPI_BITMART_URL_REST_BASE #define CCAPI_BITMART_URL_REST_BASE "https://api-cloud.bitmart.com" #endif + #ifndef CCAPI_MEXC_URL_REST_BASE #define CCAPI_MEXC_URL_REST_BASE "https://api.mexc.com" #endif + #ifndef CCAPI_MEXC_CREATE_ORDER_PATH #define CCAPI_MEXC_CREATE_ORDER_PATH "/api/v3/order" #endif + #ifndef CCAPI_MEXC_LISTEN_KEY_PATH #define CCAPI_MEXC_LISTEN_KEY_PATH "/api/v3/userDataStream" #endif + #ifndef CCAPI_MEXC_FUTURES_URL_REST_BASE #define CCAPI_MEXC_FUTURES_URL_REST_BASE "https://contract.mexc.com" #endif + #ifndef CCAPI_WHITEBIT_URL_REST_BASE #define CCAPI_WHITEBIT_URL_REST_BASE "https://whitebit.com" #endif + // end: exchange REST urls // start: exchange WS urls #ifndef CCAPI_COINBASE_URL_WS_BASE #define CCAPI_COINBASE_URL_WS_BASE "wss://ws-feed.exchange.coinbase.com" #endif + #ifndef CCAPI_GEMINI_URL_WS_BASE #define CCAPI_GEMINI_URL_WS_BASE "wss://api.gemini.com" #endif + #ifndef CCAPI_KRAKEN_URL_WS_BASE #define CCAPI_KRAKEN_URL_WS_BASE "wss://ws.kraken.com" #endif + #ifndef CCAPI_KRAKEN_URL_WS_BASE_PRIVATE #define CCAPI_KRAKEN_URL_WS_BASE_PRIVATE "wss://ws-auth.kraken.com" #endif + #ifndef CCAPI_KRAKEN_FUTURES_URL_WS_BASE #define CCAPI_KRAKEN_FUTURES_URL_WS_BASE "wss://futures.kraken.com" #endif + #ifndef CCAPI_BITSTAMP_URL_WS_BASE #define CCAPI_BITSTAMP_URL_WS_BASE "wss://ws.bitstamp.net" #endif + #ifndef CCAPI_BITFINEX_PUBLIC_URL_WS_BASE #define CCAPI_BITFINEX_PUBLIC_URL_WS_BASE "wss://api-pub.bitfinex.com" #endif + #ifndef CCAPI_BITFINEX_PRIVATE_URL_WS_BASE #define CCAPI_BITFINEX_PRIVATE_URL_WS_BASE "wss://api.bitfinex.com" #endif + #ifndef CCAPI_BITMEX_URL_WS_BASE #define CCAPI_BITMEX_URL_WS_BASE "wss://www.bitmex.com" #endif + #ifndef CCAPI_BINANCE_US_URL_WS_BASE #define CCAPI_BINANCE_US_URL_WS_BASE "wss://stream.binance.us:9443" #endif + #ifndef CCAPI_BINANCE_URL_WS_BASE #define CCAPI_BINANCE_URL_WS_BASE "wss://stream.binance.com:9443" #endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE #define CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE "wss://fstream.binance.com" #endif + +#ifndef CCAPI_BINANCE_USDS_FUTURES_HOST_WS_ORDER_ENTRY +#define CCAPI_BINANCE_USDS_FUTURES_HOST_WS_ORDER_ENTRY "ws-fapi.binance.com" +#endif + +#ifndef CCAPI_BINANCE_USDS_FUTURES_URL_WS_ORDER_ENTRY_BASE +#define CCAPI_BINANCE_USDS_FUTURES_URL_WS_ORDER_ENTRY_BASE "wss://" CCAPI_BINANCE_USDS_FUTURES_HOST_WS_ORDER_ENTRY +#endif + +#ifndef CCAPI_BINANCE_USDS_FUTURES_WS_ORDER_ENTRY_PATH +#define CCAPI_BINANCE_USDS_FUTURES_WS_ORDER_ENTRY_PATH "/ws-fapi/v1" +#endif + #ifndef CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE #define CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE "wss://dstream.binance.com" #endif + +#ifndef CCAPI_BINANCE_COIN_FUTURES_HOST_WS_ORDER_ENTRY +#define CCAPI_BINANCE_COIN_FUTURES_HOST_WS_ORDER_ENTRY "ws-dapi.binance.com" +#endif + +#ifndef CCAPI_BINANCE_COIN_FUTURES_URL_WS_ORDER_ENTRY_BASE +#define CCAPI_BINANCE_COIN_FUTURES_URL_WS_ORDER_ENTRY_BASE "wss://" CCAPI_BINANCE_COIN_FUTURES_HOST_WS_ORDER_ENTRY +#endif + +#ifndef CCAPI_BINANCE_COIN_FUTURES_WS_ORDER_ENTRY_PATH +#define CCAPI_BINANCE_COIN_FUTURES_WS_ORDER_ENTRY_PATH "/ws-dapi/v1" +#endif + +#ifndef CCAPI_BINANCE_HOST_WS_ORDER_ENTRY +#define CCAPI_BINANCE_HOST_WS_ORDER_ENTRY "ws-api.binance.com" +#endif + +#ifndef CCAPI_BINANCE_URL_WS_ORDER_ENTRY_BASE +#define CCAPI_BINANCE_URL_WS_ORDER_ENTRY_BASE "wss://" CCAPI_BINANCE_HOST_WS_ORDER_ENTRY +#endif + +#ifndef CCAPI_BINANCE_WS_ORDER_ENTRY_PATH +#define CCAPI_BINANCE_WS_ORDER_ENTRY_PATH "/ws-api/v3" +#endif + #ifndef CCAPI_HUOBI_URL_WS_BASE #define CCAPI_HUOBI_URL_WS_BASE "wss://api.huobi.pro" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_URL_WS_BASE #define CCAPI_HUOBI_USDT_SWAP_URL_WS_BASE "wss://api.hbdm.com" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC #define CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC "orders_cross" #endif -#ifndef CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC -#define CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC "matchOrders_cross" -#endif + #ifndef CCAPI_HUOBI_COIN_SWAP_URL_WS_BASE #define CCAPI_HUOBI_COIN_SWAP_URL_WS_BASE "wss://api.hbdm.com" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC #define CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC "orders" #endif -#ifndef CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC -#define CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC "matchOrders" -#endif + #ifndef CCAPI_OKX_URL_WS_BASE #define CCAPI_OKX_URL_WS_BASE "wss://ws.okx.com:8443" #endif + #ifndef CCAPI_OKX_PUBLIC_WS_PATH #define CCAPI_OKX_PUBLIC_WS_PATH "/ws/v5/public" #endif + #ifndef CCAPI_OKX_PRIVATE_WS_PATH #define CCAPI_OKX_PRIVATE_WS_PATH "/ws/v5/private" #endif + #ifndef CCAPI_OKX_BUSINESS_WS_PATH #define CCAPI_OKX_BUSINESS_WS_PATH "/ws/v5/business" #endif + #ifndef CCAPI_ERISX_URL_WS_BASE #define CCAPI_ERISX_URL_WS_BASE "wss://publicmd-api.erisx.com" #endif + #ifndef CCAPI_FTX_URL_WS_BASE #define CCAPI_FTX_URL_WS_BASE "wss://ftx.com" #endif + #ifndef CCAPI_FTX_US_URL_WS_BASE #define CCAPI_FTX_US_URL_WS_BASE "wss://ftx.us" #endif + #ifndef CCAPI_DERIBIT_URL_WS_BASE #define CCAPI_DERIBIT_URL_WS_BASE "wss://www.deribit.com" #endif + #ifndef CCAPI_GATEIO_URL_WS_BASE #define CCAPI_GATEIO_URL_WS_BASE "wss://api.gateio.ws" #endif + #ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE #define CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE "wss://fx-ws.gateio.ws" #endif + #ifndef CCAPI_CRYPTOCOM_URL_WS_BASE #define CCAPI_CRYPTOCOM_URL_WS_BASE "wss://stream.crypto.com" #endif + #ifndef CCAPI_BYBIT_URL_WS_BASE #define CCAPI_BYBIT_URL_WS_BASE "wss://stream.bybit.com" #endif + +#ifndef CCAPI_BYBIT_URL_WS_ORDER_ENTRY_BASE +#define CCAPI_BYBIT_URL_WS_ORDER_ENTRY_BASE "wss://stream.bybit.com" +#endif + +#ifndef CCAPI_BYBIT_WS_ORDER_ENTRY_PATH +#define CCAPI_BYBIT_WS_ORDER_ENTRY_PATH "/v5/trade" +#endif + #ifndef CCAPI_ASCENDEX_URL_WS_BASE #define CCAPI_ASCENDEX_URL_WS_BASE "wss://ascendex.com" #endif + #ifndef CCAPI_BITGET_URL_WS_BASE #define CCAPI_BITGET_URL_WS_BASE "wss://ws.bitget.com" #endif + #ifndef CCAPI_BITGET_FUTURES_URL_WS_BASE #define CCAPI_BITGET_FUTURES_URL_WS_BASE "wss://ws.bitget.com" #endif + #ifndef CCAPI_BITMART_URL_WS_BASE #define CCAPI_BITMART_URL_WS_BASE "wss://ws-manager-compress.bitmart.com" #endif + #ifndef CCAPI_MEXC_URL_WS_BASE #define CCAPI_MEXC_URL_WS_BASE "wss://wbs.mexc.com" #endif + #ifndef CCAPI_MEXC_FUTURES_URL_WS_BASE #define CCAPI_MEXC_FUTURES_URL_WS_BASE "wss://contract.mexc.com" #endif + #ifndef CCAPI_WHITEBIT_URL_WS_BASE #define CCAPI_WHITEBIT_URL_WS_BASE "wss://api.whitebit.com" #endif + // end: exchange WS urls // start: exchange FIX urls -#ifndef CCAPI_COINBASE_URL_FIX_BASE -#define CCAPI_COINBASE_URL_FIX_BASE "tcp+ssl://fix.exchange.coinbase.com:4198" +#ifndef CCAPI_BINANCE_URL_FIX_BASE +#define CCAPI_BINANCE_URL_FIX_BASE "tcp+tls://fix-oe.binance.com:9000" #endif + +#ifndef CCAPI_BINANCE_URL_FIX_MARKET_DATA_BASE +#define CCAPI_BINANCE_URL_FIX_MARKET_DATA_BASE "tcp+tls://fix-md.binance.com:9000" +#endif + +#ifndef CCAPI_COINBASE_URL_FIX_BASE +#define CCAPI_COINBASE_URL_FIX_BASE "tcp+ssl://fix-ord.exchange.coinbase.com:6121" +#endif + #ifndef CCAPI_GEMINI_URL_FIX_HOST #define CCAPI_GEMINI_URL_FIX_HOST "" #endif + #ifndef CCAPI_GEMINI_URL_FIX_PORT #define CCAPI_GEMINI_URL_FIX_PORT "" #endif + #ifndef CCAPI_FTX_URL_FIX_BASE #define CCAPI_FTX_URL_FIX_BASE "tcp+ssl://fix.ftx.com:4363" #endif + #ifndef CCAPI_FTX_US_URL_FIX_BASE #define CCAPI_FTX_US_URL_FIX_BASE "tcp+ssl://fix.ftx.us:4363" #endif + #ifndef CCAPI_DERIBIT_URL_FIX_BASE #define CCAPI_DERIBIT_URL_FIX_BASE "www.deribit.com:9883" #endif @@ -936,231 +1293,355 @@ #ifndef CCAPI_COINBASE_API_KEY #define CCAPI_COINBASE_API_KEY "COINBASE_API_KEY" #endif + #ifndef CCAPI_COINBASE_API_SECRET #define CCAPI_COINBASE_API_SECRET "COINBASE_API_SECRET" #endif + #ifndef CCAPI_COINBASE_API_PASSPHRASE #define CCAPI_COINBASE_API_PASSPHRASE "COINBASE_API_PASSPHRASE" #endif + #ifndef CCAPI_GEMINI_API_KEY #define CCAPI_GEMINI_API_KEY "GEMINI_API_KEY" #endif + #ifndef CCAPI_GEMINI_API_SECRET #define CCAPI_GEMINI_API_SECRET "GEMINI_API_SECRET" #endif + #ifndef CCAPI_GEMINI_API_SENDER_COMP_ID #define CCAPI_GEMINI_API_SENDER_COMP_ID "" #endif + #ifndef CCAPI_GEMINI_API_TARGET_COMP_ID #define CCAPI_GEMINI_API_TARGET_COMP_ID "" #endif + #ifndef CCAPI_KRAKEN_API_KEY #define CCAPI_KRAKEN_API_KEY "KRAKEN_API_KEY" #endif + #ifndef CCAPI_KRAKEN_API_SECRET #define CCAPI_KRAKEN_API_SECRET "KRAKEN_API_SECRET" #endif + #ifndef CCAPI_KRAKEN_FUTURES_API_KEY #define CCAPI_KRAKEN_FUTURES_API_KEY "KRAKEN_FUTURES_API_KEY" #endif + #ifndef CCAPI_KRAKEN_FUTURES_API_SECRET #define CCAPI_KRAKEN_FUTURES_API_SECRET "KRAKEN_FUTURES_API_SECRET" #endif + #ifndef CCAPI_BITSTAMP_API_KEY #define CCAPI_BITSTAMP_API_KEY "BITSTAMP_API_KEY" #endif + #ifndef CCAPI_BITSTAMP_API_SECRET #define CCAPI_BITSTAMP_API_SECRET "BITSTAMP_API_SECRET" #endif + #ifndef CCAPI_BITFINEX_API_KEY #define CCAPI_BITFINEX_API_KEY "BITFINEX_API_KEY" #endif + #ifndef CCAPI_BITFINEX_API_SECRET #define CCAPI_BITFINEX_API_SECRET "BITFINEX_API_SECRET" #endif + #ifndef CCAPI_BITMEX_API_KEY #define CCAPI_BITMEX_API_KEY "BITMEX_API_KEY" #endif + #ifndef CCAPI_BITMEX_API_SECRET #define CCAPI_BITMEX_API_SECRET "BITMEX_API_SECRET" #endif + #ifndef CCAPI_BINANCE_US_API_KEY #define CCAPI_BINANCE_US_API_KEY "BINANCE_US_API_KEY" #endif + #ifndef CCAPI_BINANCE_US_API_SECRET #define CCAPI_BINANCE_US_API_SECRET "BINANCE_US_API_SECRET" #endif + #ifndef CCAPI_BINANCE_API_KEY #define CCAPI_BINANCE_API_KEY "BINANCE_API_KEY" #endif + #ifndef CCAPI_BINANCE_API_SECRET #define CCAPI_BINANCE_API_SECRET "BINANCE_API_SECRET" #endif + +#ifndef CCAPI_BINANCE_WEBSOCKET_ORDER_ENTRY_API_KEY +#define CCAPI_BINANCE_WEBSOCKET_ORDER_ENTRY_API_KEY "BINANCE_WEBSOCKET_ORDER_ENTRY_API_KEY" +#endif + +#ifndef CCAPI_BINANCE_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH +#define CCAPI_BINANCE_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH "BINANCE_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH" +#endif + +#ifndef CCAPI_BINANCE_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD +#define CCAPI_BINANCE_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD "BINANCE_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD" +#endif + +#ifndef CCAPI_BINANCE_FIX_API_KEY +#define CCAPI_BINANCE_FIX_API_KEY "BINANCE_FIX_API_KEY" +#endif + +#ifndef CCAPI_BINANCE_FIX_API_PRIVATE_KEY_PATH +#define CCAPI_BINANCE_FIX_API_PRIVATE_KEY_PATH "BINANCE_FIX_API_PRIVATE_KEY_PATH" +#endif + +#ifndef CCAPI_BINANCE_FIX_API_PRIVATE_KEY_PASSWORD +#define CCAPI_BINANCE_FIX_API_PRIVATE_KEY_PASSWORD "BINANCE_FIX_API_PRIVATE_KEY_PASSWORD" +#endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_API_KEY #define CCAPI_BINANCE_USDS_FUTURES_API_KEY "BINANCE_USDS_FUTURES_API_KEY" #endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_API_SECRET #define CCAPI_BINANCE_USDS_FUTURES_API_SECRET "BINANCE_USDS_FUTURES_API_SECRET" #endif + +#ifndef CCAPI_BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_KEY +#define CCAPI_BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_KEY "BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_KEY" +#endif + +#ifndef CCAPI_BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH +#define CCAPI_BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH "BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH" +#endif + +#ifndef CCAPI_BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD +#define CCAPI_BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD "BINANCE_USDS_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD" +#endif + #ifndef CCAPI_BINANCE_COIN_FUTURES_API_KEY #define CCAPI_BINANCE_COIN_FUTURES_API_KEY "BINANCE_COIN_FUTURES_API_KEY" #endif + #ifndef CCAPI_BINANCE_COIN_FUTURES_API_SECRET #define CCAPI_BINANCE_COIN_FUTURES_API_SECRET "BINANCE_COIN_FUTURES_API_SECRET" #endif + +#ifndef CCAPI_BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_KEY +#define CCAPI_BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_KEY "BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_KEY" +#endif + +#ifndef CCAPI_BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH +#define CCAPI_BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH "BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PATH" +#endif + +#ifndef CCAPI_BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD +#define CCAPI_BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD "BINANCE_COIN_FUTURES_WEBSOCKET_ORDER_ENTRY_API_PRIVATE_KEY_PASSWORD" +#endif + #ifndef CCAPI_HUOBI_API_KEY #define CCAPI_HUOBI_API_KEY "HUOBI_API_KEY" #endif + #ifndef CCAPI_HUOBI_API_SECRET #define CCAPI_HUOBI_API_SECRET "HUOBI_API_SECRET" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_API_KEY #define CCAPI_HUOBI_USDT_SWAP_API_KEY "HUOBI_USDT_SWAP_API_KEY" #endif + #ifndef CCAPI_HUOBI_USDT_SWAP_API_SECRET #define CCAPI_HUOBI_USDT_SWAP_API_SECRET "HUOBI_USDT_SWAP_API_SECRET" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_API_KEY #define CCAPI_HUOBI_COIN_SWAP_API_KEY "HUOBI_COIN_SWAP_API_KEY" #endif + #ifndef CCAPI_HUOBI_COIN_SWAP_API_SECRET #define CCAPI_HUOBI_COIN_SWAP_API_SECRET "HUOBI_COIN_SWAP_API_SECRET" #endif + #ifndef CCAPI_OKX_API_KEY #define CCAPI_OKX_API_KEY "OKX_API_KEY" #endif + #ifndef CCAPI_OKX_API_SECRET #define CCAPI_OKX_API_SECRET "OKX_API_SECRET" #endif + #ifndef CCAPI_OKX_API_PASSPHRASE #define CCAPI_OKX_API_PASSPHRASE "OKX_API_PASSPHRASE" #endif + #ifndef CCAPI_OKX_API_X_SIMULATED_TRADING #define CCAPI_OKX_API_X_SIMULATED_TRADING "OKX_API_X_SIMULATED_TRADING" #endif + #ifndef CCAPI_ERISX_API_KEY #define CCAPI_ERISX_API_KEY "ERISX_API_KEY" #endif + #ifndef CCAPI_ERISX_API_SECRET #define CCAPI_ERISX_API_SECRET "ERISX_API_SECRET" #endif + #ifndef CCAPI_KUCOIN_API_KEY #define CCAPI_KUCOIN_API_KEY "KUCOIN_API_KEY" #endif + #ifndef CCAPI_KUCOIN_API_SECRET #define CCAPI_KUCOIN_API_SECRET "KUCOIN_API_SECRET" #endif + #ifndef CCAPI_KUCOIN_API_PASSPHRASE #define CCAPI_KUCOIN_API_PASSPHRASE "KUCOIN_API_PASSPHRASE" #endif + #ifndef CCAPI_KUCOIN_API_KEY_VERSION #define CCAPI_KUCOIN_API_KEY_VERSION "KUCOIN_API_KEY_VERSION" #endif + #ifndef CCAPI_KUCOIN_FUTURES_API_KEY #define CCAPI_KUCOIN_FUTURES_API_KEY "KUCOIN_FUTURES_API_KEY" #endif + #ifndef CCAPI_KUCOIN_FUTURES_API_SECRET #define CCAPI_KUCOIN_FUTURES_API_SECRET "KUCOIN_FUTURES_API_SECRET" #endif + #ifndef CCAPI_KUCOIN_FUTURES_API_PASSPHRASE #define CCAPI_KUCOIN_FUTURES_API_PASSPHRASE "KUCOIN_FUTURES_API_PASSPHRASE" #endif + #ifndef CCAPI_FTX_API_KEY #define CCAPI_FTX_API_KEY "FTX_API_KEY" #endif + #ifndef CCAPI_FTX_API_SECRET #define CCAPI_FTX_API_SECRET "FTX_API_SECRET" #endif + #ifndef CCAPI_FTX_API_SUBACCOUNT #define CCAPI_FTX_API_SUBACCOUNT "FTX_API_SUBACCOUNT" #endif + #ifndef CCAPI_FTX_US_API_KEY #define CCAPI_FTX_US_API_KEY "FTX_US_API_KEY" #endif + #ifndef CCAPI_FTX_US_API_SECRET #define CCAPI_FTX_US_API_SECRET "FTX_US_API_SECRET" #endif + #ifndef CCAPI_FTX_US_API_SUBACCOUNT #define CCAPI_FTX_US_API_SUBACCOUNT "FTX_US_API_SUBACCOUNT" #endif + #ifndef CCAPI_DERIBIT_CLIENT_ID #define CCAPI_DERIBIT_CLIENT_ID "DERIBIT_CLIENT_ID" #endif + #ifndef CCAPI_DERIBIT_CLIENT_SECRET #define CCAPI_DERIBIT_CLIENT_SECRET "DERIBIT_CLIENT_SECRET" #endif + #ifndef CCAPI_GATEIO_API_KEY #define CCAPI_GATEIO_API_KEY "GATEIO_API_KEY" #endif + #ifndef CCAPI_GATEIO_API_SECRET #define CCAPI_GATEIO_API_SECRET "GATEIO_API_SECRET" #endif + #ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY #define CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY "GATEIO_PERPETUAL_FUTURES_API_KEY" #endif + #ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET #define CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET "GATEIO_PERPETUAL_FUTURES_API_SECRET" #endif + #ifndef CCAPI_CRYPTOCOM_API_KEY #define CCAPI_CRYPTOCOM_API_KEY "CRYPTOCOM_API_KEY" #endif + #ifndef CCAPI_CRYPTOCOM_API_SECRET #define CCAPI_CRYPTOCOM_API_SECRET "CRYPTOCOM_API_SECRET" #endif + #ifndef CCAPI_BYBIT_API_KEY #define CCAPI_BYBIT_API_KEY "BYBIT_API_KEY" #endif + #ifndef CCAPI_BYBIT_API_SECRET #define CCAPI_BYBIT_API_SECRET "BYBIT_API_SECRET" #endif + #ifndef CCAPI_ASCENDEX_API_KEY #define CCAPI_ASCENDEX_API_KEY "ASCENDEX_API_KEY" #endif + #ifndef CCAPI_ASCENDEX_API_SECRET #define CCAPI_ASCENDEX_API_SECRET "ASCENDEX_API_SECRET" #endif + #ifndef CCAPI_ASCENDEX_API_ACCOUNT_GROUP #define CCAPI_ASCENDEX_API_ACCOUNT_GROUP "ASCENDEX_API_ACCOUNT_GROUP" #endif + #ifndef CCAPI_BITGET_API_KEY #define CCAPI_BITGET_API_KEY "BITGET_API_KEY" #endif + #ifndef CCAPI_BITGET_API_SECRET #define CCAPI_BITGET_API_SECRET "BITGET_API_SECRET" #endif + #ifndef CCAPI_BITGET_API_PASSPHRASE #define CCAPI_BITGET_API_PASSPHRASE "BITGET_API_PASSPHRASE" #endif + #ifndef CCAPI_BITGET_FUTURES_API_KEY #define CCAPI_BITGET_FUTURES_API_KEY "BITGET_FUTURES_API_KEY" #endif + #ifndef CCAPI_BITGET_FUTURES_API_SECRET #define CCAPI_BITGET_FUTURES_API_SECRET "BITGET_FUTURES_API_SECRET" #endif + #ifndef CCAPI_BITGET_FUTURES_API_PASSPHRASE #define CCAPI_BITGET_FUTURES_API_PASSPHRASE "BITGET_FUTURES_API_PASSPHRASE" #endif + #ifndef CCAPI_BITMART_API_KEY #define CCAPI_BITMART_API_KEY "BITMART_API_KEY" #endif + #ifndef CCAPI_BITMART_API_SECRET #define CCAPI_BITMART_API_SECRET "BITMART_API_SECRET" #endif + #ifndef CCAPI_BITMART_API_MEMO #define CCAPI_BITMART_API_MEMO "BITMART_API_MEMO" #endif + #ifndef CCAPI_MEXC_API_KEY #define CCAPI_MEXC_API_KEY "MEXC_API_KEY" #endif + #ifndef CCAPI_MEXC_API_SECRET #define CCAPI_MEXC_API_SECRET "MEXC_API_SECRET" #endif + #ifndef CCAPI_MEXC_FUTURES_API_KEY #define CCAPI_MEXC_FUTURES_API_KEY "MEXC_FUTURES_API_KEY" #endif + #ifndef CCAPI_MEXC_FUTURES_API_SECRET #define CCAPI_MEXC_FUTURES_API_SECRET "MEXC_FUTURES_API_SECRET" #endif + // end: exchange API credentials #define CCAPI_HTTP_PORT_DEFAULT "80" @@ -1168,28 +1649,40 @@ #ifndef CCAPI_BITMEX_API_RECEIVE_WINDOW_SECONDS #define CCAPI_BITMEX_API_RECEIVE_WINDOW_SECONDS 5 #endif + #ifndef CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE #define CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE "tu" #endif + #define CCAPI_AUTHORIZATION "AUTHORIZATION" #ifndef CCAPI_HFFIX_READ_MESSAGE_CHUNK_SIZE #define CCAPI_HFFIX_READ_MESSAGE_CHUNK_SIZE 4096 #endif + +#ifndef CCAPI_FIX_PROTOCOL_VERSION_BINANCE +#define CCAPI_FIX_PROTOCOL_VERSION_BINANCE "FIX.4.4" +#endif + #ifndef CCAPI_FIX_PROTOCOL_VERSION_COINBASE #define CCAPI_FIX_PROTOCOL_VERSION_COINBASE "FIX.4.2" #endif + #ifndef CCAPI_FIX_PROTOCOL_VERSION_GEMINI #define CCAPI_FIX_PROTOCOL_VERSION_GEMINI "FIX.4.4" #endif + #ifndef CCAPI_FIX_PROTOCOL_VERSION_FTX #define CCAPI_FIX_PROTOCOL_VERSION_FTX "FIX.4.2" #endif + #ifndef CCAPI_FIX_PROTOCOL_VERSION_FTX_US #define CCAPI_FIX_PROTOCOL_VERSION_FTX_US "FIX.4.2" #endif + #ifndef CCAPI_FIX_PROTOCOL_VERSION_DERIBIT #define CCAPI_FIX_PROTOCOL_VERSION_DERIBIT "FIX.4.4" #endif + #ifndef CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS #define CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS 5000 #endif @@ -1197,31 +1690,54 @@ #ifndef CCAPI_OKX_API_BROKER_CODE #define CCAPI_OKX_API_BROKER_CODE "9cbc6a17a1fcBCDE" #endif + #ifndef CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID #define CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID "CCAPI" #endif + #ifndef CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY #define CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY "acd80910-9304-4625-93c0-dabe644d2ae3" #endif + #ifndef CCAPI_BITGET_API_CHANNEL_API_CODE #define CCAPI_BITGET_API_CHANNEL_API_CODE "95mpa" #endif + #ifndef CCAPI_GATEIO_API_CHANNEL_ID -#define CCAPI_GATEIO_API_CHANNEL_ID "cryptochassis" +#define CCAPI_GATEIO_API_CHANNEL_ID "cryptochassis2" #endif + #ifndef CCAPI_MEXC_API_SOURCE #define CCAPI_MEXC_API_SOURCE "CHAS" #endif + #ifndef CCAPI_BYBIT_API_BROKER_ID #define CCAPI_BYBIT_API_BROKER_ID "Vs000261" #endif + #ifndef CCAPI_BINANCE_API_LINK_ID #define CCAPI_BINANCE_API_LINK_ID "XHKUG2CH" #endif + #ifndef CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID #define CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID "QzcVS63u" #endif + #ifndef CCAPI_BITMART_BROKER_ID #define CCAPI_BITMART_BROKER_ID "cryptochassis01" #endif -#endif // INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_ + +#ifndef CCAPI_CRYPTOCOM_BROKER_CODE +#define CCAPI_CRYPTOCOM_BROKER_CODE "CHAS" +#endif + +#ifndef CCAPI_HTX_BROKER_ID +#define CCAPI_HTX_BROKER_ID "AA3b46363e" +#endif + +#ifndef CCAPI_EM_CLIENT_ORDER_ID_SEQUENCE_NUMBER_PAD_TO_LENGTH +#define CCAPI_EM_CLIENT_ORDER_ID_SEQUENCE_NUMBER_PAD_TO_LENGTH 3 +#endif + +#endif +// INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_ diff --git a/linux/include/ccapi_cpp/ccapi_market_data_message.h b/linux/include/ccapi_cpp/ccapi_market_data_message.h index 721098ed9..1bcc7d3e4 100644 --- a/linux/include/ccapi_cpp/ccapi_market_data_message.h +++ b/linux/include/ccapi_cpp/ccapi_market_data_message.h @@ -2,9 +2,11 @@ #define INCLUDE_CCAPI_CPP_CCAPI_MARKET_DATA_MESSAGE_H_ #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_util_private.h" + // #include "ccapi_message.h" namespace ccapi { -class MarketDataMessage CCAPI_FINAL { + +class MarketDataMessage { /** * A handle to a single market data message. Each MarketDataMessage is associated with one 'exchangeSubscriptionId' value. The MarketDataMessage contents are * represented in its 'data' attribute. Each MarketDataMessage object consists of an Type attribute and a RecapType attribute. The exchange timestamp (if any) @@ -23,6 +25,7 @@ class MarketDataMessage CCAPI_FINAL { NONE, // normal data tick; not a recap SOLICITED, // generated on request by subscriber }; + static std::string recapTypeToString(RecapType recapType) { std::string output; switch (recapType) { @@ -47,6 +50,7 @@ class MarketDataMessage CCAPI_FINAL { AGG_TRADE = 3, CANDLESTICK = 4, }; + static std::string dataTypeToString(DataType dataType) { std::string output; switch (dataType) { @@ -84,6 +88,7 @@ class MarketDataMessage CCAPI_FINAL { VOLUME = 10, QUOTE_VOLUME = 11, }; + static std::string dataFieldTypeToString(DataFieldType dataFieldType) { std::string output; switch (dataFieldType) { @@ -128,48 +133,103 @@ class MarketDataMessage CCAPI_FINAL { } return output; } - typedef std::map TypeForDataPoint; - typedef std::map > > TypeForData; - static std::string dataToString(const TypeForData& data) { + + typedef std::map TypeForDataPoint; + typedef std::map> TypeForData; + + typedef std::map TypeForOwingDataPoint; + typedef std::map> TypeForOwingData; + + static TypeForOwingData ConvertDataToOwingData(const TypeForData& input) { + TypeForOwingData output; + for (const auto& [dataType, dataPoints] : input) { + for (const auto& dataPoint : dataPoints) { + output[dataType].push_back(ConvertDataPointToOwingDataPoint(dataPoint)); + } + } + return output; + } + + static TypeForData ConvertOwningDataToData(const TypeForOwingData& input) { + TypeForData output; + for (const auto& [dataType, dataPoints] : input) { + for (const auto& dataPoint : dataPoints) { + output[dataType].push_back(ConvertOwningDataPointToDataPoint(dataPoint)); + } + } + return output; + } + + static TypeForOwingDataPoint ConvertDataPointToOwingDataPoint(const TypeForDataPoint& input) { + TypeForOwingDataPoint output; + for (const auto& [dataFieldType, dataFieldValue] : input) { + output.emplace(dataFieldType, std::string(dataFieldValue)); + } + return output; + } + + static TypeForDataPoint ConvertOwningDataPointToDataPoint(const TypeForOwingDataPoint& input) { + TypeForDataPoint output; + for (const auto& [dataFieldType, dataFieldValue] : input) { + output.emplace(dataFieldType, std::string_view(dataFieldValue)); + } + return output; + } + + template + static std::string dataToString(const DataMap& data) { std::string output1 = "{"; auto size1 = data.size(); auto i1 = 0; + for (const auto& elem1 : data) { output1 += dataTypeToString(elem1.first); output1 += "="; + std::string output2 = "[ "; auto size2 = elem1.second.size(); auto i2 = 0; + for (const auto& elem2 : elem1.second) { std::string output3 = "{"; auto size3 = elem2.size(); auto i3 = 0; + for (const auto& elem3 : elem2) { output3 += dataFieldTypeToString(elem3.first); output3 += "="; + + // Works for std::string, std::string_view, or any type output3 += ccapi::toString(elem3.second); + if (i3 < size3 - 1) { output3 += ", "; } ++i3; } + output3 += "}"; output2 += output3; + if (i2 < size2 - 1) { output2 += ", "; } ++i2; } + output2 += " ]"; output1 += output2; + if (i1 < size1 - 1) { output1 += ", "; } ++i1; } + output1 += "}"; return output1; } + static std::string typeToString(Type type) { std::string output; switch (type) { @@ -193,16 +253,19 @@ class MarketDataMessage CCAPI_FINAL { } return output; } + std::string toString() const { std::string output = "MarketDataMessage [type = " + typeToString(type) + ", recapType = " + recapTypeToString(recapType) + ", tp = " + ccapi::toString(tp) + - ", exchangeSubscriptionId = " + exchangeSubscriptionId + ", data = " + dataToString(data) + "]"; + ", exchangeSubscriptionId = " + exchangeSubscriptionId + ", data = " + dataToString(data) + "]"; return output; } + Type type{Type::UNKNOWN}; RecapType recapType{RecapType::UNKNOWN}; TimePoint tp{std::chrono::seconds{0}}; std::string exchangeSubscriptionId; TypeForData data; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_MARKET_DATA_MESSAGE_H_ diff --git a/linux/include/ccapi_cpp/ccapi_message.h b/linux/include/ccapi_cpp/ccapi_message.h index 849ccd7fa..8fe1a0580 100644 --- a/linux/include/ccapi_cpp/ccapi_message.h +++ b/linux/include/ccapi_cpp/ccapi_message.h @@ -5,14 +5,16 @@ #include "ccapi_cpp/ccapi_element.h" #include "ccapi_cpp/ccapi_logger.h" + namespace ccapi { + /** * A handle to a single message. Message objects are obtained from the getMessageList() function of the Event object. Each Message is associated with one or * more correlation id values. The Message contents are represented as Elements and can be accessed via the getElementList() function. Each Message object * consists of an Type attribute and a RecapType attribute. The exchange timestamp (if any) associated with the Messsage object can be retrieved via the * getTime() function. The library timestamp can be retrieved via the getTimeReceived() function. */ -class Message CCAPI_FINAL { +class Message { public: enum class RecapType { UNKNOWN, @@ -21,6 +23,7 @@ class Message CCAPI_FINAL { NONE, // Normal data tick, not a recap. For market depth, it represents the updated order book state. For public trade, it represents the new trades. These // are the batches of data points after the first batch. }; + static std::string recapTypeToString(RecapType recapType) { std::string output; switch (recapType) { @@ -48,10 +51,12 @@ class Message CCAPI_FINAL { MARKET_DATA_EVENTS_CANDLESTICK, EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE, EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE, + EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE_LITE, EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE, EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE, SUBSCRIPTION_STARTED, SUBSCRIPTION_FAILURE, + SUBSCRIPTION_FAILURE_DUE_TO_CONNECTION_FAILURE, SESSION_CONNECTION_UP, SESSION_CONNECTION_DOWN, INCORRECT_STATE_FOUND, @@ -70,18 +75,23 @@ class Message CCAPI_FINAL { GET_RECENT_CANDLESTICKS, GET_HISTORICAL_CANDLESTICKS, GET_MARKET_DEPTH, + GET_SERVER_TIME, GET_INSTRUMENT, GET_INSTRUMENTS, + GET_BBOS, + GET_TICKERS, RESPONSE_ERROR, REQUEST_FAILURE, GENERIC_ERROR, CUSTOM, FIX, FIX_FAILURE, + FIX_FAILURE_DUE_TO_CONNECTION_FAILURE, GENERIC_PUBLIC_REQUEST, GENERIC_PUBLIC_SUBSCRIPTION, GENERIC_PRIVATE_REQUEST, }; + static std::string typeToString(Type type) { std::string output; switch (type) { @@ -112,6 +122,9 @@ class Message CCAPI_FINAL { case Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE: output = "EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE"; break; + case Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE_LITE: + output = "EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE_LITE"; + break; case Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE: output = "EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE"; break; @@ -124,6 +137,9 @@ class Message CCAPI_FINAL { case Type::SUBSCRIPTION_FAILURE: output = "SUBSCRIPTION_FAILURE"; break; + case Type::SUBSCRIPTION_FAILURE_DUE_TO_CONNECTION_FAILURE: + output = "SUBSCRIPTION_FAILURE_DUE_TO_CONNECTION_FAILURE"; + break; case Type::SESSION_CONNECTION_UP: output = "SESSION_CONNECTION_UP"; break; @@ -178,12 +194,21 @@ class Message CCAPI_FINAL { case Type::GET_MARKET_DEPTH: output = "GET_MARKET_DEPTH"; break; + case Type::GET_SERVER_TIME: + output = "GET_SERVER_TIME"; + break; case Type::GET_INSTRUMENT: output = "GET_INSTRUMENT"; break; case Type::GET_INSTRUMENTS: output = "GET_INSTRUMENTS"; break; + case Type::GET_BBOS: + output = "GET_BBOS"; + break; + case Type::GET_TICKERS: + output = "GET_TICKERS"; + break; case Type::RESPONSE_ERROR: output = "RESPONSE_ERROR"; break; @@ -202,6 +227,9 @@ class Message CCAPI_FINAL { case Type::FIX_FAILURE: output = "FIX_FAILURE"; break; + case Type::FIX_FAILURE_DUE_TO_CONNECTION_FAILURE: + output = "FIX_FAILURE_DUE_TO_CONNECTION_FAILURE"; + break; case Type::GENERIC_PUBLIC_REQUEST: output = "GENERIC_PUBLIC_REQUEST"; break; @@ -216,48 +244,63 @@ class Message CCAPI_FINAL { } return output; } + std::string toString() const { std::string output = "Message [type = " + typeToString(type) + ", recapType = " + recapTypeToString(recapType) + ", time = " + UtilTime::getISOTimestamp(time) + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + - ", elementList = " + ccapi::firstNToString(elementList, 10) + ", correlationIdList = " + ccapi::toString(correlationIdList) + - ", secondaryCorrelationIdMap = " + ccapi::toString(secondaryCorrelationIdMap) + "]"; + ", elementList = " + ccapi::firstNToString(elementList, 10) + ", correlationIdList = " + ccapi::toString(correlationIdList) + "]"; return output; } - std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { + + std::string toPrettyString(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { std::string sl(leftToIndent, ' '); std::string ss(leftToIndent + space, ' '); std::string output = (indentFirstLine ? sl : "") + "Message [\n" + ss + "type = " + typeToString(type) + ",\n" + ss + "recapType = " + recapTypeToString(recapType) + ",\n" + ss + "time = " + UtilTime::getISOTimestamp(time) + ",\n" + ss + "timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ",\n" + ss + "elementList = " + ccapi::firstNToStringPretty(elementList, 10, space, space + leftToIndent, false) + ",\n" + ss + - "correlationIdList = " + ccapi::toString(correlationIdList) + ",\n" + ss + - "secondaryCorrelationIdMap = " + ccapi::toString(secondaryCorrelationIdMap) + "\n" + sl + "]"; + "correlationIdList = " + ccapi::toString(correlationIdList) + ",\n" + sl + "]"; return output; } + const std::vector& getElementList() const { return elementList; } + void setElementList(const std::vector& elementList) { this->elementList = elementList; } + void setElementList(std::vector& elementList) { this->elementList = std::move(elementList); } + const std::vector& getCorrelationIdList() const { return correlationIdList; } - const std::map& getSecondaryCorrelationIdMap() const { return secondaryCorrelationIdMap; } + void setCorrelationIdList(const std::vector& correlationIdList) { this->correlationIdList = correlationIdList; } - void setSecondaryCorrelationIdMap(const std::map& secondaryCorrelationIdMap) { - this->secondaryCorrelationIdMap = secondaryCorrelationIdMap; - } + // 'getTime' only works in C++. For other languages, please use 'getTimeISO'. TimePoint getTime() const { return time; } + std::string getTimeISO() const { return UtilTime::getISOTimestamp(time); } + std::pair getTimeUnix() const { return UtilTime::divide(time); } + std::pair getTimePair() const { return UtilTime::divide(time); } + void setTime(TimePoint time) { this->time = time; } + RecapType getRecapType() const { return recapType; } + void setRecapType(RecapType recapType) { this->recapType = recapType; } + Type getType() const { return type; } + void setType(Type type) { this->type = type; } + // 'getTimeReceived' only works in C++. For other languages, please use 'getTimeReceivedISO'. TimePoint getTimeReceived() const { return timeReceived; } + std::string getTimeReceivedISO() const { return UtilTime::getISOTimestamp(timeReceived); } + std::pair getTimeReceivedUnix() const { return UtilTime::divide(timeReceived); } + std::pair getTimeReceivedPair() const { return UtilTime::divide(timeReceived); } + void setTimeReceived(TimePoint timeReceived) { this->timeReceived = timeReceived; } #ifndef CCAPI_EXPOSE_INTERNAL @@ -267,9 +310,9 @@ class Message CCAPI_FINAL { TimePoint timeReceived{std::chrono::seconds{0}}; std::vector elementList; std::vector correlationIdList; - std::map secondaryCorrelationIdMap; Type type{Type::UNKNOWN}; RecapType recapType{RecapType::UNKNOWN}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_MESSAGE_H_ diff --git a/linux/include/ccapi_cpp/ccapi_queue.h b/linux/include/ccapi_cpp/ccapi_queue.h index f1657a825..31f5fc2b6 100644 --- a/linux/include/ccapi_cpp/ccapi_queue.h +++ b/linux/include/ccapi_cpp/ccapi_queue.h @@ -1,24 +1,26 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_QUEUE_H_ #define INCLUDE_CCAPI_CPP_CCAPI_QUEUE_H_ #include -#include #include #include "ccapi_cpp/ccapi_logger.h" + namespace ccapi { + /** * This class represents a generic FIFO queue. */ -template + +template class Queue { public: - std::string EXCEPTION_QUEUE_FULL = "queue is full"; - std::string EXCEPTION_QUEUE_EMPTY = "queue is empty"; + inline static const std::string EXCEPTION_QUEUE_FULL = "queue is full"; + inline static const std::string EXCEPTION_QUEUE_EMPTY = "queue is empty"; + explicit Queue(const size_t maxSize = 0) : maxSize(maxSize) {} + void pushBack(const T& t) { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif if (this->maxSize <= 0 || this->queue.size() < this->maxSize) { CCAPI_LOGGER_TRACE("this->queue.size() = " + size_tToString(this->queue.size())); this->queue.push_back(t); @@ -26,10 +28,9 @@ class Queue { throw std::runtime_error(EXCEPTION_QUEUE_FULL); } } + void pushBack(T&& t) { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif if (this->maxSize <= 0 || this->queue.size() < this->maxSize) { CCAPI_LOGGER_TRACE("this->queue.size() = " + size_tToString(this->queue.size())); this->queue.push_back(t); @@ -37,10 +38,9 @@ class Queue { throw std::runtime_error(EXCEPTION_QUEUE_FULL); } } + T popBack() { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif if (this->queue.empty()) { throw std::runtime_error(EXCEPTION_QUEUE_EMPTY); } else { @@ -49,18 +49,16 @@ class Queue { return t; } } + std::vector purge() { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif std::vector p; std::swap(p, this->queue); return p; } + void removeAll(std::vector& c) { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif if (c.empty()) { c = std::move(this->queue); } else { @@ -69,16 +67,14 @@ class Queue { } this->queue.clear(); } + size_t size() const { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif return this->queue.size(); } + bool empty() const { -#ifndef CCAPI_USE_SINGLE_THREAD std::lock_guard lock(this->m); -#endif return this->queue.empty(); } #ifndef CCAPI_EXPOSE_INTERNAL @@ -86,10 +82,9 @@ class Queue { private: #endif std::vector queue; -#ifndef CCAPI_USE_SINGLE_THREAD mutable std::mutex m; -#endif size_t maxSize{}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_QUEUE_H_ diff --git a/linux/include/ccapi_cpp/ccapi_request.h b/linux/include/ccapi_cpp/ccapi_request.h index d2e4f14f3..5e23b9796 100644 --- a/linux/include/ccapi_cpp/ccapi_request.h +++ b/linux/include/ccapi_cpp/ccapi_request.h @@ -16,16 +16,19 @@ #define CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT 0x600 #define CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ORDER CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT #define CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT 0x700 + namespace ccapi { + /** * A single request. Request objects are created using Request constructors. They are used with Session::sendRequest() or Session::sendRequestByWebsocket() or * Session::sendRequestByFix(). The Request object contains the parameters for a single request. Once a Request has been created its fields can be further - * modified using the convenience functions appendParam() or appendParamFix() or setParamList() or setParamListFix(). A correlation id can be used as the unique + * modified using the convenience functions appendParam() or appendFixParam() or setParamList() or setParamListFix(). A correlation id can be used as the unique * identifier to tag all data associated with this request. */ -class Request CCAPI_FINAL { +class Request { public: enum class Operation { + UNKNOWN = 0, CUSTOM = CCAPI_REQUEST_OPERATION_TYPE_CUSTOM, GENERIC_PUBLIC_REQUEST = CCAPI_REQUEST_OPERATION_TYPE_GENERIC_PUBLIC_REQUEST, GENERIC_PRIVATE_REQUEST = CCAPI_REQUEST_OPERATION_TYPE_GENERIC_PRIVATE_REQUEST, @@ -37,8 +40,11 @@ class Request CCAPI_FINAL { GET_RECENT_CANDLESTICKS, GET_HISTORICAL_CANDLESTICKS, GET_MARKET_DEPTH, + GET_SERVER_TIME, GET_INSTRUMENT, GET_INSTRUMENTS, + GET_BBOS, + GET_TICKERS, CREATE_ORDER = CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ORDER, CANCEL_ORDER, GET_ORDER, @@ -48,12 +54,16 @@ class Request CCAPI_FINAL { GET_ACCOUNT_BALANCES, GET_ACCOUNT_POSITIONS, }; + static std::string operationToString(Operation operation) { std::string output; switch (operation) { case Operation::CUSTOM: output = "CUSTOM"; break; + case Operation::UNKNOWN: + output = "UNKNOWN"; + break; case Operation::GENERIC_PUBLIC_REQUEST: output = "GENERIC_PUBLIC_REQUEST"; break; @@ -84,12 +94,21 @@ class Request CCAPI_FINAL { case Operation::GET_MARKET_DEPTH: output = "GET_MARKET_DEPTH"; break; + case Operation::GET_SERVER_TIME: + output = "GET_SERVER_TIME"; + break; case Operation::GET_INSTRUMENT: output = "GET_INSTRUMENT"; break; case Operation::GET_INSTRUMENTS: output = "GET_INSTRUMENTS"; break; + case Operation::GET_BBOS: + output = "GET_BBOS"; + break; + case Operation::GET_TICKERS: + output = "GET_TICKERS"; + break; case Operation::CREATE_ORDER: output = "CREATE_ORDER"; break; @@ -115,13 +134,13 @@ class Request CCAPI_FINAL { output = "GET_ACCOUNT_POSITIONS"; break; default: - CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + CCAPI_LOGGER_FATAL(std::string(CCAPI_UNSUPPORTED_VALUE) + " " + std::to_string(static_cast(operation))); } return output; } - Request() {} - Request(Operation operation, std::string exchange, std::string instrument = "", std::string correlationId = "", - std::map credential = {}) + + explicit Request(Operation operation = Operation::UNKNOWN, const std::string& exchange = "", const std::string& instrument = "", + const std::string& correlationId = "", const std::map& credential = {}) : operation(operation), exchange(exchange), instrument(instrument), correlationId(correlationId), credential(credential) { if (operation == Operation::CUSTOM) { this->serviceName = CCAPI_UNKNOWN; @@ -138,37 +157,51 @@ class Request CCAPI_FINAL { this->correlationId = UtilString::generateRandomString(CCAPI_CORRELATION_ID_GENERATED_LENGTH); } } + std::string toString() const { std::map shortCredential; for (const auto& x : credential) { shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); } std::string output = - "Request [exchange = " + exchange + ", marginType = " + marginType + ", instrument = " + instrument + ", serviceName = " + serviceName + - ", correlationId = " + correlationId + ", secondaryCorrelationId = " + secondaryCorrelationId + + "Request [operation = " + operationToString(operation) + ", exchange = " + exchange + ", marginType = " + marginType + ", instrument = " + instrument + + ", serviceName = " + serviceName + ", correlationId = " + correlationId + (this->serviceName == CCAPI_FIX ? ", paramListFix = " + ccapi::toString(paramListFix) : ", paramList = " + ccapi::toString(paramList)) + - ", credential = " + ccapi::toString(shortCredential) + ", operation = " + operationToString(operation) + - ", timeSent = " + UtilTime::getISOTimestamp(timeSent) + ", index = " + ccapi::toString(index) + ", localIpAddress = " + localIpAddress + - ", baseUrl = " + baseUrl + "]"; + ", credential = " + ccapi::toString(shortCredential) + ", timeSent = " + UtilTime::getISOTimestamp(timeSent) + ", index = " + ccapi::toString(index) + + ", localIpAddress = " + localIpAddress + ", baseUrl = " + baseUrl + "]"; return output; } + const std::string& getCorrelationId() const { return correlationId; } - const std::string& getSecondaryCorrelationId() const { return secondaryCorrelationId; } + const std::string& getExchange() const { return exchange; } + const std::string& getMarginType() const { return marginType; } + const std::string& getInstrument() const { return instrument; } + const std::map& getCredential() const { return credential; } + const std::string& getServiceName() const { return serviceName; } + void appendParam(const std::map& param) { this->paramList.push_back(param); } - void appendParamFix(const std::vector >& param) { this->paramListFix.push_back(param); } - void appendParamListFix(const std::vector > >& paramList) { + + void appendFixParam(const std::vector>& param) { this->paramListFix.push_back(param); } + + void appendParamListFix(const std::vector>>& paramList) { this->paramListFix.insert(std::end(this->paramListFix), std::begin(paramList), std::end(paramList)); } - void setParamListFix(const std::vector > >& paramListFix) { this->paramListFix = paramListFix; } + + void setParamListFix(const std::vector>>& paramListFix) { this->paramListFix = paramListFix; } + Operation getOperation() const { return operation; } - const std::vector >& getParamList() const { return paramList; } - const std::vector > >& getParamListFix() const { return paramListFix; } - void setParamList(const std::vector >& paramList) { this->paramList = paramList; } + + const std::vector>& getParamList() const { return paramList; } + + const std::vector>>& getParamListFix() const { return paramListFix; } + + void setParamList(const std::vector>& paramList) { this->paramList = paramList; } + std::map getFirstParamWithDefault(const std::map defaultValue = {}) const { if (this->paramList.empty()) { return defaultValue; @@ -176,26 +209,45 @@ class Request CCAPI_FINAL { return this->paramList.front(); } } + // 'getTimeSent' only works in C++. For other languages, please use 'getTimeSentISO'. TimePoint getTimeSent() const { return timeSent; } + std::string getTimeSentISO() const { return UtilTime::getISOTimestamp(timeSent); } + std::pair getTimeSentPair() const { return UtilTime::divide(timeSent); } + void setTimeSent(TimePoint timeSent) { this->timeSent = timeSent; } + int getIndex() const { return index; } + const std::string& getLocalIpAddress() const { return localIpAddress; } + const std::string& getBaseUrl() const { return baseUrl; } + const std::string& getHost() const { return host; } + const std::string& getPort() const { return port; } + + void setExchange(const std::string& exchange) { this->exchange = exchange; } + + void setInstrument(const std::string& instrument) { this->instrument = instrument; } + void setIndex(int index) { this->index = index; } + void setCredential(const std::map& credential) { this->credential = credential; } + void setCorrelationId(const std::string& correlationId) { this->correlationId = correlationId; } - void setSecondaryCorrelationId(const std::string& secondaryCorrelationId) { this->secondaryCorrelationId = secondaryCorrelationId; } + void setMarginType(const std::string& marginType) { this->marginType = marginType; } + void setLocalIpAddress(const std::string& localIpAddress) { this->localIpAddress = localIpAddress; } + void setBaseUrl(const std::string& baseUrl) { this->baseUrl = baseUrl; this->setBaseUrlParts(); } + void setBaseUrlParts() { auto splitted1 = UtilString::split(this->baseUrl, "://"); if (splitted1.size() >= 2) { @@ -212,20 +264,51 @@ class Request CCAPI_FINAL { } } } + + std::string generateNextClientOrderId() { + static int64_t lastClientOrderIdUnixTimestampInSeconds = 0; + static int64_t lastClientOrderIdSequenceNumber = 0; + + const auto& now = UtilTime::now(); + const auto& unixTimestampInSeconds = std::chrono::duration_cast(now.time_since_epoch()).count(); + + if (lastClientOrderIdUnixTimestampInSeconds != unixTimestampInSeconds) { + lastClientOrderIdUnixTimestampInSeconds = unixTimestampInSeconds; + lastClientOrderIdSequenceNumber = 0; + } else { + ++lastClientOrderIdSequenceNumber; + } + + std::string nextClientOrderId; + if (this->exchange == CCAPI_EXCHANGE_NAME_BINANCE) { + nextClientOrderId += "x-"; + nextClientOrderId += CCAPI_BINANCE_API_LINK_ID; + nextClientOrderId += "-"; + } else if (this->exchange == CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES || this->exchange == CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES) { + nextClientOrderId += "x-"; + nextClientOrderId += CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID; + nextClientOrderId += "-"; + } else if (this->exchange == CCAPI_EXCHANGE_NAME_HUOBI) { + nextClientOrderId += CCAPI_HTX_BROKER_ID; + nextClientOrderId += "-"; + } + nextClientOrderId += std::to_string(lastClientOrderIdUnixTimestampInSeconds); + nextClientOrderId += UtilString::leftPadTo(std::to_string(lastClientOrderIdSequenceNumber), CCAPI_EM_CLIENT_ORDER_ID_SEQUENCE_NUMBER_PAD_TO_LENGTH, '0'); + return nextClientOrderId; + } #ifndef CCAPI_EXPOSE_INTERNAL private: #endif + Operation operation{Operation::UNKNOWN}; std::string exchange; std::string marginType; std::string instrument; std::string serviceName; std::string correlationId; - std::string secondaryCorrelationId; - std::vector > paramList; + std::vector> paramList; std::map credential; - Operation operation; - std::vector > > paramListFix; + std::vector>> paramListFix; TimePoint timeSent{std::chrono::seconds{0}}; int index{}; std::string localIpAddress; @@ -233,5 +316,6 @@ class Request CCAPI_FINAL { std::string host; std::string port; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_REQUEST_H_ diff --git a/linux/include/ccapi_cpp/ccapi_session.h b/linux/include/ccapi_cpp/ccapi_session.h index d77557232..3ac0dba2c 100644 --- a/linux/include/ccapi_cpp/ccapi_session.h +++ b/linux/include/ccapi_cpp/ccapi_session.h @@ -210,18 +210,21 @@ // start: enable exchanges for FIX #ifdef CCAPI_ENABLE_SERVICE_FIX -#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE -#include "ccapi_cpp/service/ccapi_fix_service_coinbase.h" -#endif -#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI -#include "ccapi_cpp/service/ccapi_fix_service_gemini.h" -#endif -#ifdef CCAPI_ENABLE_EXCHANGE_FTX -#include "ccapi_cpp/service/ccapi_fix_service_ftx.h" -#endif -#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US -#include "ccapi_cpp/service/ccapi_fix_service_ftx_us.h" +#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE +#include "ccapi_cpp/service/ccapi_fix_service_binance.h" #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_COINBASE +// #include "ccapi_cpp/service/ccapi_fix_service_coinbase.h" +// #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_GEMINI +// #include "ccapi_cpp/service/ccapi_fix_service_gemini.h" +// #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_FTX +// #include "ccapi_cpp/service/ccapi_fix_service_ftx.h" +// #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_FTX_US +// #include "ccapi_cpp/service/ccapi_fix_service_ftx_us.h" +// #endif // #ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT // #include "ccapi_cpp/service/ccapi_fix_service_deribit.h" // #endif @@ -242,7 +245,9 @@ #include "ccapi_cpp/service/ccapi_service.h" #include "ccapi_cpp/service/ccapi_service_context.h" using steady_timer = boost::asio::steady_timer; + namespace ccapi { + /** * This class provides a consumer session for making requests and subscriptions for services. Sessions manage access to services either by requests and * responses or subscriptions. A Session can dispatch events and replies in either an immediate or batching mode. The mode of a Session is determined when it is @@ -253,6 +258,7 @@ class Session { public: Session(const Session&) = delete; Session& operator=(const Session&) = delete; + Session(const SessionOptions& sessionOptions = SessionOptions(), const BtsSessionOptions &btsSessionOptions = BtsSessionOptions(), const SessionConfigs& sessionConfigs = SessionConfigs(), EventHandler* eventHandler = nullptr, EventDispatcher* eventDispatcher = nullptr #ifndef SWIG @@ -264,9 +270,7 @@ class Session { btsSessionOptions(btsSessionOptions), sessionConfigs(sessionConfigs), eventHandler(eventHandler), -#ifndef CCAPI_USE_SINGLE_THREAD eventDispatcher(eventDispatcher), -#endif eventQueue(sessionOptions.maxEventQueueSize) #ifndef SWIG , @@ -275,351 +279,337 @@ class Session { { if (!this->serviceContextPtr) { this->serviceContextPtr = new ServiceContext(); + this->useInternalServiceContextPtr = true; } CCAPI_LOGGER_FUNCTION_ENTER; -#ifndef CCAPI_USE_SINGLE_THREAD - if (this->eventHandler) { - if (!this->eventDispatcher) { - this->eventDispatcher = new EventDispatcher(); - this->useInternalEventDispatcher = true; - } - } else { - if (this->eventDispatcher) { - throw std::runtime_error("undefined behavior"); - } + if (!this->eventHandler && this->eventDispatcher) { + throw std::runtime_error("eventHandler is needed when eventDispatcher is provided"); } -#endif this->start(); CCAPI_LOGGER_FUNCTION_EXIT; } + virtual ~Session() { CCAPI_LOGGER_FUNCTION_ENTER; -#ifndef CCAPI_USE_SINGLE_THREAD - if (this->useInternalEventDispatcher) { - delete this->eventDispatcher; + this->delayTimerByIdMap.clear(); + this->serviceByServiceNameExchangeMap.clear(); + if (this->useInternalServiceContextPtr) { + delete this->serviceContextPtr; } -#endif - delete this->serviceContextPtr; CCAPI_LOGGER_FUNCTION_EXIT; } + virtual void start() { CCAPI_LOGGER_FUNCTION_ENTER; - std::thread t([this]() { this->serviceContextPtr->start(); }); - this->t = std::move(t); - this->internalEventHandler = std::bind(&Session::onEvent, this, std::placeholders::_1, std::placeholders::_2); + if (this->useInternalServiceContextPtr) { + this->serviceContextPtr->start(); + } + this->onEventFunc = std::bind(&Session::onEvent, this, std::placeholders::_1, std::placeholders::_2); #ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA #ifdef CCAPI_ENABLE_EXCHANGE_COINBASE if (this->btsSessionOptions.enableCoinbase()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_COINBASE] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_GEMINI this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_GEMINI] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KRAKEN] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITSTAMP] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITFINEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITMEX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITMEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US if (this->btsSessionOptions.enableBinanceUs()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE_US] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE if (this->btsSessionOptions.enableBinance()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES if (this->btsSessionOptions.enableBinanceUsdsFutures()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES if (this->btsSessionOptions.enableBinanceCoinFutures()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_OKX if (this->btsSessionOptions.enableOkx()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_OKX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_ERISX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ERISX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KUCOIN] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_FTX - this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_FTX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + if (this->btsSessionOptions.enableFtx()) { + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_FTX] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); + } #endif #ifdef CCAPI_ENABLE_EXCHANGE_FTX_US this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_FTX_US] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT if (this->btsSessionOptions.enableDeribit()) { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_DERIBIT] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); } #endif #ifdef CCAPI_ENABLE_EXCHANGE_GATEIO this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_GATEIO] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_CRYPTOCOM] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BYBIT] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ASCENDEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITGET this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITGET] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITGET_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITMART this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITMART] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_MEXC this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_MEXC] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_MEXC_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_WHITEBIT] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #endif #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT #ifdef CCAPI_ENABLE_EXCHANGE_COINBASE - if (this->btsSessionOptions.enableCoinbase()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_COINBASE] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_COINBASE] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_GEMINI this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_GEMINI] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KRAKEN] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITSTAMP] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITFINEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITMEX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITMEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US - if (this->btsSessionOptions.enableBinanceUs()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_US] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_US] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE - if (this->btsSessionOptions.enableBinance()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif // #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_MARGIN // this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_MARGIN] = -// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); // #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES - if (this->btsSessionOptions.enableBinanceUsdsFutures()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES - if (this->btsSessionOptions.enableBinanceCoinFutures()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_OKX - if (this->btsSessionOptions.enableOkx()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_OKX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_OKX] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_ERISX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ERISX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KUCOIN] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_FTX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_FTX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_FTX_US this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_FTX_US] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT - if (this->btsSessionOptions.enableDeribit()) { - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_DERIBIT] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); - } + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_DERIBIT] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_GATEIO this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_GATEIO] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_CRYPTOCOM] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BYBIT] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ASCENDEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITGET this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITGET] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITGET_FUTURES] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BITMART this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITMART] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_MEXC this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_MEXC] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif // #ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES // this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_MEXC_FUTURES] = -// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); // #endif // #ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT // this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_WHITEBIT] = -// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); // #endif #endif #ifdef CCAPI_ENABLE_SERVICE_FIX -#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE - this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_COINBASE] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE + this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_BINANCE] = + std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_COINBASE +// this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_COINBASE] = +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif // #ifdef CCAPI_ENABLE_EXCHANGE_GEMINI // this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_GEMINI] = -// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_FTX +// this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX] = +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_FTX_US +// this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX_US] = +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); // #endif -#ifdef CCAPI_ENABLE_EXCHANGE_FTX - this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); -#endif -#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US - this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX_US] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); -#endif // #ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT // this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_DERIBIT] = -// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// std::make_shared(this->onEventFunc, sessionOptions, sessionConfigs, this->serviceContextPtr); // #endif #endif for (const auto& x : this->serviceByServiceNameExchangeMap) { @@ -631,28 +621,63 @@ class Session { } CCAPI_LOGGER_FUNCTION_EXIT; } + virtual void stop() { -#ifndef CCAPI_USE_SINGLE_THREAD - if (this->useInternalEventDispatcher) { - this->eventDispatcher->stop(); - } -#endif - for (const auto& x : this->serviceByServiceNameExchangeMap) { - for (const auto& y : x.second) { - y.second->stop(); + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this]() { + for (const auto& [_, delayTimer] : this->delayTimerByIdMap) { + delayTimer->cancel(); } + if (heartbeatTimerPtr) { + heartbeatTimerPtr->cancel(); + } + for (const auto& x : this->serviceByServiceNameExchangeMap) { + for (const auto& y : x.second) { + y.second->stop(); + } + } + }); + + if (this->useInternalServiceContextPtr) { + this->serviceContextPtr->stop(); } - this->serviceContextPtr->stop(); - this->t.join(); } + + typedef boost::system::error_code ErrorCode; + + virtual void setHeartbeatTimer(long heartbeatIntervalMilliseconds) { + auto timerPtr = + std::make_shared(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(heartbeatIntervalMilliseconds)); + timerPtr->async_wait([this, heartbeatIntervalMilliseconds](ErrorCode const& ec) { + if (ec) { + if (ec != boost::asio::error::operation_aborted) { + std::string errorMessage = "heartbeat timer error: " + ec.message(); + CCAPI_LOGGER_ERROR(errorMessage); + this->onError(Event::Type::SESSION_STATUS, Message::Type::GENERIC_ERROR, errorMessage); + } + } else { + Event event; + event.setType(Event::Type::HEARTBEAT); + this->onEvent(event, nullptr); + this->setHeartbeatTimer(heartbeatIntervalMilliseconds); + } + }); + this->heartbeatTimerPtr = timerPtr; + } + virtual void subscribe(Subscription& subscription) { std::vector subscriptionList; subscriptionList.push_back(subscription); this->subscribe(subscriptionList); } + virtual void subscribe(std::vector& subscriptionList) { CCAPI_LOGGER_FUNCTION_ENTER; for (auto& subscription : subscriptionList) { + CCAPI_LOGGER_TRACE("subscription = " + toString(subscription)); + if (subscription.getField() == CCAPI_HEARTBEAT) { + this->setHeartbeatTimer(std::stol(subscription.getOptionMap().at(CCAPI_HEARTBEAT_INTERVAL_MILLISECONDS))); + continue; + } auto exchange = subscription.getExchange(); if (exchange == CCAPI_EXCHANGE_NAME_BYBIT) { auto instrumentType = subscription.getInstrumentType(); @@ -680,8 +705,11 @@ class Session { subscription.setInstrumentType(instrumentType); } } - std::map > subscriptionListByServiceNameMap; + std::map> subscriptionListByServiceNameMap; for (const auto& subscription : subscriptionList) { + if (subscription.getField() == CCAPI_HEARTBEAT) { + continue; + } auto serviceName = subscription.getServiceName(); subscriptionListByServiceNameMap[serviceName].push_back(subscription); } @@ -690,7 +718,7 @@ class Session { auto subscriptionList = x.second; if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, - "please enable service: " + serviceName + ", and the exchanges that you want"); + "please enable service: " + serviceName + ", and the exchanges that you want for subscriptionList " + toString(subscriptionList)); return; } if (serviceName == CCAPI_MARKET_DATA) { @@ -715,7 +743,7 @@ class Session { "unsupported exchange fields: " + toString(unsupportedExchangeFieldSet)); return; } - std::map > subscriptionListByExchangeMap; + std::map> subscriptionListByExchangeMap; for (const auto& subscription : subscriptionList) { auto exchange = subscription.getExchange(); subscriptionListByExchangeMap[exchange].push_back(subscription); @@ -724,15 +752,16 @@ class Session { for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) { auto exchange = subscriptionListByExchange.first; auto subscriptionList = subscriptionListByExchange.second; - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map>& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "please enable exchange: " + exchange); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, + "please enable exchange: " + exchange + " for subscriptionList " + toString(subscriptionList)); return; } serviceByExchangeMap.at(exchange)->subscribe(subscriptionList); } - } else if (serviceName == CCAPI_EXECUTION_MANAGEMENT) { - std::map > subscriptionListByExchangeMap; + } else if (serviceName == CCAPI_EXECUTION_MANAGEMENT || serviceName == CCAPI_FIX) { + std::map> subscriptionListByExchangeMap; for (const auto& subscription : subscriptionList) { auto exchange = subscription.getExchange(); subscriptionListByExchangeMap[exchange].push_back(subscription); @@ -741,9 +770,10 @@ class Session { for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) { auto exchange = subscriptionListByExchange.first; auto subscriptionList = subscriptionListByExchange.second; - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map>& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "please enable exchange: " + exchange); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, + "please enable exchange: " + exchange + " for subscriptionList " + toString(subscriptionList)); return; } serviceByExchangeMap.at(exchange)->subscribe(subscriptionList); @@ -752,55 +782,53 @@ class Session { } CCAPI_LOGGER_FUNCTION_EXIT; } - virtual void subscribeByFix(Subscription& subscription) { - auto serviceName = subscription.getServiceName(); - CCAPI_LOGGER_DEBUG("serviceName = " + serviceName); - if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) { - this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want"); - return; - } - auto exchange = subscription.getExchange(); - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); - if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { - this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange); - return; - } - serviceByExchangeMap.at(exchange)->subscribeByFix(subscription); - } - virtual void subscribeByFix(std::vector& subscriptionList) { - for (auto& x : subscriptionList) { - this->subscribeByFix(x); - } - } + + // virtual void subscribe(Subscription& subscription) { + // auto serviceName = subscription.getServiceName(); + // CCAPI_LOGGER_DEBUG("serviceName = " + serviceName); + // if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) { + // this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, + // "please enable service: " + serviceName + ", and the exchanges that you want for subscription " + toString(subscription)); + // return; + // } + // auto exchange = subscription.getExchange(); + // std::map>& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + // if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { + // this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange+" for subscription " + + // toString(subscription)); return; + // } + // serviceByExchangeMap.at(exchange)->subscribe(subscription); + // } + + // virtual void subscribe(std::vector& subscriptionList) { + // for (auto& x : subscriptionList) { + // this->subscribe(x); + // } + // } + virtual void onEvent(Event& event, Queue* eventQueue) { CCAPI_LOGGER_FUNCTION_ENTER; - CCAPI_LOGGER_TRACE("event = " + toString(event)); + CCAPI_LOGGER_DEBUG("event = " + toString(event)); if (eventQueue) { eventQueue->pushBack(std::move(event)); } else { if (this->eventHandler) { CCAPI_LOGGER_TRACE("handle event in immediate mode"); -#ifdef CCAPI_USE_SINGLE_THREAD - bool shouldContinue = true; - try { - this->eventHandler->processEvent(event, this); - } catch (const std::runtime_error& e) { - CCAPI_LOGGER_ERROR(e.what()); - } -#else - this->eventDispatcher->dispatch([that = this, event = std::move(event)] { - bool shouldContinue = true; + if (!this->eventDispatcher) { try { - shouldContinue = that->eventHandler->processEvent(event, that); + this->eventHandler->processEvent(event, this); } catch (const std::runtime_error& e) { CCAPI_LOGGER_ERROR(e.what()); } - if (!shouldContinue) { - CCAPI_LOGGER_DEBUG("about to pause the event dispatcher"); - that->eventDispatcher->pause(); - } - }); -#endif + } else { + this->eventDispatcher->dispatch([that = this, event = std::move(event)] { + try { + that->eventHandler->processEvent(event, that); + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(e.what()); + } + }); + } } else { CCAPI_LOGGER_TRACE("handle event in batching mode"); this->eventQueue.pushBack(std::move(event)); @@ -808,87 +836,93 @@ class Session { } CCAPI_LOGGER_FUNCTION_EXIT; } - virtual void sendRequestByFix(Request& request) { + + virtual void sendRequestByFix(const std::string& fixOrderEntrySubscriptionCorrelationId, Request& request) { CCAPI_LOGGER_FUNCTION_ENTER; auto serviceName = request.getServiceName(); CCAPI_LOGGER_DEBUG("serviceName = " + serviceName); if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) { - this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want"); + this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, + "please enable service: " + serviceName + ", and the exchanges that you want for request " + toString(request)); return; } - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map>& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); auto exchange = request.getExchange(); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange); return; } - std::shared_ptr& servicePtr = serviceByExchangeMap.at(exchange); + std::shared_ptr servicePtr = serviceByExchangeMap.at(exchange); auto now = UtilTime::now(); - servicePtr->sendRequestByFix(request, now); + servicePtr->sendRequestByFix(fixOrderEntrySubscriptionCorrelationId, request, now); CCAPI_LOGGER_FUNCTION_EXIT; } - virtual void sendRequestByFix(std::vector& requestList) { + + virtual void sendRequestByFix(const std::string& fixOrderEntrySubscriptionCorrelationId, std::vector& requestList) { for (auto& x : requestList) { - this->sendRequestByFix(x); + this->sendRequestByFix(fixOrderEntrySubscriptionCorrelationId, x); } } - virtual void sendRequestByWebsocket(Request& request) { + + virtual void sendRequestByWebsocket(const std::string& websocketOrderEntrySubscriptionCorrelationId, Request& request) { CCAPI_LOGGER_FUNCTION_ENTER; - auto serviceName = request.getServiceName(); + const auto& serviceName = request.getServiceName(); CCAPI_LOGGER_DEBUG("serviceName = " + serviceName); if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) { - this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want"); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, + "please enable service: " + serviceName + ", and the exchanges that you want for websocketOrderEntrySubscriptionCorrelationId " + + toString(websocketOrderEntrySubscriptionCorrelationId) + ", request = " + toString(request)); return; } - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); - auto exchange = request.getExchange(); + const std::map>& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + const auto& exchange = request.getExchange(); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange); return; } - std::shared_ptr& servicePtr = serviceByExchangeMap.at(exchange); - auto now = UtilTime::now(); - servicePtr->sendRequestByWebsocket(request, now); + std::shared_ptr servicePtr = serviceByExchangeMap.at(exchange); + const auto& now = UtilTime::now(); + servicePtr->sendRequestByWebsocket(websocketOrderEntrySubscriptionCorrelationId, request, now); CCAPI_LOGGER_FUNCTION_EXIT; } - virtual void sendRequestByWebsocket(std::vector& requestList) { + + virtual void sendRequestByWebsocket(const std::string& websocketOrderEntrySubscriptionCorrelationId, std::vector& requestList) { for (auto& x : requestList) { - this->sendRequestByWebsocket(x); + this->sendRequestByWebsocket(websocketOrderEntrySubscriptionCorrelationId, x); } } + virtual void sendRequest(Request& request, Queue* eventQueuePtr = nullptr, long delayMilliseconds = 0) { CCAPI_LOGGER_FUNCTION_ENTER; std::vector requestList({request}); this->sendRequest(requestList, eventQueuePtr, delayMilliseconds); CCAPI_LOGGER_FUNCTION_EXIT; } + virtual void sendRequest(std::vector& requestList, Queue* eventQueuePtr = nullptr, long delayMilliseconds = 0) { CCAPI_LOGGER_FUNCTION_ENTER; - std::vector > > futurePtrList; + std::vector>> futurePtrList; // std::set serviceNameExchangeSet; int i = 0; for (auto& request : requestList) { request.setIndex(i); - auto serviceName = request.getServiceName(); + const auto& serviceName = request.getServiceName(); CCAPI_LOGGER_DEBUG("serviceName = " + serviceName); if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, - "please enable service: " + serviceName + ", and the exchanges that you want", eventQueuePtr); + "please enable service: " + serviceName + ", and the exchanges that you want for request " + toString(request), eventQueuePtr); return; } - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); - auto exchange = request.getExchange(); + std::map>& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + const auto& exchange = request.getExchange(); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { - this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange, eventQueuePtr); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange + " for request " + toString(request), + eventQueuePtr); return; } - std::shared_ptr& servicePtr = serviceByExchangeMap.at(exchange); - std::string key = serviceName + exchange; - // if (eventQueuePtr && serviceNameExchangeSet.find(key) == serviceNameExchangeSet.end()) { - // // servicePtr->setEventHandler(std::bind(&Session::onEvent, this, std::placeholders::_1, eventQueuePtr)); - // serviceNameExchangeSet.insert(key); - // } - auto now = UtilTime::now(); + std::shared_ptr servicePtr = serviceByExchangeMap.at(exchange); + const std::string& key = serviceName + exchange; + const auto& now = UtilTime::now(); auto futurePtr = servicePtr->sendRequest(request, !!eventQueuePtr, now, delayMilliseconds, eventQueuePtr); if (eventQueuePtr) { futurePtrList.push_back(futurePtr); @@ -904,7 +938,9 @@ class Session { } CCAPI_LOGGER_FUNCTION_EXIT; } + virtual Queue& getEventQueue() { return eventQueue; } + virtual void onError(const Event::Type eventType, const Message::Type messageType, const std::string& errorMessage, Queue* eventQueuePtr = nullptr) { CCAPI_LOGGER_ERROR("errorMessage = " + errorMessage); Event event; @@ -924,44 +960,51 @@ class Session { virtual void setImmediate(std::function successHandler) { boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, successHandler]() { if (this->eventHandler) { -#ifdef CCAPI_USE_SINGLE_THREAD - successHandler(); -#else - this->eventDispatcher->dispatch([successHandler] { - successHandler(); - }); -#endif + if (!this->eventDispatcher) { + successHandler(); + } else { + this->eventDispatcher->dispatch([successHandler] { successHandler(); }); + } } }); } + virtual void setTimer(const std::string& id, long delayMilliseconds, std::function errorHandler, std::function successHandler) { boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id, delayMilliseconds, errorHandler, successHandler]() { - std::shared_ptr timerPtr( - new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, boost::asio::chrono::milliseconds(delayMilliseconds))); + auto timerPtr = std::make_shared(*this->serviceContextPtr->ioContextPtr, boost::asio::chrono::milliseconds(delayMilliseconds)); timerPtr->async_wait([this, id, errorHandler, successHandler](const boost::system::error_code& ec) { if (this->eventHandler) { -#ifdef CCAPI_USE_SINGLE_THREAD - if (ec) { - errorHandler(ec); - } else { - successHandler(); - } -#else - this->eventDispatcher->dispatch([ec, errorHandler, successHandler] { + if (!this->eventDispatcher) { if (ec) { - errorHandler(ec); + if (errorHandler) { + errorHandler(ec); + } } else { - successHandler(); + if (successHandler) { + successHandler(); + } } - }); -#endif + } else { + this->eventDispatcher->dispatch([ec, errorHandler, successHandler] { + if (ec) { + if (errorHandler) { + errorHandler(ec); + } + } else { + if (successHandler) { + successHandler(); + } + } + }); + } } this->delayTimerByIdMap.erase(id); }); this->delayTimerByIdMap[id] = timerPtr; }); } + virtual void cancelTimer(const std::string& id) { boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id]() { if (this->delayTimerByIdMap.find(id) != this->delayTimerByIdMap.end()) { @@ -970,6 +1013,7 @@ class Session { } }); } + void purgeHttpConnectionPool(const std::string& serviceName = "", const std::string& exchangeName = "") { for (const auto& x : this->serviceByServiceNameExchangeMap) { if (serviceName.empty() || serviceName == x.first) { @@ -981,6 +1025,7 @@ class Session { } } } + void forceCloseWebsocketConnections(const std::string& serviceName = "", const std::string& exchangeName = "") { for (const auto& x : this->serviceByServiceNameExchangeMap) { if (serviceName.empty() || serviceName == x.first) { @@ -1001,16 +1046,15 @@ class Session { BtsSessionOptions btsSessionOptions; SessionConfigs sessionConfigs; EventHandler* eventHandler{nullptr}; -#ifndef CCAPI_USE_SINGLE_THREAD EventDispatcher* eventDispatcher{nullptr}; - bool useInternalEventDispatcher{}; -#endif - ServiceContext* serviceContextPtr{nullptr}; - std::map > > serviceByServiceNameExchangeMap; - std::thread t; + std::map>> serviceByServiceNameExchangeMap; Queue eventQueue; - std::function* eventQueue)> internalEventHandler; - std::map > delayTimerByIdMap; + ServiceContext* serviceContextPtr{nullptr}; + bool useInternalServiceContextPtr{}; + std::function* eventQueue)> onEventFunc; + std::map> delayTimerByIdMap; + std::shared_ptr heartbeatTimerPtr{nullptr}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_H_ diff --git a/linux/include/ccapi_cpp/ccapi_session_configs.h b/linux/include/ccapi_cpp/ccapi_session_configs.h index ca66bd3f8..737d5675c 100644 --- a/linux/include/ccapi_cpp/ccapi_session_configs.h +++ b/linux/include/ccapi_cpp/ccapi_session_configs.h @@ -8,28 +8,47 @@ #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * This class contains the configs when creating a session. It loads and maintains exchange information. Most of the values shouldn't be changed. To use * non-default configs on a Session, create a SessionConfigs instance and set the required configs and then supply it when creating a Session. */ -class SessionConfigs CCAPI_FINAL { +class SessionConfigs { public: explicit SessionConfigs(std::map credential = {}) : credential(credential) { this->updateExchange(); this->updateExchangeRest(); this->initializUrlFixBase(); } - const std::map >& getExchangeFieldMap() const { return exchangeFieldMap; } - const std::map >& getExchangeFieldWebsocketChannelMap() const { return exchangeFieldWebsocketChannelMap; } + + const std::map>& getExchangeFieldMap() const { return exchangeFieldMap; } + + const std::map>& getExchangeFieldWebsocketChannelMap() const { return exchangeFieldWebsocketChannelMap; } + const std::map& getUrlWebsocketBase() const { return urlWebsocketBase; } + + const std::map& getUrlWebsocketOrderEntryBase() const { return urlWebsocketOrderEntryBase; } + const std::map& getUrlRestBase() const { return urlRestBase; } + const std::map& getUrlFixBase() const { return urlFixBase; } + + const std::map& getUrlFixMarketDataBase() const { return urlFixMarketDataBase; } + const std::map& getInitialSequenceByExchangeMap() const { return initialSequenceByExchangeMap; } + const std::map& getCredential() const { return credential; } + void setUrlWebsocketBase(const std::map& urlWebsocketBase) { this->urlWebsocketBase = urlWebsocketBase; } + void setUrlRestBase(const std::map& urlRestBase) { this->urlRestBase = urlRestBase; } + void setUrlFixBase(const std::map& urlFixBase) { this->urlFixBase = urlFixBase; } + + void setUrlFixMarketDataBase(const std::map& urlFixMarketDataBase) { this->urlFixMarketDataBase = urlFixMarketDataBase; } + void setCredential(const std::map& credential) { this->credential = credential; } #ifndef CCAPI_EXPOSE_INTERNAL @@ -79,6 +98,7 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE}, }; std::map fieldWebsocketChannelMapBinanceUsdsFutures = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_TRADE}, {CCAPI_AGG_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE}, {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH}, {CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE}, @@ -351,8 +371,16 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_MEXC_FUTURES, CCAPI_MEXC_FUTURES_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_WHITEBIT, CCAPI_WHITEBIT_URL_WS_BASE}, }; + this->urlWebsocketOrderEntryBase = { + {CCAPI_EXCHANGE_NAME_OKX, CCAPI_OKX_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_WS_ORDER_ENTRY_BASE}, + {CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_WS_ORDER_ENTRY_BASE}, + {CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_WS_ORDER_ENTRY_BASE}, + {CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_WS_ORDER_ENTRY_BASE}, + }; this->initialSequenceByExchangeMap = {{CCAPI_EXCHANGE_NAME_GEMINI, 0}, {CCAPI_EXCHANGE_NAME_BITFINEX, 1}}; } + void updateExchangeRest() { this->urlRestBase = { {CCAPI_EXCHANGE_NAME_COINBASE, CCAPI_COINBASE_URL_REST_BASE}, @@ -390,21 +418,26 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_WHITEBIT, CCAPI_WHITEBIT_URL_REST_BASE}, }; } + void initializUrlFixBase() { this->urlFixBase = { - {CCAPI_EXCHANGE_NAME_COINBASE, CCAPI_COINBASE_URL_FIX_BASE}, - {CCAPI_EXCHANGE_NAME_FTX, CCAPI_FTX_URL_FIX_BASE}, - {CCAPI_EXCHANGE_NAME_FTX_US, CCAPI_FTX_US_URL_FIX_BASE}, - {CCAPI_EXCHANGE_NAME_DERIBIT, CCAPI_DERIBIT_URL_FIX_BASE}, + {CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_FIX_BASE}, + }; + this->urlFixMarketDataBase = { + {CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_FIX_MARKET_DATA_BASE}, }; } - std::map > exchangeFieldMap; - std::map > exchangeFieldWebsocketChannelMap; + + std::map> exchangeFieldMap; + std::map> exchangeFieldWebsocketChannelMap; std::map urlWebsocketBase; + std::map urlWebsocketOrderEntryBase; std::map urlRestBase; std::map urlFixBase; + std::map urlFixMarketDataBase; std::map initialSequenceByExchangeMap; std::map credential; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_CONFIGS_H_ diff --git a/linux/include/ccapi_cpp/ccapi_session_options.h b/linux/include/ccapi_cpp/ccapi_session_options.h index 1281a2f97..ffec80108 100644 --- a/linux/include/ccapi_cpp/ccapi_session_options.h +++ b/linux/include/ccapi_cpp/ccapi_session_options.h @@ -1,15 +1,18 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_ #define INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_ +#include #include #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * This class contains the options which the user can specify when creating a session. To use non-default options on a Session, create a SessionOptions instance * and set the required options and then supply it when creating a Session. */ -class SessionOptions CCAPI_FINAL { +class SessionOptions { public: std::string toString() const { std::string output = "SessionOptions [enableCheckSequence = " + ccapi::toString(enableCheckSequence) + @@ -29,9 +32,12 @@ class SessionOptions CCAPI_FINAL { ", httpRequestTimeoutMilliseconds = " + ccapi::toString(httpRequestTimeoutMilliseconds) + ", httpConnectionPoolMaxSize = " + ccapi::toString(httpConnectionPoolMaxSize) + ", httpConnectionKeepAliveTimeoutSeconds = " + ccapi::toString(httpConnectionKeepAliveTimeoutSeconds) + - ", enableOneHttpConnectionPerRequest = " + ccapi::toString(enableOneHttpConnectionPerRequest) + "]"; + ", enableOneHttpConnectionPerRequest = " + ccapi::toString(enableOneHttpConnectionPerRequest) + + ", websocketConnectTimeoutMilliseconds = " + ccapi::toString(websocketConnectTimeoutMilliseconds) + + ", fixConnectTimeoutMilliseconds = " + ccapi::toString(fixConnectTimeoutMilliseconds) + "]"; return output; } + // long warnLateEventMaxMilliseconds{}; // used to print a warning log message if en event arrives late bool enableCheckSequence{}; // used to check sequence number discontinuity bool enableCheckOrderBookChecksum{}; // used to check order book checksum @@ -49,14 +55,13 @@ class SessionOptions CCAPI_FINAL { int httpMaxNumRetry{1}; int httpMaxNumRedirect{1}; long httpRequestTimeoutMilliseconds{10000}; - int httpConnectionPoolMaxSize{1}; // used to set the maximal number of http connections to be kept in the pool (connections in the pool are idle) + int httpConnectionPoolMaxSize{2}; // used to set the maximal number of http connections to be kept in the pool (connections in the pool are idle) long httpConnectionKeepAliveTimeoutSeconds{ 10}; // used to remove a http connection from the http connection pool if it has stayed idle for at least this amount of time bool enableOneHttpConnectionPerRequest{}; // create a new http connection for each request -#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP -#else long websocketConnectTimeoutMilliseconds{10000}; -#endif + long fixConnectTimeoutMilliseconds{10000}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_ diff --git a/linux/include/ccapi_cpp/ccapi_subscription.h b/linux/include/ccapi_cpp/ccapi_subscription.h index e2c14d7c8..5eb8fff01 100644 --- a/linux/include/ccapi_cpp/ccapi_subscription.h +++ b/linux/include/ccapi_cpp/ccapi_subscription.h @@ -6,17 +6,18 @@ #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** - * A single subscription. A 'Subscription' is used when calling 'Session::subscribe()' or 'Session::subscribeByFix'. Subscription objects are created using + * A single subscription. A 'Subscription' is used when calling 'Session::subscribe()' or 'Session::subscribe'. Subscription objects are created using * Subscription constructors. A correlation id can be used as the unique identifier to tag all data associated with this subscription. */ -class Subscription CCAPI_FINAL { +class Subscription { public: - Subscription() {} - Subscription(std::string exchange, std::string instrument, std::string field, std::string options = "", std::string correlationId = "", - std::map credential = {}) - : exchange(exchange), instrument(instrument), field(field), correlationId(correlationId), credential(credential) { + explicit Subscription(const std::string& exchange = "", const std::string& instrument = "", const std::string& field = "", const std::string& options = "", + const std::string& correlationId = "", const std::map& credential = {}, const std::string& proxyUrl = "") + : exchange(exchange), instrument(instrument), field(field), correlationId(correlationId), credential(credential), proxyUrl(proxyUrl) { auto originalInstrumentSet = UtilString::splitToSet(instrument, ","); std::copy_if(originalInstrumentSet.begin(), originalInstrumentSet.end(), std::inserter(this->instrumentSet, this->instrumentSet.end()), [](const std::string& value) { return !value.empty(); }); @@ -41,11 +42,12 @@ class Subscription CCAPI_FINAL { this->optionMap[optionKeyValue.at(0)] = optionKeyValue.at(1); } } - std::set executionManagementSubscriptionFieldSet = {std::string(CCAPI_EM_ORDER_UPDATE), std::string(CCAPI_EM_PRIVATE_TRADE), - std::string(CCAPI_EM_BALANCE_UPDATE), std::string(CCAPI_EM_POSITION_UPDATE)}; + std::set executionManagementSubscriptionFieldSet = {std::string(CCAPI_EM_ORDER_UPDATE), std::string(CCAPI_EM_PRIVATE_TRADE), + std::string(CCAPI_EM_PRIVATE_TRADE_LITE), std::string(CCAPI_EM_BALANCE_UPDATE), + std::string(CCAPI_EM_POSITION_UPDATE), std::string(CCAPI_EM_WEBSOCKET_ORDER_ENTRY)}; if (field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) { this->serviceName = CCAPI_MARKET_DATA; - } else if (field == CCAPI_FIX || field == CCAPI_FIX_MARKET_DATA || field == CCAPI_FIX_EXECUTION_MANAGEMENT) { + } else if (field == CCAPI_FIX || field == CCAPI_FIX_MARKET_DATA) { this->serviceName = CCAPI_FIX; } else if (std::includes(executionManagementSubscriptionFieldSet.begin(), executionManagementSubscriptionFieldSet.end(), this->fieldSet.begin(), this->fieldSet.end())) { @@ -58,6 +60,7 @@ class Subscription CCAPI_FINAL { this->correlationId = UtilString::generateRandomString(CCAPI_CORRELATION_ID_GENERATED_LENGTH); } } + std::string toString() const { std::map shortCredential; for (const auto& x : credential) { @@ -65,21 +68,35 @@ class Subscription CCAPI_FINAL { } std::string output = "Subscription [exchange = " + exchange + ", marginType = " + marginType + ", instrumentType = " + instrumentType + ", instrument = " + instrument + ", field = " + field + ", optionMap = " + ccapi::toString(optionMap) + - ", correlationId = " + correlationId + ", credential = " + ccapi::toString(shortCredential) + ", serviceName = " + serviceName + - ", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]"; + ", correlationId = " + correlationId + ", credential = " + ccapi::toString(shortCredential) + ", proxyUrl = " + proxyUrl + + ", serviceName = " + serviceName + ", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]"; return output; } + const std::string& getCorrelationId() const { return correlationId; } + const std::string& getExchange() const { return exchange; } + const std::string& getInstrument() const { return instrument; } + const std::string& getInstrumentType() const { return instrumentType; } + const std::string& getField() const { return field; } + const std::string& getRawOptions() const { return rawOptions; } + const std::map& getOptionMap() const { return optionMap; } + const std::map& getCredential() const { return credential; } + + const std::string& getProxyUrl() const { return proxyUrl; } + const std::string& getServiceName() const { return serviceName; } + const std::set& getInstrumentSet() const { return instrumentSet; } + const std::set& getFieldSet() const { return fieldSet; } + const std::string getSerializedOptions() const { std::string output; if (this->rawOptions.empty()) { @@ -98,15 +115,32 @@ class Subscription CCAPI_FINAL { } return output; } + const std::string getSerializedCredential() const { return ccapi::toString(this->credential); } + // 'getTimeSent' only works in C++. For other languages, please use 'getTimeSentISO'. TimePoint getTimeSent() const { return timeSent; } + std::string getTimeSentISO() const { return UtilTime::getISOTimestamp(timeSent); } + std::pair getTimeSentPair() const { return UtilTime::divide(timeSent); } + const std::string& getMarginType() const { return marginType; } + + void setExchange(const std::string& exchange) { this->exchange = exchange; } + + void setInstrument(const std::string& instrument) { this->instrument = instrument; } + + void setField(const std::string& field) { this->field = field; } + + void setProxyUrl(const std::string& proxyUrl) { this->proxyUrl = proxyUrl; } + void setTimeSent(TimePoint timeSent) { this->timeSent = timeSent; } + void setInstrumentType(const std::string& instrumentType) { this->instrumentType = instrumentType; } + void setMarginType(const std::string& marginType) { this->marginType = marginType; } + enum class Status { UNKNOWN, SUBSCRIBING, @@ -114,6 +148,7 @@ class Subscription CCAPI_FINAL { UNSUBSCRIBING, UNSUBSCRIBED, }; + static std::string statusToString(Status status) { std::string output; switch (status) { @@ -133,7 +168,7 @@ class Subscription CCAPI_FINAL { output = "UNSUBSCRIBED"; break; default: - CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + CCAPI_LOGGER_FATAL(std::string(CCAPI_UNSUPPORTED_VALUE) + " " + std::to_string(static_cast(status))); } return output; } @@ -150,10 +185,12 @@ class Subscription CCAPI_FINAL { std::map optionMap; std::string correlationId; std::map credential; + std::string proxyUrl; std::string serviceName; std::set instrumentSet; std::set fieldSet; TimePoint timeSent{std::chrono::seconds{0}}; }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_SUBSCRIPTION_H_ diff --git a/linux/include/ccapi_cpp/ccapi_url.h b/linux/include/ccapi_cpp/ccapi_url.h index 12f6e588a..a39fdaddf 100644 --- a/linux/include/ccapi_cpp/ccapi_url.h +++ b/linux/include/ccapi_cpp/ccapi_url.h @@ -5,11 +5,13 @@ #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util_private.h" + namespace ccapi { + /** * This class represents a url. */ -class Url CCAPI_FINAL { +class Url { public: explicit Url(std::string urlStr) { std::regex ex("^(.*:)//([A-Za-z0-9\\-\\.]+)(:[0-9]+)?(.*)$"); @@ -21,12 +23,15 @@ class Url CCAPI_FINAL { this->target = std::string(what[4].first, what[4].second); } } + Url(std::string protocol, std::string host, std::string port, std::string target) : protocol(protocol), host(host), port(port), target(target) {} + std::string toString() const { std::string output = "Url [protocol = " + protocol + ", host = " + host + ", port = " + port + ", target = " + target + "]"; return output; } - static std::string urlEncode(const std::string &value) { + + static std::string urlEncode(const std::string& value) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; @@ -44,7 +49,8 @@ class Url CCAPI_FINAL { } return escaped.str(); } - static std::string urlDecode(const std::string &value) { + + static std::string urlDecode(const std::string& value) { std::string ret; char ch; int i, ii; @@ -60,17 +66,19 @@ class Url CCAPI_FINAL { } return (ret); } - static std::map convertQueryStringToMap(const std::string &input) { + + static std::map convertQueryStringToMap(const std::string& input) { std::map output; - for (const auto &x : UtilString::split(input, "&")) { + for (const auto& x : UtilString::split(input, "&")) { auto y = UtilString::split(x, "="); output.insert(std::make_pair(y.at(0), Url::urlDecode(y.at(1)))); } return output; } - static std::string convertMapToQueryString(const std::map &input) { + + static std::string convertMapToQueryString(const std::map& input) { std::string output; - for (const auto &x : input) { + for (const auto& x : input) { output += x.first; output += "="; output += x.second; @@ -81,10 +89,11 @@ class Url CCAPI_FINAL { } return output; } - static std::string convertMapToFormUrlEncoded(const std::map &input) { + + static std::string convertMapToFormUrlEncoded(const std::map& input) { std::string output; int i = 0; - for (const auto &x : input) { + for (const auto& x : input) { output += Url::urlEncode(x.first); output += "="; output += Url::urlEncode(x.second); @@ -94,18 +103,21 @@ class Url CCAPI_FINAL { } return output; } - static std::map convertFormUrlEncodedToMap(const std::string &input) { + + static std::map convertFormUrlEncodedToMap(const std::string& input) { std::map output; - for (const auto &x : UtilString::split(input, "&")) { + for (const auto& x : UtilString::split(input, "&")) { auto y = UtilString::split(x, "="); output.insert(std::make_pair(Url::urlDecode(y.at(0)), Url::urlDecode(y.at(1)))); } return output; } + std::string protocol; std::string host; std::string port; std::string target; // should be url-encoded }; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_URL_H_ diff --git a/linux/include/ccapi_cpp/ccapi_util.h b/linux/include/ccapi_cpp/ccapi_util.h index 0b0f4976f..3d0652c6e 100644 --- a/linux/include/ccapi_cpp/ccapi_util.h +++ b/linux/include/ccapi_cpp/ccapi_util.h @@ -2,7 +2,10 @@ #define INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_ #include #include + namespace ccapi { + typedef std::chrono::time_point TimePoint; + } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_ diff --git a/linux/include/ccapi_cpp/ccapi_util_private.h b/linux/include/ccapi_cpp/ccapi_util_private.h index cc8e16653..655a1d912 100644 --- a/linux/include/ccapi_cpp/ccapi_util_private.h +++ b/linux/include/ccapi_cpp/ccapi_util_private.h @@ -7,20 +7,25 @@ #include #include +#include #include #include +#include #include +#include #include #include #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -28,12 +33,19 @@ #include "ccapi_cpp/ccapi_macro.h" #include "ccapi_cpp/ccapi_util.h" #include "openssl/evp.h" +#include "openssl/pem.h" + namespace ccapi { + /** * Utilities. */ -class UtilString CCAPI_FINAL { +class UtilString { public: + static bool startsWith(const std::string& str, const std::string& prefix) { + return str.size() >= prefix.size() && std::memcmp(str.data(), prefix.data(), prefix.size()) == 0; + } + static std::string roundInputBySignificantFigure(double input, int numSignificantFigure, int roundDirection) { const auto& splitted = UtilString::split(UtilString::printDoubleScientific(input), 'e'); double a = std::stod(splitted.at(0)) * std::pow(10, numSignificantFigure - 1); @@ -55,15 +67,16 @@ class UtilString CCAPI_FINAL { output += "."; output += c.substr(c.size() + exponent); } else { -// output = std::string(-exponent - c.size() + 1, '0'); -// output += "."; -// output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "000.124" + // output = std::string(-exponent - c.size() + 1, '0'); + // output += "."; + // output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "000.124" output = "0."; output += std::string(-exponent - c.size(), '0'); - output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "0.00124" + output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "0.00124" } return output; } + static std::string replaceFirstOccurrence(std::string& s, const std::string& toReplace, const std::string& replaceWith) { std::size_t pos = s.find(toReplace); if (pos == std::string::npos) { @@ -71,6 +84,7 @@ class UtilString CCAPI_FINAL { }; return s.replace(pos, toReplace.length(), replaceWith); } + static bool endsWith(const std::string& mainStr, const std::string& toMatch) { if (mainStr.size() >= toMatch.size() && mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0) { return true; @@ -78,15 +92,18 @@ class UtilString CCAPI_FINAL { return false; } } + static std::string printDoubleScientific(double number, int precision = CCAPI_PRINT_DOUBLE_PRECISION_DEFAULT) { std::stringstream ss; ss << std::setprecision(precision) << std::scientific << number; // ss << number; return ss.str(); } + static bool isNumber(const std::string& s) { return !s.empty() && std::find_if(s.begin(), s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end(); } + // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c static std::string generateRandomString(const size_t length) { static const auto ch_set = std::vector({'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', @@ -99,6 +116,7 @@ class UtilString CCAPI_FINAL { std::generate_n(str.begin(), length, randchar); return str; } + static std::string generateUuidV4() { static std::random_device rd; static std::mt19937 gen(rd()); @@ -129,6 +147,7 @@ class UtilString CCAPI_FINAL { }; return ss.str(); } + static std::vector split(const std::string& in, char sep) { std::vector r; r.reserve(std::count(in.begin(), in.end(), sep) + 1); @@ -141,6 +160,7 @@ class UtilString CCAPI_FINAL { } } } + static std::vector split(const std::string& original, const std::string& delimiter) { std::string s = original; std::vector output; @@ -154,6 +174,7 @@ class UtilString CCAPI_FINAL { output.emplace_back(std::move(s)); return output; } + static std::set splitToSet(const std::string& original, const std::string& delimiter) { std::string s = original; std::set output; @@ -167,12 +188,13 @@ class UtilString CCAPI_FINAL { output.insert(std::move(s)); return output; } + static std::string join(const std::vector& strings, const std::string& delimiter) { switch (strings.size()) { case 0: return ""; case 1: - return strings[0]; + return strings.at(0); default: std::ostringstream joined; std::copy(strings.begin(), strings.end() - 1, std::ostream_iterator(joined, delimiter.c_str())); @@ -180,50 +202,76 @@ class UtilString CCAPI_FINAL { return joined.str(); } } + + static std::string join(const std::set& strings, const std::string& delimiter) { + std::vector strings_vector(strings.begin(), strings.end()); + return join(strings_vector, delimiter); + } + static std::string toUpper(const std::string& input) { std::string output(input); std::transform(output.begin(), output.end(), output.begin(), ::toupper); return output; } + static std::string toLower(const std::string& input) { std::string output(input); std::transform(output.begin(), output.end(), output.begin(), ::tolower); return output; } + static std::string ltrim(const std::string& original, const std::string& chars = "\t\n\v\f\r ") { std::string str = original; str.erase(0, str.find_first_not_of(chars)); return str; } + static std::string ltrim(const std::string& original, char c) { std::string str = original; str.erase(0, str.find_first_not_of(c)); return str; } + static void ltrimInPlace(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); } + static void ltrimInPlace(std::string& str, char c) { str.erase(0, str.find_first_not_of(c)); } + static std::string rtrim(const std::string& original, const std::string& chars = "\t\n\v\f\r ") { std::string str = original; str.erase(str.find_last_not_of(chars) + 1); return str; } + static std::string rtrim(const std::string& original, char c) { std::string str = original; str.erase(str.find_last_not_of(c) + 1); return str; } + + static std::string_view rtrim(std::string_view str, char c) { + std::size_t end = str.find_last_not_of(c); + if (end == std::string_view::npos) return {}; // All characters were 'c' — return empty view + return str.substr(0, end + 1); + } + static void rtrimInPlace(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); } + static void rtrimInPlace(std::string& str, char c) { str.erase(str.find_last_not_of(c) + 1); } + static std::string trim(const std::string& original, const std::string& chars = "\t\n\v\f\r ") { return ltrim(rtrim(original, chars), chars); } + static std::string trim(const std::string& original, char c) { return ltrim(rtrim(original, c), c); } + static void trimInPlace(std::string& str, const std::string& chars = "\t\n\v\f\r ") { rtrimInPlace(str, chars); ltrimInPlace(str, chars); } + static void trimInPlace(std::string& str, char c) { rtrimInPlace(str, c); ltrimInPlace(str, c); } + static std::string firstNCharacter(const std::string& str, const size_t n) { if (str.length() > n) { return str.substr(0, n) + "..."; @@ -231,8 +279,9 @@ class UtilString CCAPI_FINAL { return str; } } + static std::string normalizeDecimalString(const std::string& original) { - if (original.find('.') != std::string::npos) { + if (original.find('.') != std::string::npos && original.find_first_of("Ee") == std::string::npos) { std::string str(original); rtrimInPlace(str, "0"); rtrimInPlace(str, "."); @@ -241,14 +290,36 @@ class UtilString CCAPI_FINAL { return original; } } - static std::string normalizeDecimalString(const char* data) { - std::string str(data); - if (str.find('.') != std::string::npos) { - rtrimInPlace(str, "0"); - rtrimInPlace(str, "."); + + // static std::string normalizeDecimalStringView(const char* data) { + // std::string str(data); + // if (str.find('.') != std::string::npos) { + // rtrimInPlace(str, "0"); + // rtrimInPlace(str, "."); + // } + // return str; + // } + + static std::string_view normalizeDecimalStringView(std::string_view input) { + // Quick check for dot + size_t dotPos = input.find('.'); + if (dotPos == std::string_view::npos || input.find_first_of("Ee") != std::string::npos) return input; + + size_t end = input.size(); + + // Remove trailing '0's + while (end > dotPos && input[end - 1] == '0') { + --end; } - return str; + + // Remove trailing '.' if all decimals were zeros + if (end > dotPos && input[end - 1] == '.') { + --end; + } + + return input.substr(0, end); } + static std::string leftPadTo(const std::string& str, const size_t padToLength, const char paddingChar) { std::string copy = str; if (padToLength > copy.size()) { @@ -256,6 +327,7 @@ class UtilString CCAPI_FINAL { } return copy; } + static std::string rightPadTo(const std::string& str, const size_t padToLength, const char paddingChar) { std::string copy = str; if (padToLength > copy.size()) { @@ -264,7 +336,8 @@ class UtilString CCAPI_FINAL { return copy; } }; -class UtilTime CCAPI_FINAL { + +class UtilTime { public: static std::string convertFIXTimeToISO(const std::string& fixTime) { // convert 20200925-15:55:28.093490622 to 2020-09-25T15:55:28.093490622Z @@ -279,6 +352,7 @@ class UtilTime CCAPI_FINAL { output += "Z"; return output; } + static std::string convertTimePointToFIXTime(const TimePoint& tp) { int year, month, day, hour, minute, second, millisecond; timePointToParts(tp, year, month, day, hour, minute, second, millisecond); @@ -308,6 +382,7 @@ class UtilTime CCAPI_FINAL { output += millisecondStr; return output; } + template static void timePointToParts(TimePoint tp, int& year, int& month, int& day, int& hour, int& minute, int& second, int& fractionalSecond) { auto epoch_sec = std::chrono::time_point_cast(tp).time_since_epoch().count(); @@ -339,6 +414,7 @@ class UtilTime CCAPI_FINAL { auto now = std::chrono::system_clock::now(); return TimePoint(now); } + static TimePoint parse(const std::string& input) { std::tm time{}; time.tm_year = std::strtol(&input[0], nullptr, 10) - 1900; @@ -365,16 +441,19 @@ class UtilTime CCAPI_FINAL { } return TimePoint(std::chrono::system_clock::from_time_t(timegm(&time))) + std::chrono::nanoseconds(nanoseconds); } + static TimePoint makeTimePoint(const std::pair& timePair) { auto tp = TimePoint(std::chrono::duration(timePair.first)); tp += std::chrono::nanoseconds(timePair.second); return tp; } + static TimePoint makeTimePointMilli(const std::pair& timePair) { auto tp = TimePoint(std::chrono::milliseconds(timePair.first)); tp += std::chrono::nanoseconds(timePair.second); return tp; } + static std::pair divide(const TimePoint& tp) { auto then = tp.time_since_epoch(); auto s = std::chrono::duration_cast(then); @@ -382,6 +461,7 @@ class UtilTime CCAPI_FINAL { auto ns = std::chrono::duration_cast(then); return std::make_pair(s.count(), ns.count()); } + static std::pair divide(const std::string& seconds) { if (seconds.find('.') != std::string::npos) { std::string secondsCopy = seconds; @@ -394,6 +474,7 @@ class UtilTime CCAPI_FINAL { return std::make_pair(std::stoll(seconds), 0); } } + static std::pair divideMilli(const std::string& milliseconds) { if (milliseconds.find('.') != std::string::npos) { std::string millisecondsCopy = milliseconds; @@ -406,6 +487,7 @@ class UtilTime CCAPI_FINAL { return std::make_pair(std::stoll(milliseconds), 0); } } + static std::string convertMillisecondsStrToSecondsStr(const std::string& milliseconds) { std::string output; if (milliseconds.length() >= 4) { @@ -419,9 +501,11 @@ class UtilTime CCAPI_FINAL { } return output; } + static std::pair divideNanoWhole(const std::string& nanoseconds) { return std::make_pair(std::stoll(nanoseconds.substr(0, nanoseconds.length() - 9)), std::stoll(nanoseconds.substr(nanoseconds.length() - 9))); } + template static std::string getISOTimestamp(const TimePoint& tp) { int year, month, day, hour, minute, second, fractionalSecond; @@ -466,15 +550,19 @@ class UtilTime CCAPI_FINAL { output += "Z"; return output; } + static int getUnixTimestamp(const TimePoint& tp) { auto then = tp.time_since_epoch(); auto s = std::chrono::duration_cast(then); return s.count(); } + static TimePoint makeTimePointFromMilliseconds(long long milliseconds) { return TimePoint(std::chrono::milliseconds(milliseconds)); } + static TimePoint makeTimePointFromSeconds(long seconds) { return TimePoint(std::chrono::seconds(seconds)); } }; -class UtilAlgorithm CCAPI_FINAL { + +class UtilAlgorithm { public: enum class ShaVersion { UNKNOWN, @@ -483,6 +571,23 @@ class UtilAlgorithm CCAPI_FINAL { }; public: + static std::string toBase62(size_t value) { + static constexpr char kBase62Chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + std::string result; + do { + result += kBase62Chars[value % 62]; + value /= 62; + } while (value); + std::reverse(result.begin(), result.end()); + return result; + } + + static std::string shortBase62Hash(const std::string& input) { + std::hash hasher; + return toBase62(hasher(input)); + } + static std::string computeHash(const ShaVersion shaVersion, const std::string& unhashed, bool returnHex = false) { EVP_MD_CTX* context = EVP_MD_CTX_new(); switch (shaVersion) { @@ -514,6 +619,7 @@ class UtilAlgorithm CCAPI_FINAL { } return ss.str(); } + static std::string stringToHex(const std::string& input) { static const char hex_digits[] = "0123456789abcdef"; std::string output; @@ -524,6 +630,7 @@ class UtilAlgorithm CCAPI_FINAL { } return output; } + static int hexValue(unsigned char hex_digit) { static const signed char hex_values[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, @@ -538,6 +645,7 @@ class UtilAlgorithm CCAPI_FINAL { if (value == -1) throw std::invalid_argument("invalid hex digit"); return value; } + static std::string hexToString(const std::string& input) { const auto len = input.length(); if (len & 1) throw std::invalid_argument("odd length"); @@ -550,6 +658,7 @@ class UtilAlgorithm CCAPI_FINAL { } return output; } + // https://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c static std::string base64Encode(const std::string& input) { static const unsigned char base64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @@ -586,6 +695,7 @@ class UtilAlgorithm CCAPI_FINAL { } return outStr; } + static std::string base64Decode(const std::string& in) { static const int B64index[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, @@ -615,10 +725,12 @@ class UtilAlgorithm CCAPI_FINAL { } return str; } + // https://github.com/brianloveswords/base64url static std::string base64UrlFromBase64(const std::string& base64) { return std::regex_replace(std::regex_replace(std::regex_replace(base64, std::regex("="), ""), std::regex("\\+"), "-"), std::regex("\\/"), "_"); } + static std::string base64FromBase64Url(const std::string& base64Url) { auto segmentLength = 4; auto stringLength = base64Url.size(); @@ -631,12 +743,111 @@ class UtilAlgorithm CCAPI_FINAL { paddedBase64Url += std::string(padLength, '='); return std::regex_replace(std::regex_replace(paddedBase64Url, std::regex("\\-"), "+"), std::regex("_"), "/"); } + static std::string base64UrlEncode(const std::string& in) { return base64UrlFromBase64(base64Encode(in)); } + static std::string base64UrlDecode(const std::string& in) { return base64Decode(base64FromBase64Url(in)); } + static double exponentialBackoff(double initial, double multiplier, double base, double exponent) { return initial + multiplier * (pow(base, exponent) - 1); } + template static uint_fast32_t crc(InputIterator first, InputIterator last); + + static EVP_PKEY* loadPrivateKey(const std::string& keyPem, const std::string& password = "") { + BIO* bio = BIO_new_mem_buf(keyPem.data(), static_cast(keyPem.size())); + if (!bio) return nullptr; + + const EVP_PKEY_ASN1_METHOD* meth = EVP_PKEY_asn1_find_str(nullptr, "ED25519", -1); + if (!meth) { + throw std::runtime_error("ED25519 is NOT supported in this OpenSSL build."); + } + + EVP_PKEY* pkey = nullptr; + if (password.empty()) { + pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr); + } else { + pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast(password.c_str())); + } + + BIO_free(bio); + return pkey; + } + + static std::string readFile(const std::string& path) { + std::ifstream file(path, std::ios::binary); + if (!file.is_open()) { + throw std::runtime_error("Failed to open file: " + path); + } + + std::ostringstream oss; + oss << file.rdbuf(); + return oss.str(); + } + + static std::string base64Encode(const std::vector& input) { + BIO *bio, *b64; + BUF_MEM* bufferPtr; + b64 = BIO_new(BIO_f_base64()); + bio = BIO_new(BIO_s_mem()); + b64 = BIO_push(b64, bio); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + BIO_write(b64, input.data(), static_cast(input.size())); + BIO_flush(b64); + BIO_get_mem_ptr(b64, &bufferPtr); + std::string result(bufferPtr->data, bufferPtr->length); + BIO_free_all(b64); + return result; + } + + static std::string signPayload(EVP_PKEY* pkey, const std::string& payload) { + EVP_MD_CTX* ctx = EVP_MD_CTX_new(); + if (!ctx) throw std::runtime_error("Failed to create EVP_MD_CTX"); + + const int key_type = EVP_PKEY_base_id(pkey); + const bool is_ed25519 = key_type == EVP_PKEY_ED25519; + + if (EVP_DigestSignInit(ctx, nullptr, is_ed25519 ? nullptr : EVP_sha256(), nullptr, pkey) != 1) throw std::runtime_error("EVP_DigestSignInit failed"); + + size_t sigLen = 0; + + if (is_ed25519) { + // One-shot sign for Ed25519 + if (EVP_DigestSign(ctx, nullptr, &sigLen, reinterpret_cast(payload.data()), payload.size()) != 1) + throw std::runtime_error("EVP_DigestSign (get length) failed"); + + std::vector signature(sigLen); + if (EVP_DigestSign(ctx, signature.data(), &sigLen, reinterpret_cast(payload.data()), payload.size()) != 1) + throw std::runtime_error("EVP_DigestSign failed"); + signature.resize(sigLen); + EVP_MD_CTX_free(ctx); + return base64Encode(signature); + } else { + // Traditional sign (e.g., RSA) + if (EVP_DigestSignUpdate(ctx, payload.data(), payload.size()) != 1) throw std::runtime_error("EVP_DigestSignUpdate failed"); + + if (EVP_DigestSignFinal(ctx, nullptr, &sigLen) != 1) throw std::runtime_error("EVP_DigestSignFinal (get length) failed"); + + std::vector signature(sigLen); + if (EVP_DigestSignFinal(ctx, signature.data(), &sigLen) != 1) throw std::runtime_error("EVP_DigestSignFinal failed"); + + signature.resize(sigLen); + EVP_MD_CTX_free(ctx); + return base64Encode(signature); + } + } + + static const EVP_MD* getDigest(const ShaVersion version) { + switch (version) { + case ShaVersion::SHA256: + return EVP_sha256(); + case ShaVersion::SHA512: + return EVP_sha512(); + default: + throw std::invalid_argument("Unsupported SHA version"); + } + } }; + template inline uint_fast32_t UtilAlgorithm::crc(InputIterator first, InputIterator last) { static auto const table = []() { @@ -661,17 +872,19 @@ inline uint_fast32_t UtilAlgorithm::crc(InputIterator first, InputIterator last) ~std::accumulate(first, last, ~uint_fast32_t{0} & uint_fast32_t{0xFFFFFFFFuL}, [](uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); } -class UtilSystem CCAPI_FINAL { + +class UtilSystem { public: - static bool getEnvAsBool(const std::string variableName, const bool defaultValue = false) { + static bool getEnvAsBool(const std::string& variableName, const bool defaultValue = false) { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { - return UtilString::toLower(std::string(env_p)) == "true"; + return UtilString::toLower(env_p) == "true"; } else { return defaultValue; } } - static std::string getEnvAsString(const std::string variableName, const std::string defaultValue = "") { + + static std::string getEnvAsString(const std::string& variableName, const std::string& defaultValue = "") { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { return std::string(env_p); @@ -679,7 +892,8 @@ class UtilSystem CCAPI_FINAL { return defaultValue; } } - static int getEnvAsInt(const std::string variableName, const int defaultValue = 0) { + + static int getEnvAsInt(const std::string& variableName, const int defaultValue = 0) { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { return std::stoi(std::string(env_p)); @@ -687,7 +901,8 @@ class UtilSystem CCAPI_FINAL { return defaultValue; } } - static long getEnvAsLong(const std::string variableName, const long defaultValue = 0) { + + static long getEnvAsLong(const std::string& variableName, const long defaultValue = 0) { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { return std::stol(std::string(env_p)); @@ -695,7 +910,8 @@ class UtilSystem CCAPI_FINAL { return defaultValue; } } - static float getEnvAsFloat(const std::string variableName, const float defaultValue = 0) { + + static float getEnvAsFloat(const std::string& variableName, const float defaultValue = 0) { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { return std::stof(std::string(env_p)); @@ -703,7 +919,8 @@ class UtilSystem CCAPI_FINAL { return defaultValue; } } - static double getEnvAsDouble(const std::string variableName, const double defaultValue = 0) { + + static double getEnvAsDouble(const std::string& variableName, const double defaultValue = 0) { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { return std::stod(std::string(env_p)); @@ -711,6 +928,7 @@ class UtilSystem CCAPI_FINAL { return defaultValue; } } + static bool checkEnvExist(const std::string& variableName) { const char* env_p = std::getenv(variableName.c_str()); if (env_p) { @@ -720,17 +938,486 @@ class UtilSystem CCAPI_FINAL { } } }; + +/** + * This class provides a numeric type for representing an arbitrary precision decimal number. It is minimalistic for the purpose of high performance. + * Furthermore, unlike double, it is suitable for being used as the key of a map. boost::multiprecision::cpp_dec_float can also be used, but based on + * test it does lead to nearly 100% increase in cpu usage! + */ +class Decimal { + public: + Decimal() {} + + template >> + Decimal(T value) { + if (value < 0) { + this->sign = false; + this->before = -value; + } else if (value > 0) { + this->before = value; + } + } + + explicit Decimal(std::string_view originalValue) { + if (originalValue.empty()) { + throw std::invalid_argument("Decimal constructor input value cannot be empty"); + } + if (originalValue.at(0) == '-') { + this->sign = false; + } + auto foundE = originalValue.find('E'); + if (foundE != std::string::npos || originalValue.find('e') != std::string::npos) { + if (foundE == std::string::npos) { + foundE = originalValue.find('e'); + } + std::string fixedPointValue = std::string(originalValue.substr(this->sign ? 0 : 1, this->sign ? foundE : foundE - 1)); + auto foundDot = fixedPointValue.find('.'); + if (foundDot != std::string::npos) { + fixedPointValue.erase(fixedPointValue.find_last_not_of('0') + 1); + fixedPointValue.erase(fixedPointValue.find_last_not_of('.') + 1); + } + std::string exponent = std::string(originalValue.substr(foundE + 1)); + if (exponent.at(0) == '+') { + exponent.erase(0, 1); + } + exponent.erase(0, exponent.find_first_not_of('0')); + if (exponent.empty()) { + exponent = "0"; + } + if (exponent != "0") { + foundDot = fixedPointValue.find('.'); + if (foundDot != std::string::npos) { + if (exponent.at(0) != '-') { + if (std::stoi(exponent) < fixedPointValue.substr(foundDot + 1).length()) { + fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1).substr(0, std::stoi(exponent)) + "." + + fixedPointValue.substr(foundDot + 1).substr(std::stoi(exponent)); + } else { + fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1) + + std::string(std::stoi(exponent) - fixedPointValue.substr(foundDot + 1).length(), '0'); + } + } else { + fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1); + } + } else { + if (exponent.at(0) != '-') { + fixedPointValue += std::string(std::stoi(exponent), '0'); + } else { + fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue; + } + } + } + foundDot = fixedPointValue.find('.'); + std::string numPart = fixedPointValue.substr(0, foundDot); + if (!numPart.empty() && numPart[0] == '+') { + numPart.erase(0, 1); + } + auto [_, ec] = std::from_chars(numPart.data(), numPart.data() + numPart.size(), this->before); + if (ec != std::errc()) { + throw std::invalid_argument("Invalid numeric input: " + std::string(numPart)); + } + if (foundDot != std::string::npos) { + this->frac = fixedPointValue.substr(foundDot + 1); + // if (!keepTrailingZero) { + this->frac.erase(this->frac.find_last_not_of('0') + 1); + // } + } + } else { + auto found = originalValue.find('.'); + std::string numPart = std::string(originalValue.substr(this->sign ? 0 : 1, found)); + if (!numPart.empty() && numPart[0] == '+') { + numPart.erase(0, 1); + } + auto [_, ec] = std::from_chars(numPart.data(), numPart.data() + numPart.size(), this->before); + if (ec != std::errc()) { + throw std::invalid_argument("Invalid numeric input: " + std::string(numPart)); + } + if (found != std::string::npos) { + this->frac = originalValue.substr(found + 1); + // if (!keepTrailingZero) { + this->frac.erase(this->frac.find_last_not_of('0') + 1); + // } + } + } + + if (!this->sign && this->before == 0 && this->frac.empty() + // ((keepTrailingZero && std::all_of(this->frac.begin(), this->frac.end(), [](char c) { return c == '0'; })) || + // (!keepTrailingZero && this->frac.empty())) + ) { + this->sign = true; + } + } + + std::string toString() const { + if (!this->cachedToString) { + std::string stringValue; + if (!this->sign) { + stringValue += "-"; + } + stringValue += std::to_string(this->before); + if (!this->frac.empty()) { + stringValue += "."; + stringValue += this->frac; + } + cachedToString.emplace(stringValue); + } + return *this->cachedToString; + } + + double toDouble() const { + if (!this->cachedToDouble) { + cachedToDouble.emplace(std::stod(this->toString())); + } + return *this->cachedToDouble; + } + + friend bool operator<(const Decimal& l, const Decimal& r) { + if (l.sign && r.sign) { + if (l.before < r.before) { + return true; + } else if (l.before > r.before) { + return false; + } else { + return l.frac < r.frac; + } + } else if (l.sign && !r.sign) { + return false; + } else if (!l.sign && r.sign) { + return true; + } else { + Decimal nl = l; + nl.sign = true; + Decimal nr = r; + nr.sign = true; + return nl > nr; + } + } + + friend bool operator>(const Decimal& l, const Decimal& r) { return r < l; } + + friend bool operator<=(const Decimal& l, const Decimal& r) { return !(l > r); } + + friend bool operator>=(const Decimal& l, const Decimal& r) { return !(l < r); } + + friend bool operator==(const Decimal& l, const Decimal& r) { return !(l > r) && !(l < r); } + + friend bool operator!=(const Decimal& l, const Decimal& r) { return !(l == r); } + + /* ---------- Arithmetic operators ---------- */ + + // unary –––––––––––––––––––––––––––––––––––––– + /// -x (flip the sign) + Decimal operator-() const { + Decimal tmp = *this; + if (!(tmp.before == 0 && tmp.frac.empty())) { // keep “–0” positive + tmp.sign = !tmp.sign; + } + return tmp; + } + + // binary ––––––––––––––––––––––––––––––––––––– + /// x + y + friend Decimal operator+(const Decimal& lhs, const Decimal& rhs) { + return lhs.add(rhs); // reuse the pre-existing logic + } + + /// x - y + friend Decimal operator-(const Decimal& lhs, const Decimal& rhs) { + return lhs.subtract(rhs); // reuse the pre-existing logic + } + + // compound-assignment –––––––––––––––––––––––– + Decimal& operator+=(const Decimal& rhs) { + *this = *this + rhs; + return *this; + } + + Decimal& operator-=(const Decimal& rhs) { + *this = *this - rhs; + return *this; + } + + template , int> = 0> + friend Decimal operator*(const Decimal& lhs, T rhs) { + return lhs.multiply(rhs); + } + + template , int> = 0> + friend Decimal operator*(T lhs, const Decimal& rhs) { + return rhs.multiply(lhs); + } + + template , int> = 0> + Decimal& operator*=(T x) { + *this = this->multiply(x); + return *this; + } + + Decimal negate() const { + Decimal o; + o.sign = !this->sign; + o.before = this->before; + o.frac = this->frac; + return o; + } + + Decimal abs() const { + if (!this->sign) { // if the input is negative + return -*this; // negate it + } + return *this; // already positive + } + + Decimal add(const Decimal& x) const { + /* ---------------- Same-sign fast path ---------------- */ + if (this->sign && x.sign) { + Decimal o; + o.sign = true; // result always positive here + o.before = this->before + x.before; // integer parts + + // === Fractional part === + std::string_view f1 = this->frac; + std::string_view f2 = x.frac; + if (f1.empty()) { // 0.xxx + 0 + o.frac = f2; + return o; + } + if (f2.empty()) { // 0 + 0.xxx + o.frac = f1; + return o; + } + + std::size_t l1 = f1.size(); + std::size_t l2 = f2.size(); + std::size_t lmax = std::max(l1, l2); + + /* ---- pad to same length (stack buffer, max 64 digits) ---- */ + char buf1[64]{}, buf2[64]{}; + std::memcpy(buf1, f1.data(), l1); + std::fill(buf1 + l1, buf1 + lmax, '0'); + std::memcpy(buf2, f2.data(), l2); + std::fill(buf2 + l2, buf2 + lmax, '0'); + + /* ---- convert to integers ---- */ + uint64_t n1 = 0, n2 = 0; + auto [p1, ec1] = std::from_chars(buf1, buf1 + lmax, n1); + auto [p2, ec2] = std::from_chars(buf2, buf2 + lmax, n2); + if (ec1 != std::errc() || ec2 != std::errc()) { + throw std::invalid_argument("Decimal::add – fractional overflow"); + } + + uint64_t sum = n1 + n2; + bool carry = sum >= static_cast(std::pow(10, lmax)); + + if (carry) { + sum -= static_cast(std::pow(10, lmax)); + ++o.before; // propagate carry to integer part + } + + /* ---- build fractional string ---- */ + std::string frac = std::to_string(sum); + if (frac.length() < lmax) { // left-pad with zeros + frac.insert(0, lmax - frac.length(), '0'); + } + frac.erase(frac.find_last_not_of('0') + 1); // trim trailing zeros + o.frac = frac; + + return o; + } + + /* ---------------- Mixed-sign cases ---------------- */ + if (this->sign && !x.sign) return this->subtract(x.negate()); + if (!this->sign && x.sign) return x.subtract(this->negate()); + /* both negative */ + return (this->negate().add(x.negate())).negate(); + } + + Decimal subtract(const Decimal& x) const { + /* ------------------------------------------------ + Case 1: both operands positive + ------------------------------------------------ */ + if (this->sign && x.sign) { + if (*this >= x) { + Decimal o; + o.sign = true; + + /* ---- Prep integer difference (may be adjusted by borrow) ---- */ + o.before = this->before - x.before; + + /* ---- Fast exit if no fractional digits at all ---- */ + if (this->frac.empty() && x.frac.empty()) return o; + + /* ---- Determine max fractional length ---- */ + std::string_view f1 = this->frac; + std::string_view f2 = x.frac; + const std::size_t l1 = f1.size(); + const std::size_t l2 = f2.size(); + const std::size_t lmax = std::max(l1, l2); + + /* ---- Ensure temporary buffer big enough ---- */ + std::vector buf1(lmax, '0'); + std::vector buf2(lmax, '0'); + + std::memcpy(buf1.data(), f1.data(), l1); + std::memcpy(buf2.data(), f2.data(), l2); + + /* ---- Parse to integers with from_chars ---- */ + uint64_t n1 = 0, n2 = 0; + auto [p1, ec1] = std::from_chars(buf1.data(), buf1.data() + lmax, n1); + auto [p2, ec2] = std::from_chars(buf2.data(), buf2.data() + lmax, n2); + if (ec1 != std::errc() || ec2 != std::errc()) { + throw std::invalid_argument("Decimal::subtract – fractional overflow"); + } + + /* ---- Borrow logic ---- */ + uint64_t base = 1; + for (std::size_t i = 0; i < lmax; ++i) base *= 10; // 10^lmax + + uint64_t diff; + if (n1 >= n2) { + diff = n1 - n2; + } else { + diff = base + n1 - n2; + --o.before; // borrow 1 from integer part + } + + /* ---- Build normalized fractional string ---- */ + std::string frac = std::to_string(diff); + if (frac.length() < lmax) frac.insert(0, lmax - frac.length(), '0'); // left-pad + frac.erase(frac.find_last_not_of('0') + 1); // trim trailing zeros + o.frac = std::move(frac); + + return o; + } + + /* if *this < x -> -(x - *this) */ + return x.subtract(*this).negate(); + } + + /* ------------------------------------------------ + Mixed sign cases re-use add()/negate() + ------------------------------------------------ */ + if (!this->sign && x.sign) return this->negate().add(x).negate(); // (-a)-(+b) = -(a+b) + if (this->sign && !x.sign) return this->add(x.negate()); // (+a)-(-b) = a+b + + /* both negative: (-a)-(-b) = b-a */ + return x.negate().subtract(this->negate()); + } + + template , int> = 0> + Decimal multiply(T x) const { + Decimal result; + + if (x == 0) return result; // default constructed Decimal = 0 + + result.sign = (this->sign == (x >= 0)); // XOR logic for sign + T abs_x = x < 0 ? -x : x; + + // Integer part multiplication + result.before = this->before * static_cast(abs_x); + + if (!this->frac.empty()) { + std::string paddedFrac = this->frac; + std::size_t fracLen = paddedFrac.length(); + + // Pad to avoid truncation + std::string_view fracPart = paddedFrac; + + // Convert frac string to integer + uint64_t fracVal = 0; + auto [p, ec] = std::from_chars(fracPart.data(), fracPart.data() + fracPart.size(), fracVal); + if (ec != std::errc()) { + throw std::invalid_argument("Decimal::multiply - fractional overflow"); + } + + // Multiply + uint64_t prod = fracVal * static_cast(abs_x); + + // Total fractional scale: keep `fracLen` digits + std::string s = std::to_string(prod); + + if (s.length() <= fracLen) { + s.insert(0, fracLen - s.length(), '0'); // left pad + result.frac = UtilString::rtrim(s, "0"); + } else { + // overflow into integer part + std::string over = s.substr(0, s.length() - fracLen); + std::string fracOnly = s.substr(s.length() - fracLen); + + result.before += std::stoull(over); + result.frac = UtilString::rtrim(fracOnly, "0"); + } + } + + return result; + } + + static const Decimal zero; +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + // false means negative sign needed + bool sign{true}; + // {-}bbbb.aaaa + uint64_t before{}; + std::string frac; + + mutable std::optional cachedToString; + mutable std::optional cachedToDouble; +}; + +inline const Decimal Decimal::zero = Decimal(0); // define after full class body + +inline std::string ConvertDecimalToString(const Decimal& input, bool normalize = true) { + // constexpr unsigned precision = GetCppDecFloatDigits::value; + + // // Always generate fixed-format string + // std::string s = input.str(precision, std::ios_base::fixed); + + // // Fast path: normalization is OFF + // if (!normalize) { + // return s; + // } + + // // Fast trimming: remove trailing zeros after the decimal + // const std::size_t dot_pos = s.find('.'); + // if (dot_pos == std::string::npos) { + // return s; // No decimal point + // } + + // std::size_t end = s.size(); + + // // Find last non-zero character after the decimal + // while (end > dot_pos + 1 && s[end - 1] == '0') { + // --end; + // } + + // // Remove decimal point if it's the last remaining character + // if (end == dot_pos + 1) { + // --end; + // } + + // s.resize(end); + return input.toString(); +} + +inline Decimal ConvertDecimalToAbs(const Decimal& input) { return input.abs(); } + +inline double ConvertDecimalToDouble(const Decimal& input) { return input.toDouble(); } + inline std::string size_tToString(const size_t& t) { std::stringstream ss; ss << t; return ss.str(); } + template std::string intToHex(T i) { std::stringstream stream; stream << std::hex << i; return stream.str(); } + template int ceilSearch(const std::vector& c, int low, int high, T x) { int i = 0; @@ -747,22 +1434,27 @@ int ceilSearch(const std::vector& c, int low, int high, T x) { } return -1; } + template struct reversion_wrapper { T& iterable; }; + template auto begin(reversion_wrapper w) { return std::rbegin(w.iterable); } + template auto end(reversion_wrapper w) { return std::rend(w.iterable); } + template reversion_wrapper reverse(T&& iterable) { return {iterable}; } + template bool firstNSame(const std::map& c1, const std::map& c2, size_t n) { if (c1.empty() || c2.empty()) { @@ -783,6 +1475,7 @@ bool firstNSame(const std::map& c1, const std::map& c2, size_t n) { } return true; } + template bool lastNSame(const std::map& c1, const std::map& c2, size_t n) { if (c1.empty() || c2.empty()) { @@ -803,6 +1496,7 @@ bool lastNSame(const std::map& c1, const std::map& c2, size_t n) { } return true; } + template void keepFirstN(std::map& c, size_t n) { if (!c.empty()) { @@ -811,6 +1505,7 @@ void keepFirstN(std::map& c, size_t n) { c.erase(it, c.end()); } } + template void keepLastN(std::map& c, size_t n) { if (!c.empty()) { @@ -819,26 +1514,31 @@ void keepLastN(std::map& c, size_t n) { c.erase(c.begin(), it); } } + template typename std::enable_if().toString()), std::string>::value, std::string>::type toString(const T& t) { return t.toString(); } + template -typename std::enable_if().toStringPretty()), std::string>::value, std::string>::type toStringPretty( +typename std::enable_if().toPrettyString()), std::string>::value, std::string>::type toPrettyString( const T& t, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { - return t.toStringPretty(space, leftToIndent, indentFirstLine); + return t.toPrettyString(space, leftToIndent, indentFirstLine); } + template typename std::enable_if::value, std::string>::type toString(const T& t) { return std::to_string(t); } + template -typename std::enable_if())), std::string>::value, std::string>::type toStringPretty( +typename std::enable_if())), std::string>::value, std::string>::type toPrettyString( const T& t, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { std::string sl(leftToIndent, ' '); std::string output = (indentFirstLine ? sl : "") + std::to_string(t); return output; } + template typename std::enable_if::value, std::string>::type toString(const T& t) { std::stringstream ss; @@ -847,22 +1547,55 @@ typename std::enable_if::value, std::string>::type toS ss << t; return ss.str(); } + template typename std::enable_if::value, std::string>::type toString(const T& t) { return t; } + template -typename std::enable_if::value, std::string>::type toStringPretty(const T& t, const int space = 2, const int leftToIndent = 0, +typename std::enable_if::value, std::string>::type toString(const T& t) { + return std::string(t); +} + +// template +// typename std::enable_if::value, std::string>::type toString(const T& t) { +// return ConvertDecimalToString(t); +// } + +template +typename std::enable_if::value, std::string>::type toPrettyString(const T& t, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { std::string sl(leftToIndent, ' '); std::string output = (indentFirstLine ? sl : "") + t; return output; } + +template +typename std::enable_if::value, std::string>::type toPrettyString(const T& t, const int space = 2, const int leftToIndent = 0, + const bool indentFirstLine = true) { + std::string sl(leftToIndent, ' '); + std::string output = (indentFirstLine ? sl : "") + std::string(t); + return output; +} + +template +typename std::enable_if>::value, std::string>::type toPrettyString(const T& p, const int space = 2, + const int leftToIndent = 0, + const bool indentFirstLine = true) { + std::string indent(leftToIndent, ' '); + std::string result; + if (indentFirstLine) result += indent; + result += "(" + std::to_string(p.first) + ", \"" + p.second + "\")"; + return result; +} + template typename std::enable_if::value, std::string>::type toString(const T& t) { auto timePair = UtilTime::divide(t); return "(" + std::to_string(timePair.first) + "," + std::to_string(timePair.second) + ")"; } + template typename std::string toString(const T* a, const size_t n) { std::string output = "["; @@ -875,6 +1608,7 @@ typename std::string toString(const T* a, const size_t n) { output += "]"; return output; } + template std::string toString(const std::unordered_set& c); template @@ -891,6 +1625,7 @@ template std::string toString(const std::vector& c); template std::string firstNToString(const std::vector& c, const size_t n); + template std::string toString(const std::pair& c) { std::string output = "("; @@ -900,6 +1635,7 @@ std::string toString(const std::pair& c) { output += ")"; return output; } + template inline std::string toString(const std::unordered_set& c) { std::string output = "["; @@ -915,6 +1651,7 @@ inline std::string toString(const std::unordered_set& c) { output += "]"; return output; } + template inline std::string toString(const std::set& c) { std::string output = "["; @@ -930,6 +1667,7 @@ inline std::string toString(const std::set& c) { output += "]"; return output; } + template inline std::string toString(const std::map& c) { std::string output = "{"; @@ -947,16 +1685,17 @@ inline std::string toString(const std::map& c) { output += "}"; return output; } + template -std::string toStringPretty(const std::map& c, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { +std::string toPrettyString(const std::map& c, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { std::string sl(leftToIndent, ' '); std::string output = (indentFirstLine ? sl : "") + "{\n"; auto size = c.size(); auto i = 0; for (const auto& elem : c) { - output += toStringPretty(elem.first, space, space + leftToIndent, true); + output += toPrettyString(elem.first, space, space + leftToIndent, true); output += " = "; - output += toStringPretty(elem.second, space, space + leftToIndent, false); + output += toPrettyString(elem.second, space, space + leftToIndent, false); if (i < size - 1) { output += ",\n"; } @@ -965,6 +1704,7 @@ std::string toStringPretty(const std::map& c, const int space = 2, const i output += "\n" + sl + "}"; return output; } + template inline std::string toString(const std::unordered_map& c) { std::string output = "{"; @@ -982,6 +1722,7 @@ inline std::string toString(const std::unordered_map& c) { output += "}"; return output; } + template inline std::string firstNToString(const std::map& c, const size_t n) { std::string output = "{"; @@ -1005,6 +1746,7 @@ inline std::string firstNToString(const std::map& c, const size_t n) { output += "}"; return output; } + template inline std::string lastNToString(const std::map& c, const size_t n) { std::string output = "{"; @@ -1028,6 +1770,7 @@ inline std::string lastNToString(const std::map& c, const size_t n) { output += "}"; return output; } + template inline std::string toString(const std::vector& c) { std::string output = "[ "; @@ -1043,14 +1786,15 @@ inline std::string toString(const std::vector& c) { output += " ]"; return output; } + template -std::string toStringPretty(const std::vector& c, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { +std::string toPrettyString(const std::vector& c, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { std::string sl(leftToIndent, ' '); std::string output = (indentFirstLine ? sl : "") + "[\n"; auto size = c.size(); auto i = 0; for (const auto& elem : c) { - output += toStringPretty(elem, space, space + leftToIndent, true); + output += toPrettyString(elem, space, space + leftToIndent, true); if (i < size - 1) { output += ",\n"; } @@ -1059,6 +1803,7 @@ std::string toStringPretty(const std::vector& c, const int space = 2, const i output += "\n" + sl + "]"; return output; } + template inline std::string firstNToString(const std::vector& c, const size_t n) { std::string output = "[ "; @@ -1080,6 +1825,7 @@ inline std::string firstNToString(const std::vector& c, const size_t n) { output += " ]"; return output; } + template std::string firstNToStringPretty(const std::vector& c, const size_t n, const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) { std::string sl(leftToIndent, ' '); @@ -1090,7 +1836,7 @@ std::string firstNToStringPretty(const std::vector& c, const size_t n, const if (i >= n) { break; } - output += toStringPretty(elem, space, space + leftToIndent, true); + output += toPrettyString(elem, space, space + leftToIndent, true); if (i < size - 1) { output += ",\n"; } @@ -1102,14 +1848,16 @@ std::string firstNToStringPretty(const std::vector& c, const size_t n, const output += "\n" + sl + "]"; return output; } + template -std::map > invertMapMulti(const std::map& c) { - std::map > output; +std::map> invertMapMulti(const std::map& c) { + std::map> output; for (const auto& elem : c) { output[elem.second].push_back(elem.first); } return output; } + template std::map invertMap(const std::map& c) { std::map output; @@ -1118,6 +1866,7 @@ std::map invertMap(const std::map& c) { } return output; } + template