10 Commits

Author SHA1 Message Date
3598fc7918 Merge 1a0ad2dc90 into 6a68f1cc45 2024-07-14 08:19:57 +00:00
1a0ad2dc90 removed cryptopp, openssl shall be used instead for blinding (but not implemented yet) 2024-07-14 10:19:46 +02:00
a5bce23891 added test_crypto.cpp with first code for rsa blinding 2024-07-14 10:19:46 +02:00
d251bf4f54 included crypto++ lib 2024-07-14 10:19:46 +02:00
6a68f1cc45 Create dependabot.yml
All checks were successful
continuous-integration/drone/push Build is passing
2023-09-05 09:01:28 +02:00
e3fd9cb576 fixes for warnings from code analysis 2023-04-20 22:56:34 +02:00
84cbb34391 added link to draftspec and to alternative implementation of RSA blind signatures using OpenSSL or BoringSSL
All checks were successful
continuous-integration/drone/push Build is passing
2023-01-30 22:09:37 +01:00
a2747b6934 updated catch2 to v3.3.1
All checks were successful
continuous-integration/drone/push Build is passing
2023-01-29 23:59:28 +01:00
ed525909bb splitted model.cpp into json_serialisation.cpp and model.cpp
All checks were successful
continuous-integration/drone/push Build is passing
2023-01-29 12:20:54 +01:00
bdab59a507 corrected Link to OpenCoin Protocol 2023-01-29 12:20:08 +01:00
12 changed files with 909 additions and 616 deletions

11
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"

View File

@ -1,9 +1,10 @@
cmake_minimum_required(VERSION 3.1.3) cmake_minimum_required(VERSION 3.15)
enable_language(C) enable_language(C)
enable_language(CXX) enable_language(CXX)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
if(POLICY CMP0077) if(POLICY CMP0077)
cmake_policy(SET CMP0077 NEW) cmake_policy(SET CMP0077 NEW)
endif() endif()
@ -16,6 +17,8 @@ endif()
project(oc-issuer VERSION 0.0.2 LANGUAGES CXX) project(oc-issuer VERSION 0.0.2 LANGUAGES CXX)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(FetchContent) include(FetchContent)
# #
@ -29,7 +32,7 @@ set(CROW_BUILD_DOCS Off)
# add crow project to the build # add crow project to the build
FetchContent_Declare(crow FetchContent_Declare(crow
GIT_REPOSITORY https://github.com/CrowCpp/Crow.git GIT_REPOSITORY https://github.com/CrowCpp/Crow.git
GIT_TAG v1.0+5 GIT_TAG v1.2.0
) )
if(NOT crow_POPULATED) if(NOT crow_POPULATED)
@ -46,6 +49,18 @@ if(NOT expected_POPULATED)
FetchContent_Populate(expected) FetchContent_Populate(expected)
endif(NOT expected_POPULATED) endif(NOT expected_POPULATED)
# add crypt++ (+cmake) library
#set(CRYPTOPP_BUILD_TESTING Off)
#set(CRYPTOPP_INSTALL Off)
#if(NOT cryptopp_POPULATED)
# FetchContent_Declare(cryptopp
# GIT_REPOSITORY https://github.com/abdes/cryptopp-cmake.git
# GIT_TAG CRYPTOPP_8_7_0_1)
# FetchContent_Populate(cryptopp)
# add_subdirectory(${cryptopp_SOURCE_DIR} ${cryptopp_BINARY_DIR})
#endif(NOT cryptopp_POPULATED)
include(CTest) include(CTest)
enable_testing() enable_testing()
@ -54,7 +69,7 @@ set(CATCH_INSTALL_EXTRAS Off)
FetchContent_Declare( FetchContent_Declare(
Catch2 Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.2.0 GIT_TAG v3.3.1
) )
FetchContent_MakeAvailable(Catch2) FetchContent_MakeAvailable(Catch2)
@ -71,16 +86,23 @@ doxygen_add_docs( doc
) )
# build common library # build common library
set(LIB_SOURCES src/model.cpp src/model.hpp src/big_int.hpp src/big_int.cpp) set(LIB_SOURCES
src/model.cpp src/model.hpp
src/json_serialisation.cpp
src/big_int.hpp src/big_int.cpp )
add_library(oc-mint-lib ${LIB_SOURCES}) add_library(oc-mint-lib ${LIB_SOURCES})
target_link_libraries(oc-mint-lib PUBLIC Crow::Crow) target_link_libraries(oc-mint-lib PUBLIC Crow::Crow) # cryptopp::cryptopp)
target_include_directories(oc-mint-lib PUBLIC ${expected_SOURCE_DIR}/include src) target_include_directories(oc-mint-lib PUBLIC ${expected_SOURCE_DIR}/include src)
add_executable(${PROJECT_NAME} src/main.cpp) add_executable(${PROJECT_NAME} src/main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE oc-mint-lib INTERFACE tl::expected::expected) target_link_libraries(${PROJECT_NAME} PRIVATE oc-mint-lib INTERFACE tl::expected::expected)
## these are unittests that can be run on any platform ## these are unittests that can be run on any platform
add_executable(tests test/test_big_int.cpp test/test.cpp) add_executable(tests test/test_big_int.cpp
test/test_json_s8n.cpp
test/test_crypto.cpp)
target_link_libraries(tests target_link_libraries(tests
oc-mint-lib oc-mint-lib
Catch2::Catch2WithMain) Catch2::Catch2WithMain)

View File

@ -6,7 +6,7 @@ opencoin-issuer-cpp - a C++ OpenCoin Issuer REST-API implementation {#mainpage}
# opencoin issuer # opencoin issuer
this is a C++ implementation of the [opencoin protocol](https://opencoin.org/0.4/OpenCoin.html) this is a C++ implementation of the [opencoin protocol](https://opencoin.org/OpenCoin.html)
done as mapping to some kind of REST interface. done as mapping to some kind of REST interface.
As all issuer related interactions of the protocol follows a request/response mechanism we are able to map all of them to Http-Requests. As all issuer related interactions of the protocol follows a request/response mechanism we are able to map all of them to Http-Requests.
@ -18,8 +18,8 @@ The following table gives an overview of the mapping of requests to URLs:
| Request | URL | Response | C++ Interface Method | | Request | URL | Response | C++ Interface Method |
|:------------------|:-------------|:------------------------------|:---------------------------------------------------| |:------------------|:-------------|:------------------------------|:---------------------------------------------------|
| RequestCDDCSerial | /cddc/serial | ResponseCDDCSerial | cdd.cdd_serial of Model::getCurrentCDDC() | | RequestCDDCSerial | /cddc/serial | ResponseCDDCSerial | cdd.cdd_serial of Model::get_current_cddc() |
| RequestCDDC | /cddc | ResponseCDDC | Model::getCurrentCDDC() | | RequestCDDC | /cddc | ResponseCDDC | Model::get_current_cddc() |
| RequestMKCs | /mkcs | ResponseMKCs | Model::getMKCs | | RequestMKCs | /mkcs | ResponseMKCs | Model::getMKCs |
| RequestMint | /mint | ResponseMint | Model::mint | | RequestMint | /mint | ResponseMint | Model::mint |
| RequestRenew | /renew | ResponseMint or ResponseDelay | ? | | RequestRenew | /renew | ResponseMint or ResponseDelay | ? |
@ -51,3 +51,8 @@ https://crypto.stackexchange.com/questions/12707/usability-of-padding-scheme-in-
https://crypto.stackexchange.com/questions/54085/is-there-a-standard-padding-format-for-rsa-blind-signatures/60728#60728 https://crypto.stackexchange.com/questions/54085/is-there-a-standard-padding-format-for-rsa-blind-signatures/60728#60728
https://crypto.stackexchange.com/questions/5626/rsa-blind-signatures-in-practice https://crypto.stackexchange.com/questions/5626/rsa-blind-signatures-in-practice
<https://cfrg.github.io/draft-irtf-cfrg-blind-signatures/draft-irtf-cfrg-rsa-blind-signatures.html>
alternative implementation using openssl
https://github.com/jedisct1/blind-rsa-signatures

View File

@ -1,82 +1,76 @@
#include "big_int.hpp" #include "big_int.hpp"
#include "tl/expected.hpp" #include "tl/expected.hpp"
#include <iostream>
#include <charconv> #include <charconv>
#include <vector>
#pragma clang diagnostic push
#pragma ide diagnostic ignored "clion-misra-cpp2008-6-4-5"
inline uint8_t hex(char c) { inline uint8_t hex(char c) {
switch(c) { switch(c) {
case '0': return 0; case '0': return 0U;
case '1': return 1; case '1': return 1U;
case '2': return 2; case '2': return 2U;
case '3': return 3; case '3': return 3U;
case '4': return 4; case '4': return 4U;
case '5': return 5; case '5': return 5U;
case '6': return 6; case '6': return 6U;
case '7': return 7; case '7': return 7U;
case '8': return 8; case '8': return 8U;
case '9': return 9; case '9': return 9U;
case 'a': return 10; case 'a': return 10U;
case 'b': return 11; case 'b': return 11U;
case 'c': return 12; case 'c': return 12U;
case 'd': return 13; case 'd': return 13U;
case 'e': return 14; case 'e': return 14U;
case 'f': return 15; case 'f': return 15U;
case 'A': return 10; case 'A': return 10U;
case 'B': return 11; case 'B': return 11U;
case 'C': return 12; case 'C': return 12U;
case 'D': return 13; case 'D': return 13U;
case 'E': return 14; case 'E': return 14U;
case 'F': return 15; case 'F': return 15U;
default: default:
return 0xff; return 0xffU;
} }
} }
#pragma clang diagnostic pop
tl::expected<BigInt,BigInt::eError> tl::expected<BigInt,BigInt::eError>
BigInt::from_string(const std::string& str) { BigInt::from_string(const std::string& str) {
BigInt b; BigInt b;
// std::cout << str << std::endl;
uint8_t hval=0; uint8_t hval=0U;
uint8_t nibble; uint8_t nibble;
size_t i = str.size()+1; size_t i = str.size()+1U;
for(auto c : str) { for(auto c : str) {
nibble = hex(c); nibble = hex(c);
if (nibble ==0xFF) { if (nibble ==0xFFU) {
return tl::make_unexpected(eError::PARSE_ERROR); return tl::make_unexpected(eError::PARSE_ERROR);
} }
if (i%2) { if ( i%2U != 0U ) {
hval = nibble << 4; hval = nibble << 4U;
} else { } else {
hval |= nibble; hval |= nibble;
b.data[256 - (i/2)]= hval; b.data[256U - (i/2U)]= hval;
hval = 0; hval = 0U;
} }
i--; i--;
} }
// std::cout << std::hex;
// for (auto b: b.data)
// {
// std::cout << (int)b;
// }
// std::cout << std::dec << std::endl;
return b; return b;
} }
BigInt BigInt::from_int(uint64_t value) BigInt BigInt::from_int(uint64_t value)
{ {
BigInt b; BigInt b;
b.data[248]=(value >> 56 & 0xff); b.data[248U]=static_cast<uint8_t>(value >> 56 & 0xffU);
b.data[249]=(value >> 48 & 0xff); b.data[249U]=static_cast<uint8_t>(value >> 48 & 0xffU);
b.data[250]=(value >> 40 & 0xff); b.data[250U]=static_cast<uint8_t>(value >> 40U & 0xffU);
b.data[251]=(value >> 32 & 0xff); b.data[251U]=static_cast<uint8_t>(value >> 32U & 0xffU);
b.data[252]=(value >> 24 & 0xff); b.data[252U]=static_cast<uint8_t>(value >> 24U & 0xffU);
b.data[253]=(value >> 16 & 0xff); b.data[253U]=static_cast<uint8_t>(value >> 16U & 0xffU);
b.data[254]=(value >> 8 & 0xff); b.data[254U]=static_cast<uint8_t>(value >> 8U & 0xffU);
b.data[255]=(value & 0xff); b.data[255U]=static_cast<uint8_t>(value & 0xffU);
return b; return b;
} }
@ -85,14 +79,16 @@ std::string BigInt::to_string() const
{ {
std::string s; std::string s;
uint8_t b; uint8_t b;
uint8_t first_digit = 0; uint8_t first_digit = 0U;
for (size_t i = 0; i<256;i++) { for (size_t i = 0U; i<256U;i++) {
b = data[i]; b = data[i];
if (first_digit==0) { if (first_digit==0U) {
if (b==0) { if (b==0U) {
continue; continue;
} else if (b>0xf) { } else if (b>0xfU) {
s.push_back(hex_char[b >> 4]); s.push_back(hex_char[b >> 4]);
} else {
/* nothing to do here */
} }
s.push_back(hex_char[b & 0xf]); s.push_back(hex_char[b & 0xf]);
first_digit = b; first_digit = b;

View File

@ -1,5 +1,5 @@
#ifndef BIG_INT_HPP #ifndef OC_ISSUER_BIG_INT_HPP
#define BIG_INT_HPP #define OC_ISSUER_BIG_INT_HPP
#include <string> #include <string>
#include <array> #include <array>
@ -9,19 +9,19 @@
struct BigInt { struct BigInt {
BigInt() : data() {} BigInt() : data() {}
virtual ~BigInt() {} virtual ~BigInt() = default;
enum class eError : uint8_t { PARSE_ERROR }; enum class eError : uint8_t { PARSE_ERROR };
static tl::expected<BigInt, eError> from_string(const std::string &str); static tl::expected<BigInt, eError> from_string(const std::string &str);
static BigInt from_int(uint64_t value); static BigInt from_int(uint64_t value);
std::string to_string() const; [[nodiscard]] std::string to_string() const;
friend bool operator == (const BigInt& rhs, const BigInt& lhs); friend bool operator == (const BigInt& rhs, const BigInt& lhs);
private: private:
std::array<uint8_t,256> data; std::array<uint8_t,256U> data;
}; };
bool operator==(const BigInt &rhs, const BigInt &lhs); bool operator==(const BigInt &rhs, const BigInt &lhs);
#endif // #ifndef #ifndef BIG_INT_HPP #endif // #ifndef #ifndef OC_ISSUER_BIG_INT_HPP

474
src/json_serialisation.cpp Normal file
View File

@ -0,0 +1,474 @@
#include "model.hpp"
#include "crow/json.h"
#include "tl/expected.hpp"
#define TO_JSON(name) r[#name]=name
#define BIGINT_TO_JSON(name) r[#name]=name.to_string()
#define TO_JSON_JSON(name) r[#name]=name.to_json()
#define TO_JSON_ARRAY(name) r[#name]=list_to_json(name)
template <class T>
crow::json::wvalue list_to_json(const std::vector<T> &array) {
crow::json::wvalue::list l;
for (const auto& item : array) {
l.push_back(item.to_json());
}
return {l};
}
crow::json::wvalue list_to_json(const std::vector<unsigned int> &array) {
crow::json::wvalue::list l;
for (auto item : array) {
l.emplace_back(item);
}
return {l};
}
crow::json::wvalue PublicKey::to_json() const {
crow::json::wvalue r;
BIGINT_TO_JSON(modulus);
BIGINT_TO_JSON(public_exponent);
r["type"]="rsa public key";
return r;
}
crow::json::wvalue WeightedUrl::to_json() const {
crow::json::wvalue::list l;
crow::json::wvalue w(weight);
l.push_back(w);
l.emplace_back(url);
return l;
}
crow::json::wvalue CDD::to_json() const {
crow::json::wvalue r;
TO_JSON(additional_info);
TO_JSON(cdd_expiry_date);
TO_JSON(cdd_location);
TO_JSON(cdd_serial);
TO_JSON(cdd_signing_date);
TO_JSON(currency_divisor);
TO_JSON(currency_name);
TO_JSON_ARRAY(denominations);
BIGINT_TO_JSON(id);
TO_JSON_ARRAY(info_service);
TO_JSON(issuer_cipher_suite);
TO_JSON_JSON(issuer_public_master_key);
TO_JSON_ARRAY(mint_service);
TO_JSON(protocol_version);
TO_JSON_ARRAY(redeem_service);
TO_JSON_ARRAY(renew_service);
r["type"] = "cdd";
return r;
}
crow::json::wvalue CDDC::to_json() const {
crow::json::wvalue r;
TO_JSON_JSON(cdd);
TO_JSON(signature);
r["type"] = "cdd certificate";
return r;
}
crow::json::wvalue MintKey::to_json() const {
crow::json::wvalue r;
TO_JSON(cdd_serial);
TO_JSON(coins_expiry_date);
TO_JSON(denomination);
BIGINT_TO_JSON(id);
BIGINT_TO_JSON(issuer_id);
TO_JSON_JSON(public_mint_key);
TO_JSON(sign_coins_not_after);
TO_JSON(sign_coins_not_before);
r["type"] = "mint key";
return r;
}
crow::json::wvalue MintKeyCert::to_json() const {
crow::json::wvalue r;
TO_JSON_JSON(mint_key);
TO_JSON(signature);
r["type"] = "mint key certificate";
return r;
}
crow::json::wvalue Response::to_json() const {
crow::json::wvalue r;
TO_JSON(message_reference);
TO_JSON(status_code);
TO_JSON(status_description);
return r;
}
crow::json::wvalue ResponseCDDCSerial::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON(cdd_serial);
r["type"] = "response cdd serial";
return r;
}
tl::expected<RequestCDDCSerial, eError>
RequestCDDCSerial::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!json.has("type") || !json.has("message_reference")) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "request cdd serial") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
RequestCDDCSerial r;
r.message_reference = json["message_reference"].u();
return r;
}
}
crow::json::wvalue ResponseCDDC::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON_JSON(cddc);
r["type"] = "response cdd serial";
return r;
}
tl::expected<RequestCDDC, eError>
RequestCDDC::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("type") && json.has("message_reference") &&
json.has("cdd_serial"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request cddc") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestCDDC r;
r.cdd_serial = json["cdd_serial"].u();
r.message_reference = json["message_reference"].u();
return r;
}
}
tl::expected<RequestMKCs, eError>
RequestMKCs::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("denominations") && json.has("message_reference") &&
json.has("mint_key_ids") && json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request mint key certificates") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestMKCs r;
r.message_reference = json["message_reference"].u();
auto denominations = json["denominations"];
if (denominations.t() != crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
for (const auto& d : denominations.lo()) {
r.denominations.push_back(d.u());
}
}
auto mint_key_ids = json["mint_key_ids"];
if (mint_key_ids.t() != crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
for (const auto& k: mint_key_ids.lo()) {
auto kv = BigInt::from_string(k.s());
if (!kv.has_value()) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else {
r.mint_key_ids.push_back(*kv);
}
}
}
return r;
}
}
crow::json::wvalue ResponseMKCs::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON_ARRAY(keys);
r["type"] = "response mint key certificates";
return r;
}
crow::json::wvalue Blind::to_json() const {
crow::json::wvalue r;
BIGINT_TO_JSON(blinded_payload_hash);
BIGINT_TO_JSON(mint_key_id);
TO_JSON(reference);
r["type"] = "blinded payload hash";
return r;
}
tl::expected<Blind, eError> Blind::from_json(const crow::json::rvalue &json) {
if (!(json.has("type")
&& json.has("blinded_payload_hash")
&& json.has("mint_key_id")
&& json.has("reference"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "blinded payload hash") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
Blind r;
auto hash = BigInt::from_string(json["blinded_payload_hash"].s());
if (!hash) {
// std::cout << "invalid hash : " << json["blinded_payload_hash"].s()
// << std::endl;
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
}
r.blinded_payload_hash = hash.value();
auto key_id = BigInt::from_string(json["mint_key_id"].s());
if (!key_id) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
}
r.mint_key_id = key_id.value();
r.reference = json["reference"].s();
return r;
}
}
crow::json::wvalue BlindSignature::to_json() const {
crow::json::wvalue r;
BIGINT_TO_JSON(blind_signature);
TO_JSON(reference);
r["type"] = "blind signature";
return r;
}
tl::expected<RequestMint, eError>
RequestMint::from_string(const std::string &str) {
std::vector<Blind> blinds;
// "type": "request mint"
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("type") && json.has("message_reference") &&
json.has("transaction_reference") && json.has("blinds"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "request mint") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
RequestMint r;
r.message_reference= json["message_reference"].u();
auto tr = BigInt::from_string(json["transaction_reference"].s());
if (!tr)
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
r.transaction_reference = *tr;
if (json["blinds"].t()!=crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_VALUE_TYPE);
}
for (const auto& item : json["blinds"]) {
auto b = Blind::from_json(item);
if (!b.has_value()) {
return tl::make_unexpected(b.error());
} else {
r.blinds.push_back(b.value());
}
}
return r;
}
}
crow::json::wvalue ResponseMint::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON_ARRAY(blind_signatures);
r["type"] = "response mint";
return r;
}
crow::json::wvalue Coin::Payload::to_json() const {
crow::json::wvalue r;
TO_JSON(cdd_location);
TO_JSON(denomination);
BIGINT_TO_JSON(issuer_id);
BIGINT_TO_JSON(mint_key_id);
TO_JSON(protocol_version);
BIGINT_TO_JSON(serial);
r["type"] = "payload";
return r;
}
crow::json::wvalue Coin::to_json() const {
crow::json::wvalue r;
TO_JSON_JSON(payload);
TO_JSON(signature);
r["type"] = "coin";
return r;
}
tl::expected<Coin::Payload, eError>
Coin::Payload::from_json(const crow::json::rvalue &json) {
if (!(json.has("cdd_location") && json.has("denomination") &&
json.has("issuer_id") && json.has("mint_key_id") &&
json.has("protocol_version") && json.has("serial") &&
json.has("type"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "payload") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
Coin::Payload payload;
payload.cdd_location = json["cdd_location"].s();
payload.denomination = json["denomination"].u();
auto id = BigInt::from_string(json["issuer_id"].s());
if (!id)
tl::make_unexpected(eError::JSON_PARSE_ERROR);
payload.issuer_id = *id;
id = BigInt::from_string(json["mint_key_id"].s());
if (!id)
tl::make_unexpected(eError::JSON_PARSE_ERROR);
payload.mint_key_id = *id;
payload.protocol_version = json["protocol_version"].s();
id = BigInt::from_string(json["serial"].s());
if (!id)
tl::make_unexpected(eError::JSON_PARSE_ERROR);
payload.serial = *id;
return payload;
}
}
tl::expected<Coin, eError> Coin::from_json(const crow::json::rvalue &json) {
if (!(json.has("type") && json.has("payload") && json.has("signature"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "coin") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
auto pl = Payload::from_json(json["payload"]);
if (!pl.has_value()) {
return tl::make_unexpected(pl.error());
} else {
Coin c;
c.payload = pl.value();
c.signature = json["signature"].s();
return c;
}
}
}
crow::json::wvalue CoinStack::to_json() const {
crow::json::wvalue r;
TO_JSON_ARRAY(coins);
TO_JSON(subject);
r["type"] = "coinstack";
return r;
}
tl::expected<RequestRenew, eError>
RequestRenew::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("blinds") && json.has("coins") &&
json.has("transaction_reference") &&
json.has("message_reference") && json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request renew") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else if ((json["coins"].t() != crow::json::type::List) ||
(json["blinds"].t() != crow::json::type::List)) {
return tl::make_unexpected(eError::JSON_WRONG_VALUE_TYPE);
} else {
RequestRenew r;
for (const auto& item : json["coins"]) {
auto coin = Coin::from_json(item);
if (!coin.has_value()) {
return tl::make_unexpected(coin.error());
} else {
r.coins.push_back(coin.value());
}
}
for (const auto& item : json["blinds"]) {
auto blind = Blind::from_json(item);
if (!blind.has_value()) {
return tl::make_unexpected(blind.error());
} else {
r.blinds.push_back(blind.value());
}
}
r.message_reference = json["message_reference"].u();
r.transaction_reference = json["transaction_reference"].s();
return r;
}
}
crow::json::wvalue ResponseDelay::to_json() const {
crow::json::wvalue r = Response::to_json();
r["type"] = "response delay";
return r;
}
tl::expected<RequestResume, eError>
RequestResume::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("transaction_reference") &&
json.has("message_reference") && json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request resume") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestResume r;
r.message_reference = json["message_reference"].u();
auto tr = BigInt::from_string(json["transaction_reference"].s());
if (!tr)
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
r.transaction_reference = *tr;
return r;
}
}
tl::expected<RequestRedeem, eError>
RequestRedeem::from_string(const std::string &str) {
// "type":
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("coins") && json.has("message_reference") &&
json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request redeem") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestRedeem r;
r.message_reference = json["message_reference"].u();
if (json["coins"].t() != crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_VALUE_TYPE);
}
for (const auto& item : json["coins"]) {
auto coin = Coin::from_json(item);
if (!coin.has_value()) {
return tl::make_unexpected(coin.error());
} else {
r.coins.push_back(coin.value());
}
}
return r;
}
}
crow::json::wvalue ResponseRedeem::to_json() const {
crow::json::wvalue r = Response::to_json();
r["type"] = "response redeem";
return r;
}

View File

@ -1,22 +1,22 @@
#include "crow.h" #include "crow.h"
#include "crow/common.h" #include "crow/common.h"
#include "crow/http_parser_merged.h"
#include "crow/http_response.h" #include "crow/http_response.h"
#include "model.hpp" #include "model.hpp"
int main() { int main() {
crow::SimpleApp app; crow::SimpleApp app;
std::shared_ptr<Model> model = Model::getModel("simple"); std::shared_ptr<Model> model = Model::get_model("simple");
CROW_ROUTE(app, "/cddc") CROW_ROUTE(app, "/cddc")
.methods(crow::HTTPMethod::POST)([&model](const crow::request &req) { .methods(crow::HTTPMethod::POST)
([&model](const crow::request &req) {
auto req_cddc = RequestCDDC::from_string(req.body); auto req_cddc = RequestCDDC::from_string(req.body);
if (!req_cddc) { if (!req_cddc) {
return crow::response(crow::status::BAD_REQUEST); return crow::response(crow::status::BAD_REQUEST);
} else { } else {
ResponseCDDC res; ResponseCDDC res;
res.message_reference = req_cddc->message_reference; res.message_reference = req_cddc->message_reference;
auto cddc = model->getCDDC(req_cddc->cdd_serial); auto cddc = model->get_cddc(req_cddc->cdd_serial);
if (!cddc) { if (!cddc) {
res.status_code = crow::status::NOT_FOUND; res.status_code = crow::status::NOT_FOUND;
} else { } else {
@ -36,7 +36,7 @@ int main() {
ResponseCDDCSerial res; ResponseCDDCSerial res;
res.message_reference = req->message_reference; res.message_reference = req->message_reference;
auto cddc = model->getCurrentCDDC(); auto cddc = model->get_current_cddc();
if (!cddc) { if (!cddc) {
res.status_code = crow::status::NOT_FOUND; res.status_code = crow::status::NOT_FOUND;
} else { } else {
@ -47,8 +47,8 @@ int main() {
} }
}); });
CROW_ROUTE(app, "/mkcs") CROW_ROUTE(app, "/mkcs").methods(crow::HTTPMethod::POST)
.methods(crow::HTTPMethod::POST)([&model](const crow::request &request) { ([&model](const crow::request &request) {
auto req = RequestMKCs::from_string(request.body); auto req = RequestMKCs::from_string(request.body);
if (!req) { if (!req) {
return crow::response(crow::status::BAD_REQUEST); return crow::response(crow::status::BAD_REQUEST);
@ -61,8 +61,8 @@ int main() {
} }
}); });
CROW_ROUTE(app, "/mint") CROW_ROUTE(app, "/mint").methods(crow::HTTPMethod::POST)
.methods(crow::HTTPMethod::POST)([&model](const crow::request &request) { ([&model](const crow::request &request) {
auto req = RequestMint::from_string(request.body); auto req = RequestMint::from_string(request.body);
if (!req) { if (!req) {
return crow::response(crow::status::BAD_REQUEST); return crow::response(crow::status::BAD_REQUEST);
@ -70,8 +70,9 @@ int main() {
ResponseMint res; ResponseMint res;
res.message_reference = req->message_reference; res.message_reference = req->message_reference;
/// \todo change argument transaction_reference to bigint /// \todo change argument transaction_reference to bigint
auto minted = model->mint(req->transaction_reference.to_string(), req->blinds); auto minted =
model->mint(req->transaction_reference.to_string(), req->blinds);
res.blind_signatures = minted; res.blind_signatures = minted;
res.status_code = crow::status::OK; res.status_code = crow::status::OK;

View File

@ -1,522 +1,56 @@
#include "model.hpp" #include "model.hpp"
#include "crow/json.h"
#include "tl/expected.hpp" #include "tl/expected.hpp"
#define TO_JSON(name) r[#name]=name
#define BIGINT_TO_JSON(name) r[#name]=name.to_string()
#define TO_JSON_JSON(name) r[#name]=name.to_json()
#define TO_JSON_ARRAY(name) r[#name]=list_to_json(name)
template <class T>
crow::json::wvalue list_to_json(const std::vector<T> &array) {
crow::json::wvalue::list l;
for (auto item : array)
l.push_back(item.to_json());
return crow::json::wvalue(l);
}
crow::json::wvalue list_to_json(const std::vector<unsigned int> &array) {
crow::json::wvalue::list l;
for (auto item : array)
l.push_back(item);
return crow::json::wvalue(l);
}
crow::json::wvalue PublicKey::to_json() const {
crow::json::wvalue r;
BIGINT_TO_JSON(modulus);
BIGINT_TO_JSON(public_exponent);
r["type"]="rsa public key";
return r;
}
crow::json::wvalue WeightedUrl::to_json() const {
crow::json::wvalue::list l;
crow::json::wvalue w(weight);
l.push_back(w);
l.push_back(url);
return l;
}
crow::json::wvalue CDD::to_json() const {
crow::json::wvalue r;
TO_JSON(additional_info);
TO_JSON(cdd_expiry_date);
TO_JSON(cdd_location);
TO_JSON(cdd_serial);
TO_JSON(cdd_signing_date);
TO_JSON(currency_divisor);
TO_JSON(currency_name);
TO_JSON_ARRAY(denominations);
BIGINT_TO_JSON(id);
TO_JSON_ARRAY(info_service);
TO_JSON(issuer_cipher_suite);
TO_JSON_JSON(issuer_public_master_key);
TO_JSON_ARRAY(mint_service);
TO_JSON(protocol_version);
TO_JSON_ARRAY(redeem_service);
TO_JSON_ARRAY(renew_service);
r["type"] = "cdd";
return r;
}
crow::json::wvalue CDDC::to_json() const {
crow::json::wvalue r;
TO_JSON_JSON(cdd);
TO_JSON(signature);
r["type"] = "cdd certificate";
return r;
}
crow::json::wvalue MintKey::to_json() const {
crow::json::wvalue r;
TO_JSON(cdd_serial);
TO_JSON(coins_expiry_date);
TO_JSON(denomination);
BIGINT_TO_JSON(id);
BIGINT_TO_JSON(issuer_id);
TO_JSON_JSON(public_mint_key);
TO_JSON(sign_coins_not_after);
TO_JSON(sign_coins_not_before);
r["type"] = "mint key";
return r;
}
crow::json::wvalue MintKeyCert::to_json() const {
crow::json::wvalue r;
TO_JSON_JSON(mint_key);
TO_JSON(signature);
r["type"] = "mint key certificate";
return r;
}
crow::json::wvalue Response::to_json() const {
crow::json::wvalue r;
TO_JSON(message_reference);
TO_JSON(status_code);
TO_JSON(status_description);
return r;
}
crow::json::wvalue ResponseCDDCSerial::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON(cdd_serial);
r["type"] = "response cdd serial";
return r;
}
tl::expected<RequestCDDCSerial, eError>
RequestCDDCSerial::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!json.has("type") || !json.has("message_reference")) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "request cdd serial") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
RequestCDDCSerial r;
r.message_reference = json["message_reference"].u();
return r;
}
}
crow::json::wvalue ResponseCDDC::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON_JSON(cddc);
r["type"] = "response cdd serial";
return r;
}
tl::expected<RequestCDDC, eError>
RequestCDDC::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("type") && json.has("message_reference") &&
json.has("cdd_serial"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request cddc") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestCDDC r;
r.cdd_serial = json["cdd_serial"].u();
r.message_reference = json["message_reference"].u();
return r;
}
}
tl::expected<RequestMKCs, eError>
RequestMKCs::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("denominations") && json.has("message_reference") &&
json.has("mint_key_ids") && json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request mint key certificates") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestMKCs r;
r.message_reference = json["message_reference"].u();
auto denominations = json["denominations"];
if (denominations.t() != crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
for (auto d : denominations.lo()) {
r.denominations.push_back(d.u());
}
}
auto mint_key_ids = json["mint_key_ids"];
if (mint_key_ids.t() != crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
for (auto k: mint_key_ids.lo()) {
auto kv = BigInt::from_string(k.s());
if (!kv.has_value()) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else {
r.mint_key_ids.push_back(*kv);
}
}
}
return r;
}
}
crow::json::wvalue ResponseMKCs::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON_ARRAY(keys);
r["type"] = "response mint key certificates";
return r;
}
crow::json::wvalue Blind::to_json() const {
crow::json::wvalue r;
BIGINT_TO_JSON(blinded_payload_hash);
BIGINT_TO_JSON(mint_key_id);
TO_JSON(reference);
r["type"] = "blinded payload hash";
return r;
}
tl::expected<Blind, eError> Blind::from_json(const crow::json::rvalue &json) {
if (!(json.has("type")
&& json.has("blinded_payload_hash")
&& json.has("mint_key_id")
&& json.has("reference"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "blinded payload hash") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
Blind r;
auto hash = BigInt::from_string(json["blinded_payload_hash"].s());
if (!hash) {
// std::cout << "invalid hash : " << json["blinded_payload_hash"].s()
// << std::endl;
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
}
r.blinded_payload_hash = hash.value();
auto key_id = BigInt::from_string(json["mint_key_id"].s());
if (!key_id) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
}
r.mint_key_id = key_id.value();
r.reference = json["reference"].s();
return r;
}
}
crow::json::wvalue BlindSignature::to_json() const {
crow::json::wvalue r;
BIGINT_TO_JSON(blind_signature);
TO_JSON(reference);
r["type"] = "blind signature";
return r;
}
tl::expected<RequestMint, eError>
RequestMint::from_string(const std::string &str) {
std::vector<Blind> blinds;
// "type": "request mint"
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("type") && json.has("message_reference") &&
json.has("transaction_reference") && json.has("blinds"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "request mint") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
RequestMint r;
r.message_reference= json["message_reference"].u();
auto tr = BigInt::from_string(json["transaction_reference"].s());
if (!tr)
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
r.transaction_reference = *tr;
if (json["blinds"].t()!=crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_VALUE_TYPE);
}
for (auto item : json["blinds"]) {
auto b = Blind::from_json(item);
if (!b.has_value()) {
return tl::make_unexpected(b.error());
} else {
r.blinds.push_back(b.value());
}
}
return r;
}
}
crow::json::wvalue ResponseMint::to_json() const {
crow::json::wvalue r = Response::to_json();
TO_JSON_ARRAY(blind_signatures);
r["type"] = "response mint";
return r;
}
crow::json::wvalue Coin::Payload::to_json() const {
crow::json::wvalue r;
TO_JSON(cdd_location);
TO_JSON(denomination);
BIGINT_TO_JSON(issuer_id);
BIGINT_TO_JSON(mint_key_id);
TO_JSON(protocol_version);
BIGINT_TO_JSON(serial);
r["type"] = "payload";
return r;
}
crow::json::wvalue Coin::to_json() const {
crow::json::wvalue r;
TO_JSON_JSON(payload);
TO_JSON(signature);
r["type"] = "coin";
return r;
}
tl::expected<Coin::Payload, eError>
Coin::Payload::from_json(const crow::json::rvalue &json) {
if (!(json.has("cdd_location") && json.has("denomination") &&
json.has("issuer_id") && json.has("mint_key_id") &&
json.has("protocol_version") && json.has("serial") &&
json.has("type"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "payload") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
Coin::Payload payload;
payload.cdd_location = json["cdd_location"].s();
payload.denomination = json["denomination"].u();
auto id = BigInt::from_string(json["issuer_id"].s());
if (!id)
tl::make_unexpected(eError::JSON_PARSE_ERROR);
payload.issuer_id = *id;
id = BigInt::from_string(json["mint_key_id"].s());
if (!id)
tl::make_unexpected(eError::JSON_PARSE_ERROR);
payload.mint_key_id = *id;
payload.protocol_version = json["protocol_version"].s();
id = BigInt::from_string(json["serial"].s());
if (!id)
tl::make_unexpected(eError::JSON_PARSE_ERROR);
payload.serial = *id;
return payload;
}
}
tl::expected<Coin, eError> Coin::from_json(const crow::json::rvalue &json) {
if (!(json.has("type") && json.has("payload") && json.has("signature"))) {
return tl::make_unexpected(eError::JSON_ERROR);
} else if (json["type"] != "coin") {
return tl::make_unexpected(eError::JSON_ERROR);
} else {
auto pl = Payload::from_json(json["payload"]);
if (!pl.has_value()) {
return tl::make_unexpected(pl.error());
} else {
Coin c;
c.payload = pl.value();
c.signature = json["signature"].s();
return c;
}
}
}
crow::json::wvalue CoinStack::to_json() const {
crow::json::wvalue r;
TO_JSON_ARRAY(coins);
TO_JSON(subject);
r["type"] = "coinstack";
return r;
}
tl::expected<RequestRenew, eError>
RequestRenew::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("blinds") && json.has("coins") &&
json.has("transaction_reference") &&
json.has("message_reference") && json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request renew") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else if ((json["coins"].t() != crow::json::type::List) ||
(json["blinds"].t() != crow::json::type::List)) {
return tl::make_unexpected(eError::JSON_WRONG_VALUE_TYPE);
} else {
RequestRenew r;
for (auto item : json["coins"]) {
auto coin = Coin::from_json(item);
if (!coin.has_value()) {
return tl::make_unexpected(coin.error());
} else {
r.coins.push_back(coin.value());
}
}
for (auto item : json["blinds"]) {
auto blind = Blind::from_json(item);
if (!blind.has_value()) {
return tl::make_unexpected(blind.error());
} else {
r.blinds.push_back(blind.value());
}
}
r.message_reference = json["message_reference"].u();
r.transaction_reference = json["transaction_reference"].s();
return r;
}
}
crow::json::wvalue ResponseDelay::to_json() const {
crow::json::wvalue r = Response::to_json();
r["type"] = "response delay";
return r;
}
tl::expected<RequestResume, eError>
RequestResume::from_string(const std::string &str) {
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("transaction_reference") &&
json.has("message_reference") && json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request resume") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestResume r;
r.message_reference = json["message_reference"].u();
auto tr = BigInt::from_string(json["transaction_reference"].s());
if (!tr)
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
r.transaction_reference = *tr;
return r;
}
}
tl::expected<RequestRedeem, eError>
RequestRedeem::from_string(const std::string &str) {
// "type":
auto json = crow::json::load(str);
if (!json) {
return tl::make_unexpected(eError::JSON_PARSE_ERROR);
} else if (!(json.has("coins") && json.has("message_reference") &&
json.has("type"))) {
return tl::make_unexpected(eError::JSON_MISSING_KEY);
} else if (json["type"] != "request redeem") {
return tl::make_unexpected(eError::JSON_WRONG_REQUEST_TYPE);
} else {
RequestRedeem r;
r.message_reference = json["message_reference"].u();
if (json["coins"].t() != crow::json::type::List) {
return tl::make_unexpected(eError::JSON_WRONG_VALUE_TYPE);
}
for (auto item : json["coins"]) {
auto coin = Coin::from_json(item);
if (!coin.has_value()) {
return tl::make_unexpected(coin.error());
} else {
r.coins.push_back(coin.value());
}
}
return r;
}
}
crow::json::wvalue ResponseRedeem::to_json() const {
crow::json::wvalue r = Response::to_json();
r["type"] = "response redeem";
return r;
}
using std::cout; using std::cout;
using std::endl; using std::endl;
#define UNUSED(s) /* s */
/** this is for now our sample model */ /** this is for now our sample model */
class DefaultModel : public Model { class DefaultModel : public Model {
public: public:
DefaultModel() {} DefaultModel() = default;
tl::expected<CDDC *, bool> getCDDC(unsigned int cdd_serial) override {
cout << __FUNCTION__ << "(" << cdd_serial << ")" << endl;
return &m_cddc;
};
tl::expected<CDDC *, bool> getCurrentCDDC() override { tl::expected<CDDC *, bool> get_cddc(unsigned int cdd_serial) override {
cout << __FUNCTION__ << "()" << endl; cout << __FUNCTION__ << "(" << cdd_serial << ")" << endl; // NOLINT(clion-misra-cpp2008-5-2-12)
return &m_cddc;
};
return &m_cddc; tl::expected<CDDC *, bool> get_current_cddc() override {
} cout << __FUNCTION__ << "()" << endl;
std::vector<BlindSignature> mint(const std::string& transaction_reference, return &m_cddc;
const std::vector<Blind> &blinds) override { }
std::vector<BlindSignature> res;
cout << __FUNCTION__ << "("
<< ")" << endl;
return res; std::vector<BlindSignature>
} mint(const std::string & UNUSED(transaction_reference),
const std::vector<Blind> &UNUSED(blinds)) override {
std::vector<BlindSignature> res;
cout << __FUNCTION__ << "("
<< ")" << endl;
const std::vector<MintKeyCert> return res;
getMKCs(const std::vector<unsigned int> &denominations, }
const std::vector<BigInt> &mint_key_ids) override {
std::vector<MintKeyCert> res; std::vector<MintKeyCert>
cout << __FUNCTION__ << endl; getMKCs(const std::vector<unsigned int> & UNUSED(denominations),
return res; const std::vector<BigInt> & UNUSED(mint_key_ids)) override {
} std::vector<MintKeyCert> res;
bool redeem(const std::vector<Coin> &coins) override { cout << __FUNCTION__ << endl;
cout << __FUNCTION__ << endl; return res;
return false; }
}
bool redeem(const std::vector<Coin> &UNUSED(coins)) override {
cout << __FUNCTION__ << endl;
return false;
}
private: private:
CDDC m_cddc; CDDC m_cddc;
}; };
std::unique_ptr<Model> Model::getModel(const std::string & /*backend_name*/) { std::unique_ptr<Model> Model::get_model(const std::string & /*backend_name*/) {
cout << __FUNCTION__ << endl; cout << __FUNCTION__ << endl;
//:wq //:wq
// if (backend_name=="default") // if (backend_name=="default")
return std::make_unique<DefaultModel>(); return std::make_unique<DefaultModel>();
} }

View File

@ -1,5 +1,5 @@
#ifndef MODEL_HPP #ifndef OC_ISSUER_MODEL_HPP
#define MODEL_HPP #define OC_ISSUER_MODEL_HPP
#include <chrono> #include <chrono>
#include <memory> #include <memory>
@ -15,14 +15,14 @@ struct PublicKey {
BigInt modulus; //: "daaa63ddda38c189b8c49020c8276adbe0a695685a...", BigInt modulus; //: "daaa63ddda38c189b8c49020c8276adbe0a695685a...",
BigInt public_exponent;//: 65537, BigInt public_exponent;//: 65537,
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
struct WeightedUrl { struct WeightedUrl {
uint32_t weight; uint32_t weight;
std::string url; std::string url;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
/** @brief currency description document /** @brief currency description document
@ -58,14 +58,14 @@ struct CDD {
std::vector<WeightedUrl> redeem_service; std::vector<WeightedUrl> redeem_service;
std::vector<WeightedUrl> renew_service; std::vector<WeightedUrl> renew_service;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
struct CDDC { struct CDDC {
CDD cdd; CDD cdd;
std::string signature; std::string signature;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
struct MintKey { struct MintKey {
@ -79,14 +79,14 @@ struct MintKey {
std::string sign_coins_not_after; std::string sign_coins_not_after;
std::string sign_coins_not_before; std::string sign_coins_not_before;
// "type": "mint key" // "type": "mint key"
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
struct MintKeyCert { struct MintKeyCert {
MintKey mint_key; MintKey mint_key;
std::string signature; std::string signature;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
enum class eError { enum class eError {
@ -103,7 +103,7 @@ struct Response {
unsigned int status_code; unsigned int status_code;
std::string status_description; std::string status_description;
virtual crow::json::wvalue to_json() const; [[nodiscard]] virtual crow::json::wvalue to_json() const=0;
}; };
struct RequestCDDCSerial { struct RequestCDDCSerial {
@ -114,9 +114,9 @@ struct RequestCDDCSerial {
}; };
struct ResponseCDDCSerial : Response { struct ResponseCDDCSerial : Response {
unsigned int cdd_serial; unsigned int cdd_serial{0U};
crow::json::wvalue to_json() const override; [[nodiscard]] crow::json::wvalue to_json() const override;
}; };
struct RequestCDDC { struct RequestCDDC {
@ -129,7 +129,7 @@ struct RequestCDDC {
struct ResponseCDDC : Response { struct ResponseCDDC : Response {
CDDC cddc; CDDC cddc;
crow::json::wvalue to_json() const override; [[nodiscard]] crow::json::wvalue to_json() const override;
}; };
struct RequestMKCs { struct RequestMKCs {
@ -144,21 +144,21 @@ struct RequestMKCs {
struct ResponseMKCs : Response { struct ResponseMKCs : Response {
std::vector<MintKeyCert> keys; std::vector<MintKeyCert> keys;
crow::json::wvalue to_json() const override; [[nodiscard]] crow::json::wvalue to_json() const override;
}; };
struct Blind { struct Blind {
BigInt blinded_payload_hash; //bigint BigInt blinded_payload_hash; //bigint
BigInt mint_key_id; //bigint BigInt mint_key_id; //bigint
std::string reference; std::string reference;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
static tl::expected<Blind, eError> from_json(const crow::json::rvalue &json); static tl::expected<Blind, eError> from_json(const crow::json::rvalue &json);
}; };
struct BlindSignature { struct BlindSignature {
BigInt blind_signature; BigInt blind_signature;
std::string reference; std::string reference;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
struct RequestMint { struct RequestMint {
@ -173,7 +173,7 @@ struct RequestMint {
struct ResponseMint : Response { struct ResponseMint : Response {
std::vector<BlindSignature> blind_signatures; std::vector<BlindSignature> blind_signatures;
crow::json::wvalue to_json() const override; [[nodiscard]] crow::json::wvalue to_json() const override;
}; };
struct Coin { struct Coin {
@ -185,14 +185,14 @@ struct Coin {
std::string protocol_version; std::string protocol_version;
BigInt serial; BigInt serial;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
static tl::expected<Payload,eError> from_json(const crow::json::rvalue& json); static tl::expected<Payload,eError> from_json(const crow::json::rvalue& json);
}; };
Payload payload; Payload payload;
std::string signature; std::string signature;
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
static tl::expected<Coin, eError> from_json(const crow::json::rvalue &json); static tl::expected<Coin, eError> from_json(const crow::json::rvalue &json);
}; };
@ -200,7 +200,7 @@ struct CoinStack {
std::vector<Coin> coins; std::vector<Coin> coins;
std::string subject; std::string subject;
// "type": "coinstack" // "type": "coinstack"
crow::json::wvalue to_json() const; [[nodiscard]] crow::json::wvalue to_json() const;
}; };
struct RequestRenew { struct RequestRenew {
@ -214,7 +214,7 @@ struct RequestRenew {
}; };
struct ResponseDelay : Response { struct ResponseDelay : Response {
crow::json::wvalue to_json() const override; [[nodiscard]] crow::json::wvalue to_json() const override;
}; };
struct RequestResume { struct RequestResume {
@ -236,12 +236,12 @@ struct RequestRedeem {
}; };
struct ResponseRedeem : Response { struct ResponseRedeem : Response {
crow::json::wvalue to_json() const override; [[nodiscard]] crow::json::wvalue to_json() const override;
}; };
class Model { class Model {
public: public:
virtual ~Model(){}; virtual ~Model()=default;
/** /**
* return the CurrencyDocumentDescription certifikate for a specific * return the CurrencyDocumentDescription certifikate for a specific
@ -249,13 +249,13 @@ public:
* [see spec](https://opencoin.org/0.4/schemata.html#cddc) * [see spec](https://opencoin.org/0.4/schemata.html#cddc)
* @return returns a pointer to the CDDC if successful, false otherwise * @return returns a pointer to the CDDC if successful, false otherwise
*/ */
virtual tl::expected<CDDC *, bool> getCDDC(unsigned int cdd_serial) = 0; virtual tl::expected<CDDC *, bool> get_cddc(unsigned int cdd_serial) = 0;
/** /**
* return the CurrencyDocumentDescription certifikate * return the CurrencyDocumentDescription certifikate
* [see spec](https://opencoin.org/0.4/schemata.html#cddc) * [see spec](https://opencoin.org/0.4/schemata.html#cddc)
* @return returns a pointer to the CDDC if successful, false otherwise * @return returns a pointer to the CDDC if successful, false otherwise
*/virtual tl::expected<CDDC *, bool> getCurrentCDDC() = 0; */virtual tl::expected<CDDC *, bool> get_current_cddc() = 0;
/** /**
* return the MintKey certificates for a given list of denominations * return the MintKey certificates for a given list of denominations
@ -266,7 +266,7 @@ public:
* *
* @return mint key certificates for given denominations and mint_key_ids * @return mint key certificates for given denominations and mint_key_ids
*/ */
virtual const std::vector<MintKeyCert> virtual std::vector<MintKeyCert>
getMKCs(const std::vector<unsigned int> &denominations, getMKCs(const std::vector<unsigned int> &denominations,
const std::vector<BigInt> &mint_key_ids) = 0; const std::vector<BigInt> &mint_key_ids) = 0;
@ -300,9 +300,9 @@ public:
* *
* @return pointer to backend instance or null on invalid backend name * @return pointer to backend instance or null on invalid backend name
*/ */
static std::unique_ptr<Model> getModel(const std::string &backend_name); static std::unique_ptr<Model> get_model(const std::string &backend_name);
private: private:
}; };
#endif // #ifndef MODEL_HPP #endif // #ifndef OC_ISSUER_MODEL_HPP

View File

@ -2,7 +2,7 @@
#include <catch2/catch_test_macros.hpp> #include <catch2/catch_test_macros.hpp>
TEST_CASE("BigInt::from_string", "[big_int]") { TEST_CASE("BigInt::from_string", "[big_int]") {
std::string VALID [] = { const std::string VALID [] = {
"1", "1",
"12", "12",
"123", "123",
@ -17,10 +17,10 @@ TEST_CASE("BigInt::from_string", "[big_int]") {
"abcdef1" "abcdef1"
}; };
for (size_t i= 0; i<sizeof(VALID)/sizeof(VALID[0]);i++) { for (const auto & i : VALID) {
auto b = BigInt::from_string(VALID[i]); auto b = BigInt::from_string(i);
REQUIRE(b->to_string() == VALID[i]);
REQUIRE(b.has_value()); REQUIRE(b.has_value());
REQUIRE(b->to_string() == i);
} }
auto invalid_hex = "aabbcc.."; auto invalid_hex = "aabbcc..";

250
test/test_crypto.cpp Normal file
View File

@ -0,0 +1,250 @@
#include <catch2/catch_test_macros.hpp>
//#include "cryptlib.h"
//#include "integer.h"
//#include "nbtheory.h"
//#include "osrng.h"
//#include "rsa.h"
//#include "sha.h"
#include <iostream>
#include <stdexcept>
/*
CryptoPP::Integer blind_signature(const CryptoPP::SecByteBlock &orig,
const CryptoPP::Integer &r,
const CryptoPP::RSA::PublicKey &pub_key,
const CryptoPP::RSA::PrivateKey &priv_key) {
using namespace CryptoPP;
using std::cout;
using std::endl;
// Convenience
const Integer &n = pub_key.GetModulus();
const Integer &e = pub_key.GetPublicExponent();
// const Integer &d = priv_key.GetPrivateExponent();
// For sizing the hashed message buffer. This should be SHA256 size.
const size_t sig_size = UnsignedMin(SHA256::BLOCKSIZE, n.ByteCount());
// Scratch
SecByteBlock buff_1, buff_2, buff_3;
Integer m(orig.data(), orig.size());
cout << "Message: " << std::hex << m << endl;
// Hash message per Rabin (1979)
buff_1.resize(sig_size);
SHA256 hash_1;
hash_1.CalculateTruncatedDigest(buff_1, buff_1.size(), orig, orig.size());
// H(m) as Integer
Integer hm(buff_1.data(), buff_1.size());
cout << "H(m): " << std::hex << hm << endl;
// Blinding factor
Integer b = a_exp_b_mod_c(r, e, n);
cout << "Random: " << std::hex << b << endl;
// Alice blinded message
Integer mm = a_times_b_mod_c(hm, b, n);
cout << "Blind msg: " << std::hex << mm << endl;
AutoSeededRandomPool prng;
// Bob sign
Integer ss = priv_key.CalculateInverse(prng, mm);
cout << "Blind sign: " << ss << endl;
return ss;
}
CryptoPP::Integer unblind_signature(const CryptoPP::Integer &ss,
const CryptoPP::Integer &r,
const CryptoPP::RSA::PublicKey &pub_key) {
const CryptoPP::Integer &n = pub_key.GetModulus();
CryptoPP::Integer s = a_times_b_mod_c(ss, r.InverseMod(n), n);
return s;
}
CryptoPP::Integer verify(CryptoPP::Integer const &ss,
const CryptoPP::Integer &r,
const CryptoPP::RSA::PublicKey &pub_key) {
CryptoPP::Integer s = unblind_signature(ss, r, pub_key);
CryptoPP::Integer v = pub_key.ApplyFunction(s);
return v;
}
TEST_CASE("cryptopp1", "[crypto]") {
using namespace CryptoPP;
using std::cout;
using std::endl;
using std::runtime_error;
// Bob artificially small key pair
AutoSeededRandomPool prng;
RSA::PrivateKey priv_key;
priv_key.GenerateRandomWithKeySize(prng, 64U);
RSA::PublicKey pub_key(priv_key);
// Convenience
const Integer &n = pub_key.GetModulus();
const Integer &e = pub_key.GetPublicExponent();
const Integer &d = priv_key.GetPrivateExponent();
// Print params
cout << "Pub mod: " << std::hex << pub_key.GetModulus() << endl;
cout << "Pub exp: " << std::hex << e << endl;
cout << "Priv mod: " << std::hex << priv_key.GetModulus() << endl;
cout << "Priv exp: " << std::hex << d << endl;
const char *MESSAGE = "secret";
SecByteBlock orig((const byte *) MESSAGE, 6U);
// Alice blinding
Integer r;
do {
r.Randomize(prng, Integer::One(), n - Integer::One());
} while (!RelativelyPrime(r, n));
CryptoPP::Integer ss = blind_signature(orig,
r,
pub_key,
priv_key);
// Alice checks s(s'(x)) = x. This is from Chaum's paper
Integer c = pub_key.ApplyFunction(ss);
cout << "Check sign: " << c << endl;
//if (c != mm) {
// throw runtime_error("Alice cross-check failed");
// }
// Alice remove blinding
Integer s = unblind_signature(ss, r, pub_key);
cout << "Unblind sign: " << s << endl;
// Eve verifies
Integer v = verify(ss, r, pub_key);
cout << "Verify: " << std::hex << v << endl;
// Scratch
SecByteBlock buff_2, buff_3;
// Convert to a string
size_t req = v.MinEncodedSize();
buff_2.resize(req);
v.Encode(&buff_2[0], buff_2.size());
// Hash message per Rabin (1979)
const size_t sig_size = UnsignedMin(SHA256::BLOCKSIZE, n.ByteCount());
buff_3.resize(sig_size);
SHA256 hash_2;
hash_2.CalculateTruncatedDigest(buff_3, buff_3.size(), orig, orig.size());
// Constant time compare
bool equal = buff_2.size() == buff_3.size() &&
VerifyBufsEqual(buff_2.data(), buff_3.data(), buff_3.size());
if (!equal) {
throw runtime_error("Eve verified failed");
}
cout << "Verified signature" << endl;
}
*/
/*
TEST_CASE("cryptopp", "[crypto]") {
using namespace CryptoPP;
using std::cout;
using std::endl;
using std::runtime_error;
// Bob artificially small key pair
AutoSeededRandomPool prng;
RSA::PrivateKey priv_key;
priv_key.GenerateRandomWithKeySize(prng, 64U);
RSA::PublicKey pub_key(priv_key);
// Convenience
const Integer &n = pub_key.GetModulus();
const Integer &e = pub_key.GetPublicExponent();
const Integer &d = priv_key.GetPrivateExponent();
// Print params
cout << "Pub mod: " << std::hex << pub_key.GetModulus() << endl;
cout << "Pub exp: " << std::hex << e << endl;
cout << "Priv mod: " << std::hex << priv_key.GetModulus() << endl;
cout << "Priv exp: " << std::hex << d << endl;
// For sizing the hashed message buffer. This should be SHA256 size.
const size_t sig_size = UnsignedMin(SHA256::BLOCKSIZE, n.ByteCount());
// Scratch
SecByteBlock buff_1, buff_2, buff_3;
// Alice original message to be signed by Bob
SecByteBlock orig((const byte *) "secret", 6U);
Integer m(orig.data(), orig.size());
cout << "Message: " << std::hex << m << endl;
// Hash message per Rabin (1979)
buff_1.resize(sig_size);
SHA256 hash_1;
hash_1.CalculateTruncatedDigest(buff_1, buff_1.size(), orig, orig.size());
// H(m) as Integer
Integer hm(buff_1.data(), buff_1.size());
cout << "H(m): " << std::hex << hm << endl;
// Alice blinding
Integer r;
do {
r.Randomize(prng, Integer::One(), n - Integer::One());
} while (!RelativelyPrime(r, n));
// Blinding factor
Integer b = a_exp_b_mod_c(r, e, n);
cout << "Random: " << std::hex << b << endl;
// Alice blinded message
Integer mm = a_times_b_mod_c(hm, b, n);
cout << "Blind msg: " << std::hex << mm << endl;
// Bob sign
Integer ss = priv_key.CalculateInverse(prng, mm);
cout << "Blind sign: " << ss << endl;
// Alice checks s(s'(x)) = x. This is from Chaum's paper
Integer c = pub_key.ApplyFunction(ss);
cout << "Check sign: " << c << endl;
if (c != mm) {
throw runtime_error("Alice cross-check failed");
}
// Alice remove blinding
Integer s = a_times_b_mod_c(ss, r.InverseMod(n), n);
cout << "Unblind sign: " << s << endl;
// Eve verifies
Integer v = pub_key.ApplyFunction(s);
cout << "Verify: " << std::hex << v << endl;
// Convert to a string
size_t req = v.MinEncodedSize();
buff_2.resize(req);
v.Encode(&buff_2[0], buff_2.size());
// Hash message per Rabin (1979)
buff_3.resize(sig_size);
SHA256 hash_2;
hash_2.CalculateTruncatedDigest(buff_3, buff_3.size(), orig, orig.size());
// Constant time compare
bool equal = buff_2.size() == buff_3.size() &&
VerifyBufsEqual(buff_2.data(), buff_3.data(), buff_3.size());
if (!equal) {
throw runtime_error("Eve verified failed");
}
cout << "Verified signature" << endl;
}
*/

View File

@ -12,7 +12,7 @@ TEST_CASE( "PublicKey::to_json", "[to_json]" ) {
REQUIRE( json["modulus"].dump() == "\"" + k.modulus.to_string() + "\"" ); REQUIRE( json["modulus"].dump() == "\"" + k.modulus.to_string() + "\"" );
REQUIRE( json["public_exponent"].dump() == "\"" + k.public_exponent.to_string()+"\"" ); REQUIRE( json["public_exponent"].dump() == "\"" + k.public_exponent.to_string()+"\"" );
REQUIRE( json["type"].dump() == "\"rsa public key\"" ); REQUIRE( json["type"].dump() == "\"rsa public key\"" );
REQUIRE( json.keys().size() == 3 ); REQUIRE( json.keys().size() == 3U );
} }
TEST_CASE("RequestCDDCSerial::from_string", "[from_string]") { TEST_CASE("RequestCDDCSerial::from_string", "[from_string]") {