Unverified Commit 75fa12ed authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #232 from skalenetwork/develop

Intel submission 3
parents 42772910 cfd149ab
name: Build, test and push SGX container
on: [push]
on:
workflow_dispatch:
push:
jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-18.04
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps:
- name: Fail, if older Github Actions machine. Click "Re-run jobs"
run: cat /proc/cpuinfo | grep avx512
- name: Login to docker
env:
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
- uses: actions/checkout@v1
- name: submodule update
run: git submodule update --init --recursive
- name: build
run: python3 scripts/docker_build.py Dockerfile sgxwallet ${GITHUB_SHA}
- name: deploy docker image
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
if: |
contains(github.ref, 'develop') || contains(github.ref, 'beta') ||
contains(github.ref, 'master') || contains(github.ref, 'stable') ||
contains(github.ref, 'SECURE_ENCLAVE_CHANGES')
run : |
export BRANCH=${GITHUB_REF##*/}
echo "Branch $BRANCH"
......@@ -29,4 +35,9 @@ jobs:
export RELEASE=true
echo "::set-env name=RELEASE::$RELEASE"
bash ./scripts/build_image.sh Dockerfile sgxwallet
bash ./scripts/publish_image.sh sgxwallet
\ No newline at end of file
bash ./scripts/publish_image.sh sgxwallet
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
name: Build base container
on:
workflow_dispatch:
push:
tags:
- build_base*
jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-18.04
env:
ACTIONS_ALLOW_UNSECURE_COMMMANDS: true
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps:
- name: Fail, if older Github Actions machine
run: cat /proc/cpuinfo | grep avx512
- name: Login to docker
env:
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
- uses: actions/checkout@v1
- name: submodule update
run: git submodule update --init --recursive
- name: Build the Docker image
run: docker build . --file DockerfileBase --tag skalenetwork/sgxwallet_base:latest
run: docker build . --file DockerfileBase --tag skalenetwork/sgxwallet_base:latest && docker push skalenetwork/sgxwallet_base:latest
- name: deploy docker image
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
run : |
......@@ -32,4 +34,4 @@ jobs:
export RELEASE=true
echo "::set-env name=RELEASE::$RELEASE"
bash ./scripts/build_image.sh DockerfileBase sgxwallet_base
bash ./scripts/publish_image.sh sgxwallet_base
\ No newline at end of file
bash ./scripts/publish_image.sh sgxwallet_base
name: Build, test and push release SGX container
on: [push]
on:
workflow_dispatch:
push:
jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-18.04
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps:
- name: Fail, if older Github Actions machine. Click "Re-run jobs"
run: cat /proc/cpuinfo | grep avx512
- name: Login to docker
env:
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
- uses: actions/checkout@v1
- name: submodule update
run: git submodule update --init --recursive
- name: build
run: python3 scripts/docker_build.py Dockerfile sgxwallet ${GITHUB_SHA}
- name: deploy docker image
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
- name: build and deploy docker image
if: |
contains(github.ref, 'develop') || contains(github.ref, 'beta') ||
contains(github.ref, 'master') || contains(github.ref, 'stable') ||
contains(github.ref, 'SECURE_ENCLAVE_CHANGES')
run : |
export BRANCH=${GITHUB_REF##*/}
echo "Branch $BRANCH"
......@@ -29,4 +34,6 @@ jobs:
export RELEASE=true
echo "::set-env name=RELEASE::$RELEASE"
bash ./scripts/build_image.sh DockerfileRelease sgxwallet_release
bash ./scripts/publish_image.sh sgxwallet_release
\ No newline at end of file
bash ./scripts/publish_image.sh sgxwallet_release
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
name: Build, test and push sim mode container
on: [push]
on:
workflow_dispatch:
push:
jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-18.04
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps:
- name: Fail, if older Github Actions machine. Click "Re-run jobs"
run: cat /proc/cpuinfo | grep avx512
- name: Check that /dev/urandom exists
run: ls /dev/urandom
- name: Login to docker
env:
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
- uses: actions/checkout@v1
- name: submodule update
run: git submodule update --init --recursive
- name: build container for release
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
run: |
export BRANCH=${GITHUB_REF##*/}
echo "Branch $BRANCH"
export VERSION=$(cat VERSION)
echo "Version $VERSION"
export VERSION=$(bash ./scripts/calculate_version.sh $BRANCH $VERSION)
echo "::set-env name=VERSION::$VERSION"
echo "Version $VERSION"
bash ./scripts/build_image.sh DockerfileSimulation sgxwallet_sim
- name: build container for testing
run: python3 scripts/docker_build.py DockerfileSimulation sgxwalletsim ${GITHUB_SHA}
- name: test
run: python3 scripts/docker_test.py DockerfileSimulation sgxwalletsim
- name: deploy docker image
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
- name: build and deploy docker image
if: |
contains(github.ref, 'develop') || contains(github.ref, 'beta') ||
contains(github.ref, 'master') || contains(github.ref, 'stable') ||
contains(github.ref, 'SECURE_ENCLAVE_CHANGES')
run : |
export BRANCH=${GITHUB_REF##*/}
echo "Branch $BRANCH"
export VERSION=${{env.VERSION}}
echo "::set-env name=VERSION::$VERSION"
echo "Version $VERSION"
export RELEASE=true
echo "::set-env name=RELEASE::$RELEASE"
bash ./scripts/publish_image.sh sgxwallet_sim
export BRANCH=${GITHUB_REF##*/}
echo "Branch $BRANCH"
export VERSION=$(cat VERSION)
echo "Version $VERSION"
export VERSION=$(bash ./scripts/calculate_version.sh $BRANCH $VERSION)
echo "::set-env name=VERSION::$VERSION"
echo "Version $VERSION"
export RELEASE=true
echo "::set-env name=RELEASE::$RELEASE"
bash ./scripts/build_image.sh DockerfileSimulation sgxwallet_sim
bash ./scripts/publish_image.sh sgxwallet_sim
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
- name: Create Release
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
id: create_release
......
......@@ -75,23 +75,22 @@ int char2int(char _input) {
return -1;
}
void carray2Hex(const unsigned char *d, uint64_t _len, char *_hexArray,
uint64_t _hexArrayLen) {
vector<char> carray2Hex(const unsigned char *d, uint64_t _len) {
CHECK_STATE(d);
CHECK_STATE(_hexArray);
vector<char> _hexArray( 2 * _len + 1);
char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
CHECK_STATE(_hexArrayLen > 2 * _len);
for (uint64_t 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;
return _hexArray;
}
......@@ -166,8 +165,7 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto hash = make_shared < array < uint8_t,
32 >> ();
auto hash = make_shared < array < uint8_t, 32 >> ();
uint64_t binLen;
......@@ -265,9 +263,7 @@ string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key
HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());
SAFE_CHAR_BUF(resultBuf, 2 * BUF_LEN + 1);
carray2Hex(encryptedKey->data(), encryptedLen, resultBuf, 2 * BUF_LEN + 1);
vector<char> resultBuf = carray2Hex(encryptedKey->data(), encryptedLen);
return string(resultBuf);
return string(resultBuf.begin(), resultBuf.end());
}
......@@ -33,13 +33,14 @@
#include "stddef.h"
#include "stdint.h"
#include <string>
#include <vector>
EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t, size_t n, char* _sig);
EXTERNC int char2int(char _input);
EXTERNC void carray2Hex(const unsigned char *d, uint64_t , char* _hexArray,
uint64_t _hexArrayLen);
EXTERNC std::vector<char> carray2Hex(const unsigned char *d, uint64_t _len);
EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, uint64_t _max_length );
......
......@@ -67,10 +67,9 @@ string ConvertToString(T field_elem, int base = 10) {
SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, base) + 2);
mpz_get_str(arr, base, t);
mpz_clear(t);
mpz_clear(t);
string output = arr;
return output;
}
......@@ -82,8 +81,7 @@ string convertHexToDec(const string &hex_str) {
try {
if (mpz_set_str(dec, hex_str.c_str(), 16) == -1) {
mpz_clear(dec);
return ret;
goto clean;
}
SAFE_CHAR_BUF(arr, mpz_sizeinbase(dec, 10) + 2);
......@@ -97,6 +95,10 @@ string convertHexToDec(const string &hex_str) {
throw SGXException(UNKNOWN_ERROR, "");
}
clean:
mpz_clear(dec);
return ret;
}
......@@ -144,17 +146,18 @@ string gen_dkg_poly(int _t) {
uint64_t length = enc_len;;
vector<char> hexEncrPoly(BUF_LEN, 0);
CHECK_STATE(encrypted_dkg_secret.size() >= length);
carray2Hex(encrypted_dkg_secret.data(), length, hexEncrPoly.data(), BUF_LEN);
vector<char> hexEncrPoly = carray2Hex(encrypted_dkg_secret.data(), length);
string result(hexEncrPoly.data());
return result;
}
vector <vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n) {
vector <vector<string>> get_verif_vect(const string& encryptedPolyHex, int t, int n) {
auto encryptedPolyHexPtr = encryptedPolyHex.c_str();
CHECK_STATE(encryptedPolyHex);
CHECK_STATE(encryptedPolyHexPtr);
vector<char> errMsg(BUF_LEN, 0);
......@@ -166,7 +169,7 @@ vector <vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int
vector <uint8_t> encrDKGPoly(2 * BUF_LEN, 0);
if (!hex2carray(encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) {
if (!hex2carray(encryptedPolyHexPtr, &encLen, encrDKGPoly.data(), 6100)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
}
......@@ -182,15 +185,39 @@ vector <vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
vector <string> g2Strings = splitString(pubShares.data(), ',');
vector <vector<string>> pubSharesVect;
vector <vector<string>> pubSharesVect(t);
for (uint64_t i = 0; i < g2Strings.size(); i++) {
vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
pubSharesVect.push_back(coeffStr);
pubSharesVect[i] = coeffStr;
}
return pubSharesVect;
}
vector <vector<string>> getVerificationVectorMult(const std::string& encryptedPolyHex, int t, int n, size_t ind) {
auto verificationVector = get_verif_vect(encryptedPolyHex, t, n);
vector<vector<string>> result(t);
for (int i = 0; i < t; ++i) {
libff::alt_bn128_G2 current_coefficient;
current_coefficient.X.c0 = libff::alt_bn128_Fq(verificationVector[i][0].c_str());
current_coefficient.X.c1 = libff::alt_bn128_Fq(verificationVector[i][1].c_str());
current_coefficient.Y.c0 = libff::alt_bn128_Fq(verificationVector[i][2].c_str());
current_coefficient.Y.c1 = libff::alt_bn128_Fq(verificationVector[i][3].c_str());
current_coefficient.Z = libff::alt_bn128_Fq2::one();
current_coefficient = libff::power(libff::alt_bn128_Fr(ind + 1), i) * current_coefficient;
current_coefficient.to_affine_coordinates();
auto g2_str = convertG2ToString(current_coefficient);
result[i] = splitString(g2_str.c_str(), ':');
}
return result;
}
string
getSecretShares(const string &_polyName, const char *_encryptedPolyHex, const vector <string> &_publicKeys,
int _t,
......@@ -199,7 +226,7 @@ getSecretShares(const string &_polyName, const char *_encryptedPolyHex, const ve
CHECK_STATE(_encryptedPolyHex);
vector<char> hexEncrKey(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
vector <uint8_t> encrDKGPoly(BUF_LEN, 0);
int errStatus = 0;
uint64_t encLen = 0;
......@@ -211,11 +238,69 @@ getSecretShares(const string &_polyName, const char *_encryptedPolyHex, const ve
sgx_status_t status = SGX_SUCCESS;
READ_LOCK(initMutex);
READ_LOCK(sgxInitMutex);
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen);
string result;
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
for (int i = 0; i < _n; i++) {
vector <uint8_t> encryptedSkey(BUF_LEN, 0);
uint64_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);
sgx_status_t status = SGX_SUCCESS;
status = trustedGetEncryptedSecretShare(eid, &errStatus,
errMsg.data(),
encrDKGPoly.data(), encLen,
encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n,
i + 1);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
result += string(currentShare.data());
hexEncrKey = carray2Hex(encryptedSkey.data(), decLen);
string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":";
string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data());
SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data());
}
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
SGXWalletServer::writeDataToDB(encryptedSecretShareName, result);
return result;
}
string getSecretSharesV2(const string& _polyName, const char* _encryptedPolyHex, const vector<string>& _publicKeys, int _t, int _n) {
CHECK_STATE(_encryptedPolyHex);
vector<char> hexEncrKey(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
vector <uint8_t> encrDKGPoly(BUF_LEN, 0);
int errStatus = 0;
uint64_t encLen = 0;
if (!hex2carray(_encryptedPolyHex, &encLen, encrDKGPoly.data(), BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
}
sgx_status_t status = SGX_SUCCESS;
READ_LOCK(sgxInitMutex);
string result;
......@@ -234,26 +319,22 @@ getSecretShares(const string &_polyName, const char *_encryptedPolyHex, const ve
spdlog::debug("pubKeyB is {}", pub_keyB);
sgx_status_t status = SGX_SUCCESS;
status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
status = trustedGetEncryptedSecretShareV2(eid, &errStatus,
errMsg.data(),
encrDKGPoly.data(), encLen,
encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n,
i + 1);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
spdlog::debug("cur_share is {}", currentShare.data());
result += string(currentShare.data());
spdlog::debug("dec len is {}", decLen);
carray2Hex(encryptedSkey.data(), decLen, hexEncrKey.data(), BUF_LEN);
hexEncrKey = carray2Hex(encryptedSkey.data(), decLen);
string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":";
spdlog::debug("hexEncr DH Key: { }", hexEncrKey.data());
spdlog::debug("name to write to db is {}", dhKeyName);
string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
spdlog::debug("name to write to db is {}", shareG2_name);
spdlog::debug("s_shareG2: {}", sShareG2.data());
SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data());
SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data());
......@@ -301,6 +382,42 @@ verifyShares(const char *publicShares, const char *encr_sshare, const char *encr
return result;
}
bool
verifySharesV2(const char *publicShares, const char *encr_sshare, const char *encryptedKeyHex, int t, int n, int ind) {
CHECK_STATE(publicShares);
CHECK_STATE(encr_sshare);
CHECK_STATE(encryptedKeyHex);
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
uint64_t decKeyLen = 0;
int result = 0;
SAFE_UINT8_BUF(encr_key, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
}
SAFE_CHAR_BUF(pshares, 8193);
strncpy(pshares, publicShares, strlen(publicShares));
sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedDkgVerifyV2(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
ind, &result);
RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
if (result == 2) {
throw SGXException(INVALID_HEX, "Invalid public shares");
}
return result;
}
bool createBLSShare(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) {
CHECK_STATE(s_shares);
......@@ -325,11 +442,9 @@ bool createBLSShare(const string &blsKeyName, const char *s_shares, const char *
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
SAFE_CHAR_BUF(hexBLSKey, 2 * BUF_LEN)
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey, 2 * BUF_LEN);
vector<char> hexBLSKey = carray2Hex(encr_bls_key, enc_bls_len);
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey);
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data());
return true;
......@@ -426,24 +541,25 @@ string decryptDHKey(const string &polyName, int ind) {
shared_ptr <string> hexEncrKeyPtr = SGXWalletServer::readFromDb(DH_key_name, "DKG_DH_KEY_");
spdlog::debug("encr DH key is {}", *hexEncrKeyPtr);
spdlog::debug("encr DH key length is {}", hexEncrKeyPtr->length());
vector<char> hexEncrKey(2 * BUF_LEN, 0);
uint64_t dhEncLen = 0;SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN);
uint64_t dhEncLen = 0;
SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN)
if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey, BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid hexEncrKey");
}
spdlog::debug("encr DH key length is {}", dhEncLen);
spdlog::debug("hex encr DH key length is {}", hexEncrKeyPtr->length());
SAFE_CHAR_BUF(DHKey, ECDSA_SKEY_LEN);
SAFE_CHAR_BUF(DHKey, ECDSA_SKEY_LEN)
sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data())
return DHKey;
}
......
......@@ -33,14 +33,20 @@ using namespace std;
string gen_dkg_poly( int _t);
vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int n);
vector <vector<string>> get_verif_vect(const string& encryptedPolyHex, int t, int n);
vector <vector<string>> getVerificationVectorMult(const std::string& encryptedPolyHex, int t, int n, size_t ind);
vector<string> splitString(const char* coeffs, const char symbol);
string getSecretShares(const string& _polyName, const char* _encryptedPolyHex, const vector<string>& _publicKeys, int _t, int _n);
string getSecretSharesV2(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);
bool verifySharesV2(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
string decryptDHKey(const string& polyName, int ind);
bool createBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
......
......@@ -10,4 +10,6 @@ RUN bash -c "make -j$(nproc)"
RUN ccache -sz
RUN mkdir -p /usr/src/sdk/sgx_data
COPY docker/start.sh ./
RUN rm -rf /usr/src/sdk/sgx-sdk-build/
RUN rm /opt/intel/sgxsdk/lib64/*_sim.so
ENTRYPOINT ["/usr/src/sdk/start.sh"]
......@@ -14,4 +14,10 @@ RUN cd scripts && ./sign_enclave.bash
RUN ccache -sz
RUN mkdir -p /usr/src/sdk/sgx_data
COPY docker/start.sh ./
RUN rm -rf /usr/src/sdk/sgx-sdk-build/
RUN rm /opt/intel/sgxsdk/lib64/*_sim.so
RUN rm /usr/src/sdk/secure_enclave/secure_enclave*.so
RUN cd /usr/src/sdk/secure_enclave && \
curl --output secure_enclave.signed.so \
https://raw.githubusercontent.com/skalenetwork/signed_sgx_enclaves/master/secure_enclave_signed.so.1
ENTRYPOINT ["/usr/src/sdk/start.sh"]
FROM skalenetwork/sgxwallet_base:latest
RUN apt update && apt install -y curl secure-delete
RUN apt update && apt install -y curl secure-delete
RUN ccache -sz
......@@ -15,5 +15,6 @@ RUN ./autoconf.bash && \
mkdir -p /usr/src/sdk/sgx_data
COPY docker/start.sh ./
RUN rm -rf /usr/src/sdk/sgx-sdk-build/
ENTRYPOINT ["/usr/src/sdk/start.sh"]
......@@ -69,19 +69,14 @@ vector <string> genECDSAKey() {
vector <string> keys(3);
vector<char> hexEncrKey(BUF_LEN * 2, 0);
carray2Hex(encr_pr_key.data(), enc_len, hexEncrKey.data(),
BUF_LEN * 2);
vector<char> hexEncrKey = carray2Hex(encr_pr_key.data(), enc_len);
keys.at(0) = hexEncrKey.data();
keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data());
vector<unsigned char> randBuffer(32, 0);
fillRandomBuffer(randBuffer);
vector<char> rand_str(BUF_LEN, 0);
carray2Hex(randBuffer.data(), 32, rand_str.data(), BUF_LEN);
vector<char> rand_str = carray2Hex(randBuffer.data(), 32);
keys.at(2) = rand_str.data();
......@@ -233,3 +228,30 @@ vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *ha
return signatureVector;
}
string encryptECDSAKey(const string& _key) {
vector<char> key(BUF_LEN, 0);
for (size_t i = 0; i < _key.size(); ++i) {
key[i] = _key[i];
}
vector<uint8_t> encryptedKey(BUF_LEN, 0);
int errStatus = 0;
vector<char> errString(BUF_LEN, 0);
uint64_t enc_len = 0;
sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedEncryptKey(eid, &errStatus, errString.data(), key.data(),
encryptedKey.data(), &enc_len);
RESTART_END
if (status != 0) {
throw SGXException(status, string("Could not encrypt ECDSA key: " + string(errString.begin(), errString.end())).c_str());
}
vector<char> hexEncrKey = carray2Hex(encryptedKey.data(), enc_len);
return string(hexEncrKey.begin(), hexEncrKey.end());
}
......@@ -35,5 +35,7 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex);
vector<string> ecdsaSignHash(const std::string& encryptedKeyHex, const char* hashHex, int base);
string encryptECDSAKey(const string& key);
#endif //SGXD_ECDSACRYPTO_H
......@@ -103,7 +103,7 @@ sgxwallet_LDADD=-l$(SGX_URTS_LIB) -l$(SGX_UAE_SERVICE_LIB) -LlibBLS/deps/deps_in
-l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ldl -l:libsgx_capable.a -l:libsgx_tprotected_fs.a \
-ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd \
-lboost_system -lboost_thread -lgnutls -lgcrypt -lcurl -lssl -lcrypto -lz -lpthread -lstdc++fs
-lboost_system -lboost_thread -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -lstdc++fs
testw_SOURCES=testw.cpp $(COMMON_SRC)
......@@ -115,4 +115,4 @@ cert_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentExcep
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 \
-l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lcurl -lssl -lcrypto -lz -lpthread -ldl
-l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -ldl
......@@ -65,15 +65,13 @@ void create_test_key() {
sgx_status_t status = SGX_SUCCESS;
{
READ_LOCK(initMutex);
READ_LOCK(sgxInitMutex);
status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len);
}
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_key, enc_len, hexEncrKey.data(), 2 * enc_len + 1);
vector<char> hexEncrKey = carray2Hex(encrypted_key, enc_len);
LevelDB::getLevelDb()->writeDataUnique("TEST_KEY", hexEncrKey.data());
}
......@@ -98,7 +96,7 @@ void validate_SEK() {
sgx_status_t status = SGX_SUCCESS;
{
READ_LOCK(initMutex);
READ_LOCK(sgxInitMutex);
status = trustedDecryptKey(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data());
}
......@@ -128,7 +126,7 @@ shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) {
sgx_status_t status = SGX_SUCCESS;
{
READ_LOCK(initMutex);
READ_LOCK(sgxInitMutex);
status = trustedSetSEKBackup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l,
SEK.c_str());
}
......@@ -167,9 +165,7 @@ void gen_SEK() {
throw SGXException(-1, "strnlen(SEK,33) != 32");
}
vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_SEK.data(), enc_len, hexEncrKey.data(), 2 * enc_len + 1);
vector<char> hexEncrKey = carray2Hex(encrypted_SEK.data(), enc_len);
spdlog::info(string("Encrypted storage encryption key:") + hexEncrKey.data());
......@@ -209,11 +205,17 @@ void gen_SEK() {
}
void reinitEnclave() {
// unfortunately process needs to be restarted to reinit enclave
// exiting with error code 3 (SGX_OUT_OF_MEMORY), so docker container can restart the
// wallet
exit(3);
static std::atomic<int> isSgxWalletExiting(0);
void safeExit() {
// this is to make sure exit is only called once if called from multiple threads
auto previousValue = isSgxWalletExiting.exchange(1);
if (previousValue != 1)
exit(3);
}
void setSEK(shared_ptr <string> hex_encrypted_SEK) {
......@@ -281,10 +283,7 @@ void enter_SEK() {
auto encrypted_SEK = check_and_set_SEK(sek);
vector<char> hexEncrKey(BUF_LEN, 0);
carray2Hex(encrypted_SEK->data(), encrypted_SEK->size(), hexEncrKey.data(),
BUF_LEN);
vector<char> hexEncrKey = carray2Hex(encrypted_SEK->data(), encrypted_SEK->size());
spdlog::info("Got sealed storage encryption key.");
......
......@@ -47,7 +47,8 @@ EXTERNC void initSEK();
EXTERNC void setSEK();
EXTERNC void reinitEnclave();
EXTERNC void safeExit();
......
......@@ -54,7 +54,7 @@
using namespace std;
std::shared_timed_mutex initMutex;
std::shared_timed_mutex sgxInitMutex;
uint64_t initTime;
void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) {
......@@ -111,8 +111,19 @@ void SGXWalletServer::printDB() {
LevelDB::getLevelDb()->visitKeys(&v, 100000000);
}
#ifdef SGX_HW_SIM
#define NUM_THREADS 16
#else
#define NUM_THREADS 64
#endif
int SGXWalletServer::initHttpsServer(bool _checkCerts) {
spdlog::info("Entering {}", __FUNCTION__);
spdlog::info("Initing server, number of threads: {}", NUM_THREADS);
string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem";
string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key";
......@@ -147,14 +158,9 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
}
int numThreads = 64;
#if SGX_MODE == SIM
numThreads = 16;
#endif
httpServer = make_shared<HttpServer>(BASE_PORT, certPath, keyPath, rootCAPath, _checkCerts,
NUM_THREADS);
httpServer = make_shared<HttpServer>(BASE_PORT, certPath, keyPath, rootCAPath, _checkCerts, numThreads);
server = make_shared<SGXWalletServer>(*httpServer,
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
......@@ -169,7 +175,8 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
int SGXWalletServer::initHttpServer() { //without ssl
spdlog::info("Entering {}", __FUNCTION__);
httpServer = make_shared<HttpServer>(BASE_PORT + 3);
httpServer = make_shared<HttpServer>(BASE_PORT + 3, "", "", "", false,
NUM_THREADS);
server = make_shared<SGXWalletServer>(*httpServer,
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
if (!server->StartListening()) {
......@@ -193,7 +200,16 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k
throw SGXException(INVALID_BLS_NAME, "Invalid BLS key name");
}
encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, (char *) errMsg.data(), _keyShare.c_str());
string hashTmp = _keyShare;
if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) {
hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2);
}
if (!checkHex(hashTmp)) {
throw SGXException(INVALID_HEX, "Invalid BLS key share, please use hex");
}
encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, (char *) errMsg.data(), hashTmp.c_str());
if (errStatus != 0) {
throw SGXException(errStatus, errMsg.data());
......@@ -259,6 +275,37 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin
}
Json::Value SGXWalletServer::importECDSAKeyImpl(const string &_keyShare,
const string &_keyShareName) {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
result["encryptedKey"] = "";
try {
if (!checkECDSAKeyName(_keyShareName)) {
throw SGXException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
string hashTmp = _keyShare;
if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) {
hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2);
}
if (!checkHex(hashTmp)) {
throw SGXException(INVALID_HEX, "Invalid ECDSA key share, please use hex");
}
string encryptedKey = encryptECDSAKey(hashTmp);
writeDataToDB(_keyShareName, encryptedKey);
result["encryptedKey"] = encryptedKey;
result["publicKey"] = getECDSAPubKey(encryptedKey);
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result);
}
Json::Value SGXWalletServer::generateECDSAKeyImpl() {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
......@@ -388,7 +435,7 @@ Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName,
shared_ptr <string> encrPoly = readFromDb(_polyName);
verifVector = get_verif_vect(encrPoly->c_str(), _t, _n);
verifVector = get_verif_vect(*encrPoly, _t, _n);
for (int i = 0; i < _t; i++) {
vector <string> currentCoef = verifVector.at(i);
......@@ -498,6 +545,8 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
CHECK_STATE(encryptedKeyHex_ptr);
bool res = createBLSShare(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str());
if (res) {
spdlog::info("BLS KEY SHARE CREATED ");
......@@ -505,6 +554,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
throw SGXException(-122, "Error while creating BLS key share");
}
for (int i = 0; i < _n; i++) {
string name = _polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb()->deleteDHDKGKey(name);
......@@ -513,6 +563,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
}
LevelDB::getLevelDb()->deleteKey(_polyName);
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName);
......@@ -540,7 +591,7 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName)
RETURN_SUCCESS(result);
}
Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& publicShares, int t, int n) {
Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value &publicShares, int t, int n) {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
......@@ -567,14 +618,14 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu
}
}
vector<string> public_shares(n);
vector <string> public_shares(n);
for (int i = 0; i < n; ++i) {
public_shares[i] = publicShares[i].asString();
}
vector<string> public_keys = calculateAllBlsPublicKeys(public_shares);
vector <string> public_keys = calculateAllBlsPublicKeys(public_shares);
if (public_keys.size() != (uint64_t)n) {
if (public_keys.size() != (uint64_t) n) {
throw SGXException(UNKNOWN_ERROR, "");
}
......@@ -586,7 +637,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu
RETURN_SUCCESS(result);
}
Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _ind) {
Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _t, int _n, int _ind) {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
......@@ -603,13 +654,23 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int
result["share*G2"] = *shareG2_ptr;
result["dhKey"] = DHKey;
// TODO: delete dh keys
// for (int i = 0; i < _n; i++) {
// string name = _polyName + "_" + to_string(i) + ":";
// LevelDB::getLevelDb()->deleteDHDKGKey(name);
// string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
// LevelDB::getLevelDb()->deleteKey(shareG2_name);
// }
shared_ptr <string> encrPoly = readFromDb(_polyName);
auto verificationVectorMult = getVerificationVectorMult(encrPoly->c_str(), _t, _n, _ind);
for (int i = 0; i < _t; i++) {
vector <string> currentCoef = verificationVectorMult.at(i);
for (int j = 0; j < 4; j++) {
result["verificationVectorMult"][i][j] = currentCoef.at(j);
}
}
for (int i = 0; i < _n; i++) {
string name = _polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb()->deleteDHDKGKey(name);
string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb()->deleteKey(shareG2_name);
}
LevelDB::getLevelDb()->deleteKey(_polyName);
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
......@@ -683,6 +744,76 @@ Json::Value SGXWalletServer::deleteBlsKeyImpl(const string &name) {
RETURN_SUCCESS(result)
}
Json::Value SGXWalletServer::getSecretShareV2Impl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n) {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result);
result["secretShare"] = "";
try {
if (_pubKeys.size() != (uint64_t) _n) {
throw SGXException(INVALID_DKG_PARAMS, "invalid number of public keys");
}
if (!checkName(_polyName, "POLY")) {
throw SGXException(INVALID_POLY_NAME, "Invalid polynomial name");
}
if (!check_n_t(_t, _n)) {
throw SGXException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
shared_ptr <string> encrPoly = readFromDb(_polyName);
vector <string> pubKeysStrs;
for (int i = 0; i < _n; i++) {
if (!checkHex(_pubKeys[i].asString(), 64)) {
throw SGXException(INVALID_HEX, "Invalid public key");
}
pubKeysStrs.push_back(_pubKeys[i].asString());
}
string secret_share_name = "encryptedSecretShare:" + _polyName;
shared_ptr <string> encryptedSecretShare = checkDataFromDb(secret_share_name);
if (encryptedSecretShare != nullptr) {
result["secretShare"] = *encryptedSecretShare.get();
} else {
string s = getSecretSharesV2(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n);
result["secretShare"] = s;
}
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXWalletServer::dkgVerificationV2Impl(const string &_publicShares, const string &_ethKeyName,
const string &_secretShare, int _t, int _n, int _index) {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
result["result"] = false;
try {
if (!checkECDSAKeyName(_ethKeyName)) {
throw SGXException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
if (!check_n_t(_t, _n) || _index >= _n || _index < 0) {
throw SGXException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
if (!checkHex(_secretShare, SECRET_SHARE_NUM_BYTES)) {
throw SGXException(INVALID_HEX, "Invalid Secret share");
}
if (_publicShares.length() != (uint64_t) 256 * _t) {
throw SGXException(INVALID_DKG_PARAMS, "Invalid length of public shares");
}
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
if (verifySharesV2(_publicShares.c_str(), _secretShare.c_str(), encryptedKeyHex_ptr->c_str(), _t, _n, _index)) {
result["result"] = true;
}
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXWalletServer::generateDKGPoly(const string &_polyName, int _t) {
return generateDKGPolyImpl(_polyName, _t);
}
......@@ -712,10 +843,14 @@ Json::Value SGXWalletServer::getBLSPublicKeyShare(const string &blsKeyName) {
return getBLSPublicKeyShareImpl(blsKeyName);
}
Json::Value SGXWalletServer::calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) {
Json::Value SGXWalletServer::calculateAllBLSPublicKeys(const Json::Value &publicShares, int t, int n) {
return calculateAllBLSPublicKeysImpl(publicShares, t, n);
}
Json::Value SGXWalletServer::importECDSAKey(const std::string &keyShare, const std::string &keyShareName) {
return importECDSAKeyImpl(keyShare, keyShareName);
}
Json::Value SGXWalletServer::generateECDSAKey() {
return generateECDSAKeyImpl();
}
......@@ -733,12 +868,13 @@ SGXWalletServer::importBLSKeyShare(const string &_keyShare, const string &_keySh
return importBLSKeyShareImpl(_keyShare, _keyShareName);
}
Json::Value SGXWalletServer::blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n) {
Json::Value
SGXWalletServer::blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n) {
return blsSignMessageHashImpl(_keyShareName, _messageHash, _t, _n);
}
Json::Value SGXWalletServer::complaintResponse(const string &polyName, int ind) {
return complaintResponseImpl(polyName, ind);
Json::Value SGXWalletServer::complaintResponse(const string &polyName, int t, int n, int ind) {
return complaintResponseImpl(polyName, t, n, ind);
}
Json::Value SGXWalletServer::multG2(const string &x) {
......@@ -761,6 +897,17 @@ Json::Value SGXWalletServer::deleteBlsKey(const string &name) {
return deleteBlsKeyImpl(name);
}
Json::Value SGXWalletServer::getSecretShareV2(const string &_polyName, const Json::Value &_publicKeys, int t, int n) {
return getSecretShareV2Impl(_polyName, _publicKeys, t, n);
}
Json::Value
SGXWalletServer::dkgVerificationV2(const string &_publicShares, const string &ethKeyName, const string &SecretShare,
int t,
int n, int index) {
return dkgVerificationV2Impl(_publicShares, ethKeyName, SecretShare, t, n, index);
}
shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) {
auto dataStr = checkDataFromDb(prefix + name);
......@@ -786,9 +933,9 @@ void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_
}
void SGXWalletServer::writeDataToDB(const string &name, const string &value) {
if (LevelDB::getLevelDb()->readString(name) != nullptr) {
throw SGXException(KEY_NAME_ALREADY_EXISTS, "Name already exists");
}
LevelDB::getLevelDb()->writeString(name, value);
}
......@@ -51,6 +51,9 @@ public:
virtual Json::Value
blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n);
virtual Json::Value importECDSAKey(const std::string& keyShare,
const std::string& keyShareName);
virtual Json::Value generateECDSAKey();
virtual Json::Value
......@@ -76,7 +79,7 @@ public:
virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n);
virtual Json::Value complaintResponse(const string &polyName, int ind);
virtual Json::Value complaintResponse(const string &polyName, int t, int n, int ind);
virtual Json::Value multG2(const string &x);
......@@ -88,6 +91,10 @@ public:
virtual Json::Value deleteBlsKey( const std::string& name );
virtual Json::Value getSecretShareV2(const string &_polyName, const Json::Value &_publicKeys, int t, int n);
virtual Json::Value dkgVerificationV2(const string &_publicShares, const string &ethKeyName, const string &SecretShare, int t, int n, int index);
static shared_ptr<string> readFromDb(const string &name, const string &prefix = "");
static shared_ptr <string> checkDataFromDb(const string &name, const string &prefix = "");
......@@ -102,6 +109,8 @@ public:
static Json::Value
blsSignMessageHashImpl(const string &_keyShareName, const string &_messageHash, int t, int n);
static Json::Value importECDSAKeyImpl(const string &_keyShare, const string &_keyShareName);
static Json::Value generateECDSAKeyImpl();
static Json::Value ecdsaSignMessageHashImpl(int _base, const string &keyName, const string &_messageHash);
......@@ -126,7 +135,7 @@ public:
static Json::Value calculateAllBLSPublicKeysImpl(const Json::Value& publicShares, int t, int n);
static Json::Value complaintResponseImpl(const string &_polyName, int _ind);
static Json::Value complaintResponseImpl(const string &_polyName, int t, int n, int _ind);
static Json::Value multG2Impl(const string &_x);
......@@ -138,6 +147,10 @@ public:
static Json::Value deleteBlsKeyImpl(const std::string& name);
static Json::Value getSecretShareV2Impl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n);
static Json::Value dkgVerificationV2Impl(const string &_publicShares, const string &_ethKeyName, const string &_secretShare, int _t, int _n, int _index);
static void printDB();
static int initHttpServer();
......
......@@ -86,7 +86,7 @@ uint64_t initEnclave() {
{
WRITE_LOCK(initMutex);
WRITE_LOCK(sgxInitMutex);
if (eid != 0) {
if (sgx_destroy_enclave(eid) != SGX_SUCCESS) {
......
......@@ -21,12 +21,9 @@
@date 2020
*/
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <libff/algebra/exponentiation/exponentiation.hpp>
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h>
#include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h"
......@@ -82,14 +79,12 @@ string TestUtils::convertDecToHex(string dec, int numBytes) {
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');
mpz_clear(num);
return result;
}
......@@ -177,6 +172,146 @@ void TestUtils::sendRPCRequest() {
static atomic<int> counter(1);
int schainID = counter.fetch_add(1);
int dkgID = counter.fetch_add(1);
int testCount = 1;
if (getenv("NIGHTLY_TESTS")) {
testCount = 10;
}
for (uint8_t i = 0; i < n; i++) {
usleep(100000);
ethKeys[i] = c.generateECDSAKey();
for (int i2 = 0; i2 < testCount; i2++) {
auto keyName = ethKeys[i]["keyName"].asString();
Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH);
CHECK_STATE(sig["status"].asInt() == 0);
}
CHECK_STATE(ethKeys[i]["status"] == 0);
string polyName =
"POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
auto response = c.generateDKGPoly(polyName, t);
CHECK_STATE(response["status"] == 0);
polyNames[i] = polyName;
for (int i3 = 0; i3 <= testCount; i3++) {
verifVects[i] = c.getVerificationVector(polyName, t, n);
CHECK_STATE(verifVects[i]["status"] == 0);
}
pubEthKeys.append(ethKeys[i]["publicKey"]);
}
for (uint8_t i = 0; i < n; i++) {
usleep(100000);
for (int i4 = 0; i4 <= testCount; i4++) {
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]["verificationVector"][k][j].asString();
pubShares[i] += convertDecToHex(pubShare);
}
}
}
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);
usleep(100000);
for (int i5 = 0; i5 <= testCount; i5++) {
Json::Value verif = c.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n,
j);
CHECK_STATE(verif["status"] == 0);
}
}
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(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash");
}
map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
Json::Value publicShares;
for (int i = 0; i < n; ++i) {
publicShares["publicShares"][i] = pubShares[i];
}
Json::Value blsPublicKeys;
for (int i6 = 0; i6 <= testCount; i6++) {
blsPublicKeys = c.calculateAllBLSPublicKeys(publicShares, t, n);
CHECK_STATE(blsPublicKeys["status"] == 0);
}
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();
auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i],
t, n);
CHECK_STATE(response["status"] == 0);
for (int i7 = 0; i7 <= testCount; i7++) {
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
}
CHECK_STATE(pubBLSKeys[i]["status"] == 0);
libff::alt_bn128_G2 publicKey(libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][0].asCString()),
libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][1].asCString())),
libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][2].asCString()),
libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][3].asCString())),
libff::alt_bn128_Fq2::one());
string public_key_str = convertG2ToString(publicKey);
CHECK_STATE(public_key_str == blsPublicKeys["publicKeys"][i].asString());
string hash = SAMPLE_HASH;
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
CHECK_STATE(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));
}
sigShareSet.merge();
}
void TestUtils::sendRPCRequestV2() {
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);
static atomic<int> counter(1);
int schainID = counter.fetch_add(1);
int dkgID = counter.fetch_add(1);
for (uint8_t i = 0; i < n; i++) {
......@@ -194,7 +329,7 @@ void TestUtils::sendRPCRequest() {
}
for (uint8_t i = 0; i < n; i++) {
secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n);
secretShares[i] = c.getSecretShareV2(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]["verificationVector"][k][j].asString();
......@@ -209,7 +344,7 @@ void TestUtils::sendRPCRequest() {
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);
Json::Value verif = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
CHECK_STATE(verif["status"] == 0);
}
......@@ -412,3 +547,303 @@ void TestUtils::doDKG(StubClient &c, int n, int t,
for (auto&& i : _blsKeyNames)
cerr << i << endl;
}
void TestUtils::doDKGV2(StubClient &c, int n, int t,
vector<string>& _ecdsaKeyNames, vector<string>& _blsKeyNames,
int schainID, int dkgID) {
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);
_ecdsaKeyNames.clear();
_blsKeyNames.clear();
for (uint8_t i = 0; i < n; i++) {
ethKeys[i] = c.generateECDSAKey();
CHECK_STATE(ethKeys[i]["status"] == 0);
auto keyName = ethKeys[i]["keyName"].asString();
CHECK_STATE(keyName.size() == ECDSA_KEY_NAME_SIZE);
_ecdsaKeyNames.push_back(keyName);
string polyName =
"POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
Json::Value response = c.generateDKGPoly(polyName, t);
CHECK_STATE(response["status"] == 0);
polyNames[i] = polyName;
verifVects[i] = c.getVerificationVector(polyName, t, n);
CHECK_STATE(verifVects[i]["status"] == 0);
pubEthKeys.append(ethKeys[i]["publicKey"]);
}
for (uint8_t i = 0; i < n; i++) {
secretShares[i] = c.getSecretShareV2(polyNames[i], pubEthKeys, t, n);
CHECK_STATE(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();
CHECK_STATE(pubShare.length() > 60);
pubShares[i] += TestUtils::convertDecToHex(pubShare);
}
}
}
int k = 0;
vector<string> secShares(n);
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[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
Json::Value response = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n,
j);
CHECK_STATE(response["status"] == 0);
bool res = response["result"].asBool();
CHECK_STATE(res);
k++;
pSharesBad[i][0] = 'q';
Json::Value wrongVerif = c.dkgVerificationV2(pSharesBad[i], ethKeys[j]["keyName"].asString(), secretShare, t,
n, j);
res = wrongVerif["result"].asBool();
CHECK_STATE(!res);
}
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(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash");
}
map<size_t, shared_ptr<BLSPublicKeyShare>> pubKeyShares;
for (int i = 0; i < n; i++) {
string endName = polyNames[i].substr(4);
string blsName = "BLS_KEY" + polyNames[i].substr(4);
_blsKeyNames.push_back(blsName);
string secretShare = secretShares[i]["secretShare"].asString();
auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
n);
CHECK_STATE(response["status"] == 0);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
CHECK_STATE(pubBLSKeys[i]["status"] == 0);
}
for (int i = 0; i < t; i++) {
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);
pubKeyShares[i + 1] = make_shared<BLSPublicKeyShare>(pubKey);
}
// create pub key
BLSPublicKey blsPublicKey(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare >>>(pubKeyShares), t,
n);
// sign verify a sample sig
for (int i = 0; i < t; i++) {
string blsName = "BLS_KEY" + polyNames[i].substr(4);
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
CHECK_STATE(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));
auto pubKey = pubKeyShares[i+1];
CHECK_STATE(pubKey->VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
}
shared_ptr<BLSSignature> commonSig = sigShareSet.merge();
CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig, t, n));
for (auto&& i : _ecdsaKeyNames)
cerr << i << endl;
for (auto&& i : _blsKeyNames)
cerr << i << endl;
}
int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key) {
int ret = -1;
SAFE_CHAR_BUF(pb_keyB_x, 65);
SAFE_CHAR_BUF(pb_keyB_y, 65);
mpz_t skey;
mpz_init(skey);
point pub_keyB = point_init();
point session_key = point_init();
pb_keyB_x[64] = 0;
strncpy(pb_keyB_x, sshare, 64);
strncpy(pb_keyB_y, sshare + 64, 64);
pb_keyB_y[64] = 0;
if (!common_key) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
common_key[0] = 0;
if (!skey_str) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
if (!sshare) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
if (mpz_set_str(skey, skey_str, 16) == -1) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
domain_parameters curve;
curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
if (point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y) != 0) {
return ret;
}
point_multiplication(session_key, skey, pub_keyB, curve);
SAFE_CHAR_BUF(arr_x, BUF_LEN);
mpz_get_str(arr_x, 16, session_key->x);
int n_zeroes = 64 - strlen(arr_x);
for (int i = 0; i < n_zeroes; i++) {
common_key[i] = '0';
}
strncpy(common_key + n_zeroes, arr_x, strlen(arr_x));
ret = 0;
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
int xorDecryptDH(char *key, const char *cypher, vector<char>& message) {
int ret = -1;
if (!cypher) {
return ret;
}
if (!key) {
return ret;
}
if (!message.data()) {
return ret;
}
SAFE_CHAR_BUF(msg_bin,33)
SAFE_CHAR_BUF(key_bin,33)
uint64_t key_length;
if (!hex2carray(key, &key_length, (uint8_t*) key_bin, 33)) {
return ret;
}
uint64_t cypher_length;
SAFE_CHAR_BUF(cypher_bin, 33);
if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) {
return ret;
}
for (int i = 0; i < 32; i++) {
msg_bin[i] = cypher_bin[i] ^ key_bin[i];
}
message = carray2Hex((unsigned char*) msg_bin, 32);
ret = 0;
return ret;
}
int xorDecryptDHV2(char *key, const char *cypher, vector<char>& message) {
int ret = -1;
if (!cypher) {
return ret;
}
if (!key) {
return ret;
}
if (!message.data()) {
return ret;
}
SAFE_CHAR_BUF(msg_bin,33)
uint64_t cypher_length;
SAFE_CHAR_BUF(cypher_bin, 33);
if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) {
return ret;
}
for (int i = 0; i < 32; i++) {
msg_bin[i] = cypher_bin[i] ^ (uint8_t)key[i];
}
message = carray2Hex((unsigned char*) msg_bin, 32);
ret = 0;
return ret;
}
......@@ -24,12 +24,11 @@
#ifndef SGXWALLET_TESTUTILS_H
#define SGXWALLET_TESTUTILS_H
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <libff/algebra/exponentiation/exponentiation.hpp>
#include <libff/algebra/fields/fp.hpp>
// #include <libff/algebra/exponentiation/exponentiation.hpp>
// #include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h>
#include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h"
......@@ -71,11 +70,23 @@ public:
static void sendRPCRequest();
static void sendRPCRequestV2();
static void destroyEnclave();
static void doDKG(StubClient &c, int n, int t,
vector<string>& _ecdsaKeyNames, vector<string>& _blsKeyNames,
int schainID, int dkgID);
static void doDKGV2(StubClient &c, int n, int t,
vector<string>& _ecdsaKeyNames, vector<string>& _blsKeyNames,
int schainID, int dkgID);
};
int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key);
int xorDecryptDH(char *key, const char *cypher, vector<char>& message);
int xorDecryptDHV2(char *key, const char *cypher, vector<char>& message);
#endif //SGXWALLET_TESTW_H
1.58.5
\ No newline at end of file
1.59.1
\ No newline at end of file
......@@ -39,6 +39,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("importBLSKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyShare",jsonrpc::JSON_STRING,"keyShareName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importBLSKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("blsSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyShareName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::blsSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("importECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"key",jsonrpc::JSON_STRING,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("generateECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::generateECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getPublicECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getPublicECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("ecdsaSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "base",jsonrpc::JSON_INTEGER,"keyName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::ecdsaSignMessageHashI);
......@@ -50,13 +51,16 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "polyName", jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::createBLSPrivateKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getBLSPublicKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("calculateAllBLSPublicKeys", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares", jsonrpc::JSON_ARRAY, "n", jsonrpc::JSON_INTEGER, "t", jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::calculateAllBLSPublicKeysI);
this->bindAndAddMethod(jsonrpc::Procedure("complaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::complaintResponseI);
this->bindAndAddMethod(jsonrpc::Procedure("complaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::complaintResponseI);
this->bindAndAddMethod(jsonrpc::Procedure("multG2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "x",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::multG2I);
this->bindAndAddMethod(jsonrpc::Procedure("isPolyExists", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::isPolyExistsI);
this->bindAndAddMethod(jsonrpc::Procedure("getServerStatus", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::getServerStatusI);
this->bindAndAddMethod(jsonrpc::Procedure("getServerVersion", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::getServerVersionI);
this->bindAndAddMethod(jsonrpc::Procedure("deleteBlsKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName", jsonrpc::JSON_STRING, NULL), &AbstractStubServer::deleteBlsKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getSecretShareV2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"publicKeys",jsonrpc::JSON_ARRAY, "n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getSecretShareV2I);
this->bindAndAddMethod(jsonrpc::Procedure("dkgVerificationV2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::dkgVerificationV2I);
}
inline virtual void importBLSKeyShareI(const Json::Value &request, Json::Value &response)
......@@ -68,6 +72,10 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["t"].asInt(), request["n"].asInt());
}
inline virtual void importECDSAKeyI(const Json::Value &request, Json::Value &response)
{
response = this->importECDSAKey( request["key"].asString(), request["keyName"].asString());
}
inline virtual void generateECDSAKeyI(const Json::Value &request, Json::Value &response)
{
(void)request;
......@@ -111,7 +119,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
}
inline virtual void complaintResponseI(const Json::Value &request, Json::Value &response)
{
response = this->complaintResponse( request["polyName"].asString(), request["ind"].asInt());
response = this->complaintResponse( request["polyName"].asString(), request["t"].asInt(), request["n"].asInt(), request["ind"].asInt());
}
inline virtual void multG2I(const Json::Value &request, Json::Value &response)
{
......@@ -139,8 +147,18 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
response = this->deleteBlsKey(request["blsKeyName"].asString());
}
inline virtual void getSecretShareV2I(const Json::Value &request, Json::Value &response)
{
response = this->getSecretShareV2(request["polyName"].asString(), request["publicKeys"], request["t"].asInt(),request["n"].asInt());
}
inline virtual void dkgVerificationV2I(const Json::Value &request, Json::Value &response)
{
response = this->dkgVerificationV2(request["publicShares"].asString(), request["ethKeyName"].asString(), request["secretShare"].asString(), request["t"].asInt(), request["n"].asInt(), request["index"].asInt());
}
virtual Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName) = 0;
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int t, int n ) = 0;
virtual Json::Value importECDSAKey(const std::string& keyShare, const std::string& keyShareName) = 0;
virtual Json::Value generateECDSAKey() = 0;
virtual Json::Value getPublicECDSAKey(const std::string& keyName) = 0;
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyName, const std::string& messageHash) = 0;
......@@ -152,13 +170,16 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
virtual Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0;
virtual Json::Value getBLSPublicKeyShare(const std::string & blsKeyName) = 0;
virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) = 0;
virtual Json::Value complaintResponse(const std::string& polyName, int ind) = 0;
virtual Json::Value complaintResponse(const std::string& polyName, int t, int n, int ind) = 0;
virtual Json::Value multG2(const std::string & x) = 0;
virtual Json::Value isPolyExists(const std::string& polyName) = 0;
virtual Json::Value getServerStatus() = 0;
virtual Json::Value getServerVersion() = 0;
virtual Json::Value deleteBlsKey(const std::string& name) = 0;
virtual Json::Value getSecretShareV2(const std::string& polyName, const Json::Value& publicKeys, int t, int n) = 0;
virtual Json::Value dkgVerificationV2( const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index) = 0;
};
#endif //JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_
......@@ -98,10 +98,10 @@ BOOST_THROW_EXCEPTION(runtime_error(__ERR_STRING__)); \
#include <shared_mutex>
extern std::shared_timed_mutex initMutex;
extern std::shared_timed_mutex sgxInitMutex;
extern uint64_t initTime;
#if SGX_MODE == SIM
#ifdef SGX_HW_SIM
#define ENCLAVE_RESTART_PERIOD_S 5
#else
#define ENCLAVE_RESTART_PERIOD_S 60 * 10
......
......@@ -28,7 +28,7 @@ cd /usr/src/sdk;
if [[ -f "/var/hwmode" ]]
then
echo "Running in SGX hardware mode"
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/intel/sgxpsw/aesm/
export LD_LIBRARY_PATH=/usr/src/sdk/secure_enclave:${LD_LIBRARY_PATH}:/opt/intel/sgxpsw/aesm
jhid -d
/opt/intel/sgxpsw/aesm/aesm_service &
pid=$!
......
Subproject commit 78ea56c3b5251e9d840ef65705bb2c5f8f193662
Subproject commit 82884ec89e84539f25af206a0148ca34c35e078f
version: '3'
services:
sgxwallet:
image: skalenetwork/sgxwallet:latest
image: skalenetwork/sgxwallet_signed:latest
restart: always
ports:
- "1026:1026"
......
#!/usr/bin/env bash
set -e
set -x
DOCKERFILE=$1
CONTAINER_NAME=$2
......
......@@ -29,23 +29,27 @@ topDir = os.getcwd() + "/sgxwallet"
print("Starting container test")
print("Top directory is:" + topDir)
DOCKER_FILE_NAME = sys.argv[1];
DOCKER_FILE_NAME = sys.argv[1]
IMAGE_NAME = sys.argv[2]
TAG_POSTFIX = "latest_commit"
FULL_IMAGE_NAME = "skalenetwork/" + IMAGE_NAME +":" + TAG_POSTFIX;
FULL_IMAGE_NAME = "skalenetwork/" + IMAGE_NAME +":" + TAG_POSTFIX
print("Running tests");
dockerRun = subprocess.run(["docker", "run", "-v", topDir + "/sgx_data:/usr/src/sdk/sgx_data","-t",
isNightly = os.environ.get("NIGHTLY_TESTS")
if isNightly :
dockerRun = subprocess.run(["docker", "run", "-e", "NIGHTLY_TESTS='1'", "-v", topDir + "/sgx_data:/usr/src/sdk/sgx_data","-t",
"-v", "/dev/urandom:/dev/random", "--name", "sgxwallet", "--network=host", "skalenetwork/" + IMAGE_NAME +":" + TAG_POSTFIX, "-t"])
else:
dockerRun = subprocess.run(["docker", "run", "-v", topDir + "/sgx_data:/usr/src/sdk/sgx_data","-t",
"-v", "/dev/urandom:/dev/random", "--name", "sgxwallet", "--network=host", "skalenetwork/" + IMAGE_NAME +":" + TAG_POSTFIX, "-t"])
print(dockerRun.stdout)
print(dockerRun.stderr)
assert dockerRun.returncode == 0;
assert subprocess.call(["docker", "rm", "sgxwallet"]) == 0
assert subprocess.call(["docker", "run", "-v", topDir + "/sgx_data:/usr/src/sdk/sgx_data","-d",
"--name", "sgxwallet",
......@@ -53,25 +57,23 @@ assert subprocess.call(["docker", "run", "-v", topDir + "/sgx_data:/usr/src/sdk/
time.sleep(5);
#
#
#assert os.path.isdir(topDir + '/sgx_data/sgxwallet.db')
#assert os.path.isdir(topDir + '/sgx_data/cert_data');
#assert os.path.isdir(topDir + '/sgx_data/CSR_DB');
#assert os.path.isdir(topDir + '/sgx_data/CSR_STATUS_DB');
#assert os.path.isfile(topDir + '/sgx_data/cert_data/SGXServerCert.crt')
#assert os.path.isfile(topDir + '/sgx_data/cert_data/SGXServerCert.key')
#assert os.path.isfile(topDir + '/sgx_data/cert_data/rootCA.pem')
#assert os.path.isfile(topDir + '/sgx_data/cert_data/rootCA.key')
assert os.path.isdir(topDir + '/sgx_data/sgxwallet.db')
assert os.path.isdir(topDir + '/sgx_data/cert_data');
assert os.path.isdir(topDir + '/sgx_data/CSR_DB');
assert os.path.isdir(topDir + '/sgx_data/CSR_STATUS_DB');
assert os.path.isfile(topDir + '/sgx_data/cert_data/SGXServerCert.crt')
assert os.path.isfile(topDir + '/sgx_data/cert_data/SGXServerCert.key')
assert os.path.isfile(topDir + '/sgx_data/cert_data/rootCA.pem')
assert os.path.isfile(topDir + '/sgx_data/cert_data/rootCA.key')
#s1 = socket.socket()
#s2 = socket.socket()
#s3 = socket.socket()
#address = '127.0.0.1'
#s1.connect((address, 1026))
#s2.connect((address, 1027))
#s3.connect((address, 1028))
s1 = socket.socket()
s2 = socket.socket()
s3 = socket.socket()
address = '127.0.0.1'
s1.connect((address, 1026))
s2.connect((address, 1027))
s3.connect((address, 1028))
#s1.close()
#s2.close()
#s3.close()
s1.close()
s2.close()
s3.close()
#!/usr/bin/env bash
set -e
set -x
CONTAINER_NAME=$1
......@@ -10,14 +11,8 @@ CONTAINER_NAME=$1
REPO_NAME=skalenetwork/$CONTAINER_NAME
IMAGE_NAME=$REPO_NAME:$VERSION
if [ "${BRANCH}" = "stable" ];
then
LATEST_IMAGE_NAME=$REPO_NAME:latest
docker tag "${IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
else
LATEST_IMAGE_NAME=$REPO_NAME:$BRANCH-latest
docker tag "${IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
fi
LATEST_IMAGE_NAME=$REPO_NAME:$BRANCH-latest
docker tag "${IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
: "${DOCKER_USERNAME?Need to set DOCKER_USERNAME}"
: "${DOCKER_PASSWORD?Need to set DOCKER_PASSWORD}"
......
......@@ -161,7 +161,7 @@ int session_key_recover(const char *skey_str, const char *sshare, char *common_k
point_clear(pub_keyB);
point_clear(session_key);
return ret;
return ret;
}
int xor_encrypt(char *key, char *message, char *cypher) {
......@@ -209,6 +209,44 @@ int xor_encrypt(char *key, char *message, char *cypher) {
return ret;
}
int xor_encrypt_v2(char *key, char *message, char *cypher) {
int ret = -1;
if (!cypher) {
LOG_ERROR("xor_encrypt: null cypher");
return ret;
}
if (!key) {
LOG_ERROR("xor_encrypt: null key");
return ret;
}
if (!message) {
LOG_ERROR("xor_encrypt: null message");
return ret;
}
SAFE_CHAR_BUF(cypher_bin, 33);
uint64_t msg_length;
uint8_t msg_bin[33];
if (!hex2carray(message, &msg_length, msg_bin)) {
return ret;
}
for (int i = 0; i < 32; i++) {
cypher_bin[i] = msg_bin[i] ^ (uint8_t)key[i];
}
carray2Hex((unsigned char*) cypher_bin, 32, cypher);
ret = 0;
return ret;
}
int xor_decrypt(char *key, char *cypher, char *message) {
int ret = -1;
......@@ -254,3 +292,60 @@ int xor_decrypt(char *key, char *cypher, char *message) {
return ret;
}
int xor_decrypt_v2(char *key, char *cypher, char *message) {
int ret = -1;
if (!cypher) {
LOG_ERROR("xor_encrypt: null cypher");
return ret;
}
if (!key) {
LOG_ERROR("xor_encrypt: null key");
return ret;
}
if (!message) {
LOG_ERROR("xor_encrypt: null message");
return ret;
}
SAFE_CHAR_BUF(msg_bin,33);
uint64_t cypher_length;
SAFE_CHAR_BUF(cypher_bin, 33);
if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin)) {
return ret;
}
for (int i = 0; i < 32; i++) {
msg_bin[i] = cypher_bin[i] ^ (uint8_t)key[i];
}
carray2Hex((unsigned char*) msg_bin, 32, message);
ret = 0;
return ret;
}
int hash_key(char* key, char* hashed_key) {
int ret = -1;
if (!key) {
LOG_ERROR("hash_key: null key");
return ret;
}
if (!hashed_key) {
LOG_ERROR("hash_key: null hashed_key");
return ret;
}
ret = sgx_sha256_msg((uint8_t*)key, ECDSA_SKEY_LEN - 1, (uint8_t*)hashed_key);
return ret;
}
......@@ -30,6 +30,12 @@ int session_key_recover(const char *skey_str, const char* sshare, char* common_k
int xor_encrypt(char* key, char* message, char* cypher);
int xor_encrypt_v2(char* key, char* message, char* cypher);
int xor_decrypt(char* key, char* cypher, char* message);
int xor_decrypt_v2(char* key, char* cypher, char* message);
int hash_key(char* key, char* hashed_key);
#endif //SGXD_DRIVE_KEY_DKG_H
......@@ -82,8 +82,8 @@ string *stringFromFq(libff::alt_bn128_Fq *_fq) {
try {
_fq->as_bigint().to_mpz(t);
char *tmp = mpz_get_str(arr, 10, t);
ret = new string(tmp);
mpz_get_str(arr, 10, t);
ret = new string(arr);
} catch (exception &e) {
LOG_ERROR(e.what());
goto clean;
......@@ -107,13 +107,13 @@ string *stringFromG1(libff::alt_bn128_G1 *_g1) {
try {
_g1->to_affine_coordinates();
auto sX = stringFromFq(&_g1->X);
sX = stringFromFq(&_g1->X);
if (!sX) {
goto clean;
}
auto sY = stringFromFq(&_g1->Y);
sY = stringFromFq(&_g1->Y);
if (!sY) {
goto clean;
......@@ -131,8 +131,8 @@ string *stringFromG1(libff::alt_bn128_G1 *_g1) {
clean:
SAFE_FREE(sX);
SAFE_FREE(sY);
SAFE_DELETE(sX);
SAFE_DELETE(sY);
return ret;
......@@ -226,7 +226,7 @@ bool enclave_sign(const char *_keyString, const char *_hashXString, const char *
}
try {
auto key = keyFromString(_keyString);
key = keyFromString(_keyString);
if (!key) {
LOG_ERROR("Null key");
......@@ -243,13 +243,13 @@ bool enclave_sign(const char *_keyString, const char *_hashXString, const char *
sign.to_affine_coordinates();
auto r = stringFromG1(&sign);
r = stringFromG1(&sign);
memset(sig, 0, BUF_LEN);
strncpy(sig, r->c_str(), BUF_LEN);
ret = true;
ret = true;
} catch (exception &e) {
LOG_ERROR(e.what());
......
#define SIGNED_ENCLAVE_VERSION "1"
\ No newline at end of file
#define SIGNED_ENCLAVE_VERSION "2"
\ No newline at end of file
......@@ -163,7 +163,7 @@ void trustedEnclaveInit(uint64_t _logLevel) {
LOG_INFO("SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!");
#endif
#if SGX_MODE == SIM
#ifdef SGX_HW_SIM
LOG_INFO("SECURITY WARNING: sgxwallet is running in INSECURE SIMULATION MODE! NEVER USE IN PRODUCTION!");
#endif
......@@ -507,15 +507,6 @@ void trustedGetPublicEcdsaKey(int *errStatus, char *errString,
point_clear(pKey);
point_clear(pKey_test);
static uint64_t counter = 0;
if (counter % 1000 == 0) {
LOG_INFO(__FUNCTION__);
LOG_INFO("Thousand SGX calls completed");
}
counter++;
}
static uint64_t sigCounter = 0;
......@@ -537,7 +528,8 @@ void trustedEcdsaSign(int *errStatus, char *errString, uint8_t *encryptedPrivate
mpz_init(privateKeyMpz);
mpz_t msgMpz;
mpz_init(msgMpz);
signature sign = signature_init();
signature sign = NULL;
sign = signature_init();
uint8_t type = 0;
uint8_t exportable = 0;
......@@ -603,7 +595,8 @@ void trustedEcdsaSign(int *errStatus, char *errString, uint8_t *encryptedPrivate
mpz_clear(privateKeyMpz);
mpz_clear(msgMpz);
signature_free(sign);
if (sign)
signature_free(sign);
LOG_DEBUG(__FUNCTION__ );
LOG_DEBUG("SGX call completed");
}
......@@ -847,10 +840,14 @@ void trustedSetEncryptedDkgPoly(int *errStatus, char *errString, uint8_t *encryp
LOG_INFO("SGX call completed");
}
void trustedGetEncryptedSecretShare(int *errStatus, char *errString, uint8_t *encrypted_skey, uint64_t *dec_len,
void trustedGetEncryptedSecretShare(int *errStatus, char *errString,
uint8_t *_encrypted_poly, uint64_t _enc_len,
uint8_t *encrypted_skey, uint64_t *dec_len,
char *result_str, char *s_shareG2, char *pub_keyB, uint8_t _t, uint8_t _n,
uint8_t ind) {
LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE
......@@ -864,6 +861,11 @@ void trustedGetEncryptedSecretShare(int *errStatus, char *errString, uint8_t *en
LOG_DEBUG(__FUNCTION__);
trustedSetEncryptedDkgPoly(&status, errString, _encrypted_poly, _enc_len);
CHECK_STATUS2("trustedSetEncryptedDkgPoly failed with status %d ");
SAFE_CHAR_BUF(skey, BUF_LEN);
SAFE_CHAR_BUF(pub_key_x, BUF_LEN);SAFE_CHAR_BUF(pub_key_y, BUF_LEN);
......@@ -915,6 +917,86 @@ void trustedGetEncryptedSecretShare(int *errStatus, char *errString, uint8_t *en
LOG_INFO("SGX call completed");
}
void trustedGetEncryptedSecretShareV2(int *errStatus, char *errString,
uint8_t *_encrypted_poly, uint64_t _enc_len,
uint8_t *encrypted_skey, uint64_t *dec_len,
char *result_str, char *s_shareG2, char *pub_keyB, uint8_t _t, uint8_t _n,
uint8_t ind) {
LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE
uint64_t enc_len;
int status;
CHECK_STATE(encrypted_skey);
CHECK_STATE(result_str);
CHECK_STATE(s_shareG2);
CHECK_STATE(pub_keyB);
LOG_DEBUG(__FUNCTION__);
trustedSetEncryptedDkgPoly(&status, errString, _encrypted_poly, _enc_len);
CHECK_STATUS2("trustedSetEncryptedDkgPoly failed with status %d ");
SAFE_CHAR_BUF(skey, BUF_LEN);
SAFE_CHAR_BUF(pub_key_x, BUF_LEN);
SAFE_CHAR_BUF(pub_key_y, BUF_LEN);
trustedGenerateEcdsaKey(&status, errString, encrypted_skey, &enc_len, pub_key_x, pub_key_y);
CHECK_STATUS("trustedGenerateEcdsaKey failed");
uint8_t type = 0;
uint8_t exportable = 0;
status = AES_decrypt(encrypted_skey, enc_len, skey, BUF_LEN, &type, &exportable);
skey[ECDSA_SKEY_LEN - 1] = 0;
CHECK_STATUS2("AES_decrypt failed (in trustedGetEncryptedSecretShareAES) with status %d");
*dec_len = enc_len;
SAFE_CHAR_BUF(common_key, BUF_LEN);
status = gen_session_key(skey, pub_keyB, common_key);
CHECK_STATUS("gen_session_key failed")
SAFE_CHAR_BUF(s_share, BUF_LEN);
status = calc_secret_share(getThreadLocalDecryptedDkgPoly(), s_share, _t, _n, ind);
CHECK_STATUS("calc secret share failed")
status = calc_secret_shareG2(s_share, s_shareG2);
CHECK_STATUS("invalid decr secret share");
SAFE_CHAR_BUF(derived_key, BUF_LEN);
status = hash_key(common_key, derived_key);
CHECK_STATUS("hash key failed")
derived_key[ECDSA_BIN_LEN - 1] = 0;
SAFE_CHAR_BUF(cypher, BUF_LEN);
status = xor_encrypt_v2(derived_key, s_share, cypher);
CHECK_STATUS("xor_encrypt failed")
strncpy(result_str, cypher, strlen(cypher));
strncpy(result_str + strlen(cypher), pub_key_x, strlen(pub_key_x));
strncpy(result_str + strlen(pub_key_x) + strlen(pub_key_y), pub_key_y, strlen(pub_key_y));
SET_SUCCESS
clean:
;
LOG_INFO(__FUNCTION__ );
LOG_INFO("SGX call completed");
}
void trustedGetPublicShares(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint64_t enc_len,
char *public_shares,
unsigned _t, unsigned _n) {
......@@ -981,12 +1063,68 @@ void trustedDkgVerify(int *errStatus, char *errString, const char *public_shares
SAFE_CHAR_BUF(decr_sshare, BUF_LEN);
status=xor_decrypt(common_key, encr_sshare, decr_sshare);
status = xor_decrypt(common_key, encr_sshare, decr_sshare);
CHECK_STATUS("xor_decrypt failed")
status = mpz_set_str(s, decr_sshare, 16);
CHECK_STATUS("invalid decr secret share");
*result = Verification(public_shares, s, _t, _ind);
SET_SUCCESS
clean:
status = mpz_set_str(s, decr_sshare, 16);
mpz_clear(s);
LOG_INFO(__FUNCTION__ );
LOG_INFO("SGX call completed");
}
void trustedDkgVerifyV2(int *errStatus, char *errString, const char *public_shares, const char *s_share,
uint8_t *encryptedPrivateKey, uint64_t enc_len, unsigned _t, int _ind, int *result) {
LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE
CHECK_STATE(public_shares);
CHECK_STATE(s_share);
CHECK_STATE(encryptedPrivateKey);
SAFE_CHAR_BUF(skey,BUF_LEN);
mpz_t s;
mpz_init(s);
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("AES_decrypt failed (in trustedDkgVerifyAES) with status %d");
SAFE_CHAR_BUF(encr_sshare, BUF_LEN);
strncpy(encr_sshare, s_share, ECDSA_SKEY_LEN - 1);
SAFE_CHAR_BUF(common_key, BUF_LEN);
status = session_key_recover(skey, s_share, common_key);
CHECK_STATUS("session_key_recover failed");
SAFE_CHAR_BUF(derived_key, BUF_LEN);
status = hash_key(common_key, derived_key);
CHECK_STATUS("hash key failed")
derived_key[ECDSA_BIN_LEN - 1] = 0;
SAFE_CHAR_BUF(decr_sshare, BUF_LEN);
status = xor_decrypt_v2(derived_key, encr_sshare, decr_sshare);
CHECK_STATUS("xor_decrypt failed")
status = mpz_set_str(s, decr_sshare, 16);
CHECK_STATUS("invalid decr secret share");
*result = Verification(public_shares, s, _t, _ind);
......@@ -1118,8 +1256,6 @@ trustedGetBlsPubKey(int *errStatus, char *errString, uint8_t *encryptedPrivateKe
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, key_len, skey_hex, BUF_LEN,
&type, &exportable);
......@@ -1132,12 +1268,9 @@ trustedGetBlsPubKey(int *errStatus, char *errString, uint8_t *encryptedPrivateKe
CHECK_STATUS("could not calculate bls public key");
SET_SUCCESS
static uint64_t counter = 0;
clean:
if (counter % 1000 == 0) {
LOG_INFO(__FUNCTION__);
LOG_INFO("Thousand SGX calls completed");
}
;
counter++;
}
<EnclaveConfiguration>
<ProdID>0</ProdID>
<ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x100000000</HeapMaxSize>
<TCSNum>128</TCSNum>
<TCSMaxNum>128</TCSMaxNum>
<TCSMinPool>128</TCSMinPool>
<ISVSVN>2</ISVSVN>
<StackMaxSize>0x200000</StackMaxSize>
<HeapMaxSize>0x200000</HeapMaxSize>
<TCSNum>16</TCSNum>
<TCSMaxNum>16</TCSMaxNum>
<TCSMinPool>16</TCSMinPool>
<TCSPolicy>0</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug>
......
<EnclaveConfiguration>
<ProdID>0</ProdID>
<ISVSVN>1</ISVSVN>
<ISVSVN>2</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x100000000</HeapMaxSize>
<TCSNum>128</TCSNum>
......
<EnclaveConfiguration>
<ProdID>0</ProdID>
<ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x1000000</HeapMaxSize>
<TCSNum>16</TCSNum>
<TCSMaxNum>16</TCSMaxNum>
<TCSMinPool>16</TCSMinPool>
<ISVSVN>2</ISVSVN>
<StackMaxSize>0x200000</StackMaxSize>
<HeapMaxSize>0x200000</HeapMaxSize>
<TCSNum>20</TCSNum>
<TCSMaxNum>20</TCSMaxNum>
<TCSMinPool>20</TCSMinPool>
<TCSPolicy>0</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug>
......
......@@ -88,15 +88,25 @@ enclave {
[out, count = 3072] uint8_t* decrypted_dkg_secret
);
public void trustedSetEncryptedDkgPoly(
[out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string,
public void trustedGetEncryptedSecretShare(
[out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string,
[in, count = 3050] uint8_t* encrypted_poly,
uint64_t enc_len);
uint64_t enc_len,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_skey,
[out] uint64_t* dec_len,
[out, count = 193] char* result_str,
[out, count = 320] char* s_shareG2,
[in, string] char* pub_keyB,
uint8_t _t,
uint8_t _n,
uint8_t ind);
public void trustedGetEncryptedSecretShare(
public void trustedGetEncryptedSecretShareV2(
[out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string,
[in, count = 3050] uint8_t* encrypted_poly,
uint64_t enc_len,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_skey,
[out] uint64_t* dec_len,
[out, count = 193] char* result_str,
......@@ -126,6 +136,17 @@ enclave {
int _ind,
[out] int* result);
public void trustedDkgVerifyV2(
[out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string,
[in, string] const char* public_shares,
[in, string] const char* s_share,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint64_t key_len,
unsigned _t,
int _ind,
[out] int* result);
public void trustedCreateBlsKey(
[out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string,
......
......@@ -47,7 +47,7 @@ void SGXWallet::printUsage() {
cerr << "\nAvailable flags:\n";
cerr << "\nDebug flags:\n\n";
cerr << " -v Verbose mode: turn on debug output\n";
cerr << " -vv Detailed verbose mode: turn on debug and trace outputs\n";
cerr << " -V Detailed verbose mode: turn on debug and trace outputs\n";
cerr << "\nBackup, restore, update flags:\n\n";
cerr << " -b filename Restore from back up or software update. You will need to put backup key into a file in sgx_data dir. \n";
cerr << " -y Do not ask user to acknowledge receipt of the backup key \n";
......
......@@ -115,14 +115,14 @@ int __ATTEMPTS__ = 0; \
do {\
__ATTEMPTS__++; \
{\
READ_LOCK(initMutex);
READ_LOCK(sgxInitMutex);
#define RESTART_END \
} \
if (status != SGX_SUCCESS || errStatus == 3) { \
spdlog::error(__FUNCTION__); \
spdlog::error("Restarting sgx on status errStatus... {} {}", status, errStatus); \
reinitEnclave(); \
spdlog::error("Exiting sgx on status errStatus... {} {}", status, errStatus); \
safeExit(); \
} \
} while ((status != SGX_SUCCESS || errStatus == 3) && __ATTEMPTS__ < 2);
......@@ -133,10 +133,9 @@ reinitEnclave(); \
if (status != SGX_SUCCESS || *errStatus == 3) { \
spdlog::error(__FUNCTION__);\
spdlog::error("Restarting sgx on status errStatus... {} {}", status, *errStatus); \
reinitEnclave(); \
safeExit(); \
} \
} while ((status != SGX_SUCCESS || *errStatus == 3) && __ATTEMPTS__ < 2);
#endif //SGXWALLET_SGXWALLET_COMMON_H
......@@ -39,6 +39,18 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value importECDSAKey(const std::string& keyShare, const std::string& keyShareName)
{
Json::Value p;
p["key"] = keyShare;
p["keyName"] = keyShareName;
Json::Value result = this->CallMethod("importECDSAKey",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value generateECDSAKey()
{
Json::Value p;
......@@ -113,6 +125,20 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getSecretShareV2(const std::string& polyName, const Json::Value& publicKeys, int t, int n)
{
Json::Value p;
p["polyName"] = polyName;
p["publicKeys"] = publicKeys;
p["n"] = n;
p["t"] = t;
Json::Value result = this->CallMethod("getSecretShareV2",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value dkgVerification(const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index)
{
Json::Value p;
......@@ -129,6 +155,22 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value dkgVerificationV2(const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index)
{
Json::Value p;
p["ethKeyName"] = ethKeyName;
p["secretShare"] = SecretShare;
p["index"] = index;
p["n"] = n;
p["publicShares"] = publicShares;
p["t"] = t;
Json::Value result = this->CallMethod("dkgVerificationV2",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n)
{
Json::Value p;
......@@ -171,10 +213,12 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value complaintResponse(const std::string& polyName, int ind)
Json::Value complaintResponse(const std::string& polyName, int t, int n,int ind)
{
Json::Value p;
p["polyName"] = polyName;
p["t"] = t;
p["n"] = n;
p["ind"] = ind;
Json::Value result = this->CallMethod("complaintResponse",p);
if (result.isObject())
......
......@@ -21,16 +21,14 @@
@date 2020
*/
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <libff/algebra/exponentiation/exponentiation.hpp>
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h>
#include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h"
#include "secure_enclave_u.h"
#include "secure_enclave/DHDkg.h"
#include "third_party/intel/sgx_detect.h"
#include <gmp.h>
#include <sgx_urts.h>
......@@ -372,10 +370,33 @@ TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", "[dkg-aes-
REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS);
uint64_t enc_len = encLen;
vector <uint8_t> encrPRDHKey(BUF_LEN, 0);
string pub_keyB = SAMPLE_PUBLIC_KEY_B;
vector<char> s_shareG2(BUF_LEN, 0);
PRINT_SRC_LINE
status = trustedGetEncryptedSecretShare(eid, &errStatus,errMsg.data(),
encryptedDKGSecret.data(), encLen,
encrPRDHKey.data(), &encLen,
result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS);
}
TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares version 2 test", "[dkg-aes-encr-sshares-v2]") {
vector<char> errMsg(BUF_LEN, 0);
vector<char> result(BUF_LEN, 0);
int errStatus = 0;
uint64_t encLen = 0;
vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
PRINT_SRC_LINE
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), enc_len);
auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS);
......@@ -385,7 +406,9 @@ TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", "[dkg-aes-
vector<char> s_shareG2(BUF_LEN, 0);
PRINT_SRC_LINE
status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &encLen,
status = trustedGetEncryptedSecretShareV2(eid, &errStatus,errMsg.data(),
encryptedDKGSecret.data(), encLen,
encrPRDHKey.data(), &encLen,
result.data(),
s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1);
......@@ -436,19 +459,62 @@ TEST_CASE_METHOD(TestFixture, "DKG_BLS test", "[dkg-bls]") {
TestUtils::doDKG(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
}
TEST_CASE_METHOD(TestFixture, "DKG_BLS V2 test", "[dkg-bls-v2]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
vector <string> ecdsaKeyNames;
vector <string> blsKeyNames;
int schainID = TestUtils::randGen();
int dkgID = TestUtils::randGen();
PRINT_SRC_LINE
TestUtils::doDKGV2(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
REQUIRE(blsKeyNames.size() == 4);
schainID = TestUtils::randGen();
dkgID = TestUtils::randGen();
TestUtils::doDKGV2(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
}
TEST_CASE_METHOD(TestFixture, "Delete Bls Key", "[delete-bls-key]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0";
libff::alt_bn128_Fr key = libff::alt_bn128_Fr(
"6507625568967977077291849236396320012317305261598035438182864059942098934847");
std::string key_str = TestUtils::stringFromFr(key);
PRINT_SRC_LINE
c.importBLSKeyShare(key_str, name);
PRINT_SRC_LINE
auto response = c.importBLSKeyShare(key_str, name);
REQUIRE(response["status"] != 0);
key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
response = c.importBLSKeyShare(key_str, name);
REQUIRE(response["status"] == 0);
REQUIRE(c.blsSignMessageHash(name, SAMPLE_HASH, 1, 1)["status"] == 0);
REQUIRE(c.deleteBlsKey(name)["deleted"] == true);
}
TEST_CASE_METHOD(TestFixture, "Import ECDSA Key", "[import-ecdsa-key]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
std::string name = "NEK:abcdef";
auto response = c.importECDSAKey("6507625568967977077291849236396320012317305261598035438182864059942098934847", name);
REQUIRE(response["status"] != 0);
string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
response = c.importECDSAKey(key_str, name);
REQUIRE(response["status"] == 0);
REQUIRE(c.ecdsaSignMessageHash(16, name, SAMPLE_HASH)["status"] == 0);
}
TEST_CASE_METHOD(TestFixture, "Backup Key", "[backup-key]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
......@@ -563,6 +629,66 @@ TEST_CASE_METHOD(TestFixture, "DKG API test", "[dkg-api]") {
REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
}
TEST_CASE_METHOD(TestFixture, "DKG API V2 test", "[dkg-api-v2]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
string polyName = SAMPLE_POLY_NAME;
PRINT_SRC_LINE
Json::Value genPoly = c.generateDKGPoly(polyName, 2);
REQUIRE(genPoly["status"].asInt() == 0);
Json::Value publicKeys;
publicKeys.append(SAMPLE_DKG_PUB_KEY_1);
publicKeys.append(SAMPLE_DKG_PUB_KEY_2);
// wrongName
Json::Value genPolyWrongName = c.generateDKGPoly("poly", 2);
REQUIRE(genPolyWrongName["status"].asInt() != 0);
Json::Value verifVectWrongName = c.getVerificationVector("poly", 2, 2);
REQUIRE(verifVectWrongName["status"].asInt() != 0);
Json::Value secretSharesWrongName = c.getSecretShareV2("poly", publicKeys, 2, 2);
REQUIRE(secretSharesWrongName["status"].asInt() != 0);
// wrong_t
Json::Value genPolyWrong_t = c.generateDKGPoly(polyName, 33);
REQUIRE(genPolyWrong_t["status"].asInt() != 0);
Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1, 2);
REQUIRE(verifVectWrong_t["status"].asInt() != 0);
Json::Value secretSharesWrong_t = c.getSecretShareV2(polyName, publicKeys, 3, 3);
REQUIRE(secretSharesWrong_t["status"].asInt() != 0);
// wrong_n
Json::Value verifVectWrong_n = c.getVerificationVector(polyName, 2, 1);
REQUIRE(verifVectWrong_n["status"].asInt() != 0);
Json::Value publicKeys1;
publicKeys1.append(SAMPLE_DKG_PUB_KEY_1);
Json::Value secretSharesWrong_n = c.getSecretShareV2(polyName, publicKeys1, 2, 1);
REQUIRE(secretSharesWrong_n["status"].asInt() != 0);
//wrong number of publicKeys
Json::Value secretSharesWrongPkeys = c.getSecretShareV2(polyName, publicKeys, 2, 3);
REQUIRE(secretSharesWrongPkeys["status"].asInt() != 0);
//wrong verif
Json::Value Skeys = c.getSecretShareV2(polyName, publicKeys, 2, 2);
REQUIRE_NOTHROW(c.getSecretShare(polyName, publicKeys, 2, 2));
REQUIRE(Skeys == c.getSecretShare(polyName, publicKeys, 2, 2));
Json::Value verifVect = c.getVerificationVector(polyName, 2, 2);
REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2, 2));
REQUIRE(verifVect == c.getVerificationVector(polyName, 2, 2));
Json::Value verificationWrongSkeys = c.dkgVerificationV2("", "", "", 2, 2, 1);
REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
}
TEST_CASE_METHOD(TestFixture, "PolyExists test", "[dkg-poly-exists]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
......@@ -643,15 +769,58 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
REQUIRE(res);
}
Json::Value complaintResponse = c.complaintResponse(polyNames[1], 0);
Json::Value complaintResponse = c.complaintResponse(polyNames[1], t, n, 0);
REQUIRE(complaintResponse["status"] == 0);
string dhKey = complaintResponse["dhKey"].asString();
string shareG2 = complaintResponse["share*G2"].asString();
string secretShare = secretShares[1]["secretShare"].asString().substr(0, 192);
vector<char> message (65, 0);
SAFE_CHAR_BUF(encr_sshare, BUF_LEN)
strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128);
SAFE_CHAR_BUF(common_key, BUF_LEN);
REQUIRE(sessionKeyRecoverDH(dhKey.c_str(), encr_sshare, common_key) == 0);
SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN)
strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1);
REQUIRE(xorDecryptDH(common_key, encr_sshare_check, message) == 0);
mpz_t hex_share;
mpz_init(hex_share);
mpz_set_str(hex_share, message.data(), 16);
libff::alt_bn128_Fr share(hex_share);
libff::alt_bn128_G2 decrypted_share_G2 = share * libff::alt_bn128_G2::one();
decrypted_share_G2.to_affine_coordinates();
mpz_clear(hex_share);
REQUIRE( convertG2ToString(decrypted_share_G2) == shareG2 );
Json::Value verificationVectorMult = complaintResponse["verificationVectorMult"];
libff::alt_bn128_G2 verificationValue = libff::alt_bn128_G2::zero();
for (int i = 0; i < t; ++i) {
libff::alt_bn128_G2 value;
value.Z = libff::alt_bn128_Fq2::one();
value.X.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][0].asCString());
value.X.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][1].asCString());
value.Y.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][2].asCString());
value.Y.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][3].asCString());
verificationValue = verificationValue + value;
}
verificationValue.to_affine_coordinates();
REQUIRE( verificationValue == decrypted_share_G2 );
BLSSigShareSet sigShareSet(t, n);
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;
......@@ -698,6 +867,171 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
}
TEST_CASE_METHOD(TestFixture, "AES_DKG V2 test", "[aes-dkg-v2]") {
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 pubEthKeys;
Json::Value secretShares[n];
Json::Value pubBLSKeys[n];
Json::Value blsSigShares[n];
vector <string> pubShares(n);
vector <string> polyNames(n);
int schainID = TestUtils::randGen();
int dkgID = TestUtils::randGen();
for (uint8_t i = 0; i < n; i++) {
PRINT_SRC_LINE
ethKeys[i] = c.generateECDSAKey();
REQUIRE(ethKeys[i]["status"] == 0);
string polyName =
"POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
REQUIRE(ethKeys[i]["status"] == 0);
auto response = c.generateDKGPoly(polyName, t);
REQUIRE(response["status"] == 0);
polyNames[i] = polyName;
PRINT_SRC_LINE
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++) {
PRINT_SRC_LINE
secretShares[i] = c.getSecretShareV2(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] += TestUtils::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);
PRINT_SRC_LINE
Json::Value verif = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
REQUIRE(verif["status"] == 0);
bool res = verif["result"].asBool();
k++;
REQUIRE(res);
}
Json::Value complaintResponse = c.complaintResponse(polyNames[1], t, n, 0);
REQUIRE(complaintResponse["status"] == 0);
string dhKey = complaintResponse["dhKey"].asString();
string shareG2 = complaintResponse["share*G2"].asString();
string secretShare = secretShares[1]["secretShare"].asString().substr(0, 192);
vector<char> message (65, 0);
SAFE_CHAR_BUF(encr_sshare, BUF_LEN)
strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128);
SAFE_CHAR_BUF(common_key, BUF_LEN);
REQUIRE(sessionKeyRecoverDH(dhKey.c_str(), encr_sshare, common_key) == 0);
auto hashed_key = cryptlite::sha256::hash_hex(string(common_key, 64));
SAFE_CHAR_BUF(derived_key, 33)
uint64_t key_length;
REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t*) derived_key, 33));
SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN)
strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1);
REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0);
mpz_t hex_share;
mpz_init(hex_share);
mpz_set_str(hex_share, message.data(), 16);
libff::alt_bn128_Fr share(hex_share);
libff::alt_bn128_G2 decrypted_share_G2 = share * libff::alt_bn128_G2::one();
decrypted_share_G2.to_affine_coordinates();
mpz_clear(hex_share);
REQUIRE( convertG2ToString(decrypted_share_G2) == shareG2 );
Json::Value verificationVectorMult = complaintResponse["verificationVectorMult"];
libff::alt_bn128_G2 verificationValue = libff::alt_bn128_G2::zero();
for (int i = 0; i < t; ++i) {
libff::alt_bn128_G2 value;
value.Z = libff::alt_bn128_Fq2::one();
value.X.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][0].asCString());
value.X.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][1].asCString());
value.Y.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][2].asCString());
value.Y.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][3].asCString());
verificationValue = verificationValue + value;
}
verificationValue.to_affine_coordinates();
REQUIRE( verificationValue == decrypted_share_G2 );
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(), 32)) {
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);
auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
n);
REQUIRE(response["status"] == 0);
PRINT_SRC_LINE
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
REQUIRE(pubBLSKeys[i]["status"] == 0);
string hash = SAMPLE_HASH;
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
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));
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);
PRINT_SRC_LINE
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);
REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
}
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
int errStatus = 0;
vector<char> errMsg(BUF_LEN, 0);
......@@ -716,12 +1050,24 @@ TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data());
REQUIRE(status == 0);
REQUIRE(errStatus == 0);
REQUIRE(key.compare(decr_key.data()) == 0);
REQUIRE(errStatus == 0);
}
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypto]") {
vector <thread> threads;
int num_threads = 16;
for (int i = 0; i < num_threads; i++) {
threads.push_back(thread(TestUtils::sendRPCRequest));
}
for (auto &thread : threads) {
thread.join();
}
}
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls", "[many-threads-crypto-v2]") {
vector <thread> threads;
int num_threads = 4;
for (int i = 0; i < num_threads; i++) {
......
......@@ -31,7 +31,7 @@
#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 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"
......
......@@ -30,12 +30,15 @@ topDir = os.getcwd() + "/sgxwallet"
print("Top directory is:" + topDir)
testList = ["[first-run]",
"[second-run]",
"[many-threads-crypto]",
"[many-threads-crypto-v2]",
"[backup-restore]",
"[cert-sign]",
"[get-server-status]",
"[get-server-version]",
"[backup-key]",
"[delete-bls-key]",
"[import-ecdsa-key]",
"[ecdsa-aes-key-gen]",
"[ecdsa-aes-key-sig-gen]",
"[ecdsa-aes-get-pub-key]",
......@@ -43,14 +46,16 @@ testList = ["[first-run]",
"[bls-key-encrypt]",
"[dkg-aes-gen]",
"[dkg-aes-encr-sshares]",
"[dkg-verify]",
"[dkg-aes-encr-sshares-v2]",
"[dkg-api]",
"[dkg-api-v2]",
"[dkg-bls]",
"[dkg-bls-v2]",
"[dkg-poly-exists]",
"[dkg-aes-pub-shares]",
"[many-threads-crypto]",
"[aes-encrypt-decrypt]",
"[aes-dkg]"
"[aes-dkg]",
"[aes-dkg-v2]"
]
......
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