Unverified Commit 8465cb08 authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #78 from skalenetwork/SKALE-2274-review-disabled-tests

Skale 2274 review disabled tests
parents c2cde3e9 86e8b271
......@@ -27,23 +27,25 @@
#include <string>
#include <vector>
std::string gen_dkg_poly( int _t);
using namespace std;
std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyHex, int t, int n);
string gen_dkg_poly( int _t);
std::vector<std::string> splitString(const char* coeffs, const char symbol);
vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int n);
std::string trustedGetSecretShares(const std::string& _polyName, const char* _encryptedPolyHex, const std::vector<std::string>& _publicKeys, int _t, int _n);
vector<string> splitString(const char* coeffs, const char symbol);
string trustedGetSecretShares(const string& _polyName, const char* _encryptedPolyHex, const vector<string>& _publicKeys, int _t, int _n);
bool verifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
std::string decryptDHKey(const std::string& polyName, int ind);
string decryptDHKey(const string& polyName, int ind);
bool CreateBLSShare( const std::string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
bool CreateBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex);
vector<string> GetBLSPubKey(const char * encryptedKeyHex);
std::vector<std::string> mult_G2(const std::string& x);
vector<string> mult_G2(const string& x);
......
......@@ -29,7 +29,7 @@ RUN apt update && \
make -s -j$(nproc) sdk_install_pkg psw_install_pkg && \
./linux/installer/bin/sgx_linux_x64_sdk_2.5.100.49891.bin --prefix=/opt/intel && \
./linux/installer/bin/sgx_linux_x64_psw_2.5.100.49891.bin && \
cd .. && rm -rf linux-sgx/ && cd scripts && ./build.py && \
cd .. && rm -rf linux-sgx/ && cd scripts && ./build_deps.py && \
wget --progress=dot:mega -O - https://github.com/intel/dynamic-application-loader-host-interface/archive/072d233296c15d0dcd1fb4570694d0244729f87b.tar.gz | tar -xz && \
cd dynamic-application-loader-host-interface-072d233296c15d0dcd1fb4570694d0244729f87b && \
cmake . -DCMAKE_BUILD_TYPE=Release -DINIT_SYSTEM=SysVinit && \
......
......@@ -24,20 +24,15 @@
#include "spdlog/spdlog.h"
#include "sgxwallet_common.h"
#include "common.h"
#include "SGXException.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;
......@@ -58,6 +53,11 @@ level_enum Log::logLevelFromString(string &_s) {
}
void Log::handleSGXException(Json::Value& _result, SGXException& _e ) {
spdlog::error("Responding with JSON error:" + _e.errString);
_result["status"] = _e.status;
_result["errorMessage"] = _e.errString;
}
......@@ -30,7 +30,11 @@
#include <map>
#include <memory>
#include "json/json.h"
#include "spdlog/spdlog.h"
#include "SGXException.h"
#include "InvalidArgumentException.h"
#include "InvalidStateException.h"
......@@ -39,21 +43,18 @@
using namespace std;
class Exception;
#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ )
#define LOG( __SEVERITY__, __MESSAGE__ ) \
#define LOG(__SEVERITY__, __MESSAGE__) \
cerr << to_string(__SEVERITY__) << " " << __MESSAGE__ << " " << className( __PRETTY_FUNCTION__ ) << endl;
enum level_enum { trace, debug, info, warn, err };
enum level_enum {
trace, debug, info, warn, err
};
class Log {
......@@ -62,8 +63,16 @@ public:
level_enum globalLogLevel;
void setGlobalLogLevel( string& _s );
void setGlobalLogLevel(string &_s);
static level_enum logLevelFromString(string &_s);
static void handleSGXException(Json::Value &_result, SGXException &_e);
};
#define INIT_RESULT(__RESULT__) Json::Value __RESULT__; __RESULT__["status"] = 0; __RESULT__["errorMessage"] = "";
#define HANDLE_SGX_EXCEPTION(_RESULT_) catch (SGXException &__e) { Log::handleSGXException(_RESULT_, __e);}
#define LOCK(__M__) lock_guard<recursive_mutex> lock(__M__);
#endif
#define SGXWALLET_VERSION "1.47.1"
\ No newline at end of file
#define SGXWALLET_VERSION "1.48.1"
\ No newline at end of file
......@@ -41,9 +41,8 @@
#include "ServerInit.h"
#include "spdlog/spdlog.h"
#include "Log.h"
#include "common.h"
void setFullOptions(int _printDebugInfo,
int _printTraceInfo, int _useHTTPS, int _autoconfirm, int _encryptKeys) {
......@@ -83,7 +82,7 @@ SGXWalletServer::SGXWalletServer(AbstractServerConnector &_connector,
: AbstractStubServer(_connector, _type) {}
void SGXWalletServer::printDB() {
cout << "HERE ARE YOUR KEYS: " << endl;
cout << "PRINTING LEVELDB: " << endl;
class MyVisitor : public LevelDB::KeyVisitor {
public:
virtual void visitDBKey(const char *_data) {
......@@ -296,19 +295,13 @@ Json::Value SGXWalletServer::generateECDSAKeyImpl() {
result["PublicKey"] = keys.at(1);
result["keyName"] = keyName;
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::renameECDSAKeyImpl(const string &_keyName, const string &_tempKeyName) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
result["encryptedKey"] = "";
try {
......@@ -327,24 +320,22 @@ Json::Value SGXWalletServer::renameECDSAKeyImpl(const string &_keyName, const st
}
shared_ptr<string> key_ptr = readFromDb(_tempKeyName);
cerr << "new key name is " << _keyName << endl;
writeDataToDB(_keyName, *key_ptr);
LevelDB::getLevelDb()->deleteTempNEK(_tempKeyName);
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_keyName, const string &_messageHash) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
result["signature_v"] = "";
result["signature_r"] = "";
result["signature_s"] = "";
......@@ -384,19 +375,15 @@ Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_
result["signature_r"] = sign_vect.at(1);
result["signature_s"] = sign_vect.at(2);
} catch (SGXException &_e) {
cerr << "err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::getPublicECDSAKeyImpl(const string &_keyName) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
result["publicKey"] = "";
result["PublicKey"] = "";
......@@ -414,20 +401,14 @@ Json::Value SGXWalletServer::getPublicECDSAKeyImpl(const string &_keyName) {
result["PublicKey"] = publicKey;
result["publicKey"] = publicKey;
} catch (SGXException &_e) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::generateDKGPolyImpl(const string &_polyName, int _t) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
//result["encryptedPoly"] = "";
INIT_RESULT(result)
string encrPolyHex;
......@@ -442,12 +423,8 @@ Json::Value SGXWalletServer::generateDKGPolyImpl(const string &_polyName, int _t
encrPolyHex = gen_dkg_poly(_t);
writeDataToDB(_polyName, encrPolyHex);
//result["encryptedPoly"] = encrPolyHex;
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
......@@ -619,21 +596,14 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
LevelDB::getLevelDb()->deleteKey(shareG2_name);
}
} catch (SGXException &_e) {
//cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
try {
if (!checkName(_blsKeyName, "BLS_KEY")) {
......@@ -649,21 +619,15 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName)
result["BlsPublicKeyShare"][i] = public_key_vect.at(i);
}
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
//debug_print();
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _ind) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
try {
if (!checkName(_polyName, "POLY")) {
throw SGXException(INVALID_POLY_NAME, "Invalid polynomial name");
......@@ -677,82 +641,65 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int
result["dhKey"] = DHKey;
result["DHKey"] = DHKey;
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::multG2Impl(const string &_x) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
try {
vector<string> xG2_vect = mult_G2(_x);
auto xG2_vect = mult_G2(_x);
for (uint8_t i = 0; i < 4; i++) {
result["x*G2"][i] = xG2_vect.at(i);
}
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::isPolyExistsImpl(const string &_polyName) {
Json::Value result;
INIT_RESULT(result)
result["IsExist"] = false;
result["exists"] = false;
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"] = "";
if (poly_str_ptr != nullptr) {
result["IsExist"] = true;
result["exists"] = true;
}
} catch (SGXException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["IsExist"] = false;
result["exists"] = false;
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::getServerStatusImpl() {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
INIT_RESULT(result)
return result;
}
Json::Value SGXWalletServer::generateDKGPoly(const string &_polyName, int _t) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return generateDKGPolyImpl(_polyName, _t);
}
Json::Value SGXWalletServer::getVerificationVector(const string &_polynomeName, int _t, int _n) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return getVerificationVectorImpl(_polynomeName, _t, _n);
}
Json::Value SGXWalletServer::getSecretShare(const string &_polyName, const Json::Value &_publicKeys, int t, int n) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return getSecretShareImpl(_polyName, _publicKeys, t, n);
}
......@@ -760,41 +707,41 @@ Json::Value
SGXWalletServer::dkgVerification(const string &_publicShares, const string &ethKeyName, const string &SecretShare,
int t,
int n, int index) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return dkgVerificationImpl(_publicShares, ethKeyName, SecretShare, t, n, index);
}
Json::Value
SGXWalletServer::createBLSPrivateKey(const string &blsKeyName, const string &ethKeyName, const string &polyName,
const string &SecretShare, int t, int n) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return createBLSPrivateKeyImpl(blsKeyName, ethKeyName, polyName, SecretShare, t, n);
}
Json::Value SGXWalletServer::getBLSPublicKeyShare(const string &blsKeyName) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return getBLSPublicKeyShareImpl(blsKeyName);
}
Json::Value SGXWalletServer::generateECDSAKey() {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return generateECDSAKeyImpl();
}
Json::Value SGXWalletServer::renameECDSAKey(const string &_keyName, const string &_tmpKeyName) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return renameECDSAKeyImpl(_keyName, _tmpKeyName);
}
Json::Value SGXWalletServer::getPublicECDSAKey(const string &_keyName) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return getPublicECDSAKeyImpl(_keyName);
}
Json::Value SGXWalletServer::ecdsaSignMessageHash(int _base, const string &_keyShareName, const string &_messageHash) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
spdlog::debug("MessageHash first {}", _messageHash);
return ecdsaSignMessageHashImpl(_base, _keyShareName, _messageHash);
}
......@@ -803,38 +750,38 @@ Json::Value SGXWalletServer::ecdsaSignMessageHash(int _base, const string &_keyS
Json::Value
SGXWalletServer::importBLSKeyShare(const string &_keyShare, const string &_keyShareName, int _t, int _n,
int index) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return importBLSKeyShareImpl(_keyShare, _keyShareName, _t, _n, index);
}
Json::Value SGXWalletServer::blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n,
int _signerIndex) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return blsSignMessageHashImpl(_keyShareName, _messageHash, _t, _n, _signerIndex);
}
Json::Value SGXWalletServer::importECDSAKey(const string &_key, const string &_keyName) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return importECDSAKeyImpl(_key, _keyName);
}
Json::Value SGXWalletServer::complaintResponse(const string &polyName, int ind) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return complaintResponseImpl(polyName, ind);
}
Json::Value SGXWalletServer::multG2(const string &x) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return multG2Impl(x);
}
Json::Value SGXWalletServer::isPolyExists(const string &polyName) {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return isPolyExistsImpl(polyName);
}
Json::Value SGXWalletServer::getServerStatus() {
lock_guard<recursive_mutex> lock(m);
LOCK(m)
return getServerStatusImpl();
}
......
......@@ -106,10 +106,12 @@ void initEnclave(uint32_t _logLevel) {
}
int sgxServerInited = 0;
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
static int sgxServerInited;
cout << "Running sgxwallet version:" << SGXWALLET_VERSION << endl;
CHECK_STATE(sgxServerInited == 0)
sgxServerInited = 1;
......
# Building SGX wallet from source
### Install Intel SGX SDK
The Intel SGX SDK is required for both Intel SGX hardware platform and Intel SGX simulator mode.
The following instructions download the Intel SGX SDK 2.5 and installs it in
`/opt/intel/sgxsdk/` :
```bash
sudo mkdir -p /opt/intel
cd /opt/intel
sudo wget https://download.01.org/intel-sgx/linux-2.5/rhel7.4-server/sgx_linux_x64_psw_2.5.100.49891.bin
echo "yes" | sudo bash ./sgx_linux_x64_sdk_2.5.100.49891.bin
```
This installs the Intel SGX SDK in the recommended location,
`/opt/intel/sgxsdk` .
The Intel SGX OpenSSL library expects the SDK to be here by default.
After installing, source the Intel SGX SDK activation script to set
`$SGX_SDK`, `$PATH`, `$PKG_CONFIG_PATH`, and `$LD_LIBRARY_PATH`.
Append this line to your login shell script (`~/.bashrc` or similar):
```bash
source /opt/intel/sgxsdk/environment
echo "source /opt/intel/sgxsdk/environment" >>~/.bashrc
```
To learn more about Intel SGX read the
[Intel SGX SDK documentation](https://software.intel.com/en-us/sgx-sdk/documentation)
or visit the [Intel SGX homepage](https://software.intel.com/en-us/sgx).
Downloads are listed at
[Intel SGX Downloads for Linux](https://01.org/intel-software-guard-extensions/downloads).
<!-- SPDX-License-Identifier: (AGPL-3.0-only OR CC-BY-4.0) -->
This document describes how to build sgxwallet on Ubuntu 18.04.
## Clone this repository and its submodules
`git clone --recurse-submodules https://github.com/skalenetwork/sgxwallet.git`
## Install Prerequisites
```bash
sudo apt-get install build-essential make cmake gcc g++ yasm python libprotobuf10 flex bison automake libtool texinfo libgcrypt20-dev libgnutls28-dev
```
## Install required debian packages
```bash
cd scripts; sudo ./install_packages.sh; cd ..
```
## Build dependencies
Dependencies only need to be built once.
```bash
cd scripts; ./build.py; cd ..
cd scripts; ./build_deps.py; cd ..
```
## Set SGX environment variables
```bash
source sgx-sdk-build/sgxsdk/environment
```
## Configure and build sgxwallet
......@@ -80,7 +40,7 @@ Note: to run in simulation mode, add --enable-sgx-simulation flag when you run c
```bash
./configure --enable-sgx-simulation
make
```
## Build base Docker container
......
......@@ -71,6 +71,8 @@ JSON_LIBS_DIR = topDir + "/jsonrpc"
#subprocess.call(["git", "submodule", "update", "--init"])
print("Cleaning")
subprocess.call(["rm", "-f", "install-sh"])
subprocess.call(["rm", "-f", "compile"])
subprocess.call(["rm", "-f", "missing"])
......@@ -85,24 +87,37 @@ subprocess.call(["rm", "-rf", SDK_DIR])
assert subprocess.call(["cp", "configure.gmp", GMP_DIR + "/configure"]) == 0
print("Build LevelDB");
os.chdir(LEVELDB_DIR)
assert subprocess.call(["bash", "-c", "mkdir -p build"]) == 0
os.chdir(LEVELDB_BUILD_DIR)
assert subprocess.call(["bash", "-c", "cmake -DCMAKE_BUILD_TYPE=Release .. && cmake --build ."]) == 0
print("Build LibBLS");
os.chdir(BLS_DIR + "/deps")
assert subprocess.call(["bash", "-c", "./build.sh"]) == 0
os.chdir(BLS_DIR)
assert subprocess.call(["bash", "-c", "cmake -H. -Bbuild"]) == 0
os.chdir(BLS_DIR + "/build")
assert subprocess.call(["bash", "-c", "make"]) == 0
print("Build JSON");
os.chdir(JSON_LIBS_DIR)
assert subprocess.call(["bash", "-c", "./build.sh"]) == 0
print("Install Linux SDK");
os.chdir(SCRIPTS_DIR)
assert subprocess.call(["bash", "-c", "./sgx_linux_x64_sdk_2.5.100.49891.bin --prefix=" + topDir + "/sgx-sdk-build"]) == 0
print("Make GMP");
os.chdir(GMP_DIR)
assert subprocess.call(["bash", "-c", "./configure --prefix=" + TGMP_BUILD_DIR + " --disable-shared --enable-static --with-pic --enable-sgx --with-sgxsdk=" + SDK_DIR + "/sgxsdk"]) == 0
......
#!/bin/bash
sudo dpkg -i *.deb
sudo apt install ccache cmake flex bison yasm ccache autoconf texinfo libgcrypt20-dev libgnutls28-dev libtool pkg-config
sudo apt install -y build-essential make gcc g++ yasm python libprotobuf10 flex bison automake
sudo apt install -y ccache cmake ccache autoconf texinfo libgcrypt20-dev libgnutls28-dev libtool pkg-config
......@@ -57,7 +57,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SGXWalletServer.hpp"
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "stubclient.h"
......@@ -70,6 +70,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "common.h"
#include "stubclient.h"
#include "SGXWalletServer.h"
#include "testw.h"
using namespace jsonrpc;
using namespace std;
default_random_engine randGen((unsigned int) time(0));
......@@ -86,27 +92,33 @@ string stringFromFr(libff::alt_bn128_Fr &el) {
}
void usage() {
fprintf(stderr, "usage: sgxwallet\n");
exit(1);
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);
string result = hex;
int n_zeroes = numBytes * 2 - result.length();
result.insert(0, n_zeroes, '0');
return result;
}
sgx_launch_token_t token = {0};
sgx_enclave_id_t eid = 0;
sgx_status_t status;
int updated;
#define TEST_BLS_KEY_SHARE "4160780231445160889237664391382223604184857153814275770598791864649971919844"
#define TEST_BLS_KEY_NAME "SCHAIN:17:INDEX:5:KEY:1"
void resetDB() {
sgx_destroy_enclave(eid);
//string db_name = SGXDATA_FOLDER + WALLETDB_NAME;
REQUIRE(system("rm -rf "
WALLETDB_NAME) == 0);
REQUIRE(system("bash -c \"rm -rf " SGXDATA_FOLDER "* \"") == 0);
}
shared_ptr<string> encryptTestKey() {
shared_ptr <string> encryptTestKey() {
const char *key = TEST_BLS_KEY_SHARE;
int errStatus = -1;
......@@ -116,14 +128,162 @@ shared_ptr<string> encryptTestKey() {
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 make_shared<string>(encryptedKeyHex);
}
vector <libff::alt_bn128_Fr> splitStringToFr(const char *coeffs, const char symbol) {
string str(coeffs);
string delim;
delim.push_back(symbol);
vector <libff::alt_bn128_Fr> tokens;
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()) {
libff::alt_bn128_Fr coeff(token.c_str());
tokens.push_back(coeff);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}
vector <string> splitStringTest(const char *coeffs, const char symbol) {
string str(coeffs);
string delim;
delim.push_back(symbol);
vector <string> g2Strings;
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 coeff(token.c_str());
g2Strings.push_back(coeff);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return g2Strings;
}
libff::alt_bn128_G2 vectStringToG2(const vector <string> &G2_str_vect) {
libff::alt_bn128_G2 coeff = libff::alt_bn128_G2::zero();
coeff.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str());
coeff.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str());
coeff.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str());
coeff.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str());
coeff.Z.c0 = libff::alt_bn128_Fq::one();
coeff.Z.c1 = libff::alt_bn128_Fq::zero();
return coeff;
}
void sendRPCRequest() {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
int n = 16, t = 16;
Json::Value ethKeys[n];
Json::Value verifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value blsSigShares[n];
vector <string> pubShares(n);
vector <string> polyNames(n);
int schainID = randGen();
int dkgID = randGen();
for (uint8_t i = 0; i < n; i++) {
ethKeys[i] = c.generateECDSAKey();
string polyName =
"POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
c.generateDKGPoly(polyName, t);
polyNames[i] = polyName;
verifVects[i] = c.getVerificationVector(polyName, t, n);
REQUIRE(verifVects[i]["status"] == 0);
pubEthKeys.append(ethKeys[i]["publicKey"]);
}
for (uint8_t i = 0; i < n; i++) {
secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n);
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);
}
}
}
int k = 0;
vector <string> secShares(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
Json::Value verif = c.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
k++;
}
BLSSigShareSet sigShareSet(t, n);
string hash = SAMPLE_HASH;
auto hash_arr = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) {
throw SGXException(INVALID_HEX, "Invalid hash");
}
map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
for (int i = 0; i < t; i++) {
string endName = polyNames[i].substr(4);
string blsName = "BLS_KEY" + polyNames[i].substr(4);
string secretShare = secretShares[i]["secretShare"].asString();
c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
n);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
string hash = SAMPLE_HASH;
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
REQUIRE(blsSigShares[i]["status"] == 0);
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));
}
shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
}
void destroyEnclave() {
if (eid != 0) {
sgx_destroy_enclave(eid);
......@@ -132,16 +292,95 @@ void destroyEnclave() {
}
TEST_CASE("BLS key encrypt", "[bls-key-encrypt]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
auto key = encryptTestKey();
REQUIRE(key != nullptr);
class TestFixture {
public:
TestFixture() {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
}
~TestFixture() {
destroyEnclave();
}
};
TEST_CASE_METHOD(TestFixture, "ECDSA keygen and signature test", "[ecdsa-key-sig-gen]") {
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
vector <uint8_t> encrPrivKey(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0);
uint32_t encLen = 0;
//printf("before %p\n", pubKeyX);
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen, pubKeyX.data(),
pubKeyY.data());
REQUIRE(status == SGX_SUCCESS);
string hex = SAMPLE_HEX_HASH;
vector<char> signatureR(BUF_LEN, 0);
vector<char> signatureS(BUF_LEN, 0);
uint8_t signatureV = 0;
status = trustedEcdsaSign(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen, (unsigned char *) hex.data(),
signatureR.data(),
signatureS.data(), &signatureV, 16);
REQUIRE(status == SGX_SUCCESS);
}
TEST_CASE_METHOD(TestFixture, "ECDSA key gen", "[ecdsa-key-gen]") {
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
vector <uint8_t> encrPrivKey(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0);
uint32_t encLen = 0;
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen, pubKeyX.data(),
pubKeyY.data());
REQUIRE(status == SGX_SUCCESS);
}
TEST_CASE_METHOD(TestFixture, "ECDSA get public key", "[ecdsa-get-pub-key]") {
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;
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(),
pubKeyY.data());
REQUIRE(status == SGX_SUCCESS);
vector<char> receivedPubKeyX(BUF_LEN, 0);
vector<char> receivedPubKeyY(BUF_LEN, 0);
status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, receivedPubKeyX.data(),
receivedPubKeyY.data());
REQUIRE(status == SGX_SUCCESS);
}
/* Do later
TEST_CASE("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
TEST_CASE_METHOD("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
......@@ -165,352 +404,227 @@ TEST_CASE("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
printf("Decrypted key: %s\n", plaintextKey);
free(plaintextKey);
sgx_destroy_enclave(eid);
}
*/
TEST_CASE_METHOD(TestFixture, "ECDSA key gen API", "[ecdsa-key-gen-api]") {
TEST_CASE("DKG gen test", "[dkg-gen]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
vector<uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
uint32_t enc_len = 0;
try {
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &enc_len, 32);
REQUIRE(status == SGX_SUCCESS);
// printf("trustedGenDkgSecret completed with status: %d %s \n", errStatus, errMsg.data());
// printf("\n Length: %d \n", enc_len);
vector<char> secret(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0);
Json::Value genKey = c.generateECDSAKey();
cout << genKey << endl;
cout << c.ecdsaSignMessageHash(16, genKey["keyName"].asString(), SAMPLE_HASH);
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
uint32_t dec_len;
status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(),
(uint8_t *) secret.data(), &dec_len);
Json::Value publicKeys;
publicKeys.append(SAMPLE_DKG_PUB_KEY_1);
publicKeys.append(SAMPLE_DKG_PUB_KEY_2);
REQUIRE(status == SGX_SUCCESS);
// printf("\ntrustedDecryptDkgSecret completed with status: %d %s \n", errStatus, 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);
string share_big0 = "501e364a6ea516f4812b013bcc150cbb435a2c465c9fd525951264969d8441a986798fd3317c1c3e60f868bb26c4cff837d9185f4be6015d8326437cb5b69480495859cd5a385430ece51252acdc234d8dbde75708b600ac50b2974e813ee26bd87140d88647fcc44df7262bbba24328e8ce622cd627a15b508ffa0db9ae81e0e110fab42cfe40da66b524218ca3c8e5aa3363fbcadef748dc3523a7ffb95b8f5d8141a5163db9f69d1ab223494ed71487c9bb032a74c08a222d897a5e49a617";
string share_big = "03f749e2fcc28021895d757ec16d1636784446f5effcd3096b045136d8ab02657b32adc577f421330b81f5b7063df3b08a0621a897df2584b9046ca416e50ecc27e8c3277e981f7e650f8640289be128eecf0105f89a20e5ffb164744c45cf191d627ce9ab6c44e2ef96f230f2a4de742ea43b6f74b56849138026610b2d965605ececba527048a0f29f46334b1cec1d23df036248b24eccca99057d24764acee66c1a3f2f44771d0d237bf9d18c4177277e3ce3dc4e83686a2647fce1565ee0";
string share = share_big.substr(0, 192);
sgx_destroy_enclave(eid);
}
string publicShares = "1fc8154abcbf0c2ebf559571d7b57a8995c0e293a73d4676a8f76051a0d0ace30e00a87c9f087254c9c860c3215c4f11e8f85a3e8fae19358f06a0cbddf3df1924b1347b9b58f5bcb20958a19bdbdd832181cfa9f9e9fd698f6a485051cb47b829d10f75b6e227a7d7366dd02825b5718072cd42c39f0352071808622b7db6421b1069f519527e49052a8da6e3720cbda9212fc656eef945f5e56a4159c3b9622d883400460a9eff07fe1873f9b1ec50f6cf70098b9da0b90625b176f12329fa2ecc65082c626dc702d9cfb23a06770d4a2c7867e269efe84e3709b11001fb380a32d609855d1d46bc60f21140c636618b8ff55ed06d7788b6f81b498f96d3f9";
vector<libff::alt_bn128_Fr> SplitStringToFr(const char *coeffs, const char symbol) {
string str(coeffs);
string delim;
delim.push_back(symbol);
vector<libff::alt_bn128_Fr> tokens;
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()) {
libff::alt_bn128_Fr coeff(token.c_str());
tokens.push_back(coeff);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
Json::Value SecretShare;
SecretShare.append(share_big0);
SecretShare.append(share_big);
return tokens;
}
string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b7637092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76";
vector<string> SplitStringTest(const char *coeffs, const char symbol) {
libff::init_alt_bn128_params();
string str(coeffs);
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 coeff(token.c_str());
G2_strings.push_back(coeff);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return G2_strings;
}
string s_share = "13b871ad5025fed10a41388265b19886e78f449f758fe8642ade51440fcf850bb2083f87227d8fb53fdfb2854e2d0abec4f47e2197b821b564413af96124cd84a8700f8eb9ed03161888c9ef58d6e5896403de3608e634e23e92fba041aa283484427d0e6de20922216c65865cfe26edd2cf9cbfc3116d007710e8d82feafd9135c497bef0c800ca310ba6044763572681510dad5e043ebd87ffaa1a4cd45a899222207f3d05dec8110d132ad34c62d6a3b40bf8e9f40f875125c3035062d2ca";
string ethKeyName = SAMPLE_KEY_NAME;
libff::alt_bn128_G2 VectStringToG2(const vector<string> &G2_str_vect) {
libff::init_alt_bn128_params();
libff::alt_bn128_G2 coeff = libff::alt_bn128_G2::zero();
coeff.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str());
coeff.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str());
coeff.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str());
coeff.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str());
coeff.Z.c0 = libff::alt_bn128_Fq::one();
coeff.Z.c1 = libff::alt_bn128_Fq::zero();
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
}
return coeff;
}
TEST_CASE("DKG public shares test", "[dkg-pub-shares]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
libff::init_alt_bn128_params();
TEST_CASE_METHOD(TestFixture, "ECDSA key gen and sign", "[ecdsa-key-gen-sign-api]") {
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
uint32_t enc_len = 0;
unsigned t = 32, n = 32;
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, n);
REQUIRE(status == SGX_SUCCESS);
//printf("gen_dkg_public completed with status: %d %s \n", errStatus, errMsg);
Json::Value genKey = c.generateECDSAKey();
vector<char> errMsg1(BUF_LEN, 0);
REQUIRE(genKey["status"].asInt() == 0);
char colon = ':';
vector<char> public_shares(10000, 0);
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(),
encrypted_dkg_secret.data(), enc_len, public_shares.data(), t, n);
REQUIRE(status == SGX_SUCCESS);
// printf("\ntrustedGetPublicShares status: %d error %s \n\n", errStatus, 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<libff::alt_bn128_G2> pub_shares_G2;
for (u_int64_t i = 0; i < G2_strings.size(); i++) {
vector<string> coeff_str = splitString(G2_strings.at(i).c_str(), ':');
//libff::alt_bn128_G2 el = VectStringToG2(coeff_str);
//cerr << "pub_share G2 " << i+1 << " : " << endl;
//el.print_coordinates();
pub_shares_G2.push_back(VectStringToG2(coeff_str));
}
REQUIRE(getPubKey["status"].asInt() == 0);
REQUIRE(getPubKey["publicKey"].asString() == genKey["publicKey"].asString());
vector<char> secret(BUF_LEN, 0);
Json::Value ecdsaSign = c.ecdsaSignMessageHash(16, genKey["keyName"].asString(),
"0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encrypted_dkg_secret.data(),
(uint8_t *) secret.data(), &enc_len);
REQUIRE(status == SGX_SUCCESS);
//printf("\ntrustedDecryptDkgSecret completed with status: %d %s \n", errStatus, errMsg1.data());
REQUIRE(ecdsaSign["status"].asInt() == 0);
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");
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();
libff::alt_bn128_Fq x_c0_el = el.X.c0;
mpz_t x_c0;
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);
TEST_CASE_METHOD(TestFixture, "BLS key encrypt", "[bls-key-encrypt]") {
sgx_destroy_enclave(eid);
auto key = encryptTestKey();
REQUIRE(key != nullptr);
}
TEST_CASE("DKG encrypted secret shares test", "[dkg-encr-sshares]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "DKG gen test", "[dkg-gen]") {
vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int errStatus = 0;
uint32_t enc_len = 0;
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
// cerr << " poly generated" << endl;
uint32_t encLen = 0;
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data());
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32);
REQUIRE(status == SGX_SUCCESS);
// cerr << " poly set" << endl;
vector<uint8_t> encrPRDHKey(BUF_LEN, 0);
string pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
vector<char> secret(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0);
vector<char> s_shareG2(BUF_LEN, 0);
status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &enc_len, result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
uint32_t dec_len;
status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(),
(uint8_t *) secret.data(), &dec_len);
REQUIRE(status == SGX_SUCCESS);
// cerr << "secret share is " << result.data() << endl;
//sgx_destroy_enclave(eid);
}
TEST_CASE("DKG verification test", "[dkg-verify]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "DKG public shares test", "[dkg-pub-shares]") {
vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int errStatus = 0;
uint32_t enc_len = 0;
uint32_t encLen = 0;
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
unsigned t = 32, n = 32;
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, 2);
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n);
REQUIRE(status == SGX_SUCCESS);
// cerr << " poly generated" << endl;
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data());
REQUIRE(status == SGX_SUCCESS);
// cerr << " poly set" << endl;
vector<char> errMsg1(BUF_LEN, 0);
char colon = ':';
vector<char> pubShares(10000, 0);
vector<uint8_t> encrPrDHKey(BUF_LEN, 0);
status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(),
encryptedDKGSecret.data(), encLen, pubShares.data(), t, n);
string pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
vector<char> s_shareG2(BUF_LEN, 0);
vector <string> g2Strings = splitString(pubShares.data(), ',');
vector <libff::alt_bn128_G2> pubSharesG2;
for (u_int64_t i = 0; i < g2Strings.size(); i++) {
vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
pubSharesG2.push_back(vectStringToG2(coeffStr));
}
vector<char> secret(BUF_LEN, 0);
status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(), encrPrDHKey.data(), &enc_len, result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(),
(uint8_t *) secret.data(), &encLen);
REQUIRE(status == SGX_SUCCESS);
// printf(" trustedGetEncryptedSecretShare completed with status: %d %s \n", errStatus, errMsg.data());
// cerr << "secret share is " << result.data() << endl;
signatures::Dkg dkgObj(t, n);
vector <libff::alt_bn128_Fr> poly = splitStringToFr(secret.data(), colon);
vector <libff::alt_bn128_G2> pubSharesDkg = dkgObj.VerificationVector(poly);
for (uint32_t i = 0; i < pubSharesDkg.size(); i++) {
libff::alt_bn128_G2 el = pubSharesDkg.at(i);
el.to_affine_coordinates();
libff::alt_bn128_Fq x_c0_el = el.X.c0;
mpz_t x_c0;
mpz_init(x_c0);
x_c0_el.as_bigint().to_mpz(x_c0);
sgx_destroy_enclave(eid);
mpz_clear(x_c0);
}
REQUIRE(pubSharesG2 == pubSharesDkg);
}
TEST_CASE("ECDSA keygen and signature test", "[ecdsa]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "DKG encrypted secret shares test", "[dkg-encr-sshares]") {
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int errStatus = 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 encLen = 0;
uint32_t enc_len = 0;
vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
REQUIRE(status == SGX_SUCCESS);
//printf("before %p\n", pub_key_x);
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encr_pr_key.data(), &enc_len, pub_key_x.data(),
pub_key_y.data());
// printf("\nerrMsg %s\n", errMsg.data());
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg.data(), encryptedDKGSecret.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());
vector <uint8_t> encrPRDHKey(BUF_LEN, 0);
string hex = "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F";
// printf("hash length %d ", (int) hex.size());
vector<char> signature_r(BUF_LEN, 0);
vector<char> signature_s(BUF_LEN, 0);
uint8_t signature_v = 0;
string pub_keyB = SAMPLE_PUBLIC_KEY_B;
status = trustedEcdsaSign(eid, &errStatus, 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");
vector<char> s_shareG2(BUF_LEN, 0);
status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &encLen, result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
}
TEST_CASE("Test test", "[test]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "DKG verification test", "[dkg-verify]") {
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int errStatus = 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;
uint32_t encLen = 0;
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encr_pr_key.data(), &enc_len, pub_key_x.data(),
pub_key_y.data());
vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
REQUIRE(status == SGX_SUCCESS);
sgx_destroy_enclave(eid);
}
TEST_CASE("get public ECDSA key", "[get-pub-ecdsa-key]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
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;
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data());
REQUIRE(status == SGX_SUCCESS);
vector <uint8_t> encrPrDHKey(BUF_LEN, 0);
string pub_keyB = SAMPLE_PUBLIC_KEY_B;
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(),
pubKeyY.data());
vector<char> s_shareG2(BUF_LEN, 0);
status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(), encrPrDHKey.data(), &encLen, result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
vector<char> receivedPubKeyX(BUF_LEN, 0);
vector<char> receivedPubKeyY(BUF_LEN, 0);
status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, receivedPubKeyX.data(),
receivedPubKeyY.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);
}
/*
* ( "verification test", "[verify]" ) {
......@@ -529,90 +643,64 @@ TEST_CASE("get public ECDSA key", "[get-pub-ecdsa-key]") {
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);
string result = hex;
int n_zeroes = numBytes * 2 - result.length();
result.insert(0, n_zeroes, '0');
return result;
}
TEST_CASE("BLS_DKG test", "[bls-dkg]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "DKG_BLS test", "[dkg-bls]") {
HttpClient client("http://localhost:1029");
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
// cerr << "Client inited" << endl;
cerr << "1" << endl;
int n = 16, t = 16;
Json::Value etnKeys[n];
Json::Value VerifVects[n];
Json::Value verifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value blsSigShares[n];
vector<string> pubShares(n);
vector<string> polyNames(n);
vector <string> pubShares(n);
vector <string> polyNames(n);
int schain_id = randGen();
int dkg_id = randGen();
int schainID = randGen();
int dkgID = randGen();
for (uint8_t i = 0; i < n; i++) {
etnKeys[i] = c.generateECDSAKey();
string polyName =
"POLY:SCHAIN_ID:" + to_string(schain_id) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkg_id);
"POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
c.generateDKGPoly(polyName, t);
polyNames[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
REQUIRE(VerifVects[i]["status"] == 0);
verifVects[i] = c.getVerificationVector(polyName, t, n);
REQUIRE(verifVects[i]["status"] == 0);
pubEthKeys.append(etnKeys[i]["publicKey"]);
}
cerr << "2" << endl;
for (uint8_t i = 0; i < n; i++) {
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();
string pubShare = verifVects[i]["verificationVector"][k][j].asString();
REQUIRE(pubShare.length() > 60);
pubShares[i] += ConvertDecToHex(pubShare);
pubShares[i] += convertDecToHex(pubShare);
}
}
}
cerr << "3" << endl;
int k = 0;
vector<string> secShares_vect(n);
vector <string> secShares(n);
vector<string> pSharesBad(pubShares);
vector <string> pSharesBad(pubShares);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
secShares_vect[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
secShares[i] += 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++;
......@@ -629,299 +717,74 @@ TEST_CASE("BLS_DKG test", "[bls-dkg]") {
BLSSigShareSet sigShareSet(t, n);
cerr << "4" << endl;
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
string hash = SAMPLE_HASH;
auto hash_arr = make_shared<array<uint8_t, 32>>();
auto hash_arr = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) {
throw SGXException(INVALID_HEX, "Invalid hash");
}
map<size_t, shared_ptr<BLSPublicKeyShare>> coeffsPubKeysMap;
map <size_t, shared_ptr<BLSPublicKeyShare>> coeffsPubKeysMap;
for (int i = 0; i < t; i++) {
string endName = polyNames[i].substr(4);
string blsName = "BLS_KEY" + polyNames[i].substr(4);
string secretShare = secretShares[i]["secretShare"].asString();
c.createBLSPrivateKey(blsName, etnKeys[i]["keyName"].asString(), polyNames[i], secShares_vect[i], t, n);
c.createBLSPrivateKey(blsName, etnKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t, n);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
shared_ptr<string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
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> pubKeyVect;
vector <string> pubKeyVect;
for (uint8_t j = 0; j < 4; j++) {
pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
}
BLSPublicKeyShare pubKey(make_shared<vector<string>>(pubKeyVect), t, n);
BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKeyVect), t, n);
REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
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>>>(coeffsPubKeysMap), t, n);
shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
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]") {
setOptions(false, false, false, true);
initAll(0, false, true);
//HttpServer httpserver(1025);
//SGXWalletServer s(httpserver,
// JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
// s.StartListening();
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
// cerr << "Client inited" << endl;
try {
Json::Value genKey = c.generateECDSAKey();
cout << genKey << endl;
cout << c.ecdsaSignMessageHash(16, genKey["keyName"].asString(),
"0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
Json::Value publicKeys;
publicKeys.append(
"505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2");
publicKeys.append(
"378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25");
string share_big0 = "501e364a6ea516f4812b013bcc150cbb435a2c465c9fd525951264969d8441a986798fd3317c1c3e60f868bb26c4cff837d9185f4be6015d8326437cb5b69480495859cd5a385430ece51252acdc234d8dbde75708b600ac50b2974e813ee26bd87140d88647fcc44df7262bbba24328e8ce622cd627a15b508ffa0db9ae81e0e110fab42cfe40da66b524218ca3c8e5aa3363fbcadef748dc3523a7ffb95b8f5d8141a5163db9f69d1ab223494ed71487c9bb032a74c08a222d897a5e49a617";
string share_big = "03f749e2fcc28021895d757ec16d1636784446f5effcd3096b045136d8ab02657b32adc577f421330b81f5b7063df3b08a0621a897df2584b9046ca416e50ecc27e8c3277e981f7e650f8640289be128eecf0105f89a20e5ffb164744c45cf191d627ce9ab6c44e2ef96f230f2a4de742ea43b6f74b56849138026610b2d965605ececba527048a0f29f46334b1cec1d23df036248b24eccca99057d24764acee66c1a3f2f44771d0d237bf9d18c4177277e3ce3dc4e83686a2647fce1565ee0";
string share = share_big.substr(0, 192);
string publicShares = "1fc8154abcbf0c2ebf559571d7b57a8995c0e293a73d4676a8f76051a0d0ace30e00a87c9f087254c9c860c3215c4f11e8f85a3e8fae19358f06a0cbddf3df1924b1347b9b58f5bcb20958a19bdbdd832181cfa9f9e9fd698f6a485051cb47b829d10f75b6e227a7d7366dd02825b5718072cd42c39f0352071808622b7db6421b1069f519527e49052a8da6e3720cbda9212fc656eef945f5e56a4159c3b9622d883400460a9eff07fe1873f9b1ec50f6cf70098b9da0b90625b176f12329fa2ecc65082c626dc702d9cfb23a06770d4a2c7867e269efe84e3709b11001fb380a32d609855d1d46bc60f21140c636618b8ff55ed06d7788b6f81b498f96d3f9";
Json::Value SecretShare;
SecretShare.append(share_big0);
SecretShare.append(share_big);
string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b7637092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76";
string s_share = "13b871ad5025fed10a41388265b19886e78f449f758fe8642ade51440fcf850bb2083f87227d8fb53fdfb2854e2d0abec4f47e2197b821b564413af96124cd84a8700f8eb9ed03161888c9ef58d6e5896403de3608e634e23e92fba041aa283484427d0e6de20922216c65865cfe26edd2cf9cbfc3116d007710e8d82feafd9135c497bef0c800ca310ba6044763572681510dad5e043ebd87ffaa1a4cd45a899222207f3d05dec8110d132ad34c62d6a3b40bf8e9f40f875125c3035062d2ca";
string ethKeyName = "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01";
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
}
sgx_destroy_enclave(eid);
}
TEST_CASE("getServerStatus test", "[get-server-status]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
HttpClient client("http://localhost:1029");
TEST_CASE_METHOD(TestFixture, "Get ServerStatus", "[get-server-status]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
REQUIRE(c.getServerStatus()["status"] == 0);
sgx_destroy_enclave(eid);
}
void SendRPCRequest() {
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
int n = 16, t = 16;
Json::Value EthKeys[n];
Json::Value VerifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value BLSSigShares[n];
vector<string> pubShares(n);
vector<string> poly_names(n);
int schain_id = randGen();
int dkg_id = randGen();
for (uint8_t i = 0; i < n; i++) {
EthKeys[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;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
REQUIRE(VerifVects[i]["status"] == 0);
pubEthKeys.append(EthKeys[i]["publicKey"]);
}
for (uint8_t i = 0; i < n; i++) {
secretShares[i] = c.getSecretShare(poly_names[i], pubEthKeys, t, n);
for (uint8_t k = 0; k < t; k++) {
for (uint8_t j = 0; j < 4; j++) {
string pubShare = VerifVects[i]["Verification Vector"][k][j].asString();
pubShares[i] += ConvertDecToHex(pubShare);
}
}
}
int k = 0;
vector<string> secShares_vect(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
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);
k++;
}
BLSSigShareSet sigShareSet(t, n);
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
auto hash_arr = make_shared<array<uint8_t, 32>>();
uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) {
throw SGXException(INVALID_HEX, "Invalid hash");
}
map<size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
for (int i = 0; i < t; i++) {
string endName = poly_names[i].substr(4);
string blsName = "BLS_KEY" + poly_names[i].substr(4);
string secretShare = secretShares[i]["secretShare"].asString();
c.createBLSPrivateKey(blsName, EthKeys[i]["keyName"].asString(), poly_names[i], secShares_vect[i], t,
n);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
BLSSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
REQUIRE(BLSSigShares[i]["status"] == 0);
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));
}
shared_ptr<BLSSignature> commonSig = sigShareSet.merge();
}
TEST_CASE("ManySimultaneousThreads", "[many-threads-test]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
vector<thread> threads;
int num_threads = 4;
for (int i = 0; i < num_threads; i++) {
threads.push_back(thread(SendRPCRequest));
}
for (auto &thread : threads) {
thread.join();
}
sgx_destroy_enclave(eid);
}
TEST_CASE("ecdsa API test", "[ecdsa-api]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "DKG API test", "[dkg-api]") {
HttpClient client("http://localhost:1029");
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
Json::Value genKey = c.generateECDSAKey();
REQUIRE(genKey["status"].asInt() == 0);
Json::Value getPubKey = c.getPublicECDSAKey(genKey["keyName"].asString());
REQUIRE(getPubKey["status"].asInt() == 0);
REQUIRE(getPubKey["publicKey"].asString() == genKey["publicKey"].asString());
Json::Value ecdsaSign = c.ecdsaSignMessageHash(16, genKey["keyName"].asString(),
"0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
REQUIRE(ecdsaSign["status"].asInt() == 0);
// //wrong base
// Json::Value ecdsaSignWrongBase = c.ecdsaSignMessageHash(0, genKey["keyName"].asString(), "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
// cout << ecdsaSignWrongBase << endl;
// REQUIRE(ecdsaSignWrongBase["status"].asInt() != 0);
//
// //wrong keyName
// Json::Value ecdsaSignWrongKeyName = c.ecdsaSignMessageHash(0, "", "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db");
// cout << ecdsaSignWrongKeyName << endl;
// REQUIRE(ecdsaSignWrongKeyName["status"].asInt() != 0);
// Json::Value getPubKeyWrongKeyName = c.getPublicECDSAKey("keyName");
// REQUIRE(getPubKeyWrongKeyName["status"].asInt() != 0);
// cout << getPubKeyWrongKeyName << endl;
//
// //wrong hash
// Json::Value ecdsaSignWrongHash = c.ecdsaSignMessageHash(16, genKey["keyName"].asString(), "");
// cout << ecdsaSignWrongHash << endl;
// REQUIRE(ecdsaSignWrongHash["status"].asInt() != 0);
sgx_destroy_enclave(eid);
}
TEST_CASE("dkg API test", "[dkg-api]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
string polyName = SAMPLE_POLY_NAME;
string polyName = "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1";
Json::Value genPoly = c.generateDKGPoly(polyName, 2);
Json::Value publicKeys;
publicKeys.append(
"505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2");
publicKeys.append(
"378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25");
publicKeys.append(SAMPLE_DKG_PUB_KEY_1);
publicKeys.append(SAMPLE_DKG_PUB_KEY_2);
// wrongName
Json::Value genPolyWrongName = c.generateDKGPoly("poly", 2);
......@@ -940,7 +803,6 @@ TEST_CASE("dkg API test", "[dkg-api]") {
REQUIRE(genPolyWrong_t["status"].asInt() != 0);
Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1, 2);
REQUIRE(verifVectWrong_t["status"].asInt() != 0);
......@@ -955,8 +817,7 @@ TEST_CASE("dkg API test", "[dkg-api]") {
Json::Value publicKeys1;
publicKeys1.append(
"505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2");
publicKeys1.append(SAMPLE_DKG_PUB_KEY_1);
Json::Value secretSharesWrong_n = c.getSecretShare(polyName, publicKeys1, 2, 1);
REQUIRE(secretSharesWrong_n["status"].asInt() != 0);
......@@ -974,200 +835,173 @@ TEST_CASE("dkg API test", "[dkg-api]") {
REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
sgx_destroy_enclave(eid);
}
TEST_CASE("isPolyExists test", "[is-poly]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "PolyExists test", "[dkg-poly-exists]") {
HttpClient client("http://localhost:1029");
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
string polyName = "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1";
string polyName = SAMPLE_POLY_NAME;
Json::Value genPoly = c.generateDKGPoly(polyName, 2);
Json::Value polyExists = c.isPolyExists(polyName);
REQUIRE(polyExists["IsExist"].asBool());
REQUIRE(polyExists["exists"].asBool());
Json::Value polyDoesNotExist = c.isPolyExists("Vasya");
REQUIRE(!polyDoesNotExist["IsExist"].asBool());
REQUIRE(!polyDoesNotExist["exists"].asBool());
sgx_destroy_enclave(eid);
}
TEST_CASE("AES_DKG test", "[aes-dkg]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
HttpClient client("http://localhost:1029");
TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
int n = 2, t = 2;
Json::Value EthKeys[n];
Json::Value VerifVects[n];
Json::Value ethKeys[n];
Json::Value verifVects[n];
Json::Value pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value BLSSigShares[n];
vector<string> pubShares(n);
vector<string> poly_names(n);
Json::Value blsSigShares[n];
vector <string> pubShares(n);
vector <string> polyNames(n);
int schain_id = randGen();
int dkg_id = randGen();
int schainID = randGen();
int dkgID = randGen();
for (uint8_t i = 0; i < n; i++) {
EthKeys[i] = c.generateECDSAKey();
ethKeys[i] = c.generateECDSAKey();
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);
"POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
REQUIRE(ethKeys[i]["status"] == 0);
c.generateDKGPoly(polyName, t);
poly_names[i] = polyName;
VerifVects[i] = c.getVerificationVector(polyName, t, n);
polyNames[i] = polyName;
verifVects[i] = c.getVerificationVector(polyName, t, n);
pubEthKeys.append(EthKeys[i]["publicKey"]);
pubEthKeys.append(ethKeys[i]["publicKey"]);
}
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);
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);
string pubShare = verifVects[i]["verificationVector"][k][j].asString();
pubShares[i] += convertDecToHex(pubShare);
}
}
int k = 0;
vector<string> secShares_vect(n);
vector <string> secShares(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
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);
secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
Json::Value verif = c.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
bool res = verif["result"].asBool();
k++;
REQUIRE(res);
// }
}
Json::Value complaintResponse = c.complaintResponse(poly_names[1], 0);
Json::Value complaintResponse = c.complaintResponse(polyNames[1], 0);
REQUIRE(complaintResponse["status"] == 0);
BLSSigShareSet sigShareSet(t, n);
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
string hash = SAMPLE_HASH;
auto hash_arr = make_shared < array < uint8_t,
32 >> ();
auto hash_arr = make_shared<array<uint8_t, 32>>();
uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) {
throw SGXException(INVALID_HEX, "Invalid hash");
}
map<size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
for (int i = 0; i < t; i++) {
string endName = poly_names[i].substr(4);
string blsName = "BLS_KEY" + poly_names[i].substr(4);
c.createBLSPrivateKey(blsName, EthKeys[i]["keyName"].asString(), poly_names[i], secShares_vect[i], t, n);
string endName = polyNames[i].substr(4);
string blsName = "BLS_KEY" + polyNames[i].substr(4);
c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t, n);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
REQUIRE(pubBLSKeys[i]["status"] == 0);
string hash = "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
BLSSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
string hash = SAMPLE_HASH;
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n, i + 1);
REQUIRE(BLSSigShares[i]["status"] == 0);
REQUIRE(blsSigShares[i]["status"] == 0);
shared_ptr<string> sig_share_ptr = make_shared<string>(BLSSigShares[i]["signatureShare"].asString());
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> 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);
BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKey_vect), t, n);
REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
coeffs_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>>>(coeffs_pkeys_map), t, n);
shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
BLSPublicKey common_public(make_shared < map < size_t, shared_ptr < BLSPublicKeyShare >> > (coeffs_pkeys_map), t,
n);
REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
sgx_destroy_enclave(eid);
}
TEST_CASE("bls_sign_api test", "[bls-sign]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
HttpClient client("http://localhost:1029");
StubClient c(client, JSONRPC_CLIENT_V2);
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);
Json::Value sign = c.blsSignMessageHash(blsName, hash, t, n, 1);
REQUIRE(sign["status"] == 0);
destroyEnclave();
}
TEST_CASE("AES encrypt/decrypt", "[AES-encrypt-decrypt]") {
resetDB();
setOptions(false, false, false, true);
initAll(0, false, true);
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
int errStatus = -1;
vector<char> errMsg(BUF_LEN, 0);;
uint32_t enc_len;
string key = "123456789";
vector<uint8_t> encrypted_key(BUF_LEN, 0);
uint32_t encLen;
string key = SAMPLE_AES_KEY;
vector <uint8_t> encrypted_key(BUF_LEN, 0);
status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &enc_len);
status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen);
REQUIRE(status == 0);
vector<char> decr_key(BUF_LEN, 0);
status = trustedDecryptKeyAES(eid, &errStatus, errMsg.data(), encrypted_key.data(), enc_len, decr_key.data());
status = trustedDecryptKeyAES(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data());
REQUIRE(status == 0);
REQUIRE(key.compare(decr_key.data()) == 0);
destroyEnclave();
}
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypto]") {
vector <thread> threads;
int num_threads = 4;
for (int i = 0; i < num_threads; i++) {
threads.push_back(thread(sendRPCRequest));
}
for (auto &thread : threads) {
thread.join();
}
}
//
// Created by kladko on 06.05.20.
//
#ifndef SGXWALLET_TESTW_H
#define SGXWALLET_TESTW_H
#define TEST_BLS_KEY_SHARE "4160780231445160889237664391382223604184857153814275770598791864649971919844"
#define TEST_BLS_KEY_NAME "SCHAIN:17:INDEX:5:KEY:1"
#define SAMPLE_HASH "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db"
#define SAMPLE_HEX_HASH "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F"
#define SAMPLE_KEY_NAME "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01"
#define SAMPLE_AES_KEY "123456789"
#define SAMPLE_POLY_NAME "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1"
#define RPC_ENDPOINT "http://localhost:1029"
#define SAMPLE_PUBLIC_KEY_B "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475"
#define SAMPLE_DKG_PUB_KEY_1 "505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2"
#define SAMPLE_DKG_PUB_KEY_2 "378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25"
#endif //SGXWALLET_TESTW_H
......@@ -35,21 +35,23 @@ print("Starting build push")
print("Top directory is:" + topDir)
testList = ["[bls-key-encrypt]", "[dkg-gen]",
testList = ["[get-server-status]",
"[ecdsa-key-gen]",
"[ecdsa-key-sig-gen]",
"[ecdsa-get-pub-key]",
"[ecdsa-key-gen-api]",
"[ecdsa-key-gen-sign-api]",
"[bls-key-encrypt]",
"[dkg-gen]",
"[dkg-encr-sshares]",
"[dkg-verify]",
"[ecdsa]",
"[test]",
"[get-pub-ecdsa-key-test]",
"[bls-dkg]",
"[api]",
"[get-server-status]",
"[many-threads]",
"[ecdsa-api]",
"[dkg-api]",
"[is-poly]",
# "[bls-sign]",
"[aes-encrypt-decrypt]"]
"[dkg-bls]",
"[dkg-poly-exists]",
"[dkg-pub-shares]",
"[many-threads-crypto]",
"[aes-encrypt-decrypt]",
"[aes-dkg]"]
for t in testList:
......
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