Unverified Commit 6e7e4123 authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #71 from skalenetwork/bug/SKALE-2345-hw-fails

Bug/skale 2345 hw fails
parents fbec7209 1a324a2a
......@@ -47,6 +47,8 @@
#include "SGXWalletServer.h"
#include "BLSCrypto.h"
#include "BLSCrypto.hpp"
#include "ServerInit.h"
#include "RPCException.h"
......@@ -55,76 +57,75 @@
#include "common.h"
std::string *FqToString(libff::alt_bn128_Fq*_fq) {
std::string *FqToString(libff::alt_bn128_Fq *_fq) {
mpz_t t;
mpz_init(t);
mpz_t t;
mpz_init(t);
_fq->as_bigint().to_mpz(t);
_fq->as_bigint().to_mpz(t);
char arr[mpz_sizeinbase(t, 10) + 2];
char arr[mpz_sizeinbase(t, 10) + 2];
char *tmp = mpz_get_str(arr, 10, t);
mpz_clear(t);
char *tmp = mpz_get_str(arr, 10, t);
mpz_clear(t);
return new std::string(tmp);
return new std::string(tmp);
}
int char2int(char _input) {
if (_input >= '0' && _input <= '9')
return _input - '0';
if (_input >= 'A' && _input <= 'F')
return _input - 'A' + 10;
if (_input >= 'a' && _input <= 'f')
return _input - 'a' + 10;
return -1;
if (_input >= '0' && _input <= '9')
return _input - '0';
if (_input >= 'A' && _input <= 'F')
return _input - 'A' + 10;
if (_input >= 'a' && _input <= 'f')
return _input - 'a' + 10;
return -1;
}
void carray2Hex(const unsigned char *d, int _len, char *_hexArray) {
void carray2Hex(const unsigned char *d, int _len, char* _hexArray) {
char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (int j = 0; j < _len; j++) {
_hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)];
_hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F];
}
for (int j = 0; j < _len; j++) {
_hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)];
_hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F];
}
_hexArray[_len * 2] = 0;
_hexArray[_len * 2] = 0;
}
bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin ) {
bool hex2carray(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin) {
int len = strnlen(_hex, 2 * BUF_LEN);
int len = strnlen(_hex, 2 * BUF_LEN);
if (len == 0 && len % 2 == 1)
return false;
if (len == 0 && len % 2 == 1)
return false;
*_bin_len = len / 2;
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) {
int high = char2int((char) _hex[i * 2]);
int low = char2int((char) _hex[i * 2 + 1]);
for (int i = 0; i < len / 2; i++) {
int high = char2int((char)_hex[i * 2]);
int low = char2int((char)_hex[i * 2 + 1]);
if (high < 0 || low < 0) {
return false;
}
if (high < 0 || low < 0) {
return false;
_bin[i] = (unsigned char) (high * 16 + low);
}
_bin[i] = (unsigned char) (high * 16 + low);
}
return true;
return true;
}
bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length ) {
bool hex2carray2(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin, const int _max_length) {
int len = strnlen(_hex, _max_length);//2 * BUF_LEN);
......@@ -135,8 +136,8 @@ bool hex2carray2(const char * _hex, uint64_t *_bin_len,
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) {
int high = char2int((char)_hex[i * 2]);
int low = char2int((char)_hex[i * 2 + 1]);
int high = char2int((char) _hex[i * 2]);
int low = char2int((char) _hex[i * 2 + 1]);
if (high < 0 || low < 0) {
return false;
......@@ -149,62 +150,57 @@ 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) {
bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) {
//cerr << "ENTER SIGN" << endl;
//cerr << "ENTER SIGN" << endl;
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared<array<uint8_t, 32>>();
auto hash = make_shared<array<uint8_t, 32>>();
uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())){
throw RPCException(INVALID_HEX, "Invalid hash");
}
// assert(binLen == hash->size());
uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())) {
throw RPCException(INVALID_HEX, "Invalid hash");
}
auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
//cerr << "keyShare created" << endl;
// {
auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
// }
auto sigShareStr = sigShare->toString();
auto sigShareStr = sigShare->toString();
strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
//string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//strncpy(_sig, sigShareStr.c_str(), BUF_LEN);
//string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//strncpy(_sig, sigShareStr.c_str(), BUF_LEN);
// string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = make_shared<string>(test_sig);
// strncpy(_sig, sig_ptr->c_str(), BUF_LEN);
// string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = make_shared<string>(test_sig);
// strncpy(_sig, sig_ptr->c_str(), BUF_LEN);
//cerr<< "sig " << _sig <<endl;
//cerr<< "sig " << _sig <<endl;
return true;
return true;
}
bool sign_aes(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t _n, size_t _signerIndex,
char* _sig) {
bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) {
//cerr << "ENTER SIGN" << endl;
//cerr << "ENTER SIGN" << endl;
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared<array<uint8_t, 32>>();
auto hash = make_shared<array<uint8_t, 32>>();
uint64_t binLen;
uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())){
throw RPCException(INVALID_HEX, "Invalid hash");
}
// assert(binLen == hash->size());
if (!hex2carray(_hashHex, &binLen, hash->data())) {
throw RPCException(INVALID_HEX, "Invalid hash");
}
// assert(binLen == hash->size());
......@@ -218,103 +214,102 @@ bool sign_aes(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, siz
// auto sigShareStr = sigShare->toString();
//
// strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
shared_ptr<signatures::Bls> obj;
obj = make_shared<signatures::Bls>(signatures::Bls(_t, _n));
shared_ptr<signatures::Bls> obj;
obj = make_shared<signatures::Bls>(signatures::Bls(_t, _n));
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint =
obj->HashtoG1withHint(hash);
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint =
obj->HashtoG1withHint(hash);
int errStatus = 0;
int errStatus = 0;
string* xStr = FqToString(&(hash_with_hint.first.X));
string *xStr = FqToString(&(hash_with_hint.first.X));
if (xStr == nullptr) {
std::cerr << "Null xStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
if (xStr == nullptr) {
std::cerr << "Null xStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
string* yStr = FqToString(&(hash_with_hint.first.Y));
string *yStr = FqToString(&(hash_with_hint.first.Y));
if (yStr == nullptr) {
std::cerr << "Null yStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
}
if (yStr == nullptr) {
std::cerr << "Null yStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
}
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
char xStrArg[BUF_LEN];
char yStrArg[BUF_LEN];
char signature [BUF_LEN];
char xStrArg[BUF_LEN];
char yStrArg[BUF_LEN];
char signature[BUF_LEN];
memset(xStrArg, 0, BUF_LEN);
memset(yStrArg, 0, BUF_LEN);
memset(xStrArg, 0, BUF_LEN);
memset(yStrArg, 0, BUF_LEN);
strncpy(xStrArg, xStr->c_str(), BUF_LEN);
strncpy(yStrArg, yStr->c_str(), BUF_LEN);
strncpy(xStrArg, xStr->c_str(), BUF_LEN);
strncpy(yStrArg, yStr->c_str(), BUF_LEN);
size_t sz = 0;
size_t sz = 0;
uint8_t encryptedKey[BUF_LEN];
uint8_t encryptedKey[BUF_LEN];
bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey);
bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey);
if (!result) {
cerr << "Invalid hex encrypted key" << endl;
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
}
if (!result) {
cerr << "Invalid hex encrypted key" << endl;
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
}
sgx_status_t status =
bls_sign_message_aes(eid, &errStatus, errMsg, encryptedKey,
sz, xStrArg, yStrArg, signature);
sgx_status_t status =
bls_sign_message_aes(eid, &errStatus, errMsg, encryptedKey,
sz, xStrArg, yStrArg, signature);
if (status != SGX_SUCCESS) {
cerr <<"SGX enclave call to bls_sign_message failed:" << status << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to bls_sign_message failed"));
}
if (status != SGX_SUCCESS) {
cerr << "SGX enclave call to bls_sign_message failed:" << status << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to bls_sign_message failed"));
}
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second;
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second;
std::string sig = signature;
std::string sig = signature;
sig.append(":");
sig.append(hint);
sig.append(":");
sig.append(hint);
strncpy(_sig, sig.c_str(), BUF_LEN);
strncpy(_sig, sig.c_str(), BUF_LEN);
printf("_sig is: %s\n", sig.c_str());
printf("_sig is: %s\n", sig.c_str());
//string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//strncpy(_sig, sigShareStr.c_str(), BUF_LEN);
//string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//strncpy(_sig, sigShareStr.c_str(), BUF_LEN);
// string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = make_shared<string>(test_sig);
// strncpy(_sig, sig_ptr->c_str(), BUF_LEN);
// string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = make_shared<string>(test_sig);
// strncpy(_sig, sig_ptr->c_str(), BUF_LEN);
//cerr<< "sig " << _sig <<endl;
//cerr<< "sig " << _sig <<endl;
return true;
return true;
}
bool bls_sign(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t _n, size_t _signerIndex,
char* _sig) {
bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) {
if (!encryptKeys){
return sign(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
}
else{
return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
}
if (!encryptKeys) {
return sign(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
} else {
return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
}
}
char* encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {
shared_ptr<string> encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {
auto keyArray = make_shared<vector<char>>(BUF_LEN, 0);
auto encryptedKey = make_shared<vector<uint8_t>>(BUF_LEN, 0);
auto errMsg = make_shared<vector<char>>(BUF_LEN, 0);
......@@ -323,13 +318,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_aes(eid, errStatus, errMsg->data(), keyArray->data(), encryptedKey->data(), &encryptedLen);
if (printDebugInfo) {
spdlog::info("errStatus is {}",*errStatus);
spdlog::info(" errMsg is ", errMsg->data() );
}
spdlog::debug("errStatus is {}", *errStatus);
spdlog::debug(" errMsg is ", errMsg->data());
if (status != SGX_SUCCESS) {
......@@ -342,11 +336,11 @@ char* encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key)
}
char *result = (char *) calloc(2 * BUF_LEN, 1);
vector<char> result(2 * BUF_LEN, 0);
carray2Hex(encryptedKey->data(), encryptedLen, result);
carray2Hex(encryptedKey->data(), encryptedLen, result.data());
return result;
return make_shared<string>(result.data());
}
char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encryptedKey) {
......@@ -365,7 +359,7 @@ 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_aes(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
status = decrypt_key_aes(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
if (status != SGX_SUCCESS) {
return nullptr;
......
......@@ -30,12 +30,6 @@
#define EXTERNC
#endif
//EXTERNC void init_all();
//
//EXTERNC void init_daemon();
//
//EXTERNC void init_enclave();
EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t, size_t n,
size_t signerIndex, char* _sig);
......@@ -49,8 +43,4 @@ EXTERNC bool hex2carray2(const char * _hex, uint64_t *_bin_len,
char * encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key);
char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encryptedKey);
#endif //SGXWALLET_BLSCRYPTO_H
/*
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 BLSCrypto.hpp
@author Stan Kladko
@date 2019
*/
#ifndef SGXWALLET_BLSCRYPTO_HPP
#define SGXWALLET_BLSCRYPTO_HPP
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
using namespace std;
shared_ptr<string> encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key);
char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encryptedKey);
#endif //SGXWALLET_BLSCRYPTO_H
......@@ -80,10 +80,8 @@ BLSPrivateKeyShareSGX::BLSPrivateKeyShareSGX(
requiredSigners = _requiredSigners;
totalSigners = _totalSigners;
std::cerr << "ENTER BLSPrivateKeyShareSGX CONSTRUCTOR" << std::endl;
if (requiredSigners > totalSigners) {
throw std::invalid_argument("requiredSigners > totalSigners");
}
......
......@@ -36,75 +36,73 @@
#include "spdlog/spdlog.h"
#include "common.h"
vector<string> SplitString(const char* koefs, const char symbol){
string str(koefs);
string delim;
delim.push_back(symbol);
vector<string> G2_strings;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) {
string koef(token.c_str());
G2_strings.push_back(koef);
}
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return G2_strings;
#define DKG_MAX_SEALED_LEN 3100
vector<string> splitString(const char *koefs, const char symbol) {
string str(koefs);
string delim;
delim.push_back(symbol);
vector<string> G2_strings;
size_t prev = 0, pos = 0;
do {
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos - prev);
if (!token.empty()) {
string koef(token.c_str());
G2_strings.push_back(koef);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return G2_strings;
}
template<class T>
string ConvertToString(T field_elem, int base = 10) {
mpz_t t;
mpz_init(t);
mpz_t t;
mpz_init(t);
field_elem.as_bigint().to_mpz(t);
field_elem.as_bigint().to_mpz(t);
char arr[mpz_sizeinbase (t, base) + 2];
char arr[mpz_sizeinbase(t, base) + 2];
char * tmp = mpz_get_str(arr, base, t);
mpz_clear(t);
char *tmp = mpz_get_str(arr, base, t);
mpz_clear(t);
string output = tmp;
string output = tmp;
return output;
return output;
}
string gen_dkg_poly( int _t){
string gen_dkg_poly(int _t) {
vector<char> errMsg(1024, 0);
int err_status = 0;
vector<uint8_t> encrypted_dkg_secret(DKG_MAX_SEALED_LEN, 0);
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
uint32_t enc_len = 0;
if (!encryptKeys)
status = gen_dkg_secret (eid, &err_status, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
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.data() ) ;
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.data());
}
if (printDebugInfo) {
spdlog::info("gen_dkg_secret, status {}", err_status, " err msg ", errMsg.data());
spdlog::info("in DKGCrypto encr len is {}", enc_len);
}
spdlog::debug("gen_dkg_secret, status {}", err_status, " err msg ", errMsg.data());
spdlog::debug("in DKGCrypto encr len is {}", enc_len);
uint64_t length = DKG_MAX_SEALED_LEN;
if (encryptKeys){
length = enc_len;
if (encryptKeys) {
length = enc_len;
}
//vector<char> hexEncrPoly(DKG_MAX_SEALED_LEN * 2 + 1, 0);//(4*BUF_LEN, 1);
//vector<char> hexEncrPoly(DKG_MAX_SEALED_LEN * 2 + 1, 0);//(4*BUF_LEN, 1);
vector<char> hexEncrPoly(2 * length + 1, 0);
assert( encrypted_dkg_secret.size() >= length);
assert(encrypted_dkg_secret.size() >= length);
//carray2Hex(encrypted_dkg_secret.data(), DKG_MAX_SEALED_LEN, hexEncrPoly.data());
carray2Hex(encrypted_dkg_secret.data(), length, hexEncrPoly.data());
string result(hexEncrPoly.data());
......@@ -112,343 +110,289 @@ string gen_dkg_poly( int _t){
return result;
}
vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int n){
char* errMsg1 = (char*) calloc(1024,1);
//char errMsg1[BUF_LEN];
int err_status = 0;
if (printDebugInfo) {
// cerr << "got encr poly " << encryptedPolyHex << endl;
spdlog::info("got encr poly size {}", char_traits<char>::length(encryptedPolyHex));
}
char* public_shares = (char*)calloc(10000, 1);
memset(public_shares, 0, 10000);
// char public_shares[10000];
uint64_t enc_len = 0;
uint8_t* encr_dkg_poly = (uint8_t*) calloc(DKG_MAX_SEALED_LEN * 2, 1);
memset(encr_dkg_poly, 0, DKG_MAX_SEALED_LEN * 2);
//uint8_t encr_dkg_poly[DKG_MAX_SEALED_LEN];
if (!hex2carray2(encryptedPolyHex, &enc_len, encr_dkg_poly, 6100)){
throw RPCException(INVALID_HEX, "Invalid encryptedPolyHex");
}
if (printDebugInfo) {
//cerr << "hex_encr_poly is " << encryptedPolyHex << std::endl;
spdlog::info("hex_encr_poly length is {}", strlen(encryptedPolyHex));
spdlog::info("enc len {}", enc_len);
// cerr << "encr raw poly: " << endl;
// for ( int i = 0 ; i < 3050; i++)
// printf(" %d ", encr_dkg_poly[i] );
}
uint32_t len = 0;
if (!encryptKeys)
status = get_public_shares(eid, &err_status, errMsg1, encr_dkg_poly, len, public_shares, t, n);
else {
status = get_public_shares_aes(eid, &err_status, errMsg1, encr_dkg_poly, enc_len, public_shares, t, n);
}
if ( err_status != 0){
throw RPCException(-666, errMsg1 );
}
if (printDebugInfo) {
spdlog::info("err msg is {}", errMsg1);
spdlog::info("public_shares:");
spdlog::info("{}", public_shares);
// 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);
}
vector <string> G2_strings = SplitString( public_shares, ',');
vector <vector <string>> pub_shares_vect;
for ( uint64_t i = 0; i < G2_strings.size(); i++){
vector <string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
pub_shares_vect.push_back(koef_str);
}
free(errMsg1);
free(public_shares);
free(encr_dkg_poly);
return pub_shares_vect;
}
vector<vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n) {
vector<char> errMsg1(BUF_LEN, 0);
int errStatus = 0;
spdlog::debug("got encr poly size {}", char_traits<char>::length(encryptedPolyHex));
vector<char> pubShares(10000, 0);
string get_secret_shares(const string& polyName, const char* encryptedPolyHex, const vector<string>& publicKeys, int t, int n){
//char* errMsg1 = (char*) calloc(1024,1);
char errMsg1[BUF_LEN];
int err_status = 0;
char hexEncrKey[BUF_LEN];
memset(hexEncrKey, 0, BUF_LEN);
uint64_t enc_len = 0;
// uint8_t* encr_dkg_poly = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
uint8_t encr_dkg_poly[DKG_MAX_SEALED_LEN];
memset(encr_dkg_poly, 0, DKG_MAX_SEALED_LEN);
if(!hex2carray2(encryptedPolyHex, &enc_len, encr_dkg_poly, 6100)){
throw RPCException(INVALID_HEX, "Invalid encryptedPolyHex");
}
std::cerr << "enc_len is " << enc_len << std::endl;
if (!encryptKeys)
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 );
}
string result;
//char *hexEncrKey = (char *) calloc(2 * BUF_LEN, 1);
for ( int i = 0; i < n; i++){
uint8_t encrypted_skey[BUF_LEN];
memset(encrypted_skey, 0, BUF_LEN);
uint32_t dec_len;
char cur_share[193];
char s_shareG2[320];
string pub_keyB = publicKeys.at(i);//publicKeys.substr(128*i, 128*i + 128);
// if (DEBUG_PRINT) {
// spdlog::info("pub_keyB is {}", pub_keyB);
// }
char pubKeyB[129];
strncpy(pubKeyB, pub_keyB.c_str(), 128);
pubKeyB[128] = 0;
if (printDebugInfo) {
spdlog::info("pubKeyB is {}", pub_keyB);
uint64_t encLen = 0;
vector<uint8_t> encrDKGPoly(2 * BUF_LEN, 0);
if (!hex2carray2(encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) {
throw RPCException(INVALID_HEX, "Invalid encryptedPolyHex");
}
spdlog::debug("hex_encr_poly length is {}", strlen(encryptedPolyHex));
spdlog::debug("enc len {}", encLen);
uint32_t len = 0;
if (!encryptKeys)
get_encr_sshare(eid, &err_status, errMsg1, encrypted_skey, &dec_len,
cur_share, s_shareG2, pubKeyB, t, n, i + 1 );
else
get_encr_sshare_aes(eid, &err_status, errMsg1, encrypted_skey, &dec_len,
cur_share, s_shareG2, pubKeyB, t, n, i + 1 );
if (err_status != 0){
throw RPCException(-666, errMsg1);
status = get_public_shares(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), len, pubShares.data(), t, n);
else {
status = get_public_shares_aes(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen, pubShares.data(), t, n);
}
if (printDebugInfo) {
spdlog::info("cur_share is {}", cur_share);
if (errStatus != 0) {
throw RPCException(-666, errMsg1.data());
}
result += cur_share;
//uint32_t enc_len = BUF_LEN;
if (printDebugInfo) {
spdlog::info("dec len is {}", dec_len);
spdlog::debug("err msg is {}", errMsg1.data());
spdlog::debug("public_shares:");
spdlog::debug("{}", pubShares.data());;
spdlog::debug("get_public_shares status: {}", errStatus);
vector<string> g2Strings = splitString(pubShares.data(), ',');
vector<vector<string>> pubSharesVect;
for (uint64_t i = 0; i < g2Strings.size(); i++) {
vector<string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
pubSharesVect.push_back(coeffStr);
}
return pubSharesVect;
}
carray2Hex(encrypted_skey, dec_len, hexEncrKey);
string get_secret_shares(const string &_polyName, const char *_encryptedPolyHex, const vector<string> &_publicKeys, int _t,
int _n) {
vector<char> errMsg1(BUF_LEN, 0);
vector<char> hexEncrKey(BUF_LEN, 0);
int errStatus = 0;
uint64_t encLen = 0;
string DHKey_name = "DKG_DH_KEY_" + polyName + "_" + to_string(i) + ":";
cerr << "hexEncr DH Key: " << hexEncrKey << endl;
SGXWalletServer::writeDataToDB(DHKey_name, hexEncrKey);
vector<uint8_t > encrDKGPoly(BUF_LEN, 0);
string shareG2_name = "shareG2_" + polyName + "_" + to_string(i) + ":";
if (printDebugInfo) {
spdlog::info("name to write to db is {}", DHKey_name);
spdlog::info("name to write to db is {}", shareG2_name);
spdlog::info("s_shareG2: {}", s_shareG2);
if (!hex2carray2(_encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) {
throw RPCException(INVALID_HEX, "Invalid encryptedPolyHex");
}
SGXWalletServer::writeDataToDB(shareG2_name, s_shareG2);
if (printDebugInfo) {
spdlog::info("errMsg: {}", errMsg1);
// 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;
if (!encryptKeys)
status = set_encrypted_dkg_poly(eid, &errStatus, errMsg1.data(), encrDKGPoly.data());
else
status = set_encrypted_dkg_poly_aes(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), &encLen);
if (status != SGX_SUCCESS || errStatus != 0) {
throw RPCException(-666, errMsg1.data());
}
}
//result += '\0';
//free(encr_dkg_poly);
// free(errMsg1);
//free(hexEncrKey);
string result;
for (int i = 0; i < _n; i++) {
vector<uint8_t > encryptedSkey(BUF_LEN, 0);
uint32_t decLen;
vector<char> currentShare(193, 0);
vector<char> sShareG2(320, 0);
string pub_keyB = _publicKeys.at(i);
vector<char> pubKeyB(129,0);
strncpy(pubKeyB.data(), pub_keyB.c_str(), 128);
pubKeyB.at(128) = 0;
spdlog::debug("pubKeyB is {}", pub_keyB);
if (!encryptKeys)
get_encr_sshare(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1);
else
get_encr_sshare_aes(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1);
if (errStatus != 0) {
throw RPCException(-666, errMsg1.data());
}
spdlog::debug("cur_share is {}", currentShare.data());
result += string(currentShare.data());
spdlog::debug("dec len is {}", decLen);
carray2Hex(encryptedSkey.data(), decLen, hexEncrKey.data());
string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":";
spdlog::debug("hexEncr DH Key: { }", hexEncrKey.data());
SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data());
string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
spdlog::debug("name to write to db is {}", dhKeyName);
spdlog::debug("name to write to db is {}", shareG2_name);
spdlog::debug("s_shareG2: {}", sShareG2.data());
return result;
SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data());
spdlog::debug("errMsg: {}", errMsg1.data());
}
return result;
}
bool VerifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind ){
bool
verifyShares(const char *publicShares, const char *encr_sshare, const char *encryptedKeyHex, int t, int n, int ind) {
//char* errMsg1 = (char*) calloc(1024,1);
char errMsg1[BUF_LEN];
int err_status = 0;
uint64_t dec_key_len ;
uint64_t dec_key_len;
uint8_t encr_key[BUF_LEN];
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)){
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)) {
throw RPCException(INVALID_HEX, "Invalid encryptedPolyHex");
}
int result;
if (printDebugInfo) {
cerr << "encryptedKeyHex " << encryptedKeyHex << endl;
cerr << "dec_key_len " << dec_key_len << endl;
cerr << "encr_sshare length is " << strlen(encr_sshare) << endl;
//cerr << "public shares " << publicShares << endl;
spdlog::info("publicShares length is {}", char_traits<char>::length(publicShares));
}
spdlog::debug("publicShares length is {}", char_traits<char>::length(publicShares));
char pshares[8193];
memset(pshares, 0, 8193);
strncpy(pshares, publicShares, strlen(publicShares) );
strncpy(pshares, publicShares, strlen(publicShares));
if (!encryptKeys)
dkg_verification(eid, &err_status, errMsg1, pshares, encr_sshare, encr_key, dec_key_len, t, ind, &result);
dkg_verification(eid, &err_status, errMsg1, pshares, encr_sshare, encr_key, dec_key_len, t, ind, &result);
else
dkg_verification_aes(eid, &err_status, errMsg1, pshares, encr_sshare, encr_key, dec_key_len, t, ind, &result);
dkg_verification_aes(eid, &err_status, errMsg1, pshares, encr_sshare, encr_key, dec_key_len, t, ind, &result);
if (result == 2){
throw RPCException(INVALID_HEX, "Invalid public shares");
if (result == 2) {
throw RPCException(INVALID_HEX, "Invalid public shares");
}
if (printDebugInfo) {
spdlog::info("errMsg1: {}", errMsg1);
spdlog::info("result is: {}", result);
}
spdlog::debug("errMsg1: {}", errMsg1);
spdlog::debug("result is: {}", result);
//free(errMsg1);
return result;
}
bool CreateBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex){
if (printDebugInfo) {
spdlog::info("ENTER CreateBLSShare");
}
// char* errMsg1 = (char*) calloc(1024,1);
char errMsg1[BUF_LEN];
int err_status = 0;
uint64_t dec_key_len ;
uint8_t encr_bls_key[BUF_LEN];
memset(encr_bls_key, 0, BUF_LEN);
uint8_t encr_key[BUF_LEN];
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)){
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
uint32_t enc_bls_len = 0;
//cerr << "BEFORE create_bls_key IN ENCLAVE " << endl;
if (!encryptKeys)
create_bls_key(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key, &enc_bls_len);
else
create_bls_key_aes(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key, &enc_bls_len);
//cerr << "AFTER create_bls_key IN ENCLAVE er msg is " << errMsg1 << endl;
if ( err_status != 0){
//spdlog::info("ERROR IN ENCLAVE with status {}", err_status);
spdlog::error(errMsg1);
spdlog::error("status {}", err_status);
throw RPCException(ERROR_IN_ENCLAVE, "Create BLS private key failed in enclave");
}
else {
//char *hexBLSKey = (char *) calloc(2 * BUF_LEN, 1);
char hexBLSKey[2 * BUF_LEN];
//cerr << "BEFORE carray2Hex" << endl;
//cerr << "enc_bls_len " << enc_bls_len << endl;
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey);
// cerr << "BEFORE WRITE BLS KEY TO DB" << endl;
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey);
if (printDebugInfo) {
spdlog::info("hexBLSKey length is {}", char_traits<char>::length(hexBLSKey));
spdlog::info("bls key {}", blsKeyName, " is ", hexBLSKey );
bool CreateBLSShare(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) {
spdlog::debug("ENTER CreateBLSShare");
// char* errMsg1 = (char*) calloc(1024,1);
char errMsg1[BUF_LEN];
int err_status = 0;
uint64_t dec_key_len;
uint8_t encr_bls_key[BUF_LEN];
memset(encr_bls_key, 0, BUF_LEN);
uint8_t encr_key[BUF_LEN];
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)) {
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
uint32_t enc_bls_len = 0;
if (!encryptKeys)
create_bls_key(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key, &enc_bls_len);
else
create_bls_key_aes(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key, &enc_bls_len);
if (err_status != 0) {
spdlog::error(errMsg1);
spdlog::error("status {}", err_status);
throw RPCException(ERROR_IN_ENCLAVE, "Create BLS private key failed in enclave");
} else {
char hexBLSKey[2 * BUF_LEN];
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey);
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey);
return true;
}
//free(hexBLSKey);
return true;
}
}
vector<string> GetBLSPubKey(const char * encryptedKeyHex){
vector<string> GetBLSPubKey(const char *encryptedKeyHex) {
//char* errMsg1 = (char*) calloc(1024,1);
char errMsg1[BUF_LEN];
int err_status = 0;
uint64_t dec_key_len ;
uint64_t dec_key_len;
uint8_t encr_key[BUF_LEN];
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)){
if (!hex2carray(encryptedKeyHex, &dec_key_len, encr_key)) {
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
char pub_key[320];
if (printDebugInfo) {
spdlog::info("dec_key_len is {}", dec_key_len);
}
spdlog::debug("dec_key_len is {}", dec_key_len);
if (!encryptKeys)
get_bls_pub_key(eid, &err_status, errMsg1, encr_key, dec_key_len, pub_key);
get_bls_pub_key(eid, &err_status, errMsg1, encr_key, dec_key_len, pub_key);
else
get_bls_pub_key_aes(eid, &err_status, errMsg1, encr_key, dec_key_len, pub_key);
if ( err_status != 0){
std::cerr << errMsg1 << " status is " << err_status << std::endl;
throw RPCException(ERROR_IN_ENCLAVE, "Failed to get BLS public key in enclave");
get_bls_pub_key_aes(eid, &err_status, errMsg1, encr_key, dec_key_len, pub_key);
if (err_status != 0) {
spdlog::error(string(errMsg1) + " . Status is {}", err_status);
throw RPCException(ERROR_IN_ENCLAVE, "Failed to get BLS public key in enclave");
}
vector<string> pub_key_vect = SplitString(pub_key, ':');
vector<string> pub_key_vect = splitString(pub_key, ':');
spdlog::debug("errMsg1 is {}", errMsg1);
spdlog::debug("pub key is ");
for (int i = 0; i < 4; i++)
spdlog::debug("{}", pub_key_vect.at(i));
if (printDebugInfo) {
spdlog::info("errMsg1 is {}", errMsg1);
spdlog::info("pub key is ");
for (int i = 0; i < 4; i++)
spdlog::info("{}", pub_key_vect.at(i));
}
return pub_key_vect;
}
string decrypt_DHKey(const string& polyName, int ind){
string decrypt_DHKey(const string &polyName, int ind) {
vector<char> errMsg1(1024, 0);
int err_status = 0;
string DH_key_name = polyName + "_" + to_string(ind) + ":";
shared_ptr<string> hexEncrKey_ptr = SGXWalletServer::readFromDb(DH_key_name, "DKG_DH_KEY_");
vector<char> errMsg1(1024,0);
int err_status = 0;
spdlog::debug("encr DH key is {}", *hexEncrKey_ptr);
string DH_key_name = polyName + "_" + to_string(ind) + ":";
shared_ptr<string> hexEncrKey_ptr = SGXWalletServer::readFromDb(DH_key_name, "DKG_DH_KEY_");
if (printDebugInfo) {
spdlog::info("encr DH key is {}", *hexEncrKey_ptr);
}
vector<char> hexEncrKey(2 * BUF_LEN, 0);
vector<char> hexEncrKey(2 * BUF_LEN, 0);
uint64_t DH_enc_len = 0;
uint8_t encrypted_DHkey[BUF_LEN];
if (!hex2carray(hexEncrKey_ptr->c_str(), &DH_enc_len, encrypted_DHkey)) {
throw RPCException(INVALID_HEX, "Invalid hexEncrKey");
}
spdlog::debug("encr DH key length is {}", DH_enc_len);
spdlog::debug("hex encr DH key length is {}", hexEncrKey_ptr->length());
uint64_t DH_enc_len = 0;
uint8_t encrypted_DHkey[BUF_LEN];
if (!hex2carray(hexEncrKey_ptr->c_str(), &DH_enc_len, encrypted_DHkey)){
throw RPCException(INVALID_HEX, "Invalid hexEncrKey");
}
if (printDebugInfo) {
spdlog::info("encr DH key length is {}", DH_enc_len);
spdlog::info("hex encr DH key length is {}", hexEncrKey_ptr->length());
}
char DHKey[ECDSA_SKEY_LEN];
char DHKey[ECDSA_SKEY_LEN];
if ( !encryptKeys)
decrypt_key(eid, &err_status, errMsg1.data(), encrypted_DHkey, DH_enc_len, DHKey);
else
decrypt_key_aes(eid, &err_status, errMsg1.data(), encrypted_DHkey, DH_enc_len, DHKey);
if (err_status != 0){
throw RPCException(/*ERROR_IN_ENCLAVE*/ err_status, "decrypt key failed in enclave");
}
if (!encryptKeys)
decrypt_key(eid, &err_status, errMsg1.data(), encrypted_DHkey, DH_enc_len, DHKey);
else
decrypt_key_aes(eid, &err_status, errMsg1.data(), encrypted_DHkey, DH_enc_len, DHKey);
if (err_status != 0) {
throw RPCException(/*ERROR_IN_ENCLAVE*/ err_status, "decrypt key failed in enclave");
}
return DHKey;
return DHKey;
}
vector<string> mult_G2(const string& x){
vector<string> mult_G2(const string &x) {
vector<string> result(4);
libff::init_alt_bn128_params();
libff::alt_bn128_Fr el(x.c_str());
......
......@@ -31,11 +31,11 @@ std::string gen_dkg_poly( int _t);
std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyHex, int t, int n);
std::vector<std::string> SplitString(const char* koefs, const char symbol);
std::vector<std::string> splitString(const char* koefs, const char symbol);
std::string get_secret_shares(const std::string& polyName, const char* encryptedPolyHex, const std::vector<std::string>& publicKeys, int t, int n);
std::string get_secret_shares(const std::string& _polyName, const char* _encryptedPolyHex, const std::vector<std::string>& _publicKeys, int _t, int _n);
bool VerifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
bool verifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
std::string decrypt_DHKey(const std::string& polyName, int ind);
......
......@@ -34,169 +34,158 @@
#include "spdlog/spdlog.h"
static std::default_random_engine rand_gen((unsigned int) time(0));
static default_random_engine randGen((unsigned int) time(0));
std::string concatPubKeyWith0x(char* pub_key_x, char* pub_key_y){
std::string px = pub_key_x;
std::string py = pub_key_y;
std::string result = "0x" + px + py;// + std::to_string(pub_key_x) + std::to_string(pub_key_y);
return result;
string concatPubKeyWith0x(char *pub_key_x, char *pub_key_y) {
string px = pub_key_x;
string py = pub_key_y;
string result = "0x" + px + py;
return result;
}
std::vector<std::string> gen_ecdsa_key(){
char *errMsg = (char *)calloc(1024, 1);
int err_status = 0;
uint8_t* encr_pr_key = (uint8_t *)calloc(1024, 1);
char *pub_key_x = (char *)calloc(1024, 1);
char *pub_key_y = (char *)calloc(1024, 1);
uint32_t enc_len = 0;
if ( !encryptKeys)
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 ( status != SGX_SUCCESS || err_status != 0 ){
std::cerr << "RPCException thrown with status" << status << std::endl;
throw RPCException(status, errMsg) ;
}
std::vector<std::string> keys(3);
if (printDebugInfo) {
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);//
//std::cerr << "in ECDSACrypto encr key x " << keys.at(0) << std::endl;
//std::cerr << "in ECDSACrypto encr_len %d " << enc_len << std::endl;
unsigned long seed = rand_gen();
if (printDebugInfo) {
spdlog::info("seed is {}", seed);
std::cerr << "strlen is " << strlen(hexEncrKey) << std::endl;
}
gmp_randstate_t state;
gmp_randinit_default(state);
gmp_randseed_ui(state, seed);
mpz_t rand32;
mpz_init(rand32);
mpz_urandomb(rand32, state, 256);
char arr[mpz_sizeinbase (rand32, 16) + 2];
char * rand_str = mpz_get_str(arr, 16, rand32);
keys.at(2) = rand_str;
//std::cerr << "rand_str length is " << strlen(rand_str) << std::endl;
gmp_randclear(state);
mpz_clear(rand32);
free(errMsg);
free(pub_key_x);
free(pub_key_y);
free(encr_pr_key);
free(hexEncrKey);
return keys;
std::vector<std::string> genECDSAKey() {
char *errMsg = (char *) calloc(1024, 1);
int err_status = 0;
uint8_t *encr_pr_key = (uint8_t *) calloc(1024, 1);
char *pub_key_x = (char *) calloc(1024, 1);
char *pub_key_y = (char *) calloc(1024, 1);
uint32_t enc_len = 0;
if (!encryptKeys)
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 (status != SGX_SUCCESS || err_status != 0) {
spdlog::error("RPCException thrown with status {}", status);
throw RPCException(status, errMsg);
}
std::vector<std::string> keys(3);
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);//
unsigned long seed = randGen();
spdlog::debug("seed is {}", seed);
gmp_randstate_t state;
gmp_randinit_default(state);
gmp_randseed_ui(state, seed);
mpz_t rand32;
mpz_init(rand32);
mpz_urandomb(rand32, state, 256);
char arr[mpz_sizeinbase(rand32, 16) + 2];
char *rand_str = mpz_get_str(arr, 16, rand32);
keys.at(2) = rand_str;
gmp_randclear(state);
mpz_clear(rand32);
free(errMsg);
free(pub_key_x);
free(pub_key_y);
free(encr_pr_key);
free(hexEncrKey);
return keys;
}
std::string get_ecdsa_pubkey(const char* encryptedKeyHex){
char *errMsg = (char *)calloc(1024, 1);
int err_status = 0;
char *pub_key_x = (char *)calloc(1024, 1);
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 = (uint8_t*)calloc(1024, 1);
if (!hex2carray(encryptedKeyHex, &enc_len, encr_pr_key)){
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
if ( !encryptKeys)
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 (printDebugInfo) {
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;
std::string getECDSAPubKey(const char *_encryptedKeyHex) {
vector<char> errMsg(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0);
vector<uint8_t> encrPrKey(BUF_LEN, 0);
int err_status = 0;
uint64_t enc_len = 0;
if (!hex2carray(_encryptedKeyHex, &enc_len, encrPrKey.data())) {
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
if (!encryptKeys)
status = get_public_ecdsa_key(eid, &err_status, errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(),
pubKeyY.data());
else status = get_public_ecdsa_key_aes(eid, &err_status,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
if (err_status != 0) {
throw RPCException(-666, errMsg.data());
}
string pubKey = string(pubKeyX.data()) + string(pubKeyY.data());//concatPubKeyWith0x(pub_key_x, pub_key_y);//
spdlog::debug("enc_len is {}", enc_len);
spdlog::debug("pubkey is {}", pubKey);
spdlog::debug("pubkey length is {}", pubKey.length());
spdlog::debug("err str is {}", errMsg.data());
spdlog::debug("err status is {}", err_status);
return pubKey;
}
std::vector<std::string> ecdsa_sign_hash(const char* encryptedKeyHex, const char* hashHex, int base){
std::vector<std::string> signature_vect(3);
char *errMsg = (char *)calloc(1024, 1);
int err_status = 0;
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 = (uint8_t*)calloc(1024, 1);
if (!hex2carray(encryptedKeyHex, &dec_len, encr_key)){
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
if (printDebugInfo) {
spdlog::info("encryptedKeyHex: {}", encryptedKeyHex);
spdlog::info("HASH: {}", hashHex);
spdlog::info("encrypted len: {}", dec_len);
}
if (!encryptKeys)
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 ) ;
}
if (printDebugInfo) {
spdlog::info("signature r in ecdsa_sign_hash: {}", signature_r);
spdlog::info("signature s in ecdsa_sign_hash: {}", signature_s);
}
if ( status != SGX_SUCCESS){
spdlog::info(" failed to sign ");
}
signature_vect.at(0) = std::to_string(signature_v);
if ( base == 16) {
signature_vect.at(1) = "0x" + std::string(signature_r);
signature_vect.at(2) = "0x" + std::string(signature_s);
}
else{
signature_vect.at(1) = std::string(signature_r);
signature_vect.at(2) = std::string(signature_s);
}
free(errMsg);
free(signature_r);
free(signature_s);
free(encr_key);
return signature_vect;
vector<string> ecdsaSignHash(const char *encryptedKeyHex, const char *hashHex, int base) {
vector<string> signature_vect(3);
char *errMsg = (char *) calloc(1024, 1);
int err_status = 0;
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 = (uint8_t *) calloc(1024, 1);
if (!hex2carray(encryptedKeyHex, &dec_len, encr_key)) {
throw RPCException(INVALID_HEX, "Invalid encryptedKeyHex");
}
spdlog::debug("encryptedKeyHex: {}", encryptedKeyHex);
spdlog::debug("HASH: {}", hashHex);
spdlog::debug("encrypted len: {}", dec_len);
if (!encryptKeys)
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);
}
spdlog::debug("signature r in ecdsa_sign_hash: {}", signature_r);
spdlog::debug("signature s in ecdsa_sign_hash: {}", signature_s);
if (status != SGX_SUCCESS) {
spdlog::error(" failed to sign ");
}
signature_vect.at(0) = to_string(signature_v);
if (base == 16) {
signature_vect.at(1) = "0x" + string(signature_r);
signature_vect.at(2) = "0x" + string(signature_s);
} else {
signature_vect.at(1) = string(signature_r);
signature_vect.at(2) = string(signature_s);
}
free(errMsg);
free(signature_r);
free(signature_s);
free(encr_key);
return signature_vect;
}
\ No newline at end of file
......@@ -35,11 +35,13 @@
#define EXTERNC
#endif*/
std::vector<std::string> gen_ecdsa_key();
using namespace std;
std::string get_ecdsa_pubkey(const char* encryptedKeyHex);
vector<string> genECDSAKey();
std::vector<std::string> ecdsa_sign_hash(const char* encryptedKeyHex, const char* hashHex, int base);
string getECDSAPubKey(const char* _encryptedKeyHex);
vector<string> ecdsaSignHash(const char* encryptedKeyHex, const char* hashHex, int base);
#endif //SGXD_ECDSACRYPTO_H
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file Exception.cpp
@author Stan Kladko
@date 2018
*/
#include "Log.h"
#include "Exception.h"
void Exception::logNested(const std::exception &e, int level)
{
string prefix;
if (level == 0) {
prefix = "!Exception:";
} else {
prefix = "!Caused by:";
}
if (dynamic_cast<const std::nested_exception*>(&e) == nullptr) {
LOG(err, string(level, ' ') + prefix + e.what());
return;
} else {
LOG(err, string(level, ' ') + prefix + e.what());
}
try {
std::rethrow_if_nested(e);
} catch(const std::exception& e) {
logNested(e, level + 1);
} catch(...) {}
};
\ No newline at end of file
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file Exception.h
@author Stan Kladko
@date 2018
*/
#pragma once
class Exception : public std::exception {
public:
Exception( const std::string& _message, const std::string& _className ) {
message = _className + ":" + _message;
}
const char* what() const noexcept override {
return message.empty() ? std::exception::what() : message.c_str();
}
const std::string& getMessage() const { return message; }
bool isFatal() const { return fatal; }
private:
std::string message;
protected:
bool fatal = false;
public:
static void logNested( const std::exception& e, int level = 0 );
};
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file InvalidArgumentException.cpp
@author Stan Kladko
@date 2018
*/
#include "Log.h"
#include "InvalidArgumentException.h"
InvalidArgumentException::InvalidArgumentException(const std::string &_message, const string& _className) :
Exception(_message, _className) {
fatal = false;
}
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file InvalidArgumentException.h
@author Stan Kladko
@date 2018
*/
#pragma once
#include "Exception.h"
#include <string>
class InvalidArgumentException : public Exception {
public:
InvalidArgumentException( const std::string& _message, const std::string& _className );
};
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file InvalidStateException.cpp
@author Stan Kladko
@date 2018
*/
#include "common.h"
#include "Log.h"
#include "InvalidStateException.h"
InvalidStateException::InvalidStateException(const std::string &_message, const string& _className) :
Exception(_message, _className) {
fatal = false;
}
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file InvalidStateException.h
@author Stan Kladko
@date 2018
*/
#pragma once
#include "Exception.h"
class InvalidStateException : public Exception {
public:
InvalidStateException( const std::string& _message, const std::string& _className );
};
......@@ -62,10 +62,10 @@ std::shared_ptr<string> LevelDB::readString(const string &_key) {
auto status = db->Get(readOptions, _key, &*result);
if (printDebugInfo) {
spdlog::info("key to read from db: {}",_key );
spdlog::debug("key to read from db: {}",_key );
//std::cerr << "key to read from db: " << _key << std::endl;
}
throwExceptionOnError(status);
......@@ -83,10 +83,10 @@ void LevelDB::writeString(const string &_key, const string &_value) {
throwExceptionOnError(status);
if (printDebugInfo) {
spdlog::info("written key: {}",_key );
spdlog::debug("written key: {}",_key );
// std::cerr << "written key " << _key << std::endl;
}
}
......@@ -100,10 +100,9 @@ void LevelDB::deleteDHDKGKey (const string &_key) {
throwExceptionOnError(status);
if (printDebugInfo) {
spdlog::info("key deleted: {}",full_key );
spdlog::debug("key deleted: {}",full_key );
//std::cerr << "key deleted " << full_key << std::endl;
}
}
void LevelDB::deleteTempNEK(const string &_key){
......@@ -130,10 +129,9 @@ void LevelDB::deleteKey(const string &_key){
throwExceptionOnError(status);
if (printDebugInfo) {
spdlog::info("key deleted: {}",_key );
spdlog::debug("key deleted: {}",_key );
// std::cerr << "key deleted " << _key << std::endl;
}
}
......@@ -213,16 +211,15 @@ void LevelDB::writeDataUnique(const string & Name, const string &value) {
auto key = Name;
if (readString(Name) != nullptr) {
spdlog::info("name {}",Name, " already exists");
spdlog::debug("name {}",Name, " already exists");
// std::cerr << "name " << Name << " already exists" << std::endl;
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
}
writeString(key, value);
if (printDebugInfo) {
spdlog::info("{}",Name, " is written to db");
//std::cerr << Name << " is written to db " << std::endl;
}
spdlog::debug("{}",Name, " is written to db");
}
......@@ -273,12 +270,17 @@ bool LevelDB::isInited = false;
void LevelDB::initDataFolderAndDBs() {
if (isInited)
return;
CHECK_STATE(!isInited)
isInited = true;
spdlog::info("Initing wallet database ... ");
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
spdlog::error("could not get cwd");
spdlog::error("could not get current workin directory");
exit(-1);
}
......@@ -286,17 +288,20 @@ void LevelDB::initDataFolderAndDBs() {
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");
spdlog::info("sgx_data folder does not exist. Creating ...");
if (system(("mkdir " + sgx_data_folder).c_str()) == 0){
spdlog::info("Successfully created sgx_data folder");
}
else{
spdlog::error("creating sgx_data folder failed");
spdlog::error("Couldnt create creating sgx_data folder");
exit(-1);
}
}
spdlog::info("Opening wallet databases");
auto dbName = sgx_data_folder + WALLETDB_NAME;
levelDb = make_shared<LevelDB>(dbName);
......@@ -306,6 +311,8 @@ void LevelDB::initDataFolderAndDBs() {
auto csr_status_dbname = sgx_data_folder + "CSR_STATUS_DB";
csrStatusDb = make_shared<LevelDB>(csr_status_dbname);
spdlog::info("Successfully opened databases");
}
const string &LevelDB::getSgxDataFolder() {
......
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file Log.cpp
@author Stan Kladko
@date 2018
*/
#include "spdlog/spdlog.h"
#include "sgxwallet_common.h"
#include "common.h"
#include "Log.h"
using namespace std;
void Log::setGlobalLogLevel(string &_s) {
globalLogLevel = logLevelFromString(_s);
}
level_enum Log::logLevelFromString(string &_s) {
level_enum result = trace;
if (_s == "trace")
result = trace;
else if (_s == "debug")
result = debug;
else if (_s == "info")
result = info;
else if (_s == "warn")
result = warn;
else if (_s == "err")
result = err;
else
throw InvalidArgumentException("Unknown level name " + _s, __CLASS_NAME__);
return result;
}
/*
Copyright (C) 2018-2019 SKALE Labs
This file is part of skale-consensus.
skale-consensus 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.
skale-consensus 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 skale-consensus. If not, see <https://www.gnu.org/licenses/>.
@file Log.h
@author Stan Kladko
@date 2018
*/
#ifndef _LOG_H
#define _LOG_H
#include <stdlib.h>
#include <iostream>
#include <map>
#include <memory>
#include "InvalidArgumentException.h"
#include "InvalidStateException.h"
#include "common.h"
using namespace std;
class Exception;
#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ )
#define LOG( __SEVERITY__, __MESSAGE__ ) \
cerr << to_string(__SEVERITY__) << " " << __MESSAGE__ << " " << className( __PRETTY_FUNCTION__ ) << endl;
enum level_enum { trace, debug, info, warn, err };
class Log {
public:
level_enum globalLogLevel;
void setGlobalLogLevel( string& _s );
static level_enum logLevelFromString(string &_s);
};
#endif
......@@ -66,11 +66,13 @@ bin_PROGRAMS = sgxwallet testw cert_util
## You can't use $(wildcard ...) with automake so all source files
## have to be explicitly listed.
COMMON_SRC = sgx_stub.c sgx_detect_linux.c create_enclave.c oc_alloc.c
COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \
SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp RPCException.cpp BLSCrypto.cpp ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp SEKManager.cpp \
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 SEKManager.cpp $(COMMON_SRC)
sgxwallet_SOURCES = sgxwallet.c $(COMMON_SRC)
nodist_sgxwallet_SOURCES = $(COMMON_ENCLAVE_SRC)
......@@ -104,13 +106,12 @@ sgxwallet_LDADD=-l$(SGX_URTS_LIB) -l$(SGX_UAE_SERVICE_LIB) -LlibBLS/deps/deps_in
-lgnutls -lgcrypt -lcurl -lssl -lcrypto -lz -lpthread
testw_SOURCES=testw.cpp stubclient.cpp SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ServerInit.cpp LevelDB.cpp \
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp ServerDataChecker.cpp SEKManager.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp $(COMMON_SRC)
testw_SOURCES=testw.cpp $(COMMON_SRC)
nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
cert_util_SOURCES=cert_util.cpp stubclient.cpp RPCException.cpp LevelDB.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp
cert_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp cert_util.cpp stubclient.cpp RPCException.cpp LevelDB.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp
cert_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \
-LlibBLS/build/libff/libff \
-l:libbls.a -l:libleveldb.a \
......
......@@ -227,12 +227,10 @@ void enter_SEK(){
void init_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. Going to create SEK");
spdlog::error("SEK was not created yet. Going to create SEK");
gen_SEK();
}
else{
if (printDebugInfo)
spdlog::info("going to set SEK from db" );
set_SEK(encr_SEK_ptr);
}
}
......
......@@ -46,10 +46,10 @@
#include "spdlog/spdlog.h"
#include "common.h"
int printDebugInfo = 0;
int useHTTPS = 1;
int encryptKeys = 0;
bool autoconfirm = false;
int printDebugInfo = -1;
int useHTTPS = -1;
int encryptKeys = -1;
int autoconfirm = -1;
SGXRegistrationServer *registrationServer = nullptr;
HttpServer *httpServer2 = nullptr;
......@@ -164,13 +164,13 @@ Json::Value GetSertificateImpl(const string &hash) {
}
Json::Value SGXRegistrationServer::signCertificate(const string &csr) {
Json::Value SGXRegistrationServer::SignCertificate(const string &csr) {
spdlog::info("Enter signCertificate ");
lock_guard<recursive_mutex> lock(m);
return signCertificateImpl(csr, autoSign);
}
Json::Value SGXRegistrationServer::getCertificate(const string &hash) {
Json::Value SGXRegistrationServer::GetCertificate(const string &hash) {
lock_guard<recursive_mutex> lock(m);
return GetSertificateImpl(hash);
}
......
......@@ -42,8 +42,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);
};
......
......@@ -45,6 +45,23 @@
#include "common.h"
void setFullOptions(int _printDebugInfo, int _useHTTPS, int _autoconfirm, int _encryptKeys) {
if (_printDebugInfo)
spdlog::set_level(spdlog::level::debug);
else {
spdlog::set_level(spdlog::level::info);
}
printDebugInfo = _printDebugInfo;
useHTTPS = _useHTTPS;
autoconfirm = _autoconfirm;
encryptKeys = _encryptKeys;
}
void setOptions(int _printDebugInfo, int _useHTTPS, int _autoconfirm) {
setFullOptions(_printDebugInfo, _useHTTPS, _autoconfirm, false);
}
bool isStringDec(string &_str) {
auto res = find_if_not(_str.begin(), _str.end(), [](char c) -> bool {
......@@ -81,15 +98,14 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
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");
spdlog::info("NO ROOT CA CERTIFICATE YET. CREATING ...");
string genRootCACert = "cd cert && ./create_CA";
if (system(genRootCACert.c_str()) == 0) {
spdlog::info("ROOT CA CERTIFICATE IS SUCCESSFULLY GENERATED");
} else {
spdlog::info("ROOT CA CERTIFICATE GENERATION FAILED");
spdlog::error("ROOT CA CERTIFICATE GENERATION FAILED");
exit(-1);
}
}
......@@ -116,7 +132,7 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
if (!s->StartListening()) {
spdlog::info("SGX Server could not start listening");
spdlog::error("SGX Server could not start listening");
exit(-1);
} else {
spdlog::info("SGX Server started on port {}", BASE_PORT);
......@@ -131,7 +147,7 @@ int SGXWalletServer::initHttpServer() { //without ssl
s = new SGXWalletServer(*httpServer,
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
if (!s->StartListening()) {
spdlog::info("Server could not start listening");
spdlog::error("Server could not start listening");
exit(-1);
}
return 0;
......@@ -148,7 +164,7 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k
result["errorMessage"] = "";
result["encryptedKeyShare"] = "";
char *encryptedKeyShareHex = nullptr;
shared_ptr<string> encryptedKeyShareHex = nullptr;
try {
......@@ -162,18 +178,15 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k
throw RPCException(errStatus, errMsg);
}
result["encryptedKeyShare"] = string(encryptedKeyShareHex);
result["encryptedKeyShare"] = *encryptedKeyShareHex;
writeKeyShare(_keyShareName, encryptedKeyShareHex, _index, n, t);
writeKeyShare(_keyShareName, *encryptedKeyShareHex, _index, n, t);
} catch (RPCException &_e) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
if (encryptedKeyShareHex != nullptr) {
free(encryptedKeyShareHex);
}
return result;
}
......@@ -253,12 +266,11 @@ Json::Value SGXWalletServer::generateECDSAKeyImpl() {
result["errorMessage"] = "";
result["encryptedKey"] = "";
spdlog::info("Calling method generateECDSAKey");
vector<string> keys;
try {
keys = gen_ecdsa_key();
keys = genECDSAKey();
if (keys.size() == 0) {
throw RPCException(UNKNOWN_ERROR, "key was not generated");
......@@ -266,16 +278,14 @@ Json::Value SGXWalletServer::generateECDSAKeyImpl() {
string keyName = "NEK:" + keys.at(2);
if (printDebugInfo) {
spdlog::info("write encr key {}", keys.at(0));
spdlog::info("keyname length is {}", keyName.length());
spdlog::info("key name generated: {}", keyName);
}
spdlog::debug("key name generated: {}", keyName);
spdlog::debug("write encr key {}", keys.at(0));
writeDataToDB(keyName, keys.at(0));
result["encryptedKey"] = keys.at(0);
result["publicKey"] = keys.at(1);
result["PublicKey"] = keys.at(1);
result["keyName"] = keyName;
} catch (RPCException &_e) {
......@@ -297,15 +307,15 @@ Json::Value SGXWalletServer::renameECDSAKeyImpl(const string &_keyName, const st
string prefix = _tempKeyName.substr(0, 8);
if (prefix != "tmp_NEK:") {
throw RPCException(UNKNOWN_ERROR, "wrong temp key name");
throw RPCException(UNKNOWN_ERROR, "invalid temp key name");
}
prefix = _keyName.substr(0, 12);
if (prefix != "NEK_NODE_ID:") {
throw RPCException(UNKNOWN_ERROR, "wrong key name");
throw RPCException(UNKNOWN_ERROR, "invalid key name");
}
string postfix = _keyName.substr(12, _keyName.length());
if (!isStringDec(postfix)) {
throw RPCException(UNKNOWN_ERROR, "wrong key name");
throw RPCException(UNKNOWN_ERROR, "invalid key name");
}
shared_ptr<string> key_ptr = readFromDb(_tempKeyName);
......@@ -333,10 +343,6 @@ Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_
vector<string> sign_vect(3);
if (printDebugInfo) {
spdlog::info("entered ecdsaSignMessageHashImpl {}", _messageHash, "length {}", _messageHash.length());
}
try {
string cutHash = _messageHash;
......@@ -347,10 +353,6 @@ Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_
cutHash.erase(cutHash.begin(), cutHash.begin() + 1);
}
if (printDebugInfo) {
spdlog::info("Hash handled {}", cutHash);
}
if (!checkECDSAKeyName(_keyName)) {
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
......@@ -363,14 +365,12 @@ Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_
shared_ptr<string> key_ptr = readFromDb(_keyName, "");
sign_vect = ecdsa_sign_hash(key_ptr->c_str(), cutHash.c_str(), _base);
sign_vect = ecdsaSignHash(key_ptr->c_str(), cutHash.c_str(), _base);
if (sign_vect.size() != 3) {
throw RPCException(INVALID_ECSDA_SIGNATURE, "Invalid ecdsa signature");
}
if (printDebugInfo) {
spdlog::info("got signature_s {}", sign_vect.at(2));
}
spdlog::debug("got signature_s {}", sign_vect.at(2));
result["signature_v"] = sign_vect.at(0);
result["signature_r"] = sign_vect.at(1);
......@@ -390,22 +390,21 @@ Json::Value SGXWalletServer::getPublicECDSAKeyImpl(const string &_keyName) {
result["status"] = 0;
result["errorMessage"] = "";
result["publicKey"] = "";
result["PublicKey"] = "";
spdlog::info("Calling method getPublicECDSAKey");
string Pkey;
string publicKey;
try {
if (!checkECDSAKeyName(_keyName)) {
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
shared_ptr<string> key_ptr = readFromDb(_keyName);
Pkey = get_ecdsa_pubkey(key_ptr->c_str());
if (printDebugInfo) {
spdlog::info("PublicKey {}", Pkey);
spdlog::info("PublicKey length {}", Pkey.length());
}
result["publicKey"] = Pkey;
shared_ptr<string> keyStr = readFromDb(_keyName);
publicKey = getECDSAPubKey(keyStr->c_str());
spdlog::debug("PublicKey {}", publicKey);
spdlog::debug("PublicKey length {}", publicKey.length());
result["PublicKey"] = publicKey;
result["publicKey"] = publicKey;
} catch (RPCException &_e) {
result["status"] = _e.status;
......@@ -469,6 +468,7 @@ Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName,
vector<string> cur_coef = verifVector.at(i);
for (int j = 0; j < 4; j++) {
result["verificationVector"][i][j] = cur_coef.at(j);
result["Verification Vector"][i][j] = cur_coef.at(j);
}
}
......@@ -477,20 +477,20 @@ Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName,
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["verificationVector"] = "";
result["Verification Vector"] = "";
}
return result;
}
Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const Json::Value &_publicKeys, int _t, int _n) {
spdlog::info("enter getSecretShareImpl");
Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
if (_publicKeys.size() != (uint64_t) _n) {
throw RPCException(INVALID_DKG_PARAMS, "wrong number of public keys");
if (_pubKeys.size() != (uint64_t) _n) {
throw RPCException(INVALID_DKG_PARAMS, "invalid number of public keys");
}
if (!checkName(_polyName, "POLY")) {
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
......@@ -501,16 +501,15 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
shared_ptr<string> encr_poly_ptr = readFromDb(_polyName);
vector<string> pubKeys_vect;
vector<string> pubKeysStrs;
for (int i = 0; i < _n; i++) {
std::cerr << "publicKeys " << i << " is " << _publicKeys[i].asString() << std::endl;
if (!checkHex(_publicKeys[i].asString(), 64)) {
if (!checkHex(_pubKeys[i].asString(), 64)) {
throw RPCException(INVALID_HEX, "Invalid public key");
}
pubKeys_vect.push_back(_publicKeys[i].asString());
pubKeysStrs.push_back(_pubKeys[i].asString());
}
string s = get_secret_shares(_polyName, encr_poly_ptr->c_str(), pubKeys_vect, _t, _n);
string s = get_secret_shares(_polyName, encr_poly_ptr->c_str(), pubKeysStrs, _t, _n);
//cerr << "result is " << s << endl;
result["secretShare"] = s;
......@@ -519,6 +518,7 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["secretShare"] = "";
result["SecretShare"] = "";
}
return result;
......@@ -527,8 +527,6 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, const string &_ethKeyName,
const string &_secretShare, int _t, int _n, int _index) {
spdlog::info("enter dkgVerificationImpl");
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -551,7 +549,7 @@ Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, co
shared_ptr<string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
if (!VerifyShares(_publicShares.c_str(), _secretShare.c_str(), encryptedKeyHex_ptr->c_str(), _t, _n, _index)) {
if (!verifyShares(_publicShares.c_str(), _secretShare.c_str(), encryptedKeyHex_ptr->c_str(), _t, _n, _index)) {
result["result"] = false;
}
......@@ -568,7 +566,6 @@ Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, co
Json::Value SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string &_ethKeyName, const string &_polyName,
const string &_secretShare, int _t, int _n) {
spdlog::info("createBLSPrivateKeyImpl entered");
Json::Value result;
result["status"] = 0;
......@@ -577,8 +574,8 @@ Json::Value SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName,
try {
if (_secretShare.length() != (uint64_t) _n * 192) {
spdlog::info("wrong length of secret shares - {}", _secretShare.length());
spdlog::info("secret shares - {}", _secretShare);
spdlog::error("Invalid secret share length - {}", _secretShare.length());
spdlog::error("Secret share - {}", _secretShare);
throw RPCException(INVALID_SECRET_SHARES_LENGTH, "Invalid secret share length");
}
if (!checkECDSAKeyName(_ethKeyName)) {
......@@ -594,9 +591,8 @@ Json::Value SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName,
throw RPCException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
vector<string> sshares_vect;
if (printDebugInfo) {
spdlog::info("secret shares from json are - {}", _secretShare);
}
spdlog::debug("secret shares from json are - {}", _secretShare);
shared_ptr<string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
......@@ -635,15 +631,13 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName)
throw RPCException(INVALID_POLY_NAME, "Invalid BLSKey name");
}
shared_ptr<string> encryptedKeyHex_ptr = readFromDb(_blsKeyName);
if (printDebugInfo) {
spdlog::info("encr_bls_key_share is {}", *encryptedKeyHex_ptr);
spdlog::info("length is {}", encryptedKeyHex_ptr->length());
//cerr << "encr_bls_key_share is " << *encryptedKeyHex_ptr << endl;
// cerr << "length is " << encryptedKeyHex_ptr->length() << endl;
}
spdlog::debug("encr_bls_key_share is {}", *encryptedKeyHex_ptr);
spdlog::debug("length is {}", encryptedKeyHex_ptr->length());
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) {
......@@ -672,6 +666,7 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int
result["share*G2"] = *shareG2_ptr;
result["dhKey"] = DHKey;
result["DHKey"] = DHKey;
} catch (RPCException &_e) {
cerr << " err str " << _e.errString << endl;
......@@ -688,7 +683,6 @@ Json::Value SGXWalletServer::multG2Impl(const string &_x) {
result["status"] = 0;
result["errorMessage"] = "";
try {
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);
......@@ -708,10 +702,12 @@ Json::Value SGXWalletServer::isPolyExistsImpl(const string &_polyName) {
try {
std::shared_ptr<std::string> poly_str_ptr = LevelDB::getLevelDb()->readString(_polyName);
result["IsExist"] = true;
result["exists"] = true;
result["status"] = 0;
result["errorMessage"] = "";
if (poly_str_ptr == nullptr) {
result["IsExist"] = false;
result["exists"] = false;
result["status"] = 0;
result["errorMessage"] = "";
}
......@@ -720,6 +716,7 @@ Json::Value SGXWalletServer::isPolyExistsImpl(const string &_polyName) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["IsExist"] = false;
result["exists"] = false;
}
return result;
......@@ -736,7 +733,6 @@ Json::Value SGXWalletServer::getServerStatusImpl() {
Json::Value SGXWalletServer::generateDKGPoly(const string &_polyName, int _t) {
spdlog::info("entered generateDKGPoly");
lock_guard<recursive_mutex> lock(m);
return generateDKGPolyImpl(_polyName, _t);
}
......@@ -789,10 +785,7 @@ Json::Value SGXWalletServer::getPublicECDSAKey(const string &_keyName) {
Json::Value SGXWalletServer::ecdsaSignMessageHash(int _base, const string &_keyShareName, const string &_messageHash) {
lock_guard<recursive_mutex> lock(m);
spdlog::info("entered ecdsaSignMessageHash");
if (printDebugInfo) {
spdlog::info("MessageHash first {}", _messageHash);
}
spdlog::debug("MessageHash first {}", _messageHash);
return ecdsaSignMessageHashImpl(_base, _keyShareName, _messageHash);
}
......@@ -890,12 +883,10 @@ void SGXWalletServer::writeDataToDB(const string &Name, const string &value) {
if (LevelDB::getLevelDb()->readString(Name) != nullptr) {
spdlog::info("name {}", Name, " already exists");
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Key share already exists");
}
LevelDB::getLevelDb()->writeString(key, value);
if (printDebugInfo) {
spdlog::info("{} ", Name, " is written to db ");
}
}
......@@ -31,6 +31,8 @@
#endif
EXTERNC void setFullOptions(int _printDebugInfo, int _useHTTPS, int _autoconfirm, int _encryptKeys);
EXTERNC void setOptions(int _printDebugInfo, int _useHTTPS, int _autoconfirm);
......
......@@ -25,9 +25,11 @@
#define SGXWALLET_SGXWALLETSERVER_HPP
#include "abstractstubserver.h"
#include <mutex>
#include "abstractstubserver.h"
#include "BLSCrypto.hpp"
using namespace jsonrpc;
using namespace std;
......@@ -112,7 +114,7 @@ public:
static Json::Value getVerificationVectorImpl(const string &_polyName, int _t, int _n);
static Json::Value getSecretShareImpl(const string &_polyName, const Json::Value &_publicKeys, int _t, int _n);
static Json::Value getSecretShareImpl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n);
static Json::Value
dkgVerificationImpl(const string &_publicShares, const string &_ethKeyName, const string &_secretShare,
......
......@@ -22,71 +22,52 @@
*/
#include <memory>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp"
#include "bls.h"
#include "leveldb/db.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
#include "BLSPrivateKeyShareSGX.h"
#include "spdlog/spdlog.h"
#include <gmp.h>
#include <sgx_urts.h>
#include "BLSPrivateKeyShareSGX.h"
#include "sgxwallet_common.h"
#include "create_enclave.h"
#include "secure_enclave_u.h"
#include "sgx_detect.h"
#include <gmp.h>
#include <sgx_urts.h>
#include "sgxwallet.h"
#include "LevelDB.h"
#include "SGXWalletServer.h"
#include "SGXRegistrationServer.h"
#include "SEKManager.h"
#include "CSRManagerServer.h"
#include "BLSCrypto.h"
#include "ServerInit.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 "SGXWalletServer.hpp"
#include "SGXWALLET_VERSION"
//#include <system>
void initDaemon() {
void initUserSpace() {
libff::init_alt_bn128_params();
LevelDB::initDataFolderAndDBs();
}
void initEnclave() {
eid = 0;
updated = 0;
#ifndef SGX_HW_SIM
unsigned long support;
support = get_sgx_support();
......@@ -96,9 +77,8 @@ void initEnclave() {
}
#endif
if ( printDebugInfo) {
spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG);
}
spdlog::debug("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG);
status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token,
&updated, &eid, 0);
......@@ -108,13 +88,13 @@ void initEnclave() {
fprintf(stderr, "sgx_create_enclave: %s: file not found\n", ENCLAVE_NAME);
fprintf(stderr, "Did you forget to set LD_LIBRARY_PATH?\n");
} else {
spdlog::error("sgx_create_enclave_search failed");
fprintf(stderr, "%s: 0x%04x\n", ENCLAVE_NAME, status);
}
exit(1);
}
//fprintf(stderr, "Enclave launched\n");
spdlog::info( "Enclave launched");
spdlog::info("Enclave created and started successfully");
status = tgmp_init(eid);
if (status != SGX_SUCCESS) {
......@@ -122,38 +102,27 @@ void initEnclave() {
exit(1);
}
if (printDebugInfo) {
spdlog::info("libtgmp initialized");
//fprintf(stderr, "libtgmp initialized\n");
}
spdlog::info("Enclave libtgmp library initialized successfully");
}
int sgxServerInited = 0;
void initAll(bool _checkCert, bool _autoSign, void (*SEK_func)()) {
void initAll(bool _checkCert, bool _autoSign) {
cout << "Running sgxwallet version:" << SGXWALLET_VERSION << endl;
//spdlog::set_pattern("%c");
if (sgxServerInited == 1)
return;
initEnclave();
initDaemon();
//init_SEK();
SEK_func();
CHECK_STATE(sgxServerInited == 0)
sgxServerInited = 1;
initEnclave();
initUserSpace();
init_SEK();
if (useHTTPS) {
SGXWalletServer::initHttpsServer(_checkCert);
initRegistrationServer(_autoSign);
init_csrmanager_server();
}
else {
init_csrmanager_server();
} else {
SGXWalletServer::initHttpServer();
}
//std::cerr << "enclave inited" << std::endl;
}
......@@ -30,9 +30,9 @@
#define EXTERNC
#endif
EXTERNC void initAll(bool _checkCert, bool _autoSign, void (*func)());
EXTERNC void initAll(bool _checkCert, bool _autoSign);
EXTERNC void initDaemon();
EXTERNC void initUserSpace();
EXTERNC void initEnclave();
......
......@@ -39,16 +39,16 @@ public:
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());
response = this->SignCertificate(request["certificate"].asString());
}
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;
};
......
......@@ -32,15 +32,29 @@ using namespace std;
#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__);}
#include "InvalidStateException.h"
inline std::string className(const std::string &prettyFunction) {
size_t colons = prettyFunction.find("::");
if (colons == std::string::npos)
return "::";
size_t begin = prettyFunction.substr(0, colons).rfind(" ") + 1;
size_t end = colons - begin;
return prettyFunction.substr(begin, end);
}
#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ )
#define CHECK_STATE(_EXPRESSION_) \
if (!(_EXPRESSION_)) { \
auto __msg__ = string("State check failed::") + #_EXPRESSION_ + " " + string(__FILE__) + ":" + to_string(__LINE__); \
throw runtime_error(__msg__);}
throw InvalidStateException(__msg__, __CLASS_NAME__);}
#endif //SGXWALLET_COMMON_H
......@@ -5,25 +5,25 @@ cd /usr/src/sdk;
echo $1
if [ "$1" = -t ]; then
set -e
# ./testw [bls-key-encrypt]
# ./testw [bls-key-encrypt-decrypt]
# ./testw [dkg-gen]
# ./testw [dkg-pub_shares]
# ./testw [dkg-verify]
# ./testw [ecdsa_test]
# ./testw [test_test]
# ./testw [get_pub_ecdsa_key_test]
# ./testw [bls_dkg]
# ./testw [api_test]
# ./testw [getServerStatus_test]
# ./testw [dkg_api_test]
# ./testw [is_poly_test]
# ./testw [AES-encrypt-decrypt]
./testw [bls-key-encrypt]
#./testw [bls-key-encrypt-decrypt]
#./testw [dkg-gen]
#./testw [dkg-pub_shares]
#./testw [dkg-verify]
#./testw [ecdsa_test]
#./testw [test_test]
#./testw [get_pub_ecdsa_key_test]
#./testw [bls_dkg]
#./testw [api_test]
#./testw [getServerStatus_test]
#./testw [dkg_api_test]
#./testw [is_poly_test]
#./testw [AES-encrypt-decrypt]
#./testw [ecdsa_api_test]
#./testw [dkg-encr_sshares]
#./testw [bls_sign]
#./testw [many_threads_test]
# ./testw [aes_dkg]
#./testw [bls_sign]
#/testw [many_threads_test]
#./testw [aes_dkg]
else
./sgxwallet $1 $2 $3 $4
fi
......
......@@ -70,11 +70,7 @@ cd scripts; ./build.py; cd ..
Go to the project's top directory, then run
```bash
libtoolize --force
aclocal
autoheader
automake --force-missing --add-missing
autoconf
./autoconf.bash
./configure
make
......
version: '3'
services:
sgxwallet:
image: skalenetwork/sgxwallet:latest_commit
image: skalenetwork/sgxwallet:latest
ports:
- "1026:1026"
- "1027:1027"
......@@ -17,6 +17,7 @@ services:
max-size: "10m"
max-file: "4"
restart: unless-stopped
command: -s -d -y
command: -s
healthcheck:
test: ["CMD", "ls /dev/isg /dev/mei0"]
#!/bin/bash
cd ../skale-admin
source skale-admin/bin/activate
docker stop $(docker ps -a -q)
docker pull skalenetwork/sgxwalletsim:latest
ETH_PRIVATE_KEY=3dd85d854e41db7585080dfdb90f88a83f0c70e229c509a4a1da63d0c82d5ad0 MANAGER_BRANCH=delegation-fix bash ./scripts/deploy_manager.sh
ETH_PRIVATE_KEY=3dd85d854e41db7585080dfdb90f88a83f0c70e229c509a4a1da63d0c82d5ad0 IMA_ENDPOINT=http://localhost:1000 SCHAIN_TYPE=test2 bash ./scripts/run_tests.sh
......@@ -65,18 +65,23 @@ void printUsage() {
}
int main(int argc, char *argv[]) {
void (*SEK_initializer)();
SEK_initializer = init_SEK;
bool checkClientCert = true;
bool sign_automatically = false;
bool encryptKeysOption = false;
bool useHTTPSOption = true;
bool printDebugInfoOption = false;
bool autoconfirmOption = false;
bool checkClientCertOption = true;
bool autoSignClientCertOption = false;
int opt;
if (argc > 1 && strlen(argv[1]) == 1) {
fprintf(stderr, "option is too short %s\n", argv[1]);
printUsage();
exit(1);
}
encryptKeys = 0;
while ((opt = getopt(argc, argv, "cshd0aby")) != -1) {
switch (opt) {
......@@ -90,25 +95,25 @@ int main(int argc, char *argv[]) {
exit(1);
}
case 'c':
checkClientCert = false;
checkClientCertOption = false;
break;
case 's':
sign_automatically = true;
autoSignClientCertOption = true;
break;
case 'd':
printDebugInfo = 1;
printDebugInfoOption = true;
break;
case '0':
useHTTPS = 0;
useHTTPSOption = false;
break;
case 'a':
encryptKeys = 0;
encryptKeysOption = false;
break;
case 'b':
SEK_initializer = enter_SEK;
encryptKeysOption = false;
break;
case 'y':
autoconfirm = true;
autoconfirmOption = true;
break;
case '?':
printUsage();
......@@ -117,7 +122,10 @@ int main(int argc, char *argv[]) {
break;
}
}
initAll(checkClientCert, sign_automatically, SEK_initializer);
setFullOptions(printDebugInfoOption, useHTTPSOption, autoconfirmOption, encryptKeysOption);
initAll(checkClientCertOption, autoSignClientCertOption);
while (true) {
sleep(10);
......
......@@ -30,17 +30,23 @@
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
extern int printDebugInfo;
extern int useHTTPS;
extern int encryptKeys;
extern bool autoconfirm;
extern int autoconfirm;
#define BUF_LEN 1024
#define BUF_LEN 4096
#define MAX_KEY_LENGTH 128
#define MAX_COMPONENT_LENGTH 80
......@@ -52,9 +58,6 @@ extern bool autoconfirm;
#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
......
......@@ -46,17 +46,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <gmp.h>
#include <sgx_urts.h>
#include <stdio.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <sgx_tcrypto.h>
#include "BLSCrypto.h"
#include "ServerInit.h"
#include "DKGCrypto.h"
#include "RPCException.h"
#include "LevelDB.h"
#include "SGXWalletServer.hpp"
#include <sgx_tcrypto.h>
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "stubclient.h"
#include "BLSSigShare.h"
#include "BLSSigShareSet.h"
......@@ -66,9 +69,30 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <thread>
#include "common.h"
#include "stubclient.h"
#include <jsonrpccpp/client/connectors/httpclient.h>
#include "SGXWalletServer.h"
#include "catch.hpp"
using namespace jsonrpc;
using namespace std;
sgx_launch_token_t token = {0};
sgx_enclave_id_t eid = 0;
sgx_status_t status;
int updated;
default_random_engine rand_gen((unsigned int) time(0));
void destroyEnclave() {
if (eid != 0) {
sgx_destroy_enclave(eid);
eid = 0;
}
}
default_random_engine randGen((unsigned int) time(0));
string stringFromFr(libff::alt_bn128_Fr &el) {
......@@ -88,115 +112,28 @@ void usage() {
exit(1);
}
sgx_launch_token_t token = {0};
sgx_enclave_id_t eid;
sgx_status_t status;
int updated;
#define TEST_BLS_KEY_SHARE "4160780231445160889237664391382223604184857153814275770598791864649971919844"
#define TEST_BLS_KEY_NAME "SCHAIN:17:INDEX:5:KEY:1"
void reset_db() {
void resetDB() {
destroyEnclave();
//string db_name = SGXDATA_FOLDER + WALLETDB_NAME;
REQUIRE(system("rm -rf "
WALLETDB_NAME) == 0);
}
char *encryptTestKey() {
string encryptTestKey() {
const char *key = TEST_BLS_KEY_SHARE;
int errStatus = -1;
vector<char> errMsg(BUF_LEN, 0);;
char *encryptedKeyHex = encryptBLSKeyShare2Hex(&errStatus, errMsg.data(), key);
auto encryptedKeyHex = encryptBLSKeyShare2Hex(&errStatus, errMsg.data(), key);
REQUIRE(encryptedKeyHex != nullptr);
REQUIRE(errStatus == 0);
printf("Encrypt key completed with status: %d %s \n", errStatus, errMsg.data());
printf("Encrypted key len %d\n", (int) strlen(encryptedKeyHex));
printf("Encrypted key %s \n", encryptedKeyHex);
return encryptedKeyHex;
}
TEST_CASE("BLS key encrypt", "[bls-key-encrypt]") {
printDebugInfo = 1;
useHTTPS = 0;
autoconfirm = true;
initAll(false, true, init_SEK);
auto key = encryptTestKey();
REQUIRE(key != nullptr);
free(key);
}
TEST_CASE("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
{
printDebugInfo = 1;
useHTTPS = 0;
autoconfirm = true;
initAll(false, true, init_SEK);
//init_enclave();
int errStatus = -1;
vector<char> errMsg(BUF_LEN, 0);
char *encryptedKey = encryptTestKey();
REQUIRE(encryptedKey != nullptr);
char *plaintextKey = decryptBLSKeyShareFromHex(&errStatus, errMsg.data(), encryptedKey);
free(encryptedKey);
REQUIRE(errStatus == 0);
REQUIRE(strcmp(plaintextKey, TEST_BLS_KEY_SHARE) == 0);
printf("Decrypt key completed with status: %d %s \n", errStatus, errMsg.data());
printf("Decrypted key len %d\n", (int) strlen(plaintextKey));
printf("Decrypted key: %s\n", plaintextKey);
free(plaintextKey);
sgx_destroy_enclave(eid);
}
}
TEST_CASE("DKG gen test", "[dkg-gen]") {
autoconfirm = true;
//init_all();
initEnclave();
vector<uint8_t> encrypted_dkg_secret(DKG_MAX_SEALED_LEN, 0);
vector<char> errMsg(1024, 0);
int err_status = 0;
uint32_t enc_len = 0;
status = gen_dkg_secret(eid, &err_status, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, 32);
REQUIRE(status == SGX_SUCCESS);
printf("gen_dkg_secret completed with status: %d %s \n", err_status, errMsg.data());
printf("\n Length: %d \n", enc_len);
vector<char> secret(DKG_BUFER_LENGTH, 0);
vector<char> errMsg1(1024, 0);
uint32_t dec_len;
status = decrypt_dkg_secret(eid, &err_status, errMsg1.data(), encrypted_dkg_secret.data(),
(uint8_t *) secret.data(), &dec_len);
REQUIRE(status == SGX_SUCCESS);
printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1.data());
printf("decrypted secret %s \n\n", secret.data());
printf("secret length %d \n", (int) strlen(secret.data()));
printf("decr length %d \n", dec_len);
sgx_destroy_enclave(eid);
return *encryptedKeyHex;
}
vector<libff::alt_bn128_Fr> SplitStringToFr(const char *koefs, const char symbol) {
......@@ -240,26 +177,85 @@ vector<string> SplitStringTest(const char *koefs, const char symbol) {
return G2_strings;
}
libff::alt_bn128_G2 VectStringToG2(const vector<string> &G2_str_vect) {
libff::alt_bn128_G2 vectStringToG2(const vector<string> &_G2StrVect) {
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());
koef.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str());
koef.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str());
koef.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str());
koef.X.c0 = libff::alt_bn128_Fq(_G2StrVect.at(0).c_str());
koef.X.c1 = libff::alt_bn128_Fq(_G2StrVect.at(1).c_str());
koef.Y.c0 = libff::alt_bn128_Fq(_G2StrVect.at(2).c_str());
koef.Y.c1 = libff::alt_bn128_Fq(_G2StrVect.at(3).c_str());
koef.Z.c0 = libff::alt_bn128_Fq::one();
koef.Z.c1 = libff::alt_bn128_Fq::zero();
return koef;
}
string convertDecToHex(string _dec, int _byteCount = 32) {
mpz_t num;
mpz_init(num);
mpz_set_str(num, _dec.c_str(), 10);
vector<char> tmp(mpz_sizeinbase(num, 16) + 2, 0);
char *hex = mpz_get_str(tmp.data(), 16, num);
string result = hex;
int n_zeroes = _byteCount * 2 - result.length();
result.insert(0, n_zeroes, '0');
return result;
}
TEST_CASE("BLS key encrypt", "[bls-key-encrypt]") {
resetDB();
setOptions(false, false, true);
initAll(false, true);
auto key = encryptTestKey();
REQUIRE(key.length() > 0);
destroyEnclave();
}
TEST_CASE("DKG gen test", "[dkg-gen]") {
resetDB();
setOptions(false, false, true);
initAll(false, true);
vector<uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int err_status = 0;
uint32_t enc_len = 0;
status = gen_dkg_secret(eid, &err_status, errMsg.data(), encryptedDKGSecret.data(), &enc_len, 32);
REQUIRE(status == SGX_SUCCESS);
// printf("gen_dkg_secret completed with status: %d %s \n", err_status, errMsg.data());
// printf("\n Length: %d \n", enc_len);
vector<char> secret(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0);
uint32_t dec_len;
status = decrypt_dkg_secret(eid, &err_status, errMsg1.data(), encryptedDKGSecret.data(),
(uint8_t *) secret.data(), &dec_len);
REQUIRE(status == SGX_SUCCESS);
destroyEnclave();
}
TEST_CASE("DKG public shares test", "[dkg-pub_shares]") {
autoconfirm = true;
//init_all();
resetDB();
setOptions(false, false, true);
initAll(false, true);
libff::init_alt_bn128_params();
initEnclave();
vector<uint8_t> encrypted_dkg_secret(DKG_MAX_SEALED_LEN, 0);
vector<char> errMsg(1024, 0);
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int err_status = 0;
uint32_t enc_len = 0;
......@@ -271,7 +267,7 @@ TEST_CASE("DKG public shares test", "[dkg-pub_shares]") {
//printf("gen_dkg_public completed with status: %d %s \n", err_status, errMsg);
vector<char> errMsg1(1024, 0);
vector<char> errMsg1(BUF_LEN, 0);
char colon = ':';
vector<char> public_shares(10000, 0);
......@@ -279,32 +275,26 @@ TEST_CASE("DKG public shares test", "[dkg-pub_shares]") {
status = get_public_shares(eid, &err_status, errMsg1.data(),
encrypted_dkg_secret.data(), enc_len, public_shares.data(), t, n);
REQUIRE(status == SGX_SUCCESS);
printf("\nget_public_shares status: %d error %s \n\n", err_status, errMsg1.data());
printf(" LEN: %d \n", (int) strlen(public_shares.data()));
printf(" result: %s \n", public_shares.data());
vector<string> G2_strings = SplitString(public_shares.data(), ',');
vector<string> G2_strings = splitString(public_shares.data(), ',');
vector<libff::alt_bn128_G2> pub_shares_G2;
for (u_int64_t i = 0; i < G2_strings.size(); i++) {
vector<string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
//libff::alt_bn128_G2 el = VectStringToG2(koef_str);
//cerr << "pub_share G2 " << i+1 << " : " << endl;
//el.print_coordinates();
pub_shares_G2.push_back(VectStringToG2(koef_str));
vector<string> koef_str = splitString(G2_strings.at(i).c_str(), ':');
pub_shares_G2.push_back(vectStringToG2(koef_str));
}
vector<char> secret(DKG_MAX_SEALED_LEN, 0);
vector<char> secret(BUF_LEN, 0);
status = decrypt_dkg_secret(eid, &err_status, errMsg1.data(), encrypted_dkg_secret.data(),
(uint8_t *) secret.data(), &enc_len);
REQUIRE(status == SGX_SUCCESS);
printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1.data());
//printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1.data());
signatures::Dkg dkg_obj(t, n);
vector<libff::alt_bn128_Fr> poly = SplitStringToFr(secret.data(), colon);
vector<libff::alt_bn128_G2> pub_shares_dkg = dkg_obj.VerificationVector(poly);
printf("calculated public shares (X.c0): \n");
// printf("calculated public shares (X.c0): \n");
for (uint32_t i = 0; i < pub_shares_dkg.size(); i++) {
libff::alt_bn128_G2 el = pub_shares_dkg.at(i);
el.to_affine_coordinates();
......@@ -313,329 +303,247 @@ TEST_CASE("DKG public shares test", "[dkg-pub_shares]") {
mpz_init(x_c0);
x_c0_el.as_bigint().to_mpz(x_c0);
char arr[mpz_sizeinbase(x_c0, 10) + 2];
char *share_str = mpz_get_str(arr, 10, x_c0);
printf(" %s \n", share_str);
mpz_clear(x_c0);
}
bool res = (pub_shares_G2 == pub_shares_dkg);
REQUIRE(res == true);
sgx_destroy_enclave(eid);
destroyEnclave();
}
TEST_CASE("DKG encrypted secret shares test", "[dkg-encr_sshares]") {
autoconfirm = true;
// init_all();
initEnclave();
resetDB();
setOptions(false, false, true);
initAll(false, true);
vector<char> errMsg(1024, 1);
vector<char> result(130, 1);
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int err_status = 0;
uint32_t enc_len = 0;
vector<uint8_t> encrypted_dkg_secret(DKG_MAX_SEALED_LEN, 0);
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
status = gen_dkg_secret(eid, &err_status, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
cerr << " poly generated" << endl;
// cerr << " poly generated" << endl;
status = set_encrypted_dkg_poly(eid, &err_status, errMsg.data(), encrypted_dkg_secret.data());
REQUIRE(status == SGX_SUCCESS);
cerr << " poly set" << endl;
// cerr << " poly set" << endl;
vector<uint8_t> encrPRDHKey(1024, 0);
vector<uint8_t> encrPRDHKey(BUF_LEN, 0);
string pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
vector<char> s_shareG2(320,0);
status = get_encr_sshare(eid, &err_status, errMsg.data(), encrPRDHKey.data(), &enc_len, result.data(), s_shareG2.data(),
(char*) pub_keyB.data(), 2, 2, 1);
vector<char> s_shareG2(BUF_LEN, 0);
status = get_encr_sshare(eid, &err_status, errMsg.data(), encrPRDHKey.data(), &enc_len, result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg.data());
cerr << "secret share is " << result.data() << endl;
sgx_destroy_enclave(eid);
destroyEnclave();
}
TEST_CASE("DKG verification test", "[dkg-verify]") {
autoconfirm = true;
// init_all();
initEnclave();
resetDB();
setOptions(false, false, true);
initAll(false, true);
vector<char> errMsg(1024, 0);
vector<char> result(130, 0);
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int err_status = 0;
uint32_t enc_len = 0;
vector<uint8_t> encrypted_dkg_secret(DKG_MAX_SEALED_LEN, 1);
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
status = gen_dkg_secret(eid, &err_status, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
cerr << " poly generated" << endl;
status = set_encrypted_dkg_poly(eid, &err_status, errMsg.data(), encrypted_dkg_secret.data());
REQUIRE(status == SGX_SUCCESS);
cerr << " poly set" << endl;
vector<uint8_t> encrPrDHKey(1024, 0);
vector<uint8_t> encrPrDHKey(BUF_LEN, 0);
string pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
vector<char> s_shareG2(320,0);
vector<char> s_shareG2(BUF_LEN, 0);
status = get_encr_sshare(eid, &err_status, errMsg.data(), encrPrDHKey.data(), &enc_len, result.data(), s_shareG2.data(),
(char*) pub_keyB.data(), 2, 2, 1);
status = get_encr_sshare(eid, &err_status, errMsg.data(), encrPrDHKey.data(), &enc_len, result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg.data());
cerr << "secret share is " << result.data() << endl;
sgx_destroy_enclave(eid);
destroyEnclave();
}
TEST_CASE("ECDSA keygen and signature test", "[ecdsa_test]") {
autoconfirm = true;
initEnclave();
resetDB();
setOptions(false, false, true);
initAll(false, true);
vector<char> errMsg(1024, 0);
vector<char> errMsg(BUF_LEN, 0);
int err_status = 0;
vector<uint8_t> encr_pr_key(1024, 0);
vector<char> pub_key_x(1024, 0);
vector<char> pub_key_y(1024, 0);
vector<uint8_t> encr_pr_key(BUF_LEN, 0);
vector<char> pub_key_x(BUF_LEN, 0);
vector<char> pub_key_y(BUF_LEN, 0);
uint32_t enc_len = 0;
//printf("before %p\n", pub_key_x);
status = generate_ecdsa_key(eid, &err_status, errMsg.data(), encr_pr_key.data(), &enc_len, pub_key_x.data(),
status = generate_ecdsa_key(eid, &err_status, errMsg.data(), encr_pr_key.data(), &enc_len, pub_key_x.data(),
pub_key_y.data());
printf("\nerrMsg %s\n", errMsg.data());
REQUIRE(status == SGX_SUCCESS);
printf("\nwas pub_key_x %s: \n", pub_key_x.data());
printf("\nwas pub_key_y %s: \n", pub_key_y.data());
/*printf("\nencr priv_key : \n");
for ( int i = 0; i < 1024 ; i++)
printf("%u ", encr_pr_key[i]);*/
REQUIRE(status == SGX_SUCCESS);
string hex = "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F";
// char* hex = "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
printf("hash length %d ", (int) hex.size());
vector<char> signature_r(1024, 0);
vector<char> signature_s(1024, 0);
vector<char> signature_r(BUF_LEN, 0);
vector<char> signature_s(BUF_LEN, 0);
uint8_t signature_v = 0;
status = ecdsa_sign1(eid, &err_status, errMsg.data(), encr_pr_key.data(), enc_len, (unsigned char *) hex.data(),
signature_r.data(),
signature_s.data(), &signature_v, 16);
REQUIRE(status == SGX_SUCCESS);
printf("\nsignature r : %s ", signature_r.data());
printf("\nsignature s: %s ", signature_s.data());
printf("\nsignature v: %u ", signature_v);
printf("\n %s \n", errMsg.data());
sgx_destroy_enclave(eid);
printf("the end of ecdsa test\n");
destroyEnclave();
}
TEST_CASE("Test test", "[test_test]") {
autoconfirm = true;
initEnclave();
resetDB();
setOptions(false, false, true);
initAll(false, true);
vector<char> errMsg(1024, 0);
vector<char> errMsg(BUF_LEN, 0);
int err_status = 0;
vector<uint8_t> encr_pr_key(1024, 0);
vector<char> pub_key_x(1024, 0);
vector<char> pub_key_y(1024, 0);
vector<uint8_t> encr_pr_key(BUF_LEN, 0);
vector<char> pub_key_x(BUF_LEN, 0);
vector<char> pub_key_y(BUF_LEN, 0);
uint32_t enc_len = 0;
status = generate_ecdsa_key(eid, &err_status, errMsg.data(), encr_pr_key.data(), &enc_len, pub_key_x.data(),
pub_key_y.data());
//printf("\nerrMsg %s\n", errMsg );
REQUIRE(status == SGX_SUCCESS);
//printf("\nwas pub_key_x %s: \n", pub_key_x);
//printf("\nwas pub_key_y %s: \n", pub_key_y);
//printf("\nencr priv_key %s: \n");
//for ( int i = 0; i < 1024 ; i++)
// printf("%u ", encr_pr_key[i]);
sgx_destroy_enclave(eid);
REQUIRE(status == SGX_SUCCESS);
destroyEnclave();
}
TEST_CASE("get public ECDSA key", "[get_pub_ecdsa_key_test]") {
autoconfirm = true;
//init_all();
initEnclave();
resetDB();
setOptions(false, false, true);
initAll(false, true);
int err_status = 0;
vector<char> errMsg(1024, 0);
vector<uint8_t> encr_pr_key(1024, 0);
vector<char> pub_key_x(1024, 0);
vector<char> pub_key_y(1024, 0);
uint32_t enc_len = 0;
int errStatus = 0;
vector<char> errMsg(BUF_LEN, 0);
vector<uint8_t> encPrivKey(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0);
uint32_t encLen = 0;
//printf("before %p\n", pub_key_x);
status = generate_ecdsa_key(eid, &err_status, errMsg.data(), encr_pr_key.data(), &enc_len, pub_key_x.data(),
pub_key_y.data());
printf("\nerrMsg %s\n", errMsg.data());
REQUIRE(status == SGX_SUCCESS);
status = generate_ecdsa_key(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(),
pubKeyY.data());
printf("\nwas pub_key_x %s length %d: \n", pub_key_x.data(), (int) strlen(pub_key_x.data()));
printf("\nwas pub_key_y %s length %d: \n", pub_key_y.data(), (int) strlen(pub_key_y.data()));
/*printf("\nencr priv_key %s: \n");
for ( int i = 0; i < 1024 ; i++)
printf("%u ", encr_pr_key[i]);*/
vector<char> got_pub_key_x(1024, 0);
vector<char> got_pub_key_y(1024, 0);
status = get_public_ecdsa_key(eid, &err_status, errMsg.data(), encr_pr_key.data(), enc_len, got_pub_key_x.data(),
got_pub_key_y.data());
REQUIRE(status == SGX_SUCCESS);
printf("\nnow pub_key_x %s: \n", got_pub_key_x.data());
printf("\nnow pub_key_y %s: \n", got_pub_key_y.data());
printf("\n pr key %s \n", errMsg.data());
sgx_destroy_enclave(eid);
}
/*TEST_CASE( "verification test", "[verify]" ) {
char* pubshares = "0d72c21fc5a43452ad5f36699822309149ce6ce2cdce50dafa896e873f1b8ddd12f65a2e9c39c617a1f695f076b33b236b47ed773901fc2762f8b6f63277f5e30d7080be8e98c97f913d1920357f345dc0916c1fcb002b7beb060aa8b6b473a011bfafe9f8a5d8ea4c643ca4101e5119adbef5ae64f8dfb39cd10f1e69e31c591858d7eaca25b4c412fe909ca87ca7aadbf6d97d32d9b984e93d436f13d43ec31f40432cc750a64ac239cad6b8f78c1f1dd37427e4ff8c1cc4fe1c950fcbcec10ebfd79e0c19d0587adafe6db4f3c63ea9a329724a8804b63a9422e6898c0923209e828facf3a073254ec31af4231d999ba04eb5b7d1e0056d742a65b766f2f3";
char *sec_share = "11592366544581417165283270001305852351194685098958224535357729125789505948557";
mpz_t sshare;
mpz_init(sshare);
mpz_set_str(sshare, "11592366544581417165283270001305852351194685098958224535357729125789505948557", 10);
int result = Verification(pubshares, sshare, 2, 0);
REQUIRE(result == 1);
vector<char> receivedPubKeyX(BUF_LEN, 0);
vector<char> receivedPubKeyY(BUF_LEN, 0);
}*/
using namespace jsonrpc;
using namespace std;
string ConvertDecToHex(string dec, int numBytes = 32) {
mpz_t num;
mpz_init(num);
mpz_set_str(num, dec.c_str(), 10);
vector<char> tmp(mpz_sizeinbase(num, 16) + 2, 0);
char *hex = mpz_get_str(tmp.data(), 16, num);
status = get_public_ecdsa_key(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, receivedPubKeyX.data(),
receivedPubKeyY.data());
REQUIRE(status == SGX_SUCCESS);
string result = hex;
int n_zeroes = numBytes * 2 - result.length();
result.insert(0, n_zeroes, '0');
destroyEnclave();
return result;
}
TEST_CASE("BLS_DKG test", "[bls_dkg]") {
useHTTPS = 0;
printDebugInfo = 1;
cerr << "test started" << endl;
initAll(false, true, init_SEK);
cerr << "Server inited" << endl;
resetDB();
setOptions(false, false, true);
initAll(false, true);
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
// cerr << "Client inited" << endl;
reset_db();
cerr << "1" << endl;
int n = 16, t = 16;
Json::Value EthKeys[n];
Json::Value etnKeys[n];
Json::Value VerifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value BLSSigShares[n];
Json::Value blsSigShares[n];
vector<string> pubShares(n);
vector<string> poly_names(n);
vector<string> polyNames(n);
int schain_id = rand_gen();
int dkg_id = rand_gen();
int schain_id = randGen();
int dkg_id = randGen();
for (uint8_t i = 0; i < n; i++) {
EthKeys[i] = c.generateECDSAKey();
etnKeys[i] = c.generateECDSAKey();
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;
polyNames[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
REQUIRE(VerifVects[i]["status"] == 0);
cout << "VV " << i << " " << VerifVects[i] << endl;
pubEthKeys.append(EthKeys[i]["publicKey"]);
pubEthKeys.append(etnKeys[i]["publicKey"]);
}
cerr << "2" << endl;
for (uint8_t i = 0; i < n; i++) {
secretShares[i] = c.getSecretShare(poly_names[i], pubEthKeys, t, n);
secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n);
cout << secretShares[i] << endl;
REQUIRE(secretShares[i]["status"] == 0);
for (uint8_t k = 0; k < t; k++) {
for (uint8_t j = 0; j < 4; j++) {
string pubShare = VerifVects[i]["verificationVector"][k][j].asString();
REQUIRE(pubShare.length() > 60);
pubShares[i] += ConvertDecToHex(pubShare);
pubShares[i] += convertDecToHex(pubShare);
}
}
// 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);
// cerr << "share * G2 is " << complaintResponse["share*G2"].asString();
// cerr << "DHKey is " << complaintResponse["dhKey"].asString();
cerr << "3" << endl;
int k = 0;
vector<string> secShares_vect(n);
vector<string> pSharesBad(pubShares);
vector<string> secSharesVect;
vector<string> invalidShares;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
// if ( i != j ){
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);
cerr << "pubShare is " << pubShares[i] << endl;
bool res = c.dkgVerification(pubShares[i], EthKeys[j]["keyName"].asString(), secretShare, t, n,
secSharesVect.push_back(secretShares[j]["secretShare"].asString().substr(192 * i, 192));
bool res = c.dkgVerification(pubShares[i], etnKeys[j]["keyName"].asString(), secretShare, t, n,
j)["result"].asBool();
k++;
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,
invalidShares[i][0] = 'q';
Json::Value wrongVerif = c.dkgVerification(invalidShares[i], etnKeys[j]["keyName"].asString(), secretShare, t,
n, j);
res = wrongVerif["result"].asBool();
REQUIRE(!res);
cerr << "wrong verification " << wrongVerif << endl;
// }
}
BLSSigShareSet sigShareSet(t, n);
cerr << "4" << endl;
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
auto hash_arr = make_shared<array<uint8_t, 32>>();
......@@ -645,105 +553,70 @@ TEST_CASE("BLS_DKG test", "[bls_dkg]") {
}
map<size_t, shared_ptr<BLSPublicKeyShare>> koefs_pkeys_map;
map<size_t, shared_ptr<BLSPublicKeyShare>> coeffsPubKeysMap;
for (int i = 0; i < t; i++) {
string endName = poly_names[i].substr(4);
string blsName = "BLS_KEY" + poly_names[i].substr(4);
string endName = polyNames[i].substr(4);
string blsName = "BLS_KEY" + polyNames[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);
c.createBLSPrivateKey(blsName, etnKeys[i]["keyName"].asString(), polyNames[i], secSharesVect[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);
cerr << i << " sig share is created " << endl;
shared_ptr<string> sig_share_ptr = make_shared<string>(BLSSigShares[i]["signatureShare"].asString());
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
shared_ptr<string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
BLSSigShare sig(sig_share_ptr, i + 1, t, n);
sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));
vector<string> pubKey_vect;
vector<string> pubKeyVect;
for (uint8_t j = 0; j < 4; j++) {
pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
}
BLSPublicKeyShare pubKey(make_shared<vector<string>>(pubKey_vect), t, n);
BLSPublicKeyShare pubKey(make_shared<vector<string>>(pubKeyVect), t, n);
REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
koefs_pkeys_map[i + 1] = make_shared<BLSPublicKeyShare>(pubKey);
coeffsPubKeysMap[i + 1] = make_shared<BLSPublicKeyShare>(pubKey);
}
cerr << "5" << endl;
shared_ptr<BLSSignature> commonSig = sigShareSet.merge();
BLSPublicKey common_public(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare>>>(koefs_pkeys_map), t, n);
BLSPublicKey common_public(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare>>>(coeffsPubKeysMap), t, n);
REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
cerr << "6" << endl;
destroyEnclave();
}
TEST_CASE("API test", "[api_test]") {
autoconfirm = true;
//DEBUG_PRINT = 1;
useHTTPS = 0;
//cerr << __GNUC__ << endl;
cerr << "API test started" << endl;
initAll(false, true, init_SEK);
setOptions(false, false, true);
initAll(false, true);
//HttpServer httpserver(1025);
//SGXWalletServer s(httpserver,
// JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
// s.StartListening();
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
// cerr << "Client inited" << endl;
try {
// for ( uint8_t i = 0; i < 2; 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:" + 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 << endl;
// cout << c.renameESDSAKey("NODE_1CHAIN_1","tmp_NEK:bcacde0d26c0ea2c7e649992e7f791e1fba2492f5b7ae63dadb799075167c7fc");
// cout<<c.getPublicECDSAKey("NEK:7ca98cf32fd1edba26ea685820719fd2201b068a10c1264d382abbde13802a0e");
//cout << c.ecdsaSignMessageHash(16, "NEK:697fadfc597bdbfae9ffb7412b80939e848c9c2fec2657bb2122b6d0d4a0dca8","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
//cout << c.ecdsaSignMessageHash(16, "known_key1","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
// cout << c.blsSignMessageHash(TEST_BLS_KEY_NAME, "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db", 2,2,1 );
// cout << c.generateDKGPoly("pp2", 2);
// cout << c.generateDKGPoly("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", 2);
//cout << c.generateDKGPoly("POLY:SCHAIN_ID:14225439306783892379384764908040542049263455631509697460847850632966314337557:NODE_ID:1:DKG_ID:71951190446274221430521459675625214118086594348715", 1);
//cout << c.getVerificationVector("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:2", 2, 2);
// cout << c.getVerificationVector("polyy", 5, 5);
// cout << c.getSecretShare("p2",
// "505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e232d69c361f0bc9e05f1cf8ef387122dc1d2f7cee7b6cda3537fc9427c02328b01f02fd94ec933134dc795a642864f8cb41ae263e11abaf992e21fcf9be732deb",
// 2,2);
// cout << c.getSecretShare("p2",
// "669aa790e1c5f5199af82ab0b6f1965c382d23a2ebdda581454adba3fd082a30edab62b545f78f1e402ceef7340a0364a7046633d6151fe7e657d8b8a6352378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25e6e",
// 2,2);
Json::Value publicKeys;
publicKeys.append(
"505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2");
publicKeys.append(
"378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25");
// cout << c.getSecretShare("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", publicKeys, 2, 2);
// cout << c.generateDKGPoly("p3", 3);
// cout << c.getSecretShare("p3",
// "669aa790e1c5f5199af82ab0b6f1965c382d23a2ebdda581454adba3fd082a30edab62b545f78f1e402ceef7340a0364a7046633d6151fe7e657d8b8a6352378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25e6e9d43f1c88581f53af993da1654c9f91829c1fe5344c4452ef8d2d8675c6a051c19029f6e4f82b035fb3552058cf22c5bbafd9e6456d579634987281765d130b0",
// 3,3);
......@@ -752,34 +625,18 @@ TEST_CASE("API test", "[api_test]") {
string share = share_big.substr(0, 192);
string publicShares = "1fc8154abcbf0c2ebf559571d7b57a8995c0e293a73d4676a8f76051a0d0ace30e00a87c9f087254c9c860c3215c4f11e8f85a3e8fae19358f06a0cbddf3df1924b1347b9b58f5bcb20958a19bdbdd832181cfa9f9e9fd698f6a485051cb47b829d10f75b6e227a7d7366dd02825b5718072cd42c39f0352071808622b7db6421b1069f519527e49052a8da6e3720cbda9212fc656eef945f5e56a4159c3b9622d883400460a9eff07fe1873f9b1ec50f6cf70098b9da0b90625b176f12329fa2ecc65082c626dc702d9cfb23a06770d4a2c7867e269efe84e3709b11001fb380a32d609855d1d46bc60f21140c636618b8ff55ed06d7788b6f81b498f96d3f9";
// cout << c.dkgVerification(publicShares, "test_key1", "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 );
// string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76df831dbef474cfc38be1c980130a8d273ff410fbf87deece9d7756a1b08ba9e954c1676cc7f2cac16e16cff0c877d8cf967381321fb4cc78e3638245a1dc85419766d281aff4935cc6eac25c9842032c8f7fae567c57622969599a72c42d2e1e";
string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b7637092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76";
//cout << c.createBLSPrivateKey( "test_bls1","key0", "oleh1", shares, 2, 2 );
//cout << c.getBLSPublicKeyShare("test_bls_key0");
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.getPublicECDSAKey("NEK:91573248d6b0ebd5b1bd313ab35163361b423c0f9f01bad085d166650b8b2c1f");
//cout << c.multG2("4160780231445160889237664391382223604184857153814275770598791864649971919844");
string s_share = "13b871ad5025fed10a41388265b19886e78f449f758fe8642ade51440fcf850bb2083f87227d8fb53fdfb2854e2d0abec4f47e2197b821b564413af96124cd84a8700f8eb9ed03161888c9ef58d6e5896403de3608e634e23e92fba041aa283484427d0e6de20922216c65865cfe26edd2cf9cbfc3116d007710e8d82feafd9135c497bef0c800ca310ba6044763572681510dad5e043ebd87ffaa1a4cd45a899222207f3d05dec8110d132ad34c62d6a3b40bf8e9f40f875125c3035062d2ca";
string ethKeyName = "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01";
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
......@@ -788,9 +645,9 @@ TEST_CASE("API test", "[api_test]") {
}
TEST_CASE("getServerStatus test", "[getServerStatus_test]") {
autoconfirm = true;
useHTTPS = 0;
initAll(false, true, init_SEK);
resetDB();
setOptions(false, false, true);
initAll(false, true);
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
REQUIRE(c.getServerStatus()["status"] == 0);
......@@ -799,10 +656,9 @@ TEST_CASE("getServerStatus test", "[getServerStatus_test]") {
void SendRPCRequest() {
cout << "Hello from thread " << this_thread::get_id() << endl;
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
reset_db();
int n = 16, t = 16;
......@@ -815,8 +671,8 @@ void SendRPCRequest() {
vector<string> pubShares(n);
vector<string> poly_names(n);
int schain_id = rand_gen();
int dkg_id = rand_gen();
int schain_id = randGen();
int dkg_id = randGen();
for (uint8_t i = 0; i < n; i++) {
EthKeys[i] = c.generateECDSAKey();
string polyName =
......@@ -825,7 +681,7 @@ void SendRPCRequest() {
poly_names[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
REQUIRE(VerifVects[i]["status"] == 0);
cout << "VV " << i << " " << VerifVects[i] << endl;
pubEthKeys.append(EthKeys[i]["publicKey"]);
}
......@@ -834,11 +690,9 @@ void SendRPCRequest() {
for (uint8_t k = 0; k < t; k++) {
for (uint8_t j = 0; j < 4; j++) {
string pubShare = VerifVects[i]["Verification Vector"][k][j].asString();
pubShares[i] += ConvertDecToHex(pubShare);
pubShares[i] += convertDecToHex(pubShare);
}
}
// cerr << "i is " << i << " pubShares[i] = " << pubShares[i] << endl;
// cerr << "length is" << pubShares[i].length() << endl;
}
......@@ -848,16 +702,13 @@ void SendRPCRequest() {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
// if ( i != j ){
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);
Json::Value verif = c.dkgVerification(pubShares[i], EthKeys[j]["keyName"].asString(), secretShare, t, n, j);
cout << verif;
k++;
cerr << "NOW K IS " << k << " i is " << i << " j is " << j << endl;
// REQUIRE( res );
// }
}
......@@ -878,44 +729,32 @@ void SendRPCRequest() {
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,
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);
REQUIRE(BLSSigShares[i]["status"] == 0);
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(make_shared<BLSSigShare>(sig));
// vector<string> pubKey_vect;
// for ( uint8_t j = 0; j < 4; j++){
// pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
// }
// 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] = make_shared<BLSPublicKeyShare>(pubKey);
}
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) );
}
TEST_CASE("ManySimultaneousThreads", "[many_threads_test]") {
autoconfirm = true;
useHTTPS = 0;
printDebugInfo = 1;
encryptKeys = 1;
resetDB();
setOptions(false, false, true);
initAll(false, true, init_SEK);
initAll(false, true);
vector<thread> threads;
int num_threads = 4;
......@@ -931,32 +770,28 @@ TEST_CASE("ManySimultaneousThreads", "[many_threads_test]") {
}
TEST_CASE("ecdsa API test", "[ecdsa_api_test]") {
autoconfirm = true;
printDebugInfo = 1;
useHTTPS = 0;
encryptKeys = 1;
resetDB();
setOptions(false, false, true);
initAll(false, true);
cerr << "ecdsa_api_test started" << endl;
initAll(false, true, init_SEK);
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
Json::Value genKey = c.generateECDSAKey();
cout << genKey << endl;
REQUIRE(genKey["status"].asInt() == 0);
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
cout << getPubKey << endl;
REQUIRE(getPubKey["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);
......@@ -983,20 +818,14 @@ TEST_CASE("ecdsa API test", "[ecdsa_api_test]") {
}
TEST_CASE("dkg API test", "[dkg_api_test]") {
autoconfirm = true;
printDebugInfo = 1;
useHTTPS = 0;
resetDB();
setOptions(false, false, true);
initAll(false, true);
cerr << "dkg_api_test started" << endl;
initAll(false, true, init_SEK);
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);
......@@ -1010,99 +839,92 @@ TEST_CASE("dkg API test", "[dkg_api_test]") {
// wrongName
Json::Value genPolyWrongName = c.generateDKGPoly("poly", 2);
REQUIRE(genPolyWrongName["status"].asInt() != 0);
cout << genPolyWrongName << endl;
Json::Value verifVectWrongName = c.getVerificationVector("poly", 2, 2);
REQUIRE(verifVectWrongName["status"].asInt() != 0);
cout << verifVectWrongName << endl;
Json::Value secretSharesWrongName = c.getSecretShare("poly", publicKeys, 2, 2);
REQUIRE(secretSharesWrongName["status"].asInt() != 0);
cout << secretSharesWrongName << endl;
// wrong_t
Json::Value genPolyWrong_t = c.generateDKGPoly(polyName, 33);
REQUIRE(genPolyWrong_t["status"].asInt() != 0);
cout << genPolyWrong_t << endl;
Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1, 2);
REQUIRE(verifVectWrong_t["status"].asInt() != 0);
cout << verifVectWrong_t << endl;
Json::Value secretSharesWrong_t = c.getSecretShare(polyName, publicKeys, 3, 3);
REQUIRE(secretSharesWrong_t["status"].asInt() != 0);
cout << secretSharesWrong_t << endl;
// wrong_n
Json::Value verifVectWrong_n = c.getVerificationVector(polyName, 2, 1);
REQUIRE(verifVectWrong_n["status"].asInt() != 0);
cout << verifVectWrong_n << endl;
Json::Value publicKeys1;
publicKeys1.append(
"505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2");
Json::Value secretSharesWrong_n = c.getSecretShare(polyName, publicKeys1, 2, 1);
REQUIRE(secretSharesWrong_n["status"].asInt() != 0);
cout << secretSharesWrong_n << endl;
//wrong number of publicKeys
Json::Value secretSharesWrongPkeys = c.getSecretShare(polyName, publicKeys, 2, 3);
REQUIRE(secretSharesWrongPkeys["status"].asInt() != 0);
cout << secretSharesWrongPkeys << endl;
//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);
REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
cout << verificationWrongSkeys << endl;
sgx_destroy_enclave(eid);
}
TEST_CASE("isPolyExists test", "[is_poly_test]") {
autoconfirm = true;
printDebugInfo = 1;
useHTTPS = 0;
resetDB();
setOptions(false, false, true);
initAll(false, true);
cerr << "is_poly_test started" << endl;
initAll(false, true, init_SEK);
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());
sgx_destroy_enclave(eid);
}
TEST_CASE("AES_DKG test", "[aes_dkg]") {
autoconfirm = true;
useHTTPS = 0;
printDebugInfo = 1;
encryptKeys = 1;
resetDB();
setOptions(false, false, true);
reset_db();
cerr << "test started" << endl;
initAll(false, true, init_SEK);
cerr << "Server inited" << endl;
initAll(false, true);
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
int n = 2, t = 2;
Json::Value EthKeys[n];
......@@ -1114,37 +936,30 @@ TEST_CASE("AES_DKG test", "[aes_dkg]") {
vector<string> pubShares(n);
vector<string> poly_names(n);
int schain_id = rand_gen();
int dkg_id = rand_gen();
int schain_id = randGen();
int dkg_id = randGen();
for (uint8_t i = 0; i < n; i++) {
EthKeys[i] = c.generateECDSAKey();
cerr << "after gen key" << endl;
string polyName =
"POLY:SCHAIN_ID:" + to_string(schain_id) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkg_id);
REQUIRE(EthKeys[i]["status"] == 0);
cout << c.generateDKGPoly(polyName, t);
c.generateDKGPoly(polyName, t);
poly_names[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
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);
cout << secretShares[i] << endl;
REQUIRE(secretShares[i]["status"] == 0);
for (uint8_t k = 0; k < t; k++)
for (uint8_t j = 0; j < 4; j++) {
string pubShare = VerifVects[i]["verificationVector"][k][j].asString();
pubShares[i] += ConvertDecToHex(pubShare);
pubShares[i] += convertDecToHex(pubShare);
}
// pSharesBad[i][0] = 'q';
// Json::Value wrongVerif = c.dkgVerification(pSharesBad[i], EthKeys[j]["keyName"].asString(), secretShare, t, n, j);
// res = wrongVerif["result"].asBool();
// REQUIRE(!res);
// cerr << "wrong verification " << wrongVerif << endl;
// }
}
int k = 0;
......@@ -1152,25 +967,22 @@ TEST_CASE("AES_DKG test", "[aes_dkg]") {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
// if ( i != j ){
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);
Json::Value verif = c.dkgVerification(pubShares[i], EthKeys[j]["keyName"].asString(), secretShare, t, n, j);
cout << verif;
bool res = verif["result"].asBool();
k++;
cerr << "NOW K IS " << k << " i is " << i << " j is " << j << endl;
REQUIRE(res);
// }
}
Json::Value complaintResponse = c.complaintResponse(poly_names[1], 0);
cout << complaintResponse << endl;
REQUIRE(complaintResponse["status"] == 0);
cerr << "share * G2 is " << complaintResponse["share*G2"].asString();
cerr << "DHKey is " << complaintResponse["dhKey"].asString();
BLSSigShareSet sigShareSet(t, n);
......@@ -1188,17 +1000,16 @@ TEST_CASE("AES_DKG test", "[aes_dkg]") {
for (int i = 0; i < t; i++) {
string endName = poly_names[i].substr(4);
string blsName = "BLS_KEY" + poly_names[i].substr(4);
cout << c.createBLSPrivateKey(blsName, EthKeys[i]["keyName"].asString(), poly_names[i], secShares_vect[i], t,
n);
c.createBLSPrivateKey(blsName, EthKeys[i]["keyName"].asString(), poly_names[i], secShares_vect[i], t, n);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
cout << pubBLSKeys[i] << endl;
REQUIRE(pubBLSKeys[i]["status"] == 0);
cerr << "BLS KEY SHARE NAME IS" << blsName << endl;
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
BLSSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
cout << BLSSigShares[i] << endl;
REQUIRE(BLSSigShares[i]["status"] == 0);
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(make_shared<BLSSigShare>(sig));
......@@ -1222,28 +1033,23 @@ TEST_CASE("AES_DKG test", "[aes_dkg]") {
}
TEST_CASE("bls_sign_api test", "[bls_sign]") {
autoconfirm = true;
useHTTPS = 0;
printDebugInfo = 1;
encryptKeys = 1;
cerr << "test started" << endl;
initAll(false, true, init_SEK);
cerr << "Server inited" << endl;
resetDB();
setOptions(false, false, true);
initAll(false, true);
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
string blsName = "BLS_KEY:SCHAIN_ID:323669558:NODE_ID:1:DKG_ID:338183455";
int n = 4, t = 4;
Json::Value pubBLSKey = c.getBLSPublicKeyShare(blsName);
REQUIRE(pubBLSKey["status"] == 0);
cout << pubBLSKey << endl;
Json::Value sign = c.blsSignMessageHash(blsName, hash, t, n, 1);
cout << sign << endl;
REQUIRE(sign["status"] == 0);
// vector<string> pubKey_vect;
......@@ -1253,130 +1059,37 @@ TEST_CASE("bls_sign_api test", "[bls_sign]") {
// BLSPublicKeyShare pubKey(make_shared<vector<string>>(pubKey_vect), t, n);
// REQUIRE( pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig) , t, n));
sgx_destroy_enclave(eid);
}
TEST_CASE("AES encrypt/decrypt", "[AES-encrypt-decrypt]") {
{
autoconfirm = true;
printDebugInfo = 1;
useHTTPS = 0;
resetDB();
setOptions(false, false, true);
initAll(false, true);
initAll(false, true, init_SEK);
//init_enclave();
int errStatus = -1;
vector<char> errMsg(BUF_LEN, 0);;
uint32_t enc_len;
string key = "123456789";
vector<uint8_t> encrypted_key(BUF_LEN,0);
int errStatus = -1;
vector<char> errMsg(BUF_LEN, 0);;
uint32_t enc_len;
string key = "123456789";
vector<uint8_t> encrypted_key(BUF_LEN, 0);
status = encrypt_key_aes(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &enc_len);
status = encrypt_key_aes(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &enc_len);
REQUIRE(status == 0);
cerr << "key encrypted with status " << status << " err msg " << errMsg.data() << endl;
REQUIRE(status == 0);
vector<char> decr_key(BUF_LEN, 0);
status = decrypt_key_aes(eid, &errStatus, errMsg.data(), encrypted_key.data(), enc_len, decr_key.data());
REQUIRE(status == 0);
cerr << "key encrypted with status " << status << " err msg " << errMsg.data() << endl;
cerr << "decrypted key is " << decr_key.data() << endl;
vector<char> decr_key(BUF_LEN, 0);
status = decrypt_key_aes(eid, &errStatus, errMsg.data(), encrypted_key.data(), enc_len, decr_key.data());
REQUIRE(key.compare(decr_key.data()) == 0);
sgx_destroy_enclave(eid);
}
}
REQUIRE(status == 0);
//TEST_CASE("BLS key import", "[bls-key-import]") {
// reset_db();
// init_all(false, true);
//
//
//
// auto result = importBLSKeyShareImpl(TEST_BLS_KEY_SHARE, TEST_BLS_KEY_NAME, 2, 2, 1);
//
// REQUIRE(result["status"] == 0);
//
// REQUIRE(result["encryptedKeyShare"] != "");
//
//
//TEST_CASE("BLS sign test", "[bls-sign]") {
//
// //init_all();
// init_enclave();
//
// char* encryptedKeyHex ="04000200000000000406ffffff02000000000000000000000b000000000000ff0000000000000000813f8390f6228a568e181a4dadb6508e3e66f5247175d65dbd0d8c7fbfa4df45000000f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000008000000000000000000000000000000000dc044ae0cd79faaf41e8a7abb412790476738a98b5b6ce95fa1a32db5551b0a0d867305f4de558c64fee730a1f62394633c7d4ca65e3a40b7883e89c2801c61918b01c5de8624a52963df6f4de8581bcbdd2f9b69720d4cc764e03a04c7a99314bfdb5d2d55deda2ca40cd691f093fb2ecbae24cdacdd4d5de93189c6dfd6792d7b95bd5e330aec3538e7a85d15793"; //encryptTestKey();
//
// REQUIRE(encryptedKeyHex != nullptr);
//
//
// // const char *hexHash = "001122334455667788" "001122334455667788" "001122334455667788" "001122334455667788";
// const char *hexHash = "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F";
//
// char* hexHashBuf = (char*) calloc(BUF_LEN, 1);
//
// strncpy(hexHashBuf, hexHash, BUF_LEN);
//
// char sig[BUF_LEN];
// auto result = sign(encryptedKeyHex, hexHashBuf, 2, 2, 1, sig);
//
// REQUIRE(result == true);
// printf("Signature is: %s \n", sig );
//
//}
//
//TEST_CASE("Server BLS sign test", "[bls-server-sign]") {
//
// reset_db();
//
// init_all(false, true);
//
//
// auto result = importBLSKeyShareImpl( TEST_BLS_KEY_SHARE, TEST_BLS_KEY_NAME, 2, 2, 1);
//
// REQUIRE(result["status"] == 0);
//
// REQUIRE(result["encryptedKeyShare"] != "");
//
// const char *hexHash = "001122334455667788" "001122334455667788" "001122334455667788" "001122334455667788";
//
// REQUIRE_NOTHROW(result = blsSignMessageHashImpl(TEST_BLS_KEY_NAME, hexHash,2,2,1));
//
// if (result["status"] != 0) {
// printf("Error message: %s", result["errorMessage"].asString().c_str());
// }
//
//
// REQUIRE(result["status"] == 0);
// REQUIRE(result["signatureShare"] != "");
//
// printf("Signature is: %s \n", result["signatureShare"].asString().c_str());
//
//}
REQUIRE(key.compare(decr_key.data()) == 0);
sgx_destroy_enclave(eid);
}
//TEST_CASE("KeysDB test", "[keys-db]") {
//
//
//
// reset_db();
// init_all();
//
//
// string key = TEST_BLS_KEY_SHARE;
// string value = TEST_BLS_KEY_SHARE;
//
//
//
// REQUIRE_THROWS(readKeyShare(key));
//
//
// writeKeyShare(key, value, 1, 2, 1);
//
// REQUIRE(readKeyShare(key) != nullptr);
//
//
//// put your test here
//}
#!/usr/bin/env python3
# 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 docker_test.py
# @author Stan Kladko
# @date 2020
#
import sys, getpass,os, subprocess, socket, time
username = getpass.getuser()
assert username == "root"
topDir = os.getcwd() + "/sgxwallet"
print("Starting build push")
print("Top directory is:" + topDir)
testList = ["[bls-key-encrypt]", "[dkg-gen]",
"[dkg-encr_sshares]",
"[dkg-verify]",
"[ecdsa_test]",
"[test_test]",
"[get_pub_ecdsa_key_test]",
"[bls_dkg]",
"[api_test]",
"[getServerStatus_test]",
"[many_threads_test]",
"[ecdsa_api_test]",
"[dkg_api_test]",
"[is_poly_test]",
# "[bls_sign]",
"[AES-encrypt-decrypt]"]
for t in testList:
print("Starting " + t)
assert subprocess.call(["./testw", t]) == 0
print("Ending " + t)
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