diff --git a/.github/workflows/clang-format-check.yml b/.github/workflows/clang-format-check.yml new file mode 100644 index 00000000..36aadc73 --- /dev/null +++ b/.github/workflows/clang-format-check.yml @@ -0,0 +1,14 @@ +name: clang-format Check +on: [push] +jobs: + formatting-check: + name: Formatting Check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: DoozyX/clang-format-lint-action@v0.14 + with: + source: '.' + exclude: './CMakeFiles ./cmake ./deps ./build ./cppzmq ./gmp-build ./intel-sgx-ssl ./jsonrpc ./leveldb ./libBLS ./libzmq ./linux-sgx-driver ./rapidjson ./sgx-gmp ./sgx-sdk-build ./sgx-software-enable ./tgmp-build ./third_party/* ./newer_lcov' + extensions: 'h,hpp,hxx,cpp,cxx,cc,ipp' + clangFormatVersion: 14 diff --git a/.github/workflows/dockerimage.yml b/.github/workflows/dockerimage.yml index 09acbf14..ee92b147 100644 --- a/.github/workflows/dockerimage.yml +++ b/.github/workflows/dockerimage.yml @@ -4,7 +4,7 @@ on: push: jobs: build: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 env: ACTIONS_ALLOW_UNSECURE_COMMANDS: true DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} diff --git a/.github/workflows/dockerimagebase.yml b/.github/workflows/dockerimagebase.yml index 17e4b57b..898f02bd 100644 --- a/.github/workflows/dockerimagebase.yml +++ b/.github/workflows/dockerimagebase.yml @@ -6,7 +6,7 @@ on: - build_base* jobs: build: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 env: ACTIONS_ALLOW_UNSECURE_COMMMANDS: true DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} diff --git a/.github/workflows/dockerimageintelsubmission.yml b/.github/workflows/dockerimageintelsubmission.yml index f6ab86ee..731b05d2 100644 --- a/.github/workflows/dockerimageintelsubmission.yml +++ b/.github/workflows/dockerimageintelsubmission.yml @@ -4,7 +4,7 @@ on: push: jobs: build: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 env: DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} diff --git a/.github/workflows/dockerimagerelease.yml b/.github/workflows/dockerimagerelease.yml index d5beb5ea..4de75ca4 100644 --- a/.github/workflows/dockerimagerelease.yml +++ b/.github/workflows/dockerimagerelease.yml @@ -6,7 +6,7 @@ on: - stable jobs: build: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 env: DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} diff --git a/.github/workflows/dockerimagesim.yml b/.github/workflows/dockerimagesim.yml index b85318f0..299c3b1a 100644 --- a/.github/workflows/dockerimagesim.yml +++ b/.github/workflows/dockerimagesim.yml @@ -4,7 +4,7 @@ on: push: jobs: build: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 env: DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} @@ -21,7 +21,7 @@ jobs: - name: Build and publish container for testing run: python3 scripts/docker_build.py DockerfileSimulation sgxwallet_sim ${GITHUB_SHA} - name: test - run: python3 scripts/docker_test.py DockerfileSimulation sgxwallet_sim + run: python3 scripts/docker_test.py DockerfileSimulation sgxwallet_sim ${GITHUB_SHA} - name: build and deploy docker image if: | contains(github.ref, 'develop') || contains(github.ref, 'beta') || diff --git a/.github/workflows/issue_check.yml b/.github/workflows/issue_check.yml new file mode 100644 index 00000000..ee5ec6b2 --- /dev/null +++ b/.github/workflows/issue_check.yml @@ -0,0 +1,19 @@ +name: Get linked issues +on: + pull_request: + types: [ edited, synchronize, opened, reopened ] + +jobs: + check-linked-issues: + name: Check if pull request has linked issues + runs-on: ubuntu-latest + steps: + - name: Get issues + id: get-issues + uses: mondeja/pr-linked-issues-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }} + - name: PR has not linked issues + if: join(steps.get-issues.outputs.issues) == '' + run: + exit 1 diff --git a/BLSCrypto.cpp b/BLSCrypto.cpp index 9a31ca9b..382a4dd9 100644 --- a/BLSCrypto.cpp +++ b/BLSCrypto.cpp @@ -21,150 +21,250 @@ @date 2019 */ -#include -#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" #include "leveldb/db.h" +#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" #include +#include #include "third_party/intel/create_enclave.h" +#include -#include "bls.h" -#include - -#include "BLSPrivateKeyShareSGX.h" - - -#include "sgxwallet_common.h" -#include "sgxwallet.h" #include "SGXException.h" -#include "third_party/spdlog/spdlog.h" +#include "SGXWalletServer.hpp" #include "common.h" -#include "SGXWalletServer.h" +#include "sgxwallet.h" +#include "sgxwallet_common.h" +#include "third_party/spdlog/spdlog.h" -#include "SEKManager.h" -#include "LevelDB.h" -#include "ServerInit.h" #include "BLSCrypto.h" #include "CryptoTools.h" +#include "LevelDB.h" +#include "SEKManager.h" +#include "ServerInit.h" + +shared_ptr FqToString(libff::alt_bn128_Fq *_fq) { + + CHECK_STATE(_fq); + + mpz_t t; + mpz_init(t); + + _fq->as_bigint().to_mpz(t); + + SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2); + + mpz_get_str(arr, 10, t); + mpz_clear(t); + + return make_shared(string(arr)); +} + +bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, + size_t _n, char *_sig) { + + CHECK_STATE(_encryptedKeyHex); + CHECK_STATE(_hashHex); + CHECK_STATE(_sig); + + auto hash = make_shared>(); + uint64_t binLen; -string *FqToString(libff::alt_bn128_Fq *_fq) { + if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) { + throw SGXException(SIGN_AES_INVALID_HASH, + string(__FUNCTION__) + ":Invalid hash"); + } - CHECK_STATE(_fq); + shared_ptr obj; + obj = make_shared(libBLS::Bls(_t, _n)); - mpz_t t; - mpz_init(t); + pair hash_with_hint = + obj->HashtoG1withHint(hash); - _fq->as_bigint().to_mpz(t); + shared_ptr xStr = FqToString(&(hash_with_hint.first.X)); - SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2); + CHECK_STATE(xStr); - mpz_get_str(arr, 10, t); - mpz_clear(t); + shared_ptr yStr = FqToString(&(hash_with_hint.first.Y)); - return new string(arr); + CHECK_STATE(yStr); + + vector errMsg(BUF_LEN, 0); + + SAFE_CHAR_BUF(xStrArg, BUF_LEN); + SAFE_CHAR_BUF(yStrArg, BUF_LEN); + SAFE_CHAR_BUF(signature, BUF_LEN); + + strncpy(xStrArg, xStr->c_str(), BUF_LEN); + strncpy(yStrArg, yStr->c_str(), BUF_LEN); + + size_t sz = 0; + + SAFE_UINT8_BUF(encryptedKey, BUF_LEN); + + bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey, BUF_LEN); + + if (!result) { + BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); + } + + int errStatus = 0; + + sgx_status_t status = SGX_SUCCESS; + + status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey, + sz, xStrArg, yStrArg, signature); + + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + + string hint = + libBLS::ThresholdUtils::fieldElementToString(hash_with_hint.first.Y) + + ":" + hash_with_hint.second; + + string sig = signature; + + sig.append(":"); + sig.append(hint); + + strncpy(_sig, sig.c_str(), BUF_LEN); + + return true; +} + +bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, + size_t _n, char *_sig) { + CHECK_STATE(_encryptedKeyHex); + CHECK_STATE(_hashHex); + return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _sig); } -bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) { +bool popProveSGX(const char *encryptedKeyHex, char *prove) { + CHECK_STATE(encryptedKeyHex); + + SAFE_UINT8_BUF(encryptedKey, BUF_LEN); - CHECK_STATE(_encryptedKeyHex); - CHECK_STATE(_hashHex); - CHECK_STATE(_sig); + size_t sz = 0; - auto hash = make_shared < array < uint8_t, 32 >> (); + if (!hex2carray(encryptedKeyHex, &sz, encryptedKey, BUF_LEN)) { + BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); + } - uint64_t binLen; + sgx_status_t status = SGX_SUCCESS; - if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) { - throw SGXException(SIGN_AES_INVALID_HASH, string(__FUNCTION__) + ":Invalid hash"); - } + vector errMsg(BUF_LEN, 0); - shared_ptr obj; - obj = make_shared(signatures::Bls(_t, _n)); + int errStatus = 0; - pair hash_with_hint = obj->HashtoG1withHint(hash); + SAFE_CHAR_BUF(pubKey, 320) - string *xStr = FqToString(&(hash_with_hint.first.X)); + status = trustedGetBlsPubKey(eid, &errStatus, errMsg.data(), encryptedKey, sz, + pubKey); - CHECK_STATE(xStr); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - string *yStr = FqToString(&(hash_with_hint.first.Y)); + vector pubKeyVect = splitString(pubKey, ':'); - if (yStr == nullptr) { - delete xStr; - BOOST_THROW_EXCEPTION(runtime_error("Null yStr")); - } + spdlog::debug("pub key is "); + for (int i = 0; i < 4; i++) + spdlog::debug("{}", pubKeyVect.at(i)); - vector errMsg(BUF_LEN, 0); + libff::alt_bn128_G2 publicKey; + publicKey.Z = libff::alt_bn128_Fq2::one(); + publicKey.X.c0 = libff::alt_bn128_Fq(pubKeyVect[0].c_str()); + publicKey.X.c1 = libff::alt_bn128_Fq(pubKeyVect[1].c_str()); + publicKey.Y.c0 = libff::alt_bn128_Fq(pubKeyVect[2].c_str()); + publicKey.Y.c1 = libff::alt_bn128_Fq(pubKeyVect[3].c_str()); - SAFE_CHAR_BUF(xStrArg, BUF_LEN);SAFE_CHAR_BUF(yStrArg, BUF_LEN);SAFE_CHAR_BUF(signature, BUF_LEN); + pair hashPublicKeyWithHint = + libBLS::Bls::HashPublicKeyToG1WithHint(publicKey); - strncpy(xStrArg, xStr->c_str(), BUF_LEN); - strncpy(yStrArg, yStr->c_str(), BUF_LEN); + hashPublicKeyWithHint.first.to_affine_coordinates(); - delete xStr; - delete yStr; + shared_ptr xStr = FqToString(&(hashPublicKeyWithHint.first.X)); - size_t sz = 0; + CHECK_STATE(xStr); - SAFE_UINT8_BUF(encryptedKey, BUF_LEN); + shared_ptr yStr = FqToString(&(hashPublicKeyWithHint.first.Y)); - bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey, BUF_LEN); + CHECK_STATE(yStr); - if (!result) { - BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); - } + SAFE_CHAR_BUF(xStrArg, BUF_LEN); + SAFE_CHAR_BUF(yStrArg, BUF_LEN); - int errStatus = 0; + strncpy(xStrArg, xStr->c_str(), BUF_LEN); + strncpy(yStrArg, yStr->c_str(), BUF_LEN); - sgx_status_t status = SGX_SUCCESS; + errStatus = 0; - status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey, - sz, xStrArg, yStrArg, signature); + status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey, + sz, xStrArg, yStrArg, prove); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + hash_with_hint.second; + string hint = libBLS::ThresholdUtils::fieldElementToString( + hashPublicKeyWithHint.first.Y) + + ":" + hashPublicKeyWithHint.second; - string sig = signature; + string _prove = prove; - sig.append(":"); - sig.append(hint); + _prove.append(":"); + _prove.append(hint); - strncpy(_sig, sig.c_str(), BUF_LEN); + strncpy(prove, _prove.c_str(), BUF_LEN); - return true; + return true; } -bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) { - CHECK_STATE(_encryptedKeyHex); - CHECK_STATE(_hashHex); - return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _sig); +bool generateBLSPrivateKeyAggegated(const char *blsKeyName) { + CHECK_STATE(blsKeyName); + + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + + int exportable = 0; + + uint64_t encBlsLen = 0; + + sgx_status_t status = SGX_SUCCESS; + + SAFE_UINT8_BUF(encrBlsKey, BUF_LEN) + + status = trustedGenerateBLSKey(eid, &errStatus, errMsg.data(), &exportable, + encrBlsKey, &encBlsLen); + + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + + vector hexBLSKey = carray2Hex(encrBlsKey, encBlsLen); + + SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data()); + + return true; } -string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) { - CHECK_STATE(errStatus); - CHECK_STATE(err_string); - CHECK_STATE(_key); - auto keyArray = make_shared < vector < char >> (BUF_LEN, 0); - auto encryptedKey = make_shared < vector < uint8_t >> (BUF_LEN, 0); +string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, + const char *_key) { + CHECK_STATE(errStatus); + CHECK_STATE(err_string); + CHECK_STATE(_key); + auto keyArray = make_shared>(BUF_LEN, 0); + auto encryptedKey = make_shared>(BUF_LEN, 0); - vector errMsg(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); - strncpy(keyArray->data(), _key, BUF_LEN); - *errStatus = 0; + strncpy(keyArray->data(), _key, BUF_LEN); + *errStatus = 0; - uint64_t encryptedLen = 0; + uint64_t encryptedLen = 0; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedEncryptKey(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(), - &encryptedLen); + status = trustedEncryptKey(eid, errStatus, errMsg.data(), keyArray->data(), + encryptedKey->data(), &encryptedLen); - HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data()); - vector resultBuf = carray2Hex(encryptedKey->data(), encryptedLen); + vector resultBuf = carray2Hex(encryptedKey->data(), encryptedLen); - return string(resultBuf.begin(), resultBuf.end()); + return string(resultBuf.begin(), resultBuf.end()); } diff --git a/BLSCrypto.h b/BLSCrypto.h index 4cfd3007..4d7bd124 100644 --- a/BLSCrypto.h +++ b/BLSCrypto.h @@ -32,11 +32,22 @@ #include "stddef.h" #include "stdint.h" +#include #include #include -EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t, size_t n, char* _sig); +#include "bls.h" -std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key); +EXTERNC bool bls_sign(const char *encryptedKeyHex, const char *hashHex, + size_t t, size_t n, char *_sig); -#endif //SGXWALLET_BLSCRYPTO_H +EXTERNC bool popProveSGX(const char *encryptedKeyHex, char *_prove); + +EXTERNC bool generateBLSPrivateKeyAggegated(const char *blsKeyName); + +std::shared_ptr FqToString(libff::alt_bn128_Fq *_fq); + +std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, + const char *_key); + +#endif // SGXWALLET_BLSCRYPTO_H diff --git a/BLSPrivateKeyShareSGX.cpp b/BLSPrivateKeyShareSGX.cpp index c22127f1..1a746ada 100644 --- a/BLSPrivateKeyShareSGX.cpp +++ b/BLSPrivateKeyShareSGX.cpp @@ -23,165 +23,137 @@ #include "BLSSigShare.h" #include "BLSSignature.h" -#include "BLSutils.h" +#include -#include "third_party/spdlog/spdlog.h" #include "common.h" #include "secure_enclave_u.h" -#include "sgxwallet_common.h" #include "sgxwallet.h" +#include "sgxwallet_common.h" +#include "third_party/spdlog/spdlog.h" #include "BLSCrypto.h" +#include "BLSPrivateKeyShareSGX.h" #include "CryptoTools.h" -#include "ServerInit.h" #include "SEKManager.h" -#include "BLSPrivateKeyShareSGX.h" - -string *stringFromFq(libff::alt_bn128_Fq *_fq) { - - CHECK_STATE(_fq); - - mpz_t t; - mpz_init(t); - - _fq->as_bigint().to_mpz(t); - - SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2); - - char *tmp = mpz_get_str(arr, 10, t); - - mpz_clear(t); - - return new string(tmp); -} - -string *stringFromG1(libff::alt_bn128_G1 *_g1) { +#include "ServerInit.h" - CHECK_STATE(_g1); +shared_ptr stringFromG1(libff::alt_bn128_G1 *_g1) { - auto sX = stringFromFq(&_g1->X); - auto sY = stringFromFq(&_g1->Y); - auto sZ = stringFromFq(&_g1->Z); + CHECK_STATE(_g1); - auto sG1 = new string(*sX + ":" + *sY + ":" + *sZ); + auto sX = FqToString(&_g1->X); + auto sY = FqToString(&_g1->Y); + auto sZ = FqToString(&_g1->Z); - delete (sX); - delete (sY); - delete (sZ); + auto sG1 = make_shared(*sX + ":" + *sY + ":" + *sZ); - return sG1; + return sG1; } BLSPrivateKeyShareSGX::BLSPrivateKeyShareSGX( - shared_ptr _encryptedKeyHex, size_t _requiredSigners, - size_t _totalSigners) { - requiredSigners = _requiredSigners; - totalSigners = _totalSigners; + shared_ptr _encryptedKeyHex, size_t _requiredSigners, + size_t _totalSigners) { + requiredSigners = _requiredSigners; + totalSigners = _totalSigners; - if (requiredSigners > totalSigners) { - throw invalid_argument("requiredSigners > totalSigners"); - } + if (requiredSigners > totalSigners) { + throw invalid_argument("requiredSigners > totalSigners"); + } - if (totalSigners == 0) { - throw invalid_argument("totalSigners == 0"); - } + if (totalSigners == 0) { + throw invalid_argument("totalSigners == 0"); + } - if (_encryptedKeyHex == nullptr) { - throw invalid_argument("Null key"); - } + if (_encryptedKeyHex == nullptr) { + throw invalid_argument("Null key"); + } - if (_encryptedKeyHex->size() > 2 * MAX_ENCRYPTED_KEY_LENGTH) { - throw invalid_argument("Encrypted key size too long"); - } + if (_encryptedKeyHex->size() > 2 * MAX_ENCRYPTED_KEY_LENGTH) { + throw invalid_argument("Encrypted key size too long"); + } - encryptedKeyHex = _encryptedKeyHex; + encryptedKeyHex = _encryptedKeyHex; } string BLSPrivateKeyShareSGX::signWithHelperSGXstr( - shared_ptr > hash_byte_arr, - size_t _signerIndex) { - shared_ptr obj; - - CHECK_STATE(hash_byte_arr) - - obj = make_shared( - signatures::Bls(requiredSigners, totalSigners)); + shared_ptr> hash_byte_arr, size_t _signerIndex) { + shared_ptr obj; - pair hash_with_hint = - obj->HashtoG1withHint(hash_byte_arr); + CHECK_STATE(hash_byte_arr) - int errStatus = 0; + obj = make_shared(libBLS::Bls(requiredSigners, totalSigners)); - string *xStr = stringFromFq(&(hash_with_hint.first.X)); + pair hash_with_hint = + obj->HashtoG1withHint(hash_byte_arr); - CHECK_STATE(xStr); + int errStatus = 0; - string *yStr = stringFromFq(&(hash_with_hint.first.Y)); + shared_ptr xStr = FqToString(&(hash_with_hint.first.X)); - if (yStr == nullptr) { - delete xStr; - BOOST_THROW_EXCEPTION(runtime_error("Null yStr")); - } + CHECK_STATE(xStr); - vector errMsg(BUF_LEN, 0); + shared_ptr yStr = FqToString(&(hash_with_hint.first.Y)); - SAFE_CHAR_BUF(xStrArg, BUF_LEN)SAFE_CHAR_BUF(yStrArg, BUF_LEN)SAFE_CHAR_BUF(signature, BUF_LEN); + CHECK_STATE(yStr); - strncpy(xStrArg, xStr->c_str(), BUF_LEN); - strncpy(yStrArg, yStr->c_str(), BUF_LEN); + vector errMsg(BUF_LEN, 0); - delete xStr; - delete yStr; + SAFE_CHAR_BUF(xStrArg, BUF_LEN) + SAFE_CHAR_BUF(yStrArg, BUF_LEN) SAFE_CHAR_BUF(signature, BUF_LEN); - size_t sz = 0; + strncpy(xStrArg, xStr->c_str(), BUF_LEN); + strncpy(yStrArg, yStr->c_str(), BUF_LEN); - SAFE_UINT8_BUF(encryptedKey, BUF_LEN); + size_t sz = 0; - bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey, - BUF_LEN); + SAFE_UINT8_BUF(encryptedKey, BUF_LEN); - if (!result) { - spdlog::error("Invalid hex encrypted key"); - BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); - } + bool result = + hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey, BUF_LEN); - sgx_status_t status = SGX_SUCCESS; + if (!result) { + spdlog::error("Invalid hex encrypted key"); + BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); + } - status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey, - encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature); + sgx_status_t status = SGX_SUCCESS; - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey, + encryptedKeyHex->size() / 2, xStrArg, yStrArg, + signature); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - int sigLen; + int sigLen; - if ((sigLen = strnlen(signature, 10)) < 10) { - BOOST_THROW_EXCEPTION(runtime_error("Signature is too short:" + to_string(sigLen))); - } + if ((sigLen = strnlen(signature, 10)) < 10) { + BOOST_THROW_EXCEPTION( + runtime_error("Signature is too short:" + to_string(sigLen))); + } - string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + - hash_with_hint.second; + string hint = + libBLS::ThresholdUtils::fieldElementToString(hash_with_hint.first.Y) + + ":" + hash_with_hint.second; - string sig = signature; + string sig = signature; - sig.append(":"); - sig.append(hint); + sig.append(":"); + sig.append(hint); - return sig; + return sig; } -shared_ptr BLSPrivateKeyShareSGX::signWithHelperSGX( - shared_ptr > hash_byte_arr, - size_t _signerIndex) { +shared_ptr BLSPrivateKeyShareSGX::signWithHelperSGX( + shared_ptr> hash_byte_arr, size_t _signerIndex) { - CHECK_STATE(hash_byte_arr); + CHECK_STATE(hash_byte_arr); - string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex); + string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex); - auto sig = make_shared(signature); + auto sig = make_shared(signature); - shared_ptr s = make_shared(sig, _signerIndex, requiredSigners, - totalSigners); + shared_ptr s = make_shared( + sig, _signerIndex, requiredSigners, totalSigners); - return s; + return s; } diff --git a/BLSPrivateKeyShareSGX.h b/BLSPrivateKeyShareSGX.h index e11115ec..45e60660 100644 --- a/BLSPrivateKeyShareSGX.h +++ b/BLSPrivateKeyShareSGX.h @@ -25,8 +25,8 @@ #define SGXWALLET_BLSPRIVATEKEYSHARESGX_H #define SGXWALLET_BLSPRIVATEKEYSHARESGX_H -#include "BLSSigShare.h" #include "BLSPrivateKeyShare.h" +#include "BLSSigShare.h" class BLSPrivateKeyShareSGX { size_t requiredSigners; @@ -34,14 +34,15 @@ class BLSPrivateKeyShareSGX { size_t totalSigners; std::shared_ptr encryptedKeyHex; + public: std::shared_ptr - signWithHelperSGX(std::shared_ptr> _hash, - size_t _signerIndex); + signWithHelperSGX(std::shared_ptr> _hash, + size_t _signerIndex); - std::string signWithHelperSGXstr( - std::shared_ptr> hash_byte_arr, - size_t _signerIndex); + std::string + signWithHelperSGXstr(std::shared_ptr> hash_byte_arr, + size_t _signerIndex); BLSPrivateKeyShareSGX(std::shared_ptr _encryptedKeyHex, size_t _requiredSigners, size_t _totalSigners); diff --git a/CMakeLists.txt b/CMakeLists.txt index 81e0ed78..02343516 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,7 +44,7 @@ add_executable(sgxwallet BLSCrypto.h BLSPrivateKeyShareSGX.cpp BLSPrivateKeyShareSGX.h - catch.hpp + third_party/catch.hpp cert_util.cpp common.h create_enclave.c diff --git a/CSRManagerServer.cpp b/CSRManagerServer.cpp index e7cbb085..9914ac8a 100644 --- a/CSRManagerServer.cpp +++ b/CSRManagerServer.cpp @@ -21,8 +21,8 @@ @date 2019 */ -#include #include +#include #include @@ -37,101 +37,110 @@ shared_ptr CSRManagerServer::cs = nullptr; shared_ptr CSRManagerServer::hs3 = nullptr; CSRManagerServer::CSRManagerServer(AbstractServerConnector &connector, - serverVersion_t type) : abstractCSRManagerServer(connector, type) {} + serverVersion_t type) + : abstractCSRManagerServer(connector, type) {} Json::Value getUnsignedCSRsImpl() { - INIT_RESULT(result) + INIT_RESULT(result) - try { - vector hashes_vect = LevelDB::getCsrDb()->writeKeysToVector1(MAX_CSR_NUM); - for (int i = 0; i < (int) hashes_vect.size(); i++) { - result["hashes"][i] = hashes_vect.at(i); - } - } HANDLE_SGX_EXCEPTION(result); + try { + vector hashes_vect = + LevelDB::getCsrDb()->writeKeysToVector1(MAX_CSR_NUM); + for (int i = 0; i < (int)hashes_vect.size(); i++) { + result["hashes"][i] = hashes_vect.at(i); + } + } + HANDLE_SGX_EXCEPTION(result); - RETURN_SUCCESS(result) + RETURN_SUCCESS(result) } Json::Value signByHashImpl(const string &hash, int status) { - INIT_RESULT(result) - - try { - if (!(status == 0 || status == 2)) { - throw SGXException(-111, "Invalid csr status"); - } - - string csr_db_key = "CSR:HASH:" + hash; - shared_ptr csr_ptr = LevelDB::getCsrDb()->readString(csr_db_key); - if (csr_ptr == nullptr) { - throw SGXException(KEY_SHARE_DOES_NOT_EXIST, "HASH DOES NOT EXIST IN DB"); - } - - if (status == 0) { - string csr_name = "sgx_data/cert/" + hash + ".csr"; - ofstream outfile(csr_name); - outfile << *csr_ptr << endl; - outfile.close(); - if (access(csr_name.c_str(), F_OK) != 0) { - LevelDB::getCsrDb()->deleteKey(csr_db_key); - throw SGXException(FILE_NOT_FOUND, "Csr does not exist"); - } - - string signClientCert = "cd sgx_data/cert && ./create_client_cert " + hash; - - if (system(signClientCert.c_str()) == 0) { - spdlog::info("CLIENT CERTIFICATE IS SUCCESSFULLY GENERATED"); - } else { - spdlog::info("CLIENT CERTIFICATE GENERATION FAILED"); - LevelDB::getCsrDb()->deleteKey(csr_db_key); - string status_db_key = "CSR:HASH:" + hash + "STATUS:"; - LevelDB::getCsrStatusDb()->deleteKey(status_db_key); - LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, "-1"); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED"); - } - } + INIT_RESULT(result) + + try { + if (!(status == 0 || status == 2)) { + throw SGXException(-111, "Invalid csr status"); + } + + string csr_db_key = "CSR:HASH:" + hash; + shared_ptr csr_ptr = LevelDB::getCsrDb()->readString(csr_db_key); + if (csr_ptr == nullptr) { + throw SGXException(KEY_SHARE_DOES_NOT_EXIST, "HASH DOES NOT EXIST IN DB"); + } + if (status == 0) { + string csr_name = "sgx_data/cert/" + hash + ".csr"; + ofstream outfile(csr_name); + outfile << *csr_ptr << endl; + outfile.close(); + if (access(csr_name.c_str(), F_OK) != 0) { + LevelDB::getCsrDb()->deleteKey(csr_db_key); + throw SGXException(FILE_NOT_FOUND, "Csr does not exist"); + } + + string signClientCert = + "cd sgx_data/cert && ./create_client_cert " + hash; + + if (system(signClientCert.c_str()) == 0) { + spdlog::info("CLIENT CERTIFICATE IS SUCCESSFULLY GENERATED"); + } else { + spdlog::info("CLIENT CERTIFICATE GENERATION FAILED"); LevelDB::getCsrDb()->deleteKey(csr_db_key); string status_db_key = "CSR:HASH:" + hash + "STATUS:"; LevelDB::getCsrStatusDb()->deleteKey(status_db_key); - LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, to_string(status)); + LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, "-1"); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, + "CLIENT CERTIFICATE GENERATION FAILED"); + } + } - result["status"] = status; + LevelDB::getCsrDb()->deleteKey(csr_db_key); + string status_db_key = "CSR:HASH:" + hash + "STATUS:"; + LevelDB::getCsrStatusDb()->deleteKey(status_db_key); + LevelDB::getCsrStatusDb()->writeDataUnique(status_db_key, + to_string(status)); - } HANDLE_SGX_EXCEPTION(result) + result["status"] = status; + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result) + RETURN_SUCCESS(result) } Json::Value CSRManagerServer::getUnsignedCSRs() { - return getUnsignedCSRsImpl(); + return getUnsignedCSRsImpl(); } Json::Value CSRManagerServer::signByHash(const string &hash, int status) { - return signByHashImpl(hash, status); + return signByHashImpl(hash, status); } void CSRManagerServer::initCSRManagerServer() { - hs3 = make_shared(BASE_PORT + 2); - hs3->BindLocalhost(); - cs = make_shared(*hs3, JSONRPC_SERVER_V2); // server (json-rpc 2.0) + hs3 = make_shared(BASE_PORT + 2); + hs3->BindLocalhost(); + cs = make_shared( + *hs3, JSONRPC_SERVER_V2); // server (json-rpc 2.0) - spdlog::info("Starting csr manager server on port {} ...", BASE_PORT + 2); + spdlog::info("Starting csr manager server on port {} ...", BASE_PORT + 2); - if (!cs->StartListening()) { - spdlog::info("CSR manager server could not start listening"); - throw SGXException(CSR_MANAGER_SERVER_FAILED_TO_START, "CSRManager server could not start listening."); - } else { - spdlog::info("CSR manager server started on port {}", BASE_PORT + 2); - } + if (!cs->StartListening()) { + spdlog::info("CSR manager server could not start listening"); + throw SGXException(CSR_MANAGER_SERVER_FAILED_TO_START, + "CSRManager server could not start listening."); + } else { + spdlog::info("CSR manager server started on port {}", BASE_PORT + 2); + } }; int CSRManagerServer::exitServer() { spdlog::info("Stoping CSRManager server"); if (cs && !cs->StopListening()) { - spdlog::error("CSRManager server could not be stopped. Will forcefully terminate the app"); + spdlog::error("CSRManager server could not be stopped. Will forcefully " + "terminate the app"); } else { - spdlog::info("CSRManager server stopped"); + spdlog::info("CSRManager server stopped"); } return 0; diff --git a/CSRManagerServer.h b/CSRManagerServer.h index d8ad91a5..ba8069af 100644 --- a/CSRManagerServer.h +++ b/CSRManagerServer.h @@ -21,7 +21,6 @@ @date 2019 */ - #ifndef SGXD_CSRMANAGERSERVER_H #define SGXD_CSRMANAGERSERVER_H @@ -29,8 +28,8 @@ #include -#include "abstractCSRManagerServer.h" #include "LevelDB.h" +#include "abstractCSRManagerServer.h" using namespace jsonrpc; using namespace std; @@ -42,20 +41,15 @@ class CSRManagerServer : public abstractCSRManagerServer { static shared_ptr cs; - public: - +public: CSRManagerServer(AbstractServerConnector &connector, serverVersion_t type); virtual Json::Value getUnsignedCSRs(); - virtual Json::Value signByHash(const string& hash, int status); + virtual Json::Value signByHash(const string &hash, int status); static void initCSRManagerServer(); static int exitServer(); }; - - - - -#endif //SGXD_CSRMANAGERSERVER_H +#endif // SGXD_CSRMANAGERSERVER_H diff --git a/CryptoTools.cpp b/CryptoTools.cpp index 9b05ad2a..957221c8 100644 --- a/CryptoTools.cpp +++ b/CryptoTools.cpp @@ -23,67 +23,89 @@ #include -#include "common.h" #include "CryptoTools.h" +#include "common.h" using std::vector; int char2int(char _input) { - if (_input >= '0' && _input <= '9') - return _input - '0'; - if (_input >= 'A' && _input <= 'F') - return _input - 'A' + 10; - if (_input >= 'a' && _input <= 'f') - return _input - 'a' + 10; - return -1; + if (_input >= '0' && _input <= '9') + return _input - '0'; + if (_input >= 'A' && _input <= 'F') + return _input - 'A' + 10; + if (_input >= 'a' && _input <= 'f') + return _input - 'a' + 10; + return -1; } vector carray2Hex(const unsigned char *d, uint64_t _len) { - CHECK_STATE(d); + CHECK_STATE(d); - vector _hexArray( 2 * _len + 1); + vector _hexArray(2 * _len + 1); - char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - for (uint64_t j = 0; j < _len; j++) { - _hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)]; - _hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F]; - } + 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; + _hexArray[_len * 2] = 0; - return _hexArray; + return _hexArray; } -bool hex2carray(const char *_hex, uint64_t *_bin_len, - uint8_t *_bin, uint64_t _max_length) { - CHECK_STATE(_hex); - CHECK_STATE(_bin); - CHECK_STATE(_bin_len) +bool hex2carray(const char *_hex, uint64_t *_bin_len, uint8_t *_bin, + uint64_t _max_length) { + CHECK_STATE(_hex); + CHECK_STATE(_bin); + CHECK_STATE(_bin_len) + + uint64_t len = strnlen(_hex, 2 * _max_length + 1); - uint64_t len = strnlen(_hex, 2 * _max_length + 1); + CHECK_STATE(len != 2 * _max_length + 1); - CHECK_STATE(len != 2 * _max_length + 1); + CHECK_STATE(len <= 2 * _max_length); - CHECK_STATE(len <= 2 * _max_length); + if (len % 2 == 1) + return false; - if (len % 2 == 1) - return false; + *_bin_len = len / 2; - *_bin_len = len / 2; + for (uint64_t i = 0; i < len / 2; i++) { + int high = char2int((char)_hex[i * 2]); + int low = char2int((char)_hex[i * 2 + 1]); - for (uint64_t i = 0; i < len / 2; i++) { - int high = char2int((char) _hex[i * 2]); - int low = char2int((char) _hex[i * 2 + 1]); + if (high < 0 || low < 0) { + return false; + } + + _bin[i] = (unsigned char)(high * 16 + low); + } - if (high < 0 || low < 0) { - return false; - } + return true; +} - _bin[i] = (unsigned char) (high * 16 + low); +vector splitString(const char *coeffs, const char symbol) { + CHECK_STATE(coeffs); + std::string str(coeffs); + std::string delim; + delim.push_back(symbol); + vector G2Strings; + size_t prev = 0, pos = 0; + do { + pos = str.find(delim, prev); + if (pos == std::string::npos) + pos = str.length(); + std::string token = str.substr(prev, pos - prev); + if (!token.empty()) { + std::string coeff(token.c_str()); + G2Strings.push_back(coeff); } + prev = pos + delim.length(); + } while (pos < str.length() && prev < str.length()); - return true; -} \ No newline at end of file + return G2Strings; +} diff --git a/CryptoTools.h b/CryptoTools.h index 9eed91ac..8c8ec911 100644 --- a/CryptoTools.h +++ b/CryptoTools.h @@ -39,7 +39,9 @@ EXTERNC int char2int(char _input); EXTERNC std::vector 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 ); +EXTERNC bool hex2carray(const char *_hex, uint64_t *_bin_len, uint8_t *_bin, + uint64_t _max_length); + +std::vector splitString(const char *coeffs, const char symbol); #endif // SGXWALLET_CRYPTOTOOLS_H diff --git a/DKGCrypto.cpp b/DKGCrypto.cpp index 72bcb1f4..c5863cc7 100644 --- a/DKGCrypto.cpp +++ b/DKGCrypto.cpp @@ -21,576 +21,571 @@ @date 2019 */ - #include #include - -#include "third_party/spdlog/spdlog.h" +#include "SGXException.h" #include "common.h" #include "sgxwallet.h" -#include "SGXException.h" +#include "third_party/spdlog/spdlog.h" -#include "SGXWalletServer.hpp" #include "CryptoTools.h" -#include "SEKManager.h" #include "DKGCrypto.h" +#include "SEKManager.h" +#include "SGXWalletServer.hpp" -vector splitString(const char *coeffs, const char symbol) { - CHECK_STATE(coeffs); - string str(coeffs); - string delim; - delim.push_back(symbol); - vector G2_strings; - size_t prev = 0, pos = 0; - do { - pos = str.find(delim, prev); - if (pos == string::npos) pos = str.length(); - string token = str.substr(prev, pos - prev); - if (!token.empty()) { - string coeff(token.c_str()); - G2_strings.push_back(coeff); - } - prev = pos + delim.length(); - } while (pos < str.length() && prev < str.length()); - - return G2_strings; -} - -template -string ConvertToString(T field_elem, int base = 10) { - mpz_t t; - mpz_init(t); +template string ConvertToString(T field_elem, int base = 10) { + mpz_t t; + mpz_init(t); - field_elem.as_bigint().to_mpz(t); + field_elem.as_bigint().to_mpz(t); - SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, base) + 2); + SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, base) + 2); - mpz_get_str(arr, base, t); + mpz_get_str(arr, base, t); - mpz_clear(t); - string output = arr; - return output; + mpz_clear(t); + string output = arr; + return output; } string convertHexToDec(const string &hex_str) { - mpz_t dec; - mpz_init(dec); - - string ret = ""; - - try { - if (mpz_set_str(dec, hex_str.c_str(), 16) == -1) { - goto clean; - } - - SAFE_CHAR_BUF(arr, mpz_sizeinbase(dec, 10) + 2); - mpz_get_str(arr, 10, dec); - ret = arr; - } catch (exception &e) { - mpz_clear(dec); - throw SGXException(INCORRECT_STRING_CONVERSION, e.what()); - } catch (...) { - mpz_clear(dec); - throw SGXException(EXCEPTION_IN_CONVERT_HEX_TO_DEC, "Exception in convert hex to dec"); - } + mpz_t dec; + mpz_init(dec); - clean: + string ret = ""; + + try { + if (mpz_set_str(dec, hex_str.c_str(), 16) == -1) { + goto clean; + } + SAFE_CHAR_BUF(arr, mpz_sizeinbase(dec, 10) + 2); + mpz_get_str(arr, 10, dec); + ret = arr; + } catch (exception &e) { mpz_clear(dec); + throw SGXException(INCORRECT_STRING_CONVERSION, e.what()); + } catch (...) { + mpz_clear(dec); + throw SGXException(EXCEPTION_IN_CONVERT_HEX_TO_DEC, + "Exception in convert hex to dec"); + } + +clean: - return ret; + mpz_clear(dec); + + return ret; } -string convertG2ToString(const libff::alt_bn128_G2 &elem, int base, const string &delim) { - string result = ""; - - try { - result += ConvertToString(elem.X.c0); - result += delim; - result += ConvertToString(elem.X.c1); - result += delim; - result += ConvertToString(elem.Y.c0); - result += delim; - result += ConvertToString(elem.Y.c1); - - return result; - - } catch (exception &e) { - throw SGXException(CONVERT_G2_INCORRECT_STRING_CONVERSION, e.what()); - return result; - } catch (...) { - throw SGXException(EXCEPTION_IN_CONVERT_G2_STRING, "Exception in convert G2 to string"); - return result; - } +string convertG2ToString(const libff::alt_bn128_G2 &elem, int base, + const string &delim) { + string result = ""; + try { + result += ConvertToString(elem.X.c0); + result += delim; + result += ConvertToString(elem.X.c1); + result += delim; + result += ConvertToString(elem.Y.c0); + result += delim; + result += ConvertToString(elem.Y.c1); + + return result; + + } catch (exception &e) { + throw SGXException(CONVERT_G2_INCORRECT_STRING_CONVERSION, e.what()); return result; + } catch (...) { + throw SGXException(EXCEPTION_IN_CONVERT_G2_STRING, + "Exception in convert G2 to string"); + return result; + } + + return result; } string gen_dkg_poly(int _t) { - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - uint64_t enc_len = 0; + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + uint64_t enc_len = 0; - vector encrypted_dkg_secret(BUF_LEN, 0); + vector encrypted_dkg_secret(BUF_LEN, 0); - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), - &enc_len, _t); + status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), + encrypted_dkg_secret.data(), &enc_len, _t); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - uint64_t length = enc_len;; + uint64_t length = enc_len; + ; - CHECK_STATE(encrypted_dkg_secret.size() >= length); - vector hexEncrPoly = carray2Hex(encrypted_dkg_secret.data(), length); - string result(hexEncrPoly.data()); + CHECK_STATE(encrypted_dkg_secret.size() >= length); + vector hexEncrPoly = carray2Hex(encrypted_dkg_secret.data(), length); + string result(hexEncrPoly.data()); - return result; + return result; } -vector > get_verif_vect(const string &encryptedPolyHex, int t) { +vector> get_verif_vect(const string &encryptedPolyHex, int t) { - auto encryptedPolyHexPtr = encryptedPolyHex.c_str(); + auto encryptedPolyHexPtr = encryptedPolyHex.c_str(); - CHECK_STATE(encryptedPolyHexPtr); + CHECK_STATE(encryptedPolyHexPtr); - vector errMsg(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); - int errStatus = 0; + int errStatus = 0; - vector pubShares(10000, 0); + vector pubShares(10000, 0); - uint64_t encLen = 0; + uint64_t encLen = 0; - vector encrDKGPoly(2 * BUF_LEN, 0); + vector encrDKGPoly(2 * BUF_LEN, 0); - if (!hex2carray(encryptedPolyHexPtr, &encLen, encrDKGPoly.data(), 6100)) { - throw SGXException(GET_VV_INVALID_POLY_HEX, ":Invalid encryptedPolyHex"); - } + if (!hex2carray(encryptedPolyHexPtr, &encLen, encrDKGPoly.data(), 6100)) { + throw SGXException(GET_VV_INVALID_POLY_HEX, ":Invalid encryptedPolyHex"); + } + sgx_status_t status = SGX_SUCCESS; - sgx_status_t status = SGX_SUCCESS; + status = + trustedGetPublicShares(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), + encLen, pubShares.data(), t); - status = trustedGetPublicShares(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), encLen, - pubShares.data(), t); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - - vector g2Strings = splitString(pubShares.data(), ','); - vector > pubSharesVect(t); - for (uint64_t i = 0; i < g2Strings.size(); i++) { - vector coeffStr = splitString(g2Strings.at(i).c_str(), ':'); - pubSharesVect[i] = coeffStr; - } + vector g2Strings = splitString(pubShares.data(), ','); + vector> pubSharesVect(t); + for (uint64_t i = 0; i < g2Strings.size(); i++) { + vector coeffStr = splitString(g2Strings.at(i).c_str(), ':'); + pubSharesVect[i] = coeffStr; + } - return pubSharesVect; + return pubSharesVect; } -vector > getVerificationVectorMult(const std::string &encryptedPolyHex, int t, int n, size_t ind) { - auto verificationVector = get_verif_vect(encryptedPolyHex, t); +vector> +getVerificationVectorMult(const std::string &encryptedPolyHex, int t, int n, + size_t ind) { + auto verificationVector = get_verif_vect(encryptedPolyHex, t); - vector > result(t); + vector> 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(); + 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(); + current_coefficient = + libff::power(libff::alt_bn128_Fr(ind + 1), i) * current_coefficient; + current_coefficient.to_affine_coordinates(); - auto g2_str = convertG2ToString(current_coefficient); + auto g2_str = convertG2ToString(current_coefficient); - result[i] = splitString(g2_str.c_str(), ':'); - } + result[i] = splitString(g2_str.c_str(), ':'); + } - return result; + return result; } -string -getSecretShares(const string &_polyName, const char *_encryptedPolyHex, const vector &_publicKeys, - int _t, - int _n) { +string getSecretShares(const string &_polyName, const char *_encryptedPolyHex, + const vector &_publicKeys, int _t, int _n) { - CHECK_STATE(_encryptedPolyHex); - - vector hexEncrKey(BUF_LEN, 0); - vector errMsg(BUF_LEN, 0); - vector encrDKGPoly(BUF_LEN, 0); - int errStatus = 0; - uint64_t encLen = 0; - - - if (!hex2carray(_encryptedPolyHex, &encLen, encrDKGPoly.data(), BUF_LEN)) { - throw SGXException(GET_SS_INVALID_HEX, string(__FUNCTION__) + ":Invalid encryptedPolyHex"); - } + CHECK_STATE(_encryptedPolyHex); + vector hexEncrKey(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); + vector encrDKGPoly(BUF_LEN, 0); + int errStatus = 0; + uint64_t encLen = 0; - READ_LOCK(sgxInitMutex); + if (!hex2carray(_encryptedPolyHex, &encLen, encrDKGPoly.data(), BUF_LEN)) { + throw SGXException(GET_SS_INVALID_HEX, + string(__FUNCTION__) + ":Invalid encryptedPolyHex"); + } - string result; + READ_LOCK(sgxInitMutex); - for (int i = 0; i < _n; i++) { - vector encryptedSkey(BUF_LEN, 0); - uint64_t decLen; - vector currentShare(193, 0); - vector sShareG2(320, 0); + string result; - string pub_keyB = _publicKeys.at(i); - vector pubKeyB(129, 0); + for (int i = 0; i < _n; i++) { + vector encryptedSkey(BUF_LEN, 0); + uint64_t decLen; + vector currentShare(193, 0); + vector sShareG2(320, 0); - strncpy(pubKeyB.data(), pub_keyB.c_str(), 128); - pubKeyB.at(128) = 0; + string pub_keyB = _publicKeys.at(i); + vector pubKeyB(129, 0); - spdlog::debug("pubKeyB is {}", pub_keyB); + strncpy(pubKeyB.data(), pub_keyB.c_str(), 128); + pubKeyB.at(128) = 0; - 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); + spdlog::debug("pubKeyB is {}", pub_keyB); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + 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()); + result += string(currentShare.data()); - hexEncrKey = carray2Hex(encryptedSkey.data(), decLen); - string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":"; + hexEncrKey = carray2Hex(encryptedSkey.data(), decLen); + string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":"; - string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":"; + string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":"; - SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data()); - SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data()); - } + SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data()); + SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data()); + } - string encryptedSecretShareName = "encryptedSecretShare:" + _polyName; - SGXWalletServer::writeDataToDB(encryptedSecretShareName, result); + string encryptedSecretShareName = "encryptedSecretShare:" + _polyName; + SGXWalletServer::writeDataToDB(encryptedSecretShareName, result); - return result; + return result; } -string -getSecretSharesV2(const string &_polyName, const char *_encryptedPolyHex, const vector &_publicKeys, int _t, - int _n) { - CHECK_STATE(_encryptedPolyHex); - - vector hexEncrKey(BUF_LEN, 0); - vector errMsg(BUF_LEN, 0); - vector encrDKGPoly(BUF_LEN, 0); - int errStatus = 0; - uint64_t encLen = 0; +string getSecretSharesV2(const string &_polyName, const char *_encryptedPolyHex, + const vector &_publicKeys, int _t, int _n) { + CHECK_STATE(_encryptedPolyHex); + vector hexEncrKey(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); + vector encrDKGPoly(BUF_LEN, 0); + int errStatus = 0; + uint64_t encLen = 0; - if (!hex2carray(_encryptedPolyHex, &encLen, encrDKGPoly.data(), BUF_LEN)) { - throw SGXException(GET_SS_V2_INVALID_HEX, - string(__FUNCTION__) + ":Invalid encrypted poly Hex"); - } - + if (!hex2carray(_encryptedPolyHex, &encLen, encrDKGPoly.data(), BUF_LEN)) { + throw SGXException(GET_SS_V2_INVALID_HEX, + string(__FUNCTION__) + ":Invalid encrypted poly Hex"); + } - READ_LOCK(sgxInitMutex); + READ_LOCK(sgxInitMutex); - string result; + string result; - for (int i = 0; i < _n; i++) { - vector encryptedSkey(BUF_LEN, 0); - uint64_t decLen; - vector currentShare(193, 0); - vector sShareG2(320, 0); + for (int i = 0; i < _n; i++) { + vector encryptedSkey(BUF_LEN, 0); + uint64_t decLen; + vector currentShare(193, 0); + vector sShareG2(320, 0); - string pub_keyB = _publicKeys.at(i); - vector pubKeyB(129, 0); + string pub_keyB = _publicKeys.at(i); + vector pubKeyB(129, 0); - strncpy(pubKeyB.data(), pub_keyB.c_str(), 128); - pubKeyB.at(128) = 0; + strncpy(pubKeyB.data(), pub_keyB.c_str(), 128); + pubKeyB.at(128) = 0; - spdlog::debug("pubKeyB is {}", pub_keyB); + spdlog::debug("pubKeyB is {}", pub_keyB); - sgx_status_t status = SGX_SUCCESS; - status = trustedGetEncryptedSecretShareV2(eid, &errStatus, - errMsg.data(), - encrDKGPoly.data(), encLen, - encryptedSkey.data(), &decLen, - currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, - i + 1); + sgx_status_t status = SGX_SUCCESS; + 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, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + result += string(currentShare.data()); - result += string(currentShare.data()); + hexEncrKey = carray2Hex(encryptedSkey.data(), decLen); + string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":"; - hexEncrKey = carray2Hex(encryptedSkey.data(), decLen); - string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":"; + string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":"; - string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":"; + SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data()); + SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data()); + } - SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data()); - SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data()); - } + string encryptedSecretShareName = "encryptedSecretShare:" + _polyName; + SGXWalletServer::writeDataToDB(encryptedSecretShareName, result); - string encryptedSecretShareName = "encryptedSecretShare:" + _polyName; - SGXWalletServer::writeDataToDB(encryptedSecretShareName, result); - - return result; + return result; } -bool -verifyShares(const char *publicShares, const char *encr_sshare, const char *encryptedKeyHex, int t, int n, int ind) { +bool verifyShares(const char *publicShares, const char *encr_sshare, + const char *encryptedKeyHex, int t, int n, int ind) { - CHECK_STATE(publicShares); - CHECK_STATE(encr_sshare); - CHECK_STATE(encryptedKeyHex); + CHECK_STATE(publicShares); + CHECK_STATE(encr_sshare); + CHECK_STATE(encryptedKeyHex); - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - uint64_t decKeyLen = 0; - int result = 0; + vector 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(VERIFY_SHARES_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid encryptedPolyHex"); - } + SAFE_UINT8_BUF(encr_key, BUF_LEN); + if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) { + throw SGXException(VERIFY_SHARES_INVALID_KEY_HEX, + string(__FUNCTION__) + ":Invalid encryptedPolyHex"); + } - SAFE_CHAR_BUF(pshares, 8193); - strncpy(pshares, publicShares, strlen(publicShares)); + SAFE_CHAR_BUF(pshares, 8193); + strncpy(pshares, publicShares, strlen(publicShares)); - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedDkgVerify(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t, - ind, &result); + status = trustedDkgVerify(eid, &errStatus, errMsg.data(), pshares, + encr_sshare, encr_key, decKeyLen, t, ind, &result); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - if (result == 2) { - throw SGXException(VERIFY_SHARES_INVALID_PUBLIC_SHARES, - string(__FUNCTION__) + +":Invalid public shares"); - } + if (result == 2) { + throw SGXException(VERIFY_SHARES_INVALID_PUBLIC_SHARES, + string(__FUNCTION__) + +":Invalid public shares"); + } - return result; + return result; } -bool -verifySharesV2(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) { - CHECK_STATE(publicShares); - CHECK_STATE(encr_sshare); - CHECK_STATE(encryptedKeyHex); + CHECK_STATE(publicShares); + CHECK_STATE(encr_sshare); + CHECK_STATE(encryptedKeyHex); - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - uint64_t decKeyLen = 0; - int result = 0; + vector 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(VERIFY_SHARES_V2_INVALID_POLY_HEX, string(__FUNCTION__) + ":Invalid encryptedPolyHex"); - } + SAFE_UINT8_BUF(encr_key, BUF_LEN); + if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) { + throw SGXException(VERIFY_SHARES_V2_INVALID_POLY_HEX, + string(__FUNCTION__) + ":Invalid encryptedPolyHex"); + } - SAFE_CHAR_BUF(pshares, 8193); - strncpy(pshares, publicShares, strlen(publicShares)); + SAFE_CHAR_BUF(pshares, 8193); + strncpy(pshares, publicShares, strlen(publicShares)); - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedDkgVerifyV2(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t, - ind, &result); + status = + trustedDkgVerifyV2(eid, &errStatus, errMsg.data(), pshares, encr_sshare, + encr_key, decKeyLen, t, ind, &result); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - if (result == 2) { - throw SGXException(VERIFY_SHARES_V2_INVALID_PUBLIC_SHARES, string(__FUNCTION__) + ":Invalid public shares"); - } + if (result == 2) { + throw SGXException(VERIFY_SHARES_V2_INVALID_PUBLIC_SHARES, + string(__FUNCTION__) + ":Invalid public shares"); + } - return result; + return result; } -bool createBLSShare(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) { +bool createBLSShare(const string &blsKeyName, const char *s_shares, + const char *encryptedKeyHex) { - CHECK_STATE(s_shares); - CHECK_STATE(encryptedKeyHex); + CHECK_STATE(s_shares); + CHECK_STATE(encryptedKeyHex); - vector errMsg(BUF_LEN, 0); - int errStatus = 0; + vector errMsg(BUF_LEN, 0); + int errStatus = 0; - uint64_t decKeyLen;SAFE_UINT8_BUF(encr_bls_key, BUF_LEN);SAFE_UINT8_BUF(encr_key, BUF_LEN); - if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) { - throw SGXException(CREATE_BLS_SHARE_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid encryptedKeyHex"); - } + uint64_t decKeyLen; + SAFE_UINT8_BUF(encr_bls_key, BUF_LEN); + SAFE_UINT8_BUF(encr_key, BUF_LEN); + if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) { + throw SGXException(CREATE_BLS_SHARE_INVALID_KEY_HEX, + string(__FUNCTION__) + ":Invalid encryptedKeyHex"); + } - uint64_t enc_bls_len = 0; + uint64_t enc_bls_len = 0; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedCreateBlsKey(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key, - &enc_bls_len); + status = trustedCreateBlsKey(eid, &errStatus, errMsg.data(), s_shares, + encr_key, decKeyLen, encr_bls_key, &enc_bls_len); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - - vector hexBLSKey = carray2Hex(encr_bls_key, enc_bls_len); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data()); + vector hexBLSKey = carray2Hex(encr_bls_key, enc_bls_len); - return true; + SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data()); + return true; } -bool createBLSShareV2(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) { +bool createBLSShareV2(const string &blsKeyName, const char *s_shares, + const char *encryptedKeyHex) { - CHECK_STATE(s_shares); - CHECK_STATE(encryptedKeyHex); + CHECK_STATE(s_shares); + CHECK_STATE(encryptedKeyHex); - vector errMsg(BUF_LEN, 0); - int errStatus = 0; + vector errMsg(BUF_LEN, 0); + int errStatus = 0; - uint64_t decKeyLen; - SAFE_UINT8_BUF(encr_bls_key, BUF_LEN) - SAFE_UINT8_BUF(encr_key, BUF_LEN) - - if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) { - throw SGXException(CREATE_BLS_SHARE_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid encryptedKeyHex"); - } + uint64_t decKeyLen; + SAFE_UINT8_BUF(encr_bls_key, BUF_LEN) + SAFE_UINT8_BUF(encr_key, BUF_LEN) - uint64_t enc_bls_len = 0; + if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) { + throw SGXException(CREATE_BLS_SHARE_INVALID_KEY_HEX, + string(__FUNCTION__) + ":Invalid encryptedKeyHex"); + } - sgx_status_t status = SGX_SUCCESS; + uint64_t enc_bls_len = 0; - status = trustedCreateBlsKeyV2(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key, - &enc_bls_len); + sgx_status_t status = SGX_SUCCESS; - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + status = + trustedCreateBlsKeyV2(eid, &errStatus, errMsg.data(), s_shares, encr_key, + decKeyLen, encr_bls_key, &enc_bls_len); - vector hexBLSKey = carray2Hex(encr_bls_key, enc_bls_len); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data()); + vector hexBLSKey = carray2Hex(encr_bls_key, enc_bls_len); - return true; + SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data()); + return true; } -vector getBLSPubKey(const char *encryptedKeyHex) { +vector getBLSPubKey(const char *encryptedKeyHex) { - CHECK_STATE(encryptedKeyHex); + CHECK_STATE(encryptedKeyHex); - vector errMsg1(BUF_LEN, 0); + vector errMsg1(BUF_LEN, 0); - int errStatus = 0; - uint64_t decKeyLen = 0; + int errStatus = 0; + uint64_t decKeyLen = 0; - SAFE_UINT8_BUF(encrKey, BUF_LEN); - if (!hex2carray(encryptedKeyHex, &decKeyLen, encrKey, BUF_LEN)) { - throw SGXException(GET_BLS_PUBKEY_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid encryptedKeyHex"); - } + SAFE_UINT8_BUF(encrKey, BUF_LEN); + if (!hex2carray(encryptedKeyHex, &decKeyLen, encrKey, BUF_LEN)) { + throw SGXException(GET_BLS_PUBKEY_INVALID_KEY_HEX, + string(__FUNCTION__) + ":Invalid encryptedKeyHex"); + } - SAFE_CHAR_BUF(pubKey, 320) + SAFE_CHAR_BUF(pubKey, 320) + sgx_status_t status = SGX_SUCCESS; - sgx_status_t status = SGX_SUCCESS; + status = trustedGetBlsPubKey(eid, &errStatus, errMsg1.data(), encrKey, + decKeyLen, pubKey); - status = trustedGetBlsPubKey(eid, &errStatus, errMsg1.data(), encrKey, decKeyLen, pubKey); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data()); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data()); + vector pubKeyVect = splitString(pubKey, ':'); - vector pubKeyVect = splitString(pubKey, ':'); + spdlog::debug("pub key is "); + for (int i = 0; i < 4; i++) + spdlog::debug("{}", pubKeyVect.at(i)); - spdlog::debug("pub key is "); - for (int i = 0; i < 4; i++) - spdlog::debug("{}", pubKeyVect.at(i)); - - return pubKeyVect; + return pubKeyVect; } -vector calculateAllBlsPublicKeys(const vector &public_shares) { - size_t n = public_shares.size(); - size_t t = public_shares[0].length() / 256; - uint64_t share_length = 256; - uint8_t coord_length = 64; - - vector public_keys(n, libff::alt_bn128_G2::zero()); - - vector public_values(t, libff::alt_bn128_G2::zero()); - for (size_t i = 0; i < n; ++i) { - for (size_t j = 0; j < t; ++j) { - libff::alt_bn128_G2 public_share; - - uint64_t pos0 = share_length * j; - string x_c0_str = convertHexToDec(public_shares[i].substr(pos0, coord_length)); - string x_c1_str = convertHexToDec(public_shares[i].substr(pos0 + coord_length, coord_length)); - string y_c0_str = convertHexToDec(public_shares[i].substr(pos0 + 2 * coord_length, coord_length)); - string y_c1_str = convertHexToDec(public_shares[i].substr(pos0 + 3 * coord_length, coord_length)); - - if (x_c0_str == "" || x_c1_str == "" || y_c0_str == "" || y_c1_str == "") { - return {}; - } - - public_share.X.c0 = libff::alt_bn128_Fq(x_c0_str.c_str()); - public_share.X.c1 = libff::alt_bn128_Fq(x_c1_str.c_str()); - public_share.Y.c0 = libff::alt_bn128_Fq(y_c0_str.c_str()); - public_share.Y.c1 = libff::alt_bn128_Fq(y_c1_str.c_str()); - public_share.Z = libff::alt_bn128_Fq2::one(); - - public_values[j] = public_values[j] + public_share; - } +vector calculateAllBlsPublicKeys(const vector &public_shares) { + size_t n = public_shares.size(); + size_t t = public_shares[0].length() / 256; + uint64_t share_length = 256; + uint8_t coord_length = 64; + + vector public_keys(n, libff::alt_bn128_G2::zero()); + + vector public_values(t, libff::alt_bn128_G2::zero()); + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < t; ++j) { + libff::alt_bn128_G2 public_share; + + uint64_t pos0 = share_length * j; + string x_c0_str = + convertHexToDec(public_shares[i].substr(pos0, coord_length)); + string x_c1_str = convertHexToDec( + public_shares[i].substr(pos0 + coord_length, coord_length)); + string y_c0_str = convertHexToDec( + public_shares[i].substr(pos0 + 2 * coord_length, coord_length)); + string y_c1_str = convertHexToDec( + public_shares[i].substr(pos0 + 3 * coord_length, coord_length)); + + if (x_c0_str == "" || x_c1_str == "" || y_c0_str == "" || + y_c1_str == "") { + return {}; + } + + public_share.X.c0 = libff::alt_bn128_Fq(x_c0_str.c_str()); + public_share.X.c1 = libff::alt_bn128_Fq(x_c1_str.c_str()); + public_share.Y.c0 = libff::alt_bn128_Fq(y_c0_str.c_str()); + public_share.Y.c1 = libff::alt_bn128_Fq(y_c1_str.c_str()); + public_share.Z = libff::alt_bn128_Fq2::one(); + + public_values[j] = public_values[j] + public_share; } + } - for (size_t i = 0; i < n; ++i) { - for (size_t j = 0; j < t; ++j) { - public_keys[i] = public_keys[i] + libff::power(libff::alt_bn128_Fr(i + 1), j) * public_values[j]; - } - public_keys[i].to_affine_coordinates(); + for (size_t i = 0; i < n; ++i) { + for (size_t j = 0; j < t; ++j) { + public_keys[i] = + public_keys[i] + + libff::power(libff::alt_bn128_Fr(i + 1), j) * public_values[j]; } + public_keys[i].to_affine_coordinates(); + } - vector result(n); - for (size_t i = 0; i < n; ++i) { - result[i] = convertG2ToString(public_keys[i]); - } + vector result(n); + for (size_t i = 0; i < n; ++i) { + result[i] = convertG2ToString(public_keys[i]); + } - return result; + return result; } string decryptDHKey(const string &polyName, int ind) { - vector errMsg1(BUF_LEN, 0); - int errStatus = 0; + vector errMsg1(BUF_LEN, 0); + int errStatus = 0; - string DH_key_name = polyName + "_" + to_string(ind) + ":"; - shared_ptr hexEncrKeyPtr = SGXWalletServer::readFromDb(DH_key_name, "DKG_DH_KEY_"); + string DH_key_name = polyName + "_" + to_string(ind) + ":"; + shared_ptr 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()); + spdlog::debug("encr DH key is {}", *hexEncrKeyPtr); + spdlog::debug("encr DH key length is {}", hexEncrKeyPtr->length()); - vector hexEncrKey(2 * BUF_LEN, 0); + vector hexEncrKey(2 * BUF_LEN, 0); - uint64_t dhEncLen = 0; - SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN); - if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey, BUF_LEN)) { - throw SGXException(DECRYPT_DH_KEY_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid hexEncrKey"); - } - spdlog::debug("encr DH key length is {}", dhEncLen); + uint64_t dhEncLen = 0; + SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN); + if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey, BUF_LEN)) { + throw SGXException(DECRYPT_DH_KEY_INVALID_KEY_HEX, + string(__FUNCTION__) + ":Invalid hexEncrKey"); + } + spdlog::debug("encr DH key length is {}", dhEncLen); - SAFE_CHAR_BUF(DHKey, ECDSA_SKEY_LEN) + SAFE_CHAR_BUF(DHKey, ECDSA_SKEY_LEN) - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey); + status = trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, + dhEncLen, DHKey); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data()) + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data()) - return DHKey; + return DHKey; } -vector mult_G2(const string &x) { - vector result(4); - libff::alt_bn128_Fr el(x.c_str()); - libff::alt_bn128_G2 elG2 = el * libff::alt_bn128_G2::one(); - elG2.to_affine_coordinates(); - result[0] = ConvertToString(elG2.X.c0); - result[1] = ConvertToString(elG2.X.c1); - result[2] = ConvertToString(elG2.Y.c0); - result[3] = ConvertToString(elG2.Y.c1); - return result; +vector mult_G2(const string &x) { + vector result(4); + libff::alt_bn128_Fr el(x.c_str()); + libff::alt_bn128_G2 elG2 = el * libff::alt_bn128_G2::one(); + elG2.to_affine_coordinates(); + result[0] = ConvertToString(elG2.X.c0); + result[1] = ConvertToString(elG2.X.c1); + result[2] = ConvertToString(elG2.Y.c0); + result[3] = ConvertToString(elG2.Y.c1); + return result; } diff --git a/DKGCrypto.h b/DKGCrypto.h index c76b01e7..b3f735cd 100644 --- a/DKGCrypto.h +++ b/DKGCrypto.h @@ -31,38 +31,45 @@ using namespace std; -string gen_dkg_poly( int _t); +string gen_dkg_poly(int _t); -vector > get_verif_vect(const string& encryptedPolyHex, int t); +vector> get_verif_vect(const string &encryptedPolyHex, int t); -vector > getVerificationVectorMult(const std::string& encryptedPolyHex, int t, int n, size_t ind); +vector> +getVerificationVectorMult(const std::string &encryptedPolyHex, int t, int n, + size_t ind); -vector splitString(const char* coeffs, const char symbol); +string getSecretShares(const string &_polyName, const char *_encryptedPolyHex, + const vector &_publicKeys, int _t, int _n); -string getSecretShares(const string& _polyName, const char* _encryptedPolyHex, const vector& _publicKeys, int _t, int _n); +string getSecretSharesV2(const string &_polyName, const char *_encryptedPolyHex, + const vector &_publicKeys, int _t, int _n); -string getSecretSharesV2(const string& _polyName, const char* _encryptedPolyHex, const vector& _publicKeys, int _t, int _n); +bool verifyShares(const char *publicShares, const char *encr_sshare, + const char *encryptedKeyHex, int t, int n, int ind); -bool verifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind); +bool verifySharesV2(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); -string decryptDHKey(const string& polyName, int ind); +bool createBLSShare(const string &blsKeyName, const char *s_shares, + const char *encryptedKeyHex); -bool createBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex); +bool createBLSShareV2(const string &blsKeyName, const char *s_shares, + const char *encryptedKeyHex); -bool createBLSShareV2( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex); +vector getBLSPubKey(const char *encryptedKeyHex); -vector getBLSPubKey(const char * encryptedKeyHex); +vector mult_G2(const string &x); -vector mult_G2(const string& x); +string convertHexToDec(const string &hex_str); -string convertHexToDec(const string& hex_str); +string convertG2ToString(const libff::alt_bn128_G2 &elem, int base = 10, + const string &delim = ":"); -string convertG2ToString(const libff::alt_bn128_G2& elem, int base = 10, const string& delim = ":"); +vector calculateAllBlsPublicKeys(const vector &public_shares); -vector calculateAllBlsPublicKeys(const vector& public_shares); +bool testCreateBLSShare(const char *s_shares); -bool testCreateBLSShare( const char * s_shares); - -#endif //SGXD_DKGCRYPTO_H +#endif // SGXD_DKGCRYPTO_H diff --git a/Dockerfile b/Dockerfile index 49ab8e28..3b3b4266 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,14 @@ FROM skalenetwork/sgxwallet_base:latest COPY . /usr/src/sdk WORKDIR /usr/src/sdk -RUN apt update && apt install -y curl secure-delete + +RUN apt update && apt install -y curl secure-delete python3-pip +RUN pip3 install --upgrade pip +RUN pip3 install requests torpy + + + + RUN touch /var/hwmode RUN ./autoconf.bash RUN ./configure @@ -10,6 +17,7 @@ RUN bash -c "make -j$(nproc)" RUN ccache -sz RUN mkdir -p /usr/src/sdk/sgx_data COPY docker/start.sh ./ +COPY docker/check_firewall.py ./ RUN rm -rf /usr/src/sdk/sgx-sdk-build/ RUN rm /opt/intel/sgxsdk/lib64/*_sim.so ENTRYPOINT ["/usr/src/sdk/start.sh"] diff --git a/DockerfileBase b/DockerfileBase index 044a4d58..df7211af 100644 --- a/DockerfileBase +++ b/DockerfileBase @@ -1,6 +1,8 @@ -FROM ubuntu:18.04 +FROM ubuntu:20.04 -RUN apt-get update && apt-get install -y \ +RUN apt-get update && apt-get install software-properties-common -y && \ + add-apt-repository ppa:ubuntu-toolchain-r/test && \ + apt-get update && apt-get install -y \ autoconf \ automake \ build-essential \ @@ -16,16 +18,18 @@ RUN apt-get update && apt-get install -y \ ocaml \ ocamlbuild \ protobuf-compiler \ - python \ + python-is-python3 \ wget \ libcurl4 \ - libprotobuf10 \ - libssl1.1 \ make \ - module-init-tools \ - unzip + unzip \ + perl \ + pkgconf -RUN git clone -b sgx_2.13 --depth 1 https://github.com/intel/linux-sgx +# RUN wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb && \ +# dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb + +RUN git clone -b sgx_2.19 --depth 1 https://github.com/intel/linux-sgx RUN cd linux-sgx && make preparation @@ -50,11 +54,12 @@ WORKDIR /usr/src/sdk RUN apt update && \ apt install -yq apt-utils && \ - apt install -yq --no-install-recommends python-yaml vim \ - telnet git ca-certificates perl \ + apt install -yq --no-install-recommends vim telnet git ca-certificates perl \ reprepro libboost-all-dev alien uuid-dev libxml2-dev ccache \ yasm flex bison libprocps-dev ccache texinfo \ - libjsonrpccpp-dev curl libjsonrpccpp-tools && \ + graphviz doxygen libgnutls28-dev libgcrypt20-dev \ + libboost-dev libboost-system-dev libboost-thread-dev lsb-release libsystemd0 && \ + # glibc-tools ln -s /usr/bin/ccache /usr/local/bin/clang && \ ln -s /usr/bin/ccache /usr/local/bin/clang++ && \ ln -s /usr/bin/ccache /usr/local/bin/gcc && \ diff --git a/DockerfileIntelSubmission b/DockerfileIntelSubmission index c9f5d072..33c73051 100644 --- a/DockerfileIntelSubmission +++ b/DockerfileIntelSubmission @@ -3,7 +3,11 @@ FROM skalenetwork/sgxwallet_base:latest COPY . /usr/src/sdk WORKDIR /usr/src/sdk RUN cp -f secure_enclave/secure_enclave.config.xml.release secure_enclave/secure_enclave.config.xml -RUN apt update && apt install -y curl secure-delete + +RUN apt update && apt install -y curl secure-delete python3-pip +RUN pip3 install --upgrade pip +RUN pip3 install requests torpy + #Test signing key generation RUN cd scripts && ./generate_signing_key.bash RUN touch /var/hwmode diff --git a/DockerfileRelease b/DockerfileRelease index 3fa72652..e78a8df7 100644 --- a/DockerfileRelease +++ b/DockerfileRelease @@ -3,7 +3,12 @@ FROM skalenetwork/sgxwallet_base:latest COPY . /usr/src/sdk WORKDIR /usr/src/sdk RUN cp -f secure_enclave/secure_enclave.config.xml.release secure_enclave/secure_enclave.config.xml -RUN apt update && apt install -y curl secure-delete + +RUN apt update && apt install -y curl secure-delete python3-pip +RUN pip3 install --upgrade pip +RUN pip3 install requests torpy + + RUN touch /var/hwmode RUN ./autoconf.bash RUN ./configure --with-sgx-build=release @@ -12,6 +17,7 @@ RUN ccache -sz RUN cd scripts && ./sign_enclave.bash RUN mkdir -p /usr/src/sdk/sgx_data COPY docker/start.sh ./ +COPY docker/check_firewall.py ./ 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 diff --git a/DockerfileSimulation b/DockerfileSimulation index cb92bce8..33109841 100644 --- a/DockerfileSimulation +++ b/DockerfileSimulation @@ -1,7 +1,10 @@ FROM skalenetwork/sgxwallet_base:latest -RUN apt update && apt install -y curl secure-delete +RUN apt update && apt install -y curl secure-delete python3-pip +RUN pip3 install --upgrade pip +RUN pip3 install requests torpy + RUN ccache -sz @@ -15,6 +18,7 @@ RUN ./autoconf.bash && \ mkdir -p /usr/src/sdk/sgx_data COPY docker/start.sh ./ +COPY docker/check_firewall.py ./ RUN rm -rf /usr/src/sdk/sgx-sdk-build/ ENTRYPOINT ["/usr/src/sdk/start.sh"] diff --git a/ECDSACrypto.cpp b/ECDSACrypto.cpp index e413b83f..2470fac4 100644 --- a/ECDSACrypto.cpp +++ b/ECDSACrypto.cpp @@ -25,226 +25,228 @@ #include "SGXException.h" -#include #include +#include #include #include -#include "third_party/spdlog/spdlog.h" #include "common.h" +#include "third_party/spdlog/spdlog.h" #include "secure_enclave/Verify.h" #include "CryptoTools.h" -#include "SEKManager.h" #include "ECDSACrypto.h" +#include "SEKManager.h" void fillRandomBuffer(vector &_buffer) { - ifstream devRandom("/dev/urandom", ios::in | ios::binary); - devRandom.exceptions(ifstream::failbit | ifstream::badbit); - devRandom.read((char *) _buffer.data(), _buffer.size()); - devRandom.close(); + ifstream devRandom("/dev/urandom", ios::in | ios::binary); + devRandom.exceptions(ifstream::failbit | ifstream::badbit); + devRandom.read((char *)_buffer.data(), _buffer.size()); + devRandom.close(); } -vector genECDSAKey() { - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - vector encr_pr_key(BUF_LEN, 0); - vector pub_key_x(BUF_LEN, 0); - vector pub_key_y(BUF_LEN, 0); +vector genECDSAKey() { + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + vector encr_pr_key(BUF_LEN, 0); + vector pub_key_x(BUF_LEN, 0); + vector pub_key_y(BUF_LEN, 0); - uint64_t enc_len = 0; + uint64_t enc_len = 0; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - int exportable = 0; + int exportable = 0; - status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), - &exportable, encr_pr_key.data(), &enc_len, - pub_key_x.data(), pub_key_y.data()); + status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, + encr_pr_key.data(), &enc_len, + pub_key_x.data(), pub_key_y.data()); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - vector keys(3); + vector keys(3); - vector 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 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 randBuffer(32, 0); - fillRandomBuffer(randBuffer); + vector randBuffer(32, 0); + fillRandomBuffer(randBuffer); - vector rand_str = carray2Hex(randBuffer.data(), 32); + vector rand_str = carray2Hex(randBuffer.data(), 32); - keys.at(2) = rand_str.data(); + keys.at(2) = rand_str.data(); - CHECK_STATE(keys.at(2).size() == 64); + CHECK_STATE(keys.at(2).size() == 64); - return keys; + return keys; } -string getECDSAPubKey(const std::string& _encryptedKeyHex) { - vector errMsg(BUF_LEN, 0); - vector pubKeyX(BUF_LEN, 0); - vector pubKeyY(BUF_LEN, 0); - vector encrPrKey(BUF_LEN, 0); +string getECDSAPubKey(const std::string &_encryptedKeyHex) { + vector errMsg(BUF_LEN, 0); + vector pubKeyX(BUF_LEN, 0); + vector pubKeyY(BUF_LEN, 0); + vector encrPrKey(BUF_LEN, 0); - int errStatus = 0; - uint64_t enc_len = 0; + int errStatus = 0; + uint64_t enc_len = 0; - if (!hex2carray(_encryptedKeyHex.c_str(), &enc_len, encrPrKey.data(), - BUF_LEN)) { - throw SGXException(GET_ECDSA_PUB_KEY_INVALID_KEY_HEX, "Invalid encryptedKeyHex"); - } + if (!hex2carray(_encryptedKeyHex.c_str(), &enc_len, encrPrKey.data(), + BUF_LEN)) { + throw SGXException(GET_ECDSA_PUB_KEY_INVALID_KEY_HEX, + "Invalid encryptedKeyHex"); + } - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedGetPublicEcdsaKey(eid, &errStatus, - errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data()); + status = + trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encrPrKey.data(), + enc_len, pubKeyX.data(), pubKeyY.data()); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()) + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()) - string pubKey = string(pubKeyX.data()) + string(pubKeyY.data()); + string pubKey = string(pubKeyX.data()) + string(pubKeyY.data()); - if (pubKey.size() != 128) { - spdlog::error("Incorrect pub key size", status); - throw SGXException(666, "Incorrect pub key size"); - } + if (pubKey.size() != 128) { + spdlog::error("Incorrect pub key size", status); + throw SGXException(666, "Incorrect pub key size"); + } - return pubKey; + return pubKey; } -bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatureR, - const char *signatureS, int base) { +bool verifyECDSASig(string &pubKeyStr, const char *hashHex, + const char *signatureR, const char *signatureS, int base) { - CHECK_STATE(hashHex) - CHECK_STATE(signatureR) - CHECK_STATE(signatureS) + CHECK_STATE(hashHex) + CHECK_STATE(signatureR) + CHECK_STATE(signatureS) - auto x = pubKeyStr.substr(0, 64); - auto y = pubKeyStr.substr(64, 128); - - mpz_t msgMpz; - mpz_init(msgMpz); - if (mpz_set_str(msgMpz, hashHex, 16) == -1) { - spdlog::error("invalid message hash {}", hashHex); - mpz_clear(msgMpz); - return false; - } + auto x = pubKeyStr.substr(0, 64); + auto y = pubKeyStr.substr(64, 128); - signature sig = signature_init(); - if (signature_set_str(sig, signatureR, signatureS, base) != 0) { - spdlog::error("Failed to set str signature"); - mpz_clear(msgMpz); - signature_free(sig); - return false; - } + mpz_t msgMpz; + mpz_init(msgMpz); + if (mpz_set_str(msgMpz, hashHex, 16) == -1) { + spdlog::error("invalid message hash {}", hashHex); + mpz_clear(msgMpz); + return false; + } - domain_parameters curve = domain_parameters_init(); - domain_parameters_load_curve(curve, secp256k1); + signature sig = signature_init(); + if (signature_set_str(sig, signatureR, signatureS, base) != 0) { + spdlog::error("Failed to set str signature"); + mpz_clear(msgMpz); + signature_free(sig); + return false; + } - point publicKey = point_init(); + domain_parameters curve = domain_parameters_init(); + domain_parameters_load_curve(curve, secp256k1); - point_set_hex(publicKey, x.c_str(), y.c_str()); - if (!signature_verify(msgMpz, sig, publicKey, curve)) { - spdlog::error("ECDSA sig not verified"); - mpz_clear(msgMpz); - signature_free(sig); - domain_parameters_clear(curve); - point_clear(publicKey); - return false; - } + point publicKey = point_init(); + point_set_hex(publicKey, x.c_str(), y.c_str()); + if (!signature_verify(msgMpz, sig, publicKey, curve)) { + spdlog::error("ECDSA sig not verified"); mpz_clear(msgMpz); signature_free(sig); domain_parameters_clear(curve); point_clear(publicKey); + return false; + } - return true; + mpz_clear(msgMpz); + signature_free(sig); + domain_parameters_clear(curve); + point_clear(publicKey); + + return true; } -vector ecdsaSignHash(const std::string& encryptedKeyHex, const char *hashHex, int base) { +vector ecdsaSignHash(const std::string &encryptedKeyHex, + const char *hashHex, int base) { - CHECK_STATE(hashHex); + CHECK_STATE(hashHex); - vector signatureVector(3); + vector signatureVector(3); - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - vector signatureR(BUF_LEN, 0); - vector signatureS(BUF_LEN, 0); - vector encryptedKey(BUF_LEN, 0); - uint8_t signatureV = 0; - uint64_t decLen = 0; + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + vector signatureR(BUF_LEN, 0); + vector signatureS(BUF_LEN, 0); + vector encryptedKey(BUF_LEN, 0); + uint8_t signatureV = 0; + uint64_t decLen = 0; - string pubKeyStr = ""; + string pubKeyStr = ""; - if (!hex2carray(encryptedKeyHex.c_str(), &decLen, encryptedKey.data(), - BUF_LEN)) { - throw SGXException(ECDSA_SIGN_INVALID_KEY_HEX, "Invalid encryptedKeyHex"); - } + if (!hex2carray(encryptedKeyHex.c_str(), &decLen, encryptedKey.data(), + BUF_LEN)) { + throw SGXException(ECDSA_SIGN_INVALID_KEY_HEX, "Invalid encryptedKeyHex"); + } - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedEcdsaSign(eid, &errStatus, - errMsg.data(), encryptedKey.data(), decLen, hashHex, - signatureR.data(), - signatureS.data(), &signatureV, base); + status = trustedEcdsaSign(eid, &errStatus, errMsg.data(), encryptedKey.data(), + decLen, hashHex, signatureR.data(), + signatureS.data(), &signatureV, base); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + signatureVector.at(0) = to_string(signatureV); - signatureVector.at(0) = to_string(signatureV); + if (base == 16) { + signatureVector.at(1) = "0x" + string(signatureR.data()); + signatureVector.at(2) = "0x" + string(signatureS.data()); + } else { + signatureVector.at(1) = string(signatureR.data()); + signatureVector.at(2) = string(signatureS.data()); + } - if (base == 16) { - signatureVector.at(1) = "0x" + string(signatureR.data()); - signatureVector.at(2) = "0x" + string(signatureS.data()); - } else { - signatureVector.at(1) = string(signatureR.data()); - signatureVector.at(2) = string(signatureS.data()); - } + /* Now verify signature */ - /* Now verify signature */ + pubKeyStr = getECDSAPubKey(encryptedKeyHex); - pubKeyStr = getECDSAPubKey(encryptedKeyHex); + static uint64_t i = 0; - static uint64_t i = 0; + i++; - i++; + if (i % 1000 == 0) { - if (i % 1000 == 0) { - - if (!verifyECDSASig(pubKeyStr, hashHex, signatureR.data(), signatureS.data(), base)) { - spdlog::error("failed to verify ecdsa signature"); - throw SGXException(667, "ECDSA did not verify"); - } + if (!verifyECDSASig(pubKeyStr, hashHex, signatureR.data(), + signatureS.data(), base)) { + spdlog::error("failed to verify ecdsa signature"); + throw SGXException(667, "ECDSA did not verify"); } + } - return signatureVector; + return signatureVector; } -string encryptECDSAKey(const string& _key) { - vector key(BUF_LEN, 0); - for (size_t i = 0; i < _key.size(); ++i) { - key[i] = _key[i]; - } +string encryptECDSAKey(const string &_key) { + vector key(BUF_LEN, 0); + for (size_t i = 0; i < _key.size(); ++i) { + key[i] = _key[i]; + } - vector encryptedKey(BUF_LEN, 0); + vector encryptedKey(BUF_LEN, 0); - int errStatus = 0; - vector errString(BUF_LEN, 0); - uint64_t enc_len = 0; + int errStatus = 0; + vector errString(BUF_LEN, 0); + uint64_t enc_len = 0; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedEncryptKey(eid, &errStatus, errString.data(), key.data(), - encryptedKey.data(), &enc_len); + status = trustedEncryptKey(eid, &errStatus, errString.data(), key.data(), + encryptedKey.data(), &enc_len); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errString.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errString.data()); - vector hexEncrKey = carray2Hex(encryptedKey.data(), enc_len); + vector hexEncrKey = carray2Hex(encryptedKey.data(), enc_len); - return string(hexEncrKey.begin(), hexEncrKey.end()); + return string(hexEncrKey.begin(), hexEncrKey.end()); } diff --git a/ECDSACrypto.h b/ECDSACrypto.h index 821aec92..b5d7ac15 100644 --- a/ECDSACrypto.h +++ b/ECDSACrypto.h @@ -24,18 +24,18 @@ #ifndef SGXD_ECDSACRYPTO_H #define SGXD_ECDSACRYPTO_H -#include #include +#include using namespace std; vector genECDSAKey(); -string getECDSAPubKey(const std::string& _encryptedKeyHex); - -vector ecdsaSignHash(const std::string& encryptedKeyHex, const char* hashHex, int base); +string getECDSAPubKey(const std::string &_encryptedKeyHex); -string encryptECDSAKey(const string& key); +vector ecdsaSignHash(const std::string &encryptedKeyHex, + const char *hashHex, int base); +string encryptECDSAKey(const string &key); -#endif //SGXD_ECDSACRYPTO_H +#endif // SGXD_ECDSACRYPTO_H diff --git a/Exception.cpp b/Exception.cpp index 49120df5..5475b4dd 100644 --- a/Exception.cpp +++ b/Exception.cpp @@ -21,28 +21,27 @@ @date 2018 */ - -#include "Log.h" #include "Exception.h" +#include "Log.h" -void Exception::logNested(const std::exception &e, int level) -{ - string prefix; - - if (level == 0) { - prefix = "!Exception:"; - } else { - prefix = "!Caused by:"; - } - if (dynamic_cast(&e) == nullptr) { - LOG(err, string(level, ' ') + prefix + e.what()); - return; - } else { - LOG(err, string(level, ' ') + prefix + e.what()); - } - try { - std::rethrow_if_nested(e); - } catch(const std::exception& e) { - logNested(e, level + 1); - } catch(...) {} +void Exception::logNested(const std::exception &e, int level) { + string prefix; + + if (level == 0) { + prefix = "!Exception:"; + } else { + prefix = "!Caused by:"; + } + if (dynamic_cast(&e) == nullptr) { + LOG(err, string(level, ' ') + prefix + e.what()); + return; + } else { + LOG(err, string(level, ' ') + prefix + e.what()); + } + try { + std::rethrow_if_nested(e); + } catch (const std::exception &e) { + logNested(e, level + 1); + } catch (...) { + } }; diff --git a/Exception.h b/Exception.h index fb9b06b3..3f10553b 100644 --- a/Exception.h +++ b/Exception.h @@ -23,26 +23,28 @@ #pragma once +#include +#include class Exception : public std::exception { public: - Exception( const std::string& _message, const std::string& _className ) { - message = _className + ":" + _message; - } - const char* what() const noexcept override { - return message.empty() ? std::exception::what() : message.c_str(); - } + Exception(const std::string &_message, const std::string &_className) { + message = _className + ":" + _message; + } + const char *what() const noexcept override { + return message.empty() ? std::exception::what() : message.c_str(); + } - const std::string& getMessage() const { return message; } + const std::string &getMessage() const { return message; } - bool isFatal() const { return fatal; } + bool isFatal() const { return fatal; } private: - std::string message; + std::string message; protected: - bool fatal = false; + bool fatal = false; public: - static void logNested( const std::exception& e, int level = 0 ); + static void logNested(const std::exception &e, int level = 0); }; diff --git a/ExitHandler.cpp b/ExitHandler.cpp index 9c786b27..f4afd9e1 100644 --- a/ExitHandler.cpp +++ b/ExitHandler.cpp @@ -3,16 +3,14 @@ #include "ExitHandler.h" -void ExitHandler::exitHandler( int s ) { - exitHandler( s, ec_success ); -} +void ExitHandler::exitHandler(int s) { exitHandler(s, ec_success); } -void ExitHandler::exitHandler( int s, ExitHandler::exit_code_t ec ) { - m_signal = s; - if ( ec != ec_success ) { - g_ec = ec; - } - s_shouldExit = true; +void ExitHandler::exitHandler(int s, ExitHandler::exit_code_t ec) { + m_signal = s; + if (ec != ec_success) { + g_ec = ec; + } + s_shouldExit = true; } volatile bool ExitHandler::s_shouldExit = false; diff --git a/ExitHandler.h b/ExitHandler.h index f3245ee8..7bb5ebcc 100644 --- a/ExitHandler.h +++ b/ExitHandler.h @@ -5,25 +5,25 @@ class ExitHandler { public: - enum exit_code_t { - ec_success = 0, - ec_initing_user_space = 202, // error or exception while initializing user space - }; + enum exit_code_t { + ec_success = 0, + ec_initing_user_space = + 202, // error or exception while initializing user space + }; private: - static volatile bool s_shouldExit; - static volatile int m_signal; - static volatile exit_code_t g_ec; + static volatile bool s_shouldExit; + static volatile int m_signal; + static volatile exit_code_t g_ec; - ExitHandler() = delete; + ExitHandler() = delete; public: - static void exitHandler( int s ); - static void exitHandler( int s, ExitHandler::exit_code_t ec ); - static bool shouldExit() { return s_shouldExit; } - static int getSignal() { return m_signal; } - static exit_code_t requestedExitCode() { return g_ec; } - + static void exitHandler(int s); + static void exitHandler(int s, ExitHandler::exit_code_t ec); + static bool shouldExit() { return s_shouldExit; } + static int getSignal() { return m_signal; } + static exit_code_t requestedExitCode() { return g_ec; } }; #endif // EXITHANDLER_H diff --git a/ExitRequestedException.cpp b/ExitRequestedException.cpp index b6db2e61..849607bd 100644 --- a/ExitRequestedException.cpp +++ b/ExitRequestedException.cpp @@ -23,7 +23,4 @@ #include "ExitRequestedException.h" - -ExitRequestedException::ExitRequestedException() { - -} +ExitRequestedException::ExitRequestedException() {} diff --git a/ExitRequestedException.h b/ExitRequestedException.h index 9850ee82..e03d2f97 100644 --- a/ExitRequestedException.h +++ b/ExitRequestedException.h @@ -27,5 +27,5 @@ class ExitRequestedException : public std::exception { public: - ExitRequestedException(); + ExitRequestedException(); }; diff --git a/InvalidArgumentException.cpp b/InvalidArgumentException.cpp index 8586929b..b3d9da76 100644 --- a/InvalidArgumentException.cpp +++ b/InvalidArgumentException.cpp @@ -21,10 +21,11 @@ @date 2018 */ -#include "Log.h" #include "InvalidArgumentException.h" +#include "Log.h" -InvalidArgumentException::InvalidArgumentException(const std::string &_message, const string& _className) : - Exception(_message, _className) { - fatal = false; +InvalidArgumentException::InvalidArgumentException(const std::string &_message, + const string &_className) + : Exception(_message, _className) { + fatal = false; } diff --git a/InvalidArgumentException.h b/InvalidArgumentException.h index e1391058..82730cfe 100644 --- a/InvalidArgumentException.h +++ b/InvalidArgumentException.h @@ -28,5 +28,6 @@ class InvalidArgumentException : public Exception { public: - InvalidArgumentException( const std::string& _message, const std::string& _className ); + InvalidArgumentException(const std::string &_message, + const std::string &_className); }; diff --git a/InvalidStateException.cpp b/InvalidStateException.cpp index c66003e8..8b5a72f4 100644 --- a/InvalidStateException.cpp +++ b/InvalidStateException.cpp @@ -21,12 +21,12 @@ @date 2018 */ -#include "common.h" -#include "Log.h" #include "InvalidStateException.h" +#include "Log.h" +#include "common.h" - -InvalidStateException::InvalidStateException(const std::string &_message, const string& _className) : - Exception(_message, _className) { - fatal = false; +InvalidStateException::InvalidStateException(const std::string &_message, + const string &_className) + : Exception(_message, _className) { + fatal = false; } diff --git a/InvalidStateException.h b/InvalidStateException.h index 90bd95ce..57c7a321 100644 --- a/InvalidStateException.h +++ b/InvalidStateException.h @@ -25,8 +25,8 @@ #include "Exception.h" - class InvalidStateException : public Exception { public: - InvalidStateException( const std::string& _message, const std::string& _className ); + InvalidStateException(const std::string &_message, + const std::string &_className); }; diff --git a/LevelDB.cpp b/LevelDB.cpp index 00b5fe71..ee54ca95 100644 --- a/LevelDB.cpp +++ b/LevelDB.cpp @@ -21,131 +21,130 @@ @date 2019 */ -#include +#include #include +#include #include -#include #include "leveldb/db.h" #include -#include "sgxwallet_common.h" -#include "SGXException.h" #include "LevelDB.h" +#include "SGXException.h" +#include "sgxwallet_common.h" #include "ServerInit.h" -#include "third_party/spdlog/spdlog.h" #include "common.h" +#include "third_party/spdlog/spdlog.h" using namespace leveldb; static WriteOptions writeOptions; static ReadOptions readOptions; -shared_ptr LevelDB::readNewStyleValue(const string& value) { - Json::Value key_data; - Json::Reader reader; - reader.parse(value.c_str(), key_data); +shared_ptr LevelDB::readNewStyleValue(const string &value) { + Json::Value key_data; + Json::Reader reader; + reader.parse(value.c_str(), key_data); - return std::make_shared(key_data["value"].asString()); + return std::make_shared(key_data["value"].asString()); } std::shared_ptr LevelDB::readString(const string &_key) { - auto result = std::make_shared(); + auto result = std::make_shared(); - CHECK_STATE(db) + CHECK_STATE(db) - auto status = db->Get(readOptions, _key, result.get()); + auto status = db->Get(readOptions, _key, result.get()); - throwExceptionOnError(status); + throwExceptionOnError(status); - if (status.IsNotFound()) { - return nullptr; - } + if (status.IsNotFound()) { + return nullptr; + } - if (result->at(0) == '{') { - return readNewStyleValue(*result); - } + if (result->at(0) == '{') { + return readNewStyleValue(*result); + } - return result; + return result; } void LevelDB::writeString(const string &_key, const string &_value) { - Json::Value writerData; - writerData["value"] = _value; - writerData["timestamp"] = std::to_string(std::time(nullptr)); + Json::Value writerData; + writerData["value"] = _value; + writerData["timestamp"] = std::to_string(std::time(nullptr)); - Json::FastWriter fastWriter; - std::string output = fastWriter.write(writerData); + Json::FastWriter fastWriter; + std::string output = fastWriter.write(writerData); - auto status = db->Put(writeOptions, Slice(_key), Slice(output)); + auto status = db->Put(writeOptions, Slice(_key), Slice(output)); - throwExceptionOnError(status); + throwExceptionOnError(status); } void LevelDB::deleteDHDKGKey(const string &_key) { - string full_key = "DKG_DH_KEY_" + _key; - - auto status = db->Delete(writeOptions, Slice(full_key)); + string full_key = "DKG_DH_KEY_" + _key; - throwExceptionOnError(status); + auto status = db->Delete(writeOptions, Slice(full_key)); + throwExceptionOnError(status); } void LevelDB::deleteTempNEK(const string &_key) { - CHECK_STATE(_key.rfind("tmp_NEK", 0) == 0); + CHECK_STATE(_key.rfind("tmp_NEK", 0) == 0); - auto status = db->Delete(writeOptions, Slice(_key)); + auto status = db->Delete(writeOptions, Slice(_key)); - throwExceptionOnError(status); + throwExceptionOnError(status); } void LevelDB::deleteKey(const string &_key) { - auto status = db->Delete(writeOptions, Slice(_key)); - - throwExceptionOnError(status); + auto status = db->Delete(writeOptions, Slice(_key)); + throwExceptionOnError(status); } void LevelDB::throwExceptionOnError(Status _status) { - if (_status.IsNotFound()) - return; + if (_status.IsNotFound()) + return; - if (!_status.ok()) { - throw SGXException(COULD_NOT_ACCESS_DATABASE, ("Could not access database database:" + _status.ToString()).c_str()); - } + if (!_status.ok()) { + throw SGXException( + COULD_NOT_ACCESS_DATABASE, + ("Could not access database database:" + _status.ToString()).c_str()); + } } -uint64_t LevelDB::visitKeys(LevelDB::KeyVisitor *_visitor, uint64_t _maxKeysToVisit) { +uint64_t LevelDB::visitKeys(LevelDB::KeyVisitor *_visitor, + uint64_t _maxKeysToVisit) { - CHECK_STATE(_visitor); + CHECK_STATE(_visitor); - uint64_t readCounter = 0; + uint64_t readCounter = 0; - leveldb::Iterator *it = db->NewIterator(readOptions); - for (it->SeekToFirst(); it->Valid(); it->Next()) { - _visitor->visitDBKey(it->key().data()); - readCounter++; - if (readCounter >= _maxKeysToVisit) { - break; - } + shared_ptr it(db->NewIterator(readOptions)); + for (it->SeekToFirst(); it->Valid(); it->Next()) { + _visitor->visitDBKey(it->key().data()); + readCounter++; + if (readCounter >= _maxKeysToVisit) { + break; } + } - delete it; - - return readCounter; + return readCounter; } -std::vector LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){ +std::vector LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit) { uint64_t readCounter = 0; std::vector keys; - leveldb::Iterator *it = db->NewIterator(readOptions); + shared_ptr it(db->NewIterator(readOptions)); for (it->SeekToFirst(); it->Valid(); it->Next()) { string cur_key(it->key().data(), it->key().size()); keys.push_back(cur_key); @@ -155,106 +154,104 @@ std::vector LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){ } } - delete it; - return keys; } -void LevelDB::writeDataUnique(const string & name, const string &value) { +void LevelDB::writeDataUnique(const string &name, const string &value) { if (readString(name)) { spdlog::debug("Name {} already exists", name); - throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists"); + throw SGXException(KEY_SHARE_ALREADY_EXISTS, + "Data with this name already exists"); } writeString(name, value); } pair LevelDB::getAllKeys() { - stringstream keysInfo; - - leveldb::Iterator *it = db->NewIterator(readOptions); - uint64_t counter = 0; - for (it->SeekToFirst(); it->Valid(); it->Next()) { - ++counter; - string key = it->key().ToString(); - string value; - if (it->value().ToString()[0] == '{') { - // new style keys - Json::Value key_data; - Json::Reader reader; - reader.parse(it->value().ToString().c_str(), key_data); - - string timestamp_to_date_command = "date -d @" + key_data["timestamp"].asString(); - value = " VALUE: " + key_data["value"].asString() + ", TIMESTAMP: " + exec(timestamp_to_date_command.c_str()) + '\n'; - } else { - // old style keys - value = " VALUE: " + it->value().ToString(); - } - keysInfo << "KEY: " << key << ',' << value; + stringstream keysInfo; + + leveldb::Iterator *it = db->NewIterator(readOptions); + uint64_t counter = 0; + for (it->SeekToFirst(); it->Valid(); it->Next()) { + ++counter; + string key = it->key().ToString(); + string value; + if (it->value().ToString()[0] == '{') { + // new style keys + Json::Value key_data; + Json::Reader reader; + reader.parse(it->value().ToString().c_str(), key_data); + + string timestamp_to_date_command = + "date -d @" + key_data["timestamp"].asString(); + value = " VALUE: " + key_data["value"].asString() + + ", TIMESTAMP: " + exec(timestamp_to_date_command.c_str()) + '\n'; + } else { + // old style keys + value = " VALUE: " + it->value().ToString(); } + keysInfo << "KEY: " << key << ',' << value; + } - return {std::move(keysInfo), counter}; + return {std::move(keysInfo), counter}; } pair LevelDB::getLatestCreatedKey() { - leveldb::Iterator *it = db->NewIterator(readOptions); - - int64_t latest_timestamp = 0; - string latest_created_key_name = ""; - for (it->SeekToFirst(); it->Valid(); it->Next()) { - if (it->value().ToString()[0] == '{') { - // new style keys - Json::Value key_data; - Json::Reader reader; - reader.parse(it->value().ToString().c_str(), key_data); - - if (std::stoi(key_data["timestamp"].asString()) > latest_timestamp) { - latest_timestamp = std::stoi(key_data["timestamp"].asString()); - latest_created_key_name = it->key().ToString(); - } - } else { - // old style keys - // assuming server has at least one new-style key created - continue; - } + leveldb::Iterator *it = db->NewIterator(readOptions); + + int64_t latest_timestamp = 0; + string latest_created_key_name = ""; + for (it->SeekToFirst(); it->Valid(); it->Next()) { + if (it->value().ToString()[0] == '{') { + // new style keys + Json::Value key_data; + Json::Reader reader; + reader.parse(it->value().ToString().c_str(), key_data); + + if (std::stoi(key_data["timestamp"].asString()) > latest_timestamp) { + latest_timestamp = std::stoi(key_data["timestamp"].asString()); + latest_created_key_name = it->key().ToString(); + } + } else { + // old style keys + // assuming server has at least one new-style key created + continue; } + } - return {latest_created_key_name, latest_timestamp}; + return {latest_created_key_name, latest_timestamp}; } - LevelDB::LevelDB(string &filename) { - leveldb::Options options; - options.create_if_missing = true; + leveldb::Options options; + options.create_if_missing = true; - if (!leveldb::DB::Open(options, filename, (leveldb::DB **) &db).ok()) { - throw std::runtime_error("Unable to open levelDB database"); - } + if (!leveldb::DB::Open(options, filename, (leveldb::DB **)&db).ok()) { + throw std::runtime_error("Unable to open levelDB database"); + } - if (db == nullptr) { - throw std::runtime_error("Null levelDB object"); - } + if (db == nullptr) { + throw std::runtime_error("Null levelDB object"); + } } -LevelDB::~LevelDB() { -} +LevelDB::~LevelDB() {} const std::shared_ptr &LevelDB::getLevelDb() { - CHECK_STATE(levelDb) - return levelDb; + CHECK_STATE(levelDb) + return levelDb; } const std::shared_ptr &LevelDB::getCsrDb() { - CHECK_STATE(csrDb) - return csrDb; + CHECK_STATE(csrDb) + return csrDb; } const std::shared_ptr &LevelDB::getCsrStatusDb() { - CHECK_STATE(csrStatusDb) - return csrStatusDb; + CHECK_STATE(csrStatusDb) + return csrStatusDb; } - std::shared_ptr LevelDB::levelDb = nullptr; std::shared_ptr LevelDB::csrDb = nullptr; @@ -266,47 +263,46 @@ string LevelDB::sgx_data_folder; bool LevelDB::isInited = false; void LevelDB::initDataFolderAndDBs() { - CHECK_STATE(!isInited) - isInited = true; + CHECK_STATE(!isInited) + isInited = true; - spdlog::info("Initing wallet database ... "); + spdlog::info("Initing wallet database ... "); - char cwd[PATH_MAX]; + char cwd[PATH_MAX]; - if (getcwd(cwd, sizeof(cwd)) == NULL) { - spdlog::error("Could not get current working directory."); - throw SGXException(COULD_NOT_GET_WORKING_DIRECTORY, "Could not get current working directory."); - } + if (getcwd(cwd, sizeof(cwd)) == NULL) { + spdlog::error("Could not get current working directory."); + throw SGXException(COULD_NOT_GET_WORKING_DIRECTORY, + "Could not get current working directory."); + } - sgx_data_folder = string(cwd) + "/" + SGXDATA_FOLDER; + sgx_data_folder = string(cwd) + "/" + SGXDATA_FOLDER; - struct stat info; - if (stat(sgx_data_folder.c_str(), &info) !=0 ){ - spdlog::info("sgx_data folder does not exist. Creating ..."); + struct stat info; + if (stat(sgx_data_folder.c_str(), &info) != 0) { + spdlog::info("sgx_data folder does not exist. Creating ..."); - if (system(("mkdir " + sgx_data_folder).c_str()) == 0){ - spdlog::info("Successfully created sgx_data folder"); - } - else{ - spdlog::error("Could not create sgx_data folder."); - throw SGXException(ERROR_CREATING_SGX_DATA_FOLDER, "Could not create sgx_data folder."); - } + if (system(("mkdir " + sgx_data_folder).c_str()) == 0) { + spdlog::info("Successfully created sgx_data folder"); + } else { + spdlog::error("Could not create sgx_data folder."); + throw SGXException(ERROR_CREATING_SGX_DATA_FOLDER, + "Could not create sgx_data folder."); } + } - spdlog::info("Opening wallet databases"); + spdlog::info("Opening wallet databases"); - auto dbName = sgx_data_folder + WALLETDB_NAME; - levelDb = make_shared(dbName); + auto dbName = sgx_data_folder + WALLETDB_NAME; + levelDb = make_shared(dbName); - auto csr_dbname = sgx_data_folder + "CSR_DB"; - csrDb = make_shared(csr_dbname); + auto csr_dbname = sgx_data_folder + "CSR_DB"; + csrDb = make_shared(csr_dbname); - auto csr_status_dbname = sgx_data_folder + "CSR_STATUS_DB"; - csrStatusDb = make_shared(csr_status_dbname); + auto csr_status_dbname = sgx_data_folder + "CSR_STATUS_DB"; + csrStatusDb = make_shared(csr_status_dbname); - spdlog::info("Successfully opened databases"); + spdlog::info("Successfully opened databases"); } -const string &LevelDB::getSgxDataFolder() { - return sgx_data_folder; -} +const string &LevelDB::getSgxDataFolder() { return sgx_data_folder; } diff --git a/LevelDB.h b/LevelDB.h index 53df6b3b..4cf32e15 100644 --- a/LevelDB.h +++ b/LevelDB.h @@ -21,91 +21,85 @@ @date 2019 */ - #ifndef SGXWALLET_LEVELDB_H #define SGXWALLET_LEVELDB_H +#include "common.h" #include +#include #include #include -#include #include -#include "common.h" namespace leveldb { - class DB; - class Status; - class Slice; -} +class DB; +class Status; +class Slice; +} // namespace leveldb class LevelDB { - recursive_mutex mutex; + recursive_mutex mutex; - shared_ptr db; + shared_ptr db; - static bool isInited; + static bool isInited; - static shared_ptr levelDb; + static shared_ptr levelDb; - static shared_ptr csrDb; + static shared_ptr csrDb; - static shared_ptr csrStatusDb; + static shared_ptr csrStatusDb; - static string sgx_data_folder; + static string sgx_data_folder; public: + static void initDataFolderAndDBs(); - static void initDataFolderAndDBs(); - - static const shared_ptr &getLevelDb(); + static const shared_ptr &getLevelDb(); - static const shared_ptr &getCsrDb(); + static const shared_ptr &getCsrDb(); - static const shared_ptr &getCsrStatusDb(); + static const shared_ptr &getCsrStatusDb(); public: + shared_ptr readString(const string &_key); - shared_ptr readString(const string& _key); + shared_ptr readNewStyleValue(const string &value); - shared_ptr readNewStyleValue(const string& value); + pair getAllKeys(); - pair getAllKeys(); + pair getLatestCreatedKey(); - pair getLatestCreatedKey(); + void writeString(const string &key1, const string &value1); - void writeString(const string &key1, const string &value1); + void writeDataUnique(const string &Name, const string &value); - void writeDataUnique(const string & Name, const string &value); + void deleteDHDKGKey(const string &_key); - void deleteDHDKGKey (const string &_key); + void deleteTempNEK(const string &_key); - void deleteTempNEK (const string &_key); - - void deleteKey(const string &_key); + void deleteKey(const string &_key); public: + void throwExceptionOnError(leveldb::Status result); - void throwExceptionOnError(leveldb::Status result); - - LevelDB(string& filename); + LevelDB(string &filename); - class KeyVisitor { - public: - virtual void visitDBKey(const char* _data) = 0; - virtual void writeDBKeysToVector(const char* _data, vector & keys_vect) {} - }; + class KeyVisitor { + public: + virtual void visitDBKey(const char *_data) = 0; + virtual void writeDBKeysToVector(const char *_data, + vector &keys_vect) {} + }; - uint64_t visitKeys(KeyVisitor* _visitor, uint64_t _maxKeysToVisit); + uint64_t visitKeys(KeyVisitor *_visitor, uint64_t _maxKeysToVisit); - vector writeKeysToVector1(uint64_t _maxKeysToVisit); + vector writeKeysToVector1(uint64_t _maxKeysToVisit); - virtual ~LevelDB(); + virtual ~LevelDB(); - static const string &getSgxDataFolder(); + static const string &getSgxDataFolder(); }; - - - #endif diff --git a/Log.cpp b/Log.cpp index 872fa37a..bd314c2b 100644 --- a/Log.cpp +++ b/Log.cpp @@ -21,38 +21,38 @@ @date 2019 */ -#include "third_party/spdlog/spdlog.h" -#include "sgxwallet_common.h" -#include "common.h" -#include "SGXException.h" #include "Log.h" +#include "SGXException.h" +#include "common.h" +#include "sgxwallet_common.h" +#include "third_party/spdlog/spdlog.h" using namespace std; void Log::setGlobalLogLevel(string &_s) { - globalLogLevel = logLevelFromString(_s); + globalLogLevel = logLevelFromString(_s); } level_enum Log::logLevelFromString(string &_s) { - level_enum result = trace; - - if (_s == "trace") - result = trace; - else if (_s == "debug") - result = debug; - else if (_s == "info") - result = info; - else if (_s == "warn") - result = warn; - else if (_s == "err") - result = err; - else - throw InvalidArgumentException("Unknown level name " + _s, __CLASS_NAME__); - return result; + level_enum result = trace; + + if (_s == "trace") + result = trace; + else if (_s == "debug") + result = debug; + else if (_s == "info") + result = info; + else if (_s == "warn") + result = warn; + else if (_s == "err") + result = err; + else + throw InvalidArgumentException("Unknown level name " + _s, __CLASS_NAME__); + return result; } -void Log::handleSGXException(Json::Value& _result, SGXException& _e ) { - spdlog::error("Responding with JSON error:" + _e.getErrString()); - _result["status"] = _e.getStatus(); - _result["errorMessage"] = _e.getErrString(); +void Log::handleSGXException(Json::Value &_result, SGXException &_e) { + spdlog::error("Responding with JSON error:" + _e.getErrString()); + _result["status"] = _e.getStatus(); + _result["errorMessage"] = _e.getErrString(); } diff --git a/Log.h b/Log.h index ea11ba97..4703d37e 100644 --- a/Log.h +++ b/Log.h @@ -22,114 +22,112 @@ @date 2019 */ - #ifndef _LOG_H #define _LOG_H - -#include #include #include #include +#include -#include "json/json.h" #include "third_party/spdlog/spdlog.h" +#include "json/json.h" - -#include "SGXException.h" #include "InvalidArgumentException.h" #include "InvalidStateException.h" +#include "SGXException.h" -#include #include "common.h" +#include #include using namespace std; - class Exception; +#define __CLASS_NAME__ className(__PRETTY_FUNCTION__) -#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ ) - -#define LOG(__SEVERITY__, __MESSAGE__) \ - cerr << to_string(__SEVERITY__) << " " << __MESSAGE__ << " " << className( __PRETTY_FUNCTION__ ) << endl; - - -enum level_enum { - trace, debug, info, warn, err -}; +#define LOG(__SEVERITY__, __MESSAGE__) \ + cerr << to_string(__SEVERITY__) << " " << __MESSAGE__ << " " \ + << className(__PRETTY_FUNCTION__) << endl; +enum level_enum { trace, debug, info, warn, err }; class Log { public: + level_enum globalLogLevel; - level_enum globalLogLevel; - - void setGlobalLogLevel(string &_s); + void setGlobalLogLevel(string &_s); - static level_enum logLevelFromString(string &_s); + static level_enum logLevelFromString(string &_s); - static void handleSGXException(Json::Value &_result, SGXException &_e); + static void handleSGXException(Json::Value &_result, SGXException &_e); }; - -#define COUNT_STATISTICS \ -static uint64_t __COUNT__ = 0; \ -__COUNT__++; \ -if (__COUNT__ % 1000 == 0) { \ -spdlog::info(string(__FUNCTION__) + " processed " + to_string(__COUNT__) + " requests"); \ -struct sysinfo memInfo; \ -sysinfo (&memInfo); \ -long long totalPhysMem = memInfo.totalram; \ -/*Multiply in next statement to avoid int overflow on right hand side...*/ \ -totalPhysMem *= memInfo.mem_unit; \ -int usedByCurrentProcess = getValue(); \ -if ( 0.5 * totalPhysMem < usedByCurrentProcess ) { \ - exit(-103); \ -} \ -} - - +#define COUNT_STATISTICS \ + static uint64_t __COUNT__ = 0; \ + __COUNT__++; \ + if (__COUNT__ % 1000 == 0) { \ + spdlog::info(string(__FUNCTION__) + " processed " + to_string(__COUNT__) + \ + " requests"); \ + struct sysinfo memInfo; \ + sysinfo(&memInfo); \ + long long totalPhysMem = memInfo.totalram; \ + /*Multiply in next statement to avoid int overflow on right hand side...*/ \ + totalPhysMem *= memInfo.mem_unit; \ + int usedByCurrentProcess = getValue(); \ + if (0.5 * totalPhysMem < usedByCurrentProcess) { \ + exit(-103); \ + } \ + } // if uknown error, the error is 10000 + line number - -#define INIT_RESULT(__RESULT__) Json::Value __RESULT__; \ - int errStatus = -1 * (10000 + __LINE__); boost::ignore_unused(errStatus); string errMsg(BUF_LEN, '\0');__RESULT__["status"] = -1 * (10000 + __LINE__); __RESULT__["errorMessage"] = \ - string(__FUNCTION__); \ -string(__FUNCTION__) + ": server error. Please see server log."; - -#define HANDLE_SGX_EXCEPTION(__RESULT__) \ - catch (const SGXException& _e) { \ - if (_e.getStatus() != 0) {__RESULT__["status"] = _e.getStatus();} else { __RESULT__["status"] = -1 * (10000 + __LINE__);}; \ - auto errStr = __FUNCTION__ + string(" failed:") + _e.getErrString(); \ - __RESULT__["errorMessage"] = errStr; \ - spdlog::error(errStr); \ - return __RESULT__; \ - } catch (const exception& _e) { \ - __RESULT__["status"] = -1 * (10000 + __LINE__); \ - exception_ptr p = current_exception(); \ - auto errStr = __FUNCTION__ + string(" failed:") + p.__cxa_exception_type()->name() + ":" + _e.what(); \ - __RESULT__["errorMessage"] = errStr; \ - spdlog::error(errStr); \ - return __RESULT__; \ - } \ - catch (...) { \ - exception_ptr p = current_exception(); \ - auto errStr = __FUNCTION__ + string(" failed:") + p.__cxa_exception_type()->name(); \ - spdlog::error(errStr); \ - __RESULT__["errorMessage"] = errStr ; \ - spdlog::error(errStr); \ - return __RESULT__; \ - } - -#define RETURN_SUCCESS(__RESULT__) \ - __RESULT__["status"] = 0; \ - __RESULT__["errorMessage"] = ""; \ - return __RESULT__; +#define INIT_RESULT(__RESULT__) \ + Json::Value __RESULT__; \ + int errStatus = -1 * (10000 + __LINE__); \ + boost::ignore_unused(errStatus); \ + string errMsg(BUF_LEN, '\0'); \ + __RESULT__["status"] = -1 * (10000 + __LINE__); \ + __RESULT__["errorMessage"] = string(__FUNCTION__); \ + string(__FUNCTION__) + ": server error. Please see server log."; + +#define HANDLE_SGX_EXCEPTION(__RESULT__) \ + catch (const SGXException &_e) { \ + if (_e.getStatus() != 0) { \ + __RESULT__["status"] = _e.getStatus(); \ + } else { \ + __RESULT__["status"] = -1 * (10000 + __LINE__); \ + }; \ + auto errStr = __FUNCTION__ + string(" failed:") + _e.getErrString(); \ + __RESULT__["errorMessage"] = errStr; \ + spdlog::error(errStr); \ + return __RESULT__; \ + } \ + catch (const exception &_e) { \ + __RESULT__["status"] = -1 * (10000 + __LINE__); \ + exception_ptr p = current_exception(); \ + auto errStr = __FUNCTION__ + string(" failed:") + \ + p.__cxa_exception_type()->name() + ":" + _e.what(); \ + __RESULT__["errorMessage"] = errStr; \ + spdlog::error(errStr); \ + return __RESULT__; \ + } \ + catch (...) { \ + exception_ptr p = current_exception(); \ + auto errStr = \ + __FUNCTION__ + string(" failed:") + p.__cxa_exception_type()->name(); \ + spdlog::error(errStr); \ + __RESULT__["errorMessage"] = errStr; \ + spdlog::error(errStr); \ + return __RESULT__; \ + } + +#define RETURN_SUCCESS(__RESULT__) \ + __RESULT__["status"] = 0; \ + __RESULT__["errorMessage"] = ""; \ + return __RESULT__; #endif - diff --git a/Makefile.am b/Makefile.am index ac4ac491..6ad95870 100644 --- a/Makefile.am +++ b/Makefile.am @@ -49,8 +49,8 @@ AM_CFLAGS = -DUSER_SPACE -O2 -rdynamic -Wl,--no-as-needed -lSegFault -DSGXWALLET AM_CXXFLAGS = ${AM_CPPFLAGS} -rdynamic -Wl,--no-as-needed -lSegFault -DSGXWALLET_VERSION="$(WALLET_VERSION)" -AM_CPPFLAGS += -DSGXWALLET_VERSION="$(WALLET_VERSION)" -Wall -DSKALE_SGX=1 -DBINARY_OUTPUT=1 -Ileveldb/include -IlibBLS/bls\ - -IlibBLS/libff -IlibBLS -fno-builtin-memset $(GMP_CPPFLAGS) -I. \ +AM_CPPFLAGS += -DSGXWALLET_VERSION="$(WALLET_VERSION)" -Wall -DSKALE_SGX=1 -DBINARY_OUTPUT=1 -Ileveldb/include -IlibBLS/bls \ + -IlibBLS/libff -IlibBLS -fno-builtin-memset $(GMP_CPPFLAGS) -I. \ -I./libBLS/deps/deps_inst/x86_or_x64/include -I./libzmq/include -I./cppzmq -I./third_party/zguide \ -I./rapidjson/include/rapidjson @@ -71,9 +71,9 @@ bin_PROGRAMS = sgxwallet testw sgx_util COMMON_SRC = SGXException.cpp ExitHandler.cpp zmq_src/ZMQClient.cpp zmq_src/RspMessage.cpp zmq_src/ReqMessage.cpp \ - zmq_src/ZMQMessage.cpp zmq_src/ZMQServer.cpp zmq_src/Agent.cpp zmq_src/WorkerThreadPool.cpp ExitRequestedException.cpp \ + zmq_src/ZMQMessage.cpp zmq_src/ZMQServer.cpp zmq_src/Agent.cpp zmq_src/WorkerThreadPool.cpp ExitRequestedException.cpp \ InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp TECrypto.cpp \ - SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp CryptoTools.cpp \ + SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp CryptoTools.cpp \ DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp SEKManager.cpp \ third_party/intel/sgx_stub.c third_party/intel/sgx_detect_linux.c third_party/intel/create_enclave.c \ third_party/intel/oc_alloc.c ECDSAImpl.c TestUtils.cpp sgxwallet.c SGXInfoServer.cpp ECDSACrypto.cpp @@ -128,4 +128,3 @@ sgx_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/b -l:libbls.a -l:libleveldb.a \ -l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common \ -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -ldl - diff --git a/SEKManager.cpp b/SEKManager.cpp index 4206aa26..125b18ff 100644 --- a/SEKManager.cpp +++ b/SEKManager.cpp @@ -21,204 +21,208 @@ @date 2020 */ - +#include #include #include -#include #include "third_party/spdlog/spdlog.h" -#include "sgxwallet_common.h" #include "common.h" #include "sgxwallet.h" +#include "sgxwallet_common.h" -#include "SGXException.h" #include "CryptoTools.h" #include "LevelDB.h" +#include "SGXException.h" +#include "SEKManager.h" #include "ServerDataChecker.h" #include "ServerInit.h" -#include "SEKManager.h" using namespace std; #define BACKUP_PATH "./sgx_data/sgxwallet_backup_key.txt" - bool case_insensitive_match(string s1, string s2) { - //convert s1 and s2 into lower case strings - transform(s1.begin(), s1.end(), s1.begin(), ::tolower); - transform(s2.begin(), s2.end(), s2.begin(), ::tolower); - return s1.compare(s2); + // convert s1 and s2 into lower case strings + transform(s1.begin(), s1.end(), s1.begin(), ::tolower); + transform(s2.begin(), s2.end(), s2.begin(), ::tolower); + return s1.compare(s2); } void create_test_key() { - int errStatus = 0; - vector errMsg(1024, 0); - uint64_t enc_len; + int errStatus = 0; + vector errMsg(1024, 0); + uint64_t enc_len; - SAFE_UINT8_BUF(encrypted_key, BUF_LEN); + SAFE_UINT8_BUF(encrypted_key, BUF_LEN); - string key = TEST_VALUE; + string key = TEST_VALUE; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - { - READ_LOCK(sgxInitMutex); - status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len); - } + { + READ_LOCK(sgxInitMutex); + status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), + encrypted_key, &enc_len); + } - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - vector hexEncrKey = carray2Hex(encrypted_key, enc_len); + vector hexEncrKey = carray2Hex(encrypted_key, enc_len); - LevelDB::getLevelDb()->writeDataUnique("TEST_KEY", hexEncrKey.data()); + LevelDB::getLevelDb()->writeDataUnique("TEST_KEY", hexEncrKey.data()); } void validate_SEK() { - shared_ptr test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY"); - vector encr_test_key(BUF_LEN, 0); - vector decr_key(BUF_LEN, 0); - uint64_t len = 0; - vector errMsg(BUF_LEN, 0); + shared_ptr test_key_ptr = + LevelDB::getLevelDb()->readString("TEST_KEY"); + vector encr_test_key(BUF_LEN, 0); + vector decr_key(BUF_LEN, 0); + uint64_t len = 0; + vector errMsg(BUF_LEN, 0); - int err_status = 0; + int err_status = 0; - if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data(), - BUF_LEN)) { - spdlog::error("Corrupt test key is LevelDB"); - throw SGXException(CORRUPT_DATABASE, "Corrupt test key is LevelDB"); - } + if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data(), BUF_LEN)) { + spdlog::error("Corrupt test key is LevelDB"); + throw SGXException(CORRUPT_DATABASE, "Corrupt test key is LevelDB"); + } - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - { - READ_LOCK(sgxInitMutex); - status = trustedDecryptKey(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data()); - } + { + READ_LOCK(sgxInitMutex); + status = trustedDecryptKey(eid, &err_status, errMsg.data(), + encr_test_key.data(), len, decr_key.data()); + } - HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); - string test_key = TEST_VALUE; + string test_key = TEST_VALUE; - if (test_key.compare(decr_key.data()) != 0) { - spdlog::error("Invalid storage key. You need to recover using backup key"); - spdlog::error("Set the correct backup key into sgx_datasgxwallet_backup_key.txt"); - spdlog::error("Then run sgxwallet using backup flag"); - throw SGXException(INVALID_SEK, "Invalid storage key. Recover using backup key"); - } + if (test_key.compare(decr_key.data()) != 0) { + spdlog::error("Invalid storage key. You need to recover using backup key"); + spdlog::error( + "Set the correct backup key into sgx_datasgxwallet_backup_key.txt"); + spdlog::error("Then run sgxwallet using backup flag"); + throw SGXException(INVALID_SEK, + "Invalid storage key. Recover using backup key"); + } } -shared_ptr > check_and_set_SEK(const string &SEK) { +shared_ptr> check_and_set_SEK(const string &SEK) { - vector decr_key(BUF_LEN, 0); - vector errMsg(BUF_LEN, 0); - int err_status = 0; + vector decr_key(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); + int err_status = 0; - auto encrypted_SEK = make_shared < vector < uint8_t >> (BUF_LEN, 0); + auto encrypted_SEK = make_shared>(BUF_LEN, 0); - uint64_t l = 0; + uint64_t l = 0; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - { - READ_LOCK(sgxInitMutex); - status = trustedSetSEKBackup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l, - SEK.c_str()); - } + { + READ_LOCK(sgxInitMutex); + status = trustedSetSEKBackup(eid, &err_status, errMsg.data(), + encrypted_SEK->data(), &l, SEK.c_str()); + } - HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); - encrypted_SEK->resize(l); + encrypted_SEK->resize(l); - validate_SEK(); + validate_SEK(); - return encrypted_SEK; + return encrypted_SEK; } void gen_SEK() { - vector errMsg(1024, 0); - int err_status = 0; - vector encrypted_SEK(1024, 0); - uint64_t enc_len = 0; - - SAFE_CHAR_BUF(SEK, 65); + vector errMsg(1024, 0); + int err_status = 0; + vector encrypted_SEK(1024, 0); + uint64_t enc_len = 0; - spdlog::info("Generating backup key. Will be stored in backup_key.txt ... "); + SAFE_CHAR_BUF(SEK, 65); - sgx_status_t status = SGX_SUCCESS; - { + spdlog::info("Generating backup key. Will be stored in backup_key.txt ... "); - status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK); - } + sgx_status_t status = SGX_SUCCESS; + { - HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); + status = trustedGenerateSEK(eid, &err_status, errMsg.data(), + encrypted_SEK.data(), &enc_len, SEK); + } - if (strnlen(SEK, 33) != 32) { - throw SGXException(-1, "strnlen(SEK,33) != 32"); - } + HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); - vector hexEncrKey = carray2Hex(encrypted_SEK.data(), enc_len); + if (strnlen(SEK, 33) != 32) { + throw SGXException(-1, "strnlen(SEK,33) != 32"); + } - spdlog::info(string("Encrypted storage encryption key:") + hexEncrKey.data()); + vector hexEncrKey = carray2Hex(encrypted_SEK.data(), enc_len); - ofstream sek_file(BACKUP_PATH); - sek_file.clear(); + spdlog::info(string("Encrypted storage encryption key:") + hexEncrKey.data()); - sek_file << SEK; + ofstream sek_file(BACKUP_PATH); + sek_file.clear(); - cout << "ATTENTION! YOUR BACKUP KEY HAS BEEN WRITTEN INTO sgx_data/backup_key.txt \n" << - "PLEASE COPY IT TO THE SAFE PLACE AND THEN DELETE THE FILE MANUALLY BY RUNNING THE FOLLOWING COMMAND:\n" << - "apt-get install secure-delete && srm -vz sgx_data/backup_key.txt" << endl; + sek_file << SEK; - if (!autoconfirm) { - string confirm_str = "I confirm"; - string buffer; - do { - cout << " DO YOU CONFIRM THAT YOU COPIED THE KEY? (if you confirm type - I confirm)" - << endl; - sleep(10); - getline(cin, buffer); - } while (case_insensitive_match(confirm_str, buffer)); - } + cout << "ATTENTION! YOUR BACKUP KEY HAS BEEN WRITTEN INTO " + "sgx_data/backup_key.txt \n" + << "PLEASE COPY IT TO THE SAFE PLACE AND THEN DELETE THE FILE MANUALLY " + "BY RUNNING THE FOLLOWING COMMAND:\n" + << "apt-get install secure-delete && srm -vz sgx_data/backup_key.txt" + << endl; - LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data()); + if (!autoconfirm) { + string confirm_str = "I confirm"; + string buffer; + do { + cout << " DO YOU CONFIRM THAT YOU COPIED THE KEY? (if you confirm type - " + "I confirm)" + << endl; + sleep(10); + getline(cin, buffer); + } while (case_insensitive_match(confirm_str, buffer)); + } - create_test_key(); + LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data()); - validate_SEK(); + create_test_key(); - shared_ptr encrypted_SEK_ptr = LevelDB::getLevelDb()->readString("SEK"); + validate_SEK(); - setSEK(encrypted_SEK_ptr); + shared_ptr encrypted_SEK_ptr = + LevelDB::getLevelDb()->readString("SEK"); + setSEK(encrypted_SEK_ptr); } -void setSEK(shared_ptr hex_encrypted_SEK) { +void setSEK(shared_ptr hex_encrypted_SEK) { - CHECK_STATE(hex_encrypted_SEK); + CHECK_STATE(hex_encrypted_SEK); - vector errMsg(1024, 0); - int err_status = 0; + vector errMsg(1024, 0); + int err_status = 0; - SAFE_UINT8_BUF(encrypted_SEK, BUF_LEN); + SAFE_UINT8_BUF(encrypted_SEK, BUF_LEN); - uint64_t len = 0; + uint64_t len = 0; - if (!hex2carray(hex_encrypted_SEK->c_str(), &len, encrypted_SEK, - BUF_LEN)) { - throw SGXException(SET_SEK_INVALID_SEK_HEX, "Invalid encrypted SEK Hex"); - } + if (!hex2carray(hex_encrypted_SEK->c_str(), &len, encrypted_SEK, BUF_LEN)) { + throw SGXException(SET_SEK_INVALID_SEK_HEX, "Invalid encrypted SEK Hex"); + } - sgx_status_t status = SGX_SUCCESS; - { - status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK); - } + sgx_status_t status = SGX_SUCCESS; + { status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK); } - HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data()); - validate_SEK(); + validate_SEK(); } #include "experimental/filesystem" @@ -227,61 +231,64 @@ void setSEK(shared_ptr hex_encrypted_SEK) { void enter_SEK() { - shared_ptr test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY"); - if (test_key_ptr == nullptr) { - spdlog::error("Error: corrupt or empty LevelDB database"); - throw SGXException(CORRUPT_DATABASE, "Could not find TEST_KEY in database."); - } - - if (!experimental::filesystem::is_regular_file(BACKUP_PATH)) { - spdlog::error("File does not exist: " BACKUP_PATH); - throw SGXException(FILE_NOT_FOUND, "File does not exist: " BACKUP_PATH); - } + shared_ptr test_key_ptr = + LevelDB::getLevelDb()->readString("TEST_KEY"); + if (test_key_ptr == nullptr) { + spdlog::error("Error: corrupt or empty LevelDB database"); + throw SGXException(CORRUPT_DATABASE, + "Could not find TEST_KEY in database."); + } - ifstream sek_file(BACKUP_PATH); + if (!experimental::filesystem::is_regular_file(BACKUP_PATH)) { + spdlog::error("File does not exist: " BACKUP_PATH); + throw SGXException(FILE_NOT_FOUND, "File does not exist: " BACKUP_PATH); + } - spdlog::info("Reading backup key from file ..."); + ifstream sek_file(BACKUP_PATH); - string sek((istreambuf_iterator(sek_file)), - istreambuf_iterator()); + spdlog::info("Reading backup key from file ..."); - boost::trim(sek); + string sek((istreambuf_iterator(sek_file)), + istreambuf_iterator()); - spdlog::info("Setting backup key ..."); + boost::trim(sek); - while (!checkHex(sek, 16)) { - spdlog::error("Invalid hex in key"); - throw SGXException(SET_SEK_INVALID_SEK_HEX, "Invalid hex in key"); - } + spdlog::info("Setting backup key ..."); - auto encrypted_SEK = check_and_set_SEK(sek); + while (!checkHex(sek, 16)) { + spdlog::error("Invalid hex in key"); + throw SGXException(SET_SEK_INVALID_SEK_HEX, "Invalid hex in key"); + } - vector hexEncrKey = carray2Hex(encrypted_SEK->data(), encrypted_SEK->size()); + auto encrypted_SEK = check_and_set_SEK(sek); - spdlog::info("Got sealed storage encryption key."); + vector hexEncrKey = + carray2Hex(encrypted_SEK->data(), encrypted_SEK->size()); - LevelDB::getLevelDb()->deleteKey("SEK"); + spdlog::info("Got sealed storage encryption key."); - spdlog::info("Storing sealed storage encryption key in LevelDB ..."); + LevelDB::getLevelDb()->deleteKey("SEK"); - LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data()); + spdlog::info("Storing sealed storage encryption key in LevelDB ..."); - spdlog::info("Stored storage encryption key in LevelDB."); + LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data()); + spdlog::info("Stored storage encryption key in LevelDB."); } void initSEK() { - if (enterBackupKey) { - enter_SEK(); + if (enterBackupKey) { + enter_SEK(); + } else { + shared_ptr encrypted_SEK_ptr = + LevelDB::getLevelDb()->readString("SEK"); + if (encrypted_SEK_ptr == nullptr) { + spdlog::warn("SEK was not created yet. Going to create SEK"); + gen_SEK(); } else { - shared_ptr encrypted_SEK_ptr = LevelDB::getLevelDb()->readString("SEK"); - if (encrypted_SEK_ptr == nullptr) { - spdlog::warn("SEK was not created yet. Going to create SEK"); - gen_SEK(); - } else { - setSEK(encrypted_SEK_ptr); - } + setSEK(encrypted_SEK_ptr); } + } } -//a002e7ca685d46a32771d16fe2518e58 +// a002e7ca685d46a32771d16fe2518e58 diff --git a/SEKManager.h b/SEKManager.h index 587add37..8609b1c6 100644 --- a/SEKManager.h +++ b/SEKManager.h @@ -25,8 +25,8 @@ #define SGXD_SEKMANAGER_H #ifdef __cplusplus -#include #include +#include #endif void gen_SEK(); @@ -47,8 +47,4 @@ EXTERNC void initSEK(); EXTERNC void setSEK(); - - - - -#endif //SGXD_SEKMANAGER_H +#endif // SGXD_SEKMANAGER_H diff --git a/SGXException.cpp b/SGXException.cpp index b4317dab..fb0beb8c 100644 --- a/SGXException.cpp +++ b/SGXException.cpp @@ -23,8 +23,4 @@ #include "SGXException.h" -const char* SGXException::what() const noexcept { - return errString.c_str(); -} - - +const char *SGXException::what() const noexcept { return errString.c_str(); } diff --git a/SGXException.h b/SGXException.h index 7b5493bd..009be475 100644 --- a/SGXException.h +++ b/SGXException.h @@ -24,33 +24,29 @@ #ifndef SGXD_SGXEXCEPTION_H #define SGXD_SGXEXCEPTION_H -#include #include +#include using namespace std; class SGXException : public exception { - const int32_t status; - const string errString; + const int32_t status; + const string errString; public: + SGXException(int32_t _status, const string &_errString) + : status(_status), errString(_errString) {} - SGXException(int32_t _status, const string& _errString) : status(_status), errString(_errString) {} - - const string getMessage() const { - return "SGXException:status:" + to_string(status) + ":" + errString; - } + const string getMessage() const { + return "SGXException:status:" + to_string(status) + ":" + errString; + } - const string& getErrString() const { - return errString; - } + const string &getErrString() const { return errString; } - const char* what() const noexcept override; + const char *what() const noexcept override; - const int32_t getStatus() const { - return status; - } + const int32_t getStatus() const { return status; } }; -#endif //SGXD_SGXEXCEPTION_H +#endif // SGXD_SGXEXCEPTION_H diff --git a/SGXInfoServer.cpp b/SGXInfoServer.cpp index d21613d2..7b9d1dc2 100644 --- a/SGXInfoServer.cpp +++ b/SGXInfoServer.cpp @@ -21,8 +21,8 @@ @date 2020 */ -#include #include +#include #include #include @@ -31,109 +31,121 @@ #include "sgxwallet_common.h" -#include "SGXException.h" #include "LevelDB.h" +#include "SGXException.h" -#include "SGXInfoServer.h" #include "LevelDB.h" +#include "SGXInfoServer.h" #include "Log.h" #include "common.h" -shared_ptr SGXInfoServer::server = nullptr; -shared_ptr SGXInfoServer::httpServer = nullptr; - -SGXInfoServer::SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type, - uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys) - : AbstractInfoServer(connector, type) { - logLevel_ = _logLevel; - autoSign_ = _autoSign; - checkCerts_ = _checkCerts; - generateTestKeys_ = _generateTestKeys; +shared_ptr SGXInfoServer::server = nullptr; +shared_ptr SGXInfoServer::httpServer = nullptr; + +SGXInfoServer::SGXInfoServer(AbstractServerConnector &connector, + serverVersion_t type, uint32_t _logLevel, + bool _autoSign, bool _checkCerts, + bool _generateTestKeys) + : AbstractInfoServer(connector, type) { + logLevel_ = _logLevel; + autoSign_ = _autoSign; + checkCerts_ = _checkCerts; + generateTestKeys_ = _generateTestKeys; } Json::Value SGXInfoServer::getAllKeysInfo() { - Json::Value result; + Json::Value result; - try { - auto allKeysInfo = LevelDB::getLevelDb()->getAllKeys(); - result["allKeys"] = allKeysInfo.first.str(); - result["keysNumber"] = std::to_string(allKeysInfo.second); - } HANDLE_SGX_EXCEPTION(result) + try { + auto allKeysInfo = LevelDB::getLevelDb()->getAllKeys(); + result["allKeys"] = allKeysInfo.first.str(); + result["keysNumber"] = std::to_string(allKeysInfo.second); + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result) + RETURN_SUCCESS(result) } Json::Value SGXInfoServer::getLatestCreatedKey() { - Json::Value result; + Json::Value result; - try { - pair key = LevelDB::getLevelDb()->getLatestCreatedKey(); - result["keyName"] = key.first; - result["creationTime"] = std::to_string(key.second); - } HANDLE_SGX_EXCEPTION(result) + try { + pair key = LevelDB::getLevelDb()->getLatestCreatedKey(); + result["keyName"] = key.first; + result["creationTime"] = std::to_string(key.second); + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result) + RETURN_SUCCESS(result) } Json::Value SGXInfoServer::getServerConfiguration() { - Json::Value result; - - try { - result["autoConfirm"] = autoconfirm; - result["logLevel"] = logLevel_; - result["enterBackupKey"] = enterBackupKey; - result["useHTTPS"] = useHTTPS; - result["autoSign"] = autoSign_; - result["checkCerts"] = checkCerts_; - result["generateTestKeys"] = generateTestKeys_; - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) + Json::Value result; + + try { + result["autoConfirm"] = autoconfirm; + result["logLevel"] = logLevel_; + result["enterBackupKey"] = enterBackupKey; + result["useHTTPS"] = useHTTPS; + result["autoSign"] = autoSign_; + result["checkCerts"] = checkCerts_; + result["generateTestKeys"] = generateTestKeys_; + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } -Json::Value SGXInfoServer::isKeyExist(const string& key) { - Json::Value result; +Json::Value SGXInfoServer::isKeyExist(const string &key) { + Json::Value result; - result["isExists"] = false; - try { - shared_ptr keyPtr = LevelDB::getLevelDb()->readString(key); + result["isExists"] = false; + try { + shared_ptr keyPtr = LevelDB::getLevelDb()->readString(key); - if (keyPtr != nullptr) { - result["IsExist"] = true; - } - } HANDLE_SGX_EXCEPTION(result) + if (keyPtr != nullptr) { + result["IsExist"] = true; + } + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result) + RETURN_SUCCESS(result) } -void SGXInfoServer::initInfoServer(uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys) { - httpServer = make_shared(BASE_PORT + 4); - server = make_shared(*httpServer, JSONRPC_SERVER_V2, _logLevel, _autoSign, _checkCerts, _generateTestKeys); // hybrid server (json-rpc 1.0 & 2.0) +void SGXInfoServer::initInfoServer(uint32_t _logLevel, bool _autoSign, + bool _checkCerts, bool _generateTestKeys) { + httpServer = make_shared(BASE_PORT + 4); + server = make_shared( + *httpServer, JSONRPC_SERVER_V2, _logLevel, _autoSign, _checkCerts, + _generateTestKeys); // hybrid server (json-rpc 1.0 & 2.0) - spdlog::info("Starting info server on port {} ...", BASE_PORT + 4); + spdlog::info("Starting info server on port {} ...", BASE_PORT + 4); - if (!server->StartListening()) { - spdlog::error("Info server could not start listening on port {}", BASE_PORT + 4); - throw SGXException(SGX_INFO_SERVER_FAILED_TO_START, "Info server could not start listening."); - } else { - spdlog::info("Info server started on port {}", BASE_PORT + 4); - } + if (!server->StartListening()) { + spdlog::error("Info server could not start listening on port {}", + BASE_PORT + 4); + throw SGXException(SGX_INFO_SERVER_FAILED_TO_START, + "Info server could not start listening."); + } else { + spdlog::info("Info server started on port {}", BASE_PORT + 4); + } } int SGXInfoServer::exitServer() { spdlog::info("Stoping SGXInfo server"); if (server && !server->StopListening()) { - spdlog::error("SGXInfo server could not be stopped. Will forcefully terminate the app"); + spdlog::error("SGXInfo server could not be stopped. Will forcefully " + "terminate the app"); } else { - spdlog::info("SGXInfo server stopped"); + spdlog::info("SGXInfo server stopped"); } return 0; } shared_ptr SGXInfoServer::getServer() { - CHECK_STATE(server); - return server; + CHECK_STATE(server); + return server; } diff --git a/SGXInfoServer.h b/SGXInfoServer.h index cde88903..de0c447c 100644 --- a/SGXInfoServer.h +++ b/SGXInfoServer.h @@ -33,36 +33,36 @@ using namespace jsonrpc; using namespace std; class SGXInfoServer : public AbstractInfoServer { - recursive_mutex m; + recursive_mutex m; - uint32_t logLevel_; - bool autoSign_; - bool checkCerts_; - bool generateTestKeys_; + uint32_t logLevel_; + bool autoSign_; + bool checkCerts_; + bool generateTestKeys_; - static shared_ptr httpServer; + static shared_ptr httpServer; - static shared_ptr server; + static shared_ptr server; public: + static shared_ptr getServer(); - static shared_ptr getServer(); + SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type, + uint32_t _logLevel, bool _autoSign, bool _checkCerts, + bool _generateTestKeys); - SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type, - uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys); + virtual Json::Value getAllKeysInfo(); - virtual Json::Value getAllKeysInfo(); + virtual Json::Value getLatestCreatedKey(); - virtual Json::Value getLatestCreatedKey(); + virtual Json::Value getServerConfiguration(); - virtual Json::Value getServerConfiguration(); + virtual Json::Value isKeyExist(const string &key); - virtual Json::Value isKeyExist(const string& key); - - static void initInfoServer(uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys); - - static int exitServer(); + static void initInfoServer(uint32_t _logLevel, bool _autoSign, + bool _checkCerts, bool _generateTestKeys); + static int exitServer(); }; #endif // SGXINFOSERVER_H diff --git a/SGXRegistrationServer.cpp b/SGXRegistrationServer.cpp index 1f8d8fe7..8bad1e3d 100644 --- a/SGXRegistrationServer.cpp +++ b/SGXRegistrationServer.cpp @@ -21,27 +21,27 @@ @date 2019 */ -#include #include +#include #include -#include #include +#include #include #include "sgxwallet_common.h" -#include "SGXException.h" #include "LevelDB.h" +#include "SGXException.h" #include #include #include -#include "SGXRegistrationServer.h" #include "LevelDB.h" +#include "SGXRegistrationServer.h" #include "Log.h" #include "common.h" @@ -51,138 +51,146 @@ bool useHTTPS = false; bool enterBackupKey = false; bool autoconfirm = false; -shared_ptr SGXRegistrationServer::server = nullptr; -shared_ptr SGXRegistrationServer::httpServer = nullptr; +shared_ptr SGXRegistrationServer::server = nullptr; +shared_ptr SGXRegistrationServer::httpServer = nullptr; SGXRegistrationServer::SGXRegistrationServer(AbstractServerConnector &connector, - serverVersion_t type, bool _autoSign) - : AbstractRegServer(connector, type), autoSign(_autoSign) {} - + serverVersion_t type, + bool _autoSign) + : AbstractRegServer(connector, type), autoSign(_autoSign) {} Json::Value SGXRegistrationServer::SignCertificate(const string &csr) { - spdlog::info(__FUNCTION__); - INIT_RESULT(result) - - result["result"] = false; - - try { - std::lock_guard lock(m); - - string hash = cryptlite::sha256::hash_hex(csr); - - if (system("ls " CERT_DIR "/" CERT_CREATE_COMMAND) != 0) { - spdlog::error("cert/create_client_cert does not exist"); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED"); - } - - string csr_name = string(CERT_DIR) + "/" + hash + ".csr"; - ofstream outfile(csr_name); - outfile.exceptions(std::ifstream::failbit | std::ifstream::badbit); - outfile << csr << endl; - outfile.close(); - - if (system(("ls " + csr_name).c_str()) != 0) { - spdlog::error("could not create csr file"); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED"); - } - - if (system(("openssl req -in " + csr_name).c_str()) != 0) { - spdlog::error("Incorrect CSR format: {}", csr); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "Incorrect CSR format "); - } - - if (autoSign) { - string genCert = string("cd ") + CERT_DIR + "&& ./" - + CERT_CREATE_COMMAND + " " + hash ; - - if (system(genCert.c_str()) == 0) { - spdlog::info("Client cert " + hash + " generated"); - } else { - spdlog::error("Client cert generation failed: {} ", genCert); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED"); - } - } else { - string db_key = "CSR:HASH:" + hash; - LevelDB::getCsrStatusDb()->writeDataUnique(db_key, csr); - } - string db_key = "CSR:HASH:" + hash + "STATUS:"; - string status = "0"; - LevelDB::getCsrStatusDb()->writeDataUnique(db_key, status); - - result["result"] = true; - result["hash"] = hash; - - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) + spdlog::info(__FUNCTION__); + INIT_RESULT(result) + + result["result"] = false; + + try { + std::lock_guard lock(m); + + string hash = cryptlite::sha256::hash_hex(csr); + + if (system("ls " CERT_DIR "/" CERT_CREATE_COMMAND) != 0) { + spdlog::error("cert/create_client_cert does not exist"); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, + "CLIENT CERTIFICATE GENERATION FAILED"); + } + + string csr_name = string(CERT_DIR) + "/" + hash + ".csr"; + ofstream outfile(csr_name); + outfile.exceptions(std::ifstream::failbit | std::ifstream::badbit); + outfile << csr << endl; + outfile.close(); + + if (system(("ls " + csr_name).c_str()) != 0) { + spdlog::error("could not create csr file"); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, + "CLIENT CERTIFICATE GENERATION FAILED"); + } + + if (system(("openssl req -in " + csr_name).c_str()) != 0) { + spdlog::error("Incorrect CSR format: {}", csr); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "Incorrect CSR format "); + } + + if (autoSign) { + string genCert = + string("cd ") + CERT_DIR + "&& ./" + CERT_CREATE_COMMAND + " " + hash; + + if (system(genCert.c_str()) == 0) { + spdlog::info("Client cert " + hash + " generated"); + } else { + spdlog::error("Client cert generation failed: {} ", genCert); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, + "CLIENT CERTIFICATE GENERATION FAILED"); + } + } else { + string db_key = "CSR:HASH:" + hash; + LevelDB::getCsrStatusDb()->writeDataUnique(db_key, csr); + } + string db_key = "CSR:HASH:" + hash + "STATUS:"; + string status = "0"; + LevelDB::getCsrStatusDb()->writeDataUnique(db_key, status); + + result["result"] = true; + result["hash"] = hash; + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } Json::Value SGXRegistrationServer::GetCertificate(const string &hash) { - spdlog::info(__FUNCTION__); - - Json::Value result; - - string cert; - try { - string db_key = "CSR:HASH:" + hash + "STATUS:"; - shared_ptr status_str_ptr = LevelDB::getCsrStatusDb()->readString(db_key); - if (status_str_ptr == nullptr) { - throw SGXException(CERT_REQUEST_DOES_NOT_EXIST, "Data with this name does not exist in csr db"); - } - int status = atoi(status_str_ptr->c_str()); - - if (status == 0) { - string crtPath = "cert/" + hash + ".crt"; - - if (system(("ls " + crtPath).c_str()) != 0) { - throw SGXException(FILE_NOT_FOUND, "Certificate does not exist"); - } - - ifstream infile(crtPath); - infile.exceptions(std::ifstream::failbit | std::ifstream::badbit); - ostringstream ss; - ss << infile.rdbuf(); - infile.close(); - cert = ss.str(); - } - - result["status"] = status; - result["cert"] = cert; - - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) -} + spdlog::info(__FUNCTION__); + + Json::Value result; + + string cert; + try { + string db_key = "CSR:HASH:" + hash + "STATUS:"; + shared_ptr status_str_ptr = + LevelDB::getCsrStatusDb()->readString(db_key); + if (status_str_ptr == nullptr) { + throw SGXException(CERT_REQUEST_DOES_NOT_EXIST, + "Data with this name does not exist in csr db"); + } + int status = atoi(status_str_ptr->c_str()); -void SGXRegistrationServer::initRegistrationServer(bool _autoSign) { - httpServer = make_shared(BASE_PORT + 1); - server = make_shared(*httpServer, - JSONRPC_SERVER_V2, - _autoSign); // hybrid server (json-rpc 1.0 & 2.0) + if (status == 0) { + string crtPath = "cert/" + hash + ".crt"; - spdlog::info("Starting registration server on port {} ...", BASE_PORT + 1); + if (system(("ls " + crtPath).c_str()) != 0) { + throw SGXException(FILE_NOT_FOUND, "Certificate does not exist"); + } - if (!server->StartListening()) { - spdlog::error("Registration server could not start listening on port {}", BASE_PORT + 1); - throw SGXException(REGISTRATION_SERVER_FAILED_TO_START, "Registration server could not start listening."); - } else { - spdlog::info("Registration server started on port {}", BASE_PORT + 1); + ifstream infile(crtPath); + infile.exceptions(std::ifstream::failbit | std::ifstream::badbit); + ostringstream ss; + ss << infile.rdbuf(); + infile.close(); + cert = ss.str(); } + + result["status"] = status; + result["cert"] = cert; + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) +} + +void SGXRegistrationServer::initRegistrationServer(bool _autoSign) { + httpServer = make_shared(BASE_PORT + 1); + server = make_shared( + *httpServer, JSONRPC_SERVER_V2, + _autoSign); // hybrid server (json-rpc 1.0 & 2.0) + + spdlog::info("Starting registration server on port {} ...", BASE_PORT + 1); + + if (!server->StartListening()) { + spdlog::error("Registration server could not start listening on port {}", + BASE_PORT + 1); + throw SGXException(REGISTRATION_SERVER_FAILED_TO_START, + "Registration server could not start listening."); + } else { + spdlog::info("Registration server started on port {}", BASE_PORT + 1); + } } int SGXRegistrationServer::exitServer() { spdlog::info("Stoping registration server"); if (server && !server->StopListening()) { - spdlog::error("Registration server could not be stopped. Will forcefully terminate the app"); + spdlog::error("Registration server could not be stopped. Will forcefully " + "terminate the app"); } else { - spdlog::info("Registration server stopped"); + spdlog::info("Registration server stopped"); } return 0; } shared_ptr SGXRegistrationServer::getServer() { - CHECK_STATE(server); - return server; + CHECK_STATE(server); + return server; } diff --git a/SGXRegistrationServer.h b/SGXRegistrationServer.h index e39fa9d3..ac2ff0d5 100644 --- a/SGXRegistrationServer.h +++ b/SGXRegistrationServer.h @@ -24,42 +24,38 @@ #ifndef SGXD_SGXREGISTRATIONSERVER_H #define SGXD_SGXREGISTRATIONSERVER_H - #include #include "abstractregserver.h" #include - #define CERT_DIR "cert" #define CERT_CREATE_COMMAND "create_client_cert" - using namespace jsonrpc; using namespace std; class SGXRegistrationServer : public AbstractRegServer { - mutex m; - bool autoSign; + mutex m; + bool autoSign; - static shared_ptr httpServer; + static shared_ptr httpServer; - static shared_ptr server; + static shared_ptr server; public: + static shared_ptr getServer(); - static shared_ptr getServer(); + SGXRegistrationServer(AbstractServerConnector &connector, + serverVersion_t type, bool _autoSign = false); - SGXRegistrationServer(AbstractServerConnector &connector, serverVersion_t type, bool _autoSign = false); + virtual Json::Value SignCertificate(const string &csr); - virtual Json::Value SignCertificate(const string &csr); + virtual Json::Value GetCertificate(const string &hash); - virtual Json::Value GetCertificate(const string &hash); + static void initRegistrationServer(bool _autoSign = false); - static void initRegistrationServer(bool _autoSign = false); - - static int exitServer(); + static int exitServer(); }; - #endif // SGXD_SGXREGISTRATIONSERVER_H diff --git a/SGXWalletServer.cpp b/SGXWalletServer.cpp index c3d8644c..371f7fa0 100644 --- a/SGXWalletServer.cpp +++ b/SGXWalletServer.cpp @@ -26,20 +26,20 @@ #include #include "abstractstubserver.h" +#include #include #include -#include #include #include -#include "sgxwallet_common.h" #include "sgxwallet.h" +#include "sgxwallet_common.h" -#include "SGXException.h" -#include "LevelDB.h" #include "BLSCrypto.h" #include "DKGCrypto.h" #include "ECDSACrypto.h" +#include "LevelDB.h" +#include "SGXException.h" #include "TECrypto.h" #include "SGXWalletServer.h" @@ -51,7 +51,7 @@ #include "Log.h" #ifdef SGX_HW_SIM -#define NUM_THREADS 16 +#define NUM_THREADS 8 #else #define NUM_THREADS 200 #endif @@ -62,1092 +62,1272 @@ std::shared_timed_mutex sgxInitMutex; uint64_t initTime; -void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - - CHECK_STATE(_logLevel <= 2) - - if (_logLevel == L_TRACE) { - spdlog::set_level(spdlog::level::trace); - } else if (_logLevel == L_DEBUG) { - spdlog::set_level(spdlog::level::debug); - } else { - spdlog::set_level(spdlog::level::info); - } - - useHTTPS = _useHTTPS; - spdlog::info("useHTTPS set to " + to_string(_useHTTPS)); - autoconfirm = _autoconfirm; - spdlog::info("autoconfirm set to " + to_string(autoconfirm)); - enterBackupKey = _enterBackupKey; - spdlog::info("enterBackupKey set to " + to_string(enterBackupKey)); +void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, + int _enterBackupKey) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + + CHECK_STATE(_logLevel <= 2) + + if (_logLevel == L_TRACE) { + spdlog::set_level(spdlog::level::trace); + } else if (_logLevel == L_DEBUG) { + spdlog::set_level(spdlog::level::debug); + } else { + spdlog::set_level(spdlog::level::info); + } + + useHTTPS = _useHTTPS; + spdlog::info("useHTTPS set to " + to_string(_useHTTPS)); + autoconfirm = _autoconfirm; + spdlog::info("autoconfirm set to " + to_string(autoconfirm)); + enterBackupKey = _enterBackupKey; + spdlog::info("enterBackupKey set to " + to_string(enterBackupKey)); } void setOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - setFullOptions(_logLevel, _useHTTPS, _autoconfirm, false); + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + setFullOptions(_logLevel, _useHTTPS, _autoconfirm, false); } bool isStringDec(const string &_str) { - auto res = find_if_not(_str.begin(), _str.end(), [](char c) -> bool { - return isdigit(c); - }); - return !_str.empty() && res == _str.end(); + auto res = find_if_not(_str.begin(), _str.end(), + [](char c) -> bool { return isdigit(c); }); + return !_str.empty() && res == _str.end(); } -shared_ptr SGXWalletServer::server = nullptr; -shared_ptr SGXWalletServer::httpServer = nullptr; +shared_ptr SGXWalletServer::server = nullptr; +shared_ptr SGXWalletServer::httpServer = nullptr; SGXWalletServer::SGXWalletServer(AbstractServerConnector &_connector, serverVersion_t _type) - : AbstractStubServer(_connector, _type) {} + : AbstractStubServer(_connector, _type) {} void SGXWalletServer::printDB() { - cout << "PRINTING LEVELDB: " << endl; - class MyVisitor : public LevelDB::KeyVisitor { - public: - virtual void visitDBKey(const char *_data) { - cout << _data << endl; - } - }; + cout << "PRINTING LEVELDB: " << endl; + class MyVisitor : public LevelDB::KeyVisitor { + public: + virtual void visitDBKey(const char *_data) { cout << _data << endl; } + }; - MyVisitor v; + MyVisitor v; - LevelDB::getLevelDb()->visitKeys(&v, 100000000); + LevelDB::getLevelDb()->visitKeys(&v, 100000000); } bool SGXWalletServer::verifyCert(string &_certFileName) { - string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem"; - string verifyCert = "cert/verify_client_cert " + rootCAPath + " " + _certFileName; - return system(verifyCert.c_str()) == 0; + string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem"; + string verifyCert = + "cert/verify_client_cert " + rootCAPath + " " + _certFileName; + return system(verifyCert.c_str()) == 0; } void SGXWalletServer::createCertsIfNeeded() { - string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem"; - string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key"; + string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem"; + string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key"; - if (access(rootCAPath.c_str(), F_OK) != 0 || access(keyCAPath.c_str(), F_OK) != 0) { - spdlog::info("NO ROOT CA CERTIFICATE YET. CREATING ..."); + if (access(rootCAPath.c_str(), F_OK) != 0 || + access(keyCAPath.c_str(), F_OK) != 0) { + spdlog::info("NO ROOT CA CERTIFICATE YET. CREATING ..."); - string genRootCACert = "cd cert && ./create_CA"; + string genRootCACert = "cd cert && ./create_CA"; - if (system(genRootCACert.c_str()) == 0) { - spdlog::info("ROOT CA CERTIFICATE IS SUCCESSFULLY GENERATED"); - } else { - spdlog::error("ROOT CA CERTIFICATE GENERATION FAILED"); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "ROOT CA CERTIFICATE GENERATION FAILED"); - } + if (system(genRootCACert.c_str()) == 0) { + spdlog::info("ROOT CA CERTIFICATE IS SUCCESSFULLY GENERATED"); + } else { + spdlog::error("ROOT CA CERTIFICATE GENERATION FAILED"); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, + "ROOT CA CERTIFICATE GENERATION FAILED"); } + } - string certPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.crt"; - string keyPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.key"; + string certPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.crt"; + string keyPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.key"; - if (access(certPath.c_str(), F_OK) != 0 || access(certPath.c_str(), F_OK) != 0) { - spdlog::info("YOU DO NOT HAVE SERVER CERTIFICATE"); - spdlog::info("SERVER CERTIFICATE IS GOING TO BE CREATED"); + if (access(certPath.c_str(), F_OK) != 0 || + access(certPath.c_str(), F_OK) != 0) { + spdlog::info("YOU DO NOT HAVE SERVER CERTIFICATE"); + spdlog::info("SERVER CERTIFICATE IS GOING TO BE CREATED"); - string genCert = "cd cert && ./create_server_cert"; + string genCert = "cd cert && ./create_server_cert"; - if (system(genCert.c_str()) == 0) { - spdlog::info("SERVER CERTIFICATE IS SUCCESSFULLY GENERATED"); - } else { - spdlog::info("SERVER CERTIFICATE GENERATION FAILED"); - throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "SERVER CERTIFICATE GENERATION FAILED"); - } + if (system(genCert.c_str()) == 0) { + spdlog::info("SERVER CERTIFICATE IS SUCCESSFULLY GENERATED"); + } else { + spdlog::info("SERVER CERTIFICATE GENERATION FAILED"); + throw SGXException(FAIL_TO_CREATE_CERTIFICATE, + "SERVER CERTIFICATE GENERATION FAILED"); } + } - spdlog::info("Verifying server cert"); + spdlog::info("Verifying server cert"); - if (verifyCert(certPath)) { - spdlog::info("SERVER CERTIFICATE IS SUCCESSFULLY VERIFIED"); - } else { - spdlog::info("SERVER CERTIFICATE VERIFICATION FAILED"); - throw SGXException(FAIL_TO_VERIFY_CERTIFICATE, "SERVER CERTIFICATE VERIFICATION FAILED"); - } + if (verifyCert(certPath)) { + spdlog::info("SERVER CERTIFICATE IS SUCCESSFULLY VERIFIED"); + } else { + spdlog::info("SERVER CERTIFICATE VERIFICATION FAILED"); + throw SGXException(FAIL_TO_VERIFY_CERTIFICATE, + "SERVER CERTIFICATE VERIFICATION FAILED"); + } } void SGXWalletServer::initHttpsServer(bool _checkCerts) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - spdlog::info("Initing server, number of threads: {}", NUM_THREADS); - - string certPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.crt"; - string keyPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.key"; - string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem"; - string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key"; - - httpServer = make_shared(BASE_PORT, certPath, keyPath, rootCAPath, _checkCerts, - NUM_THREADS); - - server = make_shared(*httpServer, - JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0) - - spdlog::info("Starting sgx server on port {} ...", BASE_PORT); - - if (!server->StartListening()) { - spdlog::error("SGX Server could not start listening"); - throw SGXException(SGX_SERVER_FAILED_TO_START, "Https server could not start listening."); - } else { - spdlog::info("SGX Server started on port {}", BASE_PORT); - } + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + spdlog::info("Initing server, number of threads: {}", NUM_THREADS); + + string certPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.crt"; + string keyPath = string(SGXDATA_FOLDER) + "cert_data/SGXServerCert.key"; + string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem"; + string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key"; + + httpServer = make_shared(BASE_PORT, certPath, keyPath, rootCAPath, + _checkCerts, NUM_THREADS); + + server = make_shared( + *httpServer, + JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0) + + spdlog::info("Starting sgx server on port {} ...", BASE_PORT); + + if (!server->StartListening()) { + spdlog::error("SGX Server could not start listening"); + throw SGXException(SGX_SERVER_FAILED_TO_START, + "Https server could not start listening."); + } else { + spdlog::info("SGX Server started on port {}", BASE_PORT); + } } -void SGXWalletServer::initHttpServer() { //without ssl - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - - spdlog::info("Starting sgx http server on port {} ...", BASE_PORT + 3); - - httpServer = make_shared(BASE_PORT + 3, "", "", "", false, - NUM_THREADS); - server = make_shared(*httpServer, - JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0) - if (!server->StartListening()) { - spdlog::error("Server could not start listening"); - throw SGXException(SGX_SERVER_FAILED_TO_START, "Http server could not start listening."); - } +void SGXWalletServer::initHttpServer() { // without ssl + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + + spdlog::info("Starting sgx http server on port {} ...", BASE_PORT + 3); + + httpServer = + make_shared(BASE_PORT + 3, "", "", "", false, NUM_THREADS); + server = make_shared( + *httpServer, + JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0) + if (!server->StartListening()) { + spdlog::error("Server could not start listening"); + throw SGXException(SGX_SERVER_FAILED_TO_START, + "Http server could not start listening."); + } } int SGXWalletServer::exitServer() { - spdlog::info("Stoping sgx server"); + spdlog::info("Stoping sgx server"); - if (server && !server->StopListening()) { - spdlog::error("Sgx server could not be stopped. Will forcefully terminate the app"); - } else { - spdlog::info("Sgx server stopped"); - } + if (server && !server->StopListening()) { + spdlog::error( + "Sgx server could not be stopped. Will forcefully terminate the app"); + } else { + spdlog::info("Sgx server stopped"); + } - return 0; + return 0; } Json::Value -SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_keyShareName) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result); +SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, + const string &_keyShareName) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result); - result["encryptedKeyShare"] = ""; + result["encryptedKeyShare"] = ""; - string encryptedKeyShareHex; + string encryptedKeyShareHex; - try { - if (!checkName(_keyShareName, "BLS_KEY")) { - throw SGXException(BLS_IMPORT_INVALID_KEY_NAME, string(__FUNCTION__) + ":Invalid BLS key name"); - } + try { + if (!checkName(_keyShareName, "BLS_KEY")) { + throw SGXException(BLS_IMPORT_INVALID_KEY_NAME, + string(__FUNCTION__) + ":Invalid BLS key name"); + } - string hashTmp = _keyShare; - if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) { - hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2); - } + 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(BLS_IMPORT_INVALID_KEY_SHARE, - string(__FUNCTION__) + ":Invalid BLS key share, please use hex"); - } + if (!checkHex(hashTmp)) { + throw SGXException(BLS_IMPORT_INVALID_KEY_SHARE, + string(__FUNCTION__) + + ":Invalid BLS key share, please use hex"); + } - encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, (char *) errMsg.data(), hashTmp.c_str()); + encryptedKeyShareHex = encryptBLSKeyShare2Hex( + &errStatus, (char *)errMsg.data(), hashTmp.c_str()); - if (errStatus != 0) { - throw SGXException(errStatus, string(__FUNCTION__) + ":" + errMsg.data()); - } + if (errStatus != 0) { + throw SGXException(errStatus, string(__FUNCTION__) + ":" + errMsg.data()); + } - if (encryptedKeyShareHex.empty()) { - throw SGXException(BLS_IMPORT_EMPTY_ENCRYPTED_KEY_SHARE, string(__FUNCTION__) + - ":Empty encrypted key share"); - } + if (encryptedKeyShareHex.empty()) { + throw SGXException(BLS_IMPORT_EMPTY_ENCRYPTED_KEY_SHARE, + string(__FUNCTION__) + ":Empty encrypted key share"); + } - result["encryptedKeyShare"] = encryptedKeyShareHex; + result["encryptedKeyShare"] = encryptedKeyShareHex; - writeKeyShare(_keyShareName, encryptedKeyShareHex); - } HANDLE_SGX_EXCEPTION(result) + writeKeyShare(_keyShareName, encryptedKeyShareHex); + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } -map SGXWalletServer::blsRequests; +map SGXWalletServer::blsRequests; recursive_mutex SGXWalletServer::blsRequestsLock; -map SGXWalletServer::ecdsaRequests; +map SGXWalletServer::ecdsaRequests; recursive_mutex SGXWalletServer::ecdsaRequestsLock; -void SGXWalletServer::checkForDuplicate(map &_map, recursive_mutex &_m, - const string &_key, +void SGXWalletServer::checkForDuplicate(map &_map, + recursive_mutex &_m, const string &_key, const string &_value) { - LOCK(_m); - if (_map.count(_key) && _map.at(_key) == _value) { - usleep(100 * 1000); - spdlog::warn(string("Received an identical request from the client:") + __FUNCTION__); - } - _map[_key] = _value; + LOCK(_m); + if (_map.count(_key) && _map.at(_key) == _value) { + usleep(100 * 1000); + spdlog::warn(string("Received an identical request from the client:") + + __FUNCTION__); + } + _map[_key] = _value; } -Json::Value -SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const string &_messageHash, int t, int n) { - spdlog::trace("Entering {}", __FUNCTION__); - - COUNT_STATISTICS - - INIT_RESULT(result) - - result["status"] = -1; +Json::Value SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, + const string &_messageHash, + int t, int n) { + spdlog::trace("Entering {}", __FUNCTION__); - result["signatureShare"] = ""; + COUNT_STATISTICS - vector signature(BUF_LEN, 0); + INIT_RESULT(result) - shared_ptr value = nullptr; + result["status"] = -1; - checkForDuplicate(blsRequests, blsRequestsLock, _keyShareName, _messageHash); + result["signatureShare"] = ""; - try { - if (!checkName(_keyShareName, "BLS_KEY")) { - throw SGXException(BLS_SIGN_INVALID_KS_NAME, string(__FUNCTION__) + ":Invalid BLSKey name"); - } + vector signature(BUF_LEN, 0); - if (!check_n_t(t, n)) { - throw SGXException(BLS_SIGN_INVALID_PARAMS, string(__FUNCTION__) + ":Invalid t/n parameters"); - } + shared_ptr value = nullptr; - string hashTmp = _messageHash; - if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) { - hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2); - } + checkForDuplicate(blsRequests, blsRequestsLock, _keyShareName, _messageHash); - if (!checkHex(hashTmp)) { - throw SGXException(INVALID_BLS_HEX, string(__FUNCTION__) + ":Invalid bls hex"); - } + try { + if (!checkName(_keyShareName, "BLS_KEY")) { + throw SGXException(BLS_SIGN_INVALID_KS_NAME, + string(__FUNCTION__) + ":Invalid BLSKey name"); + } - value = readFromDb(_keyShareName); + if (!check_n_t(t, n)) { + throw SGXException(BLS_SIGN_INVALID_PARAMS, + string(__FUNCTION__) + ":Invalid t/n parameters"); + } + string hashTmp = _messageHash; + if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) { + hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2); + } - if (!bls_sign(value->c_str(), hashTmp.c_str(), t, n, signature.data())) { - throw SGXException(COULD_NOT_BLS_SIGN, ":Could not bls sign data "); - } + if (!checkHex(hashTmp)) { + throw SGXException(INVALID_BLS_HEX, + string(__FUNCTION__) + ":Invalid bls hex"); + } - } HANDLE_SGX_EXCEPTION(result) + value = readFromDb(_keyShareName); + if (!bls_sign(value->c_str(), hashTmp.c_str(), t, n, signature.data())) { + throw SGXException(COULD_NOT_BLS_SIGN, ":Could not bls sign data "); + } + } + HANDLE_SGX_EXCEPTION(result) - result["signatureShare"] = string(signature.data()); + result["signatureShare"] = string(signature.data()); - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } Json::Value SGXWalletServer::importECDSAKeyImpl(const string &_keyShare, const string &_keyShareName) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - result["encryptedKey"] = ""; - - try { - if (!checkECDSAKeyName(_keyShareName)) { - throw SGXException(INVALID_ECDSA_IMPORT_KEY_NAME, string(__FUNCTION__) + ":Invalid ECDSA import key name"); - } + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + result["encryptedKey"] = ""; + + try { + if (!checkECDSAKeyName(_keyShareName)) { + throw SGXException(INVALID_ECDSA_IMPORT_KEY_NAME, + string(__FUNCTION__) + + ":Invalid ECDSA import key name"); + } - string hashTmp = _keyShare; - if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) { - hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2); - } + 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_ECDSA_IMPORT_HEX, - string(__FUNCTION__) + ":Invalid ECDSA key share, please use hex"); - } + if (!checkHex(hashTmp)) { + throw SGXException(INVALID_ECDSA_IMPORT_HEX, + string(__FUNCTION__) + + ":Invalid ECDSA key share, please use hex"); + } - string encryptedKey = encryptECDSAKey(hashTmp); + string encryptedKey = encryptECDSAKey(hashTmp); - writeDataToDB(_keyShareName, encryptedKey); + writeDataToDB(_keyShareName, encryptedKey); - result["encryptedKey"] = encryptedKey; - result["publicKey"] = getECDSAPubKey(encryptedKey); - } HANDLE_SGX_EXCEPTION(result) + result["encryptedKey"] = encryptedKey; + result["publicKey"] = getECDSAPubKey(encryptedKey); + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } Json::Value SGXWalletServer::generateECDSAKeyImpl() { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - result["encryptedKey"] = ""; + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + result["encryptedKey"] = ""; - vector keys; + vector keys; - try { - keys = genECDSAKey(); + try { + keys = genECDSAKey(); - if (keys.size() == 0) { - throw SGXException(ECDSA_GEN_EMPTY_KEY, string(__FUNCTION__) + ":key was not generated"); - } + if (keys.size() == 0) { + throw SGXException(ECDSA_GEN_EMPTY_KEY, + string(__FUNCTION__) + ":key was not generated"); + } - string keyName = "NEK:" + keys.at(2); + string keyName = "NEK:" + keys.at(2); - writeDataToDB(keyName, keys.at(0)); + writeDataToDB(keyName, keys.at(0)); - result["encryptedKey"] = keys.at(0); - result["publicKey"] = keys.at(1); - result["PublicKey"] = keys.at(1); - result["keyName"] = keyName; - } HANDLE_SGX_EXCEPTION(result) + result["encryptedKey"] = keys.at(0); + result["publicKey"] = keys.at(1); + result["PublicKey"] = keys.at(1); + result["keyName"] = keyName; + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } -Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_keyName, const string &_messageHash) { - COUNT_STATISTICS - spdlog::trace("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - result["signature_v"] = ""; - result["signature_r"] = ""; - result["signature_s"] = ""; - - vector signatureVector(3); - - checkForDuplicate(ecdsaRequests, ecdsaRequestsLock, _keyName, _messageHash); - - try { - string hashTmp = _messageHash; - if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) { - hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2); - } - while (hashTmp[0] == '0') { - hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 1); - } - - if (!checkECDSAKeyName(_keyName)) { - throw SGXException(INVALID_ECDSA_SIGN_KEY_NAME, string(__FUNCTION__) + ":Invalid ECDSA sign key name"); - } - if (!checkHex(hashTmp)) { - throw SGXException(INVALID_ECDSA_SIGN_HASH, ":Invalid ECDSA sign hash"); - } - if (_base <= 0 || _base > 32) { - throw SGXException(INVALID_ECDSA_SIGN_BASE, ":Invalid ECDSA sign base"); - } - - shared_ptr encryptedKey = readFromDb(_keyName, ""); - - signatureVector = ecdsaSignHash(encryptedKey->c_str(), hashTmp.c_str(), _base); - if (signatureVector.size() != 3) { - throw SGXException(INVALID_ECSDA_SIGN_SIGNATURE, string(__FUNCTION__) + ":Invalid ecdsa signature"); - } - - result["signature_v"] = signatureVector.at(0); - result["signature_r"] = signatureVector.at(1); - result["signature_s"] = signatureVector.at(2); - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) +Json::Value +SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_keyName, + const string &_messageHash) { + COUNT_STATISTICS + spdlog::trace("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + result["signature_v"] = ""; + result["signature_r"] = ""; + result["signature_s"] = ""; + + vector signatureVector(3); + + checkForDuplicate(ecdsaRequests, ecdsaRequestsLock, _keyName, _messageHash); + + try { + string hashTmp = _messageHash; + if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) { + hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2); + } + while (hashTmp[0] == '0') { + hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 1); + } + + if (!checkECDSAKeyName(_keyName)) { + throw SGXException(INVALID_ECDSA_SIGN_KEY_NAME, + string(__FUNCTION__) + ":Invalid ECDSA sign key name"); + } + if (!checkHex(hashTmp)) { + throw SGXException(INVALID_ECDSA_SIGN_HASH, ":Invalid ECDSA sign hash"); + } + if (_base <= 0 || _base > 32) { + throw SGXException(INVALID_ECDSA_SIGN_BASE, ":Invalid ECDSA sign base"); + } + + shared_ptr encryptedKey = readFromDb(_keyName, ""); + + signatureVector = + ecdsaSignHash(encryptedKey->c_str(), hashTmp.c_str(), _base); + if (signatureVector.size() != 3) { + throw SGXException(INVALID_ECSDA_SIGN_SIGNATURE, + string(__FUNCTION__) + ":Invalid ecdsa signature"); + } + + result["signature_v"] = signatureVector.at(0); + result["signature_r"] = signatureVector.at(1); + result["signature_s"] = signatureVector.at(2); + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } Json::Value SGXWalletServer::getPublicECDSAKeyImpl(const string &_keyName) { - COUNT_STATISTICS - spdlog::debug("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - result["publicKey"] = ""; - result["PublicKey"] = ""; - - string publicKey; - - try { - if (!checkECDSAKeyName(_keyName)) { - throw SGXException(INVALID_ECDSA_GETPKEY_KEY_NAME, string(__FUNCTION__) + - ":Invalid ECDSA import key name"); - } - shared_ptr keyStr = readFromDb(_keyName); - publicKey = getECDSAPubKey(keyStr->c_str()); - result["PublicKey"] = publicKey; - result["publicKey"] = publicKey; - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) + COUNT_STATISTICS + spdlog::debug("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + result["publicKey"] = ""; + result["PublicKey"] = ""; + + string publicKey; + + try { + if (!checkECDSAKeyName(_keyName)) { + throw SGXException(INVALID_ECDSA_GETPKEY_KEY_NAME, + string(__FUNCTION__) + + ":Invalid ECDSA import key name"); + } + shared_ptr keyStr = readFromDb(_keyName); + publicKey = getECDSAPubKey(keyStr->c_str()); + result["PublicKey"] = publicKey; + result["publicKey"] = publicKey; + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } -Json::Value SGXWalletServer::generateDKGPolyImpl(const string &_polyName, int _t) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - string encrPolyHex; - - try { - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_GEN_DKG_POLY_NAME, - string(__FUNCTION__) + ":Invalid gen DKG polynomial name."); - } - if (_t <= 0 || _t > 32) { - throw SGXException(GENERATE_DKG_POLY_INVALID_PARAMS, string(__FUNCTION__) + ":Invalid gen dkg param t "); - } - encrPolyHex = gen_dkg_poly(_t); - writeDataToDB(_polyName, encrPolyHex); - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) +Json::Value SGXWalletServer::generateDKGPolyImpl(const string &_polyName, + int _t) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + string encrPolyHex; + + try { + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_GEN_DKG_POLY_NAME, + string(__FUNCTION__) + + ":Invalid gen DKG polynomial name."); + } + if (_t <= 0 || _t > 32) { + throw SGXException(GENERATE_DKG_POLY_INVALID_PARAMS, + string(__FUNCTION__) + ":Invalid gen dkg param t "); + } + encrPolyHex = gen_dkg_poly(_t); + writeDataToDB(_polyName, encrPolyHex); + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } -Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName, int _t) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) +Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName, + int _t) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + vector> verifVector; + try { + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_DKG_GETVV_POLY_NAME, + string(__FUNCTION__) + ":Invalid polynomial name"); + } + if (_t <= 0) { + throw SGXException(INVALID_DKG_GETVV_PARAMS, + string(__FUNCTION__) + ":Invalid t "); + } + + shared_ptr encrPoly = readFromDb(_polyName); - vector > verifVector; - try { - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_DKG_GETVV_POLY_NAME, string(__FUNCTION__) + ":Invalid polynomial name"); - } - if (_t <= 0) { - throw SGXException(INVALID_DKG_GETVV_PARAMS, string(__FUNCTION__) + ":Invalid t "); - } + verifVector = get_verif_vect(*encrPoly, _t); - shared_ptr encrPoly = readFromDb(_polyName); + for (int i = 0; i < _t; i++) { + vector currentCoef = verifVector.at(i); + for (int j = 0; j < 4; j++) { + result["verificationVector"][i][j] = currentCoef.at(j); + } + } + } + HANDLE_SGX_EXCEPTION(result) - verifVector = get_verif_vect(*encrPoly, _t); + RETURN_SUCCESS(result) +} - for (int i = 0; i < _t; i++) { - vector currentCoef = verifVector.at(i); - for (int j = 0; j < 4; j++) { - result["verificationVector"][i][j] = currentCoef.at(j); - } - } - } HANDLE_SGX_EXCEPTION(result) +Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, + const Json::Value &_pubKeys, + int _t, int _n) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result); + result["secretShare"] = ""; + + try { + if (_pubKeys.size() != (uint64_t)_n) { + throw SGXException(INVALID_DKG_GETSS_PUB_KEY_COUNT, + string(__FUNCTION__) + ":Invalid pubkey count"); + } + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_DKG_GETSS_POLY_NAME, + string(__FUNCTION__) + ":Invalid polynomial name"); + } + if (!check_n_t(_t, _n)) { + throw SGXException(INVALID_DKG_GETSS_POLY_NAME, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } - RETURN_SUCCESS(result) + shared_ptr encrPoly = readFromDb(_polyName); + vector pubKeysStrs; + for (int i = 0; i < _n; i++) { + if (!checkHex(_pubKeys[i].asString(), 64)) { + throw SGXException(INVALID_DKG_GETSS_KEY_HEX, + string(__FUNCTION__) + ":Invalid public key"); + } + pubKeysStrs.push_back(_pubKeys[i].asString()); + } + + string secret_share_name = "encryptedSecretShare:" + _polyName; + shared_ptr encryptedSecretShare = + checkDataFromDb(secret_share_name); + + if (encryptedSecretShare != nullptr) { + result["secretShare"] = *encryptedSecretShare.get(); + } else { + result["secretShare"] = + getSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n); + } + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } -Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result); - result["secretShare"] = ""; - - try { - if (_pubKeys.size() != (uint64_t) _n) { - throw SGXException(INVALID_DKG_GETSS_PUB_KEY_COUNT, string(__FUNCTION__) + ":Invalid pubkey count"); - } - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_DKG_GETSS_POLY_NAME, string(__FUNCTION__) + ":Invalid polynomial name"); - } - if (!check_n_t(_t, _n)) { - throw SGXException(INVALID_DKG_GETSS_POLY_NAME, string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - - shared_ptr encrPoly = readFromDb(_polyName); - - vector pubKeysStrs; - for (int i = 0; i < _n; i++) { - if (!checkHex(_pubKeys[i].asString(), 64)) { - throw SGXException(INVALID_DKG_GETSS_KEY_HEX, string(__FUNCTION__) + ":Invalid public key"); - } - pubKeysStrs.push_back(_pubKeys[i].asString()); - } - - string secret_share_name = "encryptedSecretShare:" + _polyName; - shared_ptr encryptedSecretShare = checkDataFromDb(secret_share_name); - - if (encryptedSecretShare != nullptr) { - result["secretShare"] = *encryptedSecretShare.get(); - } else { - result["secretShare"] = getSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n); - } - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) +Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, + const string &_ethKeyName, + const string &_secretShare, + int _t, int _n, int _index) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + result["result"] = false; + + try { + if (!checkECDSAKeyName(_ethKeyName)) { + throw SGXException(INVALID_DKG_VERIFY_ECDSA_KEY_NAME, + string(__FUNCTION__) + ":Invalid ECDSA key name"); + } + if (!check_n_t(_t, _n) || _index >= _n || _index < 0) { + throw SGXException(INVALID_DKG_VERIFY_PARAMS, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } + if (!checkHex(_secretShare, SECRET_SHARE_NUM_BYTES)) { + throw SGXException(INVALID_DKG_VERIFY_SS_HEX, + string(__FUNCTION__) + ":Invalid Secret share"); + } + if (_publicShares.length() != (uint64_t)256 * _t) { + throw SGXException(INVALID_DKG_VERIFY_PUBSHARES_LENGTH, + string(__FUNCTION__) + + ":Invalid length of public shares"); + } + + shared_ptr encryptedKeyHex_ptr = readFromDb(_ethKeyName); + + if (verifyShares(_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::dkgVerificationImpl(const string &_publicShares, const string &_ethKeyName, - const string &_secretShare, int _t, int _n, int _index) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - result["result"] = false; - - try { - if (!checkECDSAKeyName(_ethKeyName)) { - throw SGXException(INVALID_DKG_VERIFY_ECDSA_KEY_NAME, - string(__FUNCTION__) + ":Invalid ECDSA key name"); - } - if (!check_n_t(_t, _n) || _index >= _n || _index < 0) { - throw SGXException(INVALID_DKG_VERIFY_PARAMS, - string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - if (!checkHex(_secretShare, SECRET_SHARE_NUM_BYTES)) { - throw SGXException(INVALID_DKG_VERIFY_SS_HEX, - string(__FUNCTION__) + ":Invalid Secret share"); - } - if (_publicShares.length() != (uint64_t) 256 * _t) { - throw SGXException(INVALID_DKG_VERIFY_PUBSHARES_LENGTH, - string(__FUNCTION__) + ":Invalid length of public shares"); - } - - shared_ptr encryptedKeyHex_ptr = readFromDb(_ethKeyName); - - if (verifyShares(_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::createBLSPrivateKeyImpl(const string &_blsKeyName, + const string &_ethKeyName, + const string &_polyName, + const string &_secretShare, + int _t, int _n) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (_secretShare.length() != (uint64_t)_n * 192) { + throw SGXException(INVALID_CREATE_BLS_KEY_SECRET_SHARES_LENGTH, + string(__FUNCTION__) + ":Invalid secret share length"); + } + if (!checkECDSAKeyName(_ethKeyName)) { + throw SGXException(INVALID_CREATE_BLS_ECDSA_KEY_NAME, + string(__FUNCTION__) + ":Invalid ECDSA key name"); + } + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_CREATE_BLS_POLY_NAME, + string(__FUNCTION__) + ":Invalid polynomial name"); + } + if (!checkName(_blsKeyName, "BLS_KEY")) { + throw SGXException(INVALID_CREATE_BLS_KEY_NAME, + string(__FUNCTION__) + ":Invalid BLS key name"); + } + if (!check_n_t(_t, _n)) { + throw SGXException(INVALID_CREATE_BLS_DKG_PARAMS, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } + vector sshares_vect; + + shared_ptr 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 "); + } else { + throw SGXException(INVALID_CREATE_BLS_SHARE, + string(__FUNCTION__) + + ":Error while creating BLS key share"); + } + + 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; + LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName); + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result); } Json::Value -SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string &_ethKeyName, const string &_polyName, - const string &_secretShare, int _t, int _n) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - try { - if (_secretShare.length() != (uint64_t) _n * 192) { - throw SGXException(INVALID_CREATE_BLS_KEY_SECRET_SHARES_LENGTH, - string(__FUNCTION__) + ":Invalid secret share length"); - } - if (!checkECDSAKeyName(_ethKeyName)) { - throw SGXException(INVALID_CREATE_BLS_ECDSA_KEY_NAME, - string(__FUNCTION__) + ":Invalid ECDSA key name"); - } - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_CREATE_BLS_POLY_NAME, string(__FUNCTION__) + - ":Invalid polynomial name"); - } - if (!checkName(_blsKeyName, "BLS_KEY")) { - throw SGXException(INVALID_CREATE_BLS_KEY_NAME, string(__FUNCTION__) + - ":Invalid BLS key name"); - } - if (!check_n_t(_t, _n)) { - throw SGXException(INVALID_CREATE_BLS_DKG_PARAMS, - string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - vector sshares_vect; - - shared_ptr 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 "); - } else { - throw SGXException(INVALID_CREATE_BLS_SHARE, - string(__FUNCTION__) + ":Error while creating BLS key share"); - } - - 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; - LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName); - - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result); -} +SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (!checkName(_blsKeyName, "BLS_KEY")) { + throw SGXException(INVALID_GET_BLS_PUBKEY_NAME, + string(__FUNCTION__) + ":Invalid BLSKey name"); + } + shared_ptr encryptedKeyHex_ptr = readFromDb(_blsKeyName); + + vector public_key_vect = getBLSPubKey(encryptedKeyHex_ptr->c_str()); + for (uint8_t i = 0; i < 4; i++) { + result["blsPublicKeyShare"][i] = public_key_vect.at(i); + } + } + HANDLE_SGX_EXCEPTION(result) -Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - try { - if (!checkName(_blsKeyName, "BLS_KEY")) { - throw SGXException(INVALID_GET_BLS_PUBKEY_NAME, - string(__FUNCTION__) + ":Invalid BLSKey name"); - } - shared_ptr encryptedKeyHex_ptr = readFromDb(_blsKeyName); - - vector public_key_vect = getBLSPubKey(encryptedKeyHex_ptr->c_str()); - for (uint8_t i = 0; i < 4; i++) { - result["blsPublicKeyShare"][i] = public_key_vect.at(i); - } - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } -Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value &publicShares, int t, int n) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - try { - if (!check_n_t(t, n)) { - throw SGXException(INVALID_DKG_CALCULATE_ALL_PARAMS, - string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - - if (!publicShares.isArray()) { - throw SGXException(INVALID_DKG_CALCULATE_ALL_PUBSHARES, - string(__FUNCTION__) + ":Invalid public shares format"); - } - - if (publicShares.size() != (uint64_t) n) { - throw SGXException(INVALID_DKG_CALCULATE_ALL_PUBSHARES_SIZE, - string(__FUNCTION__) + ":Invalid length of public shares"); - } - - for (int i = 0; i < n; ++i) { - if (!publicShares[i].isString()) { - throw SGXException(INVALID_DKG_CALCULATE_ALL_PUBSHARES_STRING, - string(__FUNCTION__) + ":Invalid public shares string"); - } - - if (publicShares[i].asString().length() != (uint64_t) 256 * t) { - throw SGXException(INVALID_DKG_CALCULATE_ALL_STRING_PUBSHARES_SLENGTH, - string(__FUNCTION__) + ";Invalid length of public shares parts"); - } - } - - vector public_shares(n); - for (int i = 0; i < n; ++i) { - public_shares[i] = publicShares[i].asString(); - } - - vector public_keys = calculateAllBlsPublicKeys(public_shares); - - if (public_keys.size() != (uint64_t) n) { - throw SGXException(INVALID_DKG_CALCULATE_ALL_STRING_PUBKEYS_SIZE, - string(__FUNCTION__) + ":Invalid pubkeys array size"); - } - - for (int i = 0; i < n; ++i) { - result["publicKeys"][i] = public_keys[i]; - } - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result); +Json::Value +SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value &publicShares, + int t, int n) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (!check_n_t(t, n)) { + throw SGXException(INVALID_DKG_CALCULATE_ALL_PARAMS, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } + + if (!publicShares.isArray()) { + throw SGXException(INVALID_DKG_CALCULATE_ALL_PUBSHARES, + string(__FUNCTION__) + + ":Invalid public shares format"); + } + + if (publicShares.size() != (uint64_t)n) { + throw SGXException(INVALID_DKG_CALCULATE_ALL_PUBSHARES_SIZE, + string(__FUNCTION__) + + ":Invalid length of public shares"); + } + + for (int i = 0; i < n; ++i) { + if (!publicShares[i].isString()) { + throw SGXException(INVALID_DKG_CALCULATE_ALL_PUBSHARES_STRING, + string(__FUNCTION__) + + ":Invalid public shares string"); + } + + if (publicShares[i].asString().length() != (uint64_t)256 * t) { + throw SGXException(INVALID_DKG_CALCULATE_ALL_STRING_PUBSHARES_SLENGTH, + string(__FUNCTION__) + + ";Invalid length of public shares parts"); + } + } + + vector public_shares(n); + for (int i = 0; i < n; ++i) { + public_shares[i] = publicShares[i].asString(); + } + + vector public_keys = calculateAllBlsPublicKeys(public_shares); + + if (public_keys.size() != (uint64_t)n) { + throw SGXException(INVALID_DKG_CALCULATE_ALL_STRING_PUBKEYS_SIZE, + string(__FUNCTION__) + ":Invalid pubkeys array size"); + } + + for (int i = 0; i < n; ++i) { + result["publicKeys"][i] = public_keys[i]; + } + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result); } -Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _t, int _n, int _ind) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - try { - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_COMPLAINT_RESPONSE_POLY_NAME, - string(__FUNCTION__) + ":Invalid polynomial name"); - } - - string shareG2_name = "shareG2_" + _polyName + "_" + to_string(_ind) + ":"; - string DHKey = decryptDHKey(_polyName, _ind); - - shared_ptr shareG2_ptr = readFromDb(shareG2_name); - CHECK_STATE(shareG2_ptr); - result["share*G2"] = *shareG2_ptr; - result["dhKey"] = DHKey; - - shared_ptr encrPoly = readFromDb(_polyName); - - auto verificationVectorMult = getVerificationVectorMult(encrPoly->c_str(), _t, _n, _ind); - - for (int i = 0; i < _t; i++) { - vector 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; - LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName); - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result); +Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, + int _t, int _n, int _ind) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_COMPLAINT_RESPONSE_POLY_NAME, + string(__FUNCTION__) + ":Invalid polynomial name"); + } + + string shareG2_name = "shareG2_" + _polyName + "_" + to_string(_ind) + ":"; + string DHKey = decryptDHKey(_polyName, _ind); + + shared_ptr shareG2_ptr = readFromDb(shareG2_name); + CHECK_STATE(shareG2_ptr); + result["share*G2"] = *shareG2_ptr; + result["dhKey"] = DHKey; + + shared_ptr encrPoly = readFromDb(_polyName); + + auto verificationVectorMult = + getVerificationVectorMult(encrPoly->c_str(), _t, _n, _ind); + + for (int i = 0; i < _t; i++) { + vector 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; + LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName); + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result); } Json::Value SGXWalletServer::multG2Impl(const string &_x) { - COUNT_STATISTICS - INIT_RESULT(result) + COUNT_STATISTICS + INIT_RESULT(result) - try { - auto xG2_vect = mult_G2(_x); - for (uint8_t i = 0; i < 4; i++) { - result["x*G2"][i] = xG2_vect.at(i); - } - } HANDLE_SGX_EXCEPTION(result) + try { + auto xG2_vect = mult_G2(_x); + for (uint8_t i = 0; i < 4; i++) { + result["x*G2"][i] = xG2_vect.at(i); + } + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } Json::Value SGXWalletServer::isPolyExistsImpl(const string &_polyName) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) - result["IsExist"] = false; + result["IsExist"] = false; - try { - shared_ptr poly_str_ptr = LevelDB::getLevelDb()->readString(_polyName); + try { + shared_ptr poly_str_ptr = + LevelDB::getLevelDb()->readString(_polyName); - if (poly_str_ptr != nullptr) { - result["IsExist"] = true; - } - } HANDLE_SGX_EXCEPTION(result) + if (poly_str_ptr != nullptr) { + result["IsExist"] = true; + } + } + HANDLE_SGX_EXCEPTION(result) - RETURN_SUCCESS(result); + RETURN_SUCCESS(result); } -Json::Value SGXWalletServer::getServerStatusImpl() { - COUNT_STATISTICS - INIT_RESULT(result) - RETURN_SUCCESS(result) -} +Json::Value SGXWalletServer::getServerStatusImpl(){ + COUNT_STATISTICS INIT_RESULT(result) RETURN_SUCCESS(result)} Json::Value SGXWalletServer::getServerVersionImpl() { - COUNT_STATISTICS - INIT_RESULT(result) - result["version"] = TOSTRING(SGXWALLET_VERSION); - RETURN_SUCCESS(result) + COUNT_STATISTICS + INIT_RESULT(result) + result["version"] = TOSTRING(SGXWALLET_VERSION); + RETURN_SUCCESS(result) } Json::Value SGXWalletServer::deleteBlsKeyImpl(const string &name) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - result["deleted"] = false; - try { - if (!checkName(name, "BLS_KEY")) { - throw SGXException(DELETE_BLS_KEY_INVALID_KEYNAME, string(__FUNCTION__) + ":Invalid BLSKey name format"); - } - shared_ptr bls_ptr = LevelDB::getLevelDb()->readString(name); - - if (bls_ptr != nullptr) { - LevelDB::getLevelDb()->deleteKey(name); - result["deleted"] = true; - } else { - auto error_msg = "BLS key not found: " + name; - throw SGXException(DELETE_BLS_KEY_NOT_FOUND, string(__FUNCTION__) + ":" + error_msg.c_str()); - } - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result) + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + result["deleted"] = false; + try { + if (!checkName(name, "BLS_KEY")) { + throw SGXException(DELETE_BLS_KEY_INVALID_KEYNAME, + string(__FUNCTION__) + ":Invalid BLSKey name format"); + } + shared_ptr bls_ptr = LevelDB::getLevelDb()->readString(name); + + if (bls_ptr != nullptr) { + LevelDB::getLevelDb()->deleteKey(name); + result["deleted"] = true; + } else { + auto error_msg = "BLS key not found: " + name; + throw SGXException(DELETE_BLS_KEY_NOT_FOUND, + string(__FUNCTION__) + ":" + error_msg.c_str()); + } + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } -Json::Value -SGXWalletServer::getSecretShareV2Impl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result); - result["secretShare"] = ""; - - try { - if (_pubKeys.size() != (uint64_t) _n) { - throw SGXException(INVALID_DKG_GETSS_V2_PUBKEY_COUNT, - string(__FUNCTION__) + ":Invalid number of public keys"); - } - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_DKG_GETSS_V2_POLY_NAME, - string(__FUNCTION__) + ":Invalid polynomial name"); - } - if (!check_n_t(_t, _n)) { - throw SGXException(INVALID_DKG_GETSS_V2_PUBKEY_COUNT, - string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - - shared_ptr encrPoly = readFromDb(_polyName); - - vector pubKeysStrs; - for (int i = 0; i < _n; i++) { - if (!checkHex(_pubKeys[i].asString(), 64)) { - throw SGXException(INVALID_DKG_GETSS_V2_PUBKEY_HEX, - string(__FUNCTION__) + ":Invalid public key"); - } - pubKeysStrs.push_back(_pubKeys[i].asString()); - } - - string secret_share_name = "encryptedSecretShare:" + _polyName; - shared_ptr 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::getSecretShareV2Impl(const string &_polyName, + const Json::Value &_pubKeys, + int _t, int _n) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result); + result["secretShare"] = ""; + + try { + if (_pubKeys.size() != (uint64_t)_n) { + throw SGXException(INVALID_DKG_GETSS_V2_PUBKEY_COUNT, + string(__FUNCTION__) + + ":Invalid number of public keys"); + } + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_DKG_GETSS_V2_POLY_NAME, + string(__FUNCTION__) + ":Invalid polynomial name"); + } + if (!check_n_t(_t, _n)) { + throw SGXException(INVALID_DKG_GETSS_V2_PUBKEY_COUNT, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } + + shared_ptr encrPoly = readFromDb(_polyName); + + vector pubKeysStrs; + for (int i = 0; i < _n; i++) { + if (!checkHex(_pubKeys[i].asString(), 64)) { + throw SGXException(INVALID_DKG_GETSS_V2_PUBKEY_HEX, + string(__FUNCTION__) + ":Invalid public key"); + } + pubKeysStrs.push_back(_pubKeys[i].asString()); + } + + string secret_share_name = "encryptedSecretShare:" + _polyName; + shared_ptr 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) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - result["result"] = false; - - try { - if (!checkECDSAKeyName(_ethKeyName)) { - throw SGXException(INVALID_DKG_VV_V2_ECDSA_KEY_NAME, - string(__FUNCTION__) + ":Invalid ECDSA key name"); - } - if (!check_n_t(_t, _n) || _index >= _n || _index < 0) { - throw SGXException(INVALID_DKG_VV_V2_PARAMS, - string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - if (!checkHex(_secretShare, SECRET_SHARE_NUM_BYTES)) { - throw SGXException(INVALID_DKG_VV_V2_SS_HEX, - string(__FUNCTION__) + ":Invalid Secret share"); - } - if (_publicShares.length() != (uint64_t) 256 * _t) { - throw SGXException(INVALID_DKG_VV_V2_SS_COUNT, - string(__FUNCTION__) + ":Invalid count of public shares"); - } - - shared_ptr 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::dkgVerificationV2Impl(const string &_publicShares, + const string &_ethKeyName, + const string &_secretShare, + int _t, int _n, int _index) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + result["result"] = false; + + try { + if (!checkECDSAKeyName(_ethKeyName)) { + throw SGXException(INVALID_DKG_VV_V2_ECDSA_KEY_NAME, + string(__FUNCTION__) + ":Invalid ECDSA key name"); + } + if (!check_n_t(_t, _n) || _index >= _n || _index < 0) { + throw SGXException(INVALID_DKG_VV_V2_PARAMS, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } + if (!checkHex(_secretShare, SECRET_SHARE_NUM_BYTES)) { + throw SGXException(INVALID_DKG_VV_V2_SS_HEX, + string(__FUNCTION__) + ":Invalid Secret share"); + } + if (_publicShares.length() != (uint64_t)256 * _t) { + throw SGXException(INVALID_DKG_VV_V2_SS_COUNT, + string(__FUNCTION__) + + ":Invalid count of public shares"); + } + + shared_ptr 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::createBLSPrivateKeyV2Impl( + const string &_blsKeyName, const string &_ethKeyName, + const string &_polyName, const string &_secretShare, int _t, int _n) { + COUNT_STATISTICS + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (_secretShare.length() != (uint64_t)_n * 192) { + throw SGXException(INVALID_CREATE_BLS_KEY_SECRET_SHARES_LENGTH, + string(__FUNCTION__) + ":Invalid secret share length"); + } + if (!checkECDSAKeyName(_ethKeyName)) { + throw SGXException(INVALID_CREATE_BLS_ECDSA_KEY_NAME, + string(__FUNCTION__) + ":Invalid ECDSA key name"); + } + if (!checkName(_polyName, "POLY")) { + throw SGXException(INVALID_CREATE_BLS_POLY_NAME, + string(__FUNCTION__) + ":Invalid polynomial name"); + } + if (!checkName(_blsKeyName, "BLS_KEY")) { + throw SGXException(INVALID_CREATE_BLS_KEY_NAME, + string(__FUNCTION__) + ":Invalid BLS key name"); + } + if (!check_n_t(_t, _n)) { + throw SGXException(INVALID_CREATE_BLS_DKG_PARAMS, + string(__FUNCTION__) + + ":Invalid DKG parameters: n or t "); + } + vector sshares_vect; + + shared_ptr encryptedKeyHex_ptr = readFromDb(_ethKeyName); + + CHECK_STATE(encryptedKeyHex_ptr); + + bool res = createBLSShareV2(_blsKeyName, _secretShare.c_str(), + encryptedKeyHex_ptr->c_str()); + if (res) { + spdlog::info("BLS KEY SHARE CREATED "); + } else { + throw SGXException(INVALID_CREATE_BLS_SHARE, + string(__FUNCTION__) + + ":Error while creating BLS key share"); + } + + 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; + LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName); + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result); } Json::Value -SGXWalletServer::createBLSPrivateKeyV2Impl(const string &_blsKeyName, const string &_ethKeyName, - const string &_polyName, - const string &_secretShare, int _t, int _n) { - COUNT_STATISTICS - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) - - try { - if (_secretShare.length() != (uint64_t) _n * 192) { - throw SGXException(INVALID_CREATE_BLS_KEY_SECRET_SHARES_LENGTH, - string(__FUNCTION__) + ":Invalid secret share length"); - } - if (!checkECDSAKeyName(_ethKeyName)) { - throw SGXException(INVALID_CREATE_BLS_ECDSA_KEY_NAME, - string(__FUNCTION__) + ":Invalid ECDSA key name"); - } - if (!checkName(_polyName, "POLY")) { - throw SGXException(INVALID_CREATE_BLS_POLY_NAME, string(__FUNCTION__) + - ":Invalid polynomial name"); - } - if (!checkName(_blsKeyName, "BLS_KEY")) { - throw SGXException(INVALID_CREATE_BLS_KEY_NAME, string(__FUNCTION__) + - ":Invalid BLS key name"); - } - if (!check_n_t(_t, _n)) { - throw SGXException(INVALID_CREATE_BLS_DKG_PARAMS, - string(__FUNCTION__) + ":Invalid DKG parameters: n or t "); - } - vector sshares_vect; - - shared_ptr encryptedKeyHex_ptr = readFromDb(_ethKeyName); - - CHECK_STATE(encryptedKeyHex_ptr); - - bool res = createBLSShareV2(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str()); - if (res) { - spdlog::info("BLS KEY SHARE CREATED "); - } else { - throw SGXException(INVALID_CREATE_BLS_SHARE, - string(__FUNCTION__) + ":Error while creating BLS key share"); - } - - 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; - LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName); - - } HANDLE_SGX_EXCEPTION(result) - - RETURN_SUCCESS(result); +SGXWalletServer::generateBLSPrivateKeyImpl(const string &blsKeyName) { + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (!checkName(blsKeyName, "BLS_KEY")) { + throw SGXException(GENERATE_BLS_KEY_INVALID_NAME, + string(__FUNCTION__) + ":Invalid BLSKey name"); + } + + bool res = generateBLSPrivateKeyAggegated(blsKeyName.c_str()); + if (res) { + spdlog::info("BLS AGGREGATED KEY CREATED "); + } else { + throw SGXException(INVALID_CREATE_BLS_AGGREGATED_KEY, + string(__FUNCTION__) + + ":Error while creating BLS aggregated key"); + } + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result); +} + +Json::Value SGXWalletServer::getDecryptionSharesImpl( + const std::string &blsKeyName, const Json::Value &publicDecryptionValues) { + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) + + try { + if (!checkName(blsKeyName, "BLS_KEY")) { + throw SGXException(BLS_SIGN_INVALID_KS_NAME, + string(__FUNCTION__) + ":Invalid BLSKey name"); + } + + if (!publicDecryptionValues.isArray()) { + throw SGXException(INVALID_DECRYPTION_VALUE_FORMAT, + string(__FUNCTION__) + + ":Public decryption values should be an array"); + } + + for (int i = 0; i < publicDecryptionValues.size(); ++i) { + std::string publicDecryptionValue = publicDecryptionValues[i].asString(); + if (publicDecryptionValue.length() < 7 || + publicDecryptionValue.length() > 78 * 4) { + throw SGXException(INVALID_DECRYPTION_VALUE_FORMAT, + string(__FUNCTION__) + + ":Invalid publicDecryptionValue format"); + } + + shared_ptr encryptedKeyHex_ptr = readFromDb(blsKeyName); + + vector decryptionValueVector = calculateDecryptionShare( + encryptedKeyHex_ptr->c_str(), publicDecryptionValue); + for (uint8_t j = 0; j < 4; ++j) { + result["decryptionShares"][i][j] = decryptionValueVector.at(j); + } + } + } + HANDLE_SGX_EXCEPTION(result) + + RETURN_SUCCESS(result) } -Json::Value SGXWalletServer::getDecryptionSharesImpl(const std::string& blsKeyName, const Json::Value& publicDecryptionValues) { - spdlog::info("Entering {}", __FUNCTION__); - INIT_RESULT(result) +Json::Value SGXWalletServer::popProveImpl(const std::string &blsKeyName) { + spdlog::info("Entering {}", __FUNCTION__); + INIT_RESULT(result) - try { - if (!checkName(blsKeyName, "BLS_KEY")) { - throw SGXException(BLS_SIGN_INVALID_KS_NAME, string(__FUNCTION__) + ":Invalid BLSKey name"); - } + vector prove(BUF_LEN, 0); - if (!publicDecryptionValues.isArray()) { - throw SGXException(INVALID_DECRYPTION_VALUE_FORMAT, - string(__FUNCTION__) + ":Public decryption values should be an array"); - } + try { + if (!checkName(blsKeyName, "BLS_KEY")) { + throw SGXException(POP_PROVE_INVALID_KEY_NAME, + string(__FUNCTION__) + ":Invalid BLSKey name"); + } - for (int i = 0; i < publicDecryptionValues.size(); ++i) { - std::string publicDecryptionValue = publicDecryptionValues[i].asString(); - if ( publicDecryptionValue.length() < 7 || publicDecryptionValue.length() > 78 * 4 ) { - throw SGXException(INVALID_DECRYPTION_VALUE_FORMAT, string(__FUNCTION__) + ":Invalid publicDecryptionValue format"); - } + shared_ptr encryptedKeyHexPtr = readFromDb(blsKeyName); - shared_ptr encryptedKeyHex_ptr = readFromDb(blsKeyName); + if (!popProveSGX(encryptedKeyHexPtr->c_str(), prove.data())) { + throw SGXException(COULD_NOT_CREATE_POP_PROVE, + ":Could not create popProve "); + } + } + HANDLE_SGX_EXCEPTION(result) - vector decryptionValueVector = calculateDecryptionShare(encryptedKeyHex_ptr->c_str(), publicDecryptionValue); - for (uint8_t j = 0; j < 4; ++j) { - result["decryptionShares"][i][j] = decryptionValueVector.at(j); - } - } - } HANDLE_SGX_EXCEPTION(result) + result["popProve"] = string(prove.data()); - RETURN_SUCCESS(result) + RETURN_SUCCESS(result) } Json::Value SGXWalletServer::generateDKGPoly(const string &_polyName, int _t) { - return generateDKGPolyImpl(_polyName, _t); + return generateDKGPolyImpl(_polyName, _t); } -Json::Value SGXWalletServer::getVerificationVector(const string &_polynomeName, int _t) { - return getVerificationVectorImpl(_polynomeName, _t); +Json::Value SGXWalletServer::getVerificationVector(const string &_polynomeName, + int _t) { + return getVerificationVectorImpl(_polynomeName, _t); } -Json::Value SGXWalletServer::getSecretShare(const string &_polyName, const Json::Value &_publicKeys, int t, int n) { - return getSecretShareImpl(_polyName, _publicKeys, t, n); +Json::Value SGXWalletServer::getSecretShare(const string &_polyName, + const Json::Value &_publicKeys, + int t, int n) { + return getSecretShareImpl(_polyName, _publicKeys, t, n); } -Json::Value -SGXWalletServer::dkgVerification(const string &_publicShares, const string ðKeyName, const string &SecretShare, - int t, - int n, int index) { - return dkgVerificationImpl(_publicShares, ethKeyName, SecretShare, t, n, index); +Json::Value SGXWalletServer::dkgVerification(const string &_publicShares, + const string ðKeyName, + const string &SecretShare, int t, + int n, int index) { + return dkgVerificationImpl(_publicShares, ethKeyName, SecretShare, t, n, + index); } -Json::Value -SGXWalletServer::createBLSPrivateKey(const string &blsKeyName, const string ðKeyName, const string &polyName, - const string &SecretShare, int t, int n) { - return createBLSPrivateKeyImpl(blsKeyName, ethKeyName, polyName, SecretShare, t, n); +Json::Value SGXWalletServer::createBLSPrivateKey(const string &blsKeyName, + const string ðKeyName, + const string &polyName, + const string &SecretShare, + int t, int n) { + return createBLSPrivateKeyImpl(blsKeyName, ethKeyName, polyName, SecretShare, + t, n); } Json::Value SGXWalletServer::getBLSPublicKeyShare(const string &blsKeyName) { - return getBLSPublicKeyShareImpl(blsKeyName); + return getBLSPublicKeyShareImpl(blsKeyName); } -Json::Value SGXWalletServer::calculateAllBLSPublicKeys(const Json::Value &publicShares, int t, int n) { - return calculateAllBLSPublicKeysImpl(publicShares, t, 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::importECDSAKey(const std::string &keyShare, + const std::string &keyShareName) { + return importECDSAKeyImpl(keyShare, keyShareName); } Json::Value SGXWalletServer::generateECDSAKey() { - return generateECDSAKeyImpl(); + return generateECDSAKeyImpl(); } Json::Value SGXWalletServer::getPublicECDSAKey(const string &_keyName) { - return getPublicECDSAKeyImpl(_keyName); + return getPublicECDSAKeyImpl(_keyName); } -Json::Value SGXWalletServer::ecdsaSignMessageHash(int _base, const string &_keyShareName, const string &_messageHash) { - return ecdsaSignMessageHashImpl(_base, _keyShareName, _messageHash); +Json::Value SGXWalletServer::ecdsaSignMessageHash(int _base, + const string &_keyShareName, + const string &_messageHash) { + return ecdsaSignMessageHashImpl(_base, _keyShareName, _messageHash); } -Json::Value -SGXWalletServer::importBLSKeyShare(const string &_keyShare, const string &_keyShareName) { - return importBLSKeyShareImpl(_keyShare, _keyShareName); +Json::Value SGXWalletServer::importBLSKeyShare(const string &_keyShare, + const string &_keyShareName) { + return importBLSKeyShareImpl(_keyShare, _keyShareName); } -Json::Value -SGXWalletServer::blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n) { - return blsSignMessageHashImpl(_keyShareName, _messageHash, _t, _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 t, int n, int ind) { - return complaintResponseImpl(polyName, t, n, 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) { - return multG2Impl(x); -} +Json::Value SGXWalletServer::multG2(const string &x) { return multG2Impl(x); } Json::Value SGXWalletServer::isPolyExists(const string &polyName) { - return isPolyExistsImpl(polyName); + return isPolyExistsImpl(polyName); } -Json::Value SGXWalletServer::getServerStatus() { - return getServerStatusImpl(); -} +Json::Value SGXWalletServer::getServerStatus() { return getServerStatusImpl(); } Json::Value SGXWalletServer::getServerVersion() { - return getServerVersionImpl(); + return getServerVersionImpl(); } Json::Value SGXWalletServer::deleteBlsKey(const string &name) { - return deleteBlsKeyImpl(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::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 ðKeyName, const string &SecretShare, - int t, - int n, int index) { - return dkgVerificationV2Impl(_publicShares, ethKeyName, SecretShare, t, n, index); +Json::Value SGXWalletServer::dkgVerificationV2(const string &_publicShares, + const string ðKeyName, + const string &SecretShare, int t, + int n, int index) { + return dkgVerificationV2Impl(_publicShares, ethKeyName, SecretShare, t, n, + index); } -Json::Value -SGXWalletServer::createBLSPrivateKeyV2(const string &blsKeyName, const string ðKeyName, const string &polyName, - const string &SecretShare, int t, int n) { - return createBLSPrivateKeyV2Impl(blsKeyName, ethKeyName, polyName, SecretShare, t, n); +Json::Value SGXWalletServer::createBLSPrivateKeyV2(const string &blsKeyName, + const string ðKeyName, + const string &polyName, + const string &SecretShare, + int t, int n) { + return createBLSPrivateKeyV2Impl(blsKeyName, ethKeyName, polyName, + SecretShare, t, n); } -Json::Value SGXWalletServer::getDecryptionShares(const std::string& blsKeyName, const Json::Value& publicDecryptionValues) { - return getDecryptionSharesImpl(blsKeyName, publicDecryptionValues); +Json::Value SGXWalletServer::generateBLSPrivateKey(const string &blsKeyName) { + return generateBLSPrivateKeyImpl(blsKeyName); } -shared_ptr SGXWalletServer::readFromDb(const string &name, const string &prefix) { - auto dataStr = checkDataFromDb(prefix + name); +Json::Value SGXWalletServer::getDecryptionShares( + const std::string &blsKeyName, const Json::Value &publicDecryptionValues) { + return getDecryptionSharesImpl(blsKeyName, publicDecryptionValues); +} - if (dataStr == nullptr) { - throw SGXException(KEY_SHARE_DOES_NOT_EXIST, string(__FUNCTION__) + ":Data with this name does not exist: " - + prefix + name); - } +Json::Value SGXWalletServer::popProve(const std::string &blsKeyName) { + return popProveImpl(blsKeyName); +} + +shared_ptr SGXWalletServer::readFromDb(const string &name, + const string &prefix) { + auto dataStr = checkDataFromDb(prefix + name); + + if (dataStr == nullptr) { + throw SGXException(KEY_SHARE_DOES_NOT_EXIST, + string(__FUNCTION__) + + ":Data with this name does not exist: " + prefix + + name); + } - return dataStr; + return dataStr; } -shared_ptr SGXWalletServer::checkDataFromDb(const string &name, const string &prefix) { - auto dataStr = LevelDB::getLevelDb()->readString(prefix + name); +shared_ptr SGXWalletServer::checkDataFromDb(const string &name, + const string &prefix) { + auto dataStr = LevelDB::getLevelDb()->readString(prefix + name); - return dataStr; + return dataStr; } -void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_value) { - if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) { - throw SGXException(KEY_SHARE_ALREADY_EXISTS, string(__FUNCTION__) + ":Key share with this name already exists" - + _keyShareName); - } +void SGXWalletServer::writeKeyShare(const string &_keyShareName, + const string &_value) { + if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) { + throw SGXException(KEY_SHARE_ALREADY_EXISTS, + string(__FUNCTION__) + + ":Key share with this name already exists" + + _keyShareName); + } - LevelDB::getLevelDb()->writeString(_keyShareName, _value); + LevelDB::getLevelDb()->writeString(_keyShareName, _value); } void SGXWalletServer::writeDataToDB(const string &name, const string &value) { - if (LevelDB::getLevelDb()->readString(name) != nullptr) { - throw SGXException(KEY_NAME_ALREADY_EXISTS, string(__FUNCTION__) + ":Name already exists" + name); - } - - LevelDB::getLevelDb()->writeString(name, value); + if (LevelDB::getLevelDb()->readString(name) != nullptr) { + throw SGXException(KEY_NAME_ALREADY_EXISTS, + string(__FUNCTION__) + ":Name already exists" + name); + } + + LevelDB::getLevelDb()->writeString(name, value); } diff --git a/SGXWalletServer.h b/SGXWalletServer.h index ac1fe47b..d0bfb271 100644 --- a/SGXWalletServer.h +++ b/SGXWalletServer.h @@ -30,9 +30,9 @@ #define EXTERNC #endif -EXTERNC void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey); - +EXTERNC void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, + int _enterBackupKey); EXTERNC void setOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm); -#endif //SGXWALLET_SGXWALLETSERVER_H +#endif // SGXWALLET_SGXWALLETSERVER_H diff --git a/SGXWalletServer.hpp b/SGXWalletServer.hpp index 99776723..8b1cd185 100644 --- a/SGXWalletServer.hpp +++ b/SGXWalletServer.hpp @@ -24,9 +24,8 @@ #ifndef SGXWALLET_SGXWALLETSERVER_HPP #define SGXWALLET_SGXWALLETSERVER_HPP - -#include "mutex" #include "memory" +#include "mutex" #include @@ -38,152 +37,200 @@ using namespace std; #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) - class SGXWalletServer : public AbstractStubServer { - static shared_ptr server; - static shared_ptr httpServer; + static shared_ptr server; + static shared_ptr httpServer; - static map blsRequests; - static recursive_mutex blsRequestsLock; - static map ecdsaRequests; - static recursive_mutex ecdsaRequestsLock; + static map blsRequests; + static recursive_mutex blsRequestsLock; + static map ecdsaRequests; + static recursive_mutex ecdsaRequestsLock; - static void checkForDuplicate(map &_map, recursive_mutex &_m, const string &_key, - const string &_value); + static void checkForDuplicate(map &_map, recursive_mutex &_m, + const string &_key, const string &_value); public: + static bool verifyCert(string &_certFileName); + + static const char *getVersion() { return TOSTRING(SGXWALLET_VERSION); } + + SGXWalletServer(AbstractServerConnector &_connector, serverVersion_t _type); + + virtual Json::Value importBLSKeyShare(const string &_keyShare, + const string &_keyShareName); - static bool verifyCert(string& _certFileName); + virtual Json::Value blsSignMessageHash(const string &_keyShareName, + const string &_messageHash, int _t, + int _n); - static const char* getVersion() { - return TOSTRING(SGXWALLET_VERSION); - } + virtual Json::Value importECDSAKey(const std::string &keyShare, + const std::string &keyShareName); - SGXWalletServer(AbstractServerConnector &_connector, serverVersion_t _type); + virtual Json::Value generateECDSAKey(); - virtual Json::Value - importBLSKeyShare(const string &_keyShare, const string &_keyShareName); + virtual Json::Value ecdsaSignMessageHash(int _base, + const string &_keyShareName, + const string &_messageHash); - virtual Json::Value - blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n); + virtual Json::Value getPublicECDSAKey(const string &_keyName); - virtual Json::Value importECDSAKey(const std::string& keyShare, - const std::string& keyShareName); + virtual Json::Value generateDKGPoly(const string &_polyName, int _t); - virtual Json::Value generateECDSAKey(); + virtual Json::Value getVerificationVector(const string &_polynomeName, + int _t); - virtual Json::Value - ecdsaSignMessageHash(int _base, const string &_keyShareName, const string &_messageHash); + virtual Json::Value getSecretShare(const string &_polyName, + const Json::Value &_publicKeys, int t, + int n); - virtual Json::Value getPublicECDSAKey(const string &_keyName); + virtual Json::Value dkgVerification(const string &_publicShares, + const string ðKeyName, + const string &SecretShare, int t, int n, + int index); - virtual Json::Value generateDKGPoly(const string &_polyName, int _t); + virtual Json::Value createBLSPrivateKey(const string &blsKeyName, + const string ðKeyName, + const string &polyName, + const string &SecretShare, int t, + int n); - virtual Json::Value getVerificationVector(const string &_polynomeName, int _t); + virtual Json::Value generateBLSPrivateKey(const string &blsKeyName); - virtual Json::Value getSecretShare(const string &_polyName, const Json::Value &_publicKeys, int t, int n); + virtual Json::Value getBLSPublicKeyShare(const string &blsKeyName); - virtual Json::Value - dkgVerification(const string &_publicShares, const string ðKeyName, const string &SecretShare, - int t, int n, int index); + virtual Json::Value calculateAllBLSPublicKeys(const Json::Value &publicShares, + int t, int n); - virtual Json::Value - createBLSPrivateKey(const string &blsKeyName, const string ðKeyName, const string &polyName, - const string &SecretShare, int t, int n); + virtual Json::Value complaintResponse(const string &polyName, int t, int n, + int ind); - virtual Json::Value getBLSPublicKeyShare(const string &blsKeyName); + virtual Json::Value multG2(const string &x); - virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n); + virtual Json::Value isPolyExists(const string &polyName); - virtual Json::Value complaintResponse(const string &polyName, int t, int n, int ind); + virtual Json::Value getServerStatus(); - virtual Json::Value multG2(const string &x); + virtual Json::Value getServerVersion(); - virtual Json::Value isPolyExists(const string &polyName); + virtual Json::Value deleteBlsKey(const std::string &name); - virtual Json::Value getServerStatus(); + virtual Json::Value getSecretShareV2(const string &_polyName, + const Json::Value &_publicKeys, int t, + int n); - virtual Json::Value getServerVersion(); + virtual Json::Value dkgVerificationV2(const string &_publicShares, + const string ðKeyName, + const string &SecretShare, int t, int n, + int index); - virtual Json::Value deleteBlsKey( const std::string& name ); + virtual Json::Value createBLSPrivateKeyV2(const std::string &blsKeyName, + const std::string ðKeyName, + const std::string &polyName, + const std::string &SecretShare, + int t, int n); - virtual Json::Value getSecretShareV2(const string &_polyName, const Json::Value &_publicKeys, int t, int n); + virtual Json::Value + getDecryptionShares(const std::string &blsKeyName, + const Json::Value &publicDecryptionValues); - virtual Json::Value dkgVerificationV2(const string &_publicShares, const string ðKeyName, const string &SecretShare, int t, int n, int index); + virtual Json::Value popProve(const std::string &blsKeyName); - virtual Json::Value createBLSPrivateKeyV2(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n); + static shared_ptr readFromDb(const string &name, + const string &prefix = ""); - virtual Json::Value getDecryptionShares(const std::string& KeyName, const Json::Value& publicDecryptionValues); + static shared_ptr checkDataFromDb(const string &name, + const string &prefix = ""); - static shared_ptr readFromDb(const string &name, const string &prefix = ""); + static void writeDataToDB(const string &Name, const string &value); - static shared_ptr checkDataFromDb(const string &name, const string &prefix = ""); + static void writeKeyShare(const string &_keyShareName, const string &_value); - static void writeDataToDB(const string &Name, const string &value); + static Json::Value importBLSKeyShareImpl(const string &_keyShare, + const string &_keyShareName); - static void writeKeyShare(const string &_keyShareName, const string &_value); + static Json::Value blsSignMessageHashImpl(const string &_keyShareName, + const string &_messageHash, int t, + int n); - static Json::Value - importBLSKeyShareImpl(const string &_keyShare, const string &_keyShareName); + static Json::Value importECDSAKeyImpl(const string &_keyShare, + const string &_keyShareName); - static Json::Value - blsSignMessageHashImpl(const string &_keyShareName, const string &_messageHash, int t, int n); + static Json::Value generateECDSAKeyImpl(); - static Json::Value importECDSAKeyImpl(const string &_keyShare, const string &_keyShareName); + static Json::Value ecdsaSignMessageHashImpl(int _base, const string &keyName, + const string &_messageHash); - static Json::Value generateECDSAKeyImpl(); + static Json::Value getPublicECDSAKeyImpl(const string &_keyName); - static Json::Value ecdsaSignMessageHashImpl(int _base, const string &keyName, const string &_messageHash); + static Json::Value generateDKGPolyImpl(const string &_polyName, int _t); - static Json::Value getPublicECDSAKeyImpl(const string &_keyName); + static Json::Value getVerificationVectorImpl(const string &_polyName, int _t); - static Json::Value generateDKGPolyImpl(const string &_polyName, int _t); + static Json::Value getSecretShareImpl(const string &_polyName, + const Json::Value &_pubKeys, int _t, + int _n); - static Json::Value getVerificationVectorImpl(const string &_polyName, int _t); + static Json::Value dkgVerificationImpl(const string &_publicShares, + const string &_ethKeyName, + const string &_secretShare, int _t, + int _n, int _index); - static Json::Value getSecretShareImpl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n); + static Json::Value createBLSPrivateKeyImpl(const string &_blsKeyName, + const string &_ethKeyName, + const string &_polyName, + const string &_secretShare, int _t, + int _n); - static Json::Value - dkgVerificationImpl(const string &_publicShares, const string &_ethKeyName, const string &_secretShare, - int _t, int _n, int _index); + static Json::Value getBLSPublicKeyShareImpl(const string &_blsKeyName); - static Json::Value - createBLSPrivateKeyImpl(const string &_blsKeyName, const string &_ethKeyName, const string &_polyName, - const string &_secretShare, int _t, int _n); + static Json::Value + calculateAllBLSPublicKeysImpl(const Json::Value &publicShares, int t, int n); - static Json::Value getBLSPublicKeyShareImpl(const string &_blsKeyName); + static Json::Value complaintResponseImpl(const string &_polyName, int t, + int n, int _ind); - static Json::Value calculateAllBLSPublicKeysImpl(const Json::Value& publicShares, int t, int n); + static Json::Value multG2Impl(const string &_x); - static Json::Value complaintResponseImpl(const string &_polyName, int t, int n, int _ind); + static Json::Value isPolyExistsImpl(const string &_polyName); - static Json::Value multG2Impl(const string &_x); + static Json::Value getServerStatusImpl(); - static Json::Value isPolyExistsImpl(const string &_polyName); + static Json::Value getServerVersionImpl(); - static Json::Value getServerStatusImpl(); + static Json::Value deleteBlsKeyImpl(const std::string &name); - static Json::Value getServerVersionImpl(); + static Json::Value getSecretShareV2Impl(const string &_polyName, + const Json::Value &_pubKeys, int _t, + int _n); - static Json::Value deleteBlsKeyImpl(const std::string& name); + static Json::Value dkgVerificationV2Impl(const string &_publicShares, + const string &_ethKeyName, + const string &_secretShare, int _t, + int _n, int _index); - static Json::Value getSecretShareV2Impl(const string &_polyName, const Json::Value &_pubKeys, int _t, int _n); + static Json::Value createBLSPrivateKeyV2Impl(const std::string &blsKeyName, + const std::string ðKeyName, + const std::string &polyName, + const std::string &SecretShare, + int t, int n); - static Json::Value dkgVerificationV2Impl(const string &_publicShares, const string &_ethKeyName, const string &_secretShare, int _t, int _n, int _index); + static Json::Value generateBLSPrivateKeyImpl(const string &blsKeyName); - static Json::Value createBLSPrivateKeyV2Impl(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n); + static Json::Value + getDecryptionSharesImpl(const std::string &KeyName, + const Json::Value &publicDecryptionValues); - static Json::Value getDecryptionSharesImpl(const std::string& KeyName, const Json::Value& publicDecryptionValues); + static Json::Value popProveImpl(const std::string &blsKeyName); - static void printDB(); + static void printDB(); - static void initHttpServer(); + static void initHttpServer(); - static void initHttpsServer(bool _checkCerts); + static void initHttpsServer(bool _checkCerts); - static int exitServer(); + static int exitServer(); - static void createCertsIfNeeded(); + static void createCertsIfNeeded(); }; -#endif //SGXWALLET_SGXWALLETSERVER_HPP +#endif // SGXWALLET_SGXWALLETSERVER_HPP diff --git a/ServerDataChecker.cpp b/ServerDataChecker.cpp index 575a7803..ca90ebd7 100644 --- a/ServerDataChecker.cpp +++ b/ServerDataChecker.cpp @@ -21,47 +21,49 @@ @date 2019 */ -#include #include "ServerDataChecker.h" #include +#include #include -#include "third_party/spdlog/spdlog.h" #include "common.h" +#include "third_party/spdlog/spdlog.h" -vector SplitString(const string& str, const string& delim = ":"){ - vector tokens; - size_t prev = 0, pos = 0; - do { - pos = str.find(delim, prev); - if (pos == string::npos) pos = str.length(); - string token = str.substr(prev, pos-prev); - if (!token.empty()) tokens.push_back(token); - prev = pos + delim.length(); - } while (pos < str.length() && prev < str.length()); - - return tokens; +vector SplitString(const string &str, const string &delim = ":") { + vector tokens; + size_t prev = 0, pos = 0; + do { + pos = str.find(delim, prev); + if (pos == string::npos) + pos = str.length(); + string token = str.substr(prev, pos - prev); + if (!token.empty()) + tokens.push_back(token); + prev = pos + delim.length(); + } while (pos < str.length() && prev < str.length()); + + return tokens; } -bool checkECDSAKeyName(const string& keyName) { +bool checkECDSAKeyName(const string &keyName) { vector parts = SplitString(keyName); if (parts.size() != 2) { spdlog::info("ECDSAKeyName num parts != 2"); return false; } if (parts.at(0) != "NEK") { - spdlog::info("key doesn't start from NEK"); - return false; + spdlog::info("key doesn't start from NEK"); + return false; } - if ( parts.at(1).length() > 64 || parts.at(1).length() < 1){ - spdlog::info("wrong key length"); - return false; + if (parts.at(1).length() > 64 || parts.at(1).length() < 1) { + spdlog::info("wrong key length"); + return false; } mpz_t num; mpz_init(num); - if ( mpz_set_str(num, parts.at(1).c_str(), 16) == -1){ + if (mpz_set_str(num, parts.at(1).c_str(), 16) == -1) { mpz_clear(num); return false; } @@ -70,8 +72,8 @@ bool checkECDSAKeyName(const string& keyName) { return true; } -bool checkHex(const string& hex, const uint32_t sizeInBytes){ - if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){ +bool checkHex(const string &hex, const uint32_t sizeInBytes) { + if (hex.length() > sizeInBytes * 2 || hex.length() == 0) { spdlog::error("key is too long or zero {} ", hex.length()); return false; } @@ -89,85 +91,85 @@ bool checkHex(const string& hex, const uint32_t sizeInBytes){ return true; } -bool checkName (const string& Name, const string& prefix){ - vector parts = SplitString(Name); - if ( parts.size() != 7) { - spdlog::info("parts.size() != 7"); - return false; - } - if ( parts.at(0) != prefix ) { - spdlog::info("parts.at(0) != prefix"); - return false; - } - if ( parts.at(1) != "SCHAIN_ID"){ - spdlog::info("parts.at(1) != SCHAIN_ID"); - return false; - } - if ( parts.at(3) != "NODE_ID"){ - spdlog::info("parts.at(3) != Node_ID"); - return false; - } - if ( parts.at(5) != "DKG_ID"){ - spdlog::info("parts.at(1) != DKG_ID"); - return false; - } - - if ( parts.at(2).length() > 78 || parts.at(2).length() < 1){ - spdlog::info("parts.at(2).length() > 78"); - return false; - } - if (parts.at(4).length() > 5 || parts.at(4).length() < 1){ - spdlog::info("parts.at(4).length() > 5"); - return false; - } - if ( parts.at(6).length() > 78 || parts.at(6).length() < 1){ - spdlog::info("parts.at(6).length() > 78"); - return false; - } - - mpz_t num; - mpz_init(num); - - if ( mpz_set_str(num, parts.at(2).c_str(), 10) == -1) { - mpz_clear(num); - spdlog::info("parts.at(2) is not decimal number"); - return false; - } +bool checkName(const string &Name, const string &prefix) { + vector parts = SplitString(Name); + if (parts.size() != 7) { + spdlog::info("parts.size() != 7"); + return false; + } + if (parts.at(0) != prefix) { + spdlog::info("parts.at(0) != prefix"); + return false; + } + if (parts.at(1) != "SCHAIN_ID") { + spdlog::info("parts.at(1) != SCHAIN_ID"); + return false; + } + if (parts.at(3) != "NODE_ID") { + spdlog::info("parts.at(3) != Node_ID"); + return false; + } + if (parts.at(5) != "DKG_ID") { + spdlog::info("parts.at(1) != DKG_ID"); + return false; + } + + if (parts.at(2).length() > 78 || parts.at(2).length() < 1) { + spdlog::info("parts.at(2).length() > 78"); + return false; + } + if (parts.at(4).length() > 5 || parts.at(4).length() < 1) { + spdlog::info("parts.at(4).length() > 5"); + return false; + } + if (parts.at(6).length() > 78 || parts.at(6).length() < 1) { + spdlog::info("parts.at(6).length() > 78"); + return false; + } + + mpz_t num; + mpz_init(num); + + if (mpz_set_str(num, parts.at(2).c_str(), 10) == -1) { mpz_clear(num); - mpz_init(num); + spdlog::info("parts.at(2) is not decimal number"); + return false; + } + mpz_clear(num); + mpz_init(num); - if ( mpz_set_str(num, parts.at(4).c_str(), 10) == -1){ - mpz_clear(num); - spdlog::info("parts.at(4) is not decimal number"); - return false; - } + if (mpz_set_str(num, parts.at(4).c_str(), 10) == -1) { mpz_clear(num); - mpz_init(num); + spdlog::info("parts.at(4) is not decimal number"); + return false; + } + mpz_clear(num); + mpz_init(num); - if ( mpz_set_str(num, parts.at(6).c_str(),10) == -1){ - mpz_clear(num); - spdlog::info("parts.at(6) is not decimal number"); - return false; - } + if (mpz_set_str(num, parts.at(6).c_str(), 10) == -1) { mpz_clear(num); + spdlog::info("parts.at(6) is not decimal number"); + return false; + } + mpz_clear(num); - return true; + return true; } -bool check_n_t ( const int t, const int n){ - if (t > n){ +bool check_n_t(const int t, const int n) { + if (t > n) { return false; } - if ( t == 0 || n == 0){ + if (t == 0 || n == 0) { return false; } - if (n > 32){ + if (n > 32) { return false; } - if ( t < 0 || n < 0){ + if (t < 0 || n < 0) { return false; } diff --git a/ServerDataChecker.h b/ServerDataChecker.h index 6bf0b0c5..b6c695e4 100644 --- a/ServerDataChecker.h +++ b/ServerDataChecker.h @@ -26,14 +26,14 @@ #include -bool checkECDSAKeyName(const std::string& keyName); +bool checkECDSAKeyName(const std::string &keyName); -bool checkHex(const std::string& hash, const uint32_t sizeInBytes = 32); +bool checkHex(const std::string &hash, const uint32_t sizeInBytes = 32); -bool checkPolyName (const std::string& polyName); +bool checkPolyName(const std::string &polyName); -bool checkName (const std::string& Name, const std::string& prefix); +bool checkName(const std::string &Name, const std::string &prefix); -bool check_n_t ( const int t, const int n); +bool check_n_t(const int t, const int n); #endif // SGXD_SERVERDATACHECKER_H diff --git a/ServerInit.cpp b/ServerInit.cpp index 1167a6e1..09c7f837 100644 --- a/ServerInit.cpp +++ b/ServerInit.cpp @@ -21,216 +21,221 @@ @date 2019 */ -#include #include +#include -#include -#include #include -#include +#include #include +#include +#include -#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" -#include #include "bls.h" #include "leveldb/db.h" +#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" #include +#include #include "third_party/spdlog/spdlog.h" #include #include #include - -#include "ExitHandler.h" +#include "BLSCrypto.h" #include "BLSPrivateKeyShareSGX.h" -#include "sgxwallet_common.h" -#include "third_party/intel/create_enclave.h" -#include "secure_enclave_u.h" -#include "third_party/intel/sgx_detect.h" -#include "sgxwallet.h" +#include "CSRManagerServer.h" +#include "ExitHandler.h" #include "LevelDB.h" -#include "SGXWalletServer.h" -#include "SGXRegistrationServer.h" -#include "SGXInfoServer.h" #include "SEKManager.h" -#include "CSRManagerServer.h" -#include "BLSCrypto.h" -#include "ServerInit.h" #include "SGXException.h" -#include "zmq_src/ZMQServer.h" +#include "SGXInfoServer.h" +#include "SGXRegistrationServer.h" +#include "SGXWalletServer.h" #include "SGXWalletServer.hpp" +#include "ServerInit.h" +#include "secure_enclave_u.h" +#include "sgxwallet.h" +#include "sgxwallet_common.h" +#include "third_party/intel/create_enclave.h" +#include "third_party/intel/sgx_detect.h" +#include "zmq_src/ZMQServer.h" uint32_t enclaveLogLevel = 0; using namespace std; void systemHealthCheck() { - string ulimit; - try { - ulimit = exec("/bin/bash -c \"ulimit -n\""); - } catch (...) { - spdlog::error("Execution of '/bin/bash -c ulimit -n' failed"); - throw SGXException(EXECUTION_ULIMIT_FAILED, "Execution of '/bin/bash -c ulimit -n' failed."); - } - int noFiles = strtol(ulimit.c_str(), NULL, 10); - - auto noUlimitCheck = getenv("NO_ULIMIT_CHECK") != nullptr; - - if (noFiles < 65535 && !noUlimitCheck) { - string errStr = - "sgxwallet requires setting Linux file descriptor limit to at least 65535 " - "You current limit (ulimit -n) is less than 65535. \n Please set it to 65535:" - "by editing /etc/systemd/system.conf" - "and setting 'DefaultLimitNOFILE=65535'\n" - "After that, restart sgxwallet"; - spdlog::error(errStr); - throw SGXException(WRONG_ULIMIT, errStr); - } + string ulimit; + try { + ulimit = exec("/bin/bash -c \"ulimit -n\""); + } catch (...) { + spdlog::error("Execution of '/bin/bash -c ulimit -n' failed"); + throw SGXException(EXECUTION_ULIMIT_FAILED, + "Execution of '/bin/bash -c ulimit -n' failed."); + } + int noFiles = strtol(ulimit.c_str(), NULL, 10); + + auto noUlimitCheck = getenv("NO_ULIMIT_CHECK") != nullptr; + + if (noFiles < 65535 && !noUlimitCheck) { + string errStr = "sgxwallet requires setting Linux file descriptor limit to " + "at least 65535 " + "You current limit (ulimit -n) is less than 65535. \n " + "Please set it to 65535:" + "by editing /etc/systemd/system.conf" + "and setting 'DefaultLimitNOFILE=65535'\n" + "After that, restart sgxwallet"; + spdlog::error(errStr); + throw SGXException(WRONG_ULIMIT, errStr); + } } void initUserSpace() { - libff::inhibit_profiling_counters = true; + libff::inhibit_profiling_counters = true; - libff::init_alt_bn128_params(); + libff::init_alt_bn128_params(); - LevelDB::initDataFolderAndDBs(); + LevelDB::initDataFolderAndDBs(); #ifndef SGX_HW_SIM - systemHealthCheck(); + systemHealthCheck(); #endif - } uint64_t initEnclave() { #ifndef SGX_HW_SIM - unsigned long support; - support = get_sgx_support(); - if (!SGX_OK(support)) { - sgx_support_perror(support); - throw SGXException(COULD_NOT_INIT_ENCLAVE, "SGX is not supported or not enabled"); - } + unsigned long support; + support = get_sgx_support(); + if (!SGX_OK(support)) { + sgx_support_perror(support); + throw SGXException(COULD_NOT_INIT_ENCLAVE, + "SGX is not supported or not enabled"); + } #endif - spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG); - - sgx_status_t status = SGX_SUCCESS; - - { - - WRITE_LOCK(sgxInitMutex); + spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG); - if (eid != 0) { - if (sgx_destroy_enclave(eid) != SGX_SUCCESS) { - spdlog::error("Could not destroy enclave"); - } - } + sgx_status_t status = SGX_SUCCESS; - eid = 0; - updated = 0; + { - status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token, - &updated, &eid, 0); + WRITE_LOCK(sgxInitMutex); - if (status != SGX_SUCCESS) { - if (status == SGX_ERROR_ENCLAVE_FILE_ACCESS) { - spdlog::error("sgx_create_enclave: {}: file not found", ENCLAVE_NAME); - spdlog::error("Did you forget to set LD_LIBRARY_PATH?"); - } else { - spdlog::error("sgx_create_enclave_search failed {} {}", ENCLAVE_NAME, status); - } - throw SGXException(COULD_NOT_INIT_ENCLAVE, "Error initing enclave. Please re-check your enviroment."); - } + if (eid != 0) { + if (sgx_destroy_enclave(eid) != SGX_SUCCESS) { + spdlog::error("Could not destroy enclave"); + } + } - spdlog::info("Enclave created and started successfully"); + eid = 0; + updated = 0; - status = trustedEnclaveInit(eid, enclaveLogLevel); - } + status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token, + &updated, &eid, 0); if (status != SGX_SUCCESS) { - spdlog::error("trustedEnclaveInit failed: {}", status); - return status; + if (status == SGX_ERROR_ENCLAVE_FILE_ACCESS) { + spdlog::error("sgx_create_enclave: {}: file not found", ENCLAVE_NAME); + spdlog::error("Did you forget to set LD_LIBRARY_PATH?"); + } else { + spdlog::error("sgx_create_enclave_search failed {} {}", ENCLAVE_NAME, + status); + } + throw SGXException( + COULD_NOT_INIT_ENCLAVE, + "Error initing enclave. Please re-check your enviroment."); } - spdlog::info("Enclave libtgmp library and logging initialized successfully"); + spdlog::info("Enclave created and started successfully"); - return SGX_SUCCESS; -} + status = trustedEnclaveInit(eid, enclaveLogLevel); + } -void initAll(uint32_t _logLevel, bool _checkCert, - bool _checkZMQSig, bool _autoSign, bool _generateTestKeys, bool _checkKeyOwnership) { + if (status != SGX_SUCCESS) { + spdlog::error("trustedEnclaveInit failed: {}", status); + return status; + } - static atomic sgxServerInited(false); - static mutex initMutex; - enclaveLogLevel = _logLevel; + spdlog::info("Enclave libtgmp library and logging initialized successfully"); - lock_guard lock(initMutex); + return SGX_SUCCESS; +} + +void initAll(uint32_t _logLevel, bool _checkCert, bool _checkZMQSig, + bool _autoSign, bool _generateTestKeys, bool _checkKeyOwnership) { - if (sgxServerInited) - return; + static atomic sgxServerInited(false); + static mutex initMutex; + enclaveLogLevel = _logLevel; - try { + lock_guard lock(initMutex); - cout << "Running sgxwallet version:" << SGXWalletServer::getVersion() << endl; + if (sgxServerInited) + return; - CHECK_STATE(sgxServerInited != 1) - sgxServerInited = 1; + try { - uint64_t counter = 0; + cout << "Running sgxwallet version:" << SGXWalletServer::getVersion() + << endl; - uint64_t initResult = 0; - while ((initResult = initEnclave()) != 0 && counter < 10) { - sleep(1); - counter++; - } + CHECK_STATE(sgxServerInited != 1) + sgxServerInited = 1; - if (initResult != 0) { - spdlog::error("Coult not init enclave"); - } + uint64_t counter = 0; - initUserSpace(); - initSEK(); + uint64_t initResult = 0; + while ((initResult = initEnclave()) != 0 && counter < 10) { + sleep(1); + counter++; + } - SGXWalletServer::createCertsIfNeeded(); + if (initResult != 0) { + spdlog::error("Coult not init enclave"); + } - if (useHTTPS) { - spdlog::info("Initing JSON-RPC server over HTTPS"); - spdlog::info("Check client cert: {}", _checkCert); - SGXWalletServer::initHttpsServer(_checkCert); - spdlog::info("Inited JSON-RPC server over HTTPS"); - } else { - spdlog::info("Initing JSON-RPC server over HTTP"); - SGXWalletServer::initHttpServer(); - spdlog::info("Inited JSON-RPC server over HTTP"); - } + initUserSpace(); + initSEK(); - SGXRegistrationServer::initRegistrationServer(_autoSign); - CSRManagerServer::initCSRManagerServer(); - SGXInfoServer::initInfoServer(_logLevel, _checkCert, _autoSign, _generateTestKeys); - ZMQServer::initZMQServer(_checkZMQSig, _checkKeyOwnership); + SGXWalletServer::createCertsIfNeeded(); - sgxServerInited = true; - } catch (SGXException &_e) { - spdlog::error(_e.getMessage()); - ExitHandler::exitHandler(SIGTERM, ExitHandler::ec_initing_user_space); - } catch (exception &_e) { - spdlog::error(_e.what()); - ExitHandler::exitHandler(SIGTERM, ExitHandler::ec_initing_user_space); - } - catch (...) { - exception_ptr p = current_exception(); - printf("Exception %s \n", p.__cxa_exception_type()->name()); - spdlog::error("Unknown exception"); - ExitHandler::exitHandler(SIGTERM, ExitHandler::ec_initing_user_space); + if (useHTTPS) { + spdlog::info("Initing JSON-RPC server over HTTPS"); + spdlog::info("Check client cert: {}", _checkCert); + SGXWalletServer::initHttpsServer(_checkCert); + spdlog::info("Inited JSON-RPC server over HTTPS"); + } else { + spdlog::info("Initing JSON-RPC server over HTTP"); + SGXWalletServer::initHttpServer(); + spdlog::info("Inited JSON-RPC server over HTTP"); } + + SGXRegistrationServer::initRegistrationServer(_autoSign); + CSRManagerServer::initCSRManagerServer(); + SGXInfoServer::initInfoServer(_logLevel, _checkCert, _autoSign, + _generateTestKeys); + ZMQServer::initZMQServer(_checkZMQSig, _checkKeyOwnership); + + sgxServerInited = true; + } catch (SGXException &_e) { + spdlog::error(_e.getMessage()); + ExitHandler::exitHandler(SIGTERM, ExitHandler::ec_initing_user_space); + } catch (exception &_e) { + spdlog::error(_e.what()); + ExitHandler::exitHandler(SIGTERM, ExitHandler::ec_initing_user_space); + } catch (...) { + exception_ptr p = current_exception(); + printf("Exception %s \n", p.__cxa_exception_type()->name()); + spdlog::error("Unknown exception"); + ExitHandler::exitHandler(SIGTERM, ExitHandler::ec_initing_user_space); + } }; void exitAll() { - SGXWalletServer::exitServer(); - SGXRegistrationServer::exitServer(); - CSRManagerServer::exitServer(); - SGXInfoServer::exitServer(); - ZMQServer::exitZMQServer(); + SGXWalletServer::exitServer(); + SGXRegistrationServer::exitServer(); + CSRManagerServer::exitServer(); + SGXInfoServer::exitServer(); + ZMQServer::exitZMQServer(); } diff --git a/ServerInit.h b/ServerInit.h index 16b94eb5..c5969c9a 100644 --- a/ServerInit.h +++ b/ServerInit.h @@ -32,7 +32,9 @@ #define EXTERNC #endif -EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _checkZMQSig, bool _autoSign, bool _generateTestKeys, bool _checkKeyOwnership); +EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _checkZMQSig, + bool _autoSign, bool _generateTestKeys, + bool _checkKeyOwnership); void exitAll(); @@ -42,6 +44,4 @@ EXTERNC uint64_t initEnclave(); EXTERNC void exitZMQServer(); - - -#endif //SGXWALLET_SERVERINIT_H +#endif // SGXWALLET_SERVERINIT_H diff --git a/TECrypto.cpp b/TECrypto.cpp index 2dc0bb34..a471f402 100644 --- a/TECrypto.cpp +++ b/TECrypto.cpp @@ -21,50 +21,53 @@ @date 2021 */ -#include #include "leveldb/db.h" #include +#include #include "threshold_encryption/threshold_encryption.h" -#include "sgxwallet_common.h" -#include "sgxwallet.h" #include "SGXException.h" -#include "third_party/spdlog/spdlog.h" -#include "common.h" #include "SGXWalletServer.h" +#include "common.h" +#include "sgxwallet.h" +#include "sgxwallet_common.h" +#include "third_party/spdlog/spdlog.h" -#include "TECrypto.h" #include "CryptoTools.h" +#include "TECrypto.h" -#include +#include -vector calculateDecryptionShare(const string& encryptedKeyShare, - const string& publicDecryptionValue) { - size_t sz = 0; +vector calculateDecryptionShare(const string &encryptedKeyShare, + const string &publicDecryptionValue) { + size_t sz = 0; - SAFE_UINT8_BUF(encryptedKey, BUF_LEN); + SAFE_UINT8_BUF(encryptedKey, BUF_LEN); - bool result = hex2carray(encryptedKeyShare.data(), &sz, encryptedKey, BUF_LEN); + bool result = + hex2carray(encryptedKeyShare.data(), &sz, encryptedKey, BUF_LEN); - if (!result) { - BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); - } + if (!result) { + BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key")); + } - SAFE_CHAR_BUF(decryptionShare, BUF_LEN) + SAFE_CHAR_BUF(decryptionShare, BUF_LEN) - vector errMsg(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); - int errStatus = 0; + int errStatus = 0; - sgx_status_t status = SGX_SUCCESS; + sgx_status_t status = SGX_SUCCESS; - status = trustedGetDecryptionShare(eid, &errStatus, errMsg.data(), encryptedKey, - publicDecryptionValue.data(), sz, decryptionShare); + status = trustedGetDecryptionShare(eid, &errStatus, errMsg.data(), + encryptedKey, publicDecryptionValue.data(), + sz, decryptionShare); - HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); + HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data()); - auto splitted_share = BLSutils::SplitString(std::make_shared(decryptionShare), ":"); + auto splittedShare = libBLS::ThresholdUtils::SplitString( + std::make_shared(decryptionShare), ":"); - return *splitted_share; -} \ No newline at end of file + return *splittedShare; +} diff --git a/TECrypto.h b/TECrypto.h index 4c03dd57..9cae75f6 100644 --- a/TECrypto.h +++ b/TECrypto.h @@ -35,7 +35,8 @@ #include #include -std::vector calculateDecryptionShare(const std::string& encryptedKeyShare, - const std::string& publicDecryptionValue); +std::vector +calculateDecryptionShare(const std::string &encryptedKeyShare, + const std::string &publicDecryptionValue); #endif // SGXWALLET_TECRYPTO_H diff --git a/TestUtils.cpp b/TestUtils.cpp index 86b9ccb3..bc1a6f52 100644 --- a/TestUtils.cpp +++ b/TestUtils.cpp @@ -23,1059 +23,1122 @@ #include +#include "secure_enclave_u.h" #include "sgxwallet_common.h" #include "third_party/intel/create_enclave.h" -#include "secure_enclave_u.h" #include "third_party/intel/sgx_detect.h" #include "third_party/spdlog/spdlog.h" #include -#include -#include #include #include +#include +#include #include "BLSCrypto.h" -#include "ServerInit.h" -#include "DKGCrypto.h" #include "CryptoTools.h" -#include "SGXException.h" +#include "DKGCrypto.h" #include "LevelDB.h" +#include "SGXException.h" #include "SGXWalletServer.hpp" +#include "ServerInit.h" -#include "catch.hpp" +#include "BLSPublicKey.h" +#include "BLSPublicKeyShare.h" #include "BLSSigShare.h" #include "BLSSigShareSet.h" -#include "BLSPublicKeyShare.h" -#include "BLSPublicKey.h" #include "SEKManager.h" -#include -#include "common.h" -#include "stubclient.h" #include "SGXRegistrationServer.h" #include "SGXWalletServer.h" +#include "TestUtils.h" +#include "common.h" #include "sgxwallet.h" +#include "stubclient.h" #include "testw.h" -#include "TestUtils.h" +#include "third_party/catch.hpp" +#include using namespace jsonrpc; using namespace std; -default_random_engine TestUtils::randGen((unsigned int) time(0)); +default_random_engine TestUtils::randGen((unsigned int)time(0)); -string TestUtils::stringFromFr(libff::alt_bn128_Fr &el) { - mpz_t t; - mpz_init(t); - el.as_bigint().to_mpz(t); - char arr[mpz_sizeinbase(t, 10) + 2]; - mpz_get_str(arr, 10, t); - mpz_clear(t); +string TestUtils::stringFromFr(libff::alt_bn128_Fr &el, size_t base) { + mpz_t t; + mpz_init(t); + el.as_bigint().to_mpz(t); + char arr[mpz_sizeinbase(t, 10) + 2]; + mpz_get_str(arr, base, t); + mpz_clear(t); - return string(arr); + return string(arr); } string TestUtils::convertDecToHex(string dec, int numBytes) { - mpz_t num; - mpz_init(num); - mpz_set_str(num, dec.c_str(), 10); - vector 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; + mpz_t num; + mpz_init(num); + mpz_set_str(num, dec.c_str(), 10); + vector 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; } void TestUtils::resetDB() { - CHECK_STATE(system("bash -c \"rm -rf " SGXDATA_FOLDER "* \"") == 0); + CHECK_STATE(system("bash -c \"rm -rf " SGXDATA_FOLDER "* \"") == 0); } -shared_ptr TestUtils::encryptTestKey() { - const char *key = TEST_BLS_KEY_SHARE; - int errStatus = -1; - vector errMsg(BUF_LEN, 0);; - string encryptedKeyHex = encryptBLSKeyShare2Hex(&errStatus, errMsg.data(), key); +shared_ptr TestUtils::encryptTestKey() { + const char *key = TEST_BLS_KEY_SHARE; + int errStatus = -1; + vector errMsg(BUF_LEN, 0); + ; + string encryptedKeyHex = + encryptBLSKeyShare2Hex(&errStatus, errMsg.data(), key); - CHECK_STATE(!encryptedKeyHex.empty()); - CHECK_STATE(errStatus == 0); + CHECK_STATE(!encryptedKeyHex.empty()); + CHECK_STATE(errStatus == 0); - return make_shared(encryptedKeyHex); + return make_shared(encryptedKeyHex); } -vector TestUtils::splitStringToFr(const char *coeffs, const char symbol) { - string str(coeffs); - string delim; - delim.push_back(symbol); - vector tokens; - size_t prev = 0, pos = 0; - do { - pos = str.find(delim, prev); - if (pos == string::npos) pos = str.length(); - string token = str.substr(prev, pos - prev); - if (!token.empty()) { - libff::alt_bn128_Fr coeff(token.c_str()); - tokens.push_back(coeff); - } - prev = pos + delim.length(); - } while (pos < str.length() && prev < str.length()); - - return tokens; -} +vector TestUtils::splitStringToFr(const char *coeffs, + const char symbol) { + string str(coeffs); + string delim; + delim.push_back(symbol); + vector tokens; + size_t prev = 0, pos = 0; + do { + pos = str.find(delim, prev); + if (pos == string::npos) + pos = str.length(); + string token = str.substr(prev, pos - prev); + if (!token.empty()) { + libff::alt_bn128_Fr coeff(token.c_str()); + tokens.push_back(coeff); + } + prev = pos + delim.length(); + } while (pos < str.length() && prev < str.length()); -vector TestUtils::splitStringTest(const char *coeffs, const char symbol) { - string str(coeffs); - string delim; - delim.push_back(symbol); - vector g2Strings; - size_t prev = 0, pos = 0; - do { - pos = str.find(delim, prev); - if (pos == string::npos) pos = str.length(); - string token = str.substr(prev, pos - prev); - if (!token.empty()) { - string coeff(token.c_str()); - g2Strings.push_back(coeff); - } - prev = pos + delim.length(); - } while (pos < str.length() && prev < str.length()); - - return g2Strings; + return tokens; } -libff::alt_bn128_G2 TestUtils::vectStringToG2(const vector &G2_str_vect) { - libff::alt_bn128_G2 coeff = libff::alt_bn128_G2::zero(); - coeff.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str()); - coeff.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str()); - coeff.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str()); - coeff.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str()); - coeff.Z.c0 = libff::alt_bn128_Fq::one(); - coeff.Z.c1 = libff::alt_bn128_Fq::zero(); +vector TestUtils::splitStringTest(const char *coeffs, + const char symbol) { + string str(coeffs); + string delim; + delim.push_back(symbol); + vector g2Strings; + size_t prev = 0, pos = 0; + do { + pos = str.find(delim, prev); + if (pos == string::npos) + pos = str.length(); + string token = str.substr(prev, pos - prev); + if (!token.empty()) { + string coeff(token.c_str()); + g2Strings.push_back(coeff); + } + prev = pos + delim.length(); + } while (pos < str.length() && prev < str.length()); - return coeff; + return g2Strings; } -void TestUtils::sendRPCRequest() { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - - int n = 16, t = 16; - Json::Value ethKeys[n]; - Json::Value verifVects[n]; - Json::Value pubEthKeys; - Json::Value secretShares[n]; - Json::Value pubBLSKeys[n]; - Json::Value blsSigShares[n]; - vector pubShares(n); - vector polyNames(n); +libff::alt_bn128_G2 +TestUtils::vectStringToG2(const vector &G2_str_vect) { + libff::alt_bn128_G2 coeff = libff::alt_bn128_G2::zero(); + coeff.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str()); + coeff.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str()); + coeff.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str()); + coeff.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str()); + coeff.Z.c0 = libff::alt_bn128_Fq::one(); + coeff.Z.c1 = libff::alt_bn128_Fq::zero(); + + return coeff; +} - static atomic counter(1); +void TestUtils::sendRPCRequest() { + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + + int n = 16, t = 16; + Json::Value ethKeys[n]; + Json::Value verifVects[n]; + Json::Value pubEthKeys; + Json::Value secretShares[n]; + Json::Value pubBLSKeys[n]; + Json::Value blsSigShares[n]; + vector pubShares(n); + vector polyNames(n); + + static atomic 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); + } - int schainID = counter.fetch_add(1); - int dkgID = counter.fetch_add(1); + 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); + CHECK_STATE(verifVects[i]["status"] == 0); + } - int testCount = 1; + pubEthKeys.append(ethKeys[i]["publicKey"]); + } - if (getenv("NIGHTLY_TESTS")) { - testCount = 10; + 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 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); - CHECK_STATE(verifVects[i]["status"] == 0); - } - - pubEthKeys.append(ethKeys[i]["publicKey"]); + 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); + } } - - 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 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); + } } - vector secShares(n); + BLSSigShareSet sigShareSet(t, 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); - } - } + string hash = SAMPLE_HASH; - BLSSigShareSet sigShareSet(t, n); + auto hash_arr = make_shared>(); + uint64_t binLen; + if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - 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(TEST_INVALID_HEX, "Invalid hash"); - } + map> coeffs_pkeys_map; - map > coeffs_pkeys_map; - - Json::Value publicShares; - for (int i = 0; i < n; ++i) { - publicShares["publicShares"][i] = pubShares[i]; - } + Json::Value publicShares; + for (int i = 0; i < n; ++i) { + publicShares["publicShares"][i] = pubShares[i]; + } - Json::Value blsPublicKeys; + Json::Value blsPublicKeys; - for (int i6 = 0; i6 <= testCount; i6++) { - blsPublicKeys = c.calculateAllBLSPublicKeys(publicShares, t, n); - CHECK_STATE(blsPublicKeys["status"] == 0); - } + 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(); + 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); + 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); + 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()); + 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); + string public_key_str = convertG2ToString(publicKey); - CHECK_STATE(public_key_str == blsPublicKeys["publicKeys"][i].asString()); + 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); + string hash = SAMPLE_HASH; + blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); + CHECK_STATE(blsSigShares[i]["status"] == 0); - shared_ptr sig_share_ptr = make_shared(blsSigShares[i]["signatureShare"].asString()); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); - } + shared_ptr sig_share_ptr = + make_shared(blsSigShares[i]["signatureShare"].asString()); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); + } - sigShareSet.merge(); + 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 pubShares(n); - vector polyNames(n); - - static atomic counter(1); - - int schainID = counter.fetch_add(1); - int dkgID = counter.fetch_add(1); - for (uint8_t i = 0; i < n; i++) { - ethKeys[i] = c.generateECDSAKey(); - 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; - verifVects[i] = c.getVerificationVector(polyName, t); - CHECK_STATE(verifVects[i]["status"] == 0); - - pubEthKeys.append(ethKeys[i]["publicKey"]); + 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 pubShares(n); + vector polyNames(n); + + static atomic counter(1); + + int schainID = counter.fetch_add(1); + int dkgID = counter.fetch_add(1); + for (uint8_t i = 0; i < n; i++) { + ethKeys[i] = c.generateECDSAKey(); + 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; + verifVects[i] = c.getVerificationVector(polyName, t); + 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); + 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); + } } - - for (uint8_t i = 0; i < n; i++) { - 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(); - pubShares[i] += convertDecToHex(pubShare); - } - } + } + + vector secShares(n); + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) { + string secretShare = + secretShares[i]["secretShare"].asString().substr(192 * j, 192); + secShares[i] += + secretShares[j]["secretShare"].asString().substr(192 * i, 192); + Json::Value verif = c.dkgVerificationV2( + pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j); + CHECK_STATE(verif["status"] == 0); } - vector secShares(n); + BLSSigShareSet sigShareSet(t, n); - for (int i = 0; i < n; i++) - for (int j = 0; j < n; j++) { - string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192); - secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192); - Json::Value verif = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j); - CHECK_STATE(verif["status"] == 0); - } + string hash = SAMPLE_HASH; - BLSSigShareSet sigShareSet(t, n); + auto hash_arr = make_shared>(); + uint64_t binLen; + if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - string hash = SAMPLE_HASH; + map> coeffs_pkeys_map; - auto hash_arr = make_shared < array < uint8_t, 32 >> (); - uint64_t binLen; - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + Json::Value publicShares; + for (int i = 0; i < n; ++i) { + publicShares["publicShares"][i] = pubShares[i]; + } - map > coeffs_pkeys_map; + Json::Value blsPublicKeys = c.calculateAllBLSPublicKeys(publicShares, t, n); + CHECK_STATE(blsPublicKeys["status"] == 0); - Json::Value publicShares; - for (int i = 0; i < n; ++i) { - publicShares["publicShares"][i] = pubShares[i]; - } + 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(); - Json::Value 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.createBLSPrivateKeyV2(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); - auto response = c.createBLSPrivateKeyV2(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); + 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()); - 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); - string public_key_str = convertG2ToString(publicKey); + CHECK_STATE(public_key_str == blsPublicKeys["publicKeys"][i].asString()); - 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); - string hash = SAMPLE_HASH; - blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); - CHECK_STATE(blsSigShares[i]["status"] == 0); + shared_ptr sig_share_ptr = + make_shared(blsSigShares[i]["signatureShare"].asString()); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); + } - shared_ptr sig_share_ptr = make_shared(blsSigShares[i]["signatureShare"].asString()); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); - } - - sigShareSet.merge(); + sigShareSet.merge(); } void TestUtils::sendRPCRequestZMQ() { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); - - int n = 16, t = 16; - vector ethKeys(n); - Json::Value verifVects[n]; - Json::Value pubEthKeys; - vector secretShares(n); - Json::Value pubBLSKeys[n]; - vector blsSigShares(n); - vector pubShares(n); - vector polyNames(n); - - static atomic counter(1); - - int schainID = counter.fetch_add(1); - int dkgID = counter.fetch_add(1); - for (uint8_t i = 0; i < n; i++) { - auto generatedKey = client->generateECDSAKey(); - ethKeys[i] = generatedKey.second; - string polyName = - "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID); - CHECK_STATE(client->generateDKGPoly(polyName, t)); - polyNames[i] = polyName; - verifVects[i] = client->getVerificationVector(polyName, t); - - pubEthKeys.append(generatedKey.first); + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); + + int n = 16, t = 16; + vector ethKeys(n); + Json::Value verifVects[n]; + Json::Value pubEthKeys; + vector secretShares(n); + Json::Value pubBLSKeys[n]; + vector blsSigShares(n); + vector pubShares(n); + vector polyNames(n); + + static atomic counter(1); + + int schainID = counter.fetch_add(1); + int dkgID = counter.fetch_add(1); + for (uint8_t i = 0; i < n; i++) { + auto generatedKey = client->generateECDSAKey(); + ethKeys[i] = generatedKey.second; + string polyName = "POLY:SCHAIN_ID:" + to_string(schainID) + + ":NODE_ID:" + to_string(i) + + ":DKG_ID:" + to_string(dkgID); + CHECK_STATE(client->generateDKGPoly(polyName, t)); + polyNames[i] = polyName; + verifVects[i] = client->getVerificationVector(polyName, t); + + pubEthKeys.append(generatedKey.first); + } + + for (uint8_t i = 0; i < n; i++) { + secretShares[i] = client->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][k][j].asString(); + pubShares[i] += convertDecToHex(pubShare); + } } + } + + vector secShares(n); - for (uint8_t i = 0; i < n; i++) { - secretShares[i] = client->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][k][j].asString(); - pubShares[i] += convertDecToHex(pubShare); - } - } + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) { + string secretShare = secretShares[i].substr(192 * j, 192); + secShares[i] += secretShares[j].substr(192 * i, 192); + bool verif = client->dkgVerification(pubShares[i], ethKeys[j], + secretShare, t, n, j); + CHECK_STATE(verif); } - vector secShares(n); + BLSSigShareSet sigShareSet(t, n); - for (int i = 0; i < n; i++) - for (int j = 0; j < n; j++) { - string secretShare = secretShares[i].substr(192 * j, 192); - secShares[i] += secretShares[j].substr(192 * i, 192); - bool verif = client->dkgVerification(pubShares[i], ethKeys[j], secretShare, t, n, j); - CHECK_STATE(verif); - } + string hash = SAMPLE_HASH; - BLSSigShareSet sigShareSet(t, n); + auto hash_arr = make_shared>(); + uint64_t binLen; + if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - string hash = SAMPLE_HASH; + map> coeffs_pkeys_map; - auto hash_arr = make_shared < array < uint8_t, 32 >> (); - uint64_t binLen; - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + Json::Value publicShares; + for (int i = 0; i < n; ++i) { + publicShares["publicShares"][i] = pubShares[i]; + } - map > coeffs_pkeys_map; + Json::Value blsPublicKeys = client->getAllBlsPublicKeys(publicShares, t, n); - Json::Value publicShares; - for (int i = 0; i < n; ++i) { - publicShares["publicShares"][i] = pubShares[i]; - } - - Json::Value blsPublicKeys = client->getAllBlsPublicKeys(publicShares, t, n); + for (int i = 0; i < t; i++) { + string blsName = "BLS_KEY" + polyNames[i].substr(4); + string secretShare = secretShares[i]; - for (int i = 0; i < t; i++) { - string blsName = "BLS_KEY" + polyNames[i].substr(4); - string secretShare = secretShares[i]; + CHECK_STATE(client->createBLSPrivateKey(blsName, ethKeys[i], polyNames[i], + secShares[i], t, n)); + pubBLSKeys[i] = client->getBLSPublicKey(blsName); - CHECK_STATE(client->createBLSPrivateKey(blsName, ethKeys[i], polyNames[i], secShares[i], t, n)); - pubBLSKeys[i] = client->getBLSPublicKey(blsName); + libff::alt_bn128_G2 publicKey( + libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i][0].asCString()), + libff::alt_bn128_Fq(pubBLSKeys[i][1].asCString())), + libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i][2].asCString()), + libff::alt_bn128_Fq(pubBLSKeys[i][3].asCString())), + libff::alt_bn128_Fq2::one()); - libff::alt_bn128_G2 publicKey(libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i][0].asCString()), - libff::alt_bn128_Fq(pubBLSKeys[i][1].asCString())), - libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i][2].asCString()), - libff::alt_bn128_Fq(pubBLSKeys[i][3].asCString())), - libff::alt_bn128_Fq2::one()); + string public_key_str = convertG2ToString(publicKey); - string public_key_str = convertG2ToString(publicKey); + CHECK_STATE(public_key_str == blsPublicKeys[i].asString()); - CHECK_STATE(public_key_str == blsPublicKeys[i].asString()); - - string hash = SAMPLE_HASH; - blsSigShares[i] = client->blsSignMessageHash(blsName, hash, t, n); - CHECK_STATE(blsSigShares[i].length() > 0); + string hash = SAMPLE_HASH; + blsSigShares[i] = client->blsSignMessageHash(blsName, hash, t, n); + CHECK_STATE(blsSigShares[i].length() > 0); - shared_ptr sig_share_ptr = make_shared(blsSigShares[i]); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); - } + shared_ptr sig_share_ptr = make_shared(blsSigShares[i]); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); + } - sigShareSet.merge(); + sigShareSet.merge(); } void TestUtils::destroyEnclave() { - if (eid != 0) { - sgx_destroy_enclave(eid); - eid = 0; - } + if (eid != 0) { + sgx_destroy_enclave(eid); + eid = 0; + } } void TestUtils::doDKG(StubClient &c, int n, int t, - vector& _ecdsaKeyNames, vector& _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 pubShares(n); - vector 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); - CHECK_STATE(verifVects[i]["status"] == 0); - pubEthKeys.append(ethKeys[i]["publicKey"]); + vector &_ecdsaKeyNames, + vector &_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 pubShares(n); + vector 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); + CHECK_STATE(verifVects[i]["status"] == 0); + pubEthKeys.append(ethKeys[i]["publicKey"]); + } + + for (uint8_t i = 0; i < n; i++) { + secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n); + 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); + } } + } - for (uint8_t i = 0; i < n; i++) { - secretShares[i] = c.getSecretShare(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; - int k = 0; + vector secShares(n); - vector secShares(n); + vector pSharesBad(pubShares); - vector 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.dkgVerification( + pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j); + CHECK_STATE(response["status"] == 0); - 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.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, - j); - CHECK_STATE(response["status"] == 0); + bool res = response["result"].asBool(); + CHECK_STATE(res); - bool res = response["result"].asBool(); - CHECK_STATE(res); + k++; - k++; + pSharesBad[i][0] = 'q'; + Json::Value wrongVerif = + c.dkgVerification(pSharesBad[i], ethKeys[j]["keyName"].asString(), + secretShare, t, n, j); + res = wrongVerif["result"].asBool(); + CHECK_STATE(!res); + } - pSharesBad[i][0] = 'q'; - Json::Value wrongVerif = c.dkgVerification(pSharesBad[i], ethKeys[j]["keyName"].asString(), secretShare, t, - n, j); - res = wrongVerif["result"].asBool(); - CHECK_STATE(!res); - } + BLSSigShareSet sigShareSet(t, n); - BLSSigShareSet sigShareSet(t, n); + string hash = SAMPLE_HASH; - string hash = SAMPLE_HASH; + auto hash_arr = make_shared>(); + uint64_t binLen; + if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - auto hash_arr = make_shared>(); - uint64_t binLen; - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + map> pubKeyShares; - map> 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(); - 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); + } - 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 pubKeyVect; + for (uint8_t j = 0; j < 4; j++) { + pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); } + BLSPublicKeyShare pubKey(make_shared>(pubKeyVect), t, n); - for (int i = 0; i < t; i++) { - vector pubKeyVect; - for (uint8_t j = 0; j < 4; j++) { - pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); - } - BLSPublicKeyShare pubKey(make_shared>(pubKeyVect), t, n); + pubKeyShares[i + 1] = make_shared(pubKey); + } - pubKeyShares[i + 1] = make_shared(pubKey); - } - - // create pub key + // create pub key - BLSPublicKey blsPublicKey(make_shared>>(pubKeyShares), t, - n); + BLSPublicKey blsPublicKey( + make_shared>>(pubKeyShares), t, + n); - // sign verify a sample sig + // sign verify a sample sig - for (int i = 0; i < t; i++) { + 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 sig_share_ptr = make_shared(blsSigShares[i]["signatureShare"].asString()); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); + string blsName = "BLS_KEY" + polyNames[i].substr(4); + blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); + CHECK_STATE(blsSigShares[i]["status"] == 0); + shared_ptr sig_share_ptr = + make_shared(blsSigShares[i]["signatureShare"].asString()); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); - auto pubKey = pubKeyShares[i+1]; + auto pubKey = pubKeyShares[i + 1]; - CHECK_STATE(pubKey->VerifySigWithHelper(hash_arr, make_shared(sig), t, n)); - } + CHECK_STATE(pubKey->VerifySigWithHelper( + hash_arr, make_shared(sig), t, n)); + } - shared_ptr commonSig = sigShareSet.merge(); + shared_ptr commonSig = sigShareSet.merge(); - CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig, t, n)); + CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig)); - for (auto&& i : _ecdsaKeyNames) - cerr << i << endl; + for (auto &&i : _ecdsaKeyNames) + cerr << i << endl; - for (auto&& i : _blsKeyNames) - cerr << i << endl; + for (auto &&i : _blsKeyNames) + cerr << i << endl; } void TestUtils::doDKGV2(StubClient &c, int n, int t, - vector& _ecdsaKeyNames, vector& _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 pubShares(n); - vector 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); - 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); - } - } + vector &_ecdsaKeyNames, + vector &_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 pubShares(n); + vector 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); + 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 secShares(n); - - vector 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; + int k = 0; - auto hash_arr = make_shared>(); - uint64_t binLen; - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + vector secShares(n); - map> pubKeyShares; + vector pSharesBad(pubShares); - 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(); + 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); - auto response = c.createBLSPrivateKeyV2(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); - } + bool res = response["result"].asBool(); + CHECK_STATE(res); - for (int i = 0; i < t; i++) { - vector pubKeyVect; - for (uint8_t j = 0; j < 4; j++) { - pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); - } - BLSPublicKeyShare pubKey(make_shared>(pubKeyVect), t, n); + k++; - pubKeyShares[i + 1] = make_shared(pubKey); + 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); } - // create pub key + BLSSigShareSet sigShareSet(t, n); - BLSPublicKey blsPublicKey(make_shared>>(pubKeyShares), t, - n); + string hash = SAMPLE_HASH; - // sign verify a sample sig + auto hashArr = make_shared>(); + uint64_t binLen; + if (!hex2carray(hash.c_str(), &binLen, hashArr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - for (int i = 0; i < t; i++) { + map> pubKeyShares; - string blsName = "BLS_KEY" + polyNames[i].substr(4); - blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); - CHECK_STATE(blsSigShares[i]["status"] == 0); - shared_ptr sig_share_ptr = make_shared(blsSigShares[i]["signatureShare"].asString()); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); + 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 pubKey = pubKeyShares[i+1]; + auto response = + c.createBLSPrivateKeyV2(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); + } - CHECK_STATE(pubKey->VerifySigWithHelper(hash_arr, make_shared(sig), t, n)); + for (int i = 0; i < t; i++) { + vector pubKeyVect; + for (uint8_t j = 0; j < 4; j++) { + pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); } + BLSPublicKeyShare pubKey(make_shared>(pubKeyVect), t, n); - shared_ptr commonSig = sigShareSet.merge(); + pubKeyShares[i + 1] = make_shared(pubKey); + } - CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig, t, n)); + // create pub key - for (auto&& i : _ecdsaKeyNames) - cerr << i << endl; + BLSPublicKey blsPublicKey( + make_shared>>(pubKeyShares), t, + n); - for (auto&& i : _blsKeyNames) - cerr << i << endl; -} + // sign verify a sample sig + for (int i = 0; i < t; i++) { -void TestUtils::doZMQBLS(shared_ptr _zmqClient, StubClient &c, int n, int t, - vector& _ecdsaKeyNames, vector& _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 pubShares(n); - vector polyNames(n); + string blsName = "BLS_KEY" + polyNames[i].substr(4); + blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); + CHECK_STATE(blsSigShares[i]["status"] == 0); + shared_ptr sig_share_ptr = + make_shared(blsSigShares[i]["signatureShare"].asString()); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); - _ecdsaKeyNames.clear(); - _blsKeyNames.clear(); + auto pubKey = pubKeyShares[i + 1]; - for (uint8_t i = 0; i < n; i++) { - ethKeys[i] = c.generateECDSAKey(); + CHECK_STATE(pubKey->VerifySigWithHelper( + hashArr, make_shared(sig), t, n)); + } - CHECK_STATE(ethKeys[i]["status"] == 0); + shared_ptr commonSig = sigShareSet.merge(); - auto keyName = ethKeys[i]["keyName"].asString(); - CHECK_STATE(keyName.size() == ECDSA_KEY_NAME_SIZE); + CHECK_STATE(blsPublicKey.VerifySigWithHelper(hashArr, commonSig)); - _ecdsaKeyNames.push_back(keyName); + for (auto &&i : _ecdsaKeyNames) + cerr << i << endl; - string polyName = - "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID); + for (auto &&i : _blsKeyNames) + cerr << i << endl; +} - Json::Value response = c.generateDKGPoly(polyName, t); - CHECK_STATE(response["status"] == 0); - polyNames[i] = polyName; - verifVects[i] = c.getVerificationVector(polyName, t); - CHECK_STATE(verifVects[i]["status"] == 0); - pubEthKeys.append(ethKeys[i]["publicKey"]); +void TestUtils::doZMQBLS(shared_ptr _zmqClient, StubClient &c, int n, + int t, vector &_ecdsaKeyNames, + vector &_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 pubShares(n); + vector 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); + 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); + } } + } - 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; - int k = 0; + vector secShares(n); - vector secShares(n); + vector pSharesBad(pubShares); - vector 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); - 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); - bool res = response["result"].asBool(); - CHECK_STATE(res); + k++; - 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); + } - 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); - BLSSigShareSet sigShareSet(t, n); + string hash = SAMPLE_HASH; - string hash = SAMPLE_HASH; + auto hashArr = make_shared>(); + uint64_t binLen; + if (!hex2carray(hash.c_str(), &binLen, hashArr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - auto hash_arr = make_shared>(); - uint64_t binLen; - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + map> pubKeyShares; - map> 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(); - 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.createBLSPrivateKeyV2(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); + } - auto response = c.createBLSPrivateKeyV2(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 pubKeyVect; + for (uint8_t j = 0; j < 4; j++) { + pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); } + BLSPublicKeyShare pubKey(make_shared>(pubKeyVect), t, n); - for (int i = 0; i < t; i++) { - vector pubKeyVect; - for (uint8_t j = 0; j < 4; j++) { - pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); - } - BLSPublicKeyShare pubKey(make_shared>(pubKeyVect), t, n); + pubKeyShares[i + 1] = make_shared(pubKey); + } - pubKeyShares[i + 1] = make_shared(pubKey); - } - - // create pub key + // create pub key - BLSPublicKey blsPublicKey(make_shared>>(pubKeyShares), t, - n); + BLSPublicKey blsPublicKey( + make_shared>>(pubKeyShares), t, + n); - // sign verify a sample sig + // sign verify a sample sig - for (int i = 0; i < t; i++) { + for (int i = 0; i < t; i++) { - string blsName = "BLS_KEY" + polyNames[i].substr(4); - auto sigShare = make_shared(_zmqClient->blsSignMessageHash(blsName, hash, t, n)); - BLSSigShare sig(sigShare, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); + string blsName = "BLS_KEY" + polyNames[i].substr(4); + auto sigShare = make_shared( + _zmqClient->blsSignMessageHash(blsName, hash, t, n)); + BLSSigShare sig(sigShare, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); - auto pubKey = pubKeyShares[i+1]; + auto pubKey = pubKeyShares[i + 1]; - CHECK_STATE(pubKey->VerifySigWithHelper(hash_arr, make_shared(sig), t, n)); - } + CHECK_STATE(pubKey->VerifySigWithHelper( + hashArr, make_shared(sig), t, n)); + } - shared_ptr commonSig = sigShareSet.merge(); + shared_ptr commonSig = sigShareSet.merge(); - CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig, t, n)); + CHECK_STATE(blsPublicKey.VerifySigWithHelper(hashArr, commonSig)); - for (auto&& i : _ecdsaKeyNames) - cerr << i << endl; + for (auto &&i : _ecdsaKeyNames) + cerr << i << endl; - for (auto&& i : _blsKeyNames) - cerr << i << endl; + for (auto &&i : _blsKeyNames) + cerr << i << endl; } -int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key) { +int sessionKeyRecoverDH(const char *skey_str, const char *sshare, + char *common_key) { - int ret = -1; + int ret = -1; - SAFE_CHAR_BUF(pb_keyB_x, 65); - SAFE_CHAR_BUF(pb_keyB_y, 65); + 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(); + 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; + 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); - if (!common_key) { - mpz_clear(skey); - point_clear(pub_keyB); - point_clear(session_key); - - return ret; - } + return ret; + } - common_key[0] = 0; + common_key[0] = 0; - if (!skey_str) { - mpz_clear(skey); - point_clear(pub_keyB); - point_clear(session_key); - return ret; - } + 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); + if (!sshare) { + mpz_clear(skey); + point_clear(pub_keyB); + point_clear(session_key); - return ret; - } + return ret; + } - if (mpz_set_str(skey, skey_str, 16) == -1) { - mpz_clear(skey); - point_clear(pub_keyB); - point_clear(session_key); + if (mpz_set_str(skey, skey_str, 16) == -1) { + mpz_clear(skey); + point_clear(pub_keyB); + point_clear(session_key); - return ret; - } + return ret; + } - domain_parameters curve; - curve = domain_parameters_init(); - domain_parameters_load_curve(curve, secp256k1); + 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; - } + if (point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y) != 0) { + return ret; + } - point_multiplication(session_key, skey, pub_keyB, curve); + point_multiplication(session_key, skey, pub_keyB, curve); - SAFE_CHAR_BUF(arr_x, BUF_LEN); + 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)); + 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; + ret = 0; - mpz_clear(skey); - point_clear(pub_keyB); - point_clear(session_key); + mpz_clear(skey); + point_clear(pub_keyB); + point_clear(session_key); - return ret; + return ret; } -int xorDecryptDH(char *key, const char *cypher, vector& message) { +int xorDecryptDH(char *key, const char *cypher, vector &message) { - int ret = -1; + int ret = -1; - if (!cypher) { - return ret; - } + if (!cypher) { + return ret; + } - if (!key) { - return ret; - } + if (!key) { + return ret; + } - if (!message.data()) { - return ret; - } + if (!message.data()) { + return ret; + } - SAFE_CHAR_BUF(msg_bin,33) + SAFE_CHAR_BUF(msg_bin, 33) - SAFE_CHAR_BUF(key_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 key_length; + if (!hex2carray(key, &key_length, (uint8_t *)key_bin, 33)) { + return ret; + } - uint64_t cypher_length; + uint64_t cypher_length; - SAFE_CHAR_BUF(cypher_bin, 33); - if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) { - return ret; - } + 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]; - } + for (int i = 0; i < 32; i++) { + msg_bin[i] = cypher_bin[i] ^ key_bin[i]; + } - message = carray2Hex((unsigned char*) msg_bin, 32); + message = carray2Hex((unsigned char *)msg_bin, 32); - ret = 0; + ret = 0; - return ret; + return ret; } -int xorDecryptDHV2(char *key, const char *cypher, vector& message) { +int xorDecryptDHV2(char *key, const char *cypher, vector &message) { - int ret = -1; + int ret = -1; - if (!cypher) { - return ret; - } + if (!cypher) { + return ret; + } - if (!key) { - return ret; - } + if (!key) { + return ret; + } - if (!message.data()) { - return ret; - } + if (!message.data()) { + return ret; + } - SAFE_CHAR_BUF(msg_bin,33) + SAFE_CHAR_BUF(msg_bin, 33) - uint64_t cypher_length; + uint64_t cypher_length; - SAFE_CHAR_BUF(cypher_bin, 33); - if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) { - return ret; - } + 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]; - } + for (int i = 0; i < 32; i++) { + msg_bin[i] = cypher_bin[i] ^ (uint8_t)key[i]; + } - message = carray2Hex((unsigned char*) msg_bin, 32); + message = carray2Hex((unsigned char *)msg_bin, 32); - ret = 0; + ret = 0; - return ret; + return ret; } diff --git a/TestUtils.h b/TestUtils.h index 9c004d63..c921e450 100644 --- a/TestUtils.h +++ b/TestUtils.h @@ -24,22 +24,21 @@ #ifndef SGXWALLET_TESTUTILS_H #define SGXWALLET_TESTUTILS_H -#include -#include -#include +#include "abstractstubserver.h" +#include "secure_enclave_u.h" #include "sgxwallet_common.h" +#include "stubclient.h" #include "third_party/intel/create_enclave.h" -#include "secure_enclave_u.h" #include "third_party/intel/sgx_detect.h" +#include "zmq_src/ZMQClient.h" +#include #include -#include -#include #include -#include -#include "stubclient.h" #include -#include "zmq_src/ZMQClient.h" -#include "abstractstubserver.h" +#include +#include +#include +#include using namespace std; @@ -48,50 +47,50 @@ using namespace jsonrpc; class TestUtils { public: - static default_random_engine randGen; - - static string stringFromFr(libff::alt_bn128_Fr &el); + static default_random_engine randGen; - static string convertDecToHex(string dec, int numBytes = 32); + static string stringFromFr(libff::alt_bn128_Fr &el, size_t base = 10); - static void genTestKeys(); + static string convertDecToHex(string dec, int numBytes = 32); - static void resetDB(); + static void genTestKeys(); - static shared_ptr encryptTestKey(); + static void resetDB(); - static vector splitStringToFr(const char *coeffs, const char symbol); + static shared_ptr encryptTestKey(); - static vector splitStringTest(const char *coeffs, const char symbol); + static vector splitStringToFr(const char *coeffs, + const char symbol); - static libff::alt_bn128_G2 vectStringToG2(const vector &G2_str_vect); + static vector splitStringTest(const char *coeffs, const char symbol); - static void sendRPCRequest(); + static libff::alt_bn128_G2 vectStringToG2(const vector &G2_str_vect); - static void sendRPCRequestV2(); + static void sendRPCRequest(); - static void destroyEnclave(); + static void sendRPCRequestV2(); - static void doDKG(StubClient &c, int n, int t, - vector& _ecdsaKeyNames, vector& _blsKeyNames, - int schainID, int dkgID); + static void destroyEnclave(); - static void doDKGV2(StubClient &c, int n, int t, - vector& _ecdsaKeyNames, vector& _blsKeyNames, - int schainID, int dkgID); + static void doDKG(StubClient &c, int n, int t, vector &_ecdsaKeyNames, + vector &_blsKeyNames, int schainID, int dkgID); - static void doZMQBLS(shared_ptr _zmqClient, StubClient &c, int n, int t, - vector& _ecdsaKeyNames, vector& _blsKeyNames, - int schainID, int dkgID); + static void doDKGV2(StubClient &c, int n, int t, + vector &_ecdsaKeyNames, + vector &_blsKeyNames, int schainID, int dkgID); - static void sendRPCRequestZMQ(); + static void doZMQBLS(shared_ptr _zmqClient, StubClient &c, int n, + int t, vector &_ecdsaKeyNames, + vector &_blsKeyNames, int schainID, int dkgID); + static void sendRPCRequestZMQ(); }; -int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key); +int sessionKeyRecoverDH(const char *skey_str, const char *sshare, + char *common_key); -int xorDecryptDH(char *key, const char *cypher, vector& message); +int xorDecryptDH(char *key, const char *cypher, vector &message); -int xorDecryptDHV2(char *key, const char *cypher, vector& message); +int xorDecryptDHV2(char *key, const char *cypher, vector &message); -#endif //SGXWALLET_TESTW_H +#endif // SGXWALLET_TESTW_H diff --git a/VERSION b/VERSION index 6b4de0a4..abb16582 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.83.0 +1.9.0 \ No newline at end of file diff --git a/abstractCSRManagerServer.h b/abstractCSRManagerServer.h index 28dcb37b..770d3c15 100644 --- a/abstractCSRManagerServer.h +++ b/abstractCSRManagerServer.h @@ -24,34 +24,40 @@ #ifndef SGXD_ABSTRACTCSRMANAGERSERVER_H #define SGXD_ABSTRACTCSRMANAGERSERVER_H -#include #include +#include -class abstractCSRManagerServer : public jsonrpc::AbstractServer { +class abstractCSRManagerServer + : public jsonrpc::AbstractServer { public: - abstractCSRManagerServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer(conn, type) - { - this->bindAndAddMethod(jsonrpc::Procedure("getUnsignedCSRs", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &abstractCSRManagerServer::getUnsignedCSRsI); - this->bindAndAddMethod(jsonrpc::Procedure("signByHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"hash",jsonrpc::JSON_STRING, "status", jsonrpc::JSON_INTEGER, NULL), &abstractCSRManagerServer::signByHashI); - } - - inline virtual void getUnsignedCSRsI(const Json::Value &request, Json::Value &response) - { + abstractCSRManagerServer( + jsonrpc::AbstractServerConnector &conn, + jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) + : jsonrpc::AbstractServer(conn, type) { + this->bindAndAddMethod(jsonrpc::Procedure("getUnsignedCSRs", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, NULL), + &abstractCSRManagerServer::getUnsignedCSRsI); + this->bindAndAddMethod( + jsonrpc::Procedure("signByHash", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "hash", jsonrpc::JSON_STRING, + "status", jsonrpc::JSON_INTEGER, NULL), + &abstractCSRManagerServer::signByHashI); + } + + inline virtual void getUnsignedCSRsI(const Json::Value &request, + Json::Value &response) { (void)request; response = this->getUnsignedCSRs(); - } - inline virtual void signByHashI(const Json::Value &request, Json::Value &response) - { - response = this->signByHash( request["hash"].asString(), request["status"].asInt()); - } - - virtual Json::Value getUnsignedCSRs() = 0; - virtual Json::Value signByHash(const std::string& hash, int status) = 0; - + } + inline virtual void signByHashI(const Json::Value &request, + Json::Value &response) { + response = + this->signByHash(request["hash"].asString(), request["status"].asInt()); + } + + virtual Json::Value getUnsignedCSRs() = 0; + virtual Json::Value signByHash(const std::string &hash, int status) = 0; }; - - - - -#endif //SGXD_ABSTRACTCSRMANAGERSERVER_H +#endif // SGXD_ABSTRACTCSRMANAGERSERVER_H diff --git a/abstractinfoserver.h b/abstractinfoserver.h index d8fe815a..dcc21a5e 100644 --- a/abstractinfoserver.h +++ b/abstractinfoserver.h @@ -24,46 +24,57 @@ #ifndef ABSTRACTINFOSERVER_H #define ABSTRACTINFOSERVER_H -#include #include +#include -class AbstractInfoServer : public jsonrpc::AbstractServer -{ +class AbstractInfoServer : public jsonrpc::AbstractServer { public: - AbstractInfoServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer(conn, type) - { - this->bindAndAddMethod(jsonrpc::Procedure("getAllKeysInfo", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getAllKeysInfoI); - this->bindAndAddMethod(jsonrpc::Procedure("getLatestCreatedKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getLatestCreatedKeyI); - this->bindAndAddMethod(jsonrpc::Procedure("getServerConfiguration", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getServerConfigurationI); - this->bindAndAddMethod(jsonrpc::Procedure("isKeyExist", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractInfoServer::isKeyExistI); + AbstractInfoServer(jsonrpc::AbstractServerConnector &conn, + jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) + : jsonrpc::AbstractServer(conn, type) { + this->bindAndAddMethod(jsonrpc::Procedure("getAllKeysInfo", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, NULL), + &AbstractInfoServer::getAllKeysInfoI); + this->bindAndAddMethod(jsonrpc::Procedure("getLatestCreatedKey", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, NULL), + &AbstractInfoServer::getLatestCreatedKeyI); + this->bindAndAddMethod(jsonrpc::Procedure("getServerConfiguration", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, NULL), + &AbstractInfoServer::getServerConfigurationI); + this->bindAndAddMethod(jsonrpc::Procedure("isKeyExist", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "keyName", + jsonrpc::JSON_STRING, NULL), + &AbstractInfoServer::isKeyExistI); } - inline virtual void getAllKeysInfoI(const Json::Value &request, Json::Value &response) - { - response = this->getAllKeysInfo(); + inline virtual void getAllKeysInfoI(const Json::Value &request, + Json::Value &response) { + response = this->getAllKeysInfo(); } - inline virtual void getLatestCreatedKeyI(const Json::Value &request, Json::Value &response) - { - response = this->getLatestCreatedKey(); + inline virtual void getLatestCreatedKeyI(const Json::Value &request, + Json::Value &response) { + response = this->getLatestCreatedKey(); } - inline virtual void getServerConfigurationI(const Json::Value &request, Json::Value &response) - { - response = this->getServerConfiguration(); + inline virtual void getServerConfigurationI(const Json::Value &request, + Json::Value &response) { + response = this->getServerConfiguration(); } - inline virtual void isKeyExistI(const Json::Value &request, Json::Value &response) - { + inline virtual void isKeyExistI(const Json::Value &request, + Json::Value &response) { response = this->isKeyExist(request["keyName"].asString()); } - virtual Json::Value getAllKeysInfo() = 0; virtual Json::Value getLatestCreatedKey() = 0; virtual Json::Value getServerConfiguration() = 0; - virtual Json::Value isKeyExist(const std::string& key) = 0; - + virtual Json::Value isKeyExist(const std::string &key) = 0; }; #endif // ABSTRACTINFOSERVER_H diff --git a/abstractregserver.h b/abstractregserver.h index 62682ed5..02086521 100644 --- a/abstractregserver.h +++ b/abstractregserver.h @@ -24,32 +24,38 @@ #ifndef SGXD_ABSTRACTREGSERVER_H #define SGXD_ABSTRACTREGSERVER_H -#include #include +#include -class AbstractRegServer : public jsonrpc::AbstractServer -{ +class AbstractRegServer : public jsonrpc::AbstractServer { public: - AbstractRegServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer(conn, type) - { - this->bindAndAddMethod(jsonrpc::Procedure("signCertificate", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"certificate",jsonrpc::JSON_STRING, NULL), &AbstractRegServer::signCertificateI); - this->bindAndAddMethod(jsonrpc::Procedure("getCertificate", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"hash",jsonrpc::JSON_STRING, NULL), &AbstractRegServer::getCertificateI); + AbstractRegServer(jsonrpc::AbstractServerConnector &conn, + jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) + : jsonrpc::AbstractServer(conn, type) { + this->bindAndAddMethod( + jsonrpc::Procedure("signCertificate", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "certificate", + jsonrpc::JSON_STRING, NULL), + &AbstractRegServer::signCertificateI); + this->bindAndAddMethod(jsonrpc::Procedure("getCertificate", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "hash", + jsonrpc::JSON_STRING, NULL), + &AbstractRegServer::getCertificateI); } - inline virtual void signCertificateI(const Json::Value &request, Json::Value &response) - { - std::cerr << "signCertificateI in abstr server " << std::endl; - response = this->SignCertificate(request["certificate"].asString()); + inline virtual void signCertificateI(const Json::Value &request, + Json::Value &response) { + std::cerr << "signCertificateI in abstr server " << std::endl; + response = this->SignCertificate(request["certificate"].asString()); } - inline virtual void getCertificateI(const Json::Value &request, Json::Value &response) - { + inline virtual void getCertificateI(const Json::Value &request, + Json::Value &response) { response = this->GetCertificate(request["hash"].asString()); } - - virtual Json::Value SignCertificate(const std::string& cert) = 0; - virtual Json::Value GetCertificate(const std::string& hash) = 0; - + virtual Json::Value SignCertificate(const std::string &cert) = 0; + virtual Json::Value GetCertificate(const std::string &hash) = 0; }; #endif // SGXD_ABSTRACTREGSERVER_H \ No newline at end of file diff --git a/abstractstubserver.h b/abstractstubserver.h index b2803eac..fa30a1a5 100644 --- a/abstractstubserver.h +++ b/abstractstubserver.h @@ -21,7 +21,6 @@ @date 2019 */ - /** * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY! */ @@ -31,169 +30,361 @@ #include -class AbstractStubServer : public jsonrpc::AbstractServer -{ - public: - AbstractStubServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer(conn, type) - { - 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); - - this->bindAndAddMethod(jsonrpc::Procedure("generateDKGPoly", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::generateDKGPolyI); - this->bindAndAddMethod(jsonrpc::Procedure("getVerificationVector", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName", jsonrpc::JSON_STRING, "t", jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getVerificationVectorI); - this->bindAndAddMethod(jsonrpc::Procedure("getSecretShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"publicKeys",jsonrpc::JSON_ARRAY, "n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getSecretShareI); - this->bindAndAddMethod(jsonrpc::Procedure("dkgVerification", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::dkgVerificationI); - this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "polyName", jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::createBLSPrivateKeyI); - this->bindAndAddMethod(jsonrpc::Procedure("getBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getBLSPublicKeyShareI); - this->bindAndAddMethod(jsonrpc::Procedure("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,"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); - this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKeyV2", 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::createBLSPrivateKeyV2I); - - this->bindAndAddMethod(jsonrpc::Procedure("getDecryptionShares", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING,"publicDecryptionValues",jsonrpc::JSON_ARRAY, NULL), &AbstractStubServer::getDecryptionSharesI); - } - - inline virtual void importBLSKeyShareI(const Json::Value &request, Json::Value &response) - { - response = this->importBLSKeyShare( request["keyShare"].asString(), request["keyShareName"].asString()); - } - inline virtual void blsSignMessageHashI(const Json::Value &request, Json::Value &response) - { - 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; - response = this->generateECDSAKey(); - } - inline virtual void getPublicECDSAKeyI(const Json::Value &request, Json::Value &response) - { - response = this->getPublicECDSAKey(request["keyName"].asString()); - } - inline virtual void ecdsaSignMessageHashI(const Json::Value &request, Json::Value &response) - { - response = this->ecdsaSignMessageHash(request["base"].asInt(), request["keyName"].asString(), request["messageHash"].asString()); - } - - inline virtual void generateDKGPolyI(const Json::Value &request, Json::Value &response) - { - response = this->generateDKGPoly(request["polyName"].asString(), request["t"].asInt()); - } - inline virtual void getVerificationVectorI(const Json::Value &request, Json::Value &response) - { - response = this->getVerificationVector(request["polyName"].asString(), request["t"].asInt()); - } - inline virtual void getSecretShareI(const Json::Value &request, Json::Value &response) - { - response = this->getSecretShare(request["polyName"].asString(), request["publicKeys"], request["t"].asInt(),request["n"].asInt()); - } - inline virtual void dkgVerificationI(const Json::Value &request, Json::Value &response) - { - response = this->dkgVerification(request["publicShares"].asString(), request["ethKeyName"].asString(), request["secretShare"].asString(), request["t"].asInt(), request["n"].asInt(), request["index"].asInt()); - } - inline virtual void createBLSPrivateKeyI(const Json::Value &request, Json::Value &response) - { - response = this->createBLSPrivateKey(request["blsKeyName"].asString(), request["ethKeyName"].asString(), request["polyName"].asString(),request["secretShare"].asString(),request["t"].asInt(), request["n"].asInt()); - } - inline virtual void getBLSPublicKeyShareI(const Json::Value &request, Json::Value &response) - { - response = this->getBLSPublicKeyShare(request["blsKeyName"].asString()); - } - inline virtual void calculateAllBLSPublicKeysI(const Json::Value& request, Json::Value& response) { - response = this->calculateAllBLSPublicKeys(request["publicShares"], request["t"].asInt(), request["n"].asInt()); - } - inline virtual void complaintResponseI(const Json::Value &request, Json::Value &response) - { - 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) - { - response = this->multG2(request["x"].asString()); - } - inline virtual void isPolyExistsI(const Json::Value &request, Json::Value &response) - { - response = this->isPolyExists(request["polyName"].asString()); - } - - inline virtual void getServerStatusI(const Json::Value &request, Json::Value &response) - { - (void)request; - response = this->getServerStatus(); - } - - inline virtual void getServerVersionI(const Json::Value &request, Json::Value &response) - { - (void)request; - response = this->getServerVersion(); - } - - inline virtual void deleteBlsKeyI(const Json::Value& request, Json::Value& response) { - 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()); - } - inline virtual void createBLSPrivateKeyV2I(const Json::Value &request, Json::Value &response) - { - response = this->createBLSPrivateKeyV2(request["blsKeyName"].asString(), request["ethKeyName"].asString(), request["polyName"].asString(),request["secretShare"].asString(),request["t"].asInt(), request["n"].asInt()); - } - - inline virtual void getDecryptionSharesI(const Json::Value &request, Json::Value &response) - { - response = this->getDecryptionShares(request["blsKeyName"].asString(), request["publicDecryptionValues"]); - } - - 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; - - virtual Json::Value generateDKGPoly(const std::string& polyName, int t) = 0; - virtual Json::Value getVerificationVector(const std::string& polyName, int t) = 0; - virtual Json::Value getSecretShare(const std::string& polyName, const Json::Value& publicKeys, int t, int n) = 0; - virtual Json::Value dkgVerification( const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index) = 0; - virtual Json::Value createBLSPrivateKey(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n) = 0; - virtual Json::Value getBLSPublicKeyShare(const std::string& blsKeyName) = 0; - virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) = 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; - virtual Json::Value createBLSPrivateKeyV2(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0; - - virtual Json::Value getDecryptionShares(const std::string& KeyName, const Json::Value& publicDecryptionValues) = 0; +class AbstractStubServer : public jsonrpc::AbstractServer { +public: + AbstractStubServer(jsonrpc::AbstractServerConnector &conn, + jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) + : jsonrpc::AbstractServer(conn, type) { + 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); + + this->bindAndAddMethod( + jsonrpc::Procedure( + "generateDKGPoly", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, + "polyName", jsonrpc::JSON_STRING, "t", jsonrpc::JSON_INTEGER, NULL), + &AbstractStubServer::generateDKGPolyI); + this->bindAndAddMethod(jsonrpc::Procedure("getVerificationVector", + jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "polyName", + jsonrpc::JSON_STRING, "t", + jsonrpc::JSON_INTEGER, NULL), + &AbstractStubServer::getVerificationVectorI); + this->bindAndAddMethod( + jsonrpc::Procedure( + "getSecretShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, + "polyName", jsonrpc::JSON_STRING, "publicKeys", jsonrpc::JSON_ARRAY, + "n", jsonrpc::JSON_INTEGER, "t", jsonrpc::JSON_INTEGER, NULL), + &AbstractStubServer::getSecretShareI); + this->bindAndAddMethod( + jsonrpc::Procedure( + "dkgVerification", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, + "publicShares", jsonrpc::JSON_STRING, "ethKeyName", + jsonrpc::JSON_STRING, "secretShare", jsonrpc::JSON_STRING, "t", + jsonrpc::JSON_INTEGER, "n", jsonrpc::JSON_INTEGER, "index", + jsonrpc::JSON_INTEGER, NULL), + &AbstractStubServer::dkgVerificationI); + this->bindAndAddMethod( + jsonrpc::Procedure( + "createBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "blsKeyName", jsonrpc::JSON_STRING, + "ethKeyName", jsonrpc::JSON_STRING, "polyName", + jsonrpc::JSON_STRING, "secretShare", jsonrpc::JSON_STRING, "t", + jsonrpc::JSON_INTEGER, "n", jsonrpc::JSON_INTEGER, NULL), + &AbstractStubServer::createBLSPrivateKeyI); + this->bindAndAddMethod( + jsonrpc::Procedure("getBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "blsKeyName", + jsonrpc::JSON_STRING, NULL), + &AbstractStubServer::getBLSPublicKeyShareI); + this->bindAndAddMethod( + jsonrpc::Procedure("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, "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); + this->bindAndAddMethod( + jsonrpc::Procedure( + "createBLSPrivateKeyV2", 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::createBLSPrivateKeyV2I); + + this->bindAndAddMethod( + jsonrpc::Procedure("getDecryptionShares", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "blsKeyName", + jsonrpc::JSON_STRING, "publicDecryptionValues", + jsonrpc::JSON_ARRAY, NULL), + &AbstractStubServer::getDecryptionSharesI); + + this->bindAndAddMethod( + jsonrpc::Procedure("popProve", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "blsKeyName", + jsonrpc::JSON_STRING, NULL), + &AbstractStubServer::popProveI); + this->bindAndAddMethod( + jsonrpc::Procedure("generateBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, + jsonrpc::JSON_OBJECT, "blsKeyName", + jsonrpc::JSON_STRING, NULL), + &AbstractStubServer::generateBLSPrivateKeyI); + } + + inline virtual void importBLSKeyShareI(const Json::Value &request, + Json::Value &response) { + response = this->importBLSKeyShare(request["keyShare"].asString(), + request["keyShareName"].asString()); + } + inline virtual void blsSignMessageHashI(const Json::Value &request, + Json::Value &response) { + 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; + response = this->generateECDSAKey(); + } + inline virtual void getPublicECDSAKeyI(const Json::Value &request, + Json::Value &response) { + response = this->getPublicECDSAKey(request["keyName"].asString()); + } + inline virtual void ecdsaSignMessageHashI(const Json::Value &request, + Json::Value &response) { + response = this->ecdsaSignMessageHash(request["base"].asInt(), + request["keyName"].asString(), + request["messageHash"].asString()); + } + + inline virtual void generateDKGPolyI(const Json::Value &request, + Json::Value &response) { + response = this->generateDKGPoly(request["polyName"].asString(), + request["t"].asInt()); + } + inline virtual void getVerificationVectorI(const Json::Value &request, + Json::Value &response) { + response = this->getVerificationVector(request["polyName"].asString(), + request["t"].asInt()); + } + inline virtual void getSecretShareI(const Json::Value &request, + Json::Value &response) { + response = this->getSecretShare(request["polyName"].asString(), + request["publicKeys"], request["t"].asInt(), + request["n"].asInt()); + } + inline virtual void dkgVerificationI(const Json::Value &request, + Json::Value &response) { + response = this->dkgVerification( + request["publicShares"].asString(), request["ethKeyName"].asString(), + request["secretShare"].asString(), request["t"].asInt(), + request["n"].asInt(), request["index"].asInt()); + } + inline virtual void createBLSPrivateKeyI(const Json::Value &request, + Json::Value &response) { + response = this->createBLSPrivateKey( + request["blsKeyName"].asString(), request["ethKeyName"].asString(), + request["polyName"].asString(), request["secretShare"].asString(), + request["t"].asInt(), request["n"].asInt()); + } + inline virtual void getBLSPublicKeyShareI(const Json::Value &request, + Json::Value &response) { + response = this->getBLSPublicKeyShare(request["blsKeyName"].asString()); + } + inline virtual void calculateAllBLSPublicKeysI(const Json::Value &request, + Json::Value &response) { + response = this->calculateAllBLSPublicKeys( + request["publicShares"], request["t"].asInt(), request["n"].asInt()); + } + inline virtual void complaintResponseI(const Json::Value &request, + Json::Value &response) { + 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) { + response = this->multG2(request["x"].asString()); + } + inline virtual void isPolyExistsI(const Json::Value &request, + Json::Value &response) { + response = this->isPolyExists(request["polyName"].asString()); + } + + inline virtual void getServerStatusI(const Json::Value &request, + Json::Value &response) { + (void)request; + response = this->getServerStatus(); + } + + inline virtual void getServerVersionI(const Json::Value &request, + Json::Value &response) { + (void)request; + response = this->getServerVersion(); + } + + inline virtual void deleteBlsKeyI(const Json::Value &request, + Json::Value &response) { + 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()); + } + inline virtual void createBLSPrivateKeyV2I(const Json::Value &request, + Json::Value &response) { + response = this->createBLSPrivateKeyV2( + request["blsKeyName"].asString(), request["ethKeyName"].asString(), + request["polyName"].asString(), request["secretShare"].asString(), + request["t"].asInt(), request["n"].asInt()); + } + + inline virtual void getDecryptionSharesI(const Json::Value &request, + Json::Value &response) { + response = this->getDecryptionShares(request["blsKeyName"].asString(), + request["publicDecryptionValues"]); + } + + inline virtual void popProveI(const Json::Value &request, + Json::Value &response) { + response = this->popProve(request["blsKeyName"].asString()); + } + + inline virtual void generateBLSPrivateKeyI(const Json::Value &request, + Json::Value &response) { + response = this->generateBLSPrivateKey(request["blsKeyName"].asString()); + } + + 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; + + virtual Json::Value generateDKGPoly(const std::string &polyName, int t) = 0; + virtual Json::Value getVerificationVector(const std::string &polyName, + int t) = 0; + virtual Json::Value getSecretShare(const std::string &polyName, + const Json::Value &publicKeys, int t, + int n) = 0; + virtual Json::Value dkgVerification(const std::string &publicShares, + const std::string ðKeyName, + const std::string &SecretShare, int t, + int n, int index) = 0; + virtual Json::Value createBLSPrivateKey(const std::string &blsKeyName, + const std::string ðKeyName, + 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 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 ðKeyName, + const std::string &SecretShare, int t, + int n, int index) = 0; + virtual Json::Value createBLSPrivateKeyV2(const std::string &blsKeyName, + const std::string ðKeyName, + const std::string &polyName, + const std::string &SecretShare, + int t, int n) = 0; + + virtual Json::Value + getDecryptionShares(const std::string &KeyName, + const Json::Value &publicDecryptionValues) = 0; + + virtual Json::Value popProve(const std::string &blsKeyName) = 0; + virtual Json::Value generateBLSPrivateKey(const std::string &blsKeyName) = 0; }; -#endif //JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_ +#endif // JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_ diff --git a/clean.sh b/clean.sh new file mode 100755 index 00000000..99b5aa58 --- /dev/null +++ b/clean.sh @@ -0,0 +1,6 @@ +rm -rf *.o +rm -rf .deps/*.Po +rm -rf secure_enclave/*.o +rm -rf secure_enclave/.deps/*.Po +rm -rf Makefile Makefile.in +rm -rf secure_enclave/Makefile \ No newline at end of file diff --git a/common.h b/common.h index 37942b88..938fae86 100644 --- a/common.h +++ b/common.h @@ -21,135 +21,149 @@ @date 2020 */ - #ifndef SGXWALLET_COMMON_H #define SGXWALLET_COMMON_H using namespace std; -#include +#include +#include +#include +#include +#include #include +#include #include #include -#include -#include +#include +#include #include -#include -#include -#include -#include +#include +#include #include -#include -#include -#include -#include - +#include -#include "secure_enclave/Verify.h" #include "InvalidStateException.h" #include "SGXException.h" +#include "secure_enclave/Verify.h" -#define SAFE_FREE(__POINTER__) {if (__POINTER__) {free(__POINTER__); __POINTER__ = NULL;}} +#define SAFE_FREE(__POINTER__) \ + { \ + if (__POINTER__) { \ + free(__POINTER__); \ + __POINTER__ = NULL; \ + } \ + } inline std::string className(const std::string &prettyFunction) { - size_t colons = prettyFunction.find("::"); - if (colons == std::string::npos) - return "::"; - size_t begin = prettyFunction.substr(0, colons).rfind(" ") + 1; - size_t end = colons - begin; + size_t colons = prettyFunction.find("::"); + if (colons == std::string::npos) + return "::"; + size_t begin = prettyFunction.substr(0, colons).rfind(" ") + 1; + size_t end = colons - begin; - return prettyFunction.substr(begin, end); + return prettyFunction.substr(begin, end); } -#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ ) +#define __CLASS_NAME__ className(__PRETTY_FUNCTION__) #include inline void print_stack(int _line) { - void *array[10]; - size_t size; + void *array[10]; + size_t size; - // get void*'s for all entries on the stack - size = backtrace(array, 10); + // get void*'s for all entries on the stack + size = backtrace(array, 10); - // print out all the frames to stderr - fprintf(stderr, "Backtrace on line %d: \n", _line); - backtrace_symbols_fd(array, size, STDERR_FILENO); + // print out all the frames to stderr + fprintf(stderr, "Backtrace on line %d: \n", _line); + backtrace_symbols_fd(array, size, STDERR_FILENO); } -inline int parseLine(char* line) { - // This assumes that a digit will be found and the line ends in " Kb". - int i = strlen(line); - const char* p = line; - while (*p <'0' || *p > '9') p++; - line[i-3] = '\0'; - i = atoi(p); - return i; +inline int parseLine(char *line) { + // This assumes that a digit will be found and the line ends in " Kb". + int i = strlen(line); + const char *p = line; + while (*p < '0' || *p > '9') + p++; + line[i - 3] = '\0'; + i = atoi(p); + return i; } -inline int getValue() { //Note: this value is in KB! - FILE* file = fopen("/proc/self/status", "r"); - int result = -1; - char line[128]; +inline int getValue() { // Note: this value is in KB! + FILE *file = fopen("/proc/self/status", "r"); + int result = -1; + char line[128]; - while (fgets(line, 128, file) != NULL){ - if (strncmp(line, "VmRSS:", 6) == 0){ - result = parseLine(line); - break; - } + while (fgets(line, 128, file) != NULL) { + if (strncmp(line, "VmRSS:", 6) == 0) { + result = parseLine(line); + break; } - fclose(file); - return result; + } + fclose(file); + return result; } -#define CHECK_STATE(_EXPRESSION_) \ - if (!(_EXPRESSION_)) { \ - auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + std::string(__FILE__) + ":" + std::to_string(__LINE__); \ - \ - BOOST_THROW_EXCEPTION(SGXException(-100, string(__CLASS_NAME__) + ":" + __msg__));} - -#define CHECK_STATE2(_EXPRESSION_, __STATUS__) \ - if (!(_EXPRESSION_)) { \ - auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + std::string(__FILE__) + ":" + std::to_string(__LINE__); \ - \ - BOOST_THROW_EXCEPTION(SGXException(__STATUS__, string(__CLASS_NAME__) + ":" + __msg__));} - +#define CHECK_STATE(_EXPRESSION_) \ + if (!(_EXPRESSION_)) { \ + auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + \ + std::string(__FILE__) + ":" + std::to_string(__LINE__); \ + \ + BOOST_THROW_EXCEPTION( \ + SGXException(-100, string(__CLASS_NAME__) + ":" + __msg__)); \ + } + +#define CHECK_STATE2(_EXPRESSION_, __STATUS__) \ + if (!(_EXPRESSION_)) { \ + auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + \ + std::string(__FILE__) + ":" + std::to_string(__LINE__); \ + \ + BOOST_THROW_EXCEPTION( \ + SGXException(__STATUS__, string(__CLASS_NAME__) + ":" + __msg__)); \ + } #define HANDLE_TRUSTED_FUNCTION_ERROR(__STATUS__, __ERR_STATUS__, __ERR_MSG__) \ -if (__STATUS__ != SGX_SUCCESS) { \ -string __ERR_STRING__ = string("SGX enclave call to ") + \ - __FUNCTION__ + " failed with status:" \ - + to_string(__STATUS__) + \ - " Err message:" + __ERR_MSG__; \ -BOOST_THROW_EXCEPTION(SGXException(-102, string(__ERR_STRING__))); \ -}\ -\ -if (__ERR_STATUS__ != 0) {\ -string __ERR_STRING__ = string("SGX enclave call to ") +\ - __FUNCTION__ + " failed with errStatus:" + \ - to_string(__ERR_STATUS__) + \ - " Err message:" + __ERR_MSG__;\ -BOOST_THROW_EXCEPTION(runtime_error(__ERR_STRING__)); \ -} - - -#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__); -#define SAFE_UINT8_BUF(__X__, __Y__) ;uint8_t __X__ [ __Y__ ]; memset(__X__, 0, __Y__); + if (__STATUS__ != SGX_SUCCESS) { \ + string __ERR_STRING__ = string("SGX enclave call to ") + __FUNCTION__ + \ + " failed with status:" + to_string(__STATUS__) + \ + " Err message:" + __ERR_MSG__; \ + BOOST_THROW_EXCEPTION(SGXException(-102, string(__ERR_STRING__))); \ + } \ + \ + if (__ERR_STATUS__ != 0) { \ + string __ERR_STRING__ = \ + string("SGX enclave call to ") + __FUNCTION__ + \ + " failed with errStatus:" + to_string(__ERR_STATUS__) + \ + " Err message:" + __ERR_MSG__; \ + BOOST_THROW_EXCEPTION(runtime_error(__ERR_STRING__)); \ + } + +#define SAFE_CHAR_BUF(__X__, __Y__) \ + ; \ + char __X__[__Y__]; \ + memset(__X__, 0, __Y__); +#define SAFE_UINT8_BUF(__X__, __Y__) \ + ; \ + uint8_t __X__[__Y__]; \ + memset(__X__, 0, __Y__); // Copy from libconsensus -inline string exec( const char* cmd ) { - CHECK_STATE( cmd ); - std::array< char, 128 > buffer; - std::string result; - std::unique_ptr< FILE, decltype( &pclose ) > pipe( popen( cmd, "r" ), pclose ); - if ( !pipe ) { - BOOST_THROW_EXCEPTION( std::runtime_error( "popen() failed!" ) ); - } - while ( fgets( buffer.data(), buffer.size(), pipe.get() ) != nullptr ) { - result += buffer.data(); - } - return result; +inline string exec(const char *cmd) { + CHECK_STATE(cmd); + std::array buffer; + std::string result; + std::unique_ptr pipe(popen(cmd, "r"), pclose); + if (!pipe) { + BOOST_THROW_EXCEPTION(std::runtime_error("popen() failed!")); + } + while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { + result += buffer.data(); + } + return result; } #include @@ -158,8 +172,9 @@ extern std::shared_timed_mutex sgxInitMutex; extern uint64_t initTime; #define LOCK(__X__) std::lock_guard __LOCK__(__X__); -#define READ_LOCK(__X__) std::shared_lock __LOCK__(__X__); -#define WRITE_LOCK(__X__) std::unique_lock __LOCK__(__X__); - +#define READ_LOCK(__X__) \ + std::shared_lock __LOCK__(__X__); +#define WRITE_LOCK(__X__) \ + std::unique_lock __LOCK__(__X__); -#endif //SGXWALLET_COMMON_H +#endif // SGXWALLET_COMMON_H diff --git a/docker/check_firewall.py b/docker/check_firewall.py new file mode 100755 index 00000000..bfaa4ef0 --- /dev/null +++ b/docker/check_firewall.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 + + +import requests +import re +import torpy + +from torpy import TorClient + + +def get_my_external_ip(): + try: + res = requests.get("http://checkip.dyndns.org/") + myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group() + return myIp + except: + return "" + +print("Analyzing firewall security.") +print("Determining external IP address") + +ip = get_my_external_ip() + +if (ip == ""): + print("sgxwallet does not have an external IP") + print("No firewall problems detected.") + exit(0) + +print("sgxwallet has the following external IP: " + ip) + +try: + with TorClient() as tor: + # Choose random guard node and create 3-hops circuit + print("Connecting to TOR network ..."); + print("Please ignore error messages, as we are attempting to connect to the TOR network ..."); + with tor.create_circuit(1) as circuit: + print("Connected to TOR network. Connecting to sgxwallet from a random external IP." + " This may take up to a minute.") + # Create tor stream to host + with circuit.create_stream((ip, 1027)) as stream: + print("SECURITY PROBLEM: Could connect to port 1027 of sgxwallet " + ip + " from a random external IP") + print("Firewall is not working properly. Fix the firewall and then start sgx wallet") + exit(1) +except: + print("Analysis complete. No firewall problems detected.") + exit(0) diff --git a/docker/start.sh b/docker/start.sh index cd8eeffe..49307ff6 100755 --- a/docker/start.sh +++ b/docker/start.sh @@ -46,7 +46,7 @@ echo "Test run requested" sleep 5 ./testw.py else -sleep 3 +/usr/src/sdk/check_firewall.py ./sgxwallet $1 $2 $3 $4 $5 $6 fi diff --git a/docs/building.md b/docs/building.md index e2549ed0..da081ac6 100644 --- a/docs/building.md +++ b/docs/building.md @@ -2,7 +2,20 @@ # Building SGX wallet from source -## Build and install Intel SGX SDK +# + +## Clone this repository and its submodules + +`git clone --recurse-submodules https://github.com/skalenetwork/sgxwallet.git` + +## Install required debian packages + +```bash +cd scripts; sudo ./install_packages.sh; cd .. +``` + + +# Build and install Intel SGX SDK We are currently using SGX SDK version 2.13. @@ -15,22 +28,12 @@ cd linux-sgx make preparation sudo make sdk_install_pkg_no_mitigation cd /opt/intel -sudo sh -c 'echo yes | /linux-sgx/linux/installer/bin/sgx_linux_x64_sdk_*.bin +sudo sh -c 'echo yes | /linux-sgx/linux/installer/bin/sgx_linux_x64_sdk_*.bin' sudo make psw_install_pkg sudo cp /linux-sgx/linux/installer/bin/sgx_linux_x64_psw*.bin . sudo ./sgx_linux_x64_psw*.bin --no-start-aesm ``` -## Clone this repository and its submodules - -`git clone --recurse-submodules https://github.com/skalenetwork/sgxwallet.git` - -## Install required debian packages - -```bash -cd scripts; sudo ./install_packages.sh; cd .. -``` - ## Build dependencies Dependencies only need to be built once. @@ -64,6 +67,15 @@ Note: to run in simulation mode, add --enable-sgx-simulation flag when you run c make ``` +## Format code + +To format code run + +```bash +cd scripts +python3 format.py +``` + ## Build base Docker container The base container includes software common to hardware mode and simulation mode. diff --git a/docs/grep-certificates.md b/docs/grep-certificates.md new file mode 100644 index 00000000..9d311515 --- /dev/null +++ b/docs/grep-certificates.md @@ -0,0 +1,7 @@ +# How to check when the certificates stored on sgxwallet were created +- Download the file https://github.com/skalenetwork/sgxwallet/blob/develop/scripts/grep_certificates.py and put it in sgxwallet repository directory on your machine. +- Go to sgxwallet repository directory. +- Run `python3 grep_certificates.py PATH_TO_SGXWALLET_DB_FOLDER`. PATH_TO_SGXWALLET_DB_FOLDER - path (either absolute or relative) to the `sgx_data` directory where sgxwallet db is stored. For example, `/root/sgxwallet/run_sgx/sgx_data` or `run_sgx/sgx_data` +- The script will output the dates when every certificate was created. +- Go to skale-node and run `cat .skale/node_data/sgx_certs/sgx.crt | grep "Not Before"`. +- Ensure that the output of the last command exists in the list from step 3 and it is the latest certificate there! \ No newline at end of file diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 00000000..6a0d30eb --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,21 @@ +SGWallet performance measured on version 1.83.0-stable.1 for signed mode and 1.83.0-beta.5 for simulation mode on Intel Core i7-10510U CPU @ 1.80 GHz * 8. + +BLS sign operations: +- simulation mode: + - 50 BLS sign operations / per sec if sending requests via 5 threads + - 62 BLS sign operations / per sec if sending requests via 10 threads + - 69 BLS sign operations / per sec if sending requests via 15 threads +- release mode: + - 43 BLS sign operations / per sec if sending requests via 5 threads + - 52 BLS sign operations / per sec if sending requests via 10 threads + - 60 BLS sign operations / per sec if sending requests via 15 threads + +ECDSA sign operations: +- simulation mode: + - 47 ECDSA sign operations / per sec if sending requests via 5 threads + - 50 ECDSA sign operations / per sec if sending requests via 10 threads + - 52 ECDSA sign operations / per sec if sending requests via 15 threads +- release mode: + - 37 ECDSA sign operations / per sec if sending requests via 5 threads + - 48 ECDSA sign operations / per sec if sending requests via 10 threads + - 52 ECDSA sign operations / per sec if sending requests via 15 threads \ No newline at end of file diff --git a/intel-sgx-ssl b/intel-sgx-ssl index a70a1b07..f9c1f96c 160000 --- a/intel-sgx-ssl +++ b/intel-sgx-ssl @@ -1 +1 @@ -Subproject commit a70a1b07fd1bbfd3797197654297f8aa010e269a +Subproject commit f9c1f96c3c3cf7e38a7b5c28e449f009f9e49417 diff --git a/libBLS b/libBLS index 75972a81..d9f468fa 160000 --- a/libBLS +++ b/libBLS @@ -1 +1 @@ -Subproject commit 75972a810b8b1422004443028beedfef2288be50 +Subproject commit d9f468fae5a99d7a1d13974dc2a58626b4120e63 diff --git a/linux-sgx-driver b/linux-sgx-driver index 75bf89f7..54c9c4c1 160000 --- a/linux-sgx-driver +++ b/linux-sgx-driver @@ -1 +1 @@ -Subproject commit 75bf89f7d6dd4598b9f8148bd6374a407f37105c +Subproject commit 54c9c4c1fe30f459abe7c4b9c153ed2967973c22 diff --git a/scripts/build_deps.py b/scripts/build_deps.py index 2e204583..8456cfd3 100755 --- a/scripts/build_deps.py +++ b/scripts/build_deps.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # ------------------------------------------------------------------------------ # Copyright (C) 2018-Present SKALE Labs @@ -94,7 +94,7 @@ print("Install Linux SDK"); os.chdir(SCRIPTS_DIR) -assert subprocess.call(["bash", "-c", "./sgx_linux_x64_sdk_2.13.100.4.bin --prefix=" + topDir + "/sgx-sdk-build"]) == 0 +assert subprocess.call(["bash", "-c", "./sgx_linux_x64_sdk_2.19.100.3.bin --prefix=" + topDir + "/sgx-sdk-build"]) == 0 print("Make GMP"); diff --git a/scripts/build_sgx.sh b/scripts/build_sgx.sh new file mode 100755 index 00000000..68075d54 --- /dev/null +++ b/scripts/build_sgx.sh @@ -0,0 +1,9 @@ +# DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +# PROJECT_DIR=$(dirname $DIR) + +# cd $PROJECT_DIR/scripts && sudo ./install_packages.sh +# ./build_deps.py && cd $PROJECT_DIR +# source sgx-sdk-build/sgxsdk/environment +./autoconf.bash +./configure --enable-sgx-simulation +make -j4 diff --git a/scripts/docker_test.py b/scripts/docker_test.py index 54857a8f..bdb78322 100755 --- a/scripts/docker_test.py +++ b/scripts/docker_test.py @@ -31,7 +31,7 @@ DOCKER_FILE_NAME = sys.argv[1] IMAGE_NAME = sys.argv[2] -TAG_POSTFIX = "latest_commit" +TAG_POSTFIX = sys.argv[3] FULL_IMAGE_NAME = "skalenetwork/" + IMAGE_NAME +":" + TAG_POSTFIX diff --git a/scripts/format.py b/scripts/format.py new file mode 100644 index 00000000..91282720 --- /dev/null +++ b/scripts/format.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 + +import os +import subprocess + +os.chdir("..") +topDir = os.getcwd() +print(topDir) + +cpp_extensions = (".cpp", ".cxx", ".cc", ".h", ".hpp", ".hxx", ".ipp") +src_dirs = (topDir, topDir + "/zmq_src", topDir + "/secure_enclave") + +for directory in src_dirs: + print(directory) + for file in os.listdir(directory): + if os.path.isfile(os.path.join(directory,file)) and file.endswith(cpp_extensions): + print(file) + os.system("clang-format-14 -i -style=file " + directory + "/" + file) diff --git a/scripts/grep_certificates.py b/scripts/grep_certificates.py new file mode 100644 index 00000000..89d93003 --- /dev/null +++ b/scripts/grep_certificates.py @@ -0,0 +1,43 @@ +import os +import re +import sys + +def main(): + if len(sys.argv) != 2: + print("Wrong number of command line arguments: need exactly one") + exit(1) + + path = sys.argv[1] + if not os.path.exists(path): + print("No such file or directory: ", path) + exit(2) + + certs_path = os.path.join(path, "cert_data", "new_certs") + if not os.path.exists(certs_path): + print("No such file or directory: ", certs_path) + exit(3) + + if len(os.listdir(certs_path)) == 0: + print("Empty certificates directory. Nothing to review.") + return + + print("Total number of elements in folder:", len(os.listdir(certs_path))) + for entity in os.listdir(certs_path): + print("Reviewing", entity) + entity_path = os.path.join(certs_path, entity) + if not os.path.isfile(entity_path): + print("Not a regular file. Skipping.") + continue + _, extension = os.path.splitext(entity_path) + if extension != '.pem': + print("Not a ssl certificate file. Skipping.") + continue + with open(entity_path,"r") as file_one: + pattern = "Not Before" + for line in file_one: + if re.search(pattern, line): + print(line) + break + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/scripts/install_packages.sh b/scripts/install_packages.sh index 3354434e..886e14ef 100755 --- a/scripts/install_packages.sh +++ b/scripts/install_packages.sh @@ -1,5 +1,5 @@ #!/bin/bash sudo apt update -sudo apt install -y build-essential make gcc g++ yasm python libprotobuf10 flex bison automake -sudo apt install -y ccache cmake ccache autoconf texinfo libgcrypt20-dev libgnutls28-dev libtool pkg-config +sudo apt install -y build-essential make gcc g++ yasm python flex bison automake +sudo apt install -y ccache cmake ccache autoconf texinfo libgcrypt20-dev libgnutls28-dev libtool pkg-config glibc-tools sudo apt install -y ocaml ocamlbuild diff --git a/scripts/sgx_linux_x64_driver_2.11.0_0373e2e.bin b/scripts/sgx_linux_x64_driver_2.11.0_0373e2e.bin deleted file mode 100755 index 7b8ce2a4..00000000 Binary files a/scripts/sgx_linux_x64_driver_2.11.0_0373e2e.bin and /dev/null differ diff --git a/scripts/sgx_linux_x64_driver_2.11.54c9c4c.bin b/scripts/sgx_linux_x64_driver_2.11.54c9c4c.bin new file mode 100644 index 00000000..266d9051 Binary files /dev/null and b/scripts/sgx_linux_x64_driver_2.11.54c9c4c.bin differ diff --git a/scripts/sgx_linux_x64_sdk_2.13.100.4.bin b/scripts/sgx_linux_x64_sdk_2.19.100.3.bin similarity index 53% rename from scripts/sgx_linux_x64_sdk_2.13.100.4.bin rename to scripts/sgx_linux_x64_sdk_2.19.100.3.bin index 826bb4fd..cd4e8789 100755 Binary files a/scripts/sgx_linux_x64_sdk_2.13.100.4.bin and b/scripts/sgx_linux_x64_sdk_2.19.100.3.bin differ diff --git a/secure_enclave/AESUtils.c b/secure_enclave/AESUtils.c index 10bcce25..bf34369c 100644 --- a/secure_enclave/AESUtils.c +++ b/secure_enclave/AESUtils.c @@ -84,26 +84,26 @@ int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrBufLen, unsig return status; } -int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen, +int AES_decrypt(uint8_t *encrMessage, uint64_t length, char *message, uint64_t msgLen, uint8_t *type, uint8_t* exportable){ if (!message) { - LOG_ERROR("Null message in AES_encrypt"); + LOG_ERROR("Null message in AES_decrypt"); return -1; } - if (!encr_message) { - LOG_ERROR("Null encr message in AES_encrypt"); + if (!encrMessage) { + LOG_ERROR("Null encr message in AES_decrypt"); return -2; } if (!type) { - LOG_ERROR("Null type in AES_encrypt"); + LOG_ERROR("Null type in AES_decrypt"); return -3; } if (!exportable) { - LOG_ERROR("Null exportable in AES_encrypt"); + LOG_ERROR("Null exportable in AES_decrypt"); return -4; } @@ -125,11 +125,11 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t } sgx_status_t status = sgx_rijndael128GCM_decrypt(&(AES_key[512]), - encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len, + encrMessage + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len, (unsigned char*) message, - encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, + encrMessage + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, NULL, 0, - (sgx_aes_gcm_128bit_tag_t *)encr_message); + (sgx_aes_gcm_128bit_tag_t *)encrMessage); *type = message[0]; *exportable = message[1]; diff --git a/secure_enclave/AESUtils.h b/secure_enclave/AESUtils.h index 337f2ec1..3d054229 100644 --- a/secure_enclave/AESUtils.h +++ b/secure_enclave/AESUtils.h @@ -27,10 +27,10 @@ extern sgx_aes_gcm_128bit_key_t AES_key[1024]; int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen, - unsigned char type, unsigned char exportable, uint64_t* resultLen); -int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen, - uint8_t *type, uint8_t* exportable) ; - + unsigned char type, unsigned char exportable, + uint64_t *resultLen); +int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, + uint64_t msgLen, uint8_t *type, uint8_t *exportable); #define ECDSA '1' #define BLS '2' @@ -39,4 +39,4 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t #define EXPORTABLE '1' #define NON_EXPORTABLE '2' -#endif //SGXD_AESUTILS_H +#endif // SGXD_AESUTILS_H diff --git a/secure_enclave/Curves.h b/secure_enclave/Curves.h index 8a4bcdff..00177008 100644 --- a/secure_enclave/Curves.h +++ b/secure_enclave/Curves.h @@ -21,7 +21,6 @@ @date 2019 */ - #ifndef SGXWALLET_CURVES_H #define SGXWALLET_CURVES_H @@ -31,36 +30,44 @@ #define EXTERNC #endif +#include "DomainParameters.h" /*Curves that can be loaded using domain_parameters_load_curve()*/ -typedef enum { secp112r1 = 0, - //secp112r2, //See remark below - secp128r1, - //secp128r2, //See remark below - secp160k1, - secp160r1, - secp160r2, - secp192k1, - secp192r1, - secp224k1, - secp224r1, - secp256k1, - secp256r1, - secp384r1, - secp521r1 } curve_list; +typedef enum { + secp112r1 = 0, + // secp112r2, //See remark below + secp128r1, + // secp128r2, //See remark below + secp160k1, + secp160r1, + secp160r2, + secp192k1, + secp192r1, + secp224k1, + secp224r1, + secp256k1, + secp256r1, + secp384r1, + secp521r1 +} curve_list; /*Number of curves that can be loaded using domain_parameters_load_curve()*/ -#define NUMBER_OF_CURVES (secp521r1+1) +#define NUMBER_OF_CURVES (secp521r1 + 1) /*Load a curve depending on it's curve number, defined by the enum*/ -EXTERNC void domain_parameters_load_curve(domain_parameters out, curve_list curve); +EXTERNC void domain_parameters_load_curve(domain_parameters out, + curve_list curve); /* REMARK: -For some weird reason secp112r2 and secp128r2 doesn't want to be stable. Actually they work once in a while. However running the benchmark command gives -1 as operation time, sometimes and only sometimes! -Benchmark is supposed to write -1 as operation time if the operation failed. -As I don't see any reason to have extent my headache I'm putting this problem to rest by commenting these curves out. Furthermore it's very limited in terms of what can be done to debug these curves, since I don't have any test vectors for them. -It's probably related to a bug in the implementation, perhaps an exception I didn't handle or round of, who knows. +For some weird reason secp112r2 and secp128r2 doesn't want to be stable. +Actually they work once in a while. However running the benchmark command gives +-1 as operation time, sometimes and only sometimes! Benchmark is supposed to +write -1 as operation time if the operation failed. As I don't see any reason to +have extent my headache I'm putting this problem to rest by commenting these +curves out. Furthermore it's very limited in terms of what can be done to debug +these curves, since I don't have any test vectors for them. It's probably +related to a bug in the implementation, perhaps an exception I didn't handle or +round of, who knows. */ - #endif \ No newline at end of file diff --git a/secure_enclave/DHDkg.c b/secure_enclave/DHDkg.c index 4ad57786..bbac8cb0 100644 --- a/secure_enclave/DHDkg.c +++ b/secure_enclave/DHDkg.c @@ -332,7 +332,7 @@ int xor_decrypt_v2(char *key, char *cypher, char *message) { return ret; } -int hash_key(char* key, char* hashed_key) { +int hash_key(char* key, char* hashedKey, int length, bool isConvertNeeded) { int ret = -1; if (!key) { @@ -340,18 +340,22 @@ int hash_key(char* key, char* hashed_key) { return ret; } - if (!hashed_key) { + if (!hashedKey) { LOG_ERROR("hash_key: null hashed_key"); return ret; } - uint8_t key_to_hash[33]; - uint64_t len; - if (!hex2carray(key, &len, key_to_hash)) { - return ret; - } + if (isConvertNeeded) { + uint8_t key_to_hash[length + 1]; + uint64_t len; + if (!hex2carray(key, &len, key_to_hash)) { + return ret; + } - ret = sgx_sha256_msg(key_to_hash, ECDSA_BIN_LEN - 1, (uint8_t*)hashed_key); + ret = sgx_sha256_msg(key_to_hash, length, (uint8_t*)hashedKey); + } else { + ret = sgx_sha256_msg((uint8_t*)key, length, (uint8_t*)hashedKey); + } return ret; } diff --git a/secure_enclave/DHDkg.h b/secure_enclave/DHDkg.h index e4e5ec6f..72b1c944 100644 --- a/secure_enclave/DHDkg.h +++ b/secure_enclave/DHDkg.h @@ -24,18 +24,19 @@ #ifndef SGXD_DRIVE_KEY_DKG_H #define SGXD_DRIVE_KEY_DKG_H -int gen_session_key(char* skey, char* pub_keyB, char* common_key); +int gen_session_key(char *skey, char *pub_keyB, char *common_key); -int session_key_recover(const char *skey_str, const char* sshare, char* common_key); +int session_key_recover(const char *skey_str, const char *sshare, + char *common_key); -int xor_encrypt(char* key, char* message, char* cypher); +int xor_encrypt(char *key, char *message, char *cypher); -int xor_encrypt_v2(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(char *key, char *cypher, char *message); -int xor_decrypt_v2(char* key, char* cypher, char* message); +int xor_decrypt_v2(char *key, char *cypher, char *message); -int hash_key(char* key, char* hashed_key); +int hash_key(char *key, char *hashedKey, int length, bool isConvertNeeded); -#endif //SGXD_DRIVE_KEY_DKG_H +#endif // SGXD_DRIVE_KEY_DKG_H diff --git a/secure_enclave/DKGUtils.cpp b/secure_enclave/DKGUtils.cpp index aeb5e5fb..718d21b6 100644 --- a/secure_enclave/DKGUtils.cpp +++ b/secure_enclave/DKGUtils.cpp @@ -36,514 +36,580 @@ #include <../SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp> +#include "DHDkg.h" +#include "EnclaveCommon.h" #include "EnclaveConstants.h" #include #include -#include "EnclaveCommon.h" -#include "DHDkg.h" - using namespace std; string stringFromFr(const libff::alt_bn128_Fr &_el) { - string ret = ""; - mpz_t t; - mpz_init(t); - - try { - _el.as_bigint().to_mpz(t); + string ret = ""; + mpz_t t; + mpz_init(t); - SAFE_CHAR_BUF(arr, BUF_LEN); + try { + _el.as_bigint().to_mpz(t); - char *tmp = mpz_get_str(arr, 10, t); + SAFE_CHAR_BUF(arr, BUF_LEN); + char *tmp = mpz_get_str(arr, 10, t); - ret = string(tmp); + ret = string(tmp); - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: +clean: - mpz_clear(t); + mpz_clear(t); - return ret; + return ret; } -template -string ConvertToString(const T &field_elem, int base = 10) { +template string ConvertToString(const T &field_elem, int base = 10) { - string ret; + string ret; - mpz_t t; - mpz_init(t); + mpz_t t; + mpz_init(t); - try { + try { - field_elem.as_bigint().to_mpz(t); + field_elem.as_bigint().to_mpz(t); - SAFE_CHAR_BUF(arr, BUF_LEN); + SAFE_CHAR_BUF(arr, BUF_LEN); - char *tmp = mpz_get_str(arr, base, t); + char *tmp = mpz_get_str(arr, base, t); - ret = string(tmp); + ret = string(tmp); - goto clean; + goto clean; - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: - mpz_clear(t); - return ret; +clean: + mpz_clear(t); + return ret; } -string ConvertG2ToString(const libff::alt_bn128_G2 &elem, int base = 10, const string &delim = ":") { +string ConvertG2ToString(const libff::alt_bn128_G2 &elem, int base = 10, + const string &delim = ":") { - string result = ""; + string result = ""; - try { + try { - result += ConvertToString(elem.X.c0); - result += delim; - result += ConvertToString(elem.X.c1); - result += delim; - result += ConvertToString(elem.Y.c0); - result += delim; - result += ConvertToString(elem.Y.c1); + result += ConvertToString(elem.X.c0); + result += delim; + result += ConvertToString(elem.X.c1); + result += delim; + result += ConvertToString(elem.Y.c0); + result += delim; + result += ConvertToString(elem.Y.c1); - return result; + return result; - } catch (exception &e) { - LOG_ERROR(e.what()); - return result; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return result; - } + } catch (exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return result; + } + + return result; +} + +string ConvertG1ToString(const libff::alt_bn128_G1 &elem, int base = 10, + const string &delim = ":") { + + string result = ""; + + try { + + result += ConvertToString(elem.X); + result += delim; + result += ConvertToString(elem.Y); + + return result; + + } catch (exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return result; + } + + return result; +} + +libff::alt_bn128_G1 stringToG1(const char *elem) { + string str(elem); + + libff::alt_bn128_G1 result = libff::alt_bn128_G1::zero(); + + try { + int pos = str.find(":", 0); + if (pos == string::npos) + pos = str.length(); + result.X = libff::alt_bn128_Fq(str.substr(0, pos).c_str()); + result.Y = libff::alt_bn128_Fq(str.substr(pos, string::npos).c_str()); + if (str.find(":", pos) != string::npos) + return result; + + return result; + } catch (exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); return result; + } + + return result; } -vector SplitStringToFr(const char *coeffs, const char symbol) { - vector result; - string str(coeffs); - string delim; - - CHECK_ARG_CLEAN(coeffs); - - try { - - delim.push_back(symbol); - - size_t prev = 0, pos = 0; - do { - pos = str.find(delim, prev); - if (pos == string::npos) pos = str.length(); - string token = str.substr(prev, pos - prev); - if (!token.empty()) { - libff::alt_bn128_Fr coeff(token.c_str()); - result.push_back(coeff); - } - prev = pos + delim.length(); - } while (pos < str.length() && prev < str.length()); - - return result; - - } catch (exception &e) { - LOG_ERROR(e.what()); - return result; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return result; - } +vector SplitStringToFr(const char *coeffs, + const char symbol) { + vector result; + string str(coeffs); + string delim; + + CHECK_ARG_CLEAN(coeffs); - clean: + try { + + delim.push_back(symbol); + + size_t prev = 0, pos = 0; + do { + pos = str.find(delim, prev); + if (pos == string::npos) + pos = str.length(); + string token = str.substr(prev, pos - prev); + if (!token.empty()) { + libff::alt_bn128_Fr coeff(token.c_str()); + result.push_back(coeff); + } + prev = pos + delim.length(); + } while (pos < str.length() && prev < str.length()); + + return result; + + } catch (exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); return result; + } + +clean: + return result; } -bool isG2( const libff::alt_bn128_G2& point ) { +bool isG2(const libff::alt_bn128_G2 &point) { return point.is_well_formed() && libff::alt_bn128_G2::order() * point == libff::alt_bn128_G2::zero(); } int gen_dkg_poly(char *secret, unsigned _t) { - int status = 1; - string result; - - CHECK_ARG_CLEAN(secret); - - try { - for (size_t i = 0; i < _t; ++i) { - libff::alt_bn128_Fr cur_coef = libff::alt_bn128_Fr::random_element(); + int status = 1; + string result; - while (i == _t - 1 && cur_coef == libff::alt_bn128_Fr::zero()) { - cur_coef = libff::alt_bn128_Fr::random_element(); - } - result += stringFromFr(cur_coef); - result += ":"; - } - strncpy(secret, result.c_str(), result.length() + 1); + CHECK_ARG_CLEAN(secret); - if (strlen(secret) == 0) { - return status; - } + try { + for (size_t i = 0; i < _t; ++i) { + libff::alt_bn128_Fr cur_coef = libff::alt_bn128_Fr::random_element(); - status = 0; + while (i == _t - 1 && cur_coef == libff::alt_bn128_Fr::zero()) { + cur_coef = libff::alt_bn128_Fr::random_element(); + } + result += stringFromFr(cur_coef); + result += ":"; + } + strncpy(secret, result.c_str(), result.length() + 1); - } catch (exception &e) { - LOG_ERROR(e.what()); - return status; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return status; + if (strlen(secret) == 0) { + return status; } - clean: + status = 0; + + } catch (exception &e) { + LOG_ERROR(e.what()); return status; -} + } catch (...) { + LOG_ERROR("Unknown throwable"); + return status; + } -libff::alt_bn128_Fr PolynomialValue(const vector &pol, libff::alt_bn128_Fr point, unsigned _t) { +clean: + return status; +} - libff::alt_bn128_Fr result = libff::alt_bn128_Fr::zero(); +libff::alt_bn128_Fr PolynomialValue(const vector &pol, + libff::alt_bn128_Fr point, unsigned _t) { - try { + libff::alt_bn128_Fr result = libff::alt_bn128_Fr::zero(); - libff::alt_bn128_Fr pow = libff::alt_bn128_Fr::one(); - for (unsigned i = 0; i < pol.size(); ++i) { - result += pol.at(i) * pow; - pow *= point; - } + try { - return result; - } catch (exception &e) { - LOG_ERROR(e.what()); - return result; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return result; + libff::alt_bn128_Fr pow = libff::alt_bn128_Fr::one(); + for (unsigned i = 0; i < pol.size(); ++i) { + result += pol.at(i) * pow; + pow *= point; } return result; + } catch (exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return result; + } + + return result; } void calc_secret_shares(const char *decrypted_coeffs, - char *secret_shares, // calculates secret shares in base 10 to a string secret_shares, - unsigned _t, unsigned _n) { // separated by ":" - - // calculate for each node a list of secret values that will be used for verification - string result; - char symbol = ':'; + char *secret_shares, // calculates secret shares in base + // 10 to a string secret_shares, + unsigned _t, unsigned _n) { // separated by ":" + + // calculate for each node a list of secret values that will be used for + // verification + string result; + char symbol = ':'; + + CHECK_ARG_CLEAN(decrypted_coeffs); + CHECK_ARG_CLEAN(secret_shares); + CHECK_ARG_CLEAN(_n > 0); + CHECK_ARG_CLEAN(_t <= _n); + + try { + + vector poly = + SplitStringToFr(decrypted_coeffs, symbol); + + for (size_t i = 0; i < _n; ++i) { + libff::alt_bn128_Fr secret_share = + PolynomialValue(poly, libff::alt_bn128_Fr(i + 1), _t); + result += ConvertToString(secret_share); + result += ":"; + } + strncpy(secret_shares, result.c_str(), result.length() + 1); - CHECK_ARG_CLEAN(decrypted_coeffs); - CHECK_ARG_CLEAN(secret_shares); - CHECK_ARG_CLEAN(_n > 0); - CHECK_ARG_CLEAN(_t <= _n); + } catch (exception &e) { + LOG_ERROR(e.what()); + return; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return; + } - try { +clean:; +} - vector poly = SplitStringToFr(decrypted_coeffs, symbol); +int calc_secret_share(const char *decrypted_coeffs, char *s_share, unsigned _t, + unsigned _n, unsigned ind) { + int result = 1; - for (size_t i = 0; i < _n; ++i) { - libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(i + 1), _t); - result += ConvertToString(secret_share); - result += ":"; - } - strncpy(secret_shares, result.c_str(), result.length() + 1); + CHECK_ARG_CLEAN(decrypted_coeffs); + CHECK_ARG_CLEAN(s_share); + CHECK_ARG_CLEAN(_n > 0); + CHECK_ARG_CLEAN(_t <= _n); - } catch (exception &e) { - LOG_ERROR(e.what()); - return; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return; + try { + char symbol = ':'; + vector poly = + SplitStringToFr(decrypted_coeffs, symbol); + if (poly.size() != _t) { + return result; } - clean: - ; -} + libff::alt_bn128_Fr secret_share = + PolynomialValue(poly, libff::alt_bn128_Fr(ind), _t); + string cur_share = ConvertToString(secret_share, 16); + int n_zeroes = 64 - cur_share.size(); + cur_share.insert(0, n_zeroes, '0'); -int calc_secret_share(const char *decrypted_coeffs, char *s_share, - unsigned _t, unsigned _n, unsigned ind) { - int result = 1; - - CHECK_ARG_CLEAN(decrypted_coeffs); - CHECK_ARG_CLEAN(s_share); - CHECK_ARG_CLEAN(_n > 0); - CHECK_ARG_CLEAN(_t <= _n); - - try { - char symbol = ':'; - vector poly = SplitStringToFr(decrypted_coeffs, symbol); - if (poly.size() != _t) { - return result; - } - - libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(ind), _t); - string cur_share = ConvertToString(secret_share, 16); - int n_zeroes = 64 - cur_share.size(); - cur_share.insert(0, n_zeroes, '0'); - - strncpy(s_share, cur_share.c_str(), cur_share.length() + 1); - result = 0; - - return result; - } catch (exception &e) { - LOG_ERROR(e.what()); - return result; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return result; - } + strncpy(s_share, cur_share.c_str(), cur_share.length() + 1); + result = 0; - clean: return result; -} + } catch (exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return result; + } +clean: + return result; +} int calc_secret_shareG2(const char *s_share, char *s_shareG2) { - int result = 1; - - mpz_t share; - mpz_init(share); + int result = 1; - CHECK_ARG_CLEAN(s_share); - CHECK_ARG_CLEAN(s_shareG2); + mpz_t share; + mpz_init(share); - try { + CHECK_ARG_CLEAN(s_share); + CHECK_ARG_CLEAN(s_shareG2); - if (mpz_set_str(share, s_share, 16) == -1) { - goto clean; - } + try { - SAFE_CHAR_BUF(arr, BUF_LEN); + if (mpz_set_str(share, s_share, 16) == -1) { + goto clean; + } - char *share_str = mpz_get_str(arr, 10, share); + SAFE_CHAR_BUF(arr, BUF_LEN); - libff::alt_bn128_Fr secret_share(share_str); + char *share_str = mpz_get_str(arr, 10, share); - libff::alt_bn128_G2 secret_shareG2 = secret_share * libff::alt_bn128_G2::one(); + libff::alt_bn128_Fr secret_share(share_str); - secret_shareG2.to_affine_coordinates(); + libff::alt_bn128_G2 secret_shareG2 = + secret_share * libff::alt_bn128_G2::one(); - string secret_shareG2_str = ConvertG2ToString(secret_shareG2); + secret_shareG2.to_affine_coordinates(); - strncpy(s_shareG2, secret_shareG2_str.c_str(), secret_shareG2_str.length() + 1); - result = 0; - goto clean; + string secret_shareG2_str = ConvertG2ToString(secret_shareG2); - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + strncpy(s_shareG2, secret_shareG2_str.c_str(), + secret_shareG2_str.length() + 1); + result = 0; + goto clean; - clean: + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - mpz_clear(share); - return result; +clean: + mpz_clear(share); + return result; } int calc_public_shares(const char *decrypted_coeffs, char *public_shares, unsigned _t) { - // calculate for each node a list of public shares - int ret = 1; - string result; - char symbol = ':'; + // calculate for each node a list of public shares + int ret = 1; + string result; + char symbol = ':'; - CHECK_ARG_CLEAN(decrypted_coeffs); - CHECK_ARG_CLEAN(public_shares); - CHECK_ARG_CLEAN(_t > 0); - - try { - - vector poly = SplitStringToFr(decrypted_coeffs, symbol); - if (poly.size() != _t) { - return ret; - } - for (size_t i = 0; i < _t; ++i) { - libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one(); - pub_share.to_affine_coordinates(); - string pub_share_str = ConvertG2ToString(pub_share); - result += pub_share_str + ","; - } - strncpy(public_shares, result.c_str(), result.length()); - ret = 0; - - } catch (exception &e) { - LOG_ERROR(e.what()); - ret = 1; - } catch (...) { - LOG_ERROR("Unknown throwable"); - ret = 2; - } + CHECK_ARG_CLEAN(decrypted_coeffs); + CHECK_ARG_CLEAN(public_shares); + CHECK_ARG_CLEAN(_t > 0); - clean: - return ret; + try { + + vector poly = + SplitStringToFr(decrypted_coeffs, symbol); + if (poly.size() != _t) { + return ret; + } + for (size_t i = 0; i < _t; ++i) { + libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one(); + pub_share.to_affine_coordinates(); + string pub_share_str = ConvertG2ToString(pub_share); + result += pub_share_str + ","; + } + strncpy(public_shares, result.c_str(), result.length()); + ret = 0; + + } catch (exception &e) { + LOG_ERROR(e.what()); + ret = 1; + } catch (...) { + LOG_ERROR("Unknown throwable"); + ret = 2; + } + +clean: + return ret; } string ConvertHexToDec(string hex_str) { - mpz_t dec; - mpz_init(dec); + mpz_t dec; + mpz_init(dec); - string ret = ""; + string ret = ""; - try { + try { - if (mpz_set_str(dec, hex_str.c_str(), 16) == -1) { - goto clean; - } - - char arr[mpz_sizeinbase(dec, 10) + 2]; - char *result = mpz_get_str(arr, 10, dec); - CHECK_ARG_CLEAN(result); - ret = result; - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; + if (mpz_set_str(dec, hex_str.c_str(), 16) == -1) { + goto clean; } - clean: - mpz_clear(dec); - return ret; + char arr[mpz_sizeinbase(dec, 10) + 2]; + char *result = mpz_get_str(arr, 10, dec); + CHECK_ARG_CLEAN(result); + ret = result; + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } + +clean: + mpz_clear(dec); + return ret; } -int Verification(char *public_shares, mpz_t decr_secret_share, int _t, int ind) { - - string pub_shares_str = public_shares; - vector pub_shares; - uint64_t share_length = 256; - uint8_t coord_length = 64; - int ret = 0; - - CHECK_ARG_CLEAN(public_shares); - - try { - - for (int i = 0; i < _t; i++) { - libff::alt_bn128_G2 pub_share; - - uint64_t pos0 = share_length * i; - string x_c0_str = ConvertHexToDec(pub_shares_str.substr(pos0, coord_length)); - string x_c1_str = ConvertHexToDec(pub_shares_str.substr(pos0 + coord_length, coord_length)); - string y_c0_str = ConvertHexToDec(pub_shares_str.substr(pos0 + 2 * coord_length, coord_length)); - string y_c1_str = ConvertHexToDec(pub_shares_str.substr(pos0 + 3 * coord_length, coord_length)); - if (x_c0_str == "" || x_c1_str == "" || y_c0_str == "" || y_c1_str == "") { - ret = 2; - return ret; - } - pub_share.X.c0 = libff::alt_bn128_Fq(x_c0_str.c_str()); - pub_share.X.c1 = libff::alt_bn128_Fq(x_c1_str.c_str()); - pub_share.Y.c0 = libff::alt_bn128_Fq(y_c0_str.c_str()); - pub_share.Y.c1 = libff::alt_bn128_Fq(y_c1_str.c_str()); - pub_share.Z = libff::alt_bn128_Fq2::one(); - - if ( !isG2( pub_share ) ) { - ret = 3; - return ret; - } - pub_shares.push_back(pub_share); - } - - libff::alt_bn128_G2 val = libff::alt_bn128_G2::zero(); - for (int i = 0; i < _t; ++i) { - val = val + power(libff::alt_bn128_Fr(ind + 1), i) * pub_shares.at(i); - } - - SAFE_CHAR_BUF(arr, BUF_LEN); - char *tmp = mpz_get_str(arr, 10, decr_secret_share); - - libff::alt_bn128_Fr sshare(tmp); - - libff::alt_bn128_G2 val2 = sshare * libff::alt_bn128_G2::one(); - - memset(public_shares, 0, strlen(public_shares)); - strncpy(public_shares, tmp, strlen(tmp)); - - val.to_affine_coordinates(); - val2.to_affine_coordinates(); - strncpy(public_shares, ConvertToString(val.X.c0).c_str(), ConvertToString(val.X.c0).length()); - strncpy(public_shares + ConvertToString(val.X.c0).length(), ":", 1); - strncpy(public_shares + ConvertToString(val.X.c0).length() + 1, ConvertToString(val2.X.c0).c_str(), - ConvertToString(val2.X.c0).length()); - - ret = (val == sshare * libff::alt_bn128_G2::one()); - - } catch (exception &e) { - LOG_ERROR(e.what()); +int Verification(char *public_shares, mpz_t decr_secret_share, int _t, + int ind) { + + string pub_shares_str = public_shares; + vector pub_shares; + uint64_t share_length = 256; + uint8_t coord_length = 64; + int ret = 0; + + CHECK_ARG_CLEAN(public_shares); + + try { + + for (int i = 0; i < _t; i++) { + libff::alt_bn128_G2 pub_share; + + uint64_t pos0 = share_length * i; + string x_c0_str = + ConvertHexToDec(pub_shares_str.substr(pos0, coord_length)); + string x_c1_str = ConvertHexToDec( + pub_shares_str.substr(pos0 + coord_length, coord_length)); + string y_c0_str = ConvertHexToDec( + pub_shares_str.substr(pos0 + 2 * coord_length, coord_length)); + string y_c1_str = ConvertHexToDec( + pub_shares_str.substr(pos0 + 3 * coord_length, coord_length)); + if (x_c0_str == "" || x_c1_str == "" || y_c0_str == "" || + y_c1_str == "") { + ret = 2; return ret; - - } catch (...) { - LOG_ERROR("Unknown throwable"); + } + pub_share.X.c0 = libff::alt_bn128_Fq(x_c0_str.c_str()); + pub_share.X.c1 = libff::alt_bn128_Fq(x_c1_str.c_str()); + pub_share.Y.c0 = libff::alt_bn128_Fq(y_c0_str.c_str()); + pub_share.Y.c1 = libff::alt_bn128_Fq(y_c1_str.c_str()); + pub_share.Z = libff::alt_bn128_Fq2::one(); + + if (!isG2(pub_share)) { + ret = 3; return ret; + } + pub_shares.push_back(pub_share); + } + + libff::alt_bn128_G2 val = libff::alt_bn128_G2::zero(); + for (int i = 0; i < _t; ++i) { + val = val + power(libff::alt_bn128_Fr(ind + 1), i) * pub_shares.at(i); } - clean: + SAFE_CHAR_BUF(arr, BUF_LEN); + char *tmp = mpz_get_str(arr, 10, decr_secret_share); + + libff::alt_bn128_Fr sshare(tmp); + + libff::alt_bn128_G2 val2 = sshare * libff::alt_bn128_G2::one(); + + memset(public_shares, 0, strlen(public_shares)); + strncpy(public_shares, tmp, strlen(tmp)); + + val.to_affine_coordinates(); + val2.to_affine_coordinates(); + strncpy(public_shares, ConvertToString(val.X.c0).c_str(), + ConvertToString(val.X.c0).length()); + strncpy(public_shares + ConvertToString(val.X.c0).length(), ":", 1); + strncpy(public_shares + ConvertToString(val.X.c0).length() + 1, + ConvertToString(val2.X.c0).c_str(), + ConvertToString(val2.X.c0).length()); + + ret = (val == sshare * libff::alt_bn128_G2::one()); + + } catch (exception &e) { + LOG_ERROR(e.what()); return ret; + + } catch (...) { + LOG_ERROR("Unknown throwable"); + return ret; + } + +clean: + return ret; } int calc_bls_public_key(char *skey_hex, char *pub_key) { - mpz_t skey; - mpz_init(skey); + mpz_t skey; + mpz_init(skey); - int ret = 1; + int ret = 1; - CHECK_ARG_CLEAN(skey_hex); - CHECK_ARG_CLEAN(pub_key); + CHECK_ARG_CLEAN(skey_hex); + CHECK_ARG_CLEAN(pub_key); - try { + try { - if (mpz_set_str(skey, skey_hex, 16) == -1) { - mpz_clear(skey); - return 1; - } + if (mpz_set_str(skey, skey_hex, 16) == -1) { + mpz_clear(skey); + return 1; + } - char skey_dec[mpz_sizeinbase(skey, 10) + 2]; - mpz_get_str(skey_dec, 10, skey); + char skey_dec[mpz_sizeinbase(skey, 10) + 2]; + mpz_get_str(skey_dec, 10, skey); - libff::alt_bn128_Fr bls_skey(skey_dec); + libff::alt_bn128_Fr bls_skey(skey_dec); - libff::alt_bn128_G2 public_key = bls_skey * libff::alt_bn128_G2::one(); - public_key.to_affine_coordinates(); + libff::alt_bn128_G2 public_key = bls_skey * libff::alt_bn128_G2::one(); + public_key.to_affine_coordinates(); - string result = ConvertG2ToString(public_key); + string result = ConvertG2ToString(public_key); - strncpy(pub_key, result.c_str(), result.length()); + strncpy(pub_key, result.c_str(), result.length()); - mpz_clear(skey); + mpz_clear(skey); - return 0; + return 0; - } catch (exception &e) { - LOG_ERROR(e.what()); - return 1; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return 1; - } + } catch (exception &e) { + LOG_ERROR(e.what()); + return 1; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return 1; + } - clean: - mpz_clear(skey); - return ret; +clean: + mpz_clear(skey); + return ret; } diff --git a/secure_enclave/DKGUtils.h b/secure_enclave/DKGUtils.h index 95565d86..db8e98c5 100644 --- a/secure_enclave/DKGUtils.h +++ b/secure_enclave/DKGUtils.h @@ -37,20 +37,21 @@ #include <../tgmp-build/include/sgx_tgmp.h> #endif -EXTERNC int gen_dkg_poly( char* secret, unsigned _t); +EXTERNC int gen_dkg_poly(char *secret, unsigned _t); -EXTERNC void calc_secret_shares(const char* decrypted_coeffs, char * secret_shares, - unsigned _t, unsigned _n); +EXTERNC void calc_secret_shares(const char *decrypted_coeffs, + char *secret_shares, unsigned _t, unsigned _n); -EXTERNC int calc_secret_share(const char* decrypted_coeffs, char * s_share, - unsigned _t, unsigned _n, unsigned ind); +EXTERNC int calc_secret_share(const char *decrypted_coeffs, char *s_share, + unsigned _t, unsigned _n, unsigned ind); -EXTERNC int calc_public_shares(const char* decrypted_coeffs, char * public_shares, unsigned _t); +EXTERNC int calc_public_shares(const char *decrypted_coeffs, + char *public_shares, unsigned _t); -EXTERNC int Verification ( char * public_shares, mpz_t decr_secret_share, int _t, int ind); +EXTERNC int Verification(char *public_shares, mpz_t decr_secret_share, int _t, + int ind); -EXTERNC int calc_bls_public_key(char* skey, char* pub_key); +EXTERNC int calc_bls_public_key(char *skey, char *pub_key); -EXTERNC int calc_secret_shareG2(const char* s_share, char * s_shareG2); +EXTERNC int calc_secret_shareG2(const char *s_share, char *s_shareG2); #endif - diff --git a/secure_enclave/DomainParameters.cpp b/secure_enclave/DomainParameters.cpp index 5d91561c..09b2af5b 100644 --- a/secure_enclave/DomainParameters.cpp +++ b/secure_enclave/DomainParameters.cpp @@ -21,9 +21,20 @@ @date 2019 */ -#define SAFE_FREE(__X__) if (__X__) {free(__X__); __X__ = NULL;} -#define SAFE_DELETE(__X__) if (__X__) {delete(__X__); __X__ = NULL;} -#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__); +#define SAFE_FREE(__X__) \ + if (__X__) { \ + free(__X__); \ + __X__ = NULL; \ + } +#define SAFE_DELETE(__X__) \ + if (__X__) { \ + delete (__X__); \ + __X__ = NULL; \ + } +#define SAFE_CHAR_BUF(__X__, __Y__) \ + ; \ + char __X__[__Y__]; \ + memset(__X__, 0, __Y__); #ifdef USER_SPACE #include @@ -31,129 +42,105 @@ #include <../tgmp-build/include/sgx_tgmp.h> #endif +#include "EnclaveCommon.h" +#include "Point.h" +#include #include #include -#include #include -#include "EnclaveCommon.h" -#include "Point.h" #include "DomainParameters.h" -#define CHECK_ARG_ABORT(_EXPRESSION_) \ - if (!(_EXPRESSION_)) { \ - abort(); \ - } - +#define CHECK_ARG_ABORT(_EXPRESSION_) \ + if (!(_EXPRESSION_)) { \ + abort(); \ + } /*Initialize a curve*/ -domain_parameters domain_parameters_init() -{ +domain_parameters domain_parameters_init() { + domain_parameters curve; + curve = (domain_parameters)calloc(sizeof(struct domain_parameters_s), 1); + CHECK_ARG_ABORT(curve); - domain_parameters curve; - curve = (domain_parameters) calloc(sizeof(struct domain_parameters_s),1); + // Initialize all members + mpz_init(curve->p); + mpz_init(curve->a); + mpz_init(curve->b); + mpz_init(curve->n); + mpz_init(curve->h); - CHECK_ARG_ABORT(curve); + curve->G = point_init(); + CHECK_ARG_ABORT(curve->G); - //Initialize all members - mpz_init(curve->p); - mpz_init(curve->a); - mpz_init(curve->b); - mpz_init(curve->n); - mpz_init(curve->h); - - - curve->G = point_init(); - - CHECK_ARG_ABORT(curve->G); - - - return curve; + return curve; } /*Sets the name of a curve*/ -void domain_parameters_set_name(domain_parameters curve, char* name) -{ - - CHECK_ARG_ABORT(name); - int len = strlen(name); - curve->name = (char*)calloc( sizeof(char) * (len+1), 1 ); - curve->name[len] = '\0'; - strncpy(curve->name, name, len+1); - +void domain_parameters_set_name(domain_parameters curve, char *name) { + CHECK_ARG_ABORT(name); + int len = strlen(name); + curve->name = (char *)calloc(sizeof(char) * (len + 1), 1); + curve->name[len] = '\0'; + strncpy(curve->name, name, len + 1); } /*Set domain parameters from decimal unsigned long ints*/ -void domain_parameters_set_ui(domain_parameters curve, - char* name, - unsigned long int p, - unsigned long int a, - unsigned long int b, - unsigned long int Gx, - unsigned long int Gy, - unsigned long int n, - unsigned long int h) -{ - - CHECK_ARG_ABORT(name); - - domain_parameters_set_name(curve, name); - mpz_set_ui(curve->p, p); - mpz_set_ui(curve->a, a); - mpz_set_ui(curve->b, b); - point_set_ui(curve->G, Gx, Gy); - mpz_set_ui(curve->n, n); - mpz_set_ui(curve->h, h); - - +void domain_parameters_set_ui(domain_parameters curve, char *name, + unsigned long int p, unsigned long int a, + unsigned long int b, unsigned long int Gx, + unsigned long int Gy, unsigned long int n, + unsigned long int h) { + + CHECK_ARG_ABORT(name); + + domain_parameters_set_name(curve, name); + mpz_set_ui(curve->p, p); + mpz_set_ui(curve->a, a); + mpz_set_ui(curve->b, b); + point_set_ui(curve->G, Gx, Gy); + mpz_set_ui(curve->n, n); + mpz_set_ui(curve->h, h); } /*Set domain parameters from hexadecimal string*/ -void domain_parameters_set_hex(domain_parameters curve, char* name, char* p, char* a, char* b, char* Gx, char* Gy, char* n, char* h) -{ - - CHECK_ARG_ABORT(name); - CHECK_ARG_ABORT(p); - CHECK_ARG_ABORT(a); - CHECK_ARG_ABORT(b); - CHECK_ARG_ABORT(Gx); - CHECK_ARG_ABORT(Gy); - CHECK_ARG_ABORT(n); - CHECK_ARG_ABORT(h); - - - - - - domain_parameters_set_name(curve, name); - mpz_set_str(curve->p, p, 16); - mpz_set_str(curve->a, a, 16); - mpz_set_str(curve->b, b, 16); - point_set_hex(curve->G, Gx, Gy); - mpz_set_str(curve->n, n, 16); - mpz_set_str(curve->h, h, 16); - - +void domain_parameters_set_hex(domain_parameters curve, char *name, char *p, + char *a, char *b, char *Gx, char *Gy, char *n, + char *h) { + + CHECK_ARG_ABORT(name); + CHECK_ARG_ABORT(p); + CHECK_ARG_ABORT(a); + CHECK_ARG_ABORT(b); + CHECK_ARG_ABORT(Gx); + CHECK_ARG_ABORT(Gy); + CHECK_ARG_ABORT(n); + CHECK_ARG_ABORT(h); + + domain_parameters_set_name(curve, name); + mpz_set_str(curve->p, p, 16); + mpz_set_str(curve->a, a, 16); + mpz_set_str(curve->b, b, 16); + point_set_hex(curve->G, Gx, Gy); + mpz_set_str(curve->n, n, 16); + mpz_set_str(curve->h, h, 16); } /*Release memory*/ -void domain_parameters_clear(domain_parameters curve) -{ - - if (!curve) - return; - - mpz_clear(curve->p); - mpz_clear(curve->a); - mpz_clear(curve->b); - point_clear(curve->G); - mpz_clear(curve->n); - mpz_clear(curve->h); - SAFE_FREE(curve->name); - free(curve); +void domain_parameters_clear(domain_parameters curve) { + + if (!curve) + return; + + mpz_clear(curve->p); + mpz_clear(curve->a); + mpz_clear(curve->b); + point_clear(curve->G); + mpz_clear(curve->n); + mpz_clear(curve->h); + SAFE_FREE(curve->name); + free(curve); } - diff --git a/secure_enclave/DomainParameters.h b/secure_enclave/DomainParameters.h index 13b09f20..851847bc 100644 --- a/secure_enclave/DomainParameters.h +++ b/secure_enclave/DomainParameters.h @@ -30,47 +30,42 @@ #endif /*Type that represents a point*/ -typedef struct point_s* point; -struct point_s -{ - mpz_t x; - mpz_t y; - bool infinity; +typedef struct point_s *point; +struct point_s { + mpz_t x; + mpz_t y; + bool infinity; }; - /*Type that represents a curve*/ -typedef struct domain_parameters_s* domain_parameters; -struct domain_parameters_s -{ - char* name; - mpz_t p; //Prime - mpz_t a; //'a' parameter of the elliptic curve - mpz_t b; //'b' parameter of the elliptic curve - point G; //Generator point of the curve, also known as base point. - mpz_t n; - mpz_t h; +typedef struct domain_parameters_s *domain_parameters; +struct domain_parameters_s { + char *name; + mpz_t p; // Prime + mpz_t a; //'a' parameter of the elliptic curve + mpz_t b; //'b' parameter of the elliptic curve + point G; // Generator point of the curve, also known as base point. + mpz_t n; + mpz_t h; }; /*Initialize a curve*/ EXTERNC domain_parameters domain_parameters_init(); /*Sets the name of a curve*/ -EXTERNC void domain_parameters_set_name(domain_parameters curve, char* name); +EXTERNC void domain_parameters_set_name(domain_parameters curve, char *name); /*Set domain parameters from decimal unsigned long ints*/ -EXTERNC void domain_parameters_set_ui(domain_parameters curve, - char* name, - unsigned long int p, - unsigned long int a, - unsigned long int b, - unsigned long int Gx, - unsigned long int Gy, - unsigned long int n, - unsigned long int h); +EXTERNC void domain_parameters_set_ui(domain_parameters curve, char *name, + unsigned long int p, unsigned long int a, + unsigned long int b, unsigned long int Gx, + unsigned long int Gy, unsigned long int n, + unsigned long int h); /*Set domain parameters from hexadecimal string*/ -EXTERNC void domain_parameters_set_hex(domain_parameters curve, char* name, char* p, char* a, char* b, char* Gx, char* Gy, char* n, char* h); +EXTERNC void domain_parameters_set_hex(domain_parameters curve, char *name, + char *p, char *a, char *b, char *Gx, + char *Gy, char *n, char *h); /*Release memory*/ EXTERNC void domain_parameters_clear(domain_parameters curve); diff --git a/secure_enclave/EnclaveCommon.cpp b/secure_enclave/EnclaveCommon.cpp index 251d5d11..3fb86343 100644 --- a/secure_enclave/EnclaveCommon.cpp +++ b/secure_enclave/EnclaveCommon.cpp @@ -23,140 +23,137 @@ #define GMP_WITH_SGX 1 -#include #include +#include #include "../SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" #include "../SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp" #include "secure_enclave_t.h" -#include "EnclaveConstants.h" #include "EnclaveCommon.h" +#include "EnclaveConstants.h" using namespace std; thread_local uint8_t decryptedDkgPoly[DKG_BUFER_LENGTH]; -uint8_t *getThreadLocalDecryptedDkgPoly() { - return decryptedDkgPoly; -} - +uint8_t *getThreadLocalDecryptedDkgPoly() { return decryptedDkgPoly; } string *stringFromKey(libff::alt_bn128_Fr *_key) { - string *ret = nullptr; - mpz_t t; - mpz_init(t); - - SAFE_CHAR_BUF(arr, BUF_LEN); - - try { - _key->as_bigint().to_mpz(t); - - char *tmp = mpz_get_str(arr, 10, t); - - if (!tmp) { - LOG_ERROR("stringFromKey: mpz_get_str failed"); - goto clean; - } - ret = new string(tmp); - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; + string *ret = nullptr; + mpz_t t; + mpz_init(t); + + SAFE_CHAR_BUF(arr, BUF_LEN); + + try { + _key->as_bigint().to_mpz(t); + + char *tmp = mpz_get_str(arr, 10, t); + + if (!tmp) { + LOG_ERROR("stringFromKey: mpz_get_str failed"); + goto clean; } + ret = new string(tmp); + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: - mpz_clear(t); - return ret; +clean: + mpz_clear(t); + return ret; } string *stringFromFq(libff::alt_bn128_Fq *_fq) { - string *ret = nullptr; - mpz_t t; - mpz_init(t); - SAFE_CHAR_BUF(arr, BUF_LEN); - - try { - _fq->as_bigint().to_mpz(t); - mpz_get_str(arr, 10, t); - ret = new string(arr); - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + string *ret = nullptr; + mpz_t t; + mpz_init(t); + SAFE_CHAR_BUF(arr, BUF_LEN); + + try { + _fq->as_bigint().to_mpz(t); + mpz_get_str(arr, 10, t); + ret = new string(arr); + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: - mpz_clear(t); - return ret; +clean: + mpz_clear(t); + return ret; } string *stringFromG1(libff::alt_bn128_G1 *_g1) { - string *sX = nullptr; - string *sY = nullptr; - string *ret = nullptr; + string *sX = nullptr; + string *sY = nullptr; + string *ret = nullptr; - try { - _g1->to_affine_coordinates(); + try { + _g1->to_affine_coordinates(); - sX = stringFromFq(&_g1->X); + sX = stringFromFq(&_g1->X); - if (!sX) { - goto clean; - } + if (!sX) { + goto clean; + } - sY = stringFromFq(&_g1->Y); + sY = stringFromFq(&_g1->Y); - if (!sY) { - goto clean; - } + if (!sY) { + goto clean; + } - ret = new string(*sX + ":" + *sY); + ret = new string(*sX + ":" + *sY); - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: +clean: - SAFE_DELETE(sX); - SAFE_DELETE(sY); + SAFE_DELETE(sX); + SAFE_DELETE(sY); - return ret; + return ret; } libff::alt_bn128_Fr *keyFromString(const char *_keyStringHex) { - mpz_t skey; - mpz_init(skey); - SAFE_CHAR_BUF(skey_dec, BUF_LEN); - libff::alt_bn128_Fr *ret = nullptr; + mpz_t skey; + mpz_init(skey); + SAFE_CHAR_BUF(skey_dec, BUF_LEN); + libff::alt_bn128_Fr *ret = nullptr; - if (mpz_set_str(skey, _keyStringHex, 16) == -1) { - goto clean; - } + if (mpz_set_str(skey, _keyStringHex, 16) == -1) { + goto clean; + } - mpz_get_str(skey_dec, 10, skey); + mpz_get_str(skey_dec, 10, skey); - ret = new libff::alt_bn128_Fr(skey_dec); + ret = new libff::alt_bn128_Fr(skey_dec); - goto clean; + goto clean; - clean: +clean: - mpz_clear(skey); - return ret; + mpz_clear(skey); + return ret; } int inited = 0; @@ -165,206 +162,197 @@ domain_parameters curve; void enclave_init() { - LOG_INFO(__FUNCTION__ ); + LOG_INFO(__FUNCTION__); - if (inited == 1) - return; - inited = 1; + if (inited == 1) + return; + inited = 1; - LOG_INFO("Initing libff"); - try { + LOG_INFO("Initing libff"); + try { - LOG_INFO("Initing params"); + LOG_INFO("Initing params"); - libff::init_alt_bn128_params(); + libff::init_alt_bn128_params(); - LOG_INFO("Initing curve"); - curve = domain_parameters_init(); - LOG_INFO("Initing curve domain"); - domain_parameters_load_curve(curve, secp256k1); - } catch (exception& e) { - LOG_ERROR("Exception in libff init"); - LOG_ERROR(e.what()); - abort(); - } catch (...) { - LOG_ERROR("Unknown exception in libff"); - abort(); - } - LOG_INFO("Inited libff"); + LOG_INFO("Initing curve"); + curve = domain_parameters_init(); + LOG_INFO("Initing curve domain"); + domain_parameters_load_curve(curve, secp256k1); + } catch (exception &e) { + LOG_ERROR("Exception in libff init"); + LOG_ERROR(e.what()); + abort(); + } catch (...) { + LOG_ERROR("Unknown exception in libff"); + abort(); + } + LOG_INFO("Inited libff"); } -bool enclave_sign(const char *_keyString, const char *_hashXString, const char *_hashYString, - char *sig) { - - bool ret = false; +bool enclave_sign(const char *_keyString, const char *_hashXString, + const char *_hashYString, char *sig) { - libff::alt_bn128_Fr* key = nullptr; - string * r = nullptr; + bool ret = false; + libff::alt_bn128_Fr *key = nullptr; + string *r = nullptr; - if (!_keyString) { - LOG_ERROR("Null key string"); - goto clean; - } + if (!_keyString) { + LOG_ERROR("Null key string"); + goto clean; + } - if (!_hashXString) { - LOG_ERROR("Null hashX"); - goto clean; - } + if (!_hashXString) { + LOG_ERROR("Null hashX"); + goto clean; + } - if (!_hashYString) { - LOG_ERROR("Null hashY"); - goto clean; - } + if (!_hashYString) { + LOG_ERROR("Null hashY"); + goto clean; + } - if (!sig) { - LOG_ERROR("Null sig"); - goto clean; - } + if (!sig) { + LOG_ERROR("Null sig"); + goto clean; + } - try { - key = keyFromString(_keyString); + try { + key = keyFromString(_keyString); - if (!key) { - LOG_ERROR("Null key"); - goto clean; - } + if (!key) { + LOG_ERROR("Null key"); + goto clean; + } - libff::alt_bn128_Fq hashX(_hashXString); - libff::alt_bn128_Fq hashY(_hashYString); - libff::alt_bn128_Fq hashZ = 1; + libff::alt_bn128_Fq hashX(_hashXString); + libff::alt_bn128_Fq hashY(_hashYString); + libff::alt_bn128_Fq hashZ = 1; - libff::alt_bn128_G1 hash(hashX, hashY, hashZ); + libff::alt_bn128_G1 hash(hashX, hashY, hashZ); - libff::alt_bn128_G1 sign = key->as_bigint() * hash; + libff::alt_bn128_G1 sign = key->as_bigint() * hash; - sign.to_affine_coordinates(); + sign.to_affine_coordinates(); - r = stringFromG1(&sign); + r = stringFromG1(&sign); - memset(sig, 0, BUF_LEN); + memset(sig, 0, BUF_LEN); - strncpy(sig, r->c_str(), BUF_LEN); + strncpy(sig, r->c_str(), BUF_LEN); - ret = true; + ret = true; - } catch (exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + } catch (exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: +clean: - SAFE_DELETE(key); - SAFE_DELETE(r); - return ret; + SAFE_DELETE(key); + SAFE_DELETE(r); + return ret; } void carray2Hex(const unsigned char *d, int _len, char *_hexArray) { - char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - for (int j = 0; j < _len; j++) { - _hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)]; - _hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F]; - } + for (int j = 0; j < _len; j++) { + _hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)]; + _hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F]; + } - _hexArray[_len * 2] = 0; + _hexArray[_len * 2] = 0; } int char2int(char _input) { - if (_input >= '0' && _input <= '9') - return _input - '0'; - if (_input >= 'A' && _input <= 'F') - return _input - 'A' + 10; - if (_input >= 'a' && _input <= 'f') - return _input - 'a' + 10; - return -1; + if (_input >= '0' && _input <= '9') + return _input - '0'; + if (_input >= 'A' && _input <= 'F') + return _input - 'A' + 10; + if (_input >= 'a' && _input <= 'f') + return _input - 'a' + 10; + return -1; } -bool hex2carray2(const char *_hex, uint64_t *_bin_len, - uint8_t *_bin, const int _max_length) { - int len = strnlen(_hex, _max_length); - - if (len == 0 && len % 2 == 1) - return false; +bool hex2carray2(const char *_hex, uint64_t *_bin_len, uint8_t *_bin, + const int _max_length) { + int len = strnlen(_hex, _max_length); - *_bin_len = len / 2; + if (len == 0 && len % 2 == 1) + return false; - for (int i = 0; i < len / 2; i++) { - int high = char2int((char) _hex[i * 2]); - int low = char2int((char) _hex[i * 2 + 1]); + *_bin_len = len / 2; - if (high < 0 || low < 0) { - return false; - } + for (int i = 0; i < len / 2; i++) { + int high = char2int((char)_hex[i * 2]); + int low = char2int((char)_hex[i * 2 + 1]); - _bin[i] = (unsigned char) (high * 16 + low); + if (high < 0 || low < 0) { + return false; } - return true; -} + _bin[i] = (unsigned char)(high * 16 + low); + } -bool hex2carray(const char *_hex, uint64_t *_bin_len, - uint8_t *_bin) { - int len = strnlen(_hex, 2 * BUF_LEN); + return true; +} - if (len == 0 && len % 2 == 1) - return false; +bool hex2carray(const char *_hex, uint64_t *_bin_len, uint8_t *_bin) { + int len = strnlen(_hex, 2 * BUF_LEN); - *_bin_len = len / 2; + if (len == 0 && len % 2 == 1) + return false; - for (int i = 0; i < len / 2; i++) { - int high = char2int((char) _hex[i * 2]); - int low = char2int((char) _hex[i * 2 + 1]); + *_bin_len = len / 2; - if (high < 0 || low < 0) { - return false; - } + for (int i = 0; i < len / 2; i++) { + int high = char2int((char)_hex[i * 2]); + int low = char2int((char)_hex[i * 2 + 1]); - _bin[i] = (unsigned char) (high * 16 + low); + if (high < 0 || low < 0) { + return false; } - return true; + _bin[i] = (unsigned char)(high * 16 + low); + } + + return true; } enum log_level { - L_TRACE = 0, L_DEBUG = 1, L_INFO = 2, L_WARNING = 3, L_ERROR = 4 + L_TRACE = 0, + L_DEBUG = 1, + L_INFO = 2, + L_WARNING = 3, + L_ERROR = 4 }; uint32_t globalLogLevel_ = 2; void logMsg(log_level _level, const char *_msg) { - if (_level < globalLogLevel_) - return; + if (_level < globalLogLevel_) + return; - if (!_msg) { - oc_printf("Null msg in logMsg"); - return; - } + if (!_msg) { + oc_printf("Null msg in logMsg"); + return; + } - oc_printf("***ENCLAVE_LOG***:"); - oc_printf(_msg); - oc_printf("\n"); + oc_printf("***ENCLAVE_LOG***:"); + oc_printf(_msg); + oc_printf("\n"); } +void LOG_INFO(const char *_msg) { logMsg(L_INFO, _msg); }; +void LOG_WARN(const char *_msg) { logMsg(L_WARNING, _msg); }; -void LOG_INFO(const char *_msg) { - logMsg(L_INFO, _msg); -}; -void LOG_WARN(const char *_msg) { - logMsg(L_WARNING, _msg); -}; - -void LOG_ERROR(const char *_msg) { - logMsg(L_ERROR, _msg); -}; -void LOG_DEBUG(const char *_msg) { - logMsg(L_DEBUG, _msg); -}; -void LOG_TRACE(const char *_msg) { - logMsg(L_TRACE, _msg); -}; +void LOG_ERROR(const char *_msg) { logMsg(L_ERROR, _msg); }; +void LOG_DEBUG(const char *_msg) { logMsg(L_DEBUG, _msg); }; +void LOG_TRACE(const char *_msg) { logMsg(L_TRACE, _msg); }; diff --git a/secure_enclave/EnclaveCommon.h b/secure_enclave/EnclaveCommon.h index ae275a9b..0f81c432 100644 --- a/secure_enclave/EnclaveCommon.h +++ b/secure_enclave/EnclaveCommon.h @@ -16,15 +16,17 @@ You should have received a copy of the GNU Affero General Public License along with sgxwallet. If not, see . - @file BLSEnclave.h + @file EnclaveCommon.h @author Stan Kladko @date 2019 */ +#include + #include "DomainParameters.h" -#include "Signature.h" #include "Curves.h" +#include "Signature.h" #ifndef SGXWALLET_ENCLAVECOMMON_H #define SGXWALLET_ENCLAVECOMMON_H @@ -35,46 +37,62 @@ #define EXTERNC #endif -EXTERNC void check_key(int *errStatus, char *err_string, const char* _keyString); +EXTERNC void check_key(int *errStatus, char *err_string, + const char *_keyString); -EXTERNC bool enclave_sign(const char *_keyString, const char* _hashXString, const char* _hashYString, char* _sig); +EXTERNC bool enclave_sign(const char *_keyString, const char *_hashXString, + const char *_hashYString, char *_sig); EXTERNC int char2int(char _input); -EXTERNC void carray2Hex(const unsigned char *d, int _len, char* _hexArray); -EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len, - uint8_t* _bin ); -EXTERNC bool hex2carray2(const char * _hex, uint64_t *_bin_len, - uint8_t* _bin, const int _max_length ); +EXTERNC void carray2Hex(const unsigned char *d, int _len, char *_hexArray); +EXTERNC bool hex2carray(const char *_hex, uint64_t *_bin_len, uint8_t *_bin); +EXTERNC bool hex2carray2(const char *_hex, uint64_t *_bin_len, uint8_t *_bin, + const int _max_length); EXTERNC void enclave_init(); -void get_global_random(unsigned char* _randBuff, uint64_t size); +void get_global_random(unsigned char *_randBuff, uint64_t size); -EXTERNC uint8_t* getThreadLocalDecryptedDkgPoly(); +EXTERNC uint8_t *getThreadLocalDecryptedDkgPoly(); -EXTERNC void LOG_INFO(const char* msg); -EXTERNC void LOG_WARN(const char* _msg); -EXTERNC void LOG_ERROR(const char* _msg); -EXTERNC void LOG_DEBUG(const char* _msg); -EXTERNC void LOG_TRACE(const char* _msg); +EXTERNC void LOG_INFO(const char *msg); +EXTERNC void LOG_WARN(const char *_msg); +EXTERNC void LOG_ERROR(const char *_msg); +EXTERNC void LOG_DEBUG(const char *_msg); +EXTERNC void LOG_TRACE(const char *_msg); extern uint32_t globalLogLevel_; -extern unsigned char* globalRandom; +extern unsigned char *globalRandom; extern domain_parameters curve; -#define SAFE_FREE(__X__) if (__X__) {free(__X__); __X__ = NULL;} -#define SAFE_DELETE(__X__) if (__X__) {delete(__X__); __X__ = NULL;} -#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__); -#define RANDOM_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; get_global_random( \ -(unsigned char*) __X__, __Y__); - -#define CHECK_ARG_CLEAN(_EXPRESSION_) \ - if (!(_EXPRESSION_)) { \ - LOG_ERROR("State check failed::");LOG_ERROR(#_EXPRESSION_); \ - LOG_ERROR(__FILE__); LOG_ERROR(__FUNCTION__);\ - goto clean;} - - -#endif //SGXWALLET_ENCLAVECOMMON_H +#define SAFE_FREE(__X__) \ + if (__X__) { \ + free(__X__); \ + __X__ = NULL; \ + } +#define SAFE_DELETE(__X__) \ + if (__X__) { \ + delete (__X__); \ + __X__ = NULL; \ + } +#define SAFE_CHAR_BUF(__X__, __Y__) \ + ; \ + char __X__[__Y__]; \ + memset(__X__, 0, __Y__); +#define RANDOM_CHAR_BUF(__X__, __Y__) \ + ; \ + char __X__[__Y__]; \ + get_global_random((unsigned char *)__X__, __Y__); + +#define CHECK_ARG_CLEAN(_EXPRESSION_) \ + if (!(_EXPRESSION_)) { \ + LOG_ERROR("State check failed::"); \ + LOG_ERROR(#_EXPRESSION_); \ + LOG_ERROR(__FILE__); \ + LOG_ERROR(__FUNCTION__); \ + goto clean; \ + } + +#endif // SGXWALLET_ENCLAVECOMMON_H diff --git a/secure_enclave/EnclaveConstants.h b/secure_enclave/EnclaveConstants.h index ba1fec5e..75555d70 100644 --- a/secure_enclave/EnclaveConstants.h +++ b/secure_enclave/EnclaveConstants.h @@ -36,7 +36,7 @@ #define ADD_ENTROPY_SIZE 32 -#define DKG_BUFER_LENGTH 2496//3060 +#define DKG_BUFER_LENGTH 2496 // 3060 #define DKG_MAX_SEALED_LEN 3100 #define SECRET_SHARE_NUM_BYTES 96 @@ -56,4 +56,4 @@ #define ENCRYPTED_KEY_TOO_LONG -6 #define SEAL_KEY_FAILED -7 -#endif //SGXD_ENCLAVE_COMMON_H +#endif // SGXD_ENCLAVE_COMMON_H diff --git a/secure_enclave/HKDF.c b/secure_enclave/HKDF.c new file mode 100644 index 00000000..a327f059 --- /dev/null +++ b/secure_enclave/HKDF.c @@ -0,0 +1,112 @@ +/* + Copyright (C) 2019-Present SKALE Labs + + This file is part of sgxwallet. + + sgxwallet is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + sgxwallet is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with sgxwallet. If not, see . + + @file HKDF.c + @author Oleh Nikolaiev + @date 2023 +*/ + +#include +#include +#include +#include +#include +#include + +#ifdef USER_SPACE +#include +#else + +#include <../tgmp-build/include/sgx_tgmp.h> + +#endif + +#include "EnclaveCommon.h" +#include "EnclaveConstants.h" + +int hkdfExtract(char* salt, char* seed, char* prk) { + int ret = -1; + + if (!salt) { + LOG_ERROR("hkdfExtract: null salt"); + return ret; + } + + if (!seed) { + LOG_ERROR("hkdfExtract: null seed"); + return ret; + } + + if (!prk) { + LOG_ERROR("hkdfExtract: null prk"); + return ret; + } + + ret = sgx_hmac_sha256_msg((unsigned char*)salt, ECDSA_BIN_LEN - 1, seed, ECDSA_BIN_LEN, prk, ECDSA_BIN_LEN - 1); + + return ret; +} + +int hkdfExpand(char* prk, char* keyInfo, int length, char* okm) { + int ret = -1; + + if (!prk) { + LOG_ERROR("hkdfExpand: null prk"); + return ret; + } + + if (!keyInfo) { + LOG_ERROR("hkdfExpand: null key_info"); + return ret; + } + + if (!okm) { + LOG_ERROR("hkdfExpand: null okm"); + return ret; + } + + int n = ceil(length / (ECDSA_BIN_LEN - 1)); + + SAFE_CHAR_BUF(t, BUF_LEN); + SAFE_CHAR_BUF(tmp, BUF_LEN); + for (int i = 0; i < n; ++i) { + char hex[4] = "0x01"; + snprintf(hex + 3, 1, "%d", i + 1); + SAFE_CHAR_BUF(toHash, BUF_LEN); + if (i > 0) { + strncat(toHash, tmp, ECDSA_BIN_LEN - 1); + } + strncat(toHash, keyInfo, ECDSA_BIN_LEN - 1); + strncat(toHash, hex, 4); + + ret = sgx_hmac_sha256_msg(prk, ECDSA_BIN_LEN - 1, toHash, ECDSA_BIN_LEN, tmp, ECDSA_BIN_LEN - 1); + if (ret != 0) { + return ret; + } + + for (int j = 0; j < ECDSA_BIN_LEN - 1; ++j) { + t[(ECDSA_BIN_LEN - 1) * i + j] = tmp[j]; + } + } + + for (int i = 0; i < length; ++i) { + okm[i] = t[i]; + } + + return ret; +} diff --git a/secure_enclave/HKDF.h b/secure_enclave/HKDF.h new file mode 100644 index 00000000..9481065b --- /dev/null +++ b/secure_enclave/HKDF.h @@ -0,0 +1,31 @@ +/* + Copyright (C) 2019-Present SKALE Labs + + This file is part of sgxwallet. + + sgxwallet is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + sgxwallet is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with sgxwallet. If not, see . + + @file HKDF.h + @author Oleh Nikolaiev + @date 2023 +*/ + +#ifndef SGX_HKDF_H +#define SGX_HKDF_H + +int hkdfExtract(char *salt, char *seed, char *prk); + +int hkdfExpand(char *prk, char *keyInfo, int length, char *okm); + +#endif // SGX_HKDF_H diff --git a/secure_enclave/Makefile.am b/secure_enclave/Makefile.am index d81e848b..411c348c 100644 --- a/secure_enclave/Makefile.am +++ b/secure_enclave/Makefile.am @@ -83,10 +83,10 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \ secure_enclave.c \ - Curves.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \ - DKGUtils.cpp TEUtils.cpp EnclaveCommon.cpp DomainParameters.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \ - ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \ - ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG) + Curves.c NumberTheory.c Point.c Signature.c DHDkg.c HKDF.c AESUtils.c \ + DKGUtils.cpp TEUtils.cpp EnclaveCommon.cpp DomainParameters.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \ + ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \ + ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG) ## Add additional linker flags to AM_LDFLAGS here. Don't put diff --git a/secure_enclave/NumberTheory.h b/secure_enclave/NumberTheory.h index 0379a3ea..b15588ea 100644 --- a/secure_enclave/NumberTheory.h +++ b/secure_enclave/NumberTheory.h @@ -25,9 +25,8 @@ *Handbook of applied cryptography: Algorithm 2.143. */ void number_theory_exp_modp(mpz_t R, mpz_t a, mpz_t k, mpz_t P); - -/*Calculate the multiplicative inverse of a mod p, using the extended euclidean algorithm - *Handbook of applied cryptography: Algorithm 2.107 +/*Calculate the multiplicative inverse of a mod p, using the extended euclidean + *algorithm Handbook of applied cryptography: Algorithm 2.107 *http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm */ void number_theory_inverse(mpz_t R, mpz_t A, mpz_t P); diff --git a/secure_enclave/Point.h b/secure_enclave/Point.h index 1358f4e6..869c0036 100644 --- a/secure_enclave/Point.h +++ b/secure_enclave/Point.h @@ -21,13 +21,9 @@ @date 2019 */ - #ifndef SGXWALLET_POINT_H #define SGXWALLET_POINT_H - - - #include "DomainParameters.h" /*Initialize a point*/ @@ -52,13 +48,16 @@ EXTERNC int point_set_hex(point p, const char *x, const char *y); EXTERNC void point_set_ui(point p, unsigned long int x, unsigned long int y); /*Addition of point P + Q = result*/ -EXTERNC void point_addition(point result, point P, point Q, domain_parameters curve); +EXTERNC void point_addition(point result, point P, point Q, + domain_parameters curve); /*Set point R = 2P*/ EXTERNC void point_doubling(point R, point P, domain_parameters curve); -/*Perform scalar multiplication to P, with the factor multiplier, over the curve curve*/ -EXTERNC void point_multiplication(point R, mpz_t multiplier, point P, domain_parameters curve); +/*Perform scalar multiplication to P, with the factor multiplier, over the curve + * curve*/ +EXTERNC void point_multiplication(point R, mpz_t multiplier, point P, + domain_parameters curve); /*Set point from strings of a base from 2-62*/ EXTERNC int point_set_str(point p, const char *x, const char *y, int base); @@ -66,10 +65,10 @@ EXTERNC int point_set_str(point p, const char *x, const char *y, int base); /*Compare two points return 1 if not the same, returns 0 if they are the same*/ EXTERNC bool point_cmp(point P, point Q); - /*Compress a point to hexadecimal string - *This function is implemented as specified in SEC 1: Elliptic Curve Cryptography, section 2.3.3.*/ -EXTERNC char* point_compress(point P); + *This function is implemented as specified in SEC 1: Elliptic Curve + *Cryptography, section 2.3.3.*/ +EXTERNC char *point_compress(point P); /*Make R a copy of P*/ EXTERNC void point_copy(point R, point P); diff --git a/secure_enclave/Signature.h b/secure_enclave/Signature.h index 82a6e1f1..761cf861 100644 --- a/secure_enclave/Signature.h +++ b/secure_enclave/Signature.h @@ -31,26 +31,27 @@ #endif /*Type for representing a signature*/ -struct signature_s -{ - mpz_t r; - mpz_t s; - unsigned int v; +struct signature_s { + mpz_t r; + mpz_t s; + unsigned int v; }; -typedef struct signature_s* signature; +typedef struct signature_s *signature; /*Initialize a signature*/ EXTERNC signature signature_init(); /*Set signature from strings of a base from 2-62*/ -EXTERNC int signature_set_str(signature sig, const char *r, const char *s, int base); +EXTERNC int signature_set_str(signature sig, const char *r, const char *s, + int base); /*Set signature from hexadecimal strings*/ EXTERNC int signature_set_hex(signature sig, const char *r, const char *s); /*Set signature from decimal unsigned long ints*/ -EXTERNC void signature_set_ui(signature sig, unsigned long int r, unsigned long int s); +EXTERNC void signature_set_ui(signature sig, unsigned long int r, + unsigned long int s); /*Print signature to standart output stream*/ EXTERNC void signature_print(signature sig); @@ -58,19 +59,23 @@ EXTERNC void signature_print(signature sig); /*Make R a copy of P*/ EXTERNC void signature_copy(signature R, signature sig); -/*Compare two signatures return 1 if not the same, returns 0 if they are the same*/ +/*Compare two signatures return 1 if not the same, returns 0 if they are the + * same*/ EXTERNC bool signature_cmp(signature sig1, signature sig2); /*Release signature*/ EXTERNC void signature_free(signature sig); /*Generates a public key for a private key*/ -EXTERNC void signature_extract_public_key(point public_key, mpz_t private_key, domain_parameters curve); +EXTERNC void signature_extract_public_key(point public_key, mpz_t private_key, + domain_parameters curve); /*Generate signature for a message*/ -EXTERNC void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_parameters curve); +EXTERNC void signature_sign(signature sig, mpz_t message, mpz_t private_key, + domain_parameters curve); /*Verify the integrity of a message using it's signature*/ -EXTERNC bool signature_verify(mpz_t message, signature sig, point public_key, domain_parameters curve); +EXTERNC bool signature_verify(mpz_t message, signature sig, point public_key, + domain_parameters curve); #endif diff --git a/secure_enclave/TEUtils.cpp b/secure_enclave/TEUtils.cpp index 6947f3c9..eabc761e 100644 --- a/secure_enclave/TEUtils.cpp +++ b/secure_enclave/TEUtils.cpp @@ -47,165 +47,170 @@ #include <../SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp> -#include "EnclaveConstants.h" #include "EnclaveCommon.h" +#include "EnclaveConstants.h" #include "TEUtils.h" -template +template std::string fieldElementToString(const T &field_elem, int base = 10) { - std::string ret; + std::string ret; - mpz_t t; - mpz_init(t); + mpz_t t; + mpz_init(t); - try { + try { - field_elem.as_bigint().to_mpz(t); + field_elem.as_bigint().to_mpz(t); - SAFE_CHAR_BUF(arr, BUF_LEN); + SAFE_CHAR_BUF(arr, BUF_LEN); - char *tmp = mpz_get_str(arr, base, t); + char *tmp = mpz_get_str(arr, base, t); - ret = std::string(tmp); + ret = std::string(tmp); - goto clean; + goto clean; - } catch (std::exception &e) { - LOG_ERROR(e.what()); - goto clean; - } catch (...) { - LOG_ERROR("Unknown throwable"); - goto clean; - } + } catch (std::exception &e) { + LOG_ERROR(e.what()); + goto clean; + } catch (...) { + LOG_ERROR("Unknown throwable"); + goto clean; + } - clean: - mpz_clear(t); - return ret; +clean: + mpz_clear(t); + return ret; } -std::string ConvertG2ElementToString(const libff::alt_bn128_G2 &elem, int base = 10, const std::string &delim = ":") { +std::string ConvertG2ElementToString(const libff::alt_bn128_G2 &elem, + int base = 10, + const std::string &delim = ":") { - std::string result = ""; + std::string result = ""; - try { + try { - result += fieldElementToString(elem.X.c0); - result += delim; - result += fieldElementToString(elem.X.c1); - result += delim; - result += fieldElementToString(elem.Y.c0); - result += delim; - result += fieldElementToString(elem.Y.c1); + result += fieldElementToString(elem.X.c0); + result += delim; + result += fieldElementToString(elem.X.c1); + result += delim; + result += fieldElementToString(elem.Y.c0); + result += delim; + result += fieldElementToString(elem.Y.c1); - return result; - - } catch (std::exception &e) { - LOG_ERROR(e.what()); - return result; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return result; - } + return result; + } catch (std::exception &e) { + LOG_ERROR(e.what()); return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return result; + } + + return result; } -std::vector SplitStringToFq(const char *coords, const char symbol) { - std::vector result; - std::string str(coords); - std::string delim; - - CHECK_ARG_CLEAN(coords); - - try { - - delim.push_back(symbol); - - size_t prev = 0, pos = 0; - do { - pos = str.find(delim, prev); - if (pos == std::string::npos) pos = str.length(); - std::string token = str.substr(prev, pos - prev); - if (!token.empty()) { - libff::alt_bn128_Fq coeff(token.c_str()); - result.push_back(coeff); - } - prev = pos + delim.length(); - } while (pos < str.length() && prev < str.length()); - - return result; - - } catch (std::exception &e) { - LOG_ERROR(e.what()); - return result; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return result; - } +std::vector SplitStringToFq(const char *coords, + const char symbol) { + std::vector result; + std::string str(coords); + std::string delim; - clean: - return result; -} + CHECK_ARG_CLEAN(coords); -EXTERNC int getDecryptionShare(char* skey_hex, char* decryptionValue, char* decryption_share) { - mpz_t skey; - mpz_init(skey); + try { - int ret = 1; + delim.push_back(symbol); - CHECK_ARG_CLEAN(skey_hex); - CHECK_ARG_CLEAN(decryptionValue); - CHECK_ARG_CLEAN(decryption_share); + size_t prev = 0, pos = 0; + do { + pos = str.find(delim, prev); + if (pos == std::string::npos) + pos = str.length(); + std::string token = str.substr(prev, pos - prev); + if (!token.empty()) { + libff::alt_bn128_Fq coeff(token.c_str()); + result.push_back(coeff); + } + prev = pos + delim.length(); + } while (pos < str.length() && prev < str.length()); - try { - if (mpz_set_str(skey, skey_hex, 16) == -1) { - mpz_clear(skey); - return 1; - } + return result; - char skey_dec[mpz_sizeinbase(skey, 10) + 2]; - mpz_get_str(skey_dec, 10, skey); + } catch (std::exception &e) { + LOG_ERROR(e.what()); + return result; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return result; + } - libff::alt_bn128_Fr bls_skey(skey_dec); +clean: + return result; +} - auto splitted_decryption_value = SplitStringToFq(decryptionValue, ':'); +EXTERNC int getDecryptionShare(char *skey_hex, char *decryptionValue, + char *decryption_share) { + mpz_t skey; + mpz_init(skey); - libff::alt_bn128_G2 decryption_value; - decryption_value.Z = libff::alt_bn128_Fq2::one(); + int ret = 1; - decryption_value.X.c0 = splitted_decryption_value[0]; - decryption_value.X.c1 = splitted_decryption_value[1]; - decryption_value.Y.c0 = splitted_decryption_value[2]; - decryption_value.Y.c1 = splitted_decryption_value[3]; + CHECK_ARG_CLEAN(skey_hex); + CHECK_ARG_CLEAN(decryptionValue); + CHECK_ARG_CLEAN(decryption_share); - if ( !decryption_value.is_well_formed() ) { - mpz_clear(skey); - return 1; - } + try { + if (mpz_set_str(skey, skey_hex, 16) == -1) { + mpz_clear(skey); + return 1; + } - libff::alt_bn128_G2 decryption_share_point = bls_skey * decryption_value; - decryption_share_point.to_affine_coordinates(); + char skey_dec[mpz_sizeinbase(skey, 10) + 2]; + mpz_get_str(skey_dec, 10, skey); - std::string result = ConvertG2ElementToString(decryption_share_point); + libff::alt_bn128_Fr bls_skey(skey_dec); - strncpy(decryption_share, result.c_str(), result.length()); + auto splitted_decryption_value = SplitStringToFq(decryptionValue, ':'); - mpz_clear(skey); + libff::alt_bn128_G2 decryption_value; + decryption_value.Z = libff::alt_bn128_Fq2::one(); - return 0; + decryption_value.X.c0 = splitted_decryption_value[0]; + decryption_value.X.c1 = splitted_decryption_value[1]; + decryption_value.Y.c0 = splitted_decryption_value[2]; + decryption_value.Y.c1 = splitted_decryption_value[3]; - } catch (std::exception &e) { - LOG_ERROR(e.what()); - return 1; - } catch (...) { - LOG_ERROR("Unknown throwable"); - return 1; + if (!decryption_value.is_well_formed()) { + mpz_clear(skey); + return 1; } - clean: + libff::alt_bn128_G2 decryption_share_point = bls_skey * decryption_value; + decryption_share_point.to_affine_coordinates(); + + std::string result = ConvertG2ElementToString(decryption_share_point); + + strncpy(decryption_share, result.c_str(), result.length()); + mpz_clear(skey); - return ret; + + return 0; + + } catch (std::exception &e) { + LOG_ERROR(e.what()); + return 1; + } catch (...) { + LOG_ERROR("Unknown throwable"); + return 1; + } + +clean: + mpz_clear(skey); + return ret; } #endif diff --git a/secure_enclave/TEUtils.h b/secure_enclave/TEUtils.h index 0e5c5442..afe5931d 100644 --- a/secure_enclave/TEUtils.h +++ b/secure_enclave/TEUtils.h @@ -37,6 +37,7 @@ #include <../tgmp-build/include/sgx_tgmp.h> #endif -EXTERNC int getDecryptionShare(char* secret, char* decryptionValue, char* decryption_share); +EXTERNC int getDecryptionShare(char *secret, char *decryptionValue, + char *decryption_share); #endif diff --git a/secure_enclave/Verify.h b/secure_enclave/Verify.h index 4a7365b2..1a5e2443 100644 --- a/secure_enclave/Verify.h +++ b/secure_enclave/Verify.h @@ -25,9 +25,9 @@ #define USER_SPACE 1 -#include "secure_enclave/Point.h" +#include "secure_enclave/Curves.h" #include "secure_enclave/DomainParameters.h" #include "secure_enclave/NumberTheory.h" +#include "secure_enclave/Point.h" #include "secure_enclave/Signature.h" -#include "secure_enclave/Curves.h" -#endif //SGXWALLET_VERIFY_H +#endif // SGXWALLET_VERIFY_H diff --git a/secure_enclave/secure_enclave.c b/secure_enclave/secure_enclave.c index c65bcb94..02878482 100644 --- a/secure_enclave/secure_enclave.c +++ b/secure_enclave/secure_enclave.c @@ -53,6 +53,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Signature.h" #include "Curves.h" #include "DHDkg.h" +#include "HKDF.h" #include "AESUtils.h" #include "TEUtils.h" @@ -912,52 +913,52 @@ void trustedGetEncryptedSecretShare(int *errStatus, char *errString, } 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 *_encryptedPoly, uint64_t _encLen, + uint8_t *encryptedSkey, uint64_t *decLen, + char *resultStr, char *secretShareG2, char *pubKeyB, uint8_t _t, uint8_t _n, uint8_t ind) { LOG_INFO(__FUNCTION__); INIT_ERROR_STATE - uint64_t enc_len; + uint64_t encLen; int status; - CHECK_STATE(encrypted_skey); - CHECK_STATE(result_str); - CHECK_STATE(s_shareG2); - CHECK_STATE(pub_keyB); + CHECK_STATE(encryptedSkey); + CHECK_STATE(resultStr); + CHECK_STATE(secretShareG2); + CHECK_STATE(pubKeyB); LOG_DEBUG(__FUNCTION__); - trustedSetEncryptedDkgPoly(&status, errString, _encrypted_poly, _enc_len); + trustedSetEncryptedDkgPoly(&status, errString, _encryptedPoly, _encLen); 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); + SAFE_CHAR_BUF(pubKeyX, BUF_LEN); + SAFE_CHAR_BUF(pubKeyY, BUF_LEN); int is_exportable = 1; - trustedGenerateEcdsaKey(&status, errString, &is_exportable, encrypted_skey, &enc_len, pub_key_x, pub_key_y); + trustedGenerateEcdsaKey(&status, errString, &is_exportable, encryptedSkey, &encLen, pubKeyX, pubKeyY); CHECK_STATUS("trustedGenerateEcdsaKey failed"); uint8_t type = 0; uint8_t exportable = 0; - status = AES_decrypt(encrypted_skey, enc_len, skey, BUF_LEN, &type, &exportable); + status = AES_decrypt(encryptedSkey, encLen, 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; + *decLen = encLen; - SAFE_CHAR_BUF(common_key, BUF_LEN); + SAFE_CHAR_BUF(commonKey, BUF_LEN); - status = gen_session_key(skey, pub_keyB, common_key); + status = gen_session_key(skey, pubKeyB, commonKey); CHECK_STATUS("gen_session_key failed") @@ -966,22 +967,22 @@ void trustedGetEncryptedSecretShareV2(int *errStatus, char *errString, status = calc_secret_share(getThreadLocalDecryptedDkgPoly(), s_share, _t, _n, ind); CHECK_STATUS("calc secret share failed") - status = calc_secret_shareG2(s_share, s_shareG2); + status = calc_secret_shareG2(s_share, secretShareG2); CHECK_STATUS("invalid decr secret share"); - SAFE_CHAR_BUF(derived_key, BUF_LEN); - status = hash_key(common_key, derived_key); + SAFE_CHAR_BUF(derivedKey, BUF_LEN); + status = hash_key(commonKey, derivedKey, ECDSA_BIN_LEN - 1, true); CHECK_STATUS("hash key failed") - derived_key[ECDSA_BIN_LEN - 1] = 0; + derivedKey[ECDSA_BIN_LEN - 1] = 0; SAFE_CHAR_BUF(cypher, BUF_LEN); - status = xor_encrypt_v2(derived_key, s_share, cypher); + status = xor_encrypt_v2(derivedKey, 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)); + strncpy(resultStr, cypher, strlen(cypher)); + strncpy(resultStr + strlen(cypher), pubKeyX, strlen(pubKeyX)); + strncpy(resultStr + strlen(pubKeyX) + strlen(pubKeyY), pubKeyY, strlen(pubKeyY)); SET_SUCCESS @@ -1074,14 +1075,14 @@ void trustedDkgVerify(int *errStatus, char *errString, const char *public_shares 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) { +void trustedDkgVerifyV2(int *errStatus, char *errString, const char *publicShares, const char *secretShare, + uint8_t *encryptedPrivateKey, uint64_t encLen, unsigned _t, int _ind, int *result) { LOG_INFO(__FUNCTION__); INIT_ERROR_STATE - CHECK_STATE(public_shares); - CHECK_STATE(s_share); + CHECK_STATE(publicShares); + CHECK_STATE(secretShare); CHECK_STATE(encryptedPrivateKey); SAFE_CHAR_BUF(skey,BUF_LEN); @@ -1092,36 +1093,36 @@ void trustedDkgVerifyV2(int *errStatus, char *errString, const char *public_shar uint8_t type = 0; uint8_t exportable = 0; - int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, BUF_LEN, + int status = AES_decrypt(encryptedPrivateKey, encLen, skey, BUF_LEN, &type, &exportable); CHECK_STATUS2("AES_decrypt failed (in trustedDkgVerifyAES) with status %d"); - SAFE_CHAR_BUF(encr_sshare, BUF_LEN); + SAFE_CHAR_BUF(encrSshare, BUF_LEN); - strncpy(encr_sshare, s_share, ECDSA_SKEY_LEN - 1); + strncpy(encrSshare, secretShare, ECDSA_SKEY_LEN - 1); - SAFE_CHAR_BUF(common_key, BUF_LEN); + SAFE_CHAR_BUF(commonKey, BUF_LEN); - status = session_key_recover(skey, s_share, common_key); + status = session_key_recover(skey, secretShare, commonKey); CHECK_STATUS("session_key_recover failed"); - SAFE_CHAR_BUF(derived_key, BUF_LEN); - status = hash_key(common_key, derived_key); + SAFE_CHAR_BUF(derivedKey, BUF_LEN); + status = hash_key(commonKey, derivedKey, ECDSA_BIN_LEN - 1, true); CHECK_STATUS("hash key failed") - derived_key[ECDSA_BIN_LEN - 1] = 0; + derivedKey[ECDSA_BIN_LEN - 1] = 0; - SAFE_CHAR_BUF(decr_sshare, BUF_LEN); + SAFE_CHAR_BUF(decrSshare, BUF_LEN); - status = xor_decrypt_v2(derived_key, encr_sshare, decr_sshare); + status = xor_decrypt_v2(derivedKey, encrSshare, decrSshare); CHECK_STATUS("xor_decrypt failed") - status = mpz_set_str(s, decr_sshare, 16); + status = mpz_set_str(s, decrSshare, 16); CHECK_STATUS("invalid decr secret share"); - *result = Verification(public_shares, s, _t, _ind); + *result = Verification(publicShares, s, _t, _ind); SET_SUCCESS clean: @@ -1234,17 +1235,17 @@ void trustedCreateBlsKey(int *errStatus, char *errString, const char *s_shares, LOG_INFO("SGX call completed"); } -void trustedCreateBlsKeyV2(int *errStatus, char *errString, const char *s_shares, - uint8_t *encryptedPrivateKey, uint64_t key_len, uint8_t *encr_bls_key, - uint64_t *enc_bls_key_len) { +void trustedCreateBlsKeyV2(int *errStatus, char *errString, const char *secretShares, + uint8_t *encryptedPrivateKey, uint64_t keyLen, uint8_t *encrBlsKey, + uint64_t *encBlsKeyLen) { LOG_INFO(__FUNCTION__); INIT_ERROR_STATE - CHECK_STATE(s_shares); + CHECK_STATE(secretShares); CHECK_STATE(encryptedPrivateKey); - CHECK_STATE(encr_bls_key); + CHECK_STATE(encrBlsKey); SAFE_CHAR_BUF(skey, BUF_LEN); @@ -1256,87 +1257,87 @@ void trustedCreateBlsKeyV2(int *errStatus, char *errString, const char *s_shares mpz_init(q); mpz_set_str(q, "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10); - mpz_t bls_key; - mpz_init(bls_key); + mpz_t blsKey; + mpz_init(blsKey); uint8_t type = 0; uint8_t exportable = 0; - int status = AES_decrypt(encryptedPrivateKey, key_len, skey, BUF_LEN, + int status = AES_decrypt(encryptedPrivateKey, keyLen, skey, BUF_LEN, &type, &exportable); CHECK_STATUS2("aes decrypt failed with status %d"); skey[ECDSA_SKEY_LEN - 1] = 0; - int num_shares = strlen(s_shares) / 192; + int numShares = strlen(secretShares) / 192; - for (int i = 0; i < num_shares; i++) { - SAFE_CHAR_BUF(encr_sshare, 65); - strncpy(encr_sshare, s_shares + 192 * i, 64); - encr_sshare[64] = 0; + for (int i = 0; i < numShares; i++) { + SAFE_CHAR_BUF(encrSecretShare, 65); + strncpy(encrSecretShare, secretShares + 192 * i, 64); + encrSecretShare[64] = 0; - SAFE_CHAR_BUF(s_share, 193); - strncpy(s_share, s_shares + 192 * i, 192); - s_share[192] = 0; + SAFE_CHAR_BUF(secretShare, 193); + strncpy(secretShare, secretShares + 192 * i, 192); + secretShare[192] = 0; - SAFE_CHAR_BUF(common_key, 65); + SAFE_CHAR_BUF(commonKey, 65); - status = session_key_recover(skey, s_share, common_key); + status = session_key_recover(skey, secretShare, commonKey); CHECK_STATUS("session_key_recover failed"); - common_key[64] = 0; + commonKey[64] = 0; - SAFE_CHAR_BUF(derived_key, BUF_LEN); - status = hash_key(common_key, derived_key); + SAFE_CHAR_BUF(derivedKey, BUF_LEN); + status = hash_key(commonKey, derivedKey, ECDSA_BIN_LEN - 1, true); CHECK_STATUS("hash key failed") - derived_key[ECDSA_BIN_LEN - 1] = 0; + derivedKey[ECDSA_BIN_LEN - 1] = 0; - SAFE_CHAR_BUF(decr_sshare, 65); + SAFE_CHAR_BUF(decrSecretShare, 65); - status = xor_decrypt_v2(derived_key, encr_sshare, decr_sshare); + status = xor_decrypt_v2(derivedKey, encrSecretShare, decrSecretShare); CHECK_STATUS("xor_decrypt failed"); - decr_sshare[64] = 0; + decrSecretShare[64] = 0; - mpz_t decr_secret_share; - mpz_init(decr_secret_share); - if (mpz_set_str(decr_secret_share, decr_sshare, 16) == -1) { + mpz_t decryptedSecretShare; + mpz_init(decryptedSecretShare); + if (mpz_set_str(decryptedSecretShare, decrSecretShare, 16) == -1) { *errStatus = 111; snprintf(errString, BUF_LEN, "invalid decrypted secret share"); LOG_ERROR(errString); - mpz_clear(decr_secret_share); + mpz_clear(decryptedSecretShare); goto clean; } - mpz_addmul_ui(sum, decr_secret_share, 1); - mpz_clear(decr_secret_share); + mpz_addmul_ui(sum, decryptedSecretShare, 1); + mpz_clear(decryptedSecretShare); } - mpz_mod(bls_key, sum, q); + mpz_mod(blsKey, sum, q); - SAFE_CHAR_BUF(key_share, BLS_KEY_LENGTH); + SAFE_CHAR_BUF(keyShare, BLS_KEY_LENGTH); - SAFE_CHAR_BUF(arr_skey_str, BUF_LEN); + SAFE_CHAR_BUF(arrSkeyStr, BUF_LEN); - mpz_get_str(arr_skey_str, 16, bls_key); - int n_zeroes = 64 - strlen(arr_skey_str); - for (int i = 0; i < n_zeroes; i++) { - key_share[i] = '0'; + mpz_get_str(arrSkeyStr, 16, blsKey); + int nZeroes = 64 - strlen(arrSkeyStr); + for (int i = 0; i < nZeroes; i++) { + keyShare[i] = '0'; } - strncpy(key_share + n_zeroes, arr_skey_str, 65 - n_zeroes); - key_share[BLS_KEY_LENGTH - 1] = 0; + strncpy(keyShare + nZeroes, arrSkeyStr, 65 - nZeroes); + keyShare[BLS_KEY_LENGTH - 1] = 0; - status = AES_encrypt(key_share, encr_bls_key, BUF_LEN, BLS, NON_EXPORTABLE, enc_bls_key_len); + status = AES_encrypt(keyShare, encrBlsKey, BUF_LEN, BLS, NON_EXPORTABLE, encBlsKeyLen); CHECK_STATUS2("aes encrypt bls private key failed with status %d "); SET_SUCCESS clean: - mpz_clear(bls_key); + mpz_clear(blsKey); mpz_clear(sum); mpz_clear(q); LOG_INFO(__FUNCTION__ ); @@ -1406,3 +1407,127 @@ void trustedGetDecryptionShare( int *errStatus, char* errString, uint8_t* encryp clean: ; } + +void trustedGenerateBLSKey(int *errStatus, char *errString, int *isExportable, + uint8_t *encryptedPrivateKey, uint64_t *encLen) { + LOG_INFO(__FUNCTION__); + INIT_ERROR_STATE + + CHECK_STATE(encryptedPrivateKey); + + RANDOM_CHAR_BUF(randChar, 32); + + mpz_t seed; + mpz_init(seed); + + mpz_import(seed, 32, 1, sizeof(randChar[0]), 0, 0, randChar); + + SAFE_CHAR_BUF(ikm, mpz_sizeinbase(seed, 16) + 2); + + mpz_get_str(ikm, 16, seed); + + mpz_t q; + mpz_init(q); + mpz_set_str(q, "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10); + + mpz_t skey; + mpz_init(skey); + + mpz_set_ui(skey, 0); + + char salt[39] = "424c532d5349472d4b455947454e2d53414c54"; // "BLS-SIG-KEYGEN-SALT" hexademical + + int L = 48; // math.ceil(3*math.ceil(math.log2(q))/16) + char l[2] = "30"; // octet L + + int k = 0; + while (mpz_cmp_ui(skey, 0) == 0) { + SAFE_CHAR_BUF(saltHashed, BUF_LEN); + int len = strnlen(salt, 39); + int status; + if (len > ECDSA_BIN_LEN - 1) + status = hash_key(salt, saltHashed, len, true); + else + status = hash_key(salt, saltHashed, len, false); + CHECK_STATUS("hash key failed") + + SAFE_CHAR_BUF(ikmConcat, BUF_LEN); + strncat(ikmConcat, ikm, ECDSA_BIN_LEN - 1); + ikmConcat[ECDSA_BIN_LEN - 1] = '\0'; + + SAFE_CHAR_BUF(octetStr0, 2); + octetStr0[0] = '0'; + octetStr0[1] = '\0'; + + strncat(ikmConcat, octetStr0, 1); + ikmConcat[ECDSA_BIN_LEN] = '\0'; + + SAFE_CHAR_BUF(prk, BUF_LEN); + status = hkdfExtract(saltHashed, ikmConcat, prk); + CHECK_STATUS("hkdfExtract failed"); + prk[ECDSA_BIN_LEN - 1] = '\0'; + + SAFE_CHAR_BUF(okm, BUF_LEN); + status = hkdfExpand(prk, l, L, okm); + CHECK_STATUS("hkdfExpand failed"); + + SAFE_CHAR_BUF(blsKey, BUF_LEN); + carray2Hex((unsigned char*)okm, ECDSA_BIN_LEN - 1, blsKey); + + if (mpz_set_str(skey, blsKey, 16) == -1) { + *errStatus = 111; + snprintf(errString, BUF_LEN, "error in mpz_set_str"); + LOG_ERROR(errString); + + goto clean; + } + + mpz_mod(skey, skey, q); + + if (mpz_cmp_ui(skey, 0) == 0) { + for (int i = 0; i < ECDSA_BIN_LEN - 1; ++i) { + salt[i] = saltHashed[i]; + } + salt[ECDSA_BIN_LEN - 1] = '\0'; + } + } + + mpz_mod(skey, seed, q); + + SAFE_CHAR_BUF(blsKey, BLS_KEY_LENGTH); + + SAFE_CHAR_BUF(arrSkeyStr, BUF_LEN); + + if (mpz_get_str(arrSkeyStr, 16, skey) == -1) { + *errStatus = 111; + snprintf(errString, BUF_LEN, "error in mpz_get_str"); + LOG_ERROR(errString); + + goto clean; + } + + int nZeroes = 64 - strlen(arrSkeyStr); + for (int i = 0; i < nZeroes; i++) { + blsKey[i] = '0'; + } + strncpy(blsKey + nZeroes, arrSkeyStr, 65 - nZeroes); + blsKey[BLS_KEY_LENGTH - 1] = 0; + + int status; + if (isExportable) { + status = AES_encrypt(blsKey, encryptedPrivateKey, BUF_LEN, BLS, EXPORTABLE, encLen); + } else { + status = AES_encrypt(blsKey, encryptedPrivateKey, BUF_LEN, BLS, NON_EXPORTABLE, encLen); + } + + CHECK_STATUS2("aes encrypt bls private key failed with status %d "); + + SET_SUCCESS + clean: + + mpz_clear(seed); + mpz_clear(skey); + mpz_clear(q); + LOG_INFO(__FUNCTION__ ); + LOG_INFO("SGX call completed"); +} diff --git a/secure_enclave/secure_enclave.config.xml.sim b/secure_enclave/secure_enclave.config.xml.sim index 3ab37b39..a0e26c3b 100644 --- a/secure_enclave/secure_enclave.config.xml.sim +++ b/secure_enclave/secure_enclave.config.xml.sim @@ -3,9 +3,9 @@ 3 0x200000 0x200000 - 20 - 20 - 20 + 25 + 25 + 25 0 0 diff --git a/secure_enclave/secure_enclave.edl b/secure_enclave/secure_enclave.edl index 82cf6e64..e802a690 100644 --- a/secure_enclave/secure_enclave.edl +++ b/secure_enclave/secure_enclave.edl @@ -187,7 +187,15 @@ enclave { [in, count = 320] const char* public_decryption_value, uint64_t key_len, [out, count = 320] char* decrption_share); - }; + + public void trustedGenerateBLSKey( + [out] int *errStatus, + [out, count = SMALL_BUF_SIZE] char* errString, + [in, count = 1] int *isExportable, + [out, count = SMALL_BUF_SIZE] uint8_t* encryptedKey, + [out] uint64_t *encLen + ); + }; untrusted { include "gmp.h" diff --git a/sgx-gmp b/sgx-gmp index 2331e681..8b8f2ed1 160000 --- a/sgx-gmp +++ b/sgx-gmp @@ -1 +1 @@ -Subproject commit 2331e6810cd4a8434f70ac3b81fe10f5d7e5d641 +Subproject commit 8b8f2ed146004ae3636789951b35790552cb0f1b diff --git a/sgx-software-enable b/sgx-software-enable index 8c8f69d4..7977d6dd 160000 --- a/sgx-software-enable +++ b/sgx-software-enable @@ -1 +1 @@ -Subproject commit 8c8f69d40f89d80d52e4061dce10bb772bdd2fd1 +Subproject commit 7977d6dd373f3a14a615ee9be6f24ecd37c0b43d diff --git a/sgx_util b/sgx_util new file mode 100755 index 00000000..ce05382c Binary files /dev/null and b/sgx_util differ diff --git a/sgx_util.cpp b/sgx_util.cpp index 88f527c3..2f089341 100644 --- a/sgx_util.cpp +++ b/sgx_util.cpp @@ -21,103 +21,113 @@ @date 2019 */ -#include +#include "common.h" +#include "stubclient.h" #include +#include #include -#include "stubclient.h" -#include "common.h" #include -int print_hashes(){ - jsonrpc::HttpClient client("http://localhost:1028"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Client inited" << std::endl; - std::cout << c.getUnsignedCSRs() << std::endl; - exit(0); +int print_hashes() { + jsonrpc::HttpClient client("http://localhost:1028"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Client inited" << std::endl; + std::cout << c.getUnsignedCSRs() << std::endl; + exit(0); } -void sign_by_hash(std::string & hash, int status){ - jsonrpc::HttpClient client("http://localhost:1028"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Client inited" << std::endl; - std::cout << c.signByHash(hash, status) << std::endl; - exit(0); +void sign_by_hash(std::string &hash, int status) { + jsonrpc::HttpClient client("http://localhost:1028"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Client inited" << std::endl; + std::cout << c.signByHash(hash, status) << std::endl; + exit(0); } void getNumberOfKeysCreated() { - jsonrpc::HttpClient client("http://localhost:1030"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Info client inited" << std::endl; - std::cout << c.getAllKeysInfo()["keysNumber"].asString() << std::endl; - exit(0); + jsonrpc::HttpClient client("http://localhost:1030"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Info client inited" << std::endl; + std::cout << c.getAllKeysInfo()["keysNumber"].asString() << std::endl; + exit(0); } void getAllKeysInfo() { - jsonrpc::HttpClient client("http://localhost:1030"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Info client inited" << std::endl; - std::cout << c.getAllKeysInfo()["allKeys"].asString() << std::endl; - std::cout << "TOTAL KEYS IN DATABASE: " << c.getAllKeysInfo()["keysNumber"].asString() << std::endl; - exit(0); + jsonrpc::HttpClient client("http://localhost:1030"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Info client inited" << std::endl; + std::cout << c.getAllKeysInfo()["allKeys"].asString() << std::endl; + std::cout << "TOTAL KEYS IN DATABASE: " + << c.getAllKeysInfo()["keysNumber"].asString() << std::endl; + exit(0); } void getLatestCreatedKey() { - jsonrpc::HttpClient client("http://localhost:1030"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Info client inited" << std::endl; - Json::Value lastCreatedKey = c.getLatestCreatedKey(); - std::cout << "Last created key name: " << lastCreatedKey["keyName"] << std::endl; - std::string timestamp_to_date_command = "date -d @" + lastCreatedKey["creationTime"].asString(); - std::cout << "Last created key creation time: " << exec(timestamp_to_date_command.c_str()); - exit(0); + jsonrpc::HttpClient client("http://localhost:1030"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Info client inited" << std::endl; + Json::Value lastCreatedKey = c.getLatestCreatedKey(); + std::cout << "Last created key name: " << lastCreatedKey["keyName"] + << std::endl; + std::string timestamp_to_date_command = + "date -d @" + lastCreatedKey["creationTime"].asString(); + std::cout << "Last created key creation time: " + << exec(timestamp_to_date_command.c_str()); + exit(0); } void getServerConfiguration() { - jsonrpc::HttpClient client("http://localhost:1030"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Info client inited" << std::endl; - Json::Value response = c.getServerConfiguration(); - std::cout << "OPTION autoConfirm certificates switched to " << response["autoConfirm"] << '\n'; - uint32_t logLevel = response["logLevel"].asInt(); - std::string logLevelStr; - switch(logLevel) { - case 0: - logLevelStr = "trace"; - break; - case 1: - logLevelStr = "debug"; - break; - case 2: - logLevelStr = "info"; - break; - case 3: - logLevelStr = "warning"; - break; - case 4: - logLevelStr = "error"; - break; - } + jsonrpc::HttpClient client("http://localhost:1030"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Info client inited" << std::endl; + Json::Value response = c.getServerConfiguration(); + std::cout << "OPTION autoConfirm certificates switched to " + << response["autoConfirm"] << '\n'; + uint32_t logLevel = response["logLevel"].asInt(); + std::string logLevelStr; + switch (logLevel) { + case 0: + logLevelStr = "trace"; + break; + case 1: + logLevelStr = "debug"; + break; + case 2: + logLevelStr = "info"; + break; + case 3: + logLevelStr = "warning"; + break; + case 4: + logLevelStr = "error"; + break; + } - std::cout << "OPTION logLevel switched to " << logLevelStr << '\n'; - std::cout << "OPTION enterBackupKey switched to " << response["enterBackupKey"] << '\n'; - std::cout << "OPTION useHTTPS switched to " << response["useHTTPS"] << '\n'; - std::cout << "OPTION autoSign certificates switched to " << response["autoSign"] << '\n'; - std::cout << "OPTION checkCerts switched to " << response["checkCerts"] << '\n'; - std::cout << "OPTION generateTestKeys switched to " << response["generateTestKeys"] << '\n'; - exit(0); + std::cout << "OPTION logLevel switched to " << logLevelStr << '\n'; + std::cout << "OPTION enterBackupKey switched to " + << response["enterBackupKey"] << '\n'; + std::cout << "OPTION useHTTPS switched to " << response["useHTTPS"] << '\n'; + std::cout << "OPTION autoSign certificates switched to " + << response["autoSign"] << '\n'; + std::cout << "OPTION checkCerts switched to " << response["checkCerts"] + << '\n'; + std::cout << "OPTION generateTestKeys switched to " + << response["generateTestKeys"] << '\n'; + exit(0); } -void isKeyExists(const std::string& key) { - jsonrpc::HttpClient client("http://localhost:1030"); - StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); - std::cout << "Info client inited" << std::endl; - if (c.isKeyExist(key)["IsExist"].asBool()) { - std::cout << "Key with name " << key << " presents in server database.\n"; - } else { - std::cout << "Key with name " << key << " does not exist in server's database.\n"; - } - exit(0); +void isKeyExists(const std::string &key) { + jsonrpc::HttpClient client("http://localhost:1030"); + StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2); + std::cout << "Info client inited" << std::endl; + if (c.isKeyExist(key)["IsExist"].asBool()) { + std::cout << "Key with name " << key << " presents in server database.\n"; + } else { + std::cout << "Key with name " << key + << " does not exist in server's database.\n"; + } + exit(0); } int main(int argc, char *argv[]) { @@ -137,42 +147,46 @@ int main(int argc, char *argv[]) { std::cout << " -l print latest created key" << std::endl; std::cout << " -n print number of keys stored in database" << std::endl; std::cout << " -c print server's config" << std::endl; - std::cout << " -i [name] check if key with such name presents in database" << std::endl; + std::cout << " -i [name] check if key with such name presents in database" + << std::endl; exit(0); } std::string hash; std::string key; while ((opt = getopt(argc, argv, "ps:r:alci:n")) != -1) { - switch (opt) { - case 'p': print_hashes(); - break; - case 's': hash = optarg; - sign_by_hash(hash, 0); - break; - case 'r': hash = optarg; - sign_by_hash(hash, 2); - break; - case 'a': - getAllKeysInfo(); - break; - case 'l': - getLatestCreatedKey(); - break; - case 'c': - getServerConfiguration(); - break; - case 'i': key = optarg; - isKeyExists(key); - break; - case 'n': - getNumberOfKeysCreated(); - break; - case '?': // fprintf(stderr, "unknown flag\n"); - exit(1); - } + switch (opt) { + case 'p': + print_hashes(); + break; + case 's': + hash = optarg; + sign_by_hash(hash, 0); + break; + case 'r': + hash = optarg; + sign_by_hash(hash, 2); + break; + case 'a': + getAllKeysInfo(); + break; + case 'l': + getLatestCreatedKey(); + break; + case 'c': + getServerConfiguration(); + break; + case 'i': + key = optarg; + isKeyExists(key); + break; + case 'n': + getNumberOfKeysCreated(); + break; + case '?': // fprintf(stderr, "unknown flag\n"); + exit(1); + } } return 0; } - diff --git a/sgxwall.cpp b/sgxwall.cpp index 42740c90..b638f475 100644 --- a/sgxwall.cpp +++ b/sgxwall.cpp @@ -38,201 +38,207 @@ #include "zmq_src/ZMQServer.h" -#include "testw.h" #include "sgxwall.h" #include "sgxwallet.h" - +#include "testw.h" void SGXWallet::printUsage() { - cerr << "\nAvailable flags:\n"; - cerr << "\nDebug flags:\n\n"; - cerr << " -v Verbose mode: turn on debug output\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"; - cerr << "\nSecurity flags flags:\n\n"; - cerr << " -n Use http instead of https. Default is to use https with a selg-signed server cert. Insecure! \n"; - cerr << " -c Disable client authentication using certificates. Insecure!\n"; - cerr << " -s Sign client certificates without human confirmation. Insecure! \n"; - cerr << " -e Only owner of the key can access it.\n"; + cerr << "\nAvailable flags:\n"; + cerr << "\nDebug flags:\n\n"; + cerr << " -v Verbose mode: turn on debug output\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"; + cerr << "\nSecurity flags flags:\n\n"; + cerr << " -n Use http instead of https. Default is to use https with a " + "selg-signed server cert. Insecure! \n"; + cerr + << " -c Disable client authentication using certificates. Insecure!\n"; + cerr << " -s Sign client certificates without human confirmation. " + "Insecure! \n"; + cerr << " -e Only owner of the key can access it.\n"; } +void SGXWallet::serializeKeys(const vector &_ecdsaKeyNames, + const vector &_blsKeyNames, + const string &_fileName) { + Json::Value top(Json::objectValue); + Json::Value ecdsaKeysJson(Json::objectValue); + Json::Value blsKeysJson(Json::objectValue); -void SGXWallet::serializeKeys(const vector& _ecdsaKeyNames, const vector& _blsKeyNames, const string& _fileName) { - Json::Value top(Json::objectValue); - Json::Value ecdsaKeysJson(Json::objectValue); - Json::Value blsKeysJson(Json::objectValue); - - for (uint i = 0; i < _ecdsaKeyNames.size(); i++) { - auto key = to_string(i + 1); + for (uint i = 0; i < _ecdsaKeyNames.size(); i++) { + auto key = to_string(i + 1); - string keyFull(3 - key.size(), '0'); - keyFull.append(key); + string keyFull(3 - key.size(), '0'); + keyFull.append(key); - ecdsaKeysJson[keyFull] = _ecdsaKeyNames[i]; - blsKeysJson[keyFull] = _blsKeyNames[i]; - } + ecdsaKeysJson[keyFull] = _ecdsaKeyNames[i]; + blsKeysJson[keyFull] = _blsKeyNames[i]; + } - top["ecdsaKeyNames"] = ecdsaKeysJson; - top["blsKeyNames"] = blsKeysJson; + top["ecdsaKeyNames"] = ecdsaKeysJson; + top["blsKeyNames"] = blsKeysJson; - ofstream fs; + ofstream fs; - fs.open(_fileName); + fs.open(_fileName); - fs << top; + fs << top; - fs.close(); + fs.close(); } -void SGXWallet::signalHandler( int signalNo ) { - spdlog::info("Received exit signal {}.", signalNo); - ExitHandler::exitHandler( signalNo ); +void SGXWallet::signalHandler(int signalNo) { + spdlog::info("Received exit signal {}.", signalNo); + ExitHandler::exitHandler(signalNo); } - int main(int argc, char *argv[]) { - bool enterBackupKeyOption = false; - bool useHTTPSOption = true; - bool printDebugInfoOption = false; - bool printTraceInfoOption = false; - bool autoconfirmOption = false; - bool checkClientCertOption = true; - bool autoSignClientCertOption = false; - bool generateTestKeys = false; - bool checkKeyOwnership = false; - - std::signal(SIGABRT, SGXWallet::signalHandler); - - int opt; - - if (argc > 1 && strlen(argv[1]) == 1) { - SGXWallet::printUsage(); - exit(-21); + bool enterBackupKeyOption = false; + bool useHTTPSOption = true; + bool printDebugInfoOption = false; + bool printTraceInfoOption = false; + bool autoconfirmOption = false; + bool checkClientCertOption = true; + bool autoSignClientCertOption = false; + bool generateTestKeys = false; + bool checkKeyOwnership = false; + + std::signal(SIGABRT, SGXWallet::signalHandler); + + int opt; + + if (argc > 1 && strlen(argv[1]) == 1) { + SGXWallet::printUsage(); + exit(-21); + } + + while ((opt = getopt(argc, argv, "cshd0abyvVneT")) != -1) { + switch (opt) { + case 'h': + SGXWallet::printUsage(); + exit(-22); + case 'c': + checkClientCertOption = false; + break; + case 's': + autoSignClientCertOption = true; + break; + case 'd': + printDebugInfoOption = true; + break; + case 'v': + printDebugInfoOption = true; + break; + case 'V': + printDebugInfoOption = true; + printTraceInfoOption = true; + break; + case '0': + useHTTPSOption = false; + break; + case 'n': + useHTTPSOption = false; + checkKeyOwnership = false; + break; + case 'e': + checkKeyOwnership = true; + break; + case 'a': + enterBackupKeyOption = false; + break; + case 'b': + enterBackupKeyOption = true; + break; + case 'y': + autoconfirmOption = true; + break; + case 'T': + generateTestKeys = true; + break; + default: + SGXWallet::printUsage(); + exit(-23); + break; } + } - while ((opt = getopt(argc, argv, "cshd0abyvVneT")) != -1) { - switch (opt) { - case 'h': - SGXWallet::printUsage(); - exit(-22); - case 'c': - checkClientCertOption = false; - break; - case 's': - autoSignClientCertOption = true; - break; - case 'd': - printDebugInfoOption = true; - break; - case 'v': - printDebugInfoOption = true; - break; - case 'V': - printDebugInfoOption = true; - printTraceInfoOption = true; - break; - case '0': - useHTTPSOption = false; - break; - case 'n': - useHTTPSOption = false; - checkKeyOwnership = false; - break; - case 'e': - checkKeyOwnership = true; - break; - case 'a': - enterBackupKeyOption = false; - break; - case 'b': - enterBackupKeyOption = true; - break; - case 'y': - autoconfirmOption = true; - break; - case 'T': - generateTestKeys = true; - break; - default: - SGXWallet::printUsage(); - exit(-23); - break; - } - } + uint64_t logLevel = L_INFO; - uint64_t logLevel = L_INFO; + if (printDebugInfoOption) { + logLevel = L_DEBUG; + } - if (printDebugInfoOption) { - logLevel = L_DEBUG; - } + if (printTraceInfoOption) { + logLevel = L_TRACE; + } - if (printTraceInfoOption) { - logLevel = L_TRACE; - } + setFullOptions(logLevel, useHTTPSOption, autoconfirmOption, + enterBackupKeyOption); - setFullOptions(logLevel, useHTTPSOption, autoconfirmOption, enterBackupKeyOption); + uint32_t enclaveLogLevel = L_INFO; - uint32_t enclaveLogLevel = L_INFO; + if (printDebugInfoOption) { + enclaveLogLevel = L_DEBUG; + } - if (printDebugInfoOption) { - enclaveLogLevel = L_DEBUG; - } + if (printTraceInfoOption) { + enclaveLogLevel = L_TRACE; + } - if (printTraceInfoOption) { - enclaveLogLevel = L_TRACE; - } + cerr << "Calling initAll ..." << endl; + initAll(enclaveLogLevel, checkClientCertOption, checkClientCertOption, + autoSignClientCertOption, generateTestKeys, checkKeyOwnership); + cerr << "Completed initAll." << endl; - cerr << "Calling initAll ..." << endl; - initAll(enclaveLogLevel, checkClientCertOption, checkClientCertOption, autoSignClientCertOption, generateTestKeys, checkKeyOwnership); - cerr << "Completed initAll." << endl; + // check if test keys already exist - //check if test keys already exist + string TEST_KEYS_4_NODE = "sgx_data/4node.json"; - string TEST_KEYS_4_NODE = "sgx_data/4node.json"; + ifstream is(TEST_KEYS_4_NODE); + auto keysExist = is.good(); - ifstream is(TEST_KEYS_4_NODE); - auto keysExist = is.good(); + if (keysExist) { + cerr << "Found test keys." << endl; + } - if (keysExist) { - cerr << "Found test keys." << endl; - } + if (generateTestKeys && !keysExist && !ExitHandler::shouldExit()) { + cerr << "Generating test keys ..." << endl; - if (generateTestKeys && !keysExist && !ExitHandler::shouldExit()) { - cerr << "Generating test keys ..." << endl; + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); + vector ecdsaKeyNames; + vector blsKeyNames; - vector ecdsaKeyNames; - vector blsKeyNames; + int schainID = 1; + int dkgID = 1; - int schainID = 1; - int dkgID = 1; + TestUtils::doDKG(c, 4, 3, ecdsaKeyNames, blsKeyNames, schainID, dkgID); - TestUtils::doDKG(c, 4, 3, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + SGXWallet::serializeKeys(ecdsaKeyNames, blsKeyNames, "sgx_data/4node.json"); - SGXWallet::serializeKeys(ecdsaKeyNames, blsKeyNames, "sgx_data/4node.json"); + schainID = 2; + dkgID = 2; - schainID = 2; - dkgID = 2; + TestUtils::doDKG(c, 16, 11, ecdsaKeyNames, blsKeyNames, schainID, dkgID); - TestUtils::doDKG(c, 16, 11, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + SGXWallet::serializeKeys(ecdsaKeyNames, blsKeyNames, + "sgx_data/16node.json"); - SGXWallet::serializeKeys(ecdsaKeyNames, blsKeyNames, "sgx_data/16node.json"); + cerr << "Successfully completed generating test keys into sgx_data" << endl; + } - cerr << "Successfully completed generating test keys into sgx_data" << endl; - } - - while ( !ExitHandler::shouldExit() ) { - sleep(10); - } + while (!ExitHandler::shouldExit()) { + sleep(10); + } - ExitHandler::exit_code_t exitCode = ExitHandler::requestedExitCode(); - int signal = ExitHandler::getSignal(); - spdlog::info("Will exit with exit code {}", exitCode); - exitAll(); - spdlog::info("Exiting with exit code {} and signal", exitCode, signal); - return exitCode; + ExitHandler::exit_code_t exitCode = ExitHandler::requestedExitCode(); + int signal = ExitHandler::getSignal(); + spdlog::info("Will exit with exit code {}", exitCode); + exitAll(); + spdlog::info("Exiting with exit code {} and signal", exitCode, signal); + return exitCode; } diff --git a/sgxwall.h b/sgxwall.h index f6e57e6a..f626a47a 100644 --- a/sgxwall.h +++ b/sgxwall.h @@ -21,16 +21,14 @@ @date 2020 */ - class SGXWallet { public: + static void signalHandler(int signalNo); - static void signalHandler( int signalNo ); - - static void printUsage(); - - static void serializeKeys( const vector& _ecdsaKeyNames, - const vector& _blsKeyNames, const string& _fileName); + static void printUsage(); + static void serializeKeys(const vector &_ecdsaKeyNames, + const vector &_blsKeyNames, + const string &_fileName); }; diff --git a/sgxwallet.h b/sgxwallet.h index d7944c22..e85a40a5 100644 --- a/sgxwallet.h +++ b/sgxwallet.h @@ -36,10 +36,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SGXWALLET_SGXWALLET_H #define SGXWALLET_SGXWALLET_H - +#include "secure_enclave_u.h" #include "sgxwallet_common.h" #include "third_party/intel/create_enclave.h" -#include "secure_enclave_u.h" #include "third_party/intel/sgx_detect.h" #include #include @@ -50,6 +49,12 @@ extern sgx_launch_token_t token; #define ENCLAVE_NAME "secure_enclave.signed.so" -enum log_level {L_TRACE = 0, L_DEBUG = 1, L_INFO = 2,L_WARNING = 3, L_ERROR = 4 }; +enum log_level { + L_TRACE = 0, + L_DEBUG = 1, + L_INFO = 2, + L_WARNING = 3, + L_ERROR = 4 +}; -#endif //SGXWALLET_SGXWALLET_H +#endif // SGXWALLET_SGXWALLET_H diff --git a/sgxwallet_common.h b/sgxwallet_common.h index cbc4bd43..447548db 100644 --- a/sgxwallet_common.h +++ b/sgxwallet_common.h @@ -36,11 +36,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SGXD_SGXD_COMMON_H #define SGXD_SGXD_COMMON_H +#include #include #include -#include -#include #include +#include #include @@ -67,7 +67,6 @@ extern bool autoconfirm; #define ECDSA_ENCR_LEN 93 #define ECDSA_BIN_LEN 33 - #define PLAINTEXT_KEY_TOO_LONG -2 #define UNPADDED_KEY -3 #define NULL_KEY -4 @@ -140,7 +139,7 @@ extern bool autoconfirm; #define INVALID_DKG_VV_V2_ECDSA_KEY_NAME -67 #define INVALID_DKG_VV_V2_PARAMS -68 #define INVALID_DKG_VV_V2_SS_HEX -69 -#define INVALID_DKG_VV_V2_SS_COUNT -70 +#define INVALID_DKG_VV_V2_SS_COUNT -70 #define EXCEPTION_IN_CONVERT_HEX_TO_DEC -71 #define GET_SS_V2_INVALID_HEX -72 #define EXCEPTION_IN_CONVERT_G2_STRING -73 @@ -187,6 +186,10 @@ extern bool autoconfirm; #define INVALID_DECRYPTION_VALUE_FORMAT -114 #define INVALID_KEY_FORMAT -115 #define KEY_ALREADY_REGISTERED -116 +#define POP_PROVE_INVALID_KEY_NAME -117 +#define COULD_NOT_CREATE_POP_PROVE -118 +#define GENERATE_BLS_KEY_INVALID_NAME -119 +#define INVALID_CREATE_BLS_AGGREGATED_KEY -120 #define SGX_ENCLAVE_ERROR -666 @@ -200,6 +203,4 @@ extern bool autoconfirm; #define TEST_VALUE "1234567890" - - -#endif //SGXWALLET_SGXWALLET_COMMON_H +#endif // SGXWALLET_SGXWALLET_COMMON_H diff --git a/stubclient.cpp b/stubclient.cpp index 06718338..7671b68e 100644 --- a/stubclient.cpp +++ b/stubclient.cpp @@ -30,15 +30,15 @@ using namespace jsonrpc; using namespace std; int init_client() { - HttpClient client("http://localhost:1025"); - StubClient c(client, JSONRPC_CLIENT_V2); + HttpClient client("http://localhost:1025"); + StubClient c(client, JSONRPC_CLIENT_V2); - Json::Value params; + Json::Value params; - try { - cout << c.generateECDSAKey() << endl; - } catch (JsonRpcException &e) { - cerr << e.what() << endl; - } - return 0; + try { + cout << c.generateECDSAKey() << endl; + } catch (JsonRpcException &e) { + cerr << e.what() << endl; + } + return 0; } diff --git a/stubclient.h b/stubclient.h index 7a5cf703..90f373f8 100644 --- a/stubclient.h +++ b/stubclient.h @@ -5,386 +5,464 @@ #ifndef JSONRPC_CPP_STUB_STUBCLIENT_H_ #define JSONRPC_CPP_STUB_STUBCLIENT_H_ -#include #include +#include -class StubClient : public jsonrpc::Client -{ - public: - StubClient(jsonrpc::IClientConnector &conn, jsonrpc::clientVersion_t type = jsonrpc::JSONRPC_CLIENT_V2) : jsonrpc::Client(conn, type) {} - - Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName) - { - Json::Value p; - p["keyShare"] = keyShare; - p["keyShareName"] = keyShareName; - Json::Value result = this->CallMethod("importBLSKeyShare",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int t, int n) - { - Json::Value p; - p["keyShareName"] = keyShareName; - p["messageHash"] = messageHash; - p["n"] = n; - p["t"] = t; - Json::Value result = this->CallMethod("blsSignMessageHash",p); - if (result.isObject()) - return result; - else - 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; - p = Json::nullValue; - Json::Value result = this->CallMethod("generateECDSAKey",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getPublicECDSAKey(const std::string& keyName) - { - Json::Value p; - p["keyName"] = keyName; - Json::Value result = this->CallMethod("getPublicECDSAKey",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value ecdsaSignMessageHash(int base, const std::string& keyName, const std::string& messageHash) - { - Json::Value p; - p["base"] = base; - p["keyName"] = keyName; - p["messageHash"] = messageHash; - Json::Value result = this->CallMethod("ecdsaSignMessageHash",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value generateDKGPoly(const std::string& polyName, int t) - { - Json::Value p; - p["polyName"] = polyName; - p["t"] = t; - Json::Value result = this->CallMethod("generateDKGPoly",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getVerificationVector(const std::string& polyName, int t) - { - Json::Value p; - p["polyName"] = polyName; - p["t"] = t; - Json::Value result = this->CallMethod("getVerificationVector",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getSecretShare(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("getSecretShare",p); - if (result.isObject()) - return result; - else - 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; - p["ethKeyName"] = ethKeyName; - p["secretShare"] = SecretShare; - p["index"] = index; - p["n"] = n; - p["publicShares"] = publicShares; - p["t"] = t; - Json::Value result = this->CallMethod("dkgVerification",p); - if (result.isObject()) - return result; - else - 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; - p["blsKeyName"] = blsKeyName; - p["ethKeyName"] = ethKeyName; - p["polyName"] = polyName; - p["secretShare"] = SecretShare; - p["n"] = n; - p["t"] = t; - Json::Value result = this->CallMethod("createBLSPrivateKey",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value createBLSPrivateKeyV2(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n) - { - Json::Value p; - p["blsKeyName"] = blsKeyName; - p["ethKeyName"] = ethKeyName; - p["polyName"] = polyName; - p["secretShare"] = SecretShare; - p["n"] = n; - p["t"] = t; - Json::Value result = this->CallMethod("createBLSPrivateKeyV2",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getBLSPublicKeyShare(const std::string & blsKeyName) - { - Json::Value p; - p["blsKeyName"] = blsKeyName; - - Json::Value result = this->CallMethod("getBLSPublicKeyShare",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getDecryptionShares(const std::string& blsKeyName, const Json::Value& publicDecryptionValues) - { - Json::Value p; - p["blsKeyName"] = blsKeyName; - p["publicDecryptionValues"] = publicDecryptionValues["publicDecryptionValues"]; - - Json::Value result = this->CallMethod("getDecryptionShares",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) - { - Json::Value p; - p["publicShares"] = publicShares["publicShares"]; - p["t"] = t; - p["n"] = n; - - Json::Value result = this->CallMethod("calculateAllBLSPublicKeys", p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value complaintResponse(const std::string& polyName, int 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()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value multG2(const std::string & x) - { - Json::Value p; - p["x"] = x; - - Json::Value result = this->CallMethod("multG2",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value isPolyExists(const std::string & polyName) - { - Json::Value p; - p["polyName"] = polyName; - - Json::Value result = this->CallMethod("isPolyExists",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value deleteBlsKey(const std::string & polyName) - { - Json::Value p; - p["blsKeyName"] = polyName; - - Json::Value result = this->CallMethod("deleteBlsKey",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getServerStatus() - { - Json::Value p; - p = Json::nullValue; - Json::Value result = this->CallMethod("getServerStatus",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getServerVersion() { - Json::Value p; - p = Json::nullValue; - Json::Value result = this->CallMethod("getServerVersion",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - - ////CSRManagerServer - - Json::Value getUnsignedCSRs() - { - Json::Value p; - p = Json::nullValue; - Json::Value result = this->CallMethod("getUnsignedCSRs",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value signByHash(const std::string& hash, int status) - { - Json::Value p; - p["hash"] = hash; - p["status"] = status; - Json::Value result = this->CallMethod("signByHash",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - - /// InfoServer - - Json::Value getAllKeysInfo() - { - Json::Value p; - p = Json::nullValue; - Json::Value result = this->CallMethod("getAllKeysInfo", p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getLatestCreatedKey() - { - Json::Value p; - p = Json::nullValue; - Json::Value result = this->CallMethod("getLatestCreatedKey", p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value getServerConfiguration() - { - Json::Value p; - p = Json::nullValue; - Json::Value result = this->CallMethod("getServerConfiguration", p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - - Json::Value isKeyExist(const std::string& key) - { - Json::Value p; - p["keyName"] = key; - Json::Value result = this->CallMethod("isKeyExist", p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - } - +class StubClient : public jsonrpc::Client { +public: + StubClient(jsonrpc::IClientConnector &conn, + jsonrpc::clientVersion_t type = jsonrpc::JSONRPC_CLIENT_V2) + : jsonrpc::Client(conn, type) {} + + Json::Value importBLSKeyShare(const std::string &keyShare, + const std::string &keyShareName) { + Json::Value p; + p["keyShare"] = keyShare; + p["keyShareName"] = keyShareName; + Json::Value result = this->CallMethod("importBLSKeyShare", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value blsSignMessageHash(const std::string &keyShareName, + const std::string &messageHash, int t, int n) { + Json::Value p; + p["keyShareName"] = keyShareName; + p["messageHash"] = messageHash; + p["n"] = n; + p["t"] = t; + Json::Value result = this->CallMethod("blsSignMessageHash", p); + if (result.isObject()) + return result; + else + 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; + p = Json::nullValue; + Json::Value result = this->CallMethod("generateECDSAKey", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getPublicECDSAKey(const std::string &keyName) { + Json::Value p; + p["keyName"] = keyName; + Json::Value result = this->CallMethod("getPublicECDSAKey", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value ecdsaSignMessageHash(int base, const std::string &keyName, + const std::string &messageHash) { + Json::Value p; + p["base"] = base; + p["keyName"] = keyName; + p["messageHash"] = messageHash; + Json::Value result = this->CallMethod("ecdsaSignMessageHash", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value generateDKGPoly(const std::string &polyName, int t) { + Json::Value p; + p["polyName"] = polyName; + p["t"] = t; + Json::Value result = this->CallMethod("generateDKGPoly", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getVerificationVector(const std::string &polyName, int t) { + Json::Value p; + p["polyName"] = polyName; + p["t"] = t; + Json::Value result = this->CallMethod("getVerificationVector", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getSecretShare(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("getSecretShare", p); + if (result.isObject()) + return result; + else + 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 ðKeyName, + 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("dkgVerification", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value dkgVerificationV2(const std::string &publicShares, + const std::string ðKeyName, + 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 ðKeyName, + const std::string &polyName, + const std::string &SecretShare, int t, + int n) { + Json::Value p; + p["blsKeyName"] = blsKeyName; + p["ethKeyName"] = ethKeyName; + p["polyName"] = polyName; + p["secretShare"] = SecretShare; + p["n"] = n; + p["t"] = t; + Json::Value result = this->CallMethod("createBLSPrivateKey", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value createBLSPrivateKeyV2(const std::string &blsKeyName, + const std::string ðKeyName, + const std::string &polyName, + const std::string &SecretShare, int t, + int n) { + Json::Value p; + p["blsKeyName"] = blsKeyName; + p["ethKeyName"] = ethKeyName; + p["polyName"] = polyName; + p["secretShare"] = SecretShare; + p["n"] = n; + p["t"] = t; + Json::Value result = this->CallMethod("createBLSPrivateKeyV2", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value generateBLSPrivateKey(const std::string &blsKeyName) { + Json::Value p; + p["blsKeyName"] = blsKeyName; + + Json::Value result = this->CallMethod("generateBLSPrivateKey", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getBLSPublicKeyShare(const std::string &blsKeyName) { + Json::Value p; + p["blsKeyName"] = blsKeyName; + + Json::Value result = this->CallMethod("getBLSPublicKeyShare", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getDecryptionShares(const std::string &blsKeyName, + const Json::Value &publicDecryptionValues) { + Json::Value p; + p["blsKeyName"] = blsKeyName; + p["publicDecryptionValues"] = + publicDecryptionValues["publicDecryptionValues"]; + + Json::Value result = this->CallMethod("getDecryptionShares", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value calculateAllBLSPublicKeys(const Json::Value &publicShares, int t, + int n) { + Json::Value p; + p["publicShares"] = publicShares["publicShares"]; + p["t"] = t; + p["n"] = n; + + Json::Value result = this->CallMethod("calculateAllBLSPublicKeys", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value complaintResponse(const std::string &polyName, int 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()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value popProve(const std::string &blsKeyName) { + Json::Value p; + p["blsKeyName"] = blsKeyName; + + Json::Value result = this->CallMethod("popProve", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value multG2(const std::string &x) { + Json::Value p; + p["x"] = x; + + Json::Value result = this->CallMethod("multG2", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value isPolyExists(const std::string &polyName) { + Json::Value p; + p["polyName"] = polyName; + + Json::Value result = this->CallMethod("isPolyExists", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value deleteBlsKey(const std::string &polyName) { + Json::Value p; + p["blsKeyName"] = polyName; + + Json::Value result = this->CallMethod("deleteBlsKey", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getServerStatus() { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("getServerStatus", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getServerVersion() { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("getServerVersion", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + ////CSRManagerServer + + Json::Value getUnsignedCSRs() { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("getUnsignedCSRs", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value signByHash(const std::string &hash, int status) { + Json::Value p; + p["hash"] = hash; + p["status"] = status; + Json::Value result = this->CallMethod("signByHash", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + /// InfoServer + + Json::Value getAllKeysInfo() { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("getAllKeysInfo", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getLatestCreatedKey() { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("getLatestCreatedKey", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value getServerConfiguration() { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("getServerConfiguration", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } + + Json::Value isKeyExist(const std::string &key) { + Json::Value p; + p["keyName"] = key; + Json::Value result = this->CallMethod("isKeyExist", p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException( + jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, + result.toStyledString()); + } }; -#endif //JSONRPC_CPP_STUB_STUBCLIENT_H_ +#endif // JSONRPC_CPP_STUB_STUBCLIENT_H_ diff --git a/testw.cpp b/testw.cpp index aad0e550..064e7e17 100644 --- a/testw.cpp +++ b/testw.cpp @@ -21,199 +21,199 @@ @date 2020 */ -#include -#include -#include -#include +#include "secure_enclave/DHDkg.h" +#include "secure_enclave_u.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 #include -#include -#include #include +#include +#include #include +#include +#include #include "BLSCrypto.h" #include "CryptoTools.h" -#include "ServerInit.h" #include "DKGCrypto.h" -#include "SGXException.h" #include "LevelDB.h" +#include "SGXException.h" #include "SGXWalletServer.hpp" +#include "ServerInit.h" #define CATCH_CONFIG_MAIN -#include "catch.hpp" -#include "stubclient.h" +#include "BLSPublicKey.h" +#include "BLSPublicKeyShare.h" #include "BLSSigShare.h" #include "BLSSigShareSet.h" -#include "BLSPublicKeyShare.h" -#include "BLSPublicKey.h" #include "SEKManager.h" -#include #include "common.h" +#include "stubclient.h" +#include "third_party/catch.hpp" +#include #include "SGXRegistrationServer.h" #include "SGXWalletServer.h" -#include "zmq_src/ZMQClient.h" -#include "zmq_src/ZMQServer.h" -#include "sgxwallet.h" #include "TestUtils.h" +#include "sgxwallet.h" #include "testw.h" +#include "zmq_src/ZMQClient.h" +#include "zmq_src/ZMQServer.h" -#define PRINT_SRC_LINE cerr << "Executing line " << to_string(__LINE__) << endl; +#define PRINT_SRC_LINE cerr << "Executing line " << to_string(__LINE__) << endl; using namespace jsonrpc; using namespace std; class TestFixture { public: - TestFixture() { - TestUtils::resetDB(); - setOptions(L_INFO, false, true); - initAll(L_INFO, false, false, true, false, true); - } - - ~TestFixture() { - ZMQServer::exitZMQServer(); - TestUtils::destroyEnclave(); - } + TestFixture() { + TestUtils::resetDB(); + setOptions(L_INFO, false, true); + initAll(L_INFO, false, false, true, false, true); + } + + ~TestFixture() { + // ZMQServer::exitZMQServer(); + TestUtils::destroyEnclave(); + } }; class TestFixtureHTTPS { public: - TestFixtureHTTPS() { - TestUtils::resetDB(); - setOptions(L_INFO, true, true); - initAll(L_INFO, false, true, true, false, true); - } - - ~TestFixtureHTTPS() { - ZMQServer::exitZMQServer(); - TestUtils::destroyEnclave(); - } + TestFixtureHTTPS() { + TestUtils::resetDB(); + setOptions(L_INFO, true, true); + initAll(L_INFO, false, true, true, false, true); + } + + ~TestFixtureHTTPS() { + // ZMQServer::exitZMQServer(); + TestUtils::destroyEnclave(); + } }; class TestFixtureZMQSign { public: - TestFixtureZMQSign() { - TestUtils::resetDB(); - setOptions(L_INFO, false, true); - initAll(L_INFO, false, true, true, false, false); - } - - ~TestFixtureZMQSign() { - ZMQServer::exitZMQServer(); - TestUtils::destroyEnclave(); - } + TestFixtureZMQSign() { + TestUtils::resetDB(); + setOptions(L_INFO, false, true); + initAll(L_INFO, false, true, true, false, false); + } + + ~TestFixtureZMQSign() { + // ZMQServer::exitZMQServer(); + TestUtils::destroyEnclave(); + } }; class TestFixtureNoResetFromBackup { public: - TestFixtureNoResetFromBackup() { - setFullOptions(L_INFO, false, true, true); - initAll(L_INFO, false, false, true, false, true); - } + TestFixtureNoResetFromBackup() { + setFullOptions(L_INFO, false, true, true); + initAll(L_INFO, false, false, true, false, true); + } - ~TestFixtureNoResetFromBackup() { - sleep(3); - ZMQServer::exitZMQServer(); - TestUtils::destroyEnclave(); - } + ~TestFixtureNoResetFromBackup() { + sleep(3); + // ZMQServer::exitZMQServer(); + TestUtils::destroyEnclave(); + } }; class TestFixtureNoReset { public: - TestFixtureNoReset() { - setOptions(L_INFO, false, true); - initAll(L_INFO, false, false, true, false, true); - } - - ~TestFixtureNoReset() { - ZMQServer::exitZMQServer(); - TestUtils::destroyEnclave(); - } + TestFixtureNoReset() { + setOptions(L_INFO, false, true); + initAll(L_INFO, false, false, true, false, true); + } + + ~TestFixtureNoReset() { + // ZMQServer::exitZMQServer(); + TestUtils::destroyEnclave(); + } }; -TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes-key-sig-gen]") { - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - vector encrPrivKey(BUF_LEN, 0); - vector pubKeyX(BUF_LEN, 0); - vector pubKeyY(BUF_LEN, 0); - - uint64_t encLen = 0; - int exportable = 0; +TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", + "[ecdsa-aes-key-sig-gen]") { + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + vector encrPrivKey(BUF_LEN, 0); + vector pubKeyX(BUF_LEN, 0); + vector pubKeyY(BUF_LEN, 0); + + uint64_t encLen = 0; + int exportable = 0; + PRINT_SRC_LINE + auto status = trustedGenerateEcdsaKey( + eid, &errStatus, errMsg.data(), &exportable, encrPrivKey.data(), &encLen, + pubKeyX.data(), pubKeyY.data()); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); + + string hex = SAMPLE_HEX_HASH; + vector signatureR(BUF_LEN, 0); + vector signatureS(BUF_LEN, 0); + uint8_t signatureV = 0; + + for (int i = 0; i < 50; i++) { PRINT_SRC_LINE - auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encrPrivKey.data(), &encLen, - pubKeyX.data(), - pubKeyY.data()); + status = trustedEcdsaSign( + eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen, hex.data(), + signatureR.data(), signatureS.data(), &signatureV, 16); REQUIRE(status == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS); - - string hex = SAMPLE_HEX_HASH; - vector signatureR(BUF_LEN, 0); - vector signatureS(BUF_LEN, 0); - uint8_t signatureV = 0; - - for (int i = 0; i < 50; i++) { - PRINT_SRC_LINE - status = trustedEcdsaSign(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen, - hex.data(), - signatureR.data(), - signatureS.data(), &signatureV, 16); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); - } - + } } TEST_CASE_METHOD(TestFixture, "ECDSA AES key gen", "[ecdsa-aes-key-gen]") { - vector errMsg(BUF_LEN, 0); - int errStatus = 0; - vector encrPrivKey(BUF_LEN, 0); - vector pubKeyX(BUF_LEN, 0); - vector pubKeyY(BUF_LEN, 0); - uint64_t encLen = 0; - int exportable = 0; - PRINT_SRC_LINE - auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encrPrivKey.data(), &encLen, - pubKeyX.data(), - pubKeyY.data()); - - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + vector encrPrivKey(BUF_LEN, 0); + vector pubKeyX(BUF_LEN, 0); + vector pubKeyY(BUF_LEN, 0); + uint64_t encLen = 0; + int exportable = 0; + PRINT_SRC_LINE + auto status = trustedGenerateEcdsaKey( + eid, &errStatus, errMsg.data(), &exportable, encrPrivKey.data(), &encLen, + pubKeyX.data(), pubKeyY.data()); + + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); } -TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", "[ecdsa-aes-get-pub-key]") { - int errStatus = 0; - vector errMsg(BUF_LEN, 0); - vector encPrivKey(BUF_LEN, 0); - vector pubKeyX(BUF_LEN, 0); - vector pubKeyY(BUF_LEN, 0); - - uint64_t encLen = 0; - int exportable = 0; - - PRINT_SRC_LINE - auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encPrivKey.data(), &encLen, pubKeyX.data(), - pubKeyY.data()); - - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); - - vector receivedPubKeyX(BUF_LEN, 0); - vector receivedPubKeyY(BUF_LEN, 0); - - PRINT_SRC_LINE - status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, - receivedPubKeyX.data(), - receivedPubKeyY.data()); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); +TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", + "[ecdsa-aes-get-pub-key]") { + int errStatus = 0; + vector errMsg(BUF_LEN, 0); + vector encPrivKey(BUF_LEN, 0); + vector pubKeyX(BUF_LEN, 0); + vector pubKeyY(BUF_LEN, 0); + + uint64_t encLen = 0; + int exportable = 0; + + PRINT_SRC_LINE + auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), + &exportable, encPrivKey.data(), &encLen, + pubKeyX.data(), pubKeyY.data()); + + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); + + vector receivedPubKeyX(BUF_LEN, 0); + vector receivedPubKeyY(BUF_LEN, 0); + + PRINT_SRC_LINE + status = trustedGetPublicEcdsaKey( + eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, + receivedPubKeyX.data(), receivedPubKeyY.data()); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); } /* Do later @@ -230,1150 +230,1385 @@ TEST_CASE_METHOD("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") { char *encryptedKey = TestUtils::encryptTestKey(); REQUIRE(encryptedKey != nullptr); - char *plaintextKey = decryptBLSKeyShareFromHex(&errStatus, errMsg.data(), encryptedKey); - free(encryptedKey); + char *plaintextKey = decryptBLSKeyShareFromHex(&errStatus, errMsg.data(), +encryptedKey); free(encryptedKey); REQUIRE(errStatus == 0); REQUIRE(strcmp(plaintextKey, TEST_BLS_KEY_SHARE) == 0); - printf("Decrypt key completed with status: %d %s \n", errStatus, errMsg.data()); - printf("Decrypted key len %d\n", (int) strlen(plaintextKey)); + printf("Decrypt key completed with status: %d %s \n", errStatus, +errMsg.data()); printf("Decrypted key len %d\n", (int) strlen(plaintextKey)); printf("Decrypted key: %s\n", plaintextKey); free(plaintextKey); } */ string genECDSAKeyAPI(StubClient &_c) { - Json::Value genKey = _c.generateECDSAKey(); - CHECK_STATE(genKey["status"].asInt() == 0); - auto keyName = genKey["keyName"].asString(); - CHECK_STATE(keyName.size() == ECDSA_KEY_NAME_SIZE); - return keyName; + Json::Value genKey = _c.generateECDSAKey(); + CHECK_STATE(genKey["status"].asInt() == 0); + auto keyName = genKey["keyName"].asString(); + CHECK_STATE(keyName.size() == ECDSA_KEY_NAME_SIZE); + return keyName; } TEST_CASE_METHOD(TestFixture, "ECDSA key gen API", "[ecdsa-key-gen-api]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - - for (int i = 0; i <= 20; i++) { - try { - PRINT_SRC_LINE - auto keyName = genECDSAKeyAPI(c); - PRINT_SRC_LINE - Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH); - REQUIRE(sig["status"].asInt() == 0); - Json::Value getPubKey = c.getPublicECDSAKey(keyName); - REQUIRE(getPubKey["status"].asInt() == 0); - } catch (JsonRpcException &e) { - cerr << e.what() << endl; - throw; - } + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + + for (int i = 0; i <= 20; i++) { + try { + PRINT_SRC_LINE + auto keyName = genECDSAKeyAPI(c); + PRINT_SRC_LINE + Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH); + REQUIRE(sig["status"].asInt() == 0); + Json::Value getPubKey = c.getPublicECDSAKey(keyName); + REQUIRE(getPubKey["status"].asInt() == 0); + } catch (JsonRpcException &e) { + cerr << e.what() << endl; + throw; } + } - auto keyName = genECDSAKeyAPI(c); + auto keyName = genECDSAKeyAPI(c); + + Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH); - Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH); - - for (int i = 0; i <= 20; i++) { - try { - PRINT_SRC_LINE - auto keyName = genECDSAKeyAPI(c); - PRINT_SRC_LINE - Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH); - REQUIRE(sig["status"].asInt() == 0); - PRINT_SRC_LINE - Json::Value getPubKey = c.getPublicECDSAKey(keyName); - REQUIRE(getPubKey["status"].asInt() == 0); - } catch (JsonRpcException &e) { - cerr << e.what() << endl; - throw; - } + for (int i = 0; i <= 20; i++) { + try { + PRINT_SRC_LINE + auto keyName = genECDSAKeyAPI(c); + PRINT_SRC_LINE + Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH); + REQUIRE(sig["status"].asInt() == 0); + PRINT_SRC_LINE + Json::Value getPubKey = c.getPublicECDSAKey(keyName); + REQUIRE(getPubKey["status"].asInt() == 0); + } catch (JsonRpcException &e) { + cerr << e.what() << endl; + throw; } + } } TEST_CASE_METHOD(TestFixture, "BLS key encrypt", "[bls-key-encrypt]") { - auto key = TestUtils::encryptTestKey(); - REQUIRE(key); - sleep(3); + auto key = TestUtils::encryptTestKey(); + REQUIRE(key); + sleep(3); } TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") { - vector encryptedDKGSecret(BUF_LEN, 0); - vector errMsg(BUF_LEN, 0); + vector encryptedDKGSecret(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); - int errStatus = 0; - uint64_t encLen = 0; + int errStatus = 0; + uint64_t encLen = 0; - PRINT_SRC_LINE - auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); + PRINT_SRC_LINE + auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), + encryptedDKGSecret.data(), &encLen, 32); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); - vector secret(BUF_LEN, 0); - vector errMsg1(BUF_LEN, 0); + vector secret(BUF_LEN, 0); + vector errMsg1(BUF_LEN, 0); - status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), - encLen, (uint8_t *) secret.data()); + status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), + encryptedDKGSecret.data(), encLen, + (uint8_t *)secret.data()); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); - sleep(3); + sleep(3); } -TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares]") { - vector encryptedDKGSecret(BUF_LEN, 0); - vector errMsg(BUF_LEN, 0); - - int errStatus = 0; - uint64_t encLen = 0; - - unsigned t = 32, n = 32; - PRINT_SRC_LINE - auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); - - vector errMsg1(BUF_LEN, 0); - - char colon = ':'; - vector pubShares(10000, 0); - PRINT_SRC_LINE - status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(), - encryptedDKGSecret.data(), encLen, pubShares.data(), t); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); - - vector g2Strings = splitString(pubShares.data(), ','); - vector pubSharesG2; - for (u_int64_t i = 0; i < g2Strings.size(); i++) { - vector coeffStr = splitString(g2Strings.at(i).c_str(), ':'); - - pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr)); - } - - vector secret(BUF_LEN, 0); - PRINT_SRC_LINE - status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen, - (uint8_t *) secret.data()); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); - - signatures::Dkg dkgObj(t, n); - - vector poly = TestUtils::splitStringToFr(secret.data(), colon); - vector pubSharesDkg = dkgObj.VerificationVector(poly); - for (uint32_t i = 0; i < pubSharesDkg.size(); i++) { - libff::alt_bn128_G2 el = pubSharesDkg.at(i); - el.to_affine_coordinates(); - } - REQUIRE(pubSharesG2 == pubSharesDkg); +TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", + "[dkg-aes-pub-shares]") { + vector encryptedDKGSecret(BUF_LEN, 0); + vector errMsg(BUF_LEN, 0); + + int errStatus = 0; + uint64_t encLen = 0; + + unsigned t = 32, n = 32; + PRINT_SRC_LINE + auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), + encryptedDKGSecret.data(), &encLen, n); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); + + vector errMsg1(BUF_LEN, 0); + + char colon = ':'; + vector pubShares(10000, 0); + PRINT_SRC_LINE + status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(), + encryptedDKGSecret.data(), encLen, + pubShares.data(), t); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); + + vector g2Strings = splitString(pubShares.data(), ','); + vector pubSharesG2; + for (u_int64_t i = 0; i < g2Strings.size(); i++) { + vector coeffStr = splitString(g2Strings.at(i).c_str(), ':'); + + pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr)); + } + + vector secret(BUF_LEN, 0); + PRINT_SRC_LINE + status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), + encryptedDKGSecret.data(), encLen, + (uint8_t *)secret.data()); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); + + libBLS::Dkg dkgObj(t, n); + + vector poly = + TestUtils::splitStringToFr(secret.data(), colon); + vector pubSharesDkg = dkgObj.VerificationVector(poly); + for (uint32_t i = 0; i < pubSharesDkg.size(); i++) { + libff::alt_bn128_G2 el = pubSharesDkg.at(i); + el.to_affine_coordinates(); + } + REQUIRE(pubSharesG2 == pubSharesDkg); } -TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", "[dkg-aes-encr-sshares]") { - vector errMsg(BUF_LEN, 0); - vector result(BUF_LEN, 0); +TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", + "[dkg-aes-encr-sshares]") { + vector errMsg(BUF_LEN, 0); + vector result(BUF_LEN, 0); - int errStatus = 0; - uint64_t encLen = 0; + int errStatus = 0; + uint64_t encLen = 0; - vector encryptedDKGSecret(BUF_LEN, 0); - PRINT_SRC_LINE - auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); + vector encryptedDKGSecret(BUF_LEN, 0); + PRINT_SRC_LINE + auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), + encryptedDKGSecret.data(), &encLen, 2); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); - vector encrPRDHKey(BUF_LEN, 0); + vector encrPRDHKey(BUF_LEN, 0); - string pub_keyB = SAMPLE_PUBLIC_KEY_B; + string pub_keyB = SAMPLE_PUBLIC_KEY_B; - vector 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); + vector 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); + 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 errMsg(BUF_LEN, 0); - vector result(BUF_LEN, 0); +TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares version 2 test", + "[dkg-aes-encr-sshares-v2]") { + vector errMsg(BUF_LEN, 0); + vector result(BUF_LEN, 0); - int errStatus = 0; - uint64_t encLen = 0; + int errStatus = 0; + uint64_t encLen = 0; - vector encryptedDKGSecret(BUF_LEN, 0); - PRINT_SRC_LINE - auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2); - REQUIRE(status == SGX_SUCCESS); - REQUIRE(errStatus == SGX_SUCCESS); + vector encryptedDKGSecret(BUF_LEN, 0); + PRINT_SRC_LINE + auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), + encryptedDKGSecret.data(), &encLen, 2); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); - vector encrPRDHKey(BUF_LEN, 0); + vector encrPRDHKey(BUF_LEN, 0); - string pub_keyB = SAMPLE_PUBLIC_KEY_B; + string pub_keyB = SAMPLE_PUBLIC_KEY_B; - vector s_shareG2(BUF_LEN, 0); - PRINT_SRC_LINE - status = trustedGetEncryptedSecretShareV2(eid, &errStatus, errMsg.data(), - encryptedDKGSecret.data(), encLen, - encrPRDHKey.data(), &encLen, - result.data(), - s_shareG2.data(), - (char *) pub_keyB.data(), 2, 2, 1); + vector s_shareG2(BUF_LEN, 0); + PRINT_SRC_LINE + status = trustedGetEncryptedSecretShareV2( + 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); + REQUIRE(status == SGX_SUCCESS); + REQUIRE(errStatus == SGX_SUCCESS); } /* * ( "verification test", "[verify]" ) { - char* pubshares = "0d72c21fc5a43452ad5f36699822309149ce6ce2cdce50dafa896e873f1b8ddd12f65a2e9c39c617a1f695f076b33b236b47ed773901fc2762f8b6f63277f5e30d7080be8e98c97f913d1920357f345dc0916c1fcb002b7beb060aa8b6b473a011bfafe9f8a5d8ea4c643ca4101e5119adbef5ae64f8dfb39cd10f1e69e31c591858d7eaca25b4c412fe909ca87ca7aadbf6d97d32d9b984e93d436f13d43ec31f40432cc750a64ac239cad6b8f78c1f1dd37427e4ff8c1cc4fe1c950fcbcec10ebfd79e0c19d0587adafe6db4f3c63ea9a329724a8804b63a9422e6898c0923209e828facf3a073254ec31af4231d999ba04eb5b7d1e0056d742a65b766f2f3"; - char *sec_share = "11592366544581417165283270001305852351194685098958224535357729125789505948557"; + char* pubshares = +"0d72c21fc5a43452ad5f36699822309149ce6ce2cdce50dafa896e873f1b8ddd12f65a2e9c39c617a1f695f076b33b236b47ed773901fc2762f8b6f63277f5e30d7080be8e98c97f913d1920357f345dc0916c1fcb002b7beb060aa8b6b473a011bfafe9f8a5d8ea4c643ca4101e5119adbef5ae64f8dfb39cd10f1e69e31c591858d7eaca25b4c412fe909ca87ca7aadbf6d97d32d9b984e93d436f13d43ec31f40432cc750a64ac239cad6b8f78c1f1dd37427e4ff8c1cc4fe1c950fcbcec10ebfd79e0c19d0587adafe6db4f3c63ea9a329724a8804b63a9422e6898c0923209e828facf3a073254ec31af4231d999ba04eb5b7d1e0056d742a65b766f2f3"; + char *sec_share = +"11592366544581417165283270001305852351194685098958224535357729125789505948557"; mpz_t sshare; mpz_init(sshare); - mpz_set_str(sshare, "11592366544581417165283270001305852351194685098958224535357729125789505948557", 10); - int result = Verification(pubshares, sshare, 2, 0); - REQUIRE(result == 1); + mpz_set_str(sshare, +"11592366544581417165283270001305852351194685098958224535357729125789505948557", +10); int result = Verification(pubshares, sshare, 2, 0); REQUIRE(result == 1); }*/ TEST_CASE_METHOD(TestFixture, "DKG_BLS test", "[dkg-bls]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); - vector ecdsaKeyNames; - vector blsKeyNames; + vector ecdsaKeyNames; + vector blsKeyNames; - int schainID = TestUtils::randGen(); - int dkgID = TestUtils::randGen(); + int schainID = TestUtils::randGen(); + int dkgID = TestUtils::randGen(); - PRINT_SRC_LINE - TestUtils::doDKG(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + PRINT_SRC_LINE + TestUtils::doDKG(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID); - REQUIRE(blsKeyNames.size() == 4); + REQUIRE(blsKeyNames.size() == 4); - schainID = TestUtils::randGen(); - dkgID = TestUtils::randGen(); + schainID = TestUtils::randGen(); + dkgID = TestUtils::randGen(); - TestUtils::doDKG(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + 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); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); - vector ecdsaKeyNames; - vector blsKeyNames; + vector ecdsaKeyNames; + vector blsKeyNames; - int schainID = TestUtils::randGen(); - int dkgID = TestUtils::randGen(); + int schainID = TestUtils::randGen(); + int dkgID = TestUtils::randGen(); - PRINT_SRC_LINE - TestUtils::doDKGV2(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + PRINT_SRC_LINE + TestUtils::doDKGV2(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID); - REQUIRE(blsKeyNames.size() == 4); + REQUIRE(blsKeyNames.size() == 4); - schainID = TestUtils::randGen(); - dkgID = TestUtils::randGen(); + schainID = TestUtils::randGen(); + dkgID = TestUtils::randGen(); - TestUtils::doDKGV2(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + TestUtils::doDKGV2(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID); } TEST_CASE_METHOD(TestFixture, "DKG_BLS ZMQ test", "[dkgblszmq]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); - string ip = ZMQ_IP; + string ip = ZMQ_IP; - string empty = ""; - auto zmqClient = make_shared(ip, ZMQ_PORT, false, empty, empty); + string empty = ""; + auto zmqClient = make_shared(ip, ZMQ_PORT, false, empty, empty); - vector ecdsaKeyNames; - vector blsKeyNames; + vector ecdsaKeyNames; + vector blsKeyNames; - int schainID = TestUtils::randGen(); - int dkgID = TestUtils::randGen(); + int schainID = TestUtils::randGen(); + int dkgID = TestUtils::randGen(); - PRINT_SRC_LINE - TestUtils::doZMQBLS(zmqClient,c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID); - REQUIRE(blsKeyNames.size() == 4); - schainID = TestUtils::randGen(); - dkgID = TestUtils::randGen(); - TestUtils::doZMQBLS(zmqClient, c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID); + PRINT_SRC_LINE + TestUtils::doZMQBLS(zmqClient, c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, + dkgID); + REQUIRE(blsKeyNames.size() == 4); + schainID = TestUtils::randGen(); + dkgID = TestUtils::randGen(); + TestUtils::doZMQBLS(zmqClient, 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); - auto response = c.importBLSKeyShare(key_str, name); - REQUIRE(response["status"] != 0); - - key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; - response = c.importBLSKeyShare(key_str, name); - REQUIRE(response["status"] == 0); + 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("6507625568967977077291849236396320012317305261598035" + "438182864059942098934847"); + std::string key_str = TestUtils::stringFromFr(key); + 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.blsSignMessageHash(name, SAMPLE_HASH, 1, 1)["status"] == 0); - REQUIRE(c.deleteBlsKey(name)["deleted"] == true); + REQUIRE(c.deleteBlsKey(name)["deleted"] == true); } TEST_CASE_METHOD(TestFixture, "Delete Bls Key Zmq", "[delete-bls-key-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - 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); - REQUIRE(!client->importBLSKeyShare(key_str, name)); + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; + libff::alt_bn128_Fr key = + libff::alt_bn128_Fr("6507625568967977077291849236396320012317305261598035" + "438182864059942098934847"); + std::string key_str = TestUtils::stringFromFr(key); + REQUIRE(!client->importBLSKeyShare(key_str, name)); - key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; - REQUIRE(client->importBLSKeyShare(key_str, name)); + key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; + REQUIRE(client->importBLSKeyShare(key_str, name)); - REQUIRE_NOTHROW(client->blsSignMessageHash(name, SAMPLE_HASH, 1, 1)); + REQUIRE_NOTHROW(client->blsSignMessageHash(name, SAMPLE_HASH, 1, 1)); - REQUIRE(client->deleteBLSKey(name)); + REQUIRE(client->deleteBLSKey(name)); } TEST_CASE_METHOD(TestFixture, "Import ECDSA Key", "[import-ecdsa-key]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); + 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); + std::string name = "NEK:abcdef"; + auto response = c.importECDSAKey("6507625568967977077291849236396320012317305" + "261598035438182864059942098934847", + name); + REQUIRE(response["status"] != 0); - string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; - response = c.importECDSAKey(key_str, 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); + REQUIRE(c.ecdsaSignMessageHash(16, name, SAMPLE_HASH)["status"] == 0); } -TEST_CASE_METHOD(TestFixture, "Import ECDSA Key Zmq", "[import-ecdsa-key-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); +TEST_CASE_METHOD(TestFixture, "Import ECDSA Key Zmq", + "[import-ecdsa-key-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - std::string name = "NEK:abcdef"; - REQUIRE_THROWS(client->importECDSAKey("6507625568967977077291849236396320012317305261598035438182864059942098934847", - name)); + std::string name = "NEK:abcdef"; + REQUIRE_THROWS( + client->importECDSAKey("6507625568967977077291849236396320012317305261598" + "035438182864059942098934847", + name)); - string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; - string response = client->importECDSAKey(key_str, name); - REQUIRE(response == client->getECDSAPublicKey(name)); + string key_str = + "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; + string response = client->importECDSAKey(key_str, name); + REQUIRE(response == client->getECDSAPublicKey(name)); - REQUIRE_NOTHROW(client->ecdsaSignMessageHash(16, name, SAMPLE_HASH)); + REQUIRE_NOTHROW(client->ecdsaSignMessageHash(16, name, SAMPLE_HASH)); } TEST_CASE_METHOD(TestFixture, "Backup Key", "[backup-key]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - std::ifstream sek_file("sgx_data/sgxwallet_backup_key.txt"); - REQUIRE(sek_file.good()); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + std::ifstream sek_file("sgx_data/sgxwallet_backup_key.txt"); + REQUIRE(sek_file.good()); - std::string sek; - sek_file >> sek; + std::string sek; + sek_file >> sek; - REQUIRE(sek.size() == 32); - sleep(3); + REQUIRE(sek.size() == 32); + sleep(3); } TEST_CASE_METHOD(TestFixture, "Get ServerStatus", "[get-server-status]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - REQUIRE(c.getServerStatus()["status"] == 0); - sleep(3); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + REQUIRE(c.getServerStatus()["status"] == 0); + sleep(3); } -TEST_CASE_METHOD(TestFixture, "Get ServerStatusZmq", "[get-server-status-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); - REQUIRE_NOTHROW(client->getServerStatus()); - sleep(3); +TEST_CASE_METHOD(TestFixture, "Get ServerStatusZmq", + "[get-server-status-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); + REQUIRE_NOTHROW(client->getServerStatus()); + sleep(3); } TEST_CASE_METHOD(TestFixture, "Get ServerVersion", "[get-server-version]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - REQUIRE(c.getServerVersion()["version"] == SGXWalletServer::getVersion()); - sleep(3); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + REQUIRE(c.getServerVersion()["version"] == SGXWalletServer::getVersion()); + sleep(3); } -TEST_CASE_METHOD(TestFixture, "Get ServerVersionZmq", "[get-server-version-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); - REQUIRE(client->getServerVersion() == SGXWalletServer::getVersion()); - sleep(3); +TEST_CASE_METHOD(TestFixture, "Get ServerVersionZmq", + "[get-server-version-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); + REQUIRE(client->getServerVersion() == SGXWalletServer::getVersion()); + sleep(3); } TEST_CASE_METHOD(TestFixtureHTTPS, "Cert request sign", "[cert-sign]") { - PRINT_SRC_LINE + PRINT_SRC_LINE - REQUIRE_NOTHROW(SGXRegistrationServer::getServer()); + REQUIRE_NOTHROW(SGXRegistrationServer::getServer()); - PRINT_SRC_LINE + PRINT_SRC_LINE - string csrFile = "insecure-samples/yourdomain.csr"; + string csrFile = "insecure-samples/yourdomain.csr"; - ifstream infile(csrFile); - infile.exceptions(std::ifstream::failbit | std::ifstream::badbit); - ostringstream ss; - ss << infile.rdbuf(); - infile.close(); + ifstream infile(csrFile); + infile.exceptions(std::ifstream::failbit | std::ifstream::badbit); + ostringstream ss; + ss << infile.rdbuf(); + infile.close(); - PRINT_SRC_LINE + PRINT_SRC_LINE - auto result = SGXRegistrationServer::getServer()->SignCertificate(ss.str()); + auto result = SGXRegistrationServer::getServer()->SignCertificate(ss.str()); - REQUIRE(result["status"] == 0); + REQUIRE(result["status"] == 0); - PRINT_SRC_LINE - result = SGXRegistrationServer::getServer()->SignCertificate("Haha"); + PRINT_SRC_LINE + result = SGXRegistrationServer::getServer()->SignCertificate("Haha"); - REQUIRE(result["status"] != 0); + REQUIRE(result["status"] != 0); } TEST_CASE_METHOD(TestFixture, "DKG API V2 test", "[dkg-api-v2]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); - string polyName = SAMPLE_POLY_NAME; + string polyName = SAMPLE_POLY_NAME; - PRINT_SRC_LINE - Json::Value genPoly = c.generateDKGPoly(polyName, 2); - REQUIRE(genPoly["status"].asInt() == 0); + 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); + 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); + // wrongName + Json::Value genPolyWrongName = c.generateDKGPoly("poly", 2); + REQUIRE(genPolyWrongName["status"].asInt() != 0); - Json::Value verifVectWrongName = c.getVerificationVector("poly", 2); - REQUIRE(verifVectWrongName["status"].asInt() != 0); + Json::Value verifVectWrongName = c.getVerificationVector("poly", 2); + REQUIRE(verifVectWrongName["status"].asInt() != 0); - Json::Value secretSharesWrongName = c.getSecretShareV2("poly", publicKeys, 2, 2); - REQUIRE(secretSharesWrongName["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); + // wrong_t + Json::Value genPolyWrong_t = c.generateDKGPoly(polyName, 33); + REQUIRE(genPolyWrong_t["status"].asInt() != 0); - Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1); - REQUIRE(verifVectWrong_t["status"].asInt() != 0); + Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1); + REQUIRE(verifVectWrong_t["status"].asInt() != 0); - Json::Value secretSharesWrong_t = c.getSecretShareV2(polyName, publicKeys, 3, 3); - REQUIRE(secretSharesWrong_t["status"].asInt() != 0); + Json::Value secretSharesWrong_t = + c.getSecretShareV2(polyName, publicKeys, 3, 3); + REQUIRE(secretSharesWrong_t["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); + 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 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)); + // 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); - REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2)); - REQUIRE(verifVect == c.getVerificationVector(polyName, 2)); + Json::Value verifVect = c.getVerificationVector(polyName, 2); + REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2)); + REQUIRE(verifVect == c.getVerificationVector(polyName, 2)); - Json::Value verificationWrongSkeys = c.dkgVerificationV2("", "", "", 2, 2, 1); - REQUIRE(verificationWrongSkeys["status"].asInt() != 0); + Json::Value verificationWrongSkeys = c.dkgVerificationV2("", "", "", 2, 2, 1); + REQUIRE(verificationWrongSkeys["status"].asInt() != 0); } TEST_CASE_METHOD(TestFixture, "DKG API V2 ZMQ test", "[dkg-api-v2-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - string polyName = SAMPLE_POLY_NAME; + string polyName = SAMPLE_POLY_NAME; - PRINT_SRC_LINE - REQUIRE(client->generateDKGPoly(polyName, 2)); + PRINT_SRC_LINE + REQUIRE(client->generateDKGPoly(polyName, 2)); - Json::Value publicKeys; - publicKeys.append(SAMPLE_DKG_PUB_KEY_1); - publicKeys.append(SAMPLE_DKG_PUB_KEY_2); + Json::Value publicKeys; + publicKeys.append(SAMPLE_DKG_PUB_KEY_1); + publicKeys.append(SAMPLE_DKG_PUB_KEY_2); - // wrongName - REQUIRE(!client->generateDKGPoly("poly", 2)); + // wrongName + REQUIRE(!client->generateDKGPoly("poly", 2)); - REQUIRE_THROWS(client->getVerificationVector("poly", 2)); + REQUIRE_THROWS(client->getVerificationVector("poly", 2)); - REQUIRE_THROWS(client->getSecretShare("poly", publicKeys, 2, 2)); + REQUIRE_THROWS(client->getSecretShare("poly", publicKeys, 2, 2)); - // wrong_t - REQUIRE(!client->generateDKGPoly(polyName, 33)); + // wrong_t + REQUIRE(!client->generateDKGPoly(polyName, 33)); - REQUIRE_THROWS(client->getVerificationVector(polyName, 0)); + REQUIRE_THROWS(client->getVerificationVector(polyName, 0)); - REQUIRE_THROWS(client->getSecretShare(polyName, publicKeys, 3, 3)); + REQUIRE_THROWS(client->getSecretShare(polyName, publicKeys, 3, 3)); - Json::Value publicKeys1; - publicKeys1.append(SAMPLE_DKG_PUB_KEY_1); - REQUIRE_THROWS(client->getSecretShare(polyName, publicKeys1, 2, 1)); + Json::Value publicKeys1; + publicKeys1.append(SAMPLE_DKG_PUB_KEY_1); + REQUIRE_THROWS(client->getSecretShare(polyName, publicKeys1, 2, 1)); - //wrong number of publicKeys - REQUIRE_THROWS(client->getSecretShare(polyName, publicKeys, 2, 3)); + // wrong number of publicKeys + REQUIRE_THROWS(client->getSecretShare(polyName, publicKeys, 2, 3)); - //wrong verif - string Skeys = client->getSecretShare(polyName, publicKeys, 2, 2); - REQUIRE_NOTHROW(client->getSecretShare(polyName, publicKeys, 2, 2)); - REQUIRE(Skeys == client->getSecretShare(polyName, publicKeys, 2, 2)); + // wrong verif + string Skeys = client->getSecretShare(polyName, publicKeys, 2, 2); + REQUIRE_NOTHROW(client->getSecretShare(polyName, publicKeys, 2, 2)); + REQUIRE(Skeys == client->getSecretShare(polyName, publicKeys, 2, 2)); - Json::Value verifVect = client->getVerificationVector(polyName, 2); - REQUIRE_NOTHROW(client->getVerificationVector(polyName, 2)); - REQUIRE(verifVect == client->getVerificationVector(polyName, 2)); + Json::Value verifVect = client->getVerificationVector(polyName, 2); + REQUIRE_NOTHROW(client->getVerificationVector(polyName, 2)); + REQUIRE(verifVect == client->getVerificationVector(polyName, 2)); - REQUIRE_THROWS(client->dkgVerification("", "", "", 2, 2, 1)); + REQUIRE_THROWS(client->dkgVerification("", "", "", 2, 2, 1)); } TEST_CASE_METHOD(TestFixture, "PolyExists test", "[dkg-poly-exists]") { - 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"] == 0); - - PRINT_SRC_LINE - Json::Value polyExists = c.isPolyExists(polyName); - REQUIRE(polyExists["status"] == 0); - REQUIRE(polyExists["IsExist"].asBool()); - - PRINT_SRC_LINE - Json::Value polyDoesNotExist = c.isPolyExists("Vasya"); - REQUIRE(!polyDoesNotExist["IsExist"].asBool()); + 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"] == 0); + + PRINT_SRC_LINE + Json::Value polyExists = c.isPolyExists(polyName); + REQUIRE(polyExists["status"] == 0); + REQUIRE(polyExists["IsExist"].asBool()); + + PRINT_SRC_LINE + Json::Value polyDoesNotExist = c.isPolyExists("Vasya"); + REQUIRE(!polyDoesNotExist["IsExist"].asBool()); } TEST_CASE_METHOD(TestFixture, "PolyExistsZmq test", "[dkg-poly-exists-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - string polyName = SAMPLE_POLY_NAME; - REQUIRE_NOTHROW(client->generateDKGPoly(polyName, 2)); + string polyName = SAMPLE_POLY_NAME; + REQUIRE_NOTHROW(client->generateDKGPoly(polyName, 2)); - bool polyExists = client->isPolyExists(polyName); - REQUIRE(polyExists); + bool polyExists = client->isPolyExists(polyName); + REQUIRE(polyExists); - bool polyDoesNotExist = client->isPolyExists("Vasya"); - REQUIRE(!polyDoesNotExist); + bool polyDoesNotExist = client->isPolyExists("Vasya"); + REQUIRE(!polyDoesNotExist); } 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 pubShares(n); - vector 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); - 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); - } - } + 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 pubShares(n); + vector 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); - int k = 0; - vector secShares(n); + polyNames[i] = polyName; + PRINT_SRC_LINE + verifVects[i] = c.getVerificationVector(polyName, t); + REQUIRE(verifVects[i]["status"] == 0); - 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); - } + pubEthKeys.append(ethKeys[i]["publicKey"]); + } - Json::Value complaintResponse = c.complaintResponse(polyNames[1], t, n, 0); - REQUIRE(complaintResponse["status"] == 0); + 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 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); + } - string dhKey = complaintResponse["dhKey"].asString(); - string shareG2 = complaintResponse["share*G2"].asString(); - string secretShare = secretShares[1]["secretShare"].asString().substr(0, 192); + Json::Value complaintResponse = c.complaintResponse(polyNames[1], t, n, 0); + REQUIRE(complaintResponse["status"] == 0); - vector message(65, 0); + string dhKey = complaintResponse["dhKey"].asString(); + string shareG2 = complaintResponse["share*G2"].asString(); + string secretShare = secretShares[1]["secretShare"].asString().substr(0, 192); - SAFE_CHAR_BUF(encr_sshare, BUF_LEN) - strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128); + vector message(65, 0); - SAFE_CHAR_BUF(common_key, BUF_LEN); - REQUIRE(sessionKeyRecoverDH(dhKey.c_str(), encr_sshare, common_key) == 0); + SAFE_CHAR_BUF(encr_sshare, BUF_LEN) + strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128); - uint8_t key_to_hash[33]; - uint64_t len; - REQUIRE( hex2carray(common_key, &len, key_to_hash, 64) ); + 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((char*)key_to_hash, 32)); + uint8_t key_to_hash[33]; + uint64_t len; + REQUIRE(hex2carray(common_key, &len, key_to_hash, 64)); - SAFE_CHAR_BUF(derived_key, 33) + auto hashed_key = + cryptlite::sha256::hash_hex(string((char *)key_to_hash, 32)); - uint64_t key_length; - REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t *) derived_key, 33)); + SAFE_CHAR_BUF(derived_key, 33) - SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN) - strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1); + uint64_t key_length; + REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t *)derived_key, 33)); - REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0); + SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN) + strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1); - mpz_t hex_share; - mpz_init(hex_share); - mpz_set_str(hex_share, message.data(), 16); + REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0); - 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_t hex_share; + mpz_init(hex_share); + mpz_set_str(hex_share, message.data(), 16); - mpz_clear(hex_share); + 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(); - REQUIRE(convertG2ToString(decrypted_share_G2) == shareG2); + mpz_clear(hex_share); - Json::Value verificationVectorMult = complaintResponse["verificationVectorMult"]; + REQUIRE(convertG2ToString(decrypted_share_G2) == shareG2); - 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); + Json::Value verificationVectorMult = + complaintResponse["verificationVectorMult"]; - BLSSigShareSet sigShareSet(t, n); + 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); - string hash = SAMPLE_HASH; + BLSSigShareSet sigShareSet(t, n); - auto hash_arr = make_shared < array < uint8_t, 32 > > (); + string hash = SAMPLE_HASH; - uint64_t binLen; + auto hash_arr = make_shared>(); - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + uint64_t binLen; - map > coeffs_pkeys_map; + if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - for (int i = 0; i < t; i++) { - string endName = polyNames[i].substr(4); - string blsName = "BLS_KEY" + polyNames[i].substr(4); - auto response = c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], - t, n); - REQUIRE(response["status"] == 0); + map> coeffs_pkeys_map; - PRINT_SRC_LINE - pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName); - REQUIRE(pubBLSKeys[i]["status"] == 0); + for (int i = 0; i < t; i++) { + string endName = polyNames[i].substr(4); + string blsName = "BLS_KEY" + polyNames[i].substr(4); + auto response = + c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), + polyNames[i], secShares[i], t, n); + REQUIRE(response["status"] == 0); - string hash = SAMPLE_HASH; - blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); - REQUIRE(blsSigShares[i]["status"] == 0); + PRINT_SRC_LINE + pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName); + REQUIRE(pubBLSKeys[i]["status"] == 0); - shared_ptr sig_share_ptr = make_shared(blsSigShares[i]["signatureShare"].asString()); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); + string hash = SAMPLE_HASH; + blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); + REQUIRE(blsSigShares[i]["status"] == 0); - vector 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(sig), t, n)); + shared_ptr sig_share_ptr = + make_shared(blsSigShares[i]["signatureShare"].asString()); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); - coeffs_pkeys_map[i + 1] = make_shared(pubKey); + vector pubKey_vect; + for (uint8_t j = 0; j < 4; j++) { + pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); } + BLSPublicKeyShare pubKey(make_shared>(pubKey_vect), t, n); + PRINT_SRC_LINE + REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared(sig), + t, n)); - shared_ptr 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)); + coeffs_pkeys_map[i + 1] = make_shared(pubKey); + } + + shared_ptr commonSig = sigShareSet.merge(); + BLSPublicKey common_public( + make_shared>>(coeffs_pkeys_map), + t, n); + REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig)); } TEST_CASE_METHOD(TestFixture, "AES_DKG V2 ZMQ test", "[aes-dkg-v2-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); - - int n = 2, t = 2; - vector ethKeys(n); - Json::Value verifVects[n]; - Json::Value pubEthKeys; - vector secretShares(n); - Json::Value pubBLSKeys[n]; - vector blsSigShares(n); - vector pubShares(n); - vector polyNames(n); - - int schainID = TestUtils::randGen(); - int dkgID = TestUtils::randGen(); - for (uint8_t i = 0; i < n; i++) { - auto generatedKey = client->generateECDSAKey(); - ethKeys[i] = generatedKey.second; - string polyName = - "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID); - CHECK_STATE(client->generateDKGPoly(polyName, t)); - polyNames[i] = polyName; - verifVects[i] = client->getVerificationVector(polyName, t); - - pubEthKeys.append(generatedKey.first); + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); + + int n = 2, t = 2; + vector ethKeys(n); + Json::Value verifVects[n]; + Json::Value pubEthKeys; + vector secretShares(n); + Json::Value pubBLSKeys[n]; + vector blsSigShares(n); + vector pubShares(n); + vector polyNames(n); + + int schainID = TestUtils::randGen(); + int dkgID = TestUtils::randGen(); + for (uint8_t i = 0; i < n; i++) { + auto generatedKey = client->generateECDSAKey(); + ethKeys[i] = generatedKey.second; + string polyName = "POLY:SCHAIN_ID:" + to_string(schainID) + + ":NODE_ID:" + to_string(i) + + ":DKG_ID:" + to_string(dkgID); + CHECK_STATE(client->generateDKGPoly(polyName, t)); + polyNames[i] = polyName; + verifVects[i] = client->getVerificationVector(polyName, t); + + pubEthKeys.append(generatedKey.first); + } + + for (uint8_t i = 0; i < n; i++) { + secretShares[i] = client->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][k][j].asString(); + pubShares[i] += TestUtils::convertDecToHex(pubShare); + } } - - for (uint8_t i = 0; i < n; i++) { - secretShares[i] = client->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][k][j].asString(); - pubShares[i] += TestUtils::convertDecToHex(pubShare); - } - } + } + + int k = 0; + vector secShares(n); + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) { + string secretShare = secretShares[i].substr(192 * j, 192); + secShares[i] += secretShares[j].substr(192 * i, 192); + REQUIRE(client->dkgVerification(pubShares[i], ethKeys[j], secretShare, t, + n, j)); + k++; } - int k = 0; - vector secShares(n); + auto complaintResponse = client->complaintResponse(polyNames[1], t, n, 0); - for (int i = 0; i < n; i++) - for (int j = 0; j < n; j++) { - string secretShare = secretShares[i].substr(192 * j, 192); - secShares[i] += secretShares[j].substr(192 * i, 192); - REQUIRE(client->dkgVerification(pubShares[i], ethKeys[j], secretShare, t, n, j)); - k++; - } + string dhKey = std::get<0>(complaintResponse); + string shareG2 = std::get<1>(complaintResponse); + string secretShare = secretShares[1].substr(0, 192); - auto complaintResponse = client->complaintResponse(polyNames[1], t, n, 0); + vector message(65, 0); - string dhKey = std::get<0>(complaintResponse); - string shareG2 = std::get<1>(complaintResponse); - string secretShare = secretShares[1].substr(0, 192); + SAFE_CHAR_BUF(encr_sshare, BUF_LEN) + strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128); - vector message(65, 0); + SAFE_CHAR_BUF(common_key, BUF_LEN); + REQUIRE(sessionKeyRecoverDH(dhKey.c_str(), encr_sshare, common_key) == 0); - SAFE_CHAR_BUF(encr_sshare, BUF_LEN) - strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128); + uint8_t key_to_hash[33]; + uint64_t len; + REQUIRE(hex2carray(common_key, &len, key_to_hash, 64)); - 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((char *)key_to_hash, 32)); - uint8_t key_to_hash[33]; - uint64_t len; - REQUIRE( hex2carray(common_key, &len, key_to_hash, 64) ); + SAFE_CHAR_BUF(derived_key, 33) - auto hashed_key = cryptlite::sha256::hash_hex(string((char*)key_to_hash, 32)); + uint64_t key_length; + REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t *)derived_key, 33)); - SAFE_CHAR_BUF(derived_key, 33) + SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN) + strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1); - uint64_t key_length; - REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t *) derived_key, 33)); + REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0); - SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN) - strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1); + mpz_t hex_share; + mpz_init(hex_share); + mpz_set_str(hex_share, message.data(), 16); - REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0); + 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_t hex_share; - mpz_init(hex_share); - mpz_set_str(hex_share, message.data(), 16); + mpz_clear(hex_share); - 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(); + REQUIRE(convertG2ToString(decrypted_share_G2) == shareG2); - mpz_clear(hex_share); + Json::Value verificationVectorMult = std::get<2>(complaintResponse); - REQUIRE(convertG2ToString(decrypted_share_G2) == shareG2); + 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); - Json::Value verificationVectorMult = std::get<2>(complaintResponse); + BLSSigShareSet sigShareSet(t, n); - 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); + string hash = SAMPLE_HASH; - BLSSigShareSet sigShareSet(t, n); + auto hash_arr = make_shared>(); - string hash = SAMPLE_HASH; + uint64_t binLen; - auto hash_arr = make_shared < array < uint8_t, 32 > > (); + if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { + throw SGXException(TEST_INVALID_HEX, "Invalid hash"); + } - uint64_t binLen; + map> coeffs_pkeys_map; - if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) { - throw SGXException(TEST_INVALID_HEX, "Invalid hash"); - } + for (int i = 0; i < t; i++) { + string blsName = "BLS_KEY" + polyNames[i].substr(4); + REQUIRE(client->createBLSPrivateKey(blsName, ethKeys[i], polyNames[i], + secShares[i], t, n)); - map > coeffs_pkeys_map; + pubBLSKeys[i] = client->getBLSPublicKey(blsName); - for (int i = 0; i < t; i++) { - string blsName = "BLS_KEY" + polyNames[i].substr(4); - REQUIRE(client->createBLSPrivateKey(blsName, ethKeys[i], polyNames[i], secShares[i], t, n)); + string hash = SAMPLE_HASH; + blsSigShares[i] = client->blsSignMessageHash(blsName, hash, t, n); + REQUIRE(blsSigShares[i].length() > 0); - pubBLSKeys[i] = client->getBLSPublicKey(blsName); + shared_ptr sig_share_ptr = make_shared(blsSigShares[i]); + BLSSigShare sig(sig_share_ptr, i + 1, t, n); + sigShareSet.addSigShare(make_shared(sig)); - string hash = SAMPLE_HASH; - blsSigShares[i] = client->blsSignMessageHash(blsName, hash, t, n); - REQUIRE(blsSigShares[i].length() > 0); + vector pubKey_vect; + for (uint8_t j = 0; j < 4; j++) { + pubKey_vect.push_back(pubBLSKeys[i][j].asString()); + } + BLSPublicKeyShare pubKey(make_shared>(pubKey_vect), t, n); + REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared(sig), + t, n)); + + coeffs_pkeys_map[i + 1] = make_shared(pubKey); + } + + shared_ptr commonSig = sigShareSet.merge(); + BLSPublicKey common_public( + make_shared>>(coeffs_pkeys_map), + t, n); + REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig)); +} - shared_ptr sig_share_ptr = make_shared(blsSigShares[i]); - BLSSigShare sig(sig_share_ptr, i + 1, t, n); - sigShareSet.addSigShare(make_shared(sig)); +TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") { + int errStatus = 0; + vector errMsg(BUF_LEN, 0); + uint64_t encLen; + string key = SAMPLE_AES_KEY; + vector encrypted_key(BUF_LEN, 0); + + PRINT_SRC_LINE + auto status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), + encrypted_key.data(), &encLen); + + REQUIRE(status == 0); + REQUIRE(errStatus == 0); + + vector decr_key(BUF_LEN, 0); + PRINT_SRC_LINE + status = trustedDecryptKey(eid, &errStatus, errMsg.data(), + encrypted_key.data(), encLen, decr_key.data()); + + REQUIRE(status == 0); + REQUIRE(key.compare(decr_key.data()) == 0); + REQUIRE(errStatus == 0); + sleep(3); +} - vector pubKey_vect; - for (uint8_t j = 0; j < 4; j++) { - pubKey_vect.push_back(pubBLSKeys[i][j].asString()); - } - BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKey_vect), t, n); - REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared(sig), t, n)); +TEST_CASE_METHOD(TestFixture, "Exportable / non-exportable keys", + "[exportable-nonexportable-keys]") { + int errStatus = 0; + vector errMsg(BUF_LEN, 0); + vector encPrivKey(BUF_LEN, 0); + vector pubKeyX(BUF_LEN, 0); + vector pubKeyY(BUF_LEN, 0); + + uint64_t encLen = 0; + int exportable = 0; + + auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), + &exportable, encPrivKey.data(), &encLen, + pubKeyX.data(), pubKeyY.data()); + + vector decrypted_key(BUF_LEN, 0); + status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), + encLen, decrypted_key.data()); + REQUIRE(errStatus == -11); + + exportable = 1; + + encPrivKey.clear(); + errMsg.clear(); + pubKeyX.clear(); + pubKeyY.clear(); + + status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, + encPrivKey.data(), &encLen, pubKeyX.data(), + pubKeyY.data()); + + decrypted_key.clear(); + status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), + encLen, decrypted_key.data()); + REQUIRE(errStatus == 0); + REQUIRE(status == SGX_SUCCESS); + + string key = SAMPLE_AES_KEY; + vector encrypted_key(BUF_LEN, 0); + + status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), + encrypted_key.data(), &encLen); + + REQUIRE(status == 0); + REQUIRE(errStatus == 0); + + vector decr_key(BUF_LEN, 0); + PRINT_SRC_LINE + status = trustedDecryptKey(eid, &errStatus, errMsg.data(), + encrypted_key.data(), encLen, decr_key.data()); + + REQUIRE(status == 0); + REQUIRE(key.compare(decr_key.data()) == 0); + REQUIRE(errStatus == 0); + sleep(3); +} - coeffs_pkeys_map[i + 1] = make_shared(pubKey); - } +TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls", + "[many-threads-crypto-v2]") { + vector threads; + int num_threads = 4; + for (int i = 0; i < num_threads; i++) { + threads.push_back(thread(TestUtils::sendRPCRequestV2)); + } + + for (auto &thread : threads) { + thread.join(); + } +} - shared_ptr 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, "Many threads ecdsa dkg v2 bls zmq", + "[many-threads-crypto-v2-zmq]") { + vector threads; + int num_threads = 4; + for (int i = 0; i < num_threads; i++) { + threads.push_back(thread(TestUtils::sendRPCRequestZMQ)); + } + + for (auto &thread : threads) { + thread.join(); + } } -TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") { - int errStatus = 0; - vector errMsg(BUF_LEN, 0); - uint64_t encLen; - string key = SAMPLE_AES_KEY; - vector encrypted_key(BUF_LEN, 0); +TEST_CASE_METHOD(TestFixture, "First run", "[first-run]") { + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + try { PRINT_SRC_LINE - auto status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen); - - REQUIRE(status == 0); - REQUIRE(errStatus == 0); + auto keyName = genECDSAKeyAPI(c); + ofstream namefile("/tmp/keyname"); + namefile << keyName; - vector decr_key(BUF_LEN, 0); PRINT_SRC_LINE - status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data()); + } catch (JsonRpcException &e) { + cerr << e.what() << endl; + throw; + } - REQUIRE(status == 0); - REQUIRE(key.compare(decr_key.data()) == 0); - REQUIRE(errStatus == 0); - sleep(3); + sleep(3); } -TEST_CASE_METHOD(TestFixture, "Exportable / non-exportable keys", "[exportable-nonexportable-keys]") { - int errStatus = 0; - vector errMsg(BUF_LEN, 0); - vector encPrivKey(BUF_LEN, 0); - vector pubKeyX(BUF_LEN, 0); - vector pubKeyY(BUF_LEN, 0); +TEST_CASE_METHOD(TestFixtureNoReset, "Second run", "[second-run]") { - uint64_t encLen = 0; - int exportable = 0; + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); + try { + PRINT_SRC_LINE + string keyName; + ifstream namefile("/tmp/keyname"); + getline(namefile, keyName); + + Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH); + REQUIRE(sig["status"].asInt() == 0); + Json::Value getPubKey = c.getPublicECDSAKey(keyName); + REQUIRE(getPubKey["status"].asInt() == 0); + } catch (JsonRpcException &e) { + cerr << e.what() << endl; + throw; + } +} - auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encPrivKey.data(), &encLen, pubKeyX.data(), - pubKeyY.data()); +TEST_CASE_METHOD(TestFixture, "Test decryption share for threshold encryption", + "[te-decryption-share]") { + HttpClient client(RPC_ENDPOINT); + StubClient c(client, JSONRPC_CLIENT_V2); - vector decrypted_key(BUF_LEN, 0); - status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, decrypted_key.data()); - REQUIRE( errStatus == -11 ); + std::string key_str = + "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; + c.importBLSKeyShare(key_str, name); - exportable = 1; + // the same key writtn in decimal + libff::alt_bn128_Fr key = + libff::alt_bn128_Fr("6507625568967977077291849236396320012317305261598035" + "438182864059942098934847"); - encPrivKey.clear(); - errMsg.clear(); - pubKeyX.clear(); - pubKeyY.clear(); + libff::alt_bn128_G2 decryption_value1 = libff::alt_bn128_G2::random_element(); + libff::alt_bn128_G2 decryption_value2 = libff::alt_bn128_G2::random_element(); - status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encPrivKey.data(), &encLen, pubKeyX.data(), - pubKeyY.data()); + decryption_value1.to_affine_coordinates(); + decryption_value2.to_affine_coordinates(); - decrypted_key.clear(); - status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, decrypted_key.data()); - REQUIRE( errStatus == 0 ); - REQUIRE( status == SGX_SUCCESS ); + auto decrytion_value_str1 = convertG2ToString(decryption_value1, ':'); + auto decrytion_value_str2 = convertG2ToString(decryption_value2, ':'); - string key = SAMPLE_AES_KEY; - vector encrypted_key(BUF_LEN, 0); + Json::Value publicDecryptionValues; + publicDecryptionValues["publicDecryptionValues"][0] = decrytion_value_str1; + publicDecryptionValues["publicDecryptionValues"][1] = decrytion_value_str2; - status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen); + auto decryptionShares = c.getDecryptionShares(name, publicDecryptionValues); - REQUIRE(status == 0); - REQUIRE(errStatus == 0); + auto decryption_share1 = decryptionShares["decryptionShares"][0]; + auto decryption_share2 = decryptionShares["decryptionShares"][1]; - vector decr_key(BUF_LEN, 0); - PRINT_SRC_LINE - status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data()); + libff::alt_bn128_G2 share1; + share1.Z = libff::alt_bn128_Fq2::one(); - REQUIRE(status == 0); - REQUIRE(key.compare(decr_key.data()) == 0); - REQUIRE(errStatus == 0); - sleep(3); -} + share1.X.c0 = libff::alt_bn128_Fq(decryption_share1[0].asCString()); + share1.X.c1 = libff::alt_bn128_Fq(decryption_share1[1].asCString()); + share1.Y.c0 = libff::alt_bn128_Fq(decryption_share1[2].asCString()); + share1.Y.c1 = libff::alt_bn128_Fq(decryption_share1[3].asCString()); -TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls", "[many-threads-crypto-v2]") { - vector threads; - int num_threads = 4; - for (int i = 0; i < num_threads; i++) { - threads.push_back(thread(TestUtils::sendRPCRequestV2)); - } + REQUIRE(share1 == key * decryption_value1); - for (auto &thread : threads) { - thread.join(); - } -} + libff::alt_bn128_G2 share2; + share2.Z = libff::alt_bn128_Fq2::one(); -TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls zmq", "[many-threads-crypto-v2-zmq]") { - vector threads; - int num_threads = 4; - for (int i = 0; i < num_threads; i++) { - threads.push_back(thread(TestUtils::sendRPCRequestZMQ)); - } + share2.X.c0 = libff::alt_bn128_Fq(decryption_share2[0].asCString()); + share2.X.c1 = libff::alt_bn128_Fq(decryption_share2[1].asCString()); + share2.Y.c0 = libff::alt_bn128_Fq(decryption_share2[2].asCString()); + share2.Y.c1 = libff::alt_bn128_Fq(decryption_share2[3].asCString()); - for (auto &thread : threads) { - thread.join(); - } + REQUIRE(share2 == key * decryption_value2); } -TEST_CASE_METHOD(TestFixture, "First run", "[first-run]") { +TEST_CASE_METHOD(TestFixture, + "Test decryption share for threshold encryption via zmq", + "[te-decryption-share-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - try { - PRINT_SRC_LINE - auto keyName = genECDSAKeyAPI(c); - ofstream namefile("/tmp/keyname"); - namefile << keyName; + std::string key_str = + "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; + client->importBLSKeyShare(key_str, name); - PRINT_SRC_LINE - } catch (JsonRpcException &e) { - cerr << e.what() << endl; - throw; - } + // the same key writtn in decimal + libff::alt_bn128_Fr key = + libff::alt_bn128_Fr("6507625568967977077291849236396320012317305261598035" + "438182864059942098934847"); - sleep(3); -} + libff::alt_bn128_G2 decryption_value1 = libff::alt_bn128_G2::random_element(); + libff::alt_bn128_G2 decryption_value2 = libff::alt_bn128_G2::random_element(); -TEST_CASE_METHOD(TestFixtureNoReset, "Second run", "[second-run]") { + decryption_value1.to_affine_coordinates(); + decryption_value2.to_affine_coordinates(); - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); - try { - PRINT_SRC_LINE - string keyName; - ifstream namefile("/tmp/keyname"); - getline(namefile, keyName); - - Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH); - REQUIRE(sig["status"].asInt() == 0); - Json::Value getPubKey = c.getPublicECDSAKey(keyName); - REQUIRE(getPubKey["status"].asInt() == 0); - } catch (JsonRpcException &e) { - cerr << e.what() << endl; - throw; - } + auto decrytion_value_str1 = convertG2ToString(decryption_value1, ':'); + auto decrytion_value_str2 = convertG2ToString(decryption_value2, ':'); + + Json::Value publicDecryptionValues; + publicDecryptionValues["publicDecryptionValues"][0] = decrytion_value_str1; + publicDecryptionValues["publicDecryptionValues"][1] = decrytion_value_str2; + + auto decryptionShares = + client->getDecryptionShares(name, publicDecryptionValues); + + auto decryption_share1 = decryptionShares[0]; + auto decryption_share2 = decryptionShares[1]; + + libff::alt_bn128_G2 share1; + share1.Z = libff::alt_bn128_Fq2::one(); + + share1.X.c0 = libff::alt_bn128_Fq(decryption_share1[0].asCString()); + share1.X.c1 = libff::alt_bn128_Fq(decryption_share1[1].asCString()); + share1.Y.c0 = libff::alt_bn128_Fq(decryption_share1[2].asCString()); + share1.Y.c1 = libff::alt_bn128_Fq(decryption_share1[3].asCString()); + + REQUIRE(share1 == key * decryption_value1); + + libff::alt_bn128_G2 share2; + share2.Z = libff::alt_bn128_Fq2::one(); + + share2.X.c0 = libff::alt_bn128_Fq(decryption_share2[0].asCString()); + share2.X.c1 = libff::alt_bn128_Fq(decryption_share2[1].asCString()); + share2.Y.c0 = libff::alt_bn128_Fq(decryption_share2[2].asCString()); + share2.Y.c1 = libff::alt_bn128_Fq(decryption_share2[3].asCString()); + + REQUIRE(share2 == key * decryption_value2); } -TEST_CASE_METHOD(TestFixture, "Test decryption share for threshold encryption", "[te-decryption-share]") { - HttpClient client(RPC_ENDPOINT); - StubClient c(client, JSONRPC_CLIENT_V2); +TEST_CASE_METHOD(TestFixture, "Test generated bls key decrypt", + "[bls-aggregated-key-decrypt]") { + vector errMsg(BUF_LEN, 0); + int errStatus = 0; + + int exportable = 1; + + uint64_t encBlsLen = 0; - std::string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; - std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; - c.importBLSKeyShare(key_str, name); + sgx_status_t status = SGX_SUCCESS; - // the same key written in decimal - libff::alt_bn128_Fr key = libff::alt_bn128_Fr( - "6507625568967977077291849236396320012317305261598035438182864059942098934847"); + SAFE_UINT8_BUF(encrBlsKey, BUF_LEN) - libff::alt_bn128_G2 decryption_value1 = libff::alt_bn128_G2::random_element(); - libff::alt_bn128_G2 decryption_value2 = libff::alt_bn128_G2::random_element(); - - decryption_value1.to_affine_coordinates(); - decryption_value2.to_affine_coordinates(); + status = trustedGenerateBLSKey(eid, &errStatus, errMsg.data(), &exportable, + encrBlsKey, &encBlsLen); - auto decrytion_value_str1 = convertG2ToString( decryption_value1, ':' ); - auto decrytion_value_str2 = convertG2ToString( decryption_value2, ':' ); + REQUIRE(status == 0); + REQUIRE(errStatus == 0); - Json::Value publicDecryptionValues; - publicDecryptionValues["publicDecryptionValues"][0] = decrytion_value_str1; - publicDecryptionValues["publicDecryptionValues"][1] = decrytion_value_str2; + vector decrKey(BUF_LEN, 0); + status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrBlsKey, + encBlsLen, decrKey.data()); - auto decryptionShares = c.getDecryptionShares( name, publicDecryptionValues ); + REQUIRE(status == 0); + REQUIRE(errStatus == 0); - auto decryption_share1 = decryptionShares["decryptionShares"][0]; - auto decryption_share2 = decryptionShares["decryptionShares"][1]; + mpz_t blsKey; + mpz_init(blsKey); + REQUIRE(mpz_set_str(blsKey, decrKey.data(), 16) == 0); - libff::alt_bn128_G2 share1; - share1.Z = libff::alt_bn128_Fq2::one(); + mpz_t q; + mpz_init(q); + mpz_set_str(q, + "2188824287183927522224640574525727508854836440041603434369820418" + "6575808495617", + 10); - share1.X.c0 = libff::alt_bn128_Fq( decryption_share1[0].asCString() ); - share1.X.c1 = libff::alt_bn128_Fq( decryption_share1[1].asCString() ); - share1.Y.c0 = libff::alt_bn128_Fq( decryption_share1[2].asCString() ); - share1.Y.c1 = libff::alt_bn128_Fq( decryption_share1[3].asCString() ); + REQUIRE(mpz_cmp_ui(blsKey, 0) > 0); + REQUIRE(mpz_cmp(blsKey, q) < 0); - REQUIRE( share1 == key * decryption_value1 ); + SAFE_UINT8_BUF(encrBlsKeySecond, BUF_LEN) - libff::alt_bn128_G2 share2; - share2.Z = libff::alt_bn128_Fq2::one(); + status = trustedGenerateBLSKey(eid, &errStatus, errMsg.data(), &exportable, + encrBlsKeySecond, &encBlsLen); - share2.X.c0 = libff::alt_bn128_Fq( decryption_share2[0].asCString() ); - share2.X.c1 = libff::alt_bn128_Fq( decryption_share2[1].asCString() ); - share2.Y.c0 = libff::alt_bn128_Fq( decryption_share2[2].asCString() ); - share2.Y.c1 = libff::alt_bn128_Fq( decryption_share2[3].asCString() ); + vector decrKeySecond(BUF_LEN, 0); + status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrBlsKeySecond, + encBlsLen, decrKeySecond.data()); - REQUIRE( share2 == key * decryption_value2 ); + mpz_t blsKeySecond; + mpz_init(blsKeySecond); + mpz_set_str(blsKeySecond, decrKeySecond.data(), 16); + + REQUIRE(mpz_cmp(blsKey, blsKeySecond) != 0); } -TEST_CASE_METHOD(TestFixture, "Test decryption share for threshold encryption via zmq", "[te-decryption-share-zmq]") { - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); +TEST_CASE_METHOD(TestFixture, + "Test key generation for bls aggregated signatures scheme", + "[bls-aggregated-key-generation]") { + HttpClient htp(RPC_ENDPOINT); + StubClient c(htp, JSONRPC_CLIENT_V2); - std::string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f"; - std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; - client->importBLSKeyShare(key_str, name); + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; + auto response = c.generateBLSPrivateKey(name); - // the same key writtn in decimal - libff::alt_bn128_Fr key = libff::alt_bn128_Fr( - "6507625568967977077291849236396320012317305261598035438182864059942098934847"); + REQUIRE(response["status"] == 0); +} - libff::alt_bn128_G2 decryption_value1 = libff::alt_bn128_G2::random_element(); - libff::alt_bn128_G2 decryption_value2 = libff::alt_bn128_G2::random_element(); - - decryption_value1.to_affine_coordinates(); - decryption_value2.to_affine_coordinates(); +TEST_CASE_METHOD( + TestFixture, + "Test key generation for bls aggregated signatures scheme via zmq", + "[bls-aggregated-key-generation-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - auto decrytion_value_str1 = convertG2ToString( decryption_value1, ':' ); - auto decrytion_value_str2 = convertG2ToString( decryption_value2, ':' ); + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; - Json::Value publicDecryptionValues; - publicDecryptionValues["publicDecryptionValues"][0] = decrytion_value_str1; - publicDecryptionValues["publicDecryptionValues"][1] = decrytion_value_str2; + REQUIRE(client->generateBLSPrivateKey(name)); +} - auto decryptionShares = client->getDecryptionShares( name, publicDecryptionValues ); +TEST_CASE_METHOD(TestFixture, + "Test message signing for bls aggregated signatures scheme", + "[bls-aggregated-signing]") { + HttpClient htp(RPC_ENDPOINT); + StubClient c(htp, JSONRPC_CLIENT_V2); - auto decryption_share1 = decryptionShares[0]; - auto decryption_share2 = decryptionShares[1]; + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; + auto response = c.generateBLSPrivateKey(name); + REQUIRE(response["status"] == 0); - libff::alt_bn128_G2 share1; - share1.Z = libff::alt_bn128_Fq2::one(); + string hash = SAMPLE_HASH; + response = c.blsSignMessageHash(name, hash, 1, 1); + REQUIRE(response["status"] == 0); +} - share1.X.c0 = libff::alt_bn128_Fq( decryption_share1[0].asCString() ); - share1.X.c1 = libff::alt_bn128_Fq( decryption_share1[1].asCString() ); - share1.Y.c0 = libff::alt_bn128_Fq( decryption_share1[2].asCString() ); - share1.Y.c1 = libff::alt_bn128_Fq( decryption_share1[3].asCString() ); +TEST_CASE_METHOD( + TestFixture, + "Test message signing for bls aggregated signatures scheme via zmq", + "[bls-aggregated-signing-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); + + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; + REQUIRE(client->generateBLSPrivateKey(name)); + + string hash = SAMPLE_HASH; + string signature = client->blsSignMessageHash(name, hash, 1, 1); + REQUIRE(!signature.empty()); +} - REQUIRE( share1 == key * decryption_value1 ); +TEST_CASE_METHOD(TestFixture, + "Test pop prove for bls aggregated signatures scheme", + "[bls-aggregated-pop-prove]") { + HttpClient htp(RPC_ENDPOINT); + StubClient c(htp, JSONRPC_CLIENT_V2); - libff::alt_bn128_G2 share2; - share2.Z = libff::alt_bn128_Fq2::one(); + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; - share2.X.c0 = libff::alt_bn128_Fq( decryption_share2[0].asCString() ); - share2.X.c1 = libff::alt_bn128_Fq( decryption_share2[1].asCString() ); - share2.Y.c0 = libff::alt_bn128_Fq( decryption_share2[2].asCString() ); - share2.Y.c1 = libff::alt_bn128_Fq( decryption_share2[3].asCString() ); + libff::alt_bn128_Fr key = libff::alt_bn128_Fr::random_element(); + while (key == libff::alt_bn128_Fr::zero()) { + key = libff::alt_bn128_Fr::random_element(); + } - REQUIRE( share2 == key * decryption_value2 ); + std::string keyStr = TestUtils::stringFromFr(key, 16); + auto response = c.importBLSKeyShare(keyStr, name); + REQUIRE(response["status"] == 0); + + libff::alt_bn128_G1 popProveLocal = libBLS::Bls::PopProve(key); + + response = c.popProve(name); + REQUIRE(response["status"] == 0); + shared_ptr sigSharePtr = + make_shared(response["popProve"].asString()); + BLSSigShare sig(sigSharePtr, 1, 1, 1); + libff::alt_bn128_G1 popProveEnclave = *sig.getSigShare(); + + REQUIRE(popProveLocal == popProveEnclave); } -TEST_CASE_METHOD(TestFixtureZMQSign, "ZMQ-ecdsa", "[zmq-ecdsa]") { - HttpClient htp(RPC_ENDPOINT); - StubClient c(htp, JSONRPC_CLIENT_V2); +TEST_CASE_METHOD(TestFixture, + "Test pop prove for bls aggregated signatures scheme via zmq", + "[bls-aggregated-pop-prove-zmq]") { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem", - "./sgx_data/cert_data/rootCA.key"); + std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; - string keyName = ""; + libff::alt_bn128_Fr key = libff::alt_bn128_Fr::random_element(); + while (key == libff::alt_bn128_Fr::zero()) { + key = libff::alt_bn128_Fr::random_element(); + } - PRINT_SRC_LINE - keyName = genECDSAKeyAPI(c); - int end = 10000000; - string sh = string(SAMPLE_HASH); + std::string keyStr = TestUtils::stringFromFr(key, 16); + auto response = client->importBLSKeyShare(keyStr, name); + REQUIRE(response); - std::vector workers; + libff::alt_bn128_G1 popProveLocal = libBLS::Bls::PopProve(key); - PRINT_SRC_LINE + std::string pop_prove_response = client->popProve(name); + shared_ptr sigSharePtr = make_shared(pop_prove_response); + BLSSigShare sig(sigSharePtr, 1, 1, 1); + libff::alt_bn128_G1 popProveEnclave = *sig.getSigShare(); + + REQUIRE(popProveLocal == popProveEnclave); +} + +TEST_CASE_METHOD(TestFixtureZMQSign, "ZMQ-ecdsa", "[zmq-ecdsa]") { + HttpClient htp(RPC_ENDPOINT); + StubClient c(htp, JSONRPC_CLIENT_V2); - for (int j = 0; j < 2; j++) { - workers.push_back(std::thread([client, sh, keyName, end, j]() { - CHECK_STATE(client); - for (int i = (j * 2000); i < (j * 2000) + 1000; i++) { + auto client = make_shared(ZMQ_IP, ZMQ_PORT, true, + "./sgx_data/cert_data/rootCA.pem", + "./sgx_data/cert_data/rootCA.key"); - auto hash = sh.substr(0, sh.size() - 8) + to_string(end + i); + string keyName = ""; - auto sig = client->ecdsaSignMessageHash(16, keyName, hash); - REQUIRE(sig.size() > 10); - } + PRINT_SRC_LINE + keyName = genECDSAKeyAPI(c); + int end = 10000000; + string sh = string(SAMPLE_HASH); - })); - }; + std::vector workers; - std::for_each(workers.begin(), workers.end(), []( - std::thread &t) { t.join(); }); - PRINT_SRC_LINE + PRINT_SRC_LINE + + for (int j = 0; j < 2; j++) { + workers.push_back(std::thread([client, sh, keyName, end, j]() { + CHECK_STATE(client); + for (int i = (j * 2000); i < (j * 2000) + 1000; i++) { + + auto hash = sh.substr(0, sh.size() - 8) + to_string(end + i); + + auto sig = client->ecdsaSignMessageHash(16, keyName, hash); + REQUIRE(sig.size() > 10); + } + })); + }; + std::for_each(workers.begin(), workers.end(), + [](std::thread &t) { t.join(); }); + PRINT_SRC_LINE } -TEST_CASE_METHOD(TestFixtureNoResetFromBackup, "Backup restore", "[backup-restore]") {} +TEST_CASE_METHOD(TestFixtureNoResetFromBackup, "Backup restore", + "[backup-restore]") {} diff --git a/testw.h b/testw.h index 242b3fe7..901658b0 100644 --- a/testw.h +++ b/testw.h @@ -24,27 +24,39 @@ #ifndef SGXWALLET_TESTW_H #define SGXWALLET_TESTW_H -#define TEST_BLS_KEY_SHARE "4160780231445160889237664391382223604184857153814275770598791864649971919844" +#define TEST_BLS_KEY_SHARE \ + "41607802314451608892376643913822236041848571538142757705987918646499719198" \ + "44" #define TEST_BLS_KEY_NAME "SCHAIN:17:INDEX:5:KEY:1" -#define SAMPLE_HASH "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" -#define SAMPLE_HEX_HASH "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F" -#define SAMPLE_KEY_NAME "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01" +#define SAMPLE_HASH \ + "09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" +#define SAMPLE_HEX_HASH \ + "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F" +#define SAMPLE_KEY_NAME \ + "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01" #define SAMPLE_AES_KEY "123456789" #define SAMPLE_POLY_NAME "POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1" -#define RPC_ENDPOINT "http://localhost:1029" -#define RPC_ENDPOINT_HTTPS "https://localhost:1026" +#define RPC_ENDPOINT "http://localhost:1029" +#define RPC_ENDPOINT_HTTPS "https://localhost:1026" #define ZMQ_IP "127.0.0.1" #define ZMQ_PORT 1031 -#define SAMPLE_PUBLIC_KEY_B "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475" +#define SAMPLE_PUBLIC_KEY_B \ + "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e" \ + "7fc87932eee5478b1b9023de19df654395574a690843988c3ff475" -#define SAMPLE_DKG_PUB_KEY_1 "505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2" -#define SAMPLE_DKG_PUB_KEY_2 "378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25" +#define SAMPLE_DKG_PUB_KEY_1 \ + "505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d2295" \ + "3d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2" +#define SAMPLE_DKG_PUB_KEY_2 \ + "378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d" \ + "6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25" -//openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr^ +// openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out +// yourdomain.csr^ #define SAMPLE_CSR_FILE_NAME "samples/yourdomain.csr" #define ECDSA_KEY_NAME_SIZE 68 -#endif //SGXWALLET_TESTW_H +#endif // SGXWALLET_TESTW_H diff --git a/testw.py b/testw.py index ed4e8c62..ce649569 100755 --- a/testw.py +++ b/testw.py @@ -32,7 +32,7 @@ "[first-run]", "[second-run]", "[many-threads-crypto-v2]", - "[many-threads-crypto-v2-zmq]" + "[many-threads-crypto-v2-zmq]", "[backup-restore]", "[cert-sign]", "[get-server-status]", @@ -64,7 +64,14 @@ "[aes-dkg-v2]", "[aes-dkg-v2-zmq]", "[te-decryption-share]", - "[te-decryption-share-zmq]" + "[te-decryption-share-zmq]", + "[bls-aggregated-key-decrypt]", + "[bls-aggregated-key-generation]", + "[bls-aggregated-key-generation-zmq]", + "[bls-aggregated-signing]", + "[bls-aggregated-signing-zmq]", + "[bls-aggregated-pop-prove]", + "[bls-aggregated-pop-prove-zmq]" ] diff --git a/catch.hpp b/third_party/catch.hpp similarity index 86% rename from catch.hpp rename to third_party/catch.hpp index 5feb2a4b..d2a12427 100644 --- a/catch.hpp +++ b/third_party/catch.hpp @@ -1,9 +1,9 @@ /* - * Catch v2.9.2 - * Generated: 2019-08-08 13:35:12.279703 + * Catch v2.13.9 + * Generated: 2022-04-12 22:37:23.260201 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved. + * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -14,8 +14,8 @@ #define CATCH_VERSION_MAJOR 2 -#define CATCH_VERSION_MINOR 9 -#define CATCH_VERSION_PATCH 2 +#define CATCH_VERSION_MINOR 13 +#define CATCH_VERSION_PATCH 9 #ifdef __clang__ # pragma clang system_header @@ -66,13 +66,16 @@ #if !defined(CATCH_CONFIG_IMPL_ONLY) // start catch_platform.h +// See e.g.: +// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html #ifdef __APPLE__ -# include -# if TARGET_OS_OSX == 1 -# define CATCH_PLATFORM_MAC -# elif TARGET_OS_IPHONE == 1 -# define CATCH_PLATFORM_IPHONE -# endif +# include +# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ + (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) +# define CATCH_PLATFORM_MAC +# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) +# define CATCH_PLATFORM_IPHONE +# endif #elif defined(linux) || defined(__linux) || defined(__linux__) # define CATCH_PLATFORM_LINUX @@ -132,36 +135,51 @@ namespace Catch { #endif -#if defined(CATCH_CPP17_OR_GREATER) -# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +// Only GCC compiler should be used in this block, so other compilers trying to +// mask themselves as GCC should be ignored. +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) + +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) + #endif -#ifdef __clang__ +#if defined(__clang__) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) + +// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug +// which results in calls to destructors being emitted for each temporary, +// without a matching initialization. In practice, this can result in something +// like `std::string::~string` being called on an uninitialized value. +// +// For example, this code will likely segfault under IBM XL: +// ``` +// REQUIRE(std::string("12") + "34" == "1234") +// ``` +// +// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. +# if !defined(__ibmxl__) && !defined(__CUDACC__) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ +# endif + +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ + _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) + +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - _Pragma( "clang diagnostic push" ) \ - _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ - _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") -# define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ - _Pragma( "clang diagnostic pop" ) - -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic push" ) \ - _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) -# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic pop" ) - -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ - _Pragma( "clang diagnostic push" ) \ - _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) -# define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \ - _Pragma( "clang diagnostic pop" ) - -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - _Pragma( "clang diagnostic push" ) \ - _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) -# define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \ - _Pragma( "clang diagnostic pop" ) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) #endif // __clang__ @@ -186,6 +204,7 @@ namespace Catch { // Android somehow still does not support std::to_string #if defined(__ANDROID__) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE #endif //////////////////////////////////////////////////////////////////////////////// @@ -219,11 +238,7 @@ namespace Catch { //////////////////////////////////////////////////////////////////////////////// // Visual C++ -#ifdef _MSC_VER - -# if _MSC_VER >= 1900 // Visual Studio 2015 or newer -# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS -# endif +#if defined(_MSC_VER) // Universal Windows platform does not support SEH // Or console colours (or console at all...) @@ -233,12 +248,20 @@ namespace Catch { # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH # endif +# if !defined(__clang__) // Handle Clang masquerading for msvc + // MSVC traditional preprocessor needs some workaround for __VA_ARGS__ // _MSVC_TRADITIONAL == 0 means new conformant preprocessor // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor -# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) -# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -# endif +# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +# endif // MSVC_TRADITIONAL + +// Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop` +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) +# endif // __clang__ + #endif // _MSC_VER #if defined(_REENTRANT) || defined(_MSC_VER) @@ -286,49 +309,46 @@ namespace Catch { #define CATCH_CONFIG_COLOUR_NONE #endif -//////////////////////////////////////////////////////////////////////////////// -// Check if string_view is available and usable -// The check is split apart to work around v140 (VS2015) preprocessor issue... -#if defined(__has_include) -#if __has_include() && defined(CATCH_CPP17_OR_GREATER) -# define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW +#if !defined(_GLIBCXX_USE_C99_MATH_TR1) +#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER #endif -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Check if optional is available and usable -#if defined(__has_include) -# if __has_include() && defined(CATCH_CPP17_OR_GREATER) -# define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL -# endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) -#endif // __has_include -//////////////////////////////////////////////////////////////////////////////// -// Check if byte is available and usable -#if defined(__has_include) -# if __has_include() && defined(CATCH_CPP17_OR_GREATER) -# define CATCH_INTERNAL_CONFIG_CPP17_BYTE -# endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) -#endif // __has_include - -//////////////////////////////////////////////////////////////////////////////// -// Check if variant is available and usable +// Various stdlib support checks that require __has_include #if defined(__has_include) -# if __has_include() && defined(CATCH_CPP17_OR_GREATER) -# if defined(__clang__) && (__clang_major__ < 8) - // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 - // fix should be in clang 8, workaround in libstdc++ 8.2 -# include -# if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) -# define CATCH_CONFIG_NO_CPP17_VARIANT -# else -# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT -# endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) -# else -# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT -# endif // defined(__clang__) && (__clang_major__ < 8) -# endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) -#endif // __has_include + // Check if string_view is available and usable + #if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW + #endif + + // Check if optional is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if byte is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # include + # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) + # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # endif + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if variant is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # if defined(__clang__) && (__clang_major__ < 8) + // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 + // fix should be in clang 8, workaround in libstdc++ 8.2 + # include + # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # define CATCH_CONFIG_NO_CPP17_VARIANT + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__clang__) && (__clang_major__ < 8) + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // defined(__has_include) #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) # define CATCH_CONFIG_COUNTER @@ -353,10 +373,6 @@ namespace Catch { # define CATCH_CONFIG_CPP17_OPTIONAL #endif -#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) -# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS -#endif - #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) # define CATCH_CONFIG_CPP17_STRING_VIEW #endif @@ -389,21 +405,49 @@ namespace Catch { # define CATCH_CONFIG_USE_ASYNC #endif +#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) +# define CATCH_CONFIG_ANDROID_LOGWRITE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) +# define CATCH_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Even if we do not think the compiler has that warning, we still have +// to provide a macro that can be used by the code. +#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION +#endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS -# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS -# define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS -# define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS -# define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS +#endif + +// The goal of this macro is to avoid evaluation of the arguments, but +// still have the compiler warn on problems inside... +#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) +#endif + +#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#elif defined(__clang__) && (__clang_major__ < 5) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) @@ -468,7 +512,7 @@ namespace Catch { SourceLineInfo( SourceLineInfo&& ) noexcept = default; SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; - bool empty() const noexcept; + bool empty() const noexcept { return file[0] == '\0'; } bool operator == ( SourceLineInfo const& other ) const noexcept; bool operator < ( SourceLineInfo const& other ) const noexcept; @@ -509,9 +553,10 @@ namespace Catch { } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ - CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION // end catch_tag_alias_autoregistrar.h // start catch_test_registry.h @@ -551,53 +596,30 @@ namespace Catch { #include #include #include +#include namespace Catch { /// A non-owning string class (similar to the forthcoming std::string_view) /// Note that, because a StringRef may be a substring of another string, - /// it may not be null terminated. c_str() must return a null terminated - /// string, however, and so the StringRef will internally take ownership - /// (taking a copy), if necessary. In theory this ownership is not externally - /// visible - but it does mean (substring) StringRefs should not be shared between - /// threads. + /// it may not be null terminated. class StringRef { public: using size_type = std::size_t; + using const_iterator = const char*; private: - friend struct StringRefTestAccess; - - char const* m_start; - size_type m_size; - - char* m_data = nullptr; - - void takeOwnership(); - static constexpr char const* const s_empty = ""; - public: // construction/ assignment - StringRef() noexcept - : StringRef( s_empty, 0 ) - {} - - StringRef( StringRef const& other ) noexcept - : m_start( other.m_start ), - m_size( other.m_size ) - {} + char const* m_start = s_empty; + size_type m_size = 0; - StringRef( StringRef&& other ) noexcept - : m_start( other.m_start ), - m_size( other.m_size ), - m_data( other.m_data ) - { - other.m_data = nullptr; - } + public: // construction + constexpr StringRef() noexcept = default; StringRef( char const* rawChars ) noexcept; - StringRef( char const* rawChars, size_type size ) noexcept + constexpr StringRef( char const* rawChars, size_type size ) noexcept : m_start( rawChars ), m_size( size ) {} @@ -607,101 +629,64 @@ namespace Catch { m_size( stdString.size() ) {} - ~StringRef() noexcept { - delete[] m_data; - } - - auto operator = ( StringRef const &other ) noexcept -> StringRef& { - delete[] m_data; - m_data = nullptr; - m_start = other.m_start; - m_size = other.m_size; - return *this; + explicit operator std::string() const { + return std::string(m_start, m_size); } - operator std::string() const; - - void swap( StringRef& other ) noexcept; - public: // operators auto operator == ( StringRef const& other ) const noexcept -> bool; - auto operator != ( StringRef const& other ) const noexcept -> bool; + auto operator != (StringRef const& other) const noexcept -> bool { + return !(*this == other); + } - auto operator[] ( size_type index ) const noexcept -> char; + auto operator[] ( size_type index ) const noexcept -> char { + assert(index < m_size); + return m_start[index]; + } public: // named queries - auto empty() const noexcept -> bool { + constexpr auto empty() const noexcept -> bool { return m_size == 0; } - auto size() const noexcept -> size_type { + constexpr auto size() const noexcept -> size_type { return m_size; } - auto numberOfCharacters() const noexcept -> size_type; + // Returns the current start pointer. If the StringRef is not + // null-terminated, throws std::domain_exception auto c_str() const -> char const*; public: // substrings and searches - auto substr( size_type start, size_type size ) const noexcept -> StringRef; + // Returns a substring of [start, start + length). + // If start + length > size(), then the substring is [start, size()). + // If start > size(), then the substring is empty. + auto substr( size_type start, size_type length ) const noexcept -> StringRef; - // Returns the current start pointer. - // Note that the pointer can change when if the StringRef is a substring - auto currentData() const noexcept -> char const*; + // Returns the current start pointer. May not be null-terminated. + auto data() const noexcept -> char const*; - private: // ownership queries - may not be consistent between calls - auto isOwned() const noexcept -> bool; - auto isSubstring() const noexcept -> bool; - }; + constexpr auto isNullTerminated() const noexcept -> bool { + return m_start[m_size] == '\0'; + } - auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string; - auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string; - auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string; + public: // iterators + constexpr const_iterator begin() const { return m_start; } + constexpr const_iterator end() const { return m_start + m_size; } + }; auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; - inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { + constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { return StringRef( rawChars, size ); } - } // namespace Catch -inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { +constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { return Catch::StringRef( rawChars, size ); } // end catch_stringref.h -// start catch_type_traits.hpp - - -#include - -namespace Catch{ - -#ifdef CATCH_CPP17_OR_GREATER - template - inline constexpr auto is_unique = std::true_type{}; - - template - inline constexpr auto is_unique = std::bool_constant< - (!std::is_same_v && ...) && is_unique - >{}; -#else - -template -struct is_unique : std::true_type{}; - -template -struct is_unique : std::integral_constant -::value - && is_unique::value - && is_unique::value ->{}; - -#endif -} - -// end catch_type_traits.hpp // start catch_preprocessor.hpp @@ -786,7 +771,7 @@ struct is_unique : std::integral_constant #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) -#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _4, _5, _6) +#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) @@ -798,35 +783,49 @@ struct is_unique : std::integral_constant template struct TypeList {};\ template\ constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ + template class...> struct TemplateTypeList{};\ + template class...Cs>\ + constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ + template\ + struct append;\ + template\ + struct rewrap;\ + template class, typename...>\ + struct create;\ + template class, typename>\ + struct convert;\ \ - template class L1, typename...E1, template class L2, typename...E2> \ - constexpr auto append(L1, L2) noexcept -> L1 { return {}; }\ + template \ + struct append { using type = T; };\ template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ - constexpr auto append(L1, L2, Rest...) noexcept -> decltype(append(L1{}, Rest{}...)) { return {}; }\ + struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ template< template class L1, typename...E1, typename...Rest>\ - constexpr auto append(L1, TypeList, Rest...) noexcept -> L1 { return {}; }\ + struct append, TypeList, Rest...> { using type = L1; };\ \ template< template class Container, template class List, typename...elems>\ - constexpr auto rewrap(List) noexcept -> TypeList> { return {}; }\ + struct rewrap, List> { using type = TypeList>; };\ template< template class Container, template class List, class...Elems, typename...Elements>\ - constexpr auto rewrap(List,Elements...) noexcept -> decltype(append(TypeList>{}, rewrap(Elements{}...))) { return {}; }\ + struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ \ template