Unverified Commit 3f465b67 authored by kladko's avatar kladko

Merge branch 'develop' of https://github.com/skalenetwork/sgxwallet into develop

 Conflicts:
	LevelDB.h
parents 43ccd5ad 82824ef2
......@@ -20,3 +20,4 @@ jobs:
run: docker build . --file Dockerfile --tag skalenetwork/sgxwallet:latest
- name: push docker image
run: docker push skalenetwork/sgxwallet:latest
......@@ -18,6 +18,10 @@ jobs:
run: git submodule update --init --recursive
- name: Build the Docker image
run: docker build . --file DockerfileSimulation --tag skalenetwork/sgxwalletsim:latest
- name: run docker image
run: docker run -v ${PWD}/sgx_data:/usr/src/sdk/sgx_data -d --network=host skalenetwork/sgxwalletsim:latest
- name: sleep and check
run: sleep 5; scripts/docker_test.py
- name: push docker image
run: docker push skalenetwork/sgxwalletsim:latest
# Created by .ignore support plugin (hsz.mobi)
.idea/
sgx-gmp/
gmp-build
tgmp-build
install-sh
......@@ -13,6 +14,10 @@ secure_enclave.edl
am--include-marker
*.o
aclocal.m4
missing
compile
depcomp
ltmain.sh
secure_enclave.signed.so
sgxgmpmath
sgxgmppi
......
......@@ -16,3 +16,6 @@
[submodule "sgx-software-enable"]
path = sgx-software-enable
url = https://github.com/intel/sgx-software-enable
[submodule "github-markdown-toc"]
path = github-markdown-toc
url = https://github.com/ekalinin/github-markdown-toc.git
......@@ -51,6 +51,7 @@
#include "RPCException.h"
#include "spdlog/spdlog.h"
#include "common.h"
int char2int(char _input) {
if (_input >= '0' && _input <= '9')
......@@ -135,11 +136,11 @@ bool hex2carray2(const char * _hex, uint64_t *_bin_len,
bool sign(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t _n, size_t _signerIndex,
char* _sig) {
//std::cerr << "ENTER SIGN" << std::endl;
//cerr << "ENTER SIGN" << endl;
auto keyStr = std::make_shared<std::string>(_encryptedKeyHex);
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = std::make_shared<std::array<uint8_t, 32>>();
auto hash = make_shared<array<uint8_t, 32>>();
uint64_t binLen;
......@@ -150,9 +151,9 @@ bool sign(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t
auto keyShare = std::make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
//std::cerr << "keyShare created" << std::endl;
//cerr << "keyShare created" << endl;
// {
auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
// }
......@@ -161,14 +162,14 @@ bool sign(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t
strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
//std::string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//strncpy(_sig, sigShareStr.c_str(), BUF_LEN);
// std::string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = std::make_shared<std::string>(test_sig);
// string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = make_shared<string>(test_sig);
// strncpy(_sig, sig_ptr->c_str(), BUF_LEN);
//std::cerr<< "sig " << _sig <<std::endl;
//cerr<< "sig " << _sig <<endl;
return true;
......@@ -185,10 +186,12 @@ char *encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key)
unsigned int encryptedLen = 0;
status = encrypt_key(eid, errStatus, errMsg, keyArray, encryptedKey, &encryptedLen);
//status = encrypt_key(eid, errStatus, errMsg, keyArray, encryptedKey, &encryptedLen);
status = encrypt_key_aes(eid, errStatus, errMsg, keyArray, encryptedKey, &encryptedLen);
if (DEBUG_PRINT) {
spdlog::info("errStatus is {}",*errStatus, " errMsg is ", errMsg );
spdlog::info("errStatus is {}",*errStatus);
spdlog::info(" errMsg is ", errMsg );
}
if (status != SGX_SUCCESS) {
......@@ -224,7 +227,8 @@ char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encry
char *plaintextKey = (char *) calloc(BUF_LEN, 1);
status = decrypt_key(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
//status = decrypt_key(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
status = decrypt_key_aes(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
if (status != SGX_SUCCESS) {
return nullptr;
......
......@@ -21,7 +21,7 @@
@date 2019
*/
using namespace std;
#include "BLSSigShare.h"
#include "BLSSignature.h"
......@@ -33,6 +33,7 @@ using namespace std;
#include "BLSCrypto.h"
#include "ServerInit.h"
#include "common.h"
#include "BLSPrivateKeyShareSGX.h"
......
cmake_minimum_required(VERSION 3.12)
project(sgxd)
cmake_minimum_required(VERSION 3.15)
project(sgxwallet)
set(CMAKE_CXX_STANDARD 14)
include_directories(.)
include_directories(libff/libff/algebra/curves/alt_bn128)
include_directories(libff/libff/algebra/curves/bn128)
include_directories(libff/libff/algebra/curves/edwards)
include_directories(libff/libff/algebra/curves/mnt)
include_directories(libff/libff/algebra/curves/mnt/mnt4)
include_directories(libff/libff/algebra/curves/mnt/mnt6)
include_directories(libff/libff/common/default_types)
include_directories(secure_enclave)
include_directories(sgx-software-enable)
include_directories(tgmp-build)
include_directories(tgmp-build/include)
add_custom_target(sgxd COMMAND make all
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
SOURCES
libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp
libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp
libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp
libff/libff/algebra/curves/alt_bn128/alt_bn128_init.hpp
libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.cpp
libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp
libff/libff/algebra/curves/bn128/bn128_g1.cpp
libff/libff/algebra/curves/bn128/bn128_g1.hpp
libff/libff/algebra/curves/bn128/bn128_g2.cpp
libff/libff/algebra/curves/bn128/bn128_g2.hpp
libff/libff/algebra/curves/bn128/bn128_gt.cpp
libff/libff/algebra/curves/bn128/bn128_gt.hpp
libff/libff/algebra/curves/bn128/bn128_init.cpp
libff/libff/algebra/curves/bn128/bn128_init.hpp
libff/libff/algebra/curves/bn128/bn128_pairing.cpp
libff/libff/algebra/curves/bn128/bn128_pairing.hpp
libff/libff/algebra/curves/bn128/bn128_pp.cpp
libff/libff/algebra/curves/bn128/bn128_pp.hpp
libff/libff/algebra/curves/bn128/bn_utils.hpp
libff/libff/algebra/curves/bn128/bn_utils.tcc
libff/libff/algebra/curves/edwards/edwards_g1.cpp
libff/libff/algebra/curves/edwards/edwards_g1.hpp
libff/libff/algebra/curves/edwards/edwards_g2.cpp
libff/libff/algebra/curves/edwards/edwards_g2.hpp
libff/libff/algebra/curves/edwards/edwards_init.cpp
libff/libff/algebra/curves/edwards/edwards_init.hpp
libff/libff/algebra/curves/edwards/edwards_pairing.cpp
libff/libff/algebra/curves/edwards/edwards_pairing.hpp
libff/libff/algebra/curves/edwards/edwards_pp.cpp
libff/libff/algebra/curves/edwards/edwards_pp.hpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_g1.cpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_g1.hpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_g2.cpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_g2.hpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_init.cpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_init.hpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_pairing.cpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_pairing.hpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_pp.cpp
libff/libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_g1.cpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_g1.hpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_g2.cpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_g2.hpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_init.cpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_init.hpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_pairing.cpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_pairing.hpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_pp.cpp
libff/libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp
libff/libff/algebra/curves/mnt/mnt46_common.cpp
libff/libff/algebra/curves/mnt/mnt46_common.hpp
libff/libff/algebra/curves/tests/test_bilinearity.cpp
libff/libff/algebra/curves/tests/test_groups.cpp
libff/libff/algebra/curves/curve_utils.hpp
libff/libff/algebra/curves/curve_utils.tcc
libff/libff/algebra/curves/public_params.hpp
libff/libff/algebra/exponentiation/exponentiation.hpp
libff/libff/algebra/exponentiation/exponentiation.tcc
libff/libff/algebra/fields/tests/test_fields.cpp
libff/libff/algebra/fields/bigint.hpp
libff/libff/algebra/fields/bigint.tcc
libff/libff/algebra/fields/field_utils.hpp
libff/libff/algebra/fields/field_utils.tcc
libff/libff/algebra/fields/fp.hpp
libff/libff/algebra/fields/fp.tcc
libff/libff/algebra/fields/fp_aux.tcc
libff/libff/algebra/scalar_multiplication/multiexp.hpp
libff/libff/algebra/scalar_multiplication/multiexp.tcc
libff/libff/algebra/scalar_multiplication/multiexp_profile.cpp
libff/libff/algebra/scalar_multiplication/wnaf.hpp
libff/libff/algebra/scalar_multiplication/wnaf.tcc
libff/libff/common/default_types/ec_pp.hpp
libff/libff/common/double.cpp
libff/libff/common/double.hpp
libff/libff/common/profiling.cpp
libff/libff/common/profiling.hpp
libff/libff/common/rng.hpp
libff/libff/common/rng.tcc
libff/libff/common/template_utils.hpp
libff/libff/common/utils.cpp
libff/libff/common/utils.hpp
libff/libff/common/utils.tcc
add_executable(sgxwallet
secure_enclave/AESUtils.c
secure_enclave/AESUtils.h
secure_enclave/BLSEnclave.cpp
secure_enclave/BLSEnclave.h
secure_enclave/curves.c
secure_enclave/curves.h
secure_enclave/DH_dkg.c
secure_enclave/DH_dkg.h
secure_enclave/DKGUtils.cpp
secure_enclave/DKGUtils.h
secure_enclave/domain_parameters.c
secure_enclave/domain_parameters.h
secure_enclave/enclave_common.h
secure_enclave/numbertheory.c
secure_enclave/numbertheory.h
secure_enclave/point.c
secure_enclave/point.h
secure_enclave/secure_enclave.c
secure_enclave/secure_enclave.i
secure_enclave/secure_enclave_t.c
secure_enclave/secure_enclave_t.h
secure_enclave/DKGUtils.h
secure_enclave/DKGUtils.cpp
secure_enclave/signature.c
secure_enclave/signature.h
sgx-software-enable/sgx_capable.h
sgx-software-enable/sgx_enable.c
tgmp-build/include/sgx_tgmp.h
abstractCSRManagerServer.h
abstractregserver.h
abstractstubserver.h
BLSCrypto.cpp
BLSCrypto.h
BLSPrivateKeyShareSGX.cpp
BLSPrivateKeyShareSGX.h
catch.hpp
cert_util.cpp
common.h
create_enclave.c
create_enclave.h
CSRManagerServer.cpp
CSRManagerServer.h
DKGCrypto.cpp
DKGCrypto.h
ECDSACrypto.cpp
ECDSACrypto.h
LevelDB.cpp
LevelDB.h
oc_alloc.c
RPCException.cpp
RPCException.h
secure_enclave_u.c
secure_enclave_u.h
SEKManager.cpp
SEKManager.h
ServerDataChecker.cpp
ServerDataChecker.h
ServerInit.cpp
ServerInit.h
sgx_detect.h
sgx_detect_linux.c
sgx_stub.c
sgx_stub.h
sgx_tgmp.h
SGXRegistrationServer.cpp
SGXRegistrationServer.h
sgxwallet.c
testw.cpp
)
sgxwallet.h
sgxwallet_common.h
SGXWalletServer.cpp
SGXWalletServer.h
SGXWalletServer.hpp
stubclient.cpp
stubclient.h
testw.cpp)
......@@ -12,6 +12,7 @@
#include <jsonrpccpp/server/connectors/httpserver.h>
#include "spdlog/spdlog.h"
#include "common.h"
CSRManagerServer *cs = nullptr;
......@@ -22,20 +23,19 @@ CSRManagerServer::CSRManagerServer(AbstractServerConnector &connector,
serverVersion_t type):abstractCSRManagerServer(connector, type){}
Json::Value GetUnsignedCSRsImpl(){
spdlog::info("Enter GetUnsignedCSRsImpl");
Json::Value getUnsignedCSRsImpl(){
spdlog::info("Enter getUnsignedCSRsImpl");
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
//result["hashes"] =;
try{
std::vector<std::string> hashes_vect = csrDb->writeKeysToVector1(MAX_CSR_NUM);
for (int i = 0; i < hashes_vect.size(); i++){
vector<string> hashes_vect = LevelDB::getCsrDb()->writeKeysToVector1(MAX_CSR_NUM);
for (int i = 0; i < (int) hashes_vect.size(); i++){
result["hashes"][i] = hashes_vect.at(i);
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
......@@ -44,7 +44,7 @@ Json::Value GetUnsignedCSRsImpl(){
return result;
}
Json::Value SignByHashImpl(const std::string& hash, int status){
Json::Value signByHashImpl(const string& hash, int status){
Json::Value result;
result["errorMessage"] = "";
......@@ -53,46 +53,46 @@ Json::Value SignByHashImpl(const std::string& hash, int status){
throw RPCException(-111, "Invalid csr status");
}
std::string csr_db_key = "CSR:HASH:" + hash;
std::shared_ptr<std::string> csr_ptr = csrDb->readString(csr_db_key);
string csr_db_key = "CSR:HASH:" + hash;
shared_ptr<string> csr_ptr = LevelDB::getCsrDb()->readString(csr_db_key);
if (csr_ptr == nullptr){
throw RPCException(KEY_SHARE_DOES_NOT_EXIST, "HASH DOES NOT EXIST IN DB");
}
if (status == 0) {
std::string csr_name = "sgx_data/cert/" + hash + ".csr";
std::ofstream outfile(csr_name);
outfile << *csr_ptr << std::endl;
string csr_name = "sgx_data/cert/" + hash + ".csr";
ofstream outfile(csr_name);
outfile << *csr_ptr << endl;
outfile.close();
if (access(csr_name.c_str(), F_OK) != 0) {
csrDb->deleteKey(csr_db_key);
LevelDB::getCsrDb()->deleteKey(csr_db_key);
throw RPCException(FILE_NOT_FOUND, "Csr does not exist");
}
std::string signClientCert = "cd sgx_data/cert && ./create_client_cert " + hash;
string signClientCert = "cd sgx_data/cert && ./create_client_cert " + hash;
if (system(signClientCert.c_str()) == 0) {
spdlog::info("CLIENT CERTIFICATE IS SUCCESSFULLY GENERATED");
} else {
spdlog::info("CLIENT CERTIFICATE GENERATION FAILED");
csrDb->deleteKey(csr_db_key);
std::string status_db_key = "CSR:HASH:" + hash + "STATUS:";
csrStatusDb->deleteKey(status_db_key);
csrStatusDb->writeDataUnique(status_db_key, "-1");
LevelDB::getCsrDb()->deleteKey(csr_db_key);
string status_db_key = "CSR:HASH:" + hash + "STATUS:";
LevelDB::getCsrStatusDb()->deleteKey(status_db_key);
LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, "-1");
throw RPCException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED");
//exit(-1);
}
}
csrDb->deleteKey(csr_db_key);
std::string status_db_key = "CSR:HASH:" + hash + "STATUS:";
csrStatusDb->deleteKey(status_db_key);
csrStatusDb->writeDataUnique(status_db_key, std::to_string(status));
LevelDB::getCsrDb()->deleteKey(csr_db_key);
string status_db_key = "CSR:HASH:" + hash + "STATUS:";
LevelDB::getCsrStatusDb()->deleteKey(status_db_key);
LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, to_string(status));
result["status"] = status;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -101,14 +101,14 @@ Json::Value SignByHashImpl(const std::string& hash, int status){
}
Json::Value CSRManagerServer::GetUnsignedCSRs(){
std::lock_guard<std::recursive_mutex> lock(m);
return GetUnsignedCSRsImpl();
Json::Value CSRManagerServer::getUnsignedCSRs(){
lock_guard<recursive_mutex> lock(m);
return getUnsignedCSRsImpl();
}
Json::Value CSRManagerServer::SignByHash(const std::string& hash, int status){
std::lock_guard<std::recursive_mutex> lock(m);
return SignByHashImpl(hash, status);
Json::Value CSRManagerServer::signByHash(const string& hash, int status){
lock_guard<recursive_mutex> lock(m);
return signByHashImpl(hash, status);
}
int init_csrmanager_server(){
......
......@@ -20,8 +20,8 @@ class CSRManagerServer : public abstractCSRManagerServer {
CSRManagerServer(AbstractServerConnector &connector, serverVersion_t type);
virtual Json::Value GetUnsignedCSRs();
virtual Json::Value SignByHash(const std::string& hash, int status);
virtual Json::Value getUnsignedCSRs();
virtual Json::Value signByHash(const std::string& hash, int status);
};
extern int init_csrmanager_server();
......
......@@ -26,7 +26,6 @@
#include "sgxwallet.h"
#include <iostream>
#include <memory>
#include <memory>
#include "SGXWalletServer.hpp"
#include "RPCException.h"
......@@ -35,20 +34,21 @@
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include "spdlog/spdlog.h"
#include "common.h"
std::vector<std::string> SplitString(const char* koefs, const char symbol){
std::string str(koefs);
std::string delim;
vector<string> SplitString(const char* koefs, const char symbol){
string str(koefs);
string delim;
delim.push_back(symbol);
std::vector<std::string> G2_strings;
vector<string> G2_strings;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) {
std::string koef(token.c_str());
string koef(token.c_str());
G2_strings.push_back(koef);
}
prev = pos + delim.length();
......@@ -59,7 +59,7 @@ std::vector<std::string> SplitString(const char* koefs, const char symbol){
}
template<class T>
std::string ConvertToString(T field_elem, int base = 10) {
string ConvertToString(T field_elem, int base = 10) {
mpz_t t;
mpz_init(t);
......@@ -70,55 +70,47 @@ std::string ConvertToString(T field_elem, int base = 10) {
char * tmp = mpz_get_str(arr, base, t);
mpz_clear(t);
std::string output = tmp;
string output = tmp;
return output;
}
std::string gen_dkg_poly( int _t){
char *errMsg = (char *)calloc(1024, 1);
string gen_dkg_poly( int _t){
vector<char> errMsg(1024, 0);
int err_status = 0;
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);;
vector<uint8_t> encrypted_dkg_secret(DKG_MAX_SEALED_LEN, 0);
uint32_t enc_len = 0;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, _t);
if (!is_aes)
status = gen_dkg_secret (eid, &err_status, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
else
status = gen_dkg_secret_aes (eid, &err_status, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
if ( err_status != 0){
throw RPCException(-666, errMsg ) ;
throw RPCException(-666, errMsg.data() ) ;
}
if (DEBUG_PRINT) {
spdlog::info("gen_dkg_secret, status {}", err_status, " err msg ", errMsg);
/* std::cerr << "encr raw poly: " << std::endl;
for ( int i = 0 ; i < 3050; i++)
printf(" %d ", encrypted_dkg_secret[i] );*/
spdlog::info("gen_dkg_secret, status {}", err_status, " err msg ", errMsg.data());
spdlog::info("in DKGCrypto encr len is {}", enc_len);
}
char *hexEncrPoly = (char *) calloc(DKG_MAX_SEALED_LEN * 2 + 1, 1);//(4*BUF_LEN, 1);
carray2Hex(encrypted_dkg_secret, DKG_MAX_SEALED_LEN, hexEncrPoly);
std::string result(hexEncrPoly);
vector<char> hexEncrPoly(DKG_MAX_SEALED_LEN * 2 + 1, 0);//(4*BUF_LEN, 1);
free(errMsg);
free(encrypted_dkg_secret);
free(hexEncrPoly);
carray2Hex(encrypted_dkg_secret.data(), DKG_MAX_SEALED_LEN, hexEncrPoly.data());
string result(hexEncrPoly.data());
return result;
}
std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyHex, int t, int n){
vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int n){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
if (DEBUG_PRINT) {
// std::cerr << "got encr poly " << encryptedPolyHex << std::endl;
spdlog::info("got encr poly size {}", std::char_traits<char>::length(encryptedPolyHex));
// cerr << "got encr poly " << encryptedPolyHex << endl;
spdlog::info("got encr poly size {}", char_traits<char>::length(encryptedPolyHex));
}
char* public_shares = (char*)calloc(10000, 1);
......@@ -132,12 +124,12 @@ std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyH
if (DEBUG_PRINT) {
spdlog::info("enc len {}", enc_len);
/*std::cerr << "encr raw poly: " << std::endl;
/*cerr << "encr raw poly: " << endl;
for ( int i = 0 ; i < 3050; i++)
printf(" %d ", encr_dkg_poly[i] );*/
}
uint32_t len;
uint32_t len = 0;
status = get_public_shares(eid, &err_status, errMsg1, encr_dkg_poly, len, public_shares, t, n);
if ( err_status != 0){
throw RPCException(-666, errMsg1 );
......@@ -148,16 +140,16 @@ std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyH
spdlog::info("public_shares:");
spdlog::info("{}", public_shares);
// std::cerr << "public_shares:" << std::endl;
// std::cerr << public_shares << std::endl;
// cerr << "public_shares:" << endl;
// cerr << public_shares << endl;
spdlog::info("get_public_shares status: {}", err_status);
//printf("\nget_public_shares status: %d error %s \n\n", err_status, errMsg1);
}
std::vector <std::string> G2_strings = SplitString( public_shares, ',');
std::vector <std::vector <std::string>> pub_shares_vect;
vector <string> G2_strings = SplitString( public_shares, ',');
vector <vector <string>> pub_shares_vect;
for ( int i = 0; i < G2_strings.size(); i++){
std::vector <std::string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
vector <string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
pub_shares_vect.push_back(koef_str);
}
......@@ -168,7 +160,7 @@ std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyH
return pub_shares_vect;
}
std::string get_secret_shares(const std::string& polyName, const char* encryptedPolyHex, const std::vector<std::string>& publicKeys, int t, int n){
string get_secret_shares(const string& polyName, const char* encryptedPolyHex, const vector<string>& publicKeys, int t, int n){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
......@@ -179,12 +171,16 @@ std::string get_secret_shares(const std::string& polyName, const char* encrypted
throw RPCException(INVALID_HEX, "Invalid encryptedPolyHex");
}
status = set_encrypted_dkg_poly(eid, &err_status, errMsg1, encr_dkg_poly);
if ( status != SGX_SUCCESS || err_status!=0){
if (!is_aes)
status = set_encrypted_dkg_poly(eid, &err_status, errMsg1, encr_dkg_poly);
else
status = set_encrypted_dkg_poly_aes(eid, &err_status, errMsg1, encr_dkg_poly, &enc_len);
if ( status != SGX_SUCCESS || err_status != 0){
throw RPCException(-666, errMsg1 );
}
std::string result;
string result;
char *hexEncrKey = (char *) calloc(2 * BUF_LEN, 1);
for ( int i = 0; i < n; i++){
......@@ -193,7 +189,7 @@ std::string get_secret_shares(const std::string& polyName, const char* encrypted
char cur_share[193];
char s_shareG2[320];
std::string pub_keyB = publicKeys.at(i);//publicKeys.substr(128*i, 128*i + 128);
string pub_keyB = publicKeys.at(i);//publicKeys.substr(128*i, 128*i + 128);
if (DEBUG_PRINT) {
spdlog::info("pub_keyB is {}", pub_keyB);
}
......@@ -214,12 +210,12 @@ std::string get_secret_shares(const std::string& polyName, const char* encrypted
}
carray2Hex(encrypted_skey, dec_len, hexEncrKey);
std::string DHKey_name = "DKG_DH_KEY_" + polyName + "_" + std::to_string(i) + ":";
string DHKey_name = "DKG_DH_KEY_" + polyName + "_" + to_string(i) + ":";
// std::cerr << "hexEncrKey: " << hexEncrKey << std::endl;
// cerr << "hexEncrKey: " << hexEncrKey << endl;
writeDataToDB(DHKey_name, hexEncrKey);
std::string shareG2_name = "shareG2_" + polyName + "_" + std::to_string(i) + ":";
string shareG2_name = "shareG2_" + polyName + "_" + to_string(i) + ":";
if (DEBUG_PRINT) {
spdlog::info("name to write to db is {}", DHKey_name);
spdlog::info("name to write to db is {}", shareG2_name);
......@@ -229,9 +225,9 @@ std::string get_secret_shares(const std::string& polyName, const char* encrypted
if (DEBUG_PRINT) {
spdlog::info("errMsg: {}", errMsg1);
// std::cerr << "iteration " << i <<" result length is " << result.length() << std::endl ;
// std::cerr << "iteration " << i <<" share length is " << strlen(cur_share) << std::endl;
// std::cerr << "iteration " << i <<" share is " << cur_share << std::endl;
// cerr << "iteration " << i <<" result length is " << result.length() << endl ;
// cerr << "iteration " << i <<" share length is " << strlen(cur_share) << endl;
// cerr << "iteration " << i <<" share is " << cur_share << endl;
}
}
//result += '\0';
......@@ -254,16 +250,16 @@ bool VerifyShares(const char* publicShares, const char* encr_sshare, const char
}
int result;
if (DEBUG_PRINT) {
// std::cerr << "encryptedKeyHex " << encryptedKeyHex << std::endl;
// std::cerr << "dec_key_len " << dec_key_len << std::endl;
// cerr << "encryptedKeyHex " << encryptedKeyHex << endl;
// cerr << "dec_key_len " << dec_key_len << endl;
// std::cerr << "encr_sshare length is " << strlen(encr_sshare) << std::endl; std::cerr << "public shares " << publicShares << std::endl;
spdlog::info("publicShares length is {}", std::char_traits<char>::length(publicShares));
// cerr << "encr_sshare length is " << strlen(encr_sshare) << endl; cerr << "public shares " << publicShares << endl;
spdlog::info("publicShares length is {}", char_traits<char>::length(publicShares));
}
char pshares[8193];
strncpy(pshares, publicShares, strlen(publicShares) + 1);
//std::cerr << "pshares " << pshares << std::endl;
//cerr << "pshares " << pshares << endl;
dkg_verification(eid, &err_status, errMsg1, pshares, encr_sshare, encr_key, dec_key_len, t, ind, &result);
......@@ -281,7 +277,7 @@ bool VerifyShares(const char* publicShares, const char* encr_sshare, const char
return result;
}
bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const char * encryptedKeyHex){
bool CreateBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex){
if (DEBUG_PRINT) {
spdlog::info("ENTER CreateBLSShare");
}
......@@ -297,23 +293,23 @@ bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const
uint32_t enc_bls_len = 0;
//std::cerr << "BEFORE create_bls_key IN ENCLAVE " << std::endl;
//cerr << "BEFORE create_bls_key IN ENCLAVE " << endl;
create_bls_key(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key, &enc_bls_len);
//std::cerr << "AFTER create_bls_key IN ENCLAVE er msg is " << errMsg1 << std::endl;
//cerr << "AFTER create_bls_key IN ENCLAVE er msg is " << errMsg1 << endl;
if ( err_status != 0){
spdlog::info("ERROR IN ENCLAVE");
throw RPCException(ERROR_IN_ENCLAVE, "Create BLS private key failed in enclave");
}
else {
char *hexBLSKey = (char *) calloc(2 * BUF_LEN, 1);
//std::cerr << "BEFORE carray2Hex" << std::endl;
//std::cerr << "enc_bls_len " << enc_bls_len << std::endl;
//cerr << "BEFORE carray2Hex" << endl;
//cerr << "enc_bls_len " << enc_bls_len << endl;
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey);
// std::cerr << "BEFORE WRITE BLS KEY TO DB" << std::endl;
writeDataToDB(BLSKeyName, hexBLSKey);
// cerr << "BEFORE WRITE BLS KEY TO DB" << endl;
writeDataToDB(blsKeyName, hexBLSKey);
if (DEBUG_PRINT) {
spdlog::info("hexBLSKey length is {}", std::char_traits<char>::length(hexBLSKey));
spdlog::info("bls key {}", BLSKeyName, " is ", hexBLSKey );
spdlog::info("hexBLSKey length is {}", char_traits<char>::length(hexBLSKey));
spdlog::info("bls key {}", blsKeyName, " is ", hexBLSKey );
}
free(hexBLSKey);
return true;
......@@ -321,7 +317,7 @@ bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const
}
std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex){
vector<string> GetBLSPubKey(const char * encryptedKeyHex){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
......@@ -331,8 +327,6 @@ std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex){
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)){
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
// for ( int i = 0; i < BUF_LEN; i++ )
// std::cerr << encr_key[i] << " ";
char pub_key[320];
if (DEBUG_PRINT) {
......@@ -342,7 +336,7 @@ std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex){
if ( err_status != 0){
throw RPCException(ERROR_IN_ENCLAVE, "Failed to get BLS public key in enclave");
}
std::vector<std::string> pub_key_vect = SplitString(pub_key, ':');
vector<string> pub_key_vect = SplitString(pub_key, ':');
if (DEBUG_PRINT) {
spdlog::info("errMsg1 is {}", errMsg1);
......@@ -353,18 +347,18 @@ std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex){
return pub_key_vect;
}
std::string decrypt_DHKey(const std::string& polyName, int ind){
string decrypt_DHKey(const string& polyName, int ind){
char* errMsg1 = (char*) calloc(1024,1);
vector<char> errMsg1(1024,0);
int err_status = 0;
std::string DH_key_name = polyName + "_" + std::to_string(ind) + ":";
std::shared_ptr<std::string> hexEncrKey_ptr = readFromDb(DH_key_name, "DKG_DH_KEY_");
string DH_key_name = polyName + "_" + to_string(ind) + ":";
shared_ptr<string> hexEncrKey_ptr = readFromDb(DH_key_name, "DKG_DH_KEY_");
if (DEBUG_PRINT) {
spdlog::info("encr DH key is {}", *hexEncrKey_ptr);
}
char *hexEncrKey = (char *) calloc(2 * BUF_LEN, 1);
vector<char> hexEncrKey(2 * BUF_LEN, 0);
uint64_t DH_enc_len = 0;
uint8_t encrypted_DHkey[BUF_LEN];
......@@ -374,20 +368,16 @@ std::string decrypt_DHKey(const std::string& polyName, int ind){
char DHKey[ECDSA_SKEY_LEN];
decrypt_key(eid, &err_status, errMsg1, encrypted_DHkey, DH_enc_len, DHKey);
decrypt_key(eid, &err_status, errMsg1.data(), encrypted_DHkey, DH_enc_len, DHKey);
if (err_status != 0){
free(hexEncrKey);
throw RPCException(ERROR_IN_ENCLAVE, "decrypt key failed in enclave");
}
free(errMsg1);
free(hexEncrKey);
return DHKey;
}
std::vector<std::string> mult_G2(const std::string& x){
std::vector<std::string> result(4);
vector<string> mult_G2(const string& x){
vector<string> result(4);
libff::init_alt_bn128_params();
libff::alt_bn128_Fr el(x.c_str());
libff::alt_bn128_G2 elG2 = el * libff::alt_bn128_G2::one();
......
......@@ -39,7 +39,7 @@ bool VerifyShares(const char* publicShares, const char* encr_sshare, const char
std::string decrypt_DHKey(const std::string& polyName, int ind);
bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const char * encryptedKeyHex);
bool CreateBLSShare( const std::string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex);
......
FROM skalenetwork/sgxwallet_base:latest
WORKDIR /usr/src/sdk
COPY *.cpp ./
COPY *.h ./
COPY *.txt ./
COPY *.c ./
COPY *.am ./
COPY *.hpp ./
COPY *.sh ./
COPY *.gmp ./
COPY *.ac ./
COPY *.json ./
COPY docker ./docker
COPY build-aux ./build-aux
COPY cert ./cert
COPY jsonrpc ./jsonrpc
COPY leveldb ./leveldb
COPY m4 ./m4
COPY scripts ./scripts
COPY secure_enclave ./secure_enclave
COPY spdlog ./spdlog
RUN autoreconf -vif
......@@ -12,13 +32,8 @@ RUN autoconf
RUN ./configure
### RUN cd libBLS; cmake -H. -Bbuild; cmake --build build -- -j$(nproc);
RUN make
RUN wget --progress=dot:mega -O - https://github.com/intel/dynamic-application-loader-host-interface/archive/072d233296c15d0dcd1fb4570694d0244729f87b.tar.gz | tar -xz && \
cd dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b && \
cmake . -DCMAKE_BUILD_TYPE=Release -DINIT_SYSTEM=SysVinit && \
make install && \
cd .. && rm -rf dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b
RUN mkdir /sgx_data
RUN mkdir /usr/src/sdk/sgx_data
COPY docker/start.sh ./
ENTRYPOINT ["/usr/src/sdk/start.sh"]
......@@ -48,4 +48,10 @@ RUN git clone -b sgx_2.5 --depth 1 https://github.com/intel/linux-sgx && \
COPY configure.gmp ./
RUN cd scripts; ./build.py
RUN wget --progress=dot:mega -O - https://github.com/intel/dynamic-application-loader-host-interface/archive/072d233296c15d0dcd1fb4570694d0244729f87b.tar.gz | tar -xz && \
cd dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b && \
cmake . -DCMAKE_BUILD_TYPE=Release -DINIT_SYSTEM=SysVinit && \
make install && \
cd .. && rm -rf dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b
FROM skalenetwork/sgxwallet_base:latest
WORKDIR /usr/src/sdk
COPY *.cpp ./
COPY *.h ./
COPY *.txt ./
COPY *.c ./
COPY *.am ./
COPY *.hpp ./
COPY *.sh ./
COPY *.gmp ./
COPY *.ac ./
COPY *.json ./
COPY docker ./docker
COPY build-aux ./build-aux
COPY cert ./cert
COPY jsonrpc ./jsonrpc
COPY leveldb ./leveldb
COPY m4 ./m4
COPY scripts ./scripts
COPY secure_enclave ./secure_enclave
COPY spdlog ./spdlog
RUN autoreconf -vif
RUN libtoolize --force
RUN aclocal
......@@ -10,13 +30,9 @@ RUN autoconf
RUN ./configure --enable-sgx-simulation
### RUN cd libBLS; cmake -H. -Bbuild; cmake --build build -- -j$(nproc);
RUN make
RUN wget --progress=dot:mega -O - https://github.com/intel/dynamic-application-loader-host-interface/archive/072d233296c15d0dcd1fb4570694d0244729f87b.tar.gz | tar -xz && \
cd dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b && \
cmake . -DCMAKE_BUILD_TYPE=Release -DINIT_SYSTEM=SysVinit && \
make install && \
cd .. && rm -rf dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b
RUN mkdir /sgx_data
RUN mkdir /usr/src/sdk/sgx_data
COPY docker/start.sh ./
ENTRYPOINT ["/usr/src/sdk/start.sh"]
......@@ -51,14 +51,23 @@ std::vector<std::string> gen_ecdsa_key(){
char *pub_key_y = (char *)calloc(1024, 1);
uint32_t enc_len = 0;
status = generate_ecdsa_key(eid, &err_status, errMsg, encr_pr_key, &enc_len, pub_key_x, pub_key_y );
if ( !is_aes)
status = generate_ecdsa_key(eid, &err_status, errMsg, encr_pr_key, &enc_len, pub_key_x, pub_key_y );
else status = generate_ecdsa_key_aes(eid, &err_status, errMsg, encr_pr_key, &enc_len, pub_key_x, pub_key_y );
if ( err_status != 0 ){
std::cerr << "RPCException thrown" << std::endl;
throw RPCException(-666, errMsg) ;
}
std::vector<std::string> keys(3);
//std::cerr << "account key is " << errMsg << std::endl;
char *hexEncrKey = (char *) calloc(2*BUF_LEN, 1);
if (DEBUG_PRINT) {
std::cerr << "account key is " << errMsg << std::endl;
std::cerr << "enc_len is " << enc_len << std::endl;
std::cerr << "enc_key is " << std::endl;
// for(int i = 0 ; i < 1024; i++)
// std::cerr << (int)encr_pr_key[i] << " " ;
}
char *hexEncrKey = (char *) calloc(BUF_LEN * 2, 1);
carray2Hex(encr_pr_key, enc_len, hexEncrKey);
keys.at(0) = hexEncrKey;
keys.at(1) = std::string(pub_key_x) + std::string(pub_key_y);//concatPubKeyWith0x(pub_key_x, pub_key_y);//
......@@ -69,6 +78,7 @@ std::vector<std::string> gen_ecdsa_key(){
unsigned long seed = rand_gen();
if (DEBUG_PRINT) {
spdlog::info("seed is {}", seed);
std::cerr << "strlen is " << strlen(hexEncrKey) << std::endl;
}
gmp_randstate_t state;
gmp_randinit_default(state);
......@@ -105,26 +115,32 @@ std::string get_ecdsa_pubkey(const char* encryptedKeyHex){
char *pub_key_y = (char *)calloc(1024, 1);
uint64_t enc_len = 0;
uint8_t encr_pr_key[BUF_LEN];
//uint8_t encr_pr_key[BUF_LEN];
uint8_t* encr_pr_key = (uint8_t*)calloc(1024, 1);
if (!hex2carray(encryptedKeyHex, &enc_len, encr_pr_key)){
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
status = get_public_ecdsa_key(eid, &err_status, errMsg, encr_pr_key, enc_len, pub_key_x, pub_key_y );
if ( !is_aes)
status = get_public_ecdsa_key(eid, &err_status, errMsg, encr_pr_key, enc_len, pub_key_x, pub_key_y );
else status = get_public_ecdsa_key_aes(eid, &err_status, errMsg, encr_pr_key, enc_len, pub_key_x, pub_key_y );
if (err_status != 0){
throw RPCException(-666, errMsg) ;
}
std::string pubKey = std::string(pub_key_x) + std::string(pub_key_y);//concatPubKeyWith0x(pub_key_x, pub_key_y);//
if (DEBUG_PRINT) {
spdlog::info("enc_len is {}", enc_len);
spdlog::info("pubkey is {}", pubKey);
spdlog::info("pubkey length is {}", pubKey.length());
spdlog::info("err str is {}", errMsg);
spdlog::info("err status is {}", err_status);
}
free(errMsg);
free(pub_key_x);
free(pub_key_y);
free(encr_pr_key);
return pubKey;
}
......@@ -134,12 +150,13 @@ std::vector<std::string> ecdsa_sign_hash(const char* encryptedKeyHex, const char
char *errMsg = (char *)calloc(1024, 1);
int err_status = 0;
char* signature_r = (char*)malloc(1024);
char* signature_s = (char*)malloc(1024);
char* signature_r = (char *)calloc(1024, 1);
char* signature_s = (char *)calloc(1024, 1);
uint8_t signature_v = 0;
uint64_t dec_len = 0;
uint8_t encr_key[BUF_LEN];
//uint8_t encr_key[BUF_LEN];
uint8_t* encr_key = (uint8_t*)calloc(1024, 1);
if (!hex2carray(encryptedKeyHex, &dec_len, encr_key)){
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
......@@ -150,7 +167,9 @@ std::vector<std::string> ecdsa_sign_hash(const char* encryptedKeyHex, const char
spdlog::info("encrypted len: {}", dec_len);
}
status = ecdsa_sign1(eid, &err_status, errMsg, encr_key, ECDSA_ENCR_LEN, (unsigned char*)hashHex, signature_r, signature_s, &signature_v, base );
if (!is_aes)
status = ecdsa_sign1(eid, &err_status, errMsg, encr_key, ECDSA_ENCR_LEN, (unsigned char*)hashHex, signature_r, signature_s, &signature_v, base );
else status = ecdsa_sign_aes(eid, &err_status, errMsg, encr_key, dec_len, (unsigned char*)hashHex, signature_r, signature_s, &signature_v, base );
if ( err_status != 0){
throw RPCException(-666, errMsg ) ;
}
......@@ -176,6 +195,7 @@ std::vector<std::string> ecdsa_sign_hash(const char* encryptedKeyHex, const char
free(errMsg);
free(signature_r);
free(signature_s);
free(encr_key);
return signature_vect;
}
\ No newline at end of file
......@@ -37,24 +37,24 @@
#include "ServerInit.h"
#include "spdlog/spdlog.h"
#include "common.h"
using namespace leveldb;
static WriteOptions writeOptions;
static ReadOptions readOptions;
LevelDB* levelDb = nullptr;
LevelDB* csrDb = nullptr;
LevelDB* csrStatusDb = nullptr;
std::shared_ptr<std::string> LevelDB::readString(const std::string &_key) {
std::shared_ptr<string> LevelDB::readString(const string &_key) {
std::lock_guard<std::recursive_mutex> lock(mutex);
auto result = std::make_shared<std::string>();
auto result = std::make_shared<string>();
if (db == nullptr) {
throw RPCException(NULL_DATABASE, "Null db");
......@@ -75,7 +75,7 @@ std::shared_ptr<std::string> LevelDB::readString(const std::string &_key) {
return result;
}
void LevelDB::writeString(const std::string &_key, const std::string &_value) {
void LevelDB::writeString(const string &_key, const string &_value) {
std::lock_guard<std::recursive_mutex> lock(mutex);
......@@ -90,11 +90,11 @@ void LevelDB::writeString(const std::string &_key, const std::string &_value) {
}
void LevelDB::deleteDHDKGKey (const std::string &_key) {
void LevelDB::deleteDHDKGKey (const string &_key) {
std::lock_guard<std::recursive_mutex> lock(mutex);
std::string full_key = "DKG_DH_KEY_" + _key;
string full_key = "DKG_DH_KEY_" + _key;
auto status = db->Delete(writeOptions, Slice(_key));
......@@ -106,11 +106,11 @@ void LevelDB::deleteDHDKGKey (const std::string &_key) {
}
}
void LevelDB::deleteTempNEK(const std::string &_key){
void LevelDB::deleteTempNEK(const string &_key){
std::lock_guard<std::recursive_mutex> lock(mutex);
std::string prefix = _key.substr(0,8);
string prefix = _key.substr(0,8);
if (prefix != "tmp_NEK:") {
return;
}
......@@ -122,7 +122,7 @@ void LevelDB::deleteTempNEK(const std::string &_key){
std::cerr << "key deleted " << _key << std::endl;
}
void LevelDB::deleteKey(const std::string &_key){
void LevelDB::deleteKey(const string &_key){
std::lock_guard<std::recursive_mutex> lock(mutex);
......@@ -149,7 +149,7 @@ void LevelDB::writeByteArray(const char *_key, size_t _keyLen, const char *value
}
void LevelDB::writeByteArray(std::string &_key, const char *value,
void LevelDB::writeByteArray(string &_key, const char *value,
size_t _valueLen) {
std::lock_guard<std::recursive_mutex> lock(mutex);
......@@ -188,13 +188,13 @@ uint64_t LevelDB::visitKeys(LevelDB::KeyVisitor *_visitor, uint64_t _maxKeysToVi
return readCounter;
}
std::vector<std::string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
uint64_t readCounter = 0;
std::vector<std::string> keys;
std::vector<string> keys;
leveldb::Iterator *it = db->NewIterator(readOptions);
for (it->SeekToFirst(); it->Valid(); it->Next()) {
std::string cur_key(it->key().data(), it->key().size());
string cur_key(it->key().data(), it->key().size());
keys.push_back(cur_key);
// keys.push_back(it->key().data());
readCounter++;
......@@ -208,7 +208,7 @@ std::vector<std::string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
return keys;
}
void LevelDB::writeDataUnique(const std::string & Name, const std::string &value) {
void LevelDB::writeDataUnique(const string & Name, const string &value) {
auto key = Name;
......@@ -226,7 +226,7 @@ void LevelDB::writeDataUnique(const std::string & Name, const std::string &value
}
LevelDB::LevelDB(std::string &filename) {
LevelDB::LevelDB(string &filename) {
leveldb::Options options;
......@@ -243,9 +243,73 @@ LevelDB::LevelDB(std::string &filename) {
}
LevelDB::~LevelDB() {
if (db != nullptr)
delete db;
}
const std::shared_ptr<LevelDB> &LevelDB::getLevelDb() {
CHECK_STATE(levelDb)
return levelDb;
}
const std::shared_ptr<LevelDB> &LevelDB::getCsrDb() {
CHECK_STATE(csrDb)
return csrDb;
}
const std::shared_ptr<LevelDB> &LevelDB::getCsrStatusDb() {
CHECK_STATE(csrStatusDb)
return csrStatusDb;
}
std::shared_ptr<LevelDB> LevelDB::levelDb = nullptr;
std::shared_ptr<LevelDB> LevelDB::csrDb = nullptr;
std::shared_ptr<LevelDB> LevelDB::csrStatusDb = nullptr;
string LevelDB::sgx_data_folder;
bool LevelDB::isInited = false;
void LevelDB::initDataFolderAndDBs() {
if (isInited)
return;
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
spdlog::error("could not get cwd");
exit(-1);
}
sgx_data_folder = string(cwd) + "/" + SGXDATA_FOLDER;
struct stat info;
if (stat(sgx_data_folder.c_str(), &info) !=0 ){
spdlog::info("going to create sgx_data folder");
std::string make_sgx_data_folder = "mkdir " + sgx_data_folder;
if (system(make_sgx_data_folder.c_str()) == 0){
spdlog::info("sgx_data folder was created");
}
else{
spdlog::error("creating sgx_data folder failed");
exit(-1);
}
}
auto dbName = sgx_data_folder + WALLETDB_NAME;
levelDb = make_shared<LevelDB>(dbName);
auto csr_dbname = sgx_data_folder + "CSR_DB";
csrDb = make_shared<LevelDB>(csr_dbname);
auto csr_status_dbname = sgx_data_folder + "CSR_STATUS_DB";
csrStatusDb = make_shared<LevelDB>(csr_status_dbname);
}
const string &LevelDB::getSgxDataFolder() {
return sgx_data_folder;
}
......@@ -29,7 +29,7 @@
#include <string>
#include <mutex>
#include <vector>
#include "common.h"
namespace leveldb {
class DB;
class Status;
......@@ -38,38 +38,54 @@ namespace leveldb {
class LevelDB {
std::recursive_mutex mutex;
recursive_mutex mutex;
shared_ptr<leveldb::DB> db;
static bool isInited;
static shared_ptr<LevelDB> levelDb;
static shared_ptr<LevelDB> csrDb;
static shared_ptr<LevelDB> csrStatusDb;
leveldb::DB* db;
static string sgx_data_folder;
extern LevelDB* levelDb;
extern LevelDB* csrDb;
public:
static void initDataFolderAndDBs();
extern LevelDB* csrStatusDb;
static const shared_ptr<LevelDB> &getLevelDb();
static const shared_ptr<LevelDB> &getCsrDb();
static const shared_ptr<LevelDB> &getCsrStatusDb();
public:
std::shared_ptr<std::string> readString(const std::string& _key);
shared_ptr<string> readString(const string& _key);
void writeString(const std::string &key1, const std::string &value1);
void writeString(const string &key1, const string &value1);
void writeDataUnique(const std::string & Name, const std::string &value);
void writeDataUnique(const string & Name, const string &value);
void writeByteArray(const char *_key, size_t _keyLen, const char *value,
size_t _valueLen);
void writeByteArray(std::string& _key, const char *value,
void writeByteArray(string& _key, const char *value,
size_t _valueLen);
void deleteDHDKGKey (const std::string &_key);
void deleteDHDKGKey (const string &_key);
void deleteTempNEK (const std::string &_key);
void deleteTempNEK (const string &_key);
void deleteKey(const std::string &_key);
void deleteKey(const string &_key);
public:
......@@ -77,7 +93,7 @@ public:
void throwExceptionOnError(leveldb::Status result);
LevelDB(std::string& filename);
LevelDB(string& filename);
......@@ -85,15 +101,17 @@ public:
class KeyVisitor {
public:
virtual void visitDBKey(const char* _data) = 0;
virtual void writeDBKeysToVector(const char* _data, std::vector<const char*> & keys_vect) {}
virtual void writeDBKeysToVector(const char* _data, vector<const char*> & keys_vect) {}
};
uint64_t visitKeys(KeyVisitor* _visitor, uint64_t _maxKeysToVisit);
std::vector<std::string> writeKeysToVector1(uint64_t _maxKeysToVisit);
vector<string> writeKeysToVector1(uint64_t _maxKeysToVisit);
virtual ~LevelDB();
static const string &getSgxDataFolder();
};
......
......@@ -67,7 +67,7 @@ COMMON_SRC = sgx_stub.c sgx_detect_linux.c create_enclave.c oc_alloc.c
COMMON_ENCLAVE_SRC = secure_enclave_u.c secure_enclave_u.h
sgxwallet_SOURCES = sgxwallet.c SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp RPCException.cpp BLSCrypto.cpp ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp $(COMMON_SRC)
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp SEKManager.cpp $(COMMON_SRC)
nodist_sgxwallet_SOURCES = $(COMMON_ENCLAVE_SRC)
......@@ -102,7 +102,7 @@ sgxwallet_LDADD=-l$(SGX_URTS_LIB) -LlibBLS/deps/deps_inst/x86_or_x64/lib -Llevel
testw_SOURCES=testw.cpp stubclient.cpp SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ServerInit.cpp LevelDB.cpp \
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp ServerDataChecker.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp $(COMMON_SRC)
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp ServerDataChecker.cpp SEKManager.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp $(COMMON_SRC)
nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
......
......@@ -4,13 +4,52 @@
## Intro
**sgxwallet** is a next generation hardware secure crypto wallet that is based on **Intel SGX** technology. It currently supports **Ethereum** and **SKALE**, and will support **Bitcoin** in the future.
**sgxwallet** is a next generation hardware secure crypto wallet that is based on **Intel SGX** technology. It currently supports **Ethereum** and **SKALE**, and will support **Bitcoin** in the future.
**sgxwallet** runs as a network server. Clients connect to the server, authenticate to it using
TLS 1.0 protocol with client certificates, and then issue requests to the server to generate crypto
keys and perform cryptographic operations. The keys are generated inside the secure SGX enclave and never
leave the enclave unencrypted.
The server provides an initial registration service to issue client certificates to the clients.
The administrator manually approves each registration.
**sgxwallet** has been tested on **Ubuntu Linux 18.04**.
## An important note about production readiness
This sgxwallet library is still in active development and therefore should be regarded as _alpha software_. The development is still subject to security hardening, further testing, and breaking changes. **This library has not yet been reviewed or audited for security.**
The sgxwallet server is still in active development and therefore should be regarded as _alpha software_. The development is still subject to security hardening, further testing, and breaking changes. **This server has not yet been reviewed or audited for security.**
Table of Contents
=================
* [Running sgxwallet](#running-sgxwallet)
* [Clone this repository and its submodules](#clone-this-repository-and-its-submodules)
* [Try instantly in simulation mode](#try-instantly-in-simulation-mode)
* [Start, stop and upgrade sgxwallet](#start-stop-and-upgrade-sgxwallet)
* [Configure logging](#configure-logging)
* [Enable SGX on your machine](#enable-sgx-on-your-machine)
* [Enable "software-controlled" SGX](#enable-software-controlled-sgx)
* [Install SGX driver](#install-sgx-driver)
* [Run sgxwallet in secure SGX mode](#run-the-latest-sgxwallet-docker-container-from-dockerhub)
* [Development](#development)
* [Install Prerequisites](#install-prerequisites)
* [Install SGX sdk](#install-sgx-sdk)
* [Install required debian packages](#install-required-debian-packages)
* [Build dependencies](#build-dependencies)
* [Configure and build sgxwallet](#configure-and-build-sgxwallet)
* [Run sgxwallet](#run-sgxwallet)
* [Build Docker container](#build-docker-container)
* [Build Docker container in simulation mode](#build-docker-container-in-simulation-mode)
* [Run Docker container](#run-docker-container)
* [Run Docker container in simulation mode](#run-docker-container-in-simulation-mode)
* [Adding new source files](#adding-new-source-files)
* [Example of client certificate instantiation](#example-of-client-certificate-instantiation)
* [Libraries](#libraries)
* [License](#license)
# Running sgxwallet
......@@ -18,11 +57,97 @@ This sgxwallet library is still in active development and therefore should be re
`git clone --recurse-submodules https://github.com/skalenetwork/sgxwallet.git`
## Try instantly in simulation mode
The easiest way to try the sgxwallet server is to run it in
insecure simulation mode that emulates an SGX processor. Once you are familiar with the server,
you can enable sgx on your machine and run it in secure production mode.
To try the server:
Install docker-compose if you do not have it.
```
sudo apt-get install docker.io docker-compose
```
And then do
```
cd run_sgx_sim;
sudo docker-compose up
```
Voila! You should see the "SGX Server started" message.
## Start, stop and upgrade sgxwallet
As any docker-compose application sgxwallet is super easy to use.
To run the server as a daemon, do
```
sudo docker-compose up -d
```
To stop/start the server do
```
sudo docker-compose stop
sudo docker-compose start
```
To view server logs do
```
sudo docker-compose logs
```
To upgrade sgxwallet to the latest version do
```
sudo docker-compose stop
sudo docker-compose pull
sudo docker-compose up
```
Note: all docker-compose commands need to be issued from run_sgx_sim directory.
Note: sgxwallet places all its data into the sgx_data directory, which is created the first time you run sgxwallet.
Do not remove this directory!
Note: sgxwallet operates on network ports 1026 (https) and 1027 (http for initial registration).
If you have a firewall on your network, please make sure these ports are open so clients are able to
connect to the server.
## Configure logging
By default, sgxwallet will log into default Docker logs, which are rotated into four files 10M each.
To send logs to an external syslog service, edit docker compose YAML file to specify logging configuration as
```
logging:
driver: syslog
options:
syslog-address: "tcp://SYSLOG_SERVER_IP:PORT"
```
See docker-compose documentation for more options.
## Enable SGX on your machine
To build and run **sgxd**, you'll need **Intel SGX** capable hardware. Most Intel chips that were produced after 2015 support **SGX**.
Once your tried sgxwallet in the simulation mode, you can enable sgx on your machine, and run the server in production
mode. First, remove the simulation mode wallet by doing
```
sudo docker-compose rm
```
- Enter **BIOS** of you machine by pressing and holding **Del** or **F2** on boot-up and verify that **BIOS** includes **SGX options**.
You'll need **Intel SGX** capable hardware. Most Intel chips that were produced after 2015 support **SGX**.
- Enter **BIOS** of your machine by pressing and holding **Del** or **F2** on boot-up and verify that **BIOS** includes **SGX options**.
If not, your machine cant run **SGX**.
- Set SGX in BIOS as `enabled` or `software-controlled`.
- If you can set SGX to `enabled` you are done! Proceed with "Install SGX Driver" section
......@@ -30,10 +155,20 @@ To build and run **sgxd**, you'll need **Intel SGX** capable hardware. Most Inte
## Enable "software-controlled" SGX
To enable SGX using a software utility:
This repo includes the ***sgx_enable*** utility. To enable SGX run:
```bash
sudo ./sgx_enable
```
Note: if you are not using Ubuntu 18.04 (something that we do not recommend), you may need
to rebuild the sgx-software-enable utility before use by typing:
```bash
cd sgx-software-enable;
make
```
- Build `sgx-enable` utility by typing `cd sgx-software-enable; make`
- Run `./sgx_enable`. Verify that it says that **SGX** is successfully enabled
## Install SGX driver
......@@ -44,18 +179,23 @@ cd scripts; sudo ./sgx_linux_x64_driver_2.5.0_2605efa.bin; cd ..
Reboot you machine after driver install. Do `ls /dev/isgx` to check that `isgx` device is properly installed.
If you do not see the `isgx` device, you need to troubleshoot your driver installation.
## Install docker and docker-compose
```
sudo apt-get install docker.io docker-compose
```
## Run the latest sgxwallet docker container from dockerhub
## Run sgxwallet in secure SGX mode
Run the latest sgxwallet docker container image in SGX mode
```
cd run_sgx;
sudo docker-compose up -d
```
You should see "SGX Server started message".
Note: on some machines, the SGX device is not `/dev/mei0` but a different device, such
as "/dev/bs0". In this case please edit `docker-compose.yml` on your machine to specify the correct
device to use.
# Development
## Install Prerequisites
......@@ -68,14 +208,12 @@ sudo apt-get install build-essential make cmake gcc g++ yasm python libprotobuf
```bash
cd scripts; sudo ./sgx_linux_x64_sdk_2.5.100.49891.bin; cd ..
```
## Install required debian packages
```bash
cd scripts; sudo ./install_packages.sh; cd ..
```
## Build dependencies
......@@ -84,7 +222,6 @@ Dependencies only need to be built once.
```bash
cd scripts; ./build.py; cd ..
```
## Configure and build sgxwallet
......@@ -112,6 +249,7 @@ Note: to run in simulation mode, add --enable-sgx-simulation flag when you run c
Type:
```bash
source sgx-sdk-build/sgxsdk/environment;
./sgxwallet
```
......@@ -181,7 +319,7 @@ Example:
```bash
export URL_SGX_WALLET="http://127.0.0.1:1027"
curl -X POST --data '{ "jsonrpc": "2.0", "id": 2, "method": "SignCertificate", "params": { "certificate": "-----BEGIN CERTIFICATE REQUEST-----\nMIICYjCCAUoCAQAwHTEbMBkGA1UEAwwSc29tZVZlcnlVbmlxdWVOYW1lMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3C4ceRhzMAZnG87PwlkzMROHsm3B\ncPydIeiqs1dieuuvVETJqbXAcOENNsGA+AdXjZwFkDuIS24p2yZ8AwuIMAwdMsGa\n5Hzk0ugOy52iPyGEuooqV94nnL6eWw/zryTvkk7j239wMWn5our5Ia1/CBQlXXo2\n4IWTWfWYOz26SWUh4DuvzMOheMVSxg3KLaxpx7Bq09p32lR9xpl53+HqxSDIMYh9\nC3y3kA6NdkKsGE/Jt4WoZ5S5LlrhYjw+PFTeX2lbGDZpn/sxQIM16Pxo2LCfefIa\nik+aZBEAlpn22ljLZ5sEcVgBmOlL+v3waq9u0AaSYzdGFRA+0ceVwU/QTQIDAQAB\noAAwDQYJKoZIhvcNAQELBQADggEBAJXodL69Q/8zDt24AySXK0ksV3C3l5l10Hno\nfF6zKypsYev33CFbZu6HweSgK2f21+DeI9TsGKJxI7K6MUqyH0pJhwlFSeMB5/qP\nJueqXMuvStZSp0GGTaNy7Al/jzOKYNf0ePsv/Rx8NcOdy7RCZE0gW998B5jKb66x\nPgy6QvD8CkZULiRScYlOC8Ex6nc+1Z54pRC1NFWs/ugGyFgLJHy0J2gNkOv6yfsl\nH3V/ocCYSoF4ToUQAxwx+dcy4PXrL9vKzRNJgWzsI/LzCZkglo8iis9YZQawDOUf\nGmDMDkr0Fx1W1tSEpvkw0flkAXZ8PhIGCC0320jkuPeClt7OWNs=\n-----END CERTIFICATE REQUEST-----\n" } }' -H 'content-type:application/json;' $URL_SGX_WALLET
curl -X POST --data '{ "jsonrpc": "2.0", "id": 2, "method": "signCertificate", "params": { "certificate": "-----BEGIN CERTIFICATE REQUEST-----\nMIICYjCCAUoCAQAwHTEbMBkGA1UEAwwSc29tZVZlcnlVbmlxdWVOYW1lMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3C4ceRhzMAZnG87PwlkzMROHsm3B\ncPydIeiqs1dieuuvVETJqbXAcOENNsGA+AdXjZwFkDuIS24p2yZ8AwuIMAwdMsGa\n5Hzk0ugOy52iPyGEuooqV94nnL6eWw/zryTvkk7j239wMWn5our5Ia1/CBQlXXo2\n4IWTWfWYOz26SWUh4DuvzMOheMVSxg3KLaxpx7Bq09p32lR9xpl53+HqxSDIMYh9\nC3y3kA6NdkKsGE/Jt4WoZ5S5LlrhYjw+PFTeX2lbGDZpn/sxQIM16Pxo2LCfefIa\nik+aZBEAlpn22ljLZ5sEcVgBmOlL+v3waq9u0AaSYzdGFRA+0ceVwU/QTQIDAQAB\noAAwDQYJKoZIhvcNAQELBQADggEBAJXodL69Q/8zDt24AySXK0ksV3C3l5l10Hno\nfF6zKypsYev33CFbZu6HweSgK2f21+DeI9TsGKJxI7K6MUqyH0pJhwlFSeMB5/qP\nJueqXMuvStZSp0GGTaNy7Al/jzOKYNf0ePsv/Rx8NcOdy7RCZE0gW998B5jKb66x\nPgy6QvD8CkZULiRScYlOC8Ex6nc+1Z54pRC1NFWs/ugGyFgLJHy0J2gNkOv6yfsl\nH3V/ocCYSoF4ToUQAxwx+dcy4PXrL9vKzRNJgWzsI/LzCZkglo8iis9YZQawDOUf\nGmDMDkr0Fx1W1tSEpvkw0flkAXZ8PhIGCC0320jkuPeClt7OWNs=\n-----END CERTIFICATE REQUEST-----\n" } }' -H 'content-type:application/json;' $URL_SGX_WALLET
```
......
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file SEKManager.cpp
@author Stan Kladko
@date 2019
*/
#include "SEKManager.h"
#include "RPCException.h"
#include "BLSCrypto.h"
#include "LevelDB.h"
#include <iostream>
#include "sgxwallet_common.h"
#include "common.h"
#include "sgxwallet.h"
void generate_SEK(){
vector<char> errMsg(1024,0);
int err_status = 0;
vector<uint8_t> encr_SEK(1024, 0);
uint32_t enc_len = 0;
status = generate_SEK(eid, &err_status, errMsg.data(), encr_SEK.data(), &enc_len);
if ( err_status != 0 ){
cerr << "RPCException thrown" << endl;
throw RPCException(-666, errMsg.data()) ;
}
vector<char> hexEncrKey(2*enc_len + 1, 0);
carray2Hex(encr_SEK.data(), enc_len, hexEncrKey.data());
cerr << "key is " << errMsg.data() << endl;
LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data());
}
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file SEKManager.h
@author Stan Kladko
@date 2019
*/
#ifndef SGXD_SEKMANAGER_H
#define SGXD_SEKMANAGER_H
void generate_SEK();
#endif //SGXD_SEKMANAGER_H
......@@ -44,9 +44,11 @@
#include "LevelDB.h"
#include "spdlog/spdlog.h"
#include "common.h"
int DEBUG_PRINT = 0;
int is_sgx_https = 1;
int is_aes = 0;
SGXRegistrationServer *regs = nullptr;
HttpServer *hs2 = nullptr;
......@@ -63,30 +65,30 @@ SGXRegistrationServer::SGXRegistrationServer(AbstractServerConnector &connector,
: AbstractRegServer(connector, type), is_cert_created(false), cert_auto_sign(auto_sign) {}
Json::Value SignCertificateImpl(const std::string& csr, bool auto_sign = false){
Json::Value signCertificateImpl(const string& csr, bool auto_sign = false){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try{
spdlog::info("enter SignCertificateImpl");
spdlog::info("enter signCertificateImpl");
std::string status = "1";
std::string hash = cryptlite::sha256::hash_hex(csr);
string status = "1";
string hash = cryptlite::sha256::hash_hex(csr);
if ( !auto_sign) {
std::string db_key = "CSR:HASH:" + hash;
csrDb->writeDataUnique(db_key, csr);
string db_key = "CSR:HASH:" + hash;
LevelDB::getCsrStatusDb()->writeDataUnique(db_key, csr);
}
if (auto_sign) {
std::string csr_name = "cert/" + hash + ".csr";
std::ofstream outfile(csr_name);
outfile << csr << std::endl;
string csr_name = "cert/" + hash + ".csr";
ofstream outfile(csr_name);
outfile << csr << endl;
outfile.close();
if (access(csr_name.c_str(), F_OK) != 0) {
throw RPCException(FILE_NOT_FOUND, "Csr does not exist");
}
std::string genCert = "cd cert && ./create_client_cert " + hash;
string genCert = "cd cert && ./create_client_cert " + hash;
if (system(genCert.c_str()) == 0){
spdlog::info("CLIENT CERTIFICATE IS SUCCESSFULLY GENERATED");
......@@ -94,8 +96,8 @@ Json::Value SignCertificateImpl(const std::string& csr, bool auto_sign = false){
}
else{
spdlog::info("CLIENT CERTIFICATE GENERATION FAILED");
std::string status_db_key = "CSR:HASH:" + hash + "STATUS:";
csrStatusDb->writeDataUnique(status_db_key, std::to_string(FAIL_TO_CREATE_CERTIFICATE));
string status_db_key = "CSR:HASH:" + hash + "STATUS:";
LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, to_string(FAIL_TO_CREATE_CERTIFICATE));
throw RPCException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED");
//exit(-1);
}
......@@ -104,11 +106,11 @@ Json::Value SignCertificateImpl(const std::string& csr, bool auto_sign = false){
result["result"] = true;
result["hash"] = hash;
std::string db_key = "CSR:HASH:" + hash + "STATUS:";
csrStatusDb->writeDataUnique(db_key, status);
string db_key = "CSR:HASH:" + hash + "STATUS:";
LevelDB::getCsrStatusDb()->writeDataUnique(db_key, status);
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["result"] = false;
......@@ -117,26 +119,26 @@ Json::Value SignCertificateImpl(const std::string& csr, bool auto_sign = false){
return result;
}
Json::Value GetSertificateImpl(const std::string& hash){
Json::Value GetSertificateImpl(const string& hash){
Json::Value result;
std::string cert;
string cert;
try{
std::string db_key = "CSR:HASH:" + hash + "STATUS:";
std::shared_ptr<string> status_str_ptr = csrStatusDb->readString(db_key);
string db_key = "CSR:HASH:" + hash + "STATUS:";
shared_ptr<string> status_str_ptr = LevelDB::getCsrStatusDb()->readString(db_key);
if (status_str_ptr == nullptr){
throw RPCException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exist in csr db");
}
int status = std::atoi(status_str_ptr->c_str());
int status = atoi(status_str_ptr->c_str());
if ( status == 0){
std::string crt_name = "cert/" + hash + ".crt";
string crt_name = "cert/" + hash + ".crt";
//if (access(crt_name.c_str(), F_OK) == 0){
std::ifstream infile(crt_name);
ifstream infile(crt_name);
if (!infile.is_open()) {
std::string status_db_key = "CSR:HASH:" + hash + "STATUS:";
csrStatusDb->deleteKey(status_db_key);
csrStatusDb->writeDataUnique(status_db_key, std::to_string(FILE_NOT_FOUND));
string status_db_key = "CSR:HASH:" + hash + "STATUS:";
LevelDB::getCsrStatusDb()->deleteKey(status_db_key);
LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, to_string(FILE_NOT_FOUND));
throw RPCException(FILE_NOT_FOUND, "Certificate does not exist");
} else {
ostringstream ss;
......@@ -144,9 +146,9 @@ Json::Value GetSertificateImpl(const std::string& hash){
cert = ss.str();
infile.close();
std::string remove_crt = "cd cert && rm -rf " + hash + ".crt && rm -rf " + hash + ".csr";
string remove_crt = "cd cert && rm -rf " + hash + ".crt && rm -rf " + hash + ".csr";
if(system(remove_crt.c_str()) == 0){
//std::cerr << "cert removed" << std::endl;
//cerr << "cert removed" << endl;
spdlog::info(" cert removed ");
}
......@@ -161,7 +163,7 @@ Json::Value GetSertificateImpl(const std::string& hash){
result["cert"] = cert;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -170,13 +172,13 @@ Json::Value GetSertificateImpl(const std::string& hash){
}
Json::Value SGXRegistrationServer::SignCertificate(const std::string& csr){
spdlog::info("Enter SignCertificate ");
Json::Value SGXRegistrationServer::signCertificate(const string& csr){
spdlog::info("Enter signCertificate ");
lock_guard<recursive_mutex> lock(m);
return SignCertificateImpl(csr, cert_auto_sign);
return signCertificateImpl(csr, cert_auto_sign);
}
Json::Value SGXRegistrationServer::GetCertificate(const std::string& hash){
Json::Value SGXRegistrationServer::getCertificate(const string& hash){
lock_guard<recursive_mutex> lock(m);
return GetSertificateImpl(hash);
}
......@@ -190,19 +192,19 @@ void SGXRegistrationServer::set_cert_created(bool b){
int init_registration_server(bool sign_automatically) {
// std::string certPath = "cert/SGXCACertificate.crt";
// std::string keyPath = "cert/SGXCACertificate.key";
// string certPath = "cert/SGXCACertificate.crt";
// string keyPath = "cert/SGXCACertificate.key";
//
// if (access(certPath.c_str(), F_OK) != 0){
// std::cerr << "CERTIFICATE IS GOING TO BE CREATED" << std::endl;
// cerr << "CERTIFICATE IS GOING TO BE CREATED" << endl;
//
// std::string genCert = "cd cert && ./self-signed-tls -c=US -s=California -l=San-Francisco -o=\"Skale Labs\" -u=\"Department of Software Engineering\" -n=\"SGXCACertificate\" -e=info@skalelabs.com";
// string genCert = "cd cert && ./self-signed-tls -c=US -s=California -l=San-Francisco -o=\"Skale Labs\" -u=\"Department of Software Engineering\" -n=\"SGXCACertificate\" -e=info@skalelabs.com";
//
// if (system(genCert.c_str()) == 0){
// std::cerr << "CERTIFICATE IS SUCCESSFULLY GENERATED" << std::endl;
// cerr << "CERTIFICATE IS SUCCESSFULLY GENERATED" << endl;
// }
// else{
// std::cerr << "CERTIFICATE GENERATION FAILED" << std::endl;
// cerr << "CERTIFICATE GENERATION FAILED" << endl;
// exit(-1);
// }
// }
......
......@@ -44,8 +44,8 @@ public:
void set_cert_created(bool b);
virtual Json::Value SignCertificate(const std::string& csr);
virtual Json::Value GetCertificate(const std::string& hash);
virtual Json::Value signCertificate(const std::string& csr);
virtual Json::Value getCertificate(const std::string& hash);
};
......
......@@ -43,17 +43,13 @@
#include "spdlog/spdlog.h"
//#if __cplusplus < 201412L
//#error expecting C++17 standard
//#endif
#include "common.h"
//#include <boost/filesystem.hpp>
bool isStringDec( std::string & str){
auto res = std::find_if_not(str.begin(), str.end(), [](char c)->bool{
return std::isdigit(c);
bool isStringDec( string & str){
auto res = find_if_not(str.begin(), str.end(), [](char c)->bool{
return isdigit(c);
});
return !str.empty() && res == str.end();
}
......@@ -67,29 +63,29 @@ SGXWalletServer::SGXWalletServer(AbstractServerConnector &connector,
: AbstractStubServer(connector, type) {}
void debug_print(){
std::cout << "HERE ARE YOUR KEYS: " << std::endl;
cout << "HERE ARE YOUR KEYS: " << endl;
class MyVisitor: public LevelDB::KeyVisitor {
public:
virtual void visitDBKey(const char* _data){
std::cout << _data << std::endl;
cout << _data << endl;
}
};
MyVisitor v;
levelDb->visitKeys(&v, 100000000);
LevelDB::getLevelDb()->visitKeys(&v, 100000000);
}
int init_https_server(bool check_certs) {
std::string rootCAPath = std::string(SGXDATA_FOLDER) + "cert_data/rootCA.pem";
std::string keyCAPath = std::string(SGXDATA_FOLDER) + "cert_data/rootCA.key";
string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem";
string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key";
if (access(rootCAPath.c_str(), F_OK) != 0 || access(keyCAPath.c_str(), F_OK) != 0){
spdlog::info("YOU DO NOT HAVE ROOT CA CERTIFICATE");
spdlog::info("ROOT CA CERTIFICATE IS GOING TO BE CREATED");
std::string genRootCACert = "cd cert && ./create_CA";
string genRootCACert = "cd cert && ./create_CA";
if (system(genRootCACert.c_str()) == 0){
spdlog::info("ROOT CA CERTIFICATE IS SUCCESSFULLY GENERATED");
......@@ -100,14 +96,14 @@ int init_https_server(bool check_certs) {
}
}
std::string certPath = std::string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.crt";
std::string keyPath = std::string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.key";
string certPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.crt";
string keyPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.key";
if (access(certPath.c_str(), F_OK) != 0 || access(certPath.c_str(), F_OK) != 0){
spdlog::info("YOU DO NOT HAVE SERVER CERTIFICATE");
spdlog::info("SERVER CERTIFICATE IS GOING TO BE CREATED");
std::string genCert = "cd cert && ./create_server_cert";
string genCert = "cd cert && ./create_server_cert";
if (system(genCert.c_str()) == 0){
spdlog::info("SERVER CERTIFICATE IS SUCCESSFULLY GENERATED");
......@@ -146,7 +142,7 @@ int init_http_server() { //without ssl
}
Json::Value
importBLSKeyShareImpl(const std::string &_keyShare, const std::string &_keyShareName, int t, int n, int index) {
importBLSKeyShareImpl(const string &_keyShare, const string &_keyShareName, int t, int n, int index) {
Json::Value result;
int errStatus = UNKNOWN_ERROR;
......@@ -182,7 +178,7 @@ importBLSKeyShareImpl(const std::string &_keyShare, const std::string &_keyShare
return result;
}
Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::string &messageHash,int t, int n, int signerIndex) {
Json::Value blsSignMessageHashImpl(const string &keyShareName, const string &messageHash,int t, int n, int signerIndex) {
Json::Value result;
result["status"] = -1;
result["errorMessage"] = "Unknown server error";
......@@ -190,13 +186,13 @@ Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::s
char *signature = (char *) calloc(BUF_LEN, 1);
shared_ptr <std::string> value = nullptr;
shared_ptr <string> value = nullptr;
try {
if ( !checkName(keyShareName, "BLS_KEY")){
throw RPCException(INVALID_POLY_NAME, "Invalid BLSKey name");
}
std::string cutHash = messageHash;
string cutHash = messageHash;
if (cutHash[0] == '0' && (cutHash[1] == 'x'||cutHash[1] == 'X')){
cutHash.erase(cutHash.begin(), cutHash.begin() + 2);
}
......@@ -214,7 +210,7 @@ Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::s
result["errorMessage"] = _e.errString;
return result;
} catch (...) {
std::exception_ptr p = std::current_exception();
exception_ptr p = current_exception();
printf("Exception %s \n", p.__cxa_exception_type()->name());
result["status"] = -1;
result["errorMessage"] = "Read key share has thrown exception:";
......@@ -240,7 +236,7 @@ Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::s
}
Json::Value importECDSAKeyImpl(const std::string &key, const std::string &keyName) {
Json::Value importECDSAKeyImpl(const string &key, const string &keyName) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -258,7 +254,7 @@ Json::Value generateECDSAKeyImpl() {
spdlog::info("Calling method generateECDSAKey");
std::vector<std::string>keys;
vector<string>keys;
try {
keys = gen_ecdsa_key();
......@@ -267,7 +263,7 @@ Json::Value generateECDSAKeyImpl() {
throw RPCException(UNKNOWN_ERROR, "key was not generated");
}
std::string keyName = "NEK:" + keys.at(2);
string keyName = "NEK:" + keys.at(2);
if (DEBUG_PRINT) {
spdlog::info("write encr key {}", keys.at(0));
......@@ -275,15 +271,14 @@ Json::Value generateECDSAKeyImpl() {
spdlog::info("key name generated: {}", keyName);
}
//writeECDSAKey(keyName, keys.at(0));
writeDataToDB(keyName, keys.at(0));
result["encryptedKey"] = keys.at(0);
result["PublicKey"] = keys.at(1);
result["KeyName"] = keyName;
result["publicKey"] = keys.at(1);
result["keyName"] = keyName;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -291,7 +286,7 @@ Json::Value generateECDSAKeyImpl() {
return result;
}
Json::Value renameECDSAKeyImpl(const std::string& KeyName, const std::string& tempKeyName){
Json::Value renameECDSAKeyImpl(const string& KeyName, const string& tempKeyName){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -299,7 +294,7 @@ Json::Value renameECDSAKeyImpl(const std::string& KeyName, const std::string& te
try {
std::string prefix = tempKeyName.substr(0,8);
string prefix = tempKeyName.substr(0,8);
if (prefix != "tmp_NEK:") {
throw RPCException(UNKNOWN_ERROR, "wrong temp key name");
}
......@@ -307,18 +302,18 @@ Json::Value renameECDSAKeyImpl(const std::string& KeyName, const std::string& te
if (prefix != "NEK_NODE_ID:") {
throw RPCException(UNKNOWN_ERROR, "wrong key name");
}
std::string postfix = KeyName.substr(12, KeyName.length());
string postfix = KeyName.substr(12, KeyName.length());
if (!isStringDec(postfix)){
throw RPCException(UNKNOWN_ERROR, "wrong key name");
}
std::shared_ptr<std::string> key_ptr = readFromDb(tempKeyName);
std::cerr << "new key name is " << KeyName <<std::endl;
shared_ptr<string> key_ptr = readFromDb(tempKeyName);
cerr << "new key name is " << KeyName <<endl;
writeDataToDB(KeyName, *key_ptr);
levelDb->deleteTempNEK(tempKeyName);
LevelDB::getLevelDb()->deleteTempNEK(tempKeyName);
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -327,7 +322,7 @@ Json::Value renameECDSAKeyImpl(const std::string& KeyName, const std::string& te
}
Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, const std::string &messageHash) {
Json::Value ecdsaSignMessageHashImpl(int base, const string &_keyName, const string &messageHash) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -335,7 +330,7 @@ Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, cons
result["signature_r"] = "";
result["signature_s"] = "";
std::vector<std::string> sign_vect(3);
vector<string> sign_vect(3);
if (DEBUG_PRINT) {
spdlog::info("entered ecdsaSignMessageHashImpl {}", messageHash, "length {}", messageHash.length());
......@@ -343,7 +338,7 @@ Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, cons
try {
std::string cutHash = messageHash;
string cutHash = messageHash;
if (cutHash[0] == '0' && (cutHash[1] == 'x'||cutHash[1] == 'X')){
cutHash.erase(cutHash.begin(), cutHash.begin() + 2);
}
......@@ -365,7 +360,7 @@ Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, cons
throw RPCException(-22, "Invalid base");
}
std::shared_ptr<std::string> key_ptr = readFromDb(_keyName,"");
shared_ptr<string> key_ptr = readFromDb(_keyName,"");
sign_vect = ecdsa_sign_hash(key_ptr->c_str(), cutHash.c_str(), base);
if (sign_vect.size() != 3 ){
......@@ -381,7 +376,7 @@ Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, cons
result["signature_s"] = sign_vect.at(2);
} catch (RPCException &_e) {
std::cerr << "err str " << _e.errString << std::endl;
cerr << "err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -389,27 +384,27 @@ Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, cons
return result;
}
Json::Value getPublicECDSAKeyImpl(const std::string& keyName){
Json::Value getPublicECDSAKeyImpl(const string& keyName){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
result["PublicKey"] = "";
result["publicKey"] = "";
spdlog::info("Calling method getPublicECDSAKey");
std::string Pkey;
string Pkey;
try {
if ( !checkECDSAKeyName(keyName)){
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
std::shared_ptr<std::string> key_ptr = readFromDb(keyName);
shared_ptr<string> key_ptr = readFromDb(keyName);
Pkey = get_ecdsa_pubkey( key_ptr->c_str());
if (DEBUG_PRINT) {
spdlog::info("PublicKey {}", Pkey);
spdlog::info("PublicKey length {}", Pkey.length());
}
result["PublicKey"] = Pkey;
result["publicKey"] = Pkey;
} catch (RPCException &_e) {
result["status"] = _e.status;
......@@ -419,14 +414,14 @@ Json::Value getPublicECDSAKeyImpl(const std::string& keyName){
return result;
}
Json::Value generateDKGPolyImpl(const std::string& polyName, int t) {
Json::Value generateDKGPolyImpl(const string& polyName, int t) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
//result["encryptedPoly"] = "";
std::string encrPolyHex;
string encrPolyHex;
try {
if ( !checkName(polyName, "POLY")){
......@@ -440,7 +435,7 @@ Json::Value generateDKGPolyImpl(const std::string& polyName, int t) {
//result["encryptedPoly"] = encrPolyHex;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -448,13 +443,13 @@ Json::Value generateDKGPolyImpl(const std::string& polyName, int t) {
return result;
}
Json::Value getVerificationVectorImpl(const std::string& polyName, int t, int n) {
Json::Value getVerificationVectorImpl(const string& polyName, int t, int n) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
std::vector <std::vector<std::string>> verifVector;
vector <vector<string>> verifVector;
try {
if ( !checkName(polyName, "POLY")){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
......@@ -463,29 +458,29 @@ Json::Value getVerificationVectorImpl(const std::string& polyName, int t, int n)
throw RPCException(INVALID_DKG_PARAMS, "Invalid parameters: n or t ");
}
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName);
shared_ptr<string> encr_poly_ptr = readFromDb(polyName);
verifVector = get_verif_vect(encr_poly_ptr->c_str(), t, n);
//std::cerr << "verif vect size " << verifVector.size() << std::endl;
//cerr << "verif vect size " << verifVector.size() << endl;
for ( int i = 0; i < t; i++){
std::vector<std::string> cur_coef = verifVector.at(i);
vector<string> cur_coef = verifVector.at(i);
for ( int j = 0; j < 4; j++ ){
result["Verification Vector"][i][j] = cur_coef.at(j);
result["verificationVector"][i][j] = cur_coef.at(j);
}
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["Verification Vector"] = "";
result["verificationVector"] = "";
}
return result;
}
Json::Value getSecretShareImpl(const std::string& polyName, const Json::Value& publicKeys, int t, int n){
Json::Value getSecretShareImpl(const string& polyName, const Json::Value& publicKeys, int t, int n){
spdlog::info("enter getSecretShareImpl");
Json::Value result;
result["status"] = 0;
......@@ -502,9 +497,9 @@ Json::Value getSecretShareImpl(const std::string& polyName, const Json::Value& p
throw RPCException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName);
shared_ptr<string> encr_poly_ptr = readFromDb(polyName);
std::vector<std::string> pubKeys_vect;
vector<string> pubKeys_vect;
for ( int i = 0; i < n ; i++) {
if ( !checkHex(publicKeys[i].asString(), 64)){
throw RPCException(INVALID_HEX, "Invalid public key");
......@@ -512,24 +507,24 @@ Json::Value getSecretShareImpl(const std::string& polyName, const Json::Value& p
pubKeys_vect.push_back(publicKeys[i].asString());
}
std::string s = get_secret_shares(polyName, encr_poly_ptr->c_str(), pubKeys_vect, t, n);
//std::cerr << "result is " << s << std::endl;
result["SecretShare"] = s;
string s = get_secret_shares(polyName, encr_poly_ptr->c_str(), pubKeys_vect, t, n);
//cerr << "result is " << s << endl;
result["secretShare"] = s;
} catch (RPCException &_e) {
//std::cerr << " err str " << _e.errString << std::endl;
//cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["SecretShare"] = "";
result["secretShare"] = "";
}
return result;
}
Json::Value DKGVerificationImpl(const std::string& publicShares, const std::string& EthKeyName,
const std::string& SecretShare, int t, int n, int ind){
Json::Value dkgVerificationImpl(const string& publicShares, const string& ethKeyName,
const string& SecretShare, int t, int n, int ind){
spdlog::info("enter DKGVerificationImpl");
spdlog::info("enter dkgVerificationImpl");
Json::Value result;
result["status"] = 0;
......@@ -538,7 +533,7 @@ Json::Value DKGVerificationImpl(const std::string& publicShares, const std::stri
try {
if ( !checkECDSAKeyName(EthKeyName)){
if ( !checkECDSAKeyName(ethKeyName)){
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
if( !check_n_t(t, n) || ind > n || ind < 0){
......@@ -551,14 +546,14 @@ Json::Value DKGVerificationImpl(const std::string& publicShares, const std::stri
throw RPCException(INVALID_DKG_PARAMS, "Invalid length of public shares");
}
std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(EthKeyName);
shared_ptr<string> encryptedKeyHex_ptr = readFromDb(ethKeyName);
if ( !VerifyShares(publicShares.c_str(), SecretShare.c_str(), encryptedKeyHex_ptr->c_str(), t, n, ind )){
result["result"] = false;
}
} catch (RPCException &_e) {
//std::cerr << " err str " << _e.errString << std::endl;
//cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["result"] = false;
......@@ -567,9 +562,9 @@ Json::Value DKGVerificationImpl(const std::string& publicShares, const std::stri
return result;
}
Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n){
Json::Value createBLSPrivateKeyImpl(const string & blsKeyName, const string& ethKeyName, const string& polyName, const string & SecretShare, int t, int n){
spdlog::info("CreateBLSPrivateKeyImpl entered");
spdlog::info("createBLSPrivateKeyImpl entered");
Json::Value result;
result["status"] = 0;
......@@ -582,26 +577,26 @@ Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::s
spdlog::info("secret shares - {}", SecretShare);
throw RPCException(INVALID_SECRET_SHARES_LENGTH, "Invalid secret share length");
}
if ( !checkECDSAKeyName(EthKeyName)){
if ( !checkECDSAKeyName(ethKeyName)){
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
if ( !checkName(polyName, "POLY")){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
if ( !checkName(BLSKeyName, "BLS_KEY")){
if ( !checkName(blsKeyName, "BLS_KEY")){
throw RPCException(INVALID_POLY_NAME, "Invalid BLS key name");
}
if( !check_n_t(t, n)){
throw RPCException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
std::vector<std::string> sshares_vect;
vector<string> sshares_vect;
if (DEBUG_PRINT) {
spdlog::info("secret shares from json are - {}", SecretShare);
}
std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(EthKeyName);
shared_ptr<string> encryptedKeyHex_ptr = readFromDb(ethKeyName);
bool res = CreateBLSShare(BLSKeyName, SecretShare.c_str(), encryptedKeyHex_ptr->c_str());
bool res = CreateBLSShare(blsKeyName, SecretShare.c_str(), encryptedKeyHex_ptr->c_str());
if (res){
spdlog::info("BLS KEY SHARE CREATED ");
}
......@@ -610,14 +605,14 @@ Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::s
}
for ( int i = 0; i < n; i++){
std::string name = polyName + "_" + std::to_string(i) + ":";
levelDb -> deleteDHDKGKey(name);
std::string shareG2_name = "shareG2_" + polyName + "_" + std::to_string(i) + ":";
levelDb -> deleteKey(shareG2_name);
string name = polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb() -> deleteDHDKGKey(name);
string shareG2_name = "shareG2_" + polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb() -> deleteKey(shareG2_name);
}
} catch (RPCException &_e) {
//std::cerr << " err str " << _e.errString << std::endl;
//cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
......@@ -626,30 +621,30 @@ Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::s
return result;
}
Json::Value GetBLSPublicKeyShareImpl(const std::string & BLSKeyName){
Json::Value getBLSPublicKeyShareImpl(const string & blsKeyName){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
if ( !checkName(BLSKeyName, "BLS_KEY")){
if ( !checkName(blsKeyName, "BLS_KEY")){
throw RPCException(INVALID_POLY_NAME, "Invalid BLSKey name");
}
std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(BLSKeyName);
shared_ptr<string> encryptedKeyHex_ptr = readFromDb(blsKeyName);
if (DEBUG_PRINT) {
spdlog::info("encr_bls_key_share is {}", *encryptedKeyHex_ptr);
spdlog::info("length is {}", encryptedKeyHex_ptr->length());
//std::cerr << "encr_bls_key_share is " << *encryptedKeyHex_ptr << std::endl;
// std::cerr << "length is " << encryptedKeyHex_ptr->length() << std::endl;
//cerr << "encr_bls_key_share is " << *encryptedKeyHex_ptr << endl;
// cerr << "length is " << encryptedKeyHex_ptr->length() << endl;
}
std::vector<std::string> public_key_vect = GetBLSPubKey(encryptedKeyHex_ptr->c_str());
vector<string> public_key_vect = GetBLSPubKey(encryptedKeyHex_ptr->c_str());
for ( uint8_t i = 0; i < 4; i++) {
result["BLSPublicKeyShare"][i] = public_key_vect.at(i);
result["blsPublicKeyShare"][i] = public_key_vect.at(i);
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -659,7 +654,7 @@ Json::Value GetBLSPublicKeyShareImpl(const std::string & BLSKeyName){
return result;
}
Json::Value ComplaintResponseImpl(const std::string& polyName, int ind){
Json::Value complaintResponseImpl(const string& polyName, int ind){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -667,16 +662,16 @@ Json::Value ComplaintResponseImpl(const std::string& polyName, int ind){
if ( !checkName(polyName, "POLY")){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
std::string shareG2_name = "shareG2_" + polyName + "_" + std::to_string(ind) + ":";
std::shared_ptr<std::string> shareG2_ptr = readFromDb(shareG2_name);
string shareG2_name = "shareG2_" + polyName + "_" + to_string(ind) + ":";
shared_ptr<string> shareG2_ptr = readFromDb(shareG2_name);
std::string DHKey = decrypt_DHKey(polyName, ind);
string DHKey = decrypt_DHKey(polyName, ind);
result["share*G2"] = *shareG2_ptr;
result["DHKey"] = DHKey;
result["dhKey"] = DHKey;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -685,19 +680,19 @@ Json::Value ComplaintResponseImpl(const std::string& polyName, int ind){
}
Json::Value MultG2Impl(const std::string& x){
Json::Value multG2Impl(const string& x){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
spdlog::info("MultG2Impl try ");
std::vector<std::string> xG2_vect = mult_G2(x);
spdlog::info("multG2Impl try ");
vector<string> xG2_vect = mult_G2(x);
for ( uint8_t i = 0; i < 4; i++) {
result["x*G2"][i] = xG2_vect.at(i);
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
......@@ -705,6 +700,28 @@ Json::Value MultG2Impl(const std::string& x){
return result;
}
Json::Value isPolyExistsImpl(const string& polyName){
Json::Value result;
try {
std::shared_ptr<std::string> poly_str_ptr = LevelDB::getLevelDb()->readString(polyName);
result["IsExist"] = true;
result["status"] = 0;
result["errorMessage"] = "";
if (poly_str_ptr == nullptr){
result["IsExist"] = false;
result["status"] = 0;
result["errorMessage"] = "";
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["IsExist"] = false;
}
return result;
}
Json::Value getServerStatusImpl() {
Json::Value result;
......@@ -715,35 +732,35 @@ Json::Value getServerStatusImpl() {
}
Json::Value SGXWalletServer::generateDKGPoly(const std::string& polyName, int t){
Json::Value SGXWalletServer::generateDKGPoly(const string& polyName, int t){
spdlog::info("entered generateDKGPoly");
lock_guard<recursive_mutex> lock(m);
return generateDKGPolyImpl(polyName, t);
}
Json::Value SGXWalletServer::getVerificationVector(const std::string& polyName, int t, int n){
Json::Value SGXWalletServer::getVerificationVector(const string& polyName, int t, int n){
lock_guard<recursive_mutex> lock(m);
return getVerificationVectorImpl(polyName, t, n);
}
Json::Value SGXWalletServer::getSecretShare(const std::string& polyName, const Json::Value& publicKeys, int t, int n){
Json::Value SGXWalletServer::getSecretShare(const string& polyName, const Json::Value& publicKeys, int t, int n){
lock_guard<recursive_mutex> lock(m);
return getSecretShareImpl(polyName, publicKeys, t, n);
}
Json::Value SGXWalletServer::DKGVerification( const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index){
Json::Value SGXWalletServer::dkgVerification( const string& publicShares, const string& ethKeyName, const string& SecretShare, int t, int n, int index){
lock_guard<recursive_mutex> lock(m);
return DKGVerificationImpl(publicShares, EthKeyName, SecretShare, t, n, index);
return dkgVerificationImpl(publicShares, ethKeyName, SecretShare, t, n, index);
}
Json::Value SGXWalletServer::CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n){
Json::Value SGXWalletServer::createBLSPrivateKey(const string & blsKeyName, const string& ethKeyName, const string& polyName, const string& SecretShare, int t, int n){
lock_guard<recursive_mutex> lock(m);
return CreateBLSPrivateKeyImpl(BLSKeyName, EthKeyName, polyName, SecretShare, t, n);
return createBLSPrivateKeyImpl(blsKeyName, ethKeyName, polyName, SecretShare, t, n);
}
Json::Value SGXWalletServer::GetBLSPublicKeyShare(const std::string & BLSKeyName){
Json::Value SGXWalletServer::getBLSPublicKeyShare(const string & blsKeyName){
lock_guard<recursive_mutex> lock(m);
return GetBLSPublicKeyShareImpl(BLSKeyName);
return getBLSPublicKeyShareImpl(blsKeyName);
}
......@@ -753,18 +770,18 @@ Json::Value SGXWalletServer::generateECDSAKey() {
return generateECDSAKeyImpl();
}
Json::Value SGXWalletServer::renameECDSAKey(const std::string& KeyName, const std::string& tempKeyName){
Json::Value SGXWalletServer::renameECDSAKey(const string& KeyName, const string& tempKeyName){
lock_guard<recursive_mutex> lock(m);
return renameECDSAKeyImpl(KeyName, tempKeyName);
}
Json::Value SGXWalletServer::getPublicECDSAKey(const std::string &_keyName) {
Json::Value SGXWalletServer::getPublicECDSAKey(const string &_keyName) {
lock_guard<recursive_mutex> lock(m);
return getPublicECDSAKeyImpl(_keyName);
}
Json::Value SGXWalletServer::ecdsaSignMessageHash(int base, const std::string &_keyName, const std::string &messageHash ) {
Json::Value SGXWalletServer::ecdsaSignMessageHash(int base, const string &_keyName, const string &messageHash ) {
lock_guard<recursive_mutex> lock(m);
spdlog::info("entered ecdsaSignMessageHash");
if (DEBUG_PRINT) {
......@@ -775,31 +792,36 @@ Json::Value SGXWalletServer::ecdsaSignMessageHash(int base, const std::string &_
Json::Value
SGXWalletServer::importBLSKeyShare(const std::string &_keyShare, const std::string &_keyShareName, int t, int n,
SGXWalletServer::importBLSKeyShare(const string &_keyShare, const string &_keyShareName, int t, int n,
int index) {
lock_guard<recursive_mutex> lock(m);
return importBLSKeyShareImpl(_keyShare, _keyShareName, t, n, index );
}
Json::Value SGXWalletServer::blsSignMessageHash(const std::string &keyShareName, const std::string &messageHash, int t, int n,
Json::Value SGXWalletServer::blsSignMessageHash(const string &keyShareName, const string &messageHash, int t, int n,
int signerIndex) {
lock_guard<recursive_mutex> lock(m);
return blsSignMessageHashImpl(keyShareName, messageHash, t, n, signerIndex);
}
Json::Value SGXWalletServer::importECDSAKey(const std::string &key, const std::string &keyName) {
Json::Value SGXWalletServer::importECDSAKey(const string &key, const string &keyName) {
lock_guard<recursive_mutex> lock(m);
return importECDSAKeyImpl(key, keyName);
}
Json::Value SGXWalletServer::ComplaintResponse(const std::string& polyName, int ind){
Json::Value SGXWalletServer::complaintResponse(const string& polyName, int ind){
lock_guard<recursive_mutex> lock(m);
return ComplaintResponseImpl(polyName, ind);
return complaintResponseImpl(polyName, ind);
}
Json::Value SGXWalletServer::multG2(const string& x){
lock_guard<recursive_mutex> lock(m);
return multG2Impl(x);
}
Json::Value SGXWalletServer::MultG2(const std::string& x){
Json::Value SGXWalletServer::isPolyExists(const string& polyName){
lock_guard<recursive_mutex> lock(m);
return MultG2Impl(x);
return isPolyExistsImpl(polyName);
}
Json::Value SGXWalletServer::getServerStatus() {
......@@ -809,7 +831,7 @@ Json::Value SGXWalletServer::getServerStatus() {
shared_ptr<string> readFromDb(const string & name, const string & prefix) {
auto dataStr = levelDb->readString(prefix + name);
auto dataStr = LevelDB::getLevelDb()->readString(prefix + name);
if (dataStr == nullptr) {
throw RPCException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exist");
......@@ -820,7 +842,7 @@ shared_ptr<string> readFromDb(const string & name, const string & prefix) {
shared_ptr<string> readKeyShare(const string &_keyShareName) {
auto keyShareStr = levelDb->readString("BLSKEYSHARE:" + _keyShareName);
auto keyShareStr = LevelDB::getLevelDb()->readString("BLSKEYSHARE:" + _keyShareName);
if (keyShareStr == nullptr) {
throw RPCException(KEY_SHARE_DOES_NOT_EXIST, "Key share with this name does not exist");
......@@ -840,15 +862,15 @@ void writeKeyShare(const string &_keyShareName, const string &value, int index,
val["index"] = index;
val["n'"] = n;
std::string json = writer.write(val);
string json = writer.write(val);
auto key = "BLSKEYSHARE:" + _keyShareName;
if (levelDb->readString(_keyShareName) != nullptr) {
if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) {
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
}
levelDb->writeString(key, value);
LevelDB::getLevelDb()->writeString(key, value);
}
void writeDataToDB(const string & Name, const string &value) {
......@@ -856,16 +878,16 @@ void writeDataToDB(const string & Name, const string &value) {
Json::FastWriter writer;
val["value"] = value;
std::string json = writer.write(val);
string json = writer.write(val);
auto key = Name;
if (levelDb->readString(Name) != nullptr) {
if (LevelDB::getLevelDb()->readString(Name) != nullptr) {
spdlog::info("name {}", Name, " already exists");
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
}
levelDb->writeString(key, value);
LevelDB::getLevelDb()->writeString(key, value);
if (DEBUG_PRINT) {
spdlog::info("{} ", Name, " is written to db ");
}
......
......@@ -56,11 +56,12 @@ public:
virtual Json::Value generateDKGPoly(const std::string& polyName, int t);
virtual Json::Value getVerificationVector(const std::string& polyName, int t, int n);
virtual Json::Value getSecretShare(const std::string& polyName, const Json::Value& publicKeys, int t, int n);
virtual Json::Value DKGVerification(const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index);
virtual Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
virtual Json::Value GetBLSPublicKeyShare(const std::string & BLSKeyName);
virtual Json::Value ComplaintResponse(const std::string& polyName, int ind);
virtual Json::Value MultG2(const std::string & x);
virtual Json::Value dkgVerification(const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index);
virtual Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
virtual Json::Value getBLSPublicKeyShare(const std::string & blsKeyName);
virtual Json::Value complaintResponse(const std::string& polyName, int ind);
virtual Json::Value multG2(const std::string & x);
virtual Json::Value isPolyExists(const std::string& polyName);
virtual Json::Value getServerStatus();
};
......@@ -83,11 +84,13 @@ Json::Value getPublicECDSAKeyImpl(const std::string& keyName);
Json::Value generateDKGPolyImpl(const std::string& polyName, int t);
Json::Value getVerificationVectorImpl(const std::string& polyName, int t, int n);
Json::Value getSecretShareImpl(const std::string& polyName, const Json::Value& publicKeys, int t, int n);
Json::Value DKGVerificationImpl(const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index);
Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
Json::Value GetBLSPublicKeyShareImpl(const std::string & BLSKeyName);
Json::Value ComplaintResponseImpl(const std::string& polyName, int ind);
Json::Value MultG2Impl(const std::string & x);
Json::Value dkgVerificationImpl(const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index);
Json::Value createBLSPrivateKeyImpl(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
Json::Value getBLSPublicKeyShareImpl(const std::string & blsKeyName);
Json::Value complaintResponseImpl(const std::string& polyName, int ind);
Json::Value multG2Impl(const std::string & x);
Json::Value isPolyExistsImpl(const std::string& polyName);
Json::Value getServerStatusImpl();
#endif //SGXWALLET_SGXWALLETSERVER_HPP
\ No newline at end of file
......@@ -28,14 +28,15 @@
#include <iostream>
#include "spdlog/spdlog.h"
#include "common.h"
std::vector<std::string> SplitString(const std::string& str, const std::string& delim = ":"){
std::vector<std::string> tokens;
vector<string> SplitString(const string& str, const string& delim = ":"){
vector<string> tokens;
size_t prev = 0, pos = 0;
do {
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
......@@ -43,8 +44,8 @@ std::vector<std::string> SplitString(const std::string& str, const std::string&
return tokens;
}
bool checkECDSAKeyName(const std::string& keyName) {
std::vector<std::string> parts = SplitString(keyName);
bool checkECDSAKeyName(const string& keyName) {
vector<string> parts = SplitString(keyName);
if (parts.size() != 2) {
spdlog::info("ECDSAKeyName num parts != 2");
return false;
......@@ -69,7 +70,7 @@ bool checkECDSAKeyName(const std::string& keyName) {
return true;
}
bool checkHex(const std::string& hex, const uint32_t sizeInBytes){
bool checkHex(const string& hex, const uint32_t sizeInBytes){
if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){
return false;
}
......@@ -86,8 +87,8 @@ bool checkHex(const std::string& hex, const uint32_t sizeInBytes){
return true;
}
bool checkName (const std::string& Name, const std::string& prefix){
std::vector<std::string> parts = SplitString(Name);
bool checkName (const string& Name, const string& prefix){
vector<string> parts = SplitString(Name);
if ( parts.size() != 7) {
spdlog::info("parts.size() != 7");
return false;
......
......@@ -52,44 +52,33 @@
#include "BLSCrypto.h"
#include "ServerInit.h"
#include "SEKManager.h"
#include <iostream>
#include "spdlog/spdlog.h"
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <system>
void init_daemon() {
libff::init_alt_bn128_params();
std::string sgx_data_folder = SGXDATA_FOLDER;
struct stat info;
if (stat(sgx_data_folder.c_str(), &info) !=0 ){
spdlog::info("going to create sgx_data folder");
std::string make_sgx_data_folder = "mkdir " + sgx_data_folder;
if (system(make_sgx_data_folder.c_str()) == 0){
spdlog::info("sgx_data folder was created");
}
else{
spdlog::info("creating sgx_data folder failed");
exit(-1);
}
}
static std::string dbName = sgx_data_folder + WALLETDB_NAME;
levelDb = new LevelDB(dbName);
static std::string csr_dbname = sgx_data_folder + "CSR_DB";
csrDb = new LevelDB(csr_dbname);
LevelDB::initDataFolderAndDBs();
static std::string csr_status_dbname = sgx_data_folder + "CSR_STATUS_DB";
csrStatusDb = new LevelDB(csr_status_dbname);
std::shared_ptr<std::string> encr_SEK_ptr = levelDb->readString("SEK");
std::shared_ptr<std::string> encr_SEK_ptr = LevelDB::getLevelDb()->readString("SEK");
if (encr_SEK_ptr == nullptr){
spdlog::info("SEK was not created yet");
generate_SEK();
}
}
......@@ -100,9 +89,10 @@ void init_enclave() {
eid = 0;
updated = 0;
unsigned long support;
#ifndef SGX_HW_SIM
unsigned long support;
support = get_sgx_support();
if (!SGX_OK(support)) {
sgx_support_perror(support);
......@@ -150,6 +140,8 @@ void init_all(bool check_cert, bool sign_automatically) {
if (sgxServerInited == 1)
return;
init_daemon();
sgxServerInited = 1;
if (is_sgx_https) {
......@@ -162,5 +154,5 @@ void init_all(bool check_cert, bool sign_automatically) {
}
init_enclave();
//std::cerr << "enclave inited" << std::endl;
init_daemon();
}
......@@ -31,7 +31,6 @@
#endif
EXTERNC void init_all(bool check_cert, bool sign_automatically);
EXTERNC void init_daemon();
......
......@@ -12,22 +12,22 @@ class abstractCSRManagerServer : public jsonrpc::AbstractServer<abstractCSRManag
public:
abstractCSRManagerServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer<abstractCSRManagerServer>(conn, type)
{
this->bindAndAddMethod(jsonrpc::Procedure("GetUnsignedCSRs", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &abstractCSRManagerServer::GetUnsignedCSRsI);
this->bindAndAddMethod(jsonrpc::Procedure("SignByHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"hash",jsonrpc::JSON_STRING, "status", jsonrpc::JSON_INTEGER, NULL), &abstractCSRManagerServer::SignByHashI);
this->bindAndAddMethod(jsonrpc::Procedure("getUnsignedCSRs", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &abstractCSRManagerServer::getUnsignedCSRsI);
this->bindAndAddMethod(jsonrpc::Procedure("signByHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"hash",jsonrpc::JSON_STRING, "status", jsonrpc::JSON_INTEGER, NULL), &abstractCSRManagerServer::signByHashI);
}
inline virtual void GetUnsignedCSRsI(const Json::Value &request, Json::Value &response)
inline virtual void getUnsignedCSRsI(const Json::Value &request, Json::Value &response)
{
(void)request;
response = this->GetUnsignedCSRs();
response = this->getUnsignedCSRs();
}
inline virtual void SignByHashI(const Json::Value &request, Json::Value &response)
inline virtual void signByHashI(const Json::Value &request, Json::Value &response)
{
response = this->SignByHash( request["hash"].asString(), request["status"].asInt());
response = this->signByHash( request["hash"].asString(), request["status"].asInt());
}
virtual Json::Value GetUnsignedCSRs() = 0;
virtual Json::Value SignByHash(const std::string& hash, int status) = 0;
virtual Json::Value getUnsignedCSRs() = 0;
virtual Json::Value signByHash(const std::string& hash, int status) = 0;
};
......
......@@ -32,23 +32,23 @@ class AbstractRegServer : public jsonrpc::AbstractServer<AbstractRegServer>
public:
AbstractRegServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer<AbstractRegServer>(conn, type)
{
this->bindAndAddMethod(jsonrpc::Procedure("SignCertificate", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"certificate",jsonrpc::JSON_STRING, NULL), &AbstractRegServer::SignCertificateI);
this->bindAndAddMethod(jsonrpc::Procedure("GetCertificate", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"hash",jsonrpc::JSON_STRING, NULL), &AbstractRegServer::GetCertificateI);
this->bindAndAddMethod(jsonrpc::Procedure("signCertificate", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"certificate",jsonrpc::JSON_STRING, NULL), &AbstractRegServer::signCertificateI);
this->bindAndAddMethod(jsonrpc::Procedure("getCertificate", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"hash",jsonrpc::JSON_STRING, NULL), &AbstractRegServer::getCertificateI);
}
inline virtual void SignCertificateI(const Json::Value &request, Json::Value &response)
inline virtual void signCertificateI(const Json::Value &request, Json::Value &response)
{
std::cerr << "SignCertificateI in abstr server " << std::endl;
response = this->SignCertificate( request["certificate"].asString());
std::cerr << "signCertificateI in abstr server " << std::endl;
response = this->signCertificate( request["certificate"].asString());
}
inline virtual void GetCertificateI(const Json::Value &request, Json::Value &response)
inline virtual void getCertificateI(const Json::Value &request, Json::Value &response)
{
response = this->GetCertificate( request["hash"].asString());
response = this->getCertificate( request["hash"].asString());
}
virtual Json::Value SignCertificate(const std::string& cert) = 0;
virtual Json::Value GetCertificate(const std::string& hash) = 0;
virtual Json::Value signCertificate(const std::string& cert) = 0;
virtual Json::Value getCertificate(const std::string& hash) = 0;
};
......
......@@ -17,18 +17,19 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("importECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "key",jsonrpc::JSON_STRING,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("generateECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::generateECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("renameECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "KeyName",jsonrpc::JSON_STRING,"tempKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::renameECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("renameECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING,"tempKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::renameECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getPublicECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getPublicECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("ecdsaSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "base",jsonrpc::JSON_INTEGER,"keyName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::ecdsaSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("generateDKGPoly", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::generateDKGPolyI);
this->bindAndAddMethod(jsonrpc::Procedure("getVerificationVector", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"polyName",jsonrpc::JSON_STRING, "t",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getVerificationVectorI);
this->bindAndAddMethod(jsonrpc::Procedure("getSecretShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"publicKeys",jsonrpc::JSON_ARRAY, "n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getSecretShareI);
this->bindAndAddMethod(jsonrpc::Procedure("DKGVerification", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares",jsonrpc::JSON_STRING, "EthKeyName",jsonrpc::JSON_STRING, "SecretShare",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::DKGVerificationI);
this->bindAndAddMethod(jsonrpc::Procedure("CreateBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "BLSKeyName",jsonrpc::JSON_STRING, "EthKeyName",jsonrpc::JSON_STRING, "polyName", jsonrpc::JSON_STRING, "SecretShare",jsonrpc::JSON_STRING,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::CreateBLSPrivateKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("GetBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "BLSKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::GetBLSPublicKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("ComplaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::ComplaintResponseI);
this->bindAndAddMethod(jsonrpc::Procedure("MultG2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "x",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::MultG2I);
this->bindAndAddMethod(jsonrpc::Procedure("dkgVerification", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::dkgVerificationI);
this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "polyName", jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::createBLSPrivateKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getBLSPublicKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("complaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::complaintResponseI);
this->bindAndAddMethod(jsonrpc::Procedure("multG2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "x",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::multG2I);
this->bindAndAddMethod(jsonrpc::Procedure("isPolyExists", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::isPolyExistsI);
this->bindAndAddMethod(jsonrpc::Procedure("getServerStatus", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::getServerStatusI);
}
......@@ -41,6 +42,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["t"].asInt(), request["n"].asInt(), request["signerIndex"].asInt());
}
inline virtual void importECDSAKeyI(const Json::Value &request, Json::Value &response)
{
response = this->importECDSAKey(request["key"].asString(), request["keyName"].asString());
......@@ -52,7 +54,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
}
inline virtual void renameECDSAKeyI(const Json::Value &request, Json::Value &response)
{
response = this->renameECDSAKey(request["KeyName"].asString(), request["tempKeyName"].asString());
response = this->renameECDSAKey(request["keyName"].asString(), request["tempKeyName"].asString());
}
inline virtual void getPublicECDSAKeyI(const Json::Value &request, Json::Value &response)
{
......@@ -62,6 +64,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->ecdsaSignMessageHash(request["base"].asInt(), request["keyName"].asString(), request["messageHash"].asString());
}
inline virtual void generateDKGPolyI(const Json::Value &request, Json::Value &response)
{
response = this->generateDKGPoly(request["polyName"].asString(), request["t"].asInt());
......@@ -74,26 +77,32 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->getSecretShare(request["polyName"].asString(), request["publicKeys"], request["t"].asInt(),request["n"].asInt());
}
inline virtual void DKGVerificationI(const Json::Value &request, Json::Value &response)
inline virtual void dkgVerificationI(const Json::Value &request, Json::Value &response)
{
response = this->dkgVerification(request["publicShares"].asString(), request["ethKeyName"].asString(), request["secretShare"].asString(), request["t"].asInt(), request["n"].asInt(), request["index"].asInt());
}
inline virtual void createBLSPrivateKeyI(const Json::Value &request, Json::Value &response)
{
response = this->DKGVerification(request["publicShares"].asString(), request["EthKeyName"].asString(), request["SecretShare"].asString(), request["t"].asInt(), request["n"].asInt(), request["index"].asInt());
response = this->createBLSPrivateKey(request["blsKeyName"].asString(), request["ethKeyName"].asString(), request["polyName"].asString(),request["secretShare"].asString(),request["t"].asInt(), request["n"].asInt());
}
inline virtual void CreateBLSPrivateKeyI(const Json::Value &request, Json::Value &response)
inline virtual void getBLSPublicKeyShareI(const Json::Value &request, Json::Value &response)
{
response = this->CreateBLSPrivateKey(request["BLSKeyName"].asString(), request["EthKeyName"].asString(), request["polyName"].asString(),request["SecretShare"].asString(),request["t"].asInt(), request["n"].asInt());
response = this->getBLSPublicKeyShare(request["blsKeyName"].asString());
}
inline virtual void GetBLSPublicKeyShareI(const Json::Value &request, Json::Value &response)
inline virtual void complaintResponseI(const Json::Value &request, Json::Value &response)
{
response = this->GetBLSPublicKeyShare(request["BLSKeyName"].asString());
response = this->complaintResponse( request["polyName"].asString(), request["ind"].asInt());
}
inline virtual void ComplaintResponseI(const Json::Value &request, Json::Value &response)
inline virtual void multG2I(const Json::Value &request, Json::Value &response)
{
response = this->ComplaintResponse( request["polyName"].asString(), request["ind"].asInt());
response = this->multG2(request["x"].asString());
}
inline virtual void MultG2I(const Json::Value &request, Json::Value &response)
inline virtual void isPolyExistsI(const Json::Value &request, Json::Value &response)
{
response = this->MultG2(request["x"].asString());
response = this->isPolyExists(request["polyName"].asString());
}
inline virtual void getServerStatusI(const Json::Value &request, Json::Value &response)
{
(void)request;
......@@ -111,11 +120,12 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
virtual Json::Value generateDKGPoly(const std::string& polyName, int t) = 0;
virtual Json::Value getVerificationVector(const std::string& polyName, int t, int n) = 0;
virtual Json::Value getSecretShare(const std::string& polyName, const Json::Value& publicKeys, int t, int n) = 0;
virtual Json::Value DKGVerification( const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index) = 0;
virtual Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0;
virtual Json::Value GetBLSPublicKeyShare(const std::string & BLSKeyName) = 0;
virtual Json::Value ComplaintResponse(const std::string& polyName, int ind) = 0;
virtual Json::Value MultG2(const std::string & x) = 0;
virtual Json::Value dkgVerification( const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index) = 0;
virtual Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0;
virtual Json::Value getBLSPublicKeyShare(const std::string & blsKeyName) = 0;
virtual Json::Value complaintResponse(const std::string& polyName, int ind) = 0;
virtual Json::Value multG2(const std::string & x) = 0;
virtual Json::Value isPolyExists(const std::string& polyName) = 0;
virtual Json::Value getServerStatus() = 0;
};
......
# generated automatically by aclocal 1.16.1 -*- Autoconf -*-
# Copyright (C) 1996-2018 Free Software Foundation, Inc.
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])])
m4_ifndef([AC_AUTOCONF_VERSION],
[m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],,
[m4_warning([this file was generated for autoconf 2.69.
You have another version of autoconf. It may work, but is not guaranteed to.
If you have problems, you may need to regenerate the build system entirely.
To do so, use the procedure documented by the package, typically 'autoreconf'.])])
# Copyright (C) 2002-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_AUTOMAKE_VERSION(VERSION)
# ----------------------------
# Automake X.Y traces this macro to ensure aclocal.m4 has been
# generated from the m4 files accompanying Automake X.Y.
# (This private macro should not be called outside this file.)
AC_DEFUN([AM_AUTOMAKE_VERSION],
[am__api_version='1.16'
dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
dnl require some minimum version. Point them to the right macro.
m4_if([$1], [1.16.1], [],
[AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
])
# _AM_AUTOCONF_VERSION(VERSION)
# -----------------------------
# aclocal traces this macro to find the Autoconf version.
# This is a private macro too. Using m4_define simplifies
# the logic in aclocal, which can simply ignore this definition.
m4_define([_AM_AUTOCONF_VERSION], [])
# AM_SET_CURRENT_AUTOMAKE_VERSION
# -------------------------------
# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
# This function is AC_REQUIREd by AM_INIT_AUTOMAKE.
AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
[AM_AUTOMAKE_VERSION([1.16.1])dnl
m4_ifndef([AC_AUTOCONF_VERSION],
[m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))])
# AM_AUX_DIR_EXPAND -*- Autoconf -*-
# Copyright (C) 2001-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
# $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to
# '$srcdir', '$srcdir/..', or '$srcdir/../..'.
#
# Of course, Automake must honor this variable whenever it calls a
# tool from the auxiliary directory. The problem is that $srcdir (and
# therefore $ac_aux_dir as well) can be either absolute or relative,
# depending on how configure is run. This is pretty annoying, since
# it makes $ac_aux_dir quite unusable in subdirectories: in the top
# source directory, any form will work fine, but in subdirectories a
# relative path needs to be adjusted first.
#
# $ac_aux_dir/missing
# fails when called from a subdirectory if $ac_aux_dir is relative
# $top_srcdir/$ac_aux_dir/missing
# fails if $ac_aux_dir is absolute,
# fails when called from a subdirectory in a VPATH build with
# a relative $ac_aux_dir
#
# The reason of the latter failure is that $top_srcdir and $ac_aux_dir
# are both prefixed by $srcdir. In an in-source build this is usually
# harmless because $srcdir is '.', but things will broke when you
# start a VPATH build or use an absolute $srcdir.
#
# So we could use something similar to $top_srcdir/$ac_aux_dir/missing,
# iff we strip the leading $srcdir from $ac_aux_dir. That would be:
# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"`
# and then we would define $MISSING as
# MISSING="\${SHELL} $am_aux_dir/missing"
# This will work as long as MISSING is not called from configure, because
# unfortunately $(top_srcdir) has no meaning in configure.
# However there are other variables, like CC, which are often used in
# configure, and could therefore not use this "fixed" $ac_aux_dir.
#
# Another solution, used here, is to always expand $ac_aux_dir to an
# absolute PATH. The drawback is that using absolute paths prevent a
# configured tree to be moved without reconfiguration.
AC_DEFUN([AM_AUX_DIR_EXPAND],
[AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
# Expand $ac_aux_dir to an absolute path.
am_aux_dir=`cd "$ac_aux_dir" && pwd`
])
# AM_COND_IF -*- Autoconf -*-
# Copyright (C) 2008-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_COND_IF
# _AM_COND_ELSE
# _AM_COND_ENDIF
# --------------
# These macros are only used for tracing.
m4_define([_AM_COND_IF])
m4_define([_AM_COND_ELSE])
m4_define([_AM_COND_ENDIF])
# AM_COND_IF(COND, [IF-TRUE], [IF-FALSE])
# ---------------------------------------
# If the shell condition COND is true, execute IF-TRUE, otherwise execute
# IF-FALSE. Allow automake to learn about conditional instantiating macros
# (the AC_CONFIG_FOOS).
AC_DEFUN([AM_COND_IF],
[m4_ifndef([_AM_COND_VALUE_$1],
[m4_fatal([$0: no such condition "$1"])])dnl
_AM_COND_IF([$1])dnl
if test -z "$$1_TRUE"; then :
m4_n([$2])[]dnl
m4_ifval([$3],
[_AM_COND_ELSE([$1])dnl
else
$3
])dnl
_AM_COND_ENDIF([$1])dnl
fi[]dnl
])
# AM_CONDITIONAL -*- Autoconf -*-
# Copyright (C) 1997-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_CONDITIONAL(NAME, SHELL-CONDITION)
# -------------------------------------
# Define a conditional.
AC_DEFUN([AM_CONDITIONAL],
[AC_PREREQ([2.52])dnl
m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])],
[$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl
AC_SUBST([$1_TRUE])dnl
AC_SUBST([$1_FALSE])dnl
_AM_SUBST_NOTMAKE([$1_TRUE])dnl
_AM_SUBST_NOTMAKE([$1_FALSE])dnl
m4_define([_AM_COND_VALUE_$1], [$2])dnl
if $2; then
$1_TRUE=
$1_FALSE='#'
else
$1_TRUE='#'
$1_FALSE=
fi
AC_CONFIG_COMMANDS_PRE(
[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then
AC_MSG_ERROR([[conditional "$1" was never defined.
Usually this means the macro was only invoked conditionally.]])
fi])])
# Copyright (C) 1999-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be
# written in clear, in which case automake, when reading aclocal.m4,
# will think it sees a *use*, and therefore will trigger all it's
# C support machinery. Also note that it means that autoscan, seeing
# CC etc. in the Makefile, will ask for an AC_PROG_CC use...
# _AM_DEPENDENCIES(NAME)
# ----------------------
# See how the compiler implements dependency checking.
# NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC".
# We try a few techniques and use that to set a single cache variable.
#
# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was
# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular
# dependency, and given that the user is not expected to run this macro,
# just rely on AC_PROG_CC.
AC_DEFUN([_AM_DEPENDENCIES],
[AC_REQUIRE([AM_SET_DEPDIR])dnl
AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl
AC_REQUIRE([AM_MAKE_INCLUDE])dnl
AC_REQUIRE([AM_DEP_TRACK])dnl
m4_if([$1], [CC], [depcc="$CC" am_compiler_list=],
[$1], [CXX], [depcc="$CXX" am_compiler_list=],
[$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'],
[$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'],
[$1], [UPC], [depcc="$UPC" am_compiler_list=],
[$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'],
[depcc="$$1" am_compiler_list=])
AC_CACHE_CHECK([dependency style of $depcc],
[am_cv_$1_dependencies_compiler_type],
[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
# We make a subdir and do the tests there. Otherwise we can end up
# making bogus files that we don't know about and never remove. For
# instance it was reported that on HP-UX the gcc test will end up
# making a dummy file named 'D' -- because '-MD' means "put the output
# in D".
rm -rf conftest.dir
mkdir conftest.dir
# Copy depcomp to subdir because otherwise we won't find it if we're
# using a relative directory.
cp "$am_depcomp" conftest.dir
cd conftest.dir
# We will build objects and dependencies in a subdirectory because
# it helps to detect inapplicable dependency modes. For instance
# both Tru64's cc and ICC support -MD to output dependencies as a
# side effect of compilation, but ICC will put the dependencies in
# the current directory while Tru64 will put them in the object
# directory.
mkdir sub
am_cv_$1_dependencies_compiler_type=none
if test "$am_compiler_list" = ""; then
am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp`
fi
am__universal=false
m4_case([$1], [CC],
[case " $depcc " in #(
*\ -arch\ *\ -arch\ *) am__universal=true ;;
esac],
[CXX],
[case " $depcc " in #(
*\ -arch\ *\ -arch\ *) am__universal=true ;;
esac])
for depmode in $am_compiler_list; do
# Setup a source with many dependencies, because some compilers
# like to wrap large dependency lists on column 80 (with \), and
# we should not choose a depcomp mode which is confused by this.
#
# We need to recreate these files for each test, as the compiler may
# overwrite some of them when testing with obscure command lines.
# This happens at least with the AIX C compiler.
: > sub/conftest.c
for i in 1 2 3 4 5 6; do
echo '#include "conftst'$i'.h"' >> sub/conftest.c
# Using ": > sub/conftst$i.h" creates only sub/conftst1.h with
# Solaris 10 /bin/sh.
echo '/* dummy */' > sub/conftst$i.h
done
echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
# We check with '-c' and '-o' for the sake of the "dashmstdout"
# mode. It turns out that the SunPro C++ compiler does not properly
# handle '-M -o', and we need to detect this. Also, some Intel
# versions had trouble with output in subdirs.
am__obj=sub/conftest.${OBJEXT-o}
am__minus_obj="-o $am__obj"
case $depmode in
gcc)
# This depmode causes a compiler race in universal mode.
test "$am__universal" = false || continue
;;
nosideeffect)
# After this tag, mechanisms are not by side-effect, so they'll
# only be used when explicitly requested.
if test "x$enable_dependency_tracking" = xyes; then
continue
else
break
fi
;;
msvc7 | msvc7msys | msvisualcpp | msvcmsys)
# This compiler won't grok '-c -o', but also, the minuso test has
# not run yet. These depmodes are late enough in the game, and
# so weak that their functioning should not be impacted.
am__obj=conftest.${OBJEXT-o}
am__minus_obj=
;;
none) break ;;
esac
if depmode=$depmode \
source=sub/conftest.c object=$am__obj \
depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
$SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \
>/dev/null 2>conftest.err &&
grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
grep $am__obj sub/conftest.Po > /dev/null 2>&1 &&
${MAKE-make} -s -f confmf > /dev/null 2>&1; then
# icc doesn't choke on unknown options, it will just issue warnings
# or remarks (even with -Werror). So we grep stderr for any message
# that says an option was ignored or not supported.
# When given -MP, icc 7.0 and 7.1 complain thusly:
# icc: Command line warning: ignoring option '-M'; no argument required
# The diagnosis changed in icc 8.0:
# icc: Command line remark: option '-MP' not supported
if (grep 'ignoring option' conftest.err ||
grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
am_cv_$1_dependencies_compiler_type=$depmode
break
fi
fi
done
cd ..
rm -rf conftest.dir
else
am_cv_$1_dependencies_compiler_type=none
fi
])
AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type])
AM_CONDITIONAL([am__fastdep$1], [
test "x$enable_dependency_tracking" != xno \
&& test "$am_cv_$1_dependencies_compiler_type" = gcc3])
])
# AM_SET_DEPDIR
# -------------
# Choose a directory name for dependency files.
# This macro is AC_REQUIREd in _AM_DEPENDENCIES.
AC_DEFUN([AM_SET_DEPDIR],
[AC_REQUIRE([AM_SET_LEADING_DOT])dnl
AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl
])
# AM_DEP_TRACK
# ------------
AC_DEFUN([AM_DEP_TRACK],
[AC_ARG_ENABLE([dependency-tracking], [dnl
AS_HELP_STRING(
[--enable-dependency-tracking],
[do not reject slow dependency extractors])
AS_HELP_STRING(
[--disable-dependency-tracking],
[speeds up one-time build])])
if test "x$enable_dependency_tracking" != xno; then
am_depcomp="$ac_aux_dir/depcomp"
AMDEPBACKSLASH='\'
am__nodep='_no'
fi
AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno])
AC_SUBST([AMDEPBACKSLASH])dnl
_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl
AC_SUBST([am__nodep])dnl
_AM_SUBST_NOTMAKE([am__nodep])dnl
])
# Generate code to set up dependency tracking. -*- Autoconf -*-
# Copyright (C) 1999-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_OUTPUT_DEPENDENCY_COMMANDS
# ------------------------------
AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS],
[{
# Older Autoconf quotes --file arguments for eval, but not when files
# are listed without --file. Let's play safe and only enable the eval
# if we detect the quoting.
# TODO: see whether this extra hack can be removed once we start
# requiring Autoconf 2.70 or later.
AS_CASE([$CONFIG_FILES],
[*\'*], [eval set x "$CONFIG_FILES"],
[*], [set x $CONFIG_FILES])
shift
# Used to flag and report bootstrapping failures.
am_rc=0
for am_mf
do
# Strip MF so we end up with the name of the file.
am_mf=`AS_ECHO(["$am_mf"]) | sed -e 's/:.*$//'`
# Check whether this is an Automake generated Makefile which includes
# dependency-tracking related rules and includes.
# Grep'ing the whole file directly is not great: AIX grep has a line
# limit of 2048, but all sed's we know have understand at least 4000.
sed -n 's,^am--depfiles:.*,X,p' "$am_mf" | grep X >/dev/null 2>&1 \
|| continue
am_dirpart=`AS_DIRNAME(["$am_mf"])`
am_filepart=`AS_BASENAME(["$am_mf"])`
AM_RUN_LOG([cd "$am_dirpart" \
&& sed -e '/# am--include-marker/d' "$am_filepart" \
| $MAKE -f - am--depfiles]) || am_rc=$?
done
if test $am_rc -ne 0; then
AC_MSG_FAILURE([Something went wrong bootstrapping makefile fragments
for automatic dependency tracking. Try re-running configure with the
'--disable-dependency-tracking' option to at least be able to build
the package (albeit without support for automatic dependency tracking).])
fi
AS_UNSET([am_dirpart])
AS_UNSET([am_filepart])
AS_UNSET([am_mf])
AS_UNSET([am_rc])
rm -f conftest-deps.mk
}
])# _AM_OUTPUT_DEPENDENCY_COMMANDS
# AM_OUTPUT_DEPENDENCY_COMMANDS
# -----------------------------
# This macro should only be invoked once -- use via AC_REQUIRE.
#
# This code is only required when automatic dependency tracking is enabled.
# This creates each '.Po' and '.Plo' makefile fragment that we'll need in
# order to bootstrap the dependency handling code.
AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
[AC_CONFIG_COMMANDS([depfiles],
[test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS],
[AMDEP_TRUE="$AMDEP_TRUE" MAKE="${MAKE-make}"])])
# Do all the work for Automake. -*- Autoconf -*-
# Copyright (C) 1996-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This macro actually does too much. Some checks are only needed if
# your package does certain things. But this isn't really a big deal.
dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O.
m4_define([AC_PROG_CC],
m4_defn([AC_PROG_CC])
[_AM_PROG_CC_C_O
])
# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
# AM_INIT_AUTOMAKE([OPTIONS])
# -----------------------------------------------
# The call with PACKAGE and VERSION arguments is the old style
# call (pre autoconf-2.50), which is being phased out. PACKAGE
# and VERSION should now be passed to AC_INIT and removed from
# the call to AM_INIT_AUTOMAKE.
# We support both call styles for the transition. After
# the next Automake release, Autoconf can make the AC_INIT
# arguments mandatory, and then we can depend on a new Autoconf
# release and drop the old call support.
AC_DEFUN([AM_INIT_AUTOMAKE],
[AC_PREREQ([2.65])dnl
dnl Autoconf wants to disallow AM_ names. We explicitly allow
dnl the ones we care about.
m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl
AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl
AC_REQUIRE([AC_PROG_INSTALL])dnl
if test "`cd $srcdir && pwd`" != "`pwd`"; then
# Use -I$(srcdir) only when $(srcdir) != ., so that make's output
# is not polluted with repeated "-I."
AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl
# test to see if srcdir already configured
if test -f $srcdir/config.status; then
AC_MSG_ERROR([source directory already configured; run "make distclean" there first])
fi
fi
# test whether we have cygpath
if test -z "$CYGPATH_W"; then
if (cygpath --version) >/dev/null 2>/dev/null; then
CYGPATH_W='cygpath -w'
else
CYGPATH_W=echo
fi
fi
AC_SUBST([CYGPATH_W])
# Define the identity of the package.
dnl Distinguish between old-style and new-style calls.
m4_ifval([$2],
[AC_DIAGNOSE([obsolete],
[$0: two- and three-arguments forms are deprecated.])
m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl
AC_SUBST([PACKAGE], [$1])dnl
AC_SUBST([VERSION], [$2])],
[_AM_SET_OPTIONS([$1])dnl
dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT.
m4_if(
m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]),
[ok:ok],,
[m4_fatal([AC_INIT should be called with package and version arguments])])dnl
AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl
AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl
_AM_IF_OPTION([no-define],,
[AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package])
AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl
# Some tools Automake needs.
AC_REQUIRE([AM_SANITY_CHECK])dnl
AC_REQUIRE([AC_ARG_PROGRAM])dnl
AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}])
AM_MISSING_PROG([AUTOCONF], [autoconf])
AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}])
AM_MISSING_PROG([AUTOHEADER], [autoheader])
AM_MISSING_PROG([MAKEINFO], [makeinfo])
AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl
AC_REQUIRE([AC_PROG_MKDIR_P])dnl
# For better backward compatibility. To be removed once Automake 1.9.x
# dies out for good. For more background, see:
# <https://lists.gnu.org/archive/html/automake/2012-07/msg00001.html>
# <https://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
AC_SUBST([mkdir_p], ['$(MKDIR_P)'])
# We need awk for the "check" target (and possibly the TAP driver). The
# system "awk" is bad on some platforms.
AC_REQUIRE([AC_PROG_AWK])dnl
AC_REQUIRE([AC_PROG_MAKE_SET])dnl
AC_REQUIRE([AM_SET_LEADING_DOT])dnl
_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
[_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
[_AM_PROG_TAR([v7])])])
_AM_IF_OPTION([no-dependencies],,
[AC_PROVIDE_IFELSE([AC_PROG_CC],
[_AM_DEPENDENCIES([CC])],
[m4_define([AC_PROG_CC],
m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl
AC_PROVIDE_IFELSE([AC_PROG_CXX],
[_AM_DEPENDENCIES([CXX])],
[m4_define([AC_PROG_CXX],
m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl
AC_PROVIDE_IFELSE([AC_PROG_OBJC],
[_AM_DEPENDENCIES([OBJC])],
[m4_define([AC_PROG_OBJC],
m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl
AC_PROVIDE_IFELSE([AC_PROG_OBJCXX],
[_AM_DEPENDENCIES([OBJCXX])],
[m4_define([AC_PROG_OBJCXX],
m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl
])
AC_REQUIRE([AM_SILENT_RULES])dnl
dnl The testsuite driver may need to know about EXEEXT, so add the
dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This
dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below.
AC_CONFIG_COMMANDS_PRE(dnl
[m4_provide_if([_AM_COMPILER_EXEEXT],
[AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl
# POSIX will say in a future version that running "rm -f" with no argument
# is OK; and we want to be able to make that assumption in our Makefile
# recipes. So use an aggressive probe to check that the usage we want is
# actually supported "in the wild" to an acceptable degree.
# See automake bug#10828.
# To make any issue more visible, cause the running configure to be aborted
# by default if the 'rm' program in use doesn't match our expectations; the
# user can still override this though.
if rm -f && rm -fr && rm -rf; then : OK; else
cat >&2 <<'END'
Oops!
Your 'rm' program seems unable to run without file operands specified
on the command line, even when the '-f' option is present. This is contrary
to the behaviour of most rm programs out there, and not conforming with
the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542>
Please tell bug-automake@gnu.org about your system, including the value
of your $PATH and any error possibly output before this message. This
can help us improve future automake versions.
END
if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then
echo 'Configuration will proceed anyway, since you have set the' >&2
echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2
echo >&2
else
cat >&2 <<'END'
Aborting the configuration process, to ensure you take notice of the issue.
You can download and install GNU coreutils to get an 'rm' implementation
that behaves properly: <https://www.gnu.org/software/coreutils/>.
If you want to complete the configuration process using your problematic
'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM
to "yes", and re-run configure.
END
AC_MSG_ERROR([Your 'rm' program is bad, sorry.])
fi
fi
dnl The trailing newline in this macro's definition is deliberate, for
dnl backward compatibility and to allow trailing 'dnl'-style comments
dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841.
])
dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not
dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further
dnl mangled by Autoconf and run in a shell conditional statement.
m4_define([_AC_COMPILER_EXEEXT],
m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])])
# When config.status generates a header, we must update the stamp-h file.
# This file resides in the same directory as the config header
# that is generated. The stamp files are numbered to have different names.
# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the
# loop where config.status creates the headers, so we can generate
# our stamp files there.
AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK],
[# Compute $1's index in $config_headers.
_am_arg=$1
_am_stamp_count=1
for _am_header in $config_headers :; do
case $_am_header in
$_am_arg | $_am_arg:* )
break ;;
* )
_am_stamp_count=`expr $_am_stamp_count + 1` ;;
esac
done
echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count])
# Copyright (C) 2001-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_PROG_INSTALL_SH
# ------------------
# Define $install_sh.
AC_DEFUN([AM_PROG_INSTALL_SH],
[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
if test x"${install_sh+set}" != xset; then
case $am_aux_dir in
*\ * | *\ *)
install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
*)
install_sh="\${SHELL} $am_aux_dir/install-sh"
esac
fi
AC_SUBST([install_sh])])
# Copyright (C) 2003-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# Check whether the underlying file-system supports filenames
# with a leading dot. For instance MS-DOS doesn't.
AC_DEFUN([AM_SET_LEADING_DOT],
[rm -rf .tst 2>/dev/null
mkdir .tst 2>/dev/null
if test -d .tst; then
am__leading_dot=.
else
am__leading_dot=_
fi
rmdir .tst 2>/dev/null
AC_SUBST([am__leading_dot])])
# Check to see how 'make' treats includes. -*- Autoconf -*-
# Copyright (C) 2001-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_MAKE_INCLUDE()
# -----------------
# Check whether make has an 'include' directive that can support all
# the idioms we need for our automatic dependency tracking code.
AC_DEFUN([AM_MAKE_INCLUDE],
[AC_MSG_CHECKING([whether ${MAKE-make} supports the include directive])
cat > confinc.mk << 'END'
am__doit:
@echo this is the am__doit target >confinc.out
.PHONY: am__doit
END
am__include="#"
am__quote=
# BSD make does it like this.
echo '.include "confinc.mk" # ignored' > confmf.BSD
# Other make implementations (GNU, Solaris 10, AIX) do it like this.
echo 'include confinc.mk # ignored' > confmf.GNU
_am_result=no
for s in GNU BSD; do
AM_RUN_LOG([${MAKE-make} -f confmf.$s && cat confinc.out])
AS_CASE([$?:`cat confinc.out 2>/dev/null`],
['0:this is the am__doit target'],
[AS_CASE([$s],
[BSD], [am__include='.include' am__quote='"'],
[am__include='include' am__quote=''])])
if test "$am__include" != "#"; then
_am_result="yes ($s style)"
break
fi
done
rm -f confinc.* confmf.*
AC_MSG_RESULT([${_am_result}])
AC_SUBST([am__include])])
AC_SUBST([am__quote])])
# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*-
# Copyright (C) 1997-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_MISSING_PROG(NAME, PROGRAM)
# ------------------------------
AC_DEFUN([AM_MISSING_PROG],
[AC_REQUIRE([AM_MISSING_HAS_RUN])
$1=${$1-"${am_missing_run}$2"}
AC_SUBST($1)])
# AM_MISSING_HAS_RUN
# ------------------
# Define MISSING if not defined so far and test if it is modern enough.
# If it is, set am_missing_run to use it, otherwise, to nothing.
AC_DEFUN([AM_MISSING_HAS_RUN],
[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
AC_REQUIRE_AUX_FILE([missing])dnl
if test x"${MISSING+set}" != xset; then
case $am_aux_dir in
*\ * | *\ *)
MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;;
*)
MISSING="\${SHELL} $am_aux_dir/missing" ;;
esac
fi
# Use eval to expand $SHELL
if eval "$MISSING --is-lightweight"; then
am_missing_run="$MISSING "
else
am_missing_run=
AC_MSG_WARN(['missing' script is too old or missing])
fi
])
# Helper functions for option handling. -*- Autoconf -*-
# Copyright (C) 2001-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_MANGLE_OPTION(NAME)
# -----------------------
AC_DEFUN([_AM_MANGLE_OPTION],
[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])])
# _AM_SET_OPTION(NAME)
# --------------------
# Set option NAME. Presently that only means defining a flag for this option.
AC_DEFUN([_AM_SET_OPTION],
[m4_define(_AM_MANGLE_OPTION([$1]), [1])])
# _AM_SET_OPTIONS(OPTIONS)
# ------------------------
# OPTIONS is a space-separated list of Automake options.
AC_DEFUN([_AM_SET_OPTIONS],
[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET])
# -------------------------------------------
# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
AC_DEFUN([_AM_IF_OPTION],
[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
# Copyright (C) 1999-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_PROG_CC_C_O
# ---------------
# Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC
# to automatically call this.
AC_DEFUN([_AM_PROG_CC_C_O],
[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
AC_REQUIRE_AUX_FILE([compile])dnl
AC_LANG_PUSH([C])dnl
AC_CACHE_CHECK(
[whether $CC understands -c and -o together],
[am_cv_prog_cc_c_o],
[AC_LANG_CONFTEST([AC_LANG_PROGRAM([])])
# Make sure it works both with $CC and with simple cc.
# Following AC_PROG_CC_C_O, we do the test twice because some
# compilers refuse to overwrite an existing .o file with -o,
# though they will create one.
am_cv_prog_cc_c_o=yes
for am_i in 1 2; do
if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \
&& test -f conftest2.$ac_objext; then
: OK
else
am_cv_prog_cc_c_o=no
break
fi
done
rm -f core conftest*
unset am_i])
if test "$am_cv_prog_cc_c_o" != yes; then
# Losing compiler, so override with the script.
# FIXME: It is wrong to rewrite CC.
# But if we don't then we get into trouble of one sort or another.
# A longer-term fix would be to have automake use am__CC in this case,
# and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
CC="$am_aux_dir/compile $CC"
fi
AC_LANG_POP([C])])
# For backward compatibility.
AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])])
# Copyright (C) 2001-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_RUN_LOG(COMMAND)
# -------------------
# Run COMMAND, save the exit status in ac_status, and log it.
# (This has been adapted from Autoconf's _AC_RUN_LOG macro.)
AC_DEFUN([AM_RUN_LOG],
[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD
($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD
ac_status=$?
echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
(exit $ac_status); }])
# Check to make sure that the build environment is sane. -*- Autoconf -*-
# Copyright (C) 1996-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_SANITY_CHECK
# ---------------
AC_DEFUN([AM_SANITY_CHECK],
[AC_MSG_CHECKING([whether build environment is sane])
# Reject unsafe characters in $srcdir or the absolute working directory
# name. Accept space and tab only in the latter.
am_lf='
'
case `pwd` in
*[[\\\"\#\$\&\'\`$am_lf]]*)
AC_MSG_ERROR([unsafe absolute working directory name]);;
esac
case $srcdir in
*[[\\\"\#\$\&\'\`$am_lf\ \ ]]*)
AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);;
esac
# Do 'set' in a subshell so we don't clobber the current shell's
# arguments. Must try -L first in case configure is actually a
# symlink; some systems play weird games with the mod time of symlinks
# (eg FreeBSD returns the mod time of the symlink's containing
# directory).
if (
am_has_slept=no
for am_try in 1 2; do
echo "timestamp, slept: $am_has_slept" > conftest.file
set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null`
if test "$[*]" = "X"; then
# -L didn't work.
set X `ls -t "$srcdir/configure" conftest.file`
fi
if test "$[*]" != "X $srcdir/configure conftest.file" \
&& test "$[*]" != "X conftest.file $srcdir/configure"; then
# If neither matched, then we have a broken ls. This can happen
# if, for instance, CONFIG_SHELL is bash and it inherits a
# broken ls alias from the environment. This has actually
# happened. Such a system could not be considered "sane".
AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken
alias in your environment])
fi
if test "$[2]" = conftest.file || test $am_try -eq 2; then
break
fi
# Just in case.
sleep 1
am_has_slept=yes
done
test "$[2]" = conftest.file
)
then
# Ok.
:
else
AC_MSG_ERROR([newly created file is older than distributed files!
Check your system clock])
fi
AC_MSG_RESULT([yes])
# If we didn't sleep, we still need to ensure time stamps of config.status and
# generated files are strictly newer.
am_sleep_pid=
if grep 'slept: no' conftest.file >/dev/null 2>&1; then
( sleep 1 ) &
am_sleep_pid=$!
fi
AC_CONFIG_COMMANDS_PRE(
[AC_MSG_CHECKING([that generated files are newer than configure])
if test -n "$am_sleep_pid"; then
# Hide warnings about reused PIDs.
wait $am_sleep_pid 2>/dev/null
fi
AC_MSG_RESULT([done])])
rm -f conftest.file
])
# Copyright (C) 2009-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_SILENT_RULES([DEFAULT])
# --------------------------
# Enable less verbose build rules; with the default set to DEFAULT
# ("yes" being less verbose, "no" or empty being verbose).
AC_DEFUN([AM_SILENT_RULES],
[AC_ARG_ENABLE([silent-rules], [dnl
AS_HELP_STRING(
[--enable-silent-rules],
[less verbose build output (undo: "make V=1")])
AS_HELP_STRING(
[--disable-silent-rules],
[verbose build output (undo: "make V=0")])dnl
])
case $enable_silent_rules in @%:@ (((
yes) AM_DEFAULT_VERBOSITY=0;;
no) AM_DEFAULT_VERBOSITY=1;;
*) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);;
esac
dnl
dnl A few 'make' implementations (e.g., NonStop OS and NextStep)
dnl do not support nested variable expansions.
dnl See automake bug#9928 and bug#10237.
am_make=${MAKE-make}
AC_CACHE_CHECK([whether $am_make supports nested variables],
[am_cv_make_support_nested_variables],
[if AS_ECHO([['TRUE=$(BAR$(V))
BAR0=false
BAR1=true
V=1
am__doit:
@$(TRUE)
.PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then
am_cv_make_support_nested_variables=yes
else
am_cv_make_support_nested_variables=no
fi])
if test $am_cv_make_support_nested_variables = yes; then
dnl Using '$V' instead of '$(V)' breaks IRIX make.
AM_V='$(V)'
AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)'
else
AM_V=$AM_DEFAULT_VERBOSITY
AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY
fi
AC_SUBST([AM_V])dnl
AM_SUBST_NOTMAKE([AM_V])dnl
AC_SUBST([AM_DEFAULT_V])dnl
AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl
AC_SUBST([AM_DEFAULT_VERBOSITY])dnl
AM_BACKSLASH='\'
AC_SUBST([AM_BACKSLASH])dnl
_AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl
])
# Copyright (C) 2001-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_PROG_INSTALL_STRIP
# ---------------------
# One issue with vendor 'install' (even GNU) is that you can't
# specify the program used to strip binaries. This is especially
# annoying in cross-compiling environments, where the build's strip
# is unlikely to handle the host's binaries.
# Fortunately install-sh will honor a STRIPPROG variable, so we
# always use install-sh in "make install-strip", and initialize
# STRIPPROG with the value of the STRIP variable (set by the user).
AC_DEFUN([AM_PROG_INSTALL_STRIP],
[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
# Installed binaries are usually stripped using 'strip' when the user
# run "make install-strip". However 'strip' might not be the right
# tool to use in cross-compilation environments, therefore Automake
# will honor the 'STRIP' environment variable to overrule this program.
dnl Don't test for $cross_compiling = yes, because it might be 'maybe'.
if test "$cross_compiling" != no; then
AC_CHECK_TOOL([STRIP], [strip], :)
fi
INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
AC_SUBST([INSTALL_STRIP_PROGRAM])])
# Copyright (C) 2006-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_SUBST_NOTMAKE(VARIABLE)
# ---------------------------
# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in.
# This macro is traced by Automake.
AC_DEFUN([_AM_SUBST_NOTMAKE])
# AM_SUBST_NOTMAKE(VARIABLE)
# --------------------------
# Public sister of _AM_SUBST_NOTMAKE.
AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)])
# Check how to create a tarball. -*- Autoconf -*-
# Copyright (C) 2004-2018 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_PROG_TAR(FORMAT)
# --------------------
# Check how to create a tarball in format FORMAT.
# FORMAT should be one of 'v7', 'ustar', or 'pax'.
#
# Substitute a variable $(am__tar) that is a command
# writing to stdout a FORMAT-tarball containing the directory
# $tardir.
# tardir=directory && $(am__tar) > result.tar
#
# Substitute a variable $(am__untar) that extract such
# a tarball read from stdin.
# $(am__untar) < result.tar
#
AC_DEFUN([_AM_PROG_TAR],
[# Always define AMTAR for backward compatibility. Yes, it's still used
# in the wild :-( We should find a proper way to deprecate it ...
AC_SUBST([AMTAR], ['$${TAR-tar}'])
# We'll loop over all known methods to create a tar archive until one works.
_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none'
m4_if([$1], [v7],
[am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'],
[m4_case([$1],
[ustar],
[# The POSIX 1988 'ustar' format is defined with fixed-size fields.
# There is notably a 21 bits limit for the UID and the GID. In fact,
# the 'pax' utility can hang on bigger UID/GID (see automake bug#8343
# and bug#13588).
am_max_uid=2097151 # 2^21 - 1
am_max_gid=$am_max_uid
# The $UID and $GID variables are not portable, so we need to resort
# to the POSIX-mandated id(1) utility. Errors in the 'id' calls
# below are definitely unexpected, so allow the users to see them
# (that is, avoid stderr redirection).
am_uid=`id -u || echo unknown`
am_gid=`id -g || echo unknown`
AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format])
if test $am_uid -le $am_max_uid; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
_am_tools=none
fi
AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format])
if test $am_gid -le $am_max_gid; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
_am_tools=none
fi],
[pax],
[],
[m4_fatal([Unknown tar format])])
AC_MSG_CHECKING([how to create a $1 tar archive])
# Go ahead even if we have the value already cached. We do so because we
# need to set the values for the 'am__tar' and 'am__untar' variables.
_am_tools=${am_cv_prog_tar_$1-$_am_tools}
for _am_tool in $_am_tools; do
case $_am_tool in
gnutar)
for _am_tar in tar gnutar gtar; do
AM_RUN_LOG([$_am_tar --version]) && break
done
am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"'
am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"'
am__untar="$_am_tar -xf -"
;;
plaintar)
# Must skip GNU tar: if it does not support --format= it doesn't create
# ustar tarball either.
(tar --version) >/dev/null 2>&1 && continue
am__tar='tar chf - "$$tardir"'
am__tar_='tar chf - "$tardir"'
am__untar='tar xf -'
;;
pax)
am__tar='pax -L -x $1 -w "$$tardir"'
am__tar_='pax -L -x $1 -w "$tardir"'
am__untar='pax -r'
;;
cpio)
am__tar='find "$$tardir" -print | cpio -o -H $1 -L'
am__tar_='find "$tardir" -print | cpio -o -H $1 -L'
am__untar='cpio -i -H $1 -d'
;;
none)
am__tar=false
am__tar_=false
am__untar=false
;;
esac
# If the value was cached, stop now. We just wanted to have am__tar
# and am__untar set.
test -n "${am_cv_prog_tar_$1}" && break
# tar/untar a dummy directory, and stop if the command works.
rm -rf conftest.dir
mkdir conftest.dir
echo GrepMe > conftest.dir/file
AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar])
rm -rf conftest.dir
if test -s conftest.tar; then
AM_RUN_LOG([$am__untar <conftest.tar])
AM_RUN_LOG([cat conftest.dir/file])
grep GrepMe conftest.dir/file >/dev/null 2>&1 && break
fi
done
rm -rf conftest.dir
AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool])
AC_MSG_RESULT([$am_cv_prog_tar_$1])])
AC_SUBST([am__tar])
AC_SUBST([am__untar])
]) # _AM_PROG_TAR
m4_include([m4/sgx_init.m4])
......@@ -13,7 +13,7 @@ int print_hashes(){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.GetUnsignedCSRs() << std::endl;
std::cout << c.getUnsignedCSRs() << std::endl;
exit(0);
}
......@@ -21,7 +21,7 @@ void sign_by_hash(std::string & hash, int status){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.SignByHash(hash, status) << std::endl;
std::cout << c.signByHash(hash, status) << std::endl;
exit(0);
}
......
//
// Created by kladko on 25.01.20.
//
#ifndef SGXWALLET_COMMON_H
#define SGXWALLET_COMMON_H
using namespace std;
#include <stdlib.h>
#include <iostream>
#include <map>
#include <memory>
#define CHECK_ARGUMENT(_EXPRESSION_) \
if (!(_EXPRESSION_)) { \
auto __msg__ = string("Argument Check failed:") + #_EXPRESSION_ + "\n" + __CLASS_NAME__ + ":" + __FUNCTION__ + \
+ " " + string(__FILE__) + ":" + to_string(__LINE__); \
throw runtime_error(__msg__);}
#define CHECK_STATE(_EXPRESSION_) \
if (!(_EXPRESSION_)) { \
auto __msg__ = string("State check failed::") + #_EXPRESSION_ + " " + string(__FILE__) + ":" + to_string(__LINE__); \
throw runtime_error(__msg__);}
#endif //SGXWALLET_COMMON_H
/usr/share/automake-1.16/compile
\ No newline at end of file
/usr/share/automake-1.16/depcomp
\ No newline at end of file
......@@ -8,5 +8,5 @@ jhid -d
pid=$!
sleep 2
/usr/src/sdk/sgxwallet $1
cd /usr/src/sdk; ./sgxwallet $1 $2 $3 $4
Subproject commit 83fadb60a7f1607c1c46e868ed2a866bb70b4c76
/usr/share/automake-1.16/install-sh
\ No newline at end of file
/usr/share/automake-1.16/missing
\ No newline at end of file
......@@ -10,7 +10,12 @@ services:
- "/dev/isgx"
- "/dev/mei0"
volumes:
- ./sgx_data:/sgx_data
- ./sgx_data:/usr/src/sdk/sgx_data
logging:
driver: json-file
options:
max-size: "10m"
max-file: "4"
restart: unless-stopped
command: -s
......
......@@ -7,7 +7,12 @@ services:
- "1027:1027"
- "1028:1028"
volumes:
- ./sgx_data:/sgx_data
- ./sgx_data:/usr/src/sdk/sgx_data
logging:
driver: json-file
options:
max-size: "10m"
max-file: "4"
restart: unless-stopped
command: -s
command: -s -d
#!/usr/bin/env python
#
# @file docker_test.py
# @author Stan Kladko
# @date 2020
#
import sys
import os
import subprocess
import socket
assert os.path.isdir('sgx_data/sgxwallet.db')
assert os.path.isdir('sgx_data/cert_data');
assert os.path.isdir('sgx_data/CSR_DB');
assert os.path.isdir('sgx_data/CSR_STATUS_DB');
assert os.path.isfile('sgx_data/cert_data/SGXServerCert.crt')
assert os.path.isfile('sgx_data/cert_data/SGXServerCert.key')
assert os.path.isfile('sgx_data/cert_data/rootCA.pem')
assert os.path.isfile('sgx_data/cert_data/rootCA.key')
s1 = socket.socket()
s2 = socket.socket()
s3 = socket.socket()
address = '127.0.0.1'
s1.connect((address, 1026))
s2.connect((address, 1027))
s3.connect((address, 1028))
s1.close()
s2.close()
s3.close()
//
// Created by kladko on 1/22/20.
//
#include "sgx_trts.h"
#include "sgx_tcrypto.h"
#include "stdlib.h"
#include <string.h>
#include "AESUtils.h"
int AES_encrypt(char *message, uint8_t *encr_message){
sgx_read_rand(encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE);
sgx_status_t status = sgx_rijndael128GCM_encrypt(&AES_key, (uint8_t*)message, strlen(message),
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0,
(sgx_aes_gcm_128bit_tag_t *) encr_message);
return status;
}
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message){
uint64_t len = length - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE;
sgx_status_t status = sgx_rijndael128GCM_decrypt(&AES_key,
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len,
message,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0,
(sgx_aes_gcm_128bit_tag_t *)encr_message);
return status;
}
\ No newline at end of file
//
// Created by kladko on 1/22/20.
//
#ifndef SGXD_AESUTILS_H
#define SGXD_AESUTILS_H
sgx_aes_gcm_128bit_key_t AES_key;
int AES_encrypt(char *message, uint8_t *encr_message);
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message);
#endif //SGXD_AESUTILS_H
......@@ -85,7 +85,7 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c DH_dkg.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c DH_dkg.c AESUtils.c \
DKGUtils.cpp BLSEnclave.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......
......@@ -110,7 +110,7 @@ am_secure_enclave_OBJECTS = secure_enclave_t.$(OBJEXT) \
secure_enclave.$(OBJEXT) curves.$(OBJEXT) \
domain_parameters.$(OBJEXT) numbertheory.$(OBJEXT) \
point.$(OBJEXT) signature.$(OBJEXT) DH_dkg.$(OBJEXT) \
DKGUtils.$(OBJEXT) BLSEnclave.$(OBJEXT) \
AESUtils.$(OBJEXT) DKGUtils.$(OBJEXT) BLSEnclave.$(OBJEXT) \
alt_bn128_init.$(OBJEXT) alt_bn128_g2.$(OBJEXT) \
alt_bn128_g1.$(OBJEXT) $(am__objects_1) $(am__objects_1)
secure_enclave_OBJECTS = $(am_secure_enclave_OBJECTS)
......@@ -138,7 +138,8 @@ am__v_at_1 =
DEFAULT_INCLUDES = -I.@am__isrc@
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__maybe_remake_depfiles = depfiles
am__depfiles_remade = ./$(DEPDIR)/BLSEnclave.Po ./$(DEPDIR)/DH_dkg.Po \
am__depfiles_remade = ./$(DEPDIR)/AESUtils.Po \
./$(DEPDIR)/BLSEnclave.Po ./$(DEPDIR)/DH_dkg.Po \
./$(DEPDIR)/DKGUtils.Po ./$(DEPDIR)/alt_bn128_g1.Po \
./$(DEPDIR)/alt_bn128_g2.Po ./$(DEPDIR)/alt_bn128_init.Po \
./$(DEPDIR)/curves.Po ./$(DEPDIR)/domain_parameters.Po \
......@@ -346,7 +347,7 @@ ENCLAVE_CONFIG = $(ENCLAVE).config.xml
ENCLAVE_KEY = test_insecure_private_key.pem #$(ENCLAVE)_private.pem
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c DH_dkg.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c DH_dkg.c AESUtils.c \
DKGUtils.cpp BLSEnclave.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......@@ -440,6 +441,7 @@ mostlyclean-compile:
distclean-compile:
-rm -f *.tab.c
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/AESUtils.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BLSEnclave.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DH_dkg.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DKGUtils.Po@am__quote@ # am--include-marker
......@@ -660,7 +662,8 @@ clean: clean-am
clean-am: clean-generic clean-libexecPROGRAMS mostlyclean-am
distclean: distclean-am
-rm -f ./$(DEPDIR)/BLSEnclave.Po
-rm -f ./$(DEPDIR)/AESUtils.Po
-rm -f ./$(DEPDIR)/BLSEnclave.Po
-rm -f ./$(DEPDIR)/DH_dkg.Po
-rm -f ./$(DEPDIR)/DKGUtils.Po
-rm -f ./$(DEPDIR)/alt_bn128_g1.Po
......@@ -720,7 +723,8 @@ install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f ./$(DEPDIR)/BLSEnclave.Po
-rm -f ./$(DEPDIR)/AESUtils.Po
-rm -f ./$(DEPDIR)/BLSEnclave.Po
-rm -f ./$(DEPDIR)/DH_dkg.Po
-rm -f ./$(DEPDIR)/DKGUtils.Po
-rm -f ./$(DEPDIR)/alt_bn128_g1.Po
......
//
// Created by kladko on 1/24/20.
//
#ifndef SGXD_ENCLAVE_COMMON_H
#define SGXD_ENCLAVE_COMMON_H
#define BUF_LEN 1024
#define MAX_KEY_LENGTH 128
#define MAX_COMPONENT_LENGTH 80
#define MAX_COMPONENT_HEX_LENGTH MAX_COMPONENT_LENGTH * 2
#define MAX_ENCRYPTED_KEY_LENGTH 1024
#define MAX_SIG_LEN 1024
#define MAX_ERR_LEN 1024
#define SHA_256_LEN 32
#define ADD_ENTROPY_SIZE 32
#define DKG_BUFER_LENGTH 2490//3060
#define DKG_MAX_SEALED_LEN 3050
#define SECRET_SHARE_NUM_BYTES 96
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
#define ECDSA_ENCR_LEN 93
#define ECDSA_BIN_LEN 33
#define UNKNOWN_ERROR -1
#define PLAINTEXT_KEY_TOO_LONG -2
#define UNPADDED_KEY -3
#define NULL_KEY -4
#define INCORRECT_STRING_CONVERSION -5
#define ENCRYPTED_KEY_TOO_LONG -6
#define SEAL_KEY_FAILED -7
#endif //SGXD_ENCLAVE_COMMON_H
......@@ -51,10 +51,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sgx_tcrypto.h>
#include "../sgxwallet_common.h"
#include "AESUtils.h"
//#include "../sgxwallet_common.h"
#include "enclave_common.h"
uint8_t Decrypted_dkg_poly[DKG_BUFER_LENGTH];
uint8_t SEK[32];
void *(*gmp_realloc_func)(void *, size_t, size_t);
......@@ -595,6 +598,7 @@ void set_encrypted_dkg_poly(int *err_status, char *err_string, uint8_t* encrypte
(const sgx_sealed_data_t *)encrypted_poly, NULL, 0, Decrypted_dkg_poly, &decr_len);
if (status != SGX_SUCCESS) {
*err_status = -1;
snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_poly failed with status %d", status);
return;
}
......@@ -896,23 +900,431 @@ void get_bls_pub_key(int *err_status, char* err_string, uint8_t* encrypted_key,
void generate_SEK(int *err_status, char *err_string,
uint8_t *encrypted_SEK, uint32_t *enc_len){
uint8_t SEK_raw[SGX_AESGCM_KEY_SIZE];
//unsigned char* rand_char = (unsigned char*)malloc(16);
sgx_read_rand( SEK_raw, SGX_AESGCM_KEY_SIZE);
uint32_t hex_aes_key_length = SGX_AESGCM_KEY_SIZE * 2;
uint8_t SEK[hex_aes_key_length];
carray2Hex(SEK_raw, SGX_AESGCM_KEY_SIZE, SEK);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, hex_aes_key_length + 1);
memcpy(err_string, SEK, BUF_LEN);
for ( uint8_t i = 0; i < SGX_AESGCM_KEY_SIZE; i++){
AES_key[i] = SEK_raw[i];
}
unsigned char* rand_char = (unsigned char*)malloc(16);
sgx_read_rand( rand_char, 16);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, 32);
sgx_status_t status = sgx_seal_data(0, NULL, 32, (uint8_t *)rand_char, sealedLen,(sgx_sealed_data_t*)encrypted_SEK);
sgx_status_t status = sgx_seal_data(0, NULL, hex_aes_key_length + 1, SEK, sealedLen,(sgx_sealed_data_t*)encrypted_SEK);
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"seal SEK failed");
snprintf(err_string, BUF_LEN, "seal SEK failed");
*err_status = status;
return;
}
*enc_len = sealedLen;
//free(rand_char);
}
void generate_ecdsa_key_aes(int *err_status, char *err_string,
uint8_t *encrypted_key, uint32_t *enc_len, char * pub_key_x, char * pub_key_y) {
domain_parameters curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
unsigned char* rand_char = (unsigned char*)malloc(32);
sgx_read_rand( rand_char, 32);
mpz_t seed;
mpz_init(seed);
mpz_import(seed, 32, 1, sizeof(rand_char[0]), 0, 0, rand_char);
free(rand_char);
mpz_t skey;
mpz_init(skey);
mpz_mod(skey, seed, curve->p);
mpz_clear(seed);
//Public key
point Pkey = point_init();
signature_generate_key(Pkey, skey, curve);
uint8_t base = 16;
int len = mpz_sizeinbase (Pkey->x, base) + 2;
//snprintf(err_string, BUF_LEN, "len = %d\n", len);
char arr_x[len];
char* px = mpz_get_str(arr_x, base, Pkey->x);
//snprintf(err_string, BUF_LEN, "arr=%p px=%p\n", arr_x, px);
int n_zeroes = 64 - strlen(arr_x);
for ( int i = 0; i < n_zeroes; i++){
pub_key_x[i] = '0';
}
strncpy(pub_key_x + n_zeroes, arr_x, 1024 - n_zeroes);
char arr_y[mpz_sizeinbase (Pkey->y, base) + 2];
char* py = mpz_get_str(arr_y, base, Pkey->y);
n_zeroes = 64 - strlen(arr_y);
for ( int i = 0; i < n_zeroes; i++){
pub_key_y[i] = '0';
}
strncpy(pub_key_y + n_zeroes, arr_y, 1024 - n_zeroes);
char skey_str[mpz_sizeinbase (skey, ECDSA_SKEY_BASE) + 2];
char* s = mpz_get_str(skey_str, ECDSA_SKEY_BASE, skey);
snprintf(err_string, BUF_LEN, "skey is %s len %d\n", skey_str, strlen(skey_str));
int stat = AES_encrypt(skey_str, encrypted_key);
if( stat != 0) {
snprintf(err_string, BUF_LEN,"ecdsa private key encryption failed");
*err_status = stat;
return;
}
*enc_len = strlen(skey_str) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
stat = AES_decrypt(encrypted_key, *enc_len, skey_str);
if( stat != 0) {
snprintf(err_string + 19 + strlen(skey_str), BUF_LEN,"ecdsa private key decr failed with status %d", stat);
//*err_status = stat;
return;
}
mpz_clear(skey);
domain_parameters_clear(curve);
point_clear(Pkey);
}
void get_public_ecdsa_key_aes(int *err_status, char *err_string,
uint8_t *encrypted_key, uint32_t enc_len, char * pub_key_x, char * pub_key_y) {
domain_parameters curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
char skey[ECDSA_SKEY_LEN];
int status = AES_decrypt(encrypted_key, enc_len, skey);
if (status != 0) {
snprintf(err_string, BUF_LEN,"AES_decrypt failed with status %d", status);
*err_status = status;
return;
}
skey[enc_len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE] = '\0';
strncpy(err_string, skey, 1024);
mpz_t skey_mpz;
mpz_init(skey_mpz);
// mpz_import(skey_mpz, 32, 1, sizeof(skey[0]), 0, 0, skey);
if (mpz_set_str(skey_mpz, skey, ECDSA_SKEY_BASE) == -1){
snprintf(err_string, BUF_LEN,"wrong string to init private key - %s", skey);
*err_status = -10;
mpz_clear(skey_mpz);
return;
}
//Public key
point Pkey = point_init();
signature_generate_key(Pkey, skey_mpz, curve);
point Pkey_test = point_init();
point_multiplication(Pkey_test, skey_mpz, curve->G, curve);
if (!point_cmp(Pkey, Pkey_test)){
snprintf(err_string, BUF_LEN,"Points are not equal");
*err_status = -11;
return;
}
int base = 16;
int len = mpz_sizeinbase (Pkey->x, base) + 2;
//snprintf(err_string, BUF_LEN, "len = %d\n", len);
char arr_x[len];
char* px = mpz_get_str(arr_x, base, Pkey->x);
//snprintf(err_string, BUF_LEN, "arr=%p px=%p\n", arr_x, px);
int n_zeroes = 64 - strlen(arr_x);
for ( int i = 0; i < n_zeroes; i++){
pub_key_x[i] = '0';
}
strncpy(pub_key_x + n_zeroes, arr_x, 1024 - n_zeroes);
char arr_y[mpz_sizeinbase (Pkey->y, base) + 2];
char* py = mpz_get_str(arr_y, base, Pkey->y);
n_zeroes = 64 - strlen(arr_y);
for ( int i = 0; i < n_zeroes; i++){
pub_key_y[i] = '0';
}
strncpy(pub_key_y + n_zeroes, arr_y, 1024 - n_zeroes);
mpz_clear(skey_mpz);
domain_parameters_clear(curve);
point_clear(Pkey);
}
void ecdsa_sign_aes(int *err_status, char *err_string, uint8_t *encrypted_key, uint32_t enc_len,
unsigned char* hash, char * sig_r, char * sig_s, uint8_t* sig_v, int base) {
domain_parameters curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
char skey[ECDSA_SKEY_LEN];
int status = AES_decrypt(encrypted_key, enc_len, skey);
if (status != 0) {
*err_status = status;
snprintf(err_string, BUF_LEN,"aes decrypt failed with status %d", status);
return;
}
skey[enc_len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE - 1] = '\0';
snprintf(err_string, BUF_LEN,"pr key is %s length %d ", skey, strlen(skey));
mpz_t skey_mpz;
mpz_init(skey_mpz);
if (mpz_set_str(skey_mpz, skey, ECDSA_SKEY_BASE) == -1){
*err_status = -1;
snprintf(err_string, BUF_LEN ,"invalid secret key");
mpz_clear(skey_mpz);
return;
}
mpz_t msg_mpz;
mpz_init(msg_mpz);
if (mpz_set_str(msg_mpz, hash, 16) == -1){
*err_status = -1;
snprintf(err_string, BUF_LEN ,"invalid message hash");
mpz_clear(msg_mpz);
return;
}
signature sign = signature_init();
signature_sign( sign, msg_mpz, skey_mpz, curve);
point Pkey = point_init();
signature_generate_key(Pkey, skey_mpz, curve);
if ( !signature_verify(msg_mpz, sign, Pkey, curve) ){
*err_status = -2;
snprintf(err_string, BUF_LEN,"signature is not verified! ");
return;
}
//char arr_x[mpz_sizeinbase (Pkey->x, 16) + 2];
//char* px = mpz_get_str(arr_x, 16, Pkey->x);
//snprintf(err_string, BUF_LEN,"pub key x %s ", arr_x);
char arr_m[mpz_sizeinbase (msg_mpz, 16) + 2];
char* msg = mpz_get_str(arr_m, 16, msg_mpz);
snprintf(err_string, BUF_LEN,"message is %s ", arr_m);
char arr_r[mpz_sizeinbase (sign->r, base) + 2];
char* r = mpz_get_str(arr_r, base, sign->r);
strncpy(sig_r, arr_r, 1024);
char arr_s[mpz_sizeinbase (sign->s, base) + 2];
char* s = mpz_get_str(arr_s, base, sign->s);
strncpy(sig_s, arr_s, 1024);
*sig_v = sign->v;
mpz_clear(skey_mpz);
mpz_clear(msg_mpz);
domain_parameters_clear(curve);
signature_clear(sign);
point_clear(Pkey);
}
void encrypt_key_aes(int *err_status, char *err_string, char *key,
uint8_t *encrypted_key, uint32_t *enc_len) {
//init();
*err_status = UNKNOWN_ERROR;
memset(err_string, 0, BUF_LEN);
checkKey(err_status, err_string, key);
if (*err_status != 0) {
snprintf(err_string + strlen(err_string), BUF_LEN, "check_key failed");
return;
}
memset(encrypted_key, 0, BUF_LEN);
int stat = AES_encrypt(key, encrypted_key);
if ( stat != 0) {
*err_status = stat;
snprintf(err_string, BUF_LEN, "AES encrypt failed with status %d", stat);
return;
}
*enc_len = strlen(key) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
char decryptedKey[BUF_LEN];
memset(decryptedKey, 0, BUF_LEN);
stat = AES_decrypt(encrypted_key, *enc_len, decryptedKey);
if (stat != 0) {
*err_status = stat;
snprintf(err_string, BUF_LEN, ":decrypt_key failed with status %d", stat);
return;
}
uint64_t decryptedKeyLen = strnlen(decryptedKey, MAX_KEY_LENGTH);
if (decryptedKeyLen == MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "Decrypted key is not null terminated");
return;
}
*err_status = -8;
if (strncmp(key, decryptedKey, MAX_KEY_LENGTH) != 0) {
snprintf(err_string, BUF_LEN, "Decrypted key does not match original key");
return;
}
*err_status = 0;
}
void decrypt_key_aes(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, char *key) {
init();
uint32_t decLen;
*err_status = -9;
int status = AES_decrypt(encrypted_key, enc_len, key);
if (status != 0) {
*err_status = status;
snprintf(err_string, BUF_LEN, "aes decrypt failed with status %d", status);
return;
}
//snprintf(err_string, BUF_LEN, "decr key is %s", key);
if (decLen > MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "wrong decLen");//"decLen != MAX_KEY_LENGTH");
return;
}
*err_status = -10;
uint64_t keyLen = strnlen(key, MAX_KEY_LENGTH);
if (keyLen == MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "Key is not null terminated");
return;
}
*err_status = 0;
return;
}
void bls_sign_message_test(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, char *_hashX,
char *_hashY, char *signature) {
char key[BUF_LEN];
char* sig = (char*) calloc(BUF_LEN, 1);
init();
int stat = AES_decrypt(encrypted_key, enc_len, key);
if ( stat != 0) {
*err_status = stat;
strncpy(signature, err_string, BUF_LEN);
return;
}
enclave_sign(key, _hashX, _hashY, sig);
strncpy(signature, sig, BUF_LEN);
if (strnlen(signature, BUF_LEN) < 10) {
*err_status = -1;
return;
}
}
void gen_dkg_secret_aes (int *err_status, char *err_string, uint8_t *encrypted_dkg_secret, uint32_t* enc_len, size_t _t){
char* dkg_secret = (char*)calloc(DKG_BUFER_LENGTH, 1);
if (gen_dkg_poly(dkg_secret, _t) != 0 ){
*err_status = - 1;
return;
}
snprintf(err_string, BUF_LEN,"poly is %s ", dkg_secret);
int status = AES_encrypt(dkg_secret, encrypted_dkg_secret);
if(status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"SGX AES encrypt DKG poly failed");
*err_status = status;
return;
}
*enc_len = strlen(dkg_secret) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
free(dkg_secret);
}
void decrypt_dkg_secret_aes (int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint8_t* decrypted_dkg_secret, uint32_t* dec_len){
int status = AES_decrypt(encrypted_dkg_secret, dec_len, decrypted_dkg_secret);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"aes decrypt data - encrypted_dkg_secret failed with status %d", status);
*err_status = status;
return;
}
//*dec_len = decr_len;
}
void set_encrypted_dkg_poly_aes(int *err_status, char *err_string, uint8_t* encrypted_poly, uint64_t* enc_len){
uint32_t decr_len;
int status = AES_decrypt(encrypted_poly, enc_len, Decrypted_dkg_poly);
if (status != SGX_SUCCESS) {
*err_status = -1;
snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_poly failed with status %d", status);
return;
}
}
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
#define ECDSA_ENCR_LEN 93
#define ECDSA_BIN_LEN 33
enclave {
trusted {
include "sgx_tgmp.h"
public void tgmp_init();
public void e_mpz_add(
......@@ -52,20 +59,20 @@ enclave {
[out, count = 1024] char* key );
public void bls_sign_message (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] uint8_t* encrypted_key,
uint32_t enc_len,
[in, count = 1024] char* hashX ,
[in, count = 1024] char* hashY ,
[out, count = 1024] char* signature);
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] uint8_t* encrypted_key,
uint32_t enc_len,
[in, count = 1024] char* hashX ,
[in, count = 1024] char* hashY ,
[out, count = 1024] char* signature);
public void gen_dkg_secret (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[out, count = 3050] uint8_t* encrypted_dkg_secret,
[user_check] uint32_t * enc_len,
size_t _t);
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[out, count = 3050] uint8_t* encrypted_dkg_secret,
[user_check] uint32_t * enc_len,
size_t _t);
public void decrypt_dkg_secret (
[user_check] int *err_status,
......@@ -163,6 +170,72 @@ enclave {
[out, count = 1024] char *err_string,
[in, count = 1024] uint8_t *encrypted_SEK,
[user_check] uint32_t *enc_len);
public void generate_ecdsa_key_aes (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[out, count = ECDSA_ENCR_LEN] uint8_t* encrypted_key,
[user_check] uint32_t *enc_len,
[out, count = 1024] char * pub_key_x,
[out, count = 1024] char * pub_key_y);
public void get_public_ecdsa_key_aes(
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] uint8_t* encrypted_key,
uint32_t dec_len,
[out, count = 1024] char * pub_key_x,
[out, count = 1024] char * pub_key_y);
public void ecdsa_sign_aes(
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] uint8_t* encrypted_key,
uint32_t enc_len,
[in, count = 1024] unsigned char* hash,
[out, count = 1024] char* sig_r,
[out, count = 1024] char* sig_s,
[user_check] uint8_t* sig_v,
int base);
public void encrypt_key_aes (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] char* key,
[out, count = 1024] uint8_t* encrypted_key,
[user_check] uint32_t *enc_len);
public void decrypt_key_aes (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] uint8_t* encrypted_key,
uint32_t enc_len,
[out, count = 1024] char* key );
public void gen_dkg_secret_aes (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[out, count = 3050] uint8_t* encrypted_dkg_secret,
[user_check] uint32_t * enc_len,
size_t _t);
public void decrypt_dkg_secret_aes (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 3050] uint8_t* encrypted_dkg_secret,
[out, count = 2490] uint8_t* decrypted_dkg_secret,
[user_check] uint32_t* dec_len);
public void set_encrypted_dkg_poly_aes( [user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 3050] uint8_t* encrypted_poly,
[user_check] uint64_t* enc_len);
};
......
File added
......@@ -62,7 +62,7 @@ int main(int argc, char *argv[]) {
exit(1);
}
while ((opt = getopt(argc, argv, "cshd0")) != -1) {
while ((opt = getopt(argc, argv, "cshd0a")) != -1) {
switch (opt) {
case 'h':
if (strlen(argv[1]) == 2 ) {
......@@ -87,6 +87,8 @@ int main(int argc, char *argv[]) {
case '0':
is_sgx_https = 0;
break;
case 'a':
is_aes = 1;
case '?': // fprintf(stderr, "unknown flag\n");
exit(1);
default:
......
......@@ -37,6 +37,7 @@
extern int DEBUG_PRINT;
extern int is_sgx_https;
extern int is_aes;
#define BUF_LEN 1024
......@@ -57,7 +58,7 @@ extern int is_sgx_https;
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
#define ECDSA_ENCR_LEN 625
#define ECDSA_ENCR_LEN 93
#define ECDSA_BIN_LEN 33
#define UNKNOWN_ERROR -1
......
......@@ -50,8 +50,8 @@
"status": 0,
"errorMessage": "12345",
"encryptedKey": "12345",
"KeyName": "tmp:123",
"PublicKey": "12345"
"keyName": "tmp:123",
"publicKey": "12345"
}
},
......@@ -59,7 +59,7 @@
"name": "renameECDSAKey",
"params": {
"tempKeyName": "key1",
"KeyName": "key2"
"keyName": "key2"
},
"returns": {
"status": 0,
......@@ -75,7 +75,7 @@
"returns": {
"status": 0,
"errorMessage": "12345",
"PublicKey": "12345"
"publicKey": "12345"
}
},
......@@ -132,15 +132,15 @@
"returns": {
"status": 0,
"errorMessage": "12345",
"SecretShare": "123"
"secretShare": "123"
}
},
{
"name": "DKGVerification",
"name": "dkgVerification",
"params": {
"publicShares": "123",
"EthKeyName":"NEK:hex",
"SecretShare": "f_ij",
"ethKeyName":"NEK:hex",
"secretShare": "f_ij",
"n": 3,
"t": 3,
"index" : 2
......@@ -152,36 +152,36 @@
}
},
{
"name": "CreateBLSPrivateKey",
"name": "createBLSPrivateKey",
"params": {
"BLSKeyName": "BLS_KEY:SCHAIN_ID :NODE_ID :DKG_ID: ",
"EthKeyName":"NEK:hex",
"blsKeyName": "BLS_KEY:SCHAIN_ID :NODE_ID :DKG_ID: ",
"ethKeyName":"NEK:hex",
"polyName":"POLY:SCHAIN_ID :NODE_ID :DKG_ID: ",
"SecretShare": "122",
"secretShare": "122",
"n": 3,
"t": 3
},
"returns": {
"status": 0,
"errorMessage": "12345",
"BLSKeyName": "key"
"blsKeyName": "key"
}
},
{
"name": "GetBLSPublicKeyShare",
"name": "getBLSPublicKeyShare",
"params": {
"BLSKeyName": "BLS_KEY:SCHAIN_ID :NODE_ID :DKG_ID"
"blsKeyName": "BLS_KEY:SCHAIN_ID :NODE_ID :DKG_ID"
},
"returns": {
"status": 0,
"errorMessage": "12345",
"BLSPublicKeyShare": []
"blsPublicKeyShare": []
}
},
{
"name": "ComplaintResponse",
"name": "complaintResponse",
"params": {
"polyName": "p1",
"n": 3,
......@@ -192,7 +192,7 @@
"status": 0,
"errorMessage": "12345",
"share*G2": "123",
"DHKey": "123"
"dhKey": "123"
}
},
......
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file stubclient.cpp
@author Stan Kladko
@date 2019
*/
//
// Created by kladko on 9/23/19.
//
#include <iostream>
......
......@@ -68,7 +68,7 @@ class StubClient : public jsonrpc::Client
Json::Value renameECDSAKey(const std::string& KeyName, const std::string& tempKeyName) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["KeyName"] = KeyName;
p["keyName"] = KeyName;
p["tempKeyName"] = tempKeyName;
Json::Value result = this->CallMethod("renameECDSAKey",p);
if (result.isObject())
......@@ -140,68 +140,80 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value DKGVerification(const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index) throw (jsonrpc::JsonRpcException)
Json::Value dkgVerification(const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["EthKeyName"] = EthKeyName;
p["SecretShare"] = SecretShare;
p["ethKeyName"] = ethKeyName;
p["secretShare"] = SecretShare;
p["index"] = index;
p["n"] = n;
p["publicShares"] = publicShares;
p["t"] = t;
Json::Value result = this->CallMethod("DKGVerification",p);
Json::Value result = this->CallMethod("dkgVerification",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n) throw (jsonrpc::JsonRpcException)
Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["BLSKeyName"] = BLSKeyName;
p["EthKeyName"] = EthKeyName;
p["blsKeyName"] = blsKeyName;
p["ethKeyName"] = ethKeyName;
p["polyName"] = polyName;
p["SecretShare"] = SecretShare;
p["secretShare"] = SecretShare;
p["n"] = n;
p["t"] = t;
Json::Value result = this->CallMethod("CreateBLSPrivateKey",p);
Json::Value result = this->CallMethod("reateBLSPrivateKey",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value GetBLSPublicKeyShare(const std::string & BLSKeyName) throw (jsonrpc::JsonRpcException)
Json::Value getBLSPublicKeyShare(const std::string & blsKeyName) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["BLSKeyName"] = BLSKeyName;
p["blsKeyName"] = blsKeyName;
Json::Value result = this->CallMethod("GetBLSPublicKeyShare",p);
Json::Value result = this->CallMethod("getBLSPublicKeyShare",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value ComplaintResponse(const std::string& polyName, int ind) throw (jsonrpc::JsonRpcException)
Json::Value complaintResponse(const std::string& polyName, int ind) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["polyName"] = polyName;
p["ind"] = ind;
Json::Value result = this->CallMethod("ComplaintResponse",p);
Json::Value result = this->CallMethod("complaintResponse",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value MultG2(const std::string & x) throw (jsonrpc::JsonRpcException)
Json::Value multG2(const std::string & x) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["x"] = x;
Json::Value result = this->CallMethod("MultG2",p);
Json::Value result = this->CallMethod("multG2",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value isPolyExists(const std::string & polyName) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["polyName"] = polyName;
Json::Value result = this->CallMethod("isPolyExists",p);
if (result.isObject())
return result;
else
......@@ -211,11 +223,11 @@ class StubClient : public jsonrpc::Client
////CSRManagerServer
Json::Value GetUnsignedCSRs() throw (jsonrpc::JsonRpcException)
Json::Value getUnsignedCSRs() throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("GetUnsignedCSRs",p);
Json::Value result = this->CallMethod("getUnsignedCSRs",p);
if (result.isObject())
return result;
else
......@@ -224,12 +236,12 @@ class StubClient : public jsonrpc::Client
Json::Value SignByHash(const std::string& hash, int status) throw (jsonrpc::JsonRpcException)
Json::Value signByHash(const std::string& hash, int status) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["hash"] = hash;
p["status"] = status;
Json::Value result = this->CallMethod("SignByHash",p);
Json::Value result = this->CallMethod("signByHash",p);
if (result.isObject())
return result;
else
......
......@@ -79,10 +79,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BLSPublicKey.h"
#include <thread>
#include "common.h"
std::string stringFromFr(libff::alt_bn128_Fr& el) {
string stringFromFr(libff::alt_bn128_Fr& el) {
mpz_t t;
mpz_init(t);
......@@ -94,7 +95,7 @@ std::string stringFromFr(libff::alt_bn128_Fr& el) {
char *tmp = mpz_get_str(arr, 10, t);
mpz_clear(t);
return std::string(tmp);
return string(tmp);
}
......@@ -139,7 +140,8 @@ char* encryptTestKey() {
TEST_CASE("BLS key encrypt", "[bls-key-encrypt]") {
DEBUG_PRINT = 1;
is_sgx_https = 0;
init_all(false, false);
char* key = encryptTestKey();
REQUIRE(key != nullptr);
......@@ -150,8 +152,11 @@ TEST_CASE("BLS key encrypt", "[bls-key-encrypt]") {
TEST_CASE("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
{
DEBUG_PRINT = 1;
is_sgx_https = 0;
init_all(false, false);
init_all(false, false);
//init_enclave();
int errStatus = -1;
char* errMsg = (char*) calloc(BUF_LEN, 1);
......@@ -171,6 +176,8 @@ TEST_CASE("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
printf("Decrypted key len %d\n", (int) strlen(plaintextKey));
printf("Decrypted key: %s\n", plaintextKey);
sgx_destroy_enclave(eid);
}
}
......@@ -307,17 +314,17 @@ TEST_CASE( "DKG gen test", "[dkg-gen]" ) {
sgx_destroy_enclave(eid);
}
std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char symbol){
std::string str(koefs);
std::string delim;
vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char symbol){
string str(koefs);
string delim;
delim.push_back(symbol);
std::vector<libff::alt_bn128_Fr> tokens;
vector<libff::alt_bn128_Fr> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) {
libff::alt_bn128_Fr koef(token.c_str());
tokens.push_back(koef);
......@@ -329,20 +336,20 @@ std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char s
return tokens;
}
std::vector<std::string> SplitStringTest(const char* koefs, const char symbol){
vector<string> SplitStringTest(const char* koefs, const char symbol){
libff::init_alt_bn128_params();
std::string str(koefs);
std::string delim;
string str(koefs);
string delim;
delim.push_back(symbol);
std::vector<std::string> G2_strings;
vector<string> G2_strings;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) {
std::string koef(token.c_str());
string koef(token.c_str());
G2_strings.push_back(koef);
}
prev = pos + delim.length();
......@@ -352,7 +359,7 @@ std::vector<std::string> SplitStringTest(const char* koefs, const char symbol){
return G2_strings;
}
libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
libff::alt_bn128_G2 VectStringToG2(const vector<string>& G2_str_vect){
libff::init_alt_bn128_params();
libff::alt_bn128_G2 koef = libff::alt_bn128_G2::zero();
koef.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str());
......@@ -400,7 +407,7 @@ libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
printf("\nget_secret_shares status: %d %s \n", err_status, errMsg1);
printf("secret shares %s \n\n", secret_shares);
std::vector <libff::alt_bn128_Fr> s_shares = SplitStringToFr( secret_shares, colon);
vector <libff::alt_bn128_Fr> s_shares = SplitStringToFr( secret_shares, colon);
char* secret = (char*)calloc(DKG_BUFER_LENGTH, sizeof(char));
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, &dec_len);
......@@ -409,8 +416,8 @@ libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
signatures::Dkg dkg_obj(t,n);
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
std::vector < libff::alt_bn128_Fr> s_shares_dkg = dkg_obj.SecretKeyContribution(SplitStringToFr((char*)secret, colon));
vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
vector < libff::alt_bn128_Fr> s_shares_dkg = dkg_obj.SecretKeyContribution(SplitStringToFr((char*)secret, colon));
printf("calculated secret length %d : \n", s_shares_dkg.size());
for ( int i = 0; i < s_shares_dkg.size(); i++){
libff::alt_bn128_Fr cur_share = s_shares_dkg.at(i);
......@@ -461,12 +468,12 @@ TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
printf(" LEN: %d \n", strlen(public_shares));
printf(" result: %s \n", public_shares);
std::vector <std::string> G2_strings = SplitString( public_shares, ',');
std::vector <libff::alt_bn128_G2> pub_shares_G2;
vector <string> G2_strings = SplitString( public_shares, ',');
vector <libff::alt_bn128_G2> pub_shares_G2;
for ( int i = 0; i < G2_strings.size(); i++){
std::vector <std::string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
vector <string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
libff::alt_bn128_G2 el = VectStringToG2(koef_str);
//std::cerr << "pub_share G2 " << i+1 << " : " << std::endl;
//cerr << "pub_share G2 " << i+1 << " : " << endl;
//el.print_coordinates();
pub_shares_G2.push_back(VectStringToG2(koef_str));
}
......@@ -478,8 +485,8 @@ TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
signatures::Dkg dkg_obj(t,n);
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
std::vector < libff::alt_bn128_G2> pub_shares_dkg = dkg_obj.VerificationVector(poly);
vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
vector < libff::alt_bn128_G2> pub_shares_dkg = dkg_obj.VerificationVector(poly);
printf("calculated public shares (X.c0): \n");
for ( int i = 0; i < pub_shares_dkg.size(); i++){
libff::alt_bn128_G2 el = pub_shares_dkg.at(i);
......@@ -523,11 +530,11 @@ TEST_CASE( "DKG encrypted secret shares test", "[dkg-encr_sshares]" ) {
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly generated" << std::endl;
cerr << " poly generated" << endl;
status = set_encrypted_dkg_poly(eid, &err_status, errMsg, encrypted_dkg_secret);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly set" << std::endl;
cerr << " poly set" << endl;
uint8_t *encr_pr_DHkey = (uint8_t *)calloc(1024, 1);
char *pub_key_x = (char *)calloc(1024, 1);
......@@ -540,7 +547,7 @@ TEST_CASE( "DKG encrypted secret shares test", "[dkg-encr_sshares]" ) {
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg);
std::cerr << "secret share is " << result << std::endl;
cerr << "secret share is " << result << endl;
}
TEST_CASE( "DKG verification test", "[dkg-verify]" ) {
......@@ -561,11 +568,11 @@ TEST_CASE( "DKG verification test", "[dkg-verify]" ) {
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly generated" << std::endl;
cerr << " poly generated" << endl;
status = set_encrypted_dkg_poly(eid, &err_status, errMsg, encrypted_dkg_secret);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly set" << std::endl;
cerr << " poly set" << endl;
uint8_t *encr_pr_DHkey = (uint8_t *)calloc(1024, 1);
char *pub_key_x = (char *)calloc(1024, 1);
......@@ -579,7 +586,7 @@ TEST_CASE( "DKG verification test", "[dkg-verify]" ) {
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg);
std::cerr << "secret share is " << result << std::endl;
cerr << "secret share is " << result << endl;
}
......@@ -717,8 +724,8 @@ TEST_CASE( "pub_bls_key", "[pub_bls]" ) {
char *encryptedKeyHex =
"04000200000000000406ffffff02000000000000000000000b000000000000ff0000000000000000813f8390f6228a568e181a4dadb6508e3e66f5247175d65dbd0d8c7fbfa4df45000000f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000008000000000000000000000000000000000dc044ae0cd79faaf41e8a7abb412790476738a98b5b6ce95fa1a32db5551b0a0d867305f4de558c64fee730a1f62394633c7d4ca65e3a40b7883e89c2801c61918b01c5de8624a52963df6f4de8581bcbdd2f9b69720d4cc764e03a04c7a99314bfdb5d2d55deda2ca40cd691f093fb2ecbae24cdacdd4d5de93189c6dfd6792d7b95bd5e330aec3538e7a85d15793"; // encryptTestKey();
//writeDataToDB("test_bls_key0", encryptedKeyHex);
std::vector<std::string> result = GetBLSPubKey(encryptedKeyHex);
//std::cerr << "pub key " << result << std::endl;
vector<string> result = GetBLSPubKey(encryptedKeyHex);
//cerr << "pub key " << result << endl;
sgx_destroy_enclave(eid);
}
......@@ -728,7 +735,7 @@ TEST_CASE( "pub_bls_key", "[pub_bls]" ) {
using namespace jsonrpc;
using namespace std;
std::string ConvertDecToHex(std::string dec, int numBytes = 32){
string ConvertDecToHex(string dec, int numBytes = 32){
mpz_t num;
mpz_init(num);
mpz_set_str(num, dec.c_str(), 10);
......@@ -736,7 +743,7 @@ std::string ConvertDecToHex(std::string dec, int numBytes = 32){
char tmp[mpz_sizeinbase (num, 16) + 2];
char * hex = mpz_get_str(tmp, 16, num);
std::string result = hex;
string result = hex;
int n_zeroes = numBytes * 2 - result.length();
result.insert(0, n_zeroes, '0');
......@@ -747,7 +754,7 @@ std::string ConvertDecToHex(std::string dec, int numBytes = 32){
TEST_CASE("BLS_DKG test", "[bls_dkg]") {
is_sgx_https = 0;
DEBUG_PRINT = 1;
std::cerr<< "test started" << std::endl;
cerr<< "test started" << endl;
init_all(false, false);
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1029");
......@@ -757,24 +764,24 @@ TEST_CASE("BLS_DKG test", "[bls_dkg]") {
reset_db();
int n = 4, t = 4;
int n = 16, t = 16;
Json::Value EthKeys[n];
Json::Value VerifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value BLSSigShares[n];
std::vector<std::string> pubShares(n);
std::vector<std::string> poly_names(n);
vector<string> pubShares(n);
vector<string> poly_names(n);
for ( uint8_t i = 0; i < n; i++){
EthKeys[i] = c.generateECDSAKey();
std::string polyName = "POLY:SCHAIN_ID:1:NODE_ID:" + std::to_string(i) + ":DKG_ID:0";
string polyName = "POLY:SCHAIN_ID:1:NODE_ID:" + to_string(i) + ":DKG_ID:0";
c.generateDKGPoly(polyName, t);
poly_names[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
cout << "VV " << i << " " << VerifVects[i] << std::endl;
pubEthKeys.append(EthKeys[i]["PublicKey"]);
cout << "VV " << i << " " << VerifVects[i] << endl;
pubEthKeys.append(EthKeys[i]["publicKey"]);
}
......@@ -782,88 +789,88 @@ TEST_CASE("BLS_DKG test", "[bls_dkg]") {
secretShares[i] = c.getSecretShare(poly_names[i], pubEthKeys, t, n);
for ( uint8_t k = 0; k < t; k++ ) {
for (uint8_t j = 0; j < 4; j++) {
std::string pubShare = VerifVects[i]["Verification Vector"][k][j].asString();
string pubShare = VerifVects[i]["verificationVector"][k][j].asString();
pubShares[i] += ConvertDecToHex(pubShare);
}
}
// std::cerr << "i is " << i << " pubShares[i] = " << pubShares[i] << std::endl;
// std::cerr << "length is" << pubShares[i].length() << std::endl;
// cerr << "i is " << i << " pubShares[i] = " << pubShares[i] << endl;
// cerr << "length is" << pubShares[i].length() << endl;
}
Json::Value ComplaintResponse = c.ComplaintResponse(poly_names[1], 0);
std::cerr << "share * G2 is " << ComplaintResponse["share*G2"].asString();
std::cerr << "DHKey is " << ComplaintResponse["DHKey"].asString();
Json::Value complaintResponse = c.complaintResponse(poly_names[1], 0);
cerr << "share * G2 is " << complaintResponse["share*G2"].asString();
cerr << "DHKey is " << complaintResponse["dhKey"].asString();
int k = 0;
std::vector < std::string> secShares_vect(n);
vector < string> secShares_vect(n);
std::vector <std::string> pSharesBad(pubShares);
vector <string> pSharesBad(pubShares);
for ( int i = 0; i < n; i++)
for ( int j = 0; j < n; j++){
// if ( i != j ){
std::cerr << "SecretShare length is " << secretShares[i]["SecretShare"].asString().length() << std::endl;
std::string secretShare = secretShares[i]["SecretShare"].asString().substr(192*j, 192);
secShares_vect[i] += secretShares[j]["SecretShare"].asString().substr(192*i, 192);
bool res = c.DKGVerification(pubShares[i], EthKeys[j]["KeyName"].asString(), secretShare, t, n, j)["result"].asBool();
cerr << "secretShare length is " << secretShares[i]["secretShare"].asString().length() << endl;
string secretShare = secretShares[i]["secretShare"].asString().substr(192*j, 192);
secShares_vect[i] += secretShares[j]["secretShare"].asString().substr(192*i, 192);
bool res = c.dkgVerification(pubShares[i], EthKeys[j]["keyName"].asString(), secretShare, t, n, j)["result"].asBool();
k++;
std::cerr << "NOW K IS " << k << " i is " << i << " j is " << j << std::endl;
cerr << "NOW K IS " << k << " i is " << i << " j is " << j << endl;
REQUIRE(res);
pSharesBad[i][0] = 'q';
Json::Value wrongVerif = c.DKGVerification(pSharesBad[i], EthKeys[j]["KeyName"].asString(), secretShare, t, n, j);
Json::Value wrongVerif = c.dkgVerification(pSharesBad[i], EthKeys[j]["keyName"].asString(), secretShare, t, n, j);
res = wrongVerif["result"].asBool();
REQUIRE(!res);
std::cerr << "wrong verification " << wrongVerif << std::endl;
cerr << "wrong verification " << wrongVerif << endl;
// }
}
BLSSigShareSet sigShareSet(t, n);
std::string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
auto hash_arr = std::make_shared<std::array<uint8_t, 32>>();
auto hash_arr = make_shared<array<uint8_t, 32>>();
uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())){
throw RPCException(INVALID_HEX, "Invalid hash");
}
std::map<size_t, std::shared_ptr<BLSPublicKeyShare>> koefs_pkeys_map;
map<size_t, shared_ptr<BLSPublicKeyShare>> koefs_pkeys_map;
for ( int i = 0; i < t; i++){
std::string endName = poly_names[i].substr(4);
std::string blsName = "BLS_KEY" + poly_names[i].substr(4);
std::string secretShare = secretShares[i]["SecretShare"].asString();
//cout << c.CreateBLSPrivateKey(blsName, EthKeys[i]["KeyName"].asString(), poly_names[i], secretShare, t, n);
cout << c.CreateBLSPrivateKey(blsName, EthKeys[i]["KeyName"].asString(), poly_names[i], secShares_vect[i], t, n);
pubBLSKeys[i] = c.GetBLSPublicKeyShare(blsName);
std::cerr << "BLS KEY SHARE NAME IS " << blsName << std::endl;
//std::string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
string endName = poly_names[i].substr(4);
string blsName = "BLS_KEY" + poly_names[i].substr(4);
string secretShare = secretShares[i]["secretShare"].asString();
//cout << c.createBLSPrivateKey(blsName, EthKeys[i]["keyName"].asString(), poly_names[i], secretShare, t, n);
cout << c.createBLSPrivateKey(blsName, EthKeys[i]["keyName"].asString(), poly_names[i], secShares_vect[i], t, n);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
cerr << "BLS KEY SHARE NAME IS " << blsName << endl;
//string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
BLSSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
std::cerr << i << " sig share is created " << std::endl;
std::shared_ptr<std::string> sig_share_ptr = std::make_shared<std::string>(BLSSigShares[i]["signatureShare"].asString());
cerr << i << " sig share is created " << endl;
shared_ptr<string> sig_share_ptr = make_shared<string>(BLSSigShares[i]["signatureShare"].asString());
BLSSigShare sig(sig_share_ptr, i + 1, t, n);
sigShareSet.addSigShare(std::make_shared<BLSSigShare>(sig));
sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));
std::vector<std::string> pubKey_vect;
vector<string> pubKey_vect;
for ( uint8_t j = 0; j < 4; j++){
pubKey_vect.push_back(pubBLSKeys[i]["BLSPublicKeyShare"][j].asString());
pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
}
BLSPublicKeyShare pubKey(std::make_shared<std::vector<std::string>>(pubKey_vect), t, n);
REQUIRE( pubKey.VerifySigWithHelper(hash_arr, std::make_shared<BLSSigShare>(sig) , t, n));
BLSPublicKeyShare pubKey(make_shared<vector<string>>(pubKey_vect), t, n);
REQUIRE( pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig) , t, n));
koefs_pkeys_map[i+1] = std::make_shared<BLSPublicKeyShare>(pubKey);
koefs_pkeys_map[i+1] = make_shared<BLSPublicKeyShare>(pubKey);
}
std::shared_ptr<BLSSignature> commonSig = sigShareSet.merge();
BLSPublicKey common_public(std::make_shared<std::map<size_t, std::shared_ptr<BLSPublicKeyShare>>>(koefs_pkeys_map), t, n);
shared_ptr<BLSSignature> commonSig = sigShareSet.merge();
BLSPublicKey common_public(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare>>>(koefs_pkeys_map), t, n);
REQUIRE( common_public.VerifySigWithHelper(hash_arr, commonSig, t, n) );
std::cout << "try to get bls public key" << std::endl;
std::cout << c.GetBLSPublicKeyShare("BLS_KEY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:0");
cout << "try to get bls public key" << endl;
cout << c.getBLSPublicKeyShare("BLS_KEY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:0");
}
......@@ -871,7 +878,7 @@ TEST_CASE("BLS_DKG test", "[bls_dkg]") {
TEST_CASE("API test", "[api_test]") {
//DEBUG_PRINT = 1;
is_sgx_https = 0;
//std::cerr << __GNUC__ << std::endl;
//cerr << __GNUC__ << endl;
cerr << "API test started" << endl;
init_all(false, false);
//HttpServer httpserver(1025);
......@@ -886,20 +893,20 @@ TEST_CASE("API test", "[api_test]") {
try {
// for ( uint8_t i = 0; i < 2; i++) {
// levelDb->deleteKey("POLY:SCHAIN_ID:1:NODE_ID:" + std::to_string(i) +
// levelDb->deleteKey("POLY:SCHAIN_ID:1:NODE_ID:" + to_string(i) +
// ":DKG_ID:0");
//
// levelDb->deleteKey(" DKG_DH_KEY_POLY:SCHAIN_ID:0:NODE_ID:" + std::to_string(i)+ ":DKG_ID:0_0");
// levelDb->deleteKey(" DKG_DH_KEY_POLY:SCHAIN_ID:0:NODE_ID:" + std::to_string(i)+ ":DKG_ID:0_1");
// levelDb->deleteKey(" DKG_DH_KEY_POLY:SCHAIN_ID:0:NODE_ID:" + to_string(i)+ ":DKG_ID:0_0");
// levelDb->deleteKey(" DKG_DH_KEY_POLY:SCHAIN_ID:0:NODE_ID:" + to_string(i)+ ":DKG_ID:0_1");
// }
//cout << c.importBLSKeyShare("4160780231445160889237664391382223604184857153814275770598791864649971919844","BLS_KEY:SCHAIN_ID:2660016693368503500803087136248943520694587309641817:NODE_ID:33909:DKG_ID:3522960548719023733985054069487289468077787284706573", 4, 3,1);
Json::Value genKey = c.generateECDSAKey();
cout << genKey << endl;
cout << c.ecdsaSignMessageHash(16, genKey["KeyName"].asString(),"0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
Json::Value getPubKey = c.getPublicECDSAKey(genKey["KeyName"].asString());
cout << getPubKey << std::endl;
cout << c.ecdsaSignMessageHash(16, genKey["keyName"].asString(),"0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
cout << getPubKey << endl;
// cout << c.renameESDSAKey("NODE_1CHAIN_1","tmp_NEK:bcacde0d26c0ea2c7e649992e7f791e1fba2492f5b7ae63dadb799075167c7fc");
// cout<<c.getPublicECDSAKey("NEK:7ca98cf32fd1edba26ea685820719fd2201b068a10c1264d382abbde13802a0e");
//cout << c.ecdsaSignMessageHash(16, "NEK:697fadfc597bdbfae9ffb7412b80939e848c9c2fec2657bb2122b6d0d4a0dca8","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
......@@ -931,39 +938,39 @@ TEST_CASE("API test", "[api_test]") {
std::string share_big0 = "501e364a6ea516f4812b013bcc150cbb435a2c465c9fd525951264969d8441a986798fd3317c1c3e60f868bb26c4cff837d9185f4be6015d8326437cb5b69480495859cd5a385430ece51252acdc234d8dbde75708b600ac50b2974e813ee26bd87140d88647fcc44df7262bbba24328e8ce622cd627a15b508ffa0db9ae81e0e110fab42cfe40da66b524218ca3c8e5aa3363fbcadef748dc3523a7ffb95b8f5d8141a5163db9f69d1ab223494ed71487c9bb032a74c08a222d897a5e49a617";
std::string share_big = "03f749e2fcc28021895d757ec16d1636784446f5effcd3096b045136d8ab02657b32adc577f421330b81f5b7063df3b08a0621a897df2584b9046ca416e50ecc27e8c3277e981f7e650f8640289be128eecf0105f89a20e5ffb164744c45cf191d627ce9ab6c44e2ef96f230f2a4de742ea43b6f74b56849138026610b2d965605ececba527048a0f29f46334b1cec1d23df036248b24eccca99057d24764acee66c1a3f2f44771d0d237bf9d18c4177277e3ce3dc4e83686a2647fce1565ee0";
std::string share = share_big.substr(0, 192);
string share_big0 = "501e364a6ea516f4812b013bcc150cbb435a2c465c9fd525951264969d8441a986798fd3317c1c3e60f868bb26c4cff837d9185f4be6015d8326437cb5b69480495859cd5a385430ece51252acdc234d8dbde75708b600ac50b2974e813ee26bd87140d88647fcc44df7262bbba24328e8ce622cd627a15b508ffa0db9ae81e0e110fab42cfe40da66b524218ca3c8e5aa3363fbcadef748dc3523a7ffb95b8f5d8141a5163db9f69d1ab223494ed71487c9bb032a74c08a222d897a5e49a617";
string share_big = "03f749e2fcc28021895d757ec16d1636784446f5effcd3096b045136d8ab02657b32adc577f421330b81f5b7063df3b08a0621a897df2584b9046ca416e50ecc27e8c3277e981f7e650f8640289be128eecf0105f89a20e5ffb164744c45cf191d627ce9ab6c44e2ef96f230f2a4de742ea43b6f74b56849138026610b2d965605ececba527048a0f29f46334b1cec1d23df036248b24eccca99057d24764acee66c1a3f2f44771d0d237bf9d18c4177277e3ce3dc4e83686a2647fce1565ee0";
string share = share_big.substr(0, 192);
std::string publicShares = "1fc8154abcbf0c2ebf559571d7b57a8995c0e293a73d4676a8f76051a0d0ace30e00a87c9f087254c9c860c3215c4f11e8f85a3e8fae19358f06a0cbddf3df1924b1347b9b58f5bcb20958a19bdbdd832181cfa9f9e9fd698f6a485051cb47b829d10f75b6e227a7d7366dd02825b5718072cd42c39f0352071808622b7db6421b1069f519527e49052a8da6e3720cbda9212fc656eef945f5e56a4159c3b9622d883400460a9eff07fe1873f9b1ec50f6cf70098b9da0b90625b176f12329fa2ecc65082c626dc702d9cfb23a06770d4a2c7867e269efe84e3709b11001fb380a32d609855d1d46bc60f21140c636618b8ff55ed06d7788b6f81b498f96d3f9";
// cout << c.DKGVerification(publicShares, "test_key1", "37092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76", 2, 2, 0);
string publicShares = "1fc8154abcbf0c2ebf559571d7b57a8995c0e293a73d4676a8f76051a0d0ace30e00a87c9f087254c9c860c3215c4f11e8f85a3e8fae19358f06a0cbddf3df1924b1347b9b58f5bcb20958a19bdbdd832181cfa9f9e9fd698f6a485051cb47b829d10f75b6e227a7d7366dd02825b5718072cd42c39f0352071808622b7db6421b1069f519527e49052a8da6e3720cbda9212fc656eef945f5e56a4159c3b9622d883400460a9eff07fe1873f9b1ec50f6cf70098b9da0b90625b176f12329fa2ecc65082c626dc702d9cfb23a06770d4a2c7867e269efe84e3709b11001fb380a32d609855d1d46bc60f21140c636618b8ff55ed06d7788b6f81b498f96d3f9";
// cout << c.dkgVerification(publicShares, "test_key1", "37092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76", 2, 2, 0);
// cout << c.DKGVerification("oleh1", "key0", "37092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76", 2, 2, 0);
// cout << c.dkgVerification("oleh1", "key0", "37092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76", 2, 2, 0);
Json::Value SecretShare;
SecretShare.append(share_big0);
SecretShare.append(share_big);
//cout << c.CreateBLSPrivateKey( "test_bls_key1","test_key1", "p2", share_big0, 2, 2 );
//cout << c.createBLSPrivateKey( "test_bls_key1","test_key1", "p2", share_big0, 2, 2 );
// std::string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76df831dbef474cfc38be1c980130a8d273ff410fbf87deece9d7756a1b08ba9e954c1676cc7f2cac16e16cff0c877d8cf967381321fb4cc78e3638245a1dc85419766d281aff4935cc6eac25c9842032c8f7fae567c57622969599a72c42d2e1e";
std::string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b7637092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76";
//cout << c.CreateBLSPrivateKey( "test_bls1","key0", "oleh1", shares, 2, 2 );
// string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76df831dbef474cfc38be1c980130a8d273ff410fbf87deece9d7756a1b08ba9e954c1676cc7f2cac16e16cff0c877d8cf967381321fb4cc78e3638245a1dc85419766d281aff4935cc6eac25c9842032c8f7fae567c57622969599a72c42d2e1e";
string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b7637092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76";
//cout << c.createBLSPrivateKey( "test_bls1","key0", "oleh1", shares, 2, 2 );
//cout << c.GetBLSPublicKeyShare("test_bls_key0");
//cout << c.getBLSPublicKeyShare("test_bls_key0");
std::string s_share = "13b871ad5025fed10a41388265b19886e78f449f758fe8642ade51440fcf850bb2083f87227d8fb53fdfb2854e2d0abec4f47e2197b821b564413af96124cd84a8700f8eb9ed03161888c9ef58d6e5896403de3608e634e23e92fba041aa283484427d0e6de20922216c65865cfe26edd2cf9cbfc3116d007710e8d82feafd9135c497bef0c800ca310ba6044763572681510dad5e043ebd87ffaa1a4cd45a899222207f3d05dec8110d132ad34c62d6a3b40bf8e9f40f875125c3035062d2ca";
std::string EthKeyName = "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01";
//cout << c.CreateBLSPrivateKey( "test_blskey", EthKeyName, "JCGMt", s_share, 2, 2 );
//cout << c.GetBLSPublicKeyShare("test_blskey");
string s_share = "13b871ad5025fed10a41388265b19886e78f449f758fe8642ade51440fcf850bb2083f87227d8fb53fdfb2854e2d0abec4f47e2197b821b564413af96124cd84a8700f8eb9ed03161888c9ef58d6e5896403de3608e634e23e92fba041aa283484427d0e6de20922216c65865cfe26edd2cf9cbfc3116d007710e8d82feafd9135c497bef0c800ca310ba6044763572681510dad5e043ebd87ffaa1a4cd45a899222207f3d05dec8110d132ad34c62d6a3b40bf8e9f40f875125c3035062d2ca";
string ethKeyName = "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01";
//cout << c.createBLSPrivateKey( "test_blskey", ethKeyName, "JCGMt", s_share, 2, 2 );
//cout << c.getBLSPublicKeyShare("test_blskey");
// cout << c.blsSignMessageHash("dOsRY","38433e5ce087dcc1be82fcc834eae83c256b3db87d34f84440d0b708daa0c6f7", 2, 2, 1);
// cout << c.ComplaintResponse("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", 0);
// cout << c.GetBLSPublicKeyShare("BLS_KEY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:0");
// cout << c.complaintResponse("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", 0);
// cout << c.getBLSPublicKeyShare("BLS_KEY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:0");
// cout << c.getPublicECDSAKey("NEK:91573248d6b0ebd5b1bd313ab35163361b423c0f9f01bad085d166650b8b2c1f");
//cout << c.MultG2("4160780231445160889237664391382223604184857153814275770598791864649971919844");
//cout << c.multG2("4160780231445160889237664391382223604184857153814275770598791864649971919844");
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
......@@ -980,10 +987,10 @@ TEST_CASE("getServerStatus test", "[getServerStatus_test]") {
sgx_destroy_enclave(eid);
}
std::default_random_engine rand_gen((unsigned int) time(0));
default_random_engine rand_gen((unsigned int) time(0));
void SendRPCRequest(){
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
cout << "Hello from thread " << this_thread::get_id() << endl;
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
reset_db();
......@@ -996,50 +1003,50 @@ void SendRPCRequest(){
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value BLSSigShares[n];
std::vector<std::string> pubShares(n);
std::vector<std::string> poly_names(n);
vector<string> pubShares(n);
vector<string> poly_names(n);
int schain_id = rand_gen();
int dkg_id = rand_gen();
for ( uint8_t i = 0; i < n; i++){
EthKeys[i] = c.generateECDSAKey();
std::string polyName = "POLY:SCHAIN_ID:" + std::to_string(schain_id) + ":NODE_ID:" + std::to_string(i) + ":DKG_ID:" + std::to_string(dkg_id);
string polyName = "POLY:SCHAIN_ID:" + to_string(schain_id) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkg_id);
c.generateDKGPoly(polyName, t);
poly_names[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
cout << "VV " << i << " " << VerifVects[i] << std::endl;
pubEthKeys.append(EthKeys[i]["PublicKey"]);
cout << "VV " << i << " " << VerifVects[i] << endl;
pubEthKeys.append(EthKeys[i]["publicKey"]);
}
for ( uint8_t i = 0; i < n; i++){
secretShares[i] = c.getSecretShare(poly_names[i], pubEthKeys, t, n);
for ( uint8_t k = 0; k < t; k++ ) {
for (uint8_t j = 0; j < 4; j++) {
std::string pubShare = VerifVects[i]["Verification Vector"][k][j].asString();
string pubShare = VerifVects[i]["verificationVector"][k][j].asString();
pubShares[i] += ConvertDecToHex(pubShare);
}
}
// std::cerr << "i is " << i << " pubShares[i] = " << pubShares[i] << std::endl;
// std::cerr << "length is" << pubShares[i].length() << std::endl;
// cerr << "i is " << i << " pubShares[i] = " << pubShares[i] << endl;
// cerr << "length is" << pubShares[i].length() << endl;
}
// Json::Value ComplaintResponse = c.ComplaintResponse(poly_names[1], 0);
// std::cerr << "share * G2 is " << ComplaintResponse["share*G2"].asString();
// std::cerr << "DHKey is " << ComplaintResponse["DHKey"].asString();
// Json::Value complaintResponse = c.complaintResponse(poly_names[1], 0);
// cerr << "share * G2 is " << complaintResponse["share*G2"].asString();
// cerr << "DHKey is " << complaintResponse["DHKey"].asString();
int k = 0;
std::vector <std::string> secShares_vect(n);
vector <string> secShares_vect(n);
for ( int i = 0; i < n; i++)
for ( int j = 0; j < n; j++){
if ( i != j ){
std::cerr << "SecretShare length is " << secretShares[i]["SecretShare"].asString().length() << std::endl;
std::string secretShare = secretShares[i]["SecretShare"].asString().substr(192*j, 192 );
secShares_vect[i] += secretShares[j]["SecretShare"].asString().substr(192*i, 192 );
bool res = c.DKGVerification(pubShares[i], EthKeys[j]["KeyName"].asString(), secretShare, t, n, j)["result"].asBool();
cerr << "SecretShare length is " << secretShares[i]["secretShare"].asString().length() << endl;
string secretShare = secretShares[i]["secretShare"].asString().substr(192*j, 192 );
secShares_vect[i] += secretShares[j]["secretShare"].asString().substr(192*i, 192 );
bool res = c.dkgVerification(pubShares[i], EthKeys[j]["keyName"].asString(), secretShare, t, n, j)["result"].asBool();
k++;
std::cerr << "NOW K IS " << k << " i is " << i << " j is " << j << std::endl;
cerr << "NOW K IS " << k << " i is " << i << " j is " << j << endl;
REQUIRE( res );
}
}
......@@ -1049,10 +1056,10 @@ TEST_CASE("ManySimultaneousThreads", "[many_threads_test]") {
is_sgx_https = 0;
init_all( false, false );
std::vector<std::thread> threads;
vector<thread> threads;
int num_threads = 16;
for (int i = 0; i < num_threads; i++){
threads.push_back(std::thread(SendRPCRequest));
threads.push_back(thread(SendRPCRequest));
}
for(auto& thread : threads){
......@@ -1065,6 +1072,7 @@ TEST_CASE("ManySimultaneousThreads", "[many_threads_test]") {
TEST_CASE("ecdsa API test", "[ecdsa_api_test]") {
DEBUG_PRINT = 1;
is_sgx_https = 0;
is_aes = 1;
cerr << "ecdsa_api_test started" << endl;
init_all(false, false);
......@@ -1076,32 +1084,37 @@ TEST_CASE("ecdsa API test", "[ecdsa_api_test]") {
cerr << "Client inited" << endl;
Json::Value genKey = c.generateECDSAKey();
REQUIRE(genKey["status"].asInt() == 0);
cout << genKey << endl;
Json::Value ecdsaSign = c.ecdsaSignMessageHash(16, genKey["KeyName"].asString(), "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
REQUIRE(ecdsaSign["status"].asInt() == 0);
cout << ecdsaSign << std::endl;
Json::Value getPubKey = c.getPublicECDSAKey(genKey["KeyName"].asString());
REQUIRE(genKey["status"].asInt() == 0);
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
cout << getPubKey << endl;
REQUIRE(getPubKey["status"].asInt() == 0);
cout << getPubKey << std::endl;
//wrong base
Json::Value ecdsaSignWrongBase = c.ecdsaSignMessageHash(0, genKey["KeyName"].asString(), "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
cout << ecdsaSignWrongBase << std::endl;
REQUIRE(ecdsaSignWrongBase["status"].asInt() != 0);
//wrong keyName
Json::Value ecdsaSignWrongKeyName = c.ecdsaSignMessageHash(0, "", "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
cout << ecdsaSignWrongKeyName << std::endl;
REQUIRE(ecdsaSignWrongKeyName["status"].asInt() != 0);
Json::Value getPubKeyWrongKeyName = c.getPublicECDSAKey("keyName");
REQUIRE(getPubKeyWrongKeyName["status"].asInt() != 0);
cout << getPubKeyWrongKeyName << std::endl;
//wrong hash
Json::Value ecdsaSignWrongHash = c.ecdsaSignMessageHash(16, genKey["KeyName"].asString(), "");
cout << ecdsaSignWrongHash << std::endl;
REQUIRE(ecdsaSignWrongHash["status"].asInt() != 0);
REQUIRE(getPubKey["publicKey"].asString() == genKey["publicKey"].asString());
Json::Value ecdsaSign = c.ecdsaSignMessageHash(16, genKey["keyName"].asString(), "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
cout << ecdsaSign << endl;
REQUIRE(ecdsaSign["status"].asInt() == 0);
// //wrong base
// Json::Value ecdsaSignWrongBase = c.ecdsaSignMessageHash(0, genKey["keyName"].asString(), "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
// cout << ecdsaSignWrongBase << endl;
// REQUIRE(ecdsaSignWrongBase["status"].asInt() != 0);
//
// //wrong keyName
// Json::Value ecdsaSignWrongKeyName = c.ecdsaSignMessageHash(0, "", "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
// cout << ecdsaSignWrongKeyName << endl;
// REQUIRE(ecdsaSignWrongKeyName["status"].asInt() != 0);
// Json::Value getPubKeyWrongKeyName = c.getPublicECDSAKey("keyName");
// REQUIRE(getPubKeyWrongKeyName["status"].asInt() != 0);
// cout << getPubKeyWrongKeyName << endl;
//
// //wrong hash
// Json::Value ecdsaSignWrongHash = c.ecdsaSignMessageHash(16, genKey["keyName"].asString(), "");
// cout << ecdsaSignWrongHash << endl;
// REQUIRE(ecdsaSignWrongHash["status"].asInt() != 0);
sgx_destroy_enclave(eid);
}
......@@ -1121,7 +1134,7 @@ TEST_CASE("dkg API test", "[dkg_api_test]") {
reset_db();
std::string polyName = "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1";
string polyName = "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1";
Json::Value genPoly = c.generateDKGPoly(polyName, 2);
Json::Value publicKeys;
......@@ -1173,9 +1186,74 @@ TEST_CASE("dkg API test", "[dkg_api_test]") {
//wrong verif
Json::Value Skeys = c.getSecretShare(polyName, publicKeys, 2, 2);
Json::Value verifVect = c.getVerificationVector(polyName, 2, 2);
Json::Value verificationWrongSkeys = c.DKGVerification("","","",2, 2, 1);
Json::Value verificationWrongSkeys = c.dkgVerification("","","",2, 2, 1);
REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
cout << verificationWrongSkeys << endl;
sgx_destroy_enclave(eid);
}
TEST_CASE("isPolyExists test", "[is_poly_test]") {
DEBUG_PRINT = 1;
is_sgx_https = 0;
cerr << "is_poly_test started" << endl;
init_all(false, false);
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
reset_db();
string polyName = "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1";
Json::Value genPoly = c.generateDKGPoly(polyName, 2);
cout << genPoly << endl;
Json::Value polyExists = c.isPolyExists(polyName);
cout << polyExists << endl;
REQUIRE(polyExists["IsExist"].asBool());
Json::Value polyDoesNotExist = c.isPolyExists("Vasya");
cout << polyDoesNotExist << endl;
REQUIRE(!polyDoesNotExist["IsExist"].asBool());
}
TEST_CASE("AES_DKG test", "[aes_dkg]") {
is_sgx_https = 0;
DEBUG_PRINT = 1;
is_aes = 1;
std::cerr << "test started" << std::endl;
init_all(false, false);
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
reset_db();
int n = 4, t = 4;
Json::Value EthKeys[n];
Json::Value VerifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value BLSSigShares[n];
std::vector<std::string> pubShares(n);
std::vector<std::string> poly_names(n);
for (uint8_t i = 0; i < n; i++) {
EthKeys[i] = c.generateECDSAKey();
std::string polyName =
"POLY:SCHAIN_ID:1:NODE_ID:" + std::to_string(i) + ":DKG_ID:0";
cout << c.generateDKGPoly(polyName, t);
// poly_names[i] = polyName;
// VerifVects[i] = c.getVerificationVector(polyName, t, n);
// cout << "VV " << i << " " << VerifVects[i] << std::endl;
// pubEthKeys.append(EthKeys[i]["PublicKey"]);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment