testw.cpp 47.9 KB
Newer Older
1
/*
2
    Copyright (C) 2019-Present SKALE Labs
3

4
    This file is part of sgxwallet.
Chadwick Strange's avatar
Chadwick Strange committed
5

6 7 8 9
    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.
10

11 12 13 14
    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.
15

16
    You should have received a copy of the GNU Affero General Public License
17
    along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
18

19 20 21
    @file testw.cpp
    @author Stan Kladko
    @date 2020
22
*/
23

24
#include <dkg/dkg.h>
kladkogex's avatar
kladkogex committed
25
#include <jsonrpccpp/server/connectors/httpserver.h>
svetaro's avatar
svetaro committed
26
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
27
#include <dkg/dkg.h>
28
#include "sgxwallet_common.h"
29
#include "third_party/intel/create_enclave.h"
30
#include "secure_enclave_u.h"
31
#include "secure_enclave/DHDkg.h"
32
#include "third_party/intel/sgx_detect.h"
33 34
#include <gmp.h>
#include <sgx_urts.h>
kladkogex's avatar
kladkogex committed
35
#include <stdio.h>
36 37 38
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <sgx_tcrypto.h>

39
#include "BLSCrypto.h"
40
#include "CryptoTools.h"
kladkogex's avatar
kladkogex committed
41
#include "ServerInit.h"
42
#include "DKGCrypto.h"
43
#include "SGXException.h"
kladkogex's avatar
kladkogex committed
44 45
#include "LevelDB.h"
#include "SGXWalletServer.hpp"
46

kladko's avatar
kladko committed
47
#define CATCH_CONFIG_MAIN
48

49
#include "catch.hpp"
svetaro's avatar
svetaro committed
50
#include "stubclient.h"
51 52 53 54
#include "BLSSigShare.h"
#include "BLSSigShareSet.h"
#include "BLSPublicKeyShare.h"
#include "BLSPublicKey.h"
55
#include "SEKManager.h"
56
#include <thread>
kladko's avatar
kladko committed
57
#include "common.h"
kladko's avatar
kladko committed
58

kladko's avatar
kladko committed
59
#include "SGXRegistrationServer.h"
60
#include "SGXWalletServer.h"
61 62
#include "zmq_src/ZMQClient.h"
#include "zmq_src/ZMQServer.h"
kladko's avatar
kladko committed
63 64
#include "sgxwallet.h"
#include "TestUtils.h"
kladko's avatar
kladko committed
65 66
#include "testw.h"

kladko's avatar
kladko committed
67 68
#define PRINT_SRC_LINE cerr << "Executing line " <<  to_string(__LINE__) << endl;

kladko's avatar
kladko committed
69 70 71
using namespace jsonrpc;
using namespace std;

kladko's avatar
kladko committed
72
class TestFixture {
kladko's avatar
kladko committed
73
public:
kladko's avatar
kladko committed
74
    TestFixture() {
kladko's avatar
kladko committed
75
        TestUtils::resetDB();
kladko's avatar
kladko committed
76
        setOptions(L_INFO, false, true);
77
        initAll(L_INFO, false, false, true, false, true);
kladko's avatar
kladko committed
78
    }
kladko's avatar
kladko committed
79

kladko's avatar
kladko committed
80
    ~TestFixture() {
kladko's avatar
kladko committed
81
        ZMQServer::exitZMQServer();
kladko's avatar
kladko committed
82
        TestUtils::destroyEnclave();
kladko's avatar
kladko committed
83
    }
kladko's avatar
kladko committed
84 85 86 87 88
};

class TestFixtureHTTPS {
public:
    TestFixtureHTTPS() {
kladko's avatar
kladko committed
89
        TestUtils::resetDB();
kladko's avatar
kladko committed
90
        setOptions(L_INFO, true, true);
91
        initAll(L_INFO, false, true, true, false, true);
kladko's avatar
kladko committed
92
    }
kladko's avatar
kladko committed
93

kladko's avatar
kladko committed
94
    ~TestFixtureHTTPS() {
kladko's avatar
kladko committed
95
        ZMQServer::exitZMQServer();
kladko's avatar
kladko committed
96
        TestUtils::destroyEnclave();
kladko's avatar
kladko committed
97
    }
kladko's avatar
kladko committed
98
};
kladko's avatar
kladko committed
99

kladko's avatar
kladko committed
100 101 102 103 104
class TestFixtureZMQSign {
public:
    TestFixtureZMQSign() {
        TestUtils::resetDB();
        setOptions(L_INFO, false, true);
105
        initAll(L_INFO, false, true, true, false, false);
kladko's avatar
kladko committed
106 107 108 109 110 111 112 113
    }

    ~TestFixtureZMQSign() {
        ZMQServer::exitZMQServer();
        TestUtils::destroyEnclave();
    }
};

114 115 116
class TestFixtureNoResetFromBackup {
public:
    TestFixtureNoResetFromBackup() {
kladko's avatar
kladko committed
117
        setFullOptions(L_INFO, false, true, true);
118
        initAll(L_INFO, false, false, true, false, true);
119 120 121
    }

    ~TestFixtureNoResetFromBackup() {
kladko's avatar
kladko committed
122
        sleep(3);
kladko's avatar
kladko committed
123
        ZMQServer::exitZMQServer();
124 125 126 127
        TestUtils::destroyEnclave();
    }
};

128 129 130 131
class TestFixtureNoReset {
public:
    TestFixtureNoReset() {
        setOptions(L_INFO, false, true);
132
        initAll(L_INFO, false, false, true, false, true);
133 134 135
    }

    ~TestFixtureNoReset() {
kladko's avatar
kladko committed
136
        ZMQServer::exitZMQServer();
137 138 139 140
        TestUtils::destroyEnclave();
    }
};

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
141 142 143
TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes-key-sig-gen]") {
    vector<char> errMsg(BUF_LEN, 0);
    int errStatus = 0;
kladko's avatar
kladko committed
144
    vector <uint8_t> encrPrivKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
145 146 147
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);

kladko's avatar
kladko committed
148
    uint64_t encLen = 0;
149
    int exportable = 0;
kladko's avatar
kladko committed
150
    PRINT_SRC_LINE
151
    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encrPrivKey.data(), &encLen,
kladko's avatar
kladko committed
152 153
                                          pubKeyX.data(),
                                          pubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
154 155 156 157 158 159 160 161
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);

    string hex = SAMPLE_HEX_HASH;
    vector<char> signatureR(BUF_LEN, 0);
    vector<char> signatureS(BUF_LEN, 0);
    uint8_t signatureV = 0;

kladko's avatar
kladko committed
162
    for (int i = 0; i < 50; i++) {
kladko's avatar
kladko committed
163
        PRINT_SRC_LINE
kladko's avatar
kladko committed
164
        status = trustedEcdsaSign(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen,
kladko's avatar
kladko committed
165 166 167
                                  hex.data(),
                                  signatureR.data(),
                                  signatureS.data(), &signatureV, 16);
168 169
        REQUIRE(status == SGX_SUCCESS);
        REQUIRE(errStatus == SGX_SUCCESS);
kladko's avatar
kladko committed
170
    }
171

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
172 173 174 175 176
}

TEST_CASE_METHOD(TestFixture, "ECDSA AES key gen", "[ecdsa-aes-key-gen]") {
    vector<char> errMsg(BUF_LEN, 0);
    int errStatus = 0;
kladko's avatar
kladko committed
177
    vector <uint8_t> encrPrivKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
178 179
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);
kladko's avatar
kladko committed
180
    uint64_t encLen = 0;
181
    int exportable = 0;
kladko's avatar
kladko committed
182
    PRINT_SRC_LINE
183
    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encrPrivKey.data(), &encLen,
kladko's avatar
kladko committed
184 185
                                          pubKeyX.data(),
                                          pubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
186 187 188 189 190 191 192 193

    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<char> errMsg(BUF_LEN, 0);
kladko's avatar
kladko committed
194
    vector <uint8_t> encPrivKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
195 196
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);
kladko's avatar
kladko committed
197 198

    uint64_t encLen = 0;
199
    int exportable = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
200

kladko's avatar
kladko committed
201
    PRINT_SRC_LINE
202
    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encPrivKey.data(), &encLen, pubKeyX.data(),
kladko's avatar
kladko committed
203
                                          pubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
204 205 206 207 208 209 210

    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);

    vector<char> receivedPubKeyX(BUF_LEN, 0);
    vector<char> receivedPubKeyY(BUF_LEN, 0);

kladko's avatar
kladko committed
211
    PRINT_SRC_LINE
kladko's avatar
kladko committed
212
    status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen,
kladko's avatar
kladko committed
213 214
                                      receivedPubKeyX.data(),
                                      receivedPubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
215 216 217 218
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);
}

219
/* Do later
kladko's avatar
kladko committed
220
TEST_CASE_METHOD("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
221
    resetDB();
222
    setOptions(false, false, false, true);
223
    initAll(0, false, true);
224 225 226 227 228 229 230

    //init_enclave();

    int errStatus = -1;

    vector<char> errMsg(BUF_LEN, 0);

kladko's avatar
kladko committed
231
    char *encryptedKey = TestUtils::encryptTestKey();
232 233 234 235 236 237 238 239 240 241 242 243 244 245
    REQUIRE(encryptedKey != nullptr);
    char *plaintextKey = decryptBLSKeyShareFromHex(&errStatus, errMsg.data(), encryptedKey);
    free(encryptedKey);

    REQUIRE(errStatus == 0);
    REQUIRE(strcmp(plaintextKey, TEST_BLS_KEY_SHARE) == 0);

    printf("Decrypt key completed with status: %d %s \n", errStatus, errMsg.data());
    printf("Decrypted key len %d\n", (int) strlen(plaintextKey));
    printf("Decrypted key: %s\n", plaintextKey);
    free(plaintextKey);
}
*/

kladko's avatar
kladko committed
246
string genECDSAKeyAPI(StubClient &_c) {
kladko's avatar
kladko committed
247 248 249 250 251 252 253
    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;
}

kladko's avatar
kladko committed
254
TEST_CASE_METHOD(TestFixture, "ECDSA key gen API", "[ecdsa-key-gen-api]") {
kladko's avatar
kladko committed
255
    HttpClient client(RPC_ENDPOINT);
kladko's avatar
kladko committed
256
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
257

kladko's avatar
kladko committed
258 259
    for (int i = 0; i <= 20; i++) {
        try {
kladko's avatar
kladko committed
260
            PRINT_SRC_LINE
kladko's avatar
kladko committed
261
            auto keyName = genECDSAKeyAPI(c);
kladko's avatar
kladko committed
262
            PRINT_SRC_LINE
kladko's avatar
kladko committed
263
            Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH);
kladko's avatar
kladko committed
264
            REQUIRE(sig["status"].asInt() == 0);
kladko's avatar
kladko committed
265
            Json::Value getPubKey = c.getPublicECDSAKey(keyName);
kladko's avatar
kladko committed
266 267 268
            REQUIRE(getPubKey["status"].asInt() == 0);
        } catch (JsonRpcException &e) {
            cerr << e.what() << endl;
269 270 271 272
            throw;
        }
    }

kladko's avatar
kladko committed
273 274
    auto keyName = genECDSAKeyAPI(c);

kladko's avatar
kladko committed
275
    Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH);
kladko's avatar
kladko committed
276

277 278
    for (int i = 0; i <= 20; i++) {
        try {
kladko's avatar
kladko committed
279
            PRINT_SRC_LINE
280
            auto keyName = genECDSAKeyAPI(c);
kladko's avatar
kladko committed
281
            PRINT_SRC_LINE
282 283
            Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH);
            REQUIRE(sig["status"].asInt() == 0);
kladko's avatar
kladko committed
284
            PRINT_SRC_LINE
285 286 287 288
            Json::Value getPubKey = c.getPublicECDSAKey(keyName);
            REQUIRE(getPubKey["status"].asInt() == 0);
        } catch (JsonRpcException &e) {
            cerr << e.what() << endl;
kladko's avatar
kladko committed
289 290
            throw;
        }
kladko's avatar
kladko committed
291 292 293
    }
}

kladko's avatar
kladko committed
294
TEST_CASE_METHOD(TestFixture, "BLS key encrypt", "[bls-key-encrypt]") {
kladko's avatar
kladko committed
295
    auto key = TestUtils::encryptTestKey();
kladko's avatar
kladko committed
296 297
    REQUIRE(key);
    sleep(3);
kladko's avatar
kladko committed
298 299
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
300
TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") {
kladko's avatar
kladko committed
301
    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
302 303 304
    vector<char> errMsg(BUF_LEN, 0);

    int errStatus = 0;
kladko's avatar
kladko committed
305
    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
306

kladko's avatar
kladko committed
307
    PRINT_SRC_LINE
kladko's avatar
kladko committed
308
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
309 310 311
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
312
    vector<char> secret(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
313 314
    vector<char> errMsg1(BUF_LEN, 0);

kladko's avatar
kladko committed
315
    status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(),
kladko's avatar
kladko committed
316
                                     encLen, (uint8_t *) secret.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
317

kladko's avatar
kladko committed
318 319
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);
kladko's avatar
kladko committed
320 321

    sleep(3);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
322
}
323

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
324
TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares]") {
kladko's avatar
kladko committed
325
    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
326 327 328
    vector<char> errMsg(BUF_LEN, 0);

    int errStatus = 0;
kladko's avatar
kladko committed
329
    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
330 331

    unsigned t = 32, n = 32;
kladko's avatar
kladko committed
332
    PRINT_SRC_LINE
kladko's avatar
kladko committed
333
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
334
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
335
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
336 337 338 339 340

    vector<char> errMsg1(BUF_LEN, 0);

    char colon = ':';
    vector<char> pubShares(10000, 0);
kladko's avatar
kladko committed
341
    PRINT_SRC_LINE
kladko's avatar
kladko committed
342
    status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(),
343
                                    encryptedDKGSecret.data(), encLen, pubShares.data(), t);
344
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
345
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
346

kladko's avatar
kladko committed
347 348
    vector <string> g2Strings = splitString(pubShares.data(), ',');
    vector <libff::alt_bn128_G2> pubSharesG2;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
349
    for (u_int64_t i = 0; i < g2Strings.size(); i++) {
kladko's avatar
kladko committed
350
        vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
351

kladko's avatar
kladko committed
352
        pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr));
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
353 354 355
    }

    vector<char> secret(BUF_LEN, 0);
kladko's avatar
kladko committed
356
    PRINT_SRC_LINE
kladko's avatar
kladko committed
357
    status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen,
kladko's avatar
kladko committed
358
                                     (uint8_t *) secret.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
359
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
360
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
361 362 363

    signatures::Dkg dkgObj(t, n);

kladko's avatar
kladko committed
364 365
    vector <libff::alt_bn128_Fr> poly = TestUtils::splitStringToFr(secret.data(), colon);
    vector <libff::alt_bn128_G2> pubSharesDkg = dkgObj.VerificationVector(poly);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
366 367 368 369 370 371
    for (uint32_t i = 0; i < pubSharesDkg.size(); i++) {
        libff::alt_bn128_G2 el = pubSharesDkg.at(i);
        el.to_affine_coordinates();
    }
    REQUIRE(pubSharesG2 == pubSharesDkg);
}
kladko's avatar
kladko committed
372

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
373 374 375 376 377
TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", "[dkg-aes-encr-sshares]") {
    vector<char> errMsg(BUF_LEN, 0);
    vector<char> result(BUF_LEN, 0);

    int errStatus = 0;
kladko's avatar
kladko committed
378
    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
379

kladko's avatar
kladko committed
380
    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
kladko's avatar
kladko committed
381
    PRINT_SRC_LINE
kladko's avatar
kladko committed
382
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
383
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
384
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
385

kladko's avatar
kladko committed
386
    vector <uint8_t> encrPRDHKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
387 388 389 390

    string pub_keyB = SAMPLE_PUBLIC_KEY_B;

    vector<char> s_shareG2(BUF_LEN, 0);
kladko's avatar
kladko committed
391
    PRINT_SRC_LINE
kladko's avatar
kladko committed
392
    status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(),
393 394
                                            encryptedDKGSecret.data(), encLen,
                                            encrPRDHKey.data(), &encLen,
kladko's avatar
kladko committed
395 396 397
                                            result.data(),
                                            s_shareG2.data(),
                                            (char *) pub_keyB.data(), 2, 2, 1);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
398 399

    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
400
    REQUIRE(errStatus == SGX_SUCCESS);
svetaro's avatar
svetaro committed
401 402
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares version 2 test", "[dkg-aes-encr-sshares-v2]") {
    vector<char> errMsg(BUF_LEN, 0);
    vector<char> result(BUF_LEN, 0);

    int errStatus = 0;
    uint64_t encLen = 0;

    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
    PRINT_SRC_LINE
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);

    vector <uint8_t> encrPRDHKey(BUF_LEN, 0);

    string pub_keyB = SAMPLE_PUBLIC_KEY_B;

    vector<char> s_shareG2(BUF_LEN, 0);
    PRINT_SRC_LINE
kladko's avatar
kladko committed
422 423 424 425 426 427
    status = trustedGetEncryptedSecretShareV2(eid, &errStatus, errMsg.data(),
                                              encryptedDKGSecret.data(), encLen,
                                              encrPRDHKey.data(), &encLen,
                                              result.data(),
                                              s_shareG2.data(),
                                              (char *) pub_keyB.data(), 2, 2, 1);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
428 429 430 431 432

    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);
}

433 434 435 436 437 438 439 440 441 442 443
/*
 * ( "verification test", "[verify]" ) {
    char*  pubshares = "0d72c21fc5a43452ad5f36699822309149ce6ce2cdce50dafa896e873f1b8ddd12f65a2e9c39c617a1f695f076b33b236b47ed773901fc2762f8b6f63277f5e30d7080be8e98c97f913d1920357f345dc0916c1fcb002b7beb060aa8b6b473a011bfafe9f8a5d8ea4c643ca4101e5119adbef5ae64f8dfb39cd10f1e69e31c591858d7eaca25b4c412fe909ca87ca7aadbf6d97d32d9b984e93d436f13d43ec31f40432cc750a64ac239cad6b8f78c1f1dd37427e4ff8c1cc4fe1c950fcbcec10ebfd79e0c19d0587adafe6db4f3c63ea9a329724a8804b63a9422e6898c0923209e828facf3a073254ec31af4231d999ba04eb5b7d1e0056d742a65b766f2f3";
    char *sec_share = "11592366544581417165283270001305852351194685098958224535357729125789505948557";
    mpz_t sshare;
    mpz_init(sshare);
    mpz_set_str(sshare, "11592366544581417165283270001305852351194685098958224535357729125789505948557", 10);
    int result = Verification(pubshares, sshare, 2, 0);
    REQUIRE(result == 1);
}*/

kladko's avatar
kladko committed
444 445 446
TEST_CASE_METHOD(TestFixture, "DKG_BLS test", "[dkg-bls]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
447

kladko's avatar
kladko committed
448 449
    vector <string> ecdsaKeyNames;
    vector <string> blsKeyNames;
kladko's avatar
kladko committed
450 451 452 453

    int schainID = TestUtils::randGen();
    int dkgID = TestUtils::randGen();

kladko's avatar
kladko committed
454
    PRINT_SRC_LINE
kladko's avatar
kladko committed
455
    TestUtils::doDKG(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
kladko's avatar
kladko committed
456 457 458 459 460 461

    REQUIRE(blsKeyNames.size() == 4);

    schainID = TestUtils::randGen();
    dkgID = TestUtils::randGen();

kladko's avatar
kladko committed
462
    TestUtils::doDKG(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
463
}
464

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
TEST_CASE_METHOD(TestFixture, "DKG_BLS V2 test", "[dkg-bls-v2]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    vector <string> ecdsaKeyNames;
    vector <string> blsKeyNames;

    int schainID = TestUtils::randGen();
    int dkgID = TestUtils::randGen();

    PRINT_SRC_LINE
    TestUtils::doDKGV2(c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID);

    REQUIRE(blsKeyNames.size() == 4);

    schainID = TestUtils::randGen();
    dkgID = TestUtils::randGen();

    TestUtils::doDKGV2(c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
}

kladko's avatar
kladko committed
486
TEST_CASE_METHOD(TestFixture, "DKG_BLS ZMQ test", "[dkgblszmq]") {
kladko's avatar
kladko committed
487 488 489
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

kladko's avatar
kladko committed
490
    string ip = ZMQ_IP;
kladko's avatar
kladko committed
491 492 493

    string empty = "";
    auto zmqClient = make_shared<ZMQClient>(ip, ZMQ_PORT, false, empty, empty);
kladko's avatar
kladko committed
494

kladko's avatar
kladko committed
495 496 497 498 499 500 501
    vector <string> ecdsaKeyNames;
    vector <string> blsKeyNames;

    int schainID = TestUtils::randGen();
    int dkgID = TestUtils::randGen();

    PRINT_SRC_LINE
kladko's avatar
kladko committed
502
    TestUtils::doZMQBLS(zmqClient,c, 4, 1, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
kladko's avatar
kladko committed
503 504 505
    REQUIRE(blsKeyNames.size() == 4);
    schainID = TestUtils::randGen();
    dkgID = TestUtils::randGen();
kladko's avatar
kladko committed
506
    TestUtils::doZMQBLS(zmqClient, c, 16, 5, ecdsaKeyNames, blsKeyNames, schainID, dkgID);
kladko's avatar
kladko committed
507 508 509
}


510 511 512
TEST_CASE_METHOD(TestFixture, "Delete Bls Key", "[delete-bls-key]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
513

514
    std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0";
kladko's avatar
kladko committed
515 516
    libff::alt_bn128_Fr key = libff::alt_bn128_Fr(
            "6507625568967977077291849236396320012317305261598035438182864059942098934847");
517
    std::string key_str = TestUtils::stringFromFr(key);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
518 519 520 521 522 523 524 525 526
    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);

527
    REQUIRE(c.deleteBlsKey(name)["deleted"] == true);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
528
}
kladko's avatar
kladko committed
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
TEST_CASE_METHOD(TestFixture, "Delete Bls Key Zmq", "[delete-bls-key-zmq]") {
    auto client = make_shared<ZMQClient>(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));

    key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
    REQUIRE(client->importBLSKeyShare(key_str, name));

    REQUIRE_NOTHROW(client->blsSignMessageHash(name, SAMPLE_HASH, 1, 1));

    REQUIRE(client->deleteBLSKey(name));
}

548 549 550 551 552
TEST_CASE_METHOD(TestFixture, "Import ECDSA Key", "[import-ecdsa-key]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    std::string name = "NEK:abcdef";
kladko's avatar
kladko committed
553 554
    auto response = c.importECDSAKey("6507625568967977077291849236396320012317305261598035438182864059942098934847",
                                     name);
555 556 557 558 559 560 561 562 563
    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);
}

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
TEST_CASE_METHOD(TestFixture, "Import ECDSA Key Zmq", "[import-ecdsa-key-zmq]") {
    auto client = make_shared<ZMQClient>(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));

    string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
    string response = client->importECDSAKey(key_str, name);
    REQUIRE(response == client->getECDSAPublicKey(name));

    REQUIRE_NOTHROW(client->ecdsaSignMessageHash(16, name, SAMPLE_HASH));
}

579 580 581
TEST_CASE_METHOD(TestFixture, "Backup Key", "[backup-key]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
582
    std::ifstream sek_file("sgx_data/sgxwallet_backup_key.txt");
583 584 585 586 587 588
    REQUIRE(sek_file.good());

    std::string sek;
    sek_file >> sek;

    REQUIRE(sek.size() == 32);
kladko's avatar
kladko committed
589
    sleep(3);
590
}
kladko's avatar
kladko committed
591

kladko's avatar
kladko committed
592
TEST_CASE_METHOD(TestFixture, "Get ServerStatus", "[get-server-status]") {
kladko's avatar
kladko committed
593
    HttpClient client(RPC_ENDPOINT);
594
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
595
    REQUIRE(c.getServerStatus()["status"] == 0);
kladko's avatar
kladko committed
596
    sleep(3);
kladko's avatar
kladko committed
597
}
598

599
TEST_CASE_METHOD(TestFixture, "Get ServerStatusZmq", "[get-server-status-zmq]") {
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
600 601 602 603 604 605
    auto client = make_shared<ZMQClient>(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem",
                                         "./sgx_data/cert_data/rootCA.key");
    REQUIRE_NOTHROW(client->getServerStatus());
    sleep(3);
}

606 607 608
TEST_CASE_METHOD(TestFixture, "Get ServerVersion", "[get-server-version]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
609
    REQUIRE(c.getServerVersion()["version"] == SGXWalletServer::getVersion());
kladko's avatar
kladko committed
610
    sleep(3);
611 612
}

613
TEST_CASE_METHOD(TestFixture, "Get ServerVersionZmq", "[get-server-version-zmq]") {
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
614 615 616 617 618 619
    auto client = make_shared<ZMQClient>(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem",
                                         "./sgx_data/cert_data/rootCA.key");
    REQUIRE(client->getServerVersion() == SGXWalletServer::getVersion());
    sleep(3);
}

kladko's avatar
kladko committed
620
TEST_CASE_METHOD(TestFixtureHTTPS, "Cert request sign", "[cert-sign]") {
kladko's avatar
kladko committed
621 622 623 624 625 626

    PRINT_SRC_LINE

    REQUIRE_NOTHROW(SGXRegistrationServer::getServer());

    PRINT_SRC_LINE
kladko's avatar
kladko committed
627 628 629 630 631 632 633 634 635

    string csrFile = "insecure-samples/yourdomain.csr";

    ifstream infile(csrFile);
    infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    ostringstream ss;
    ss << infile.rdbuf();
    infile.close();

kladko's avatar
kladko committed
636 637
    PRINT_SRC_LINE

kladko's avatar
kladko committed
638
    auto result = SGXRegistrationServer::getServer()->SignCertificate(ss.str());
kladko's avatar
kladko committed
639 640

    REQUIRE(result["status"] == 0);
kladko's avatar
kladko committed
641

kladko's avatar
kladko committed
642
    PRINT_SRC_LINE
kladko's avatar
kladko committed
643 644 645
    result = SGXRegistrationServer::getServer()->SignCertificate("Haha");

    REQUIRE(result["status"] != 0);
kladko's avatar
kladko committed
646 647
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
TEST_CASE_METHOD(TestFixture, "DKG API V2 test", "[dkg-api-v2]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    string polyName = SAMPLE_POLY_NAME;

    PRINT_SRC_LINE
    Json::Value genPoly = c.generateDKGPoly(polyName, 2);
    REQUIRE(genPoly["status"].asInt() == 0);

    Json::Value publicKeys;
    publicKeys.append(SAMPLE_DKG_PUB_KEY_1);
    publicKeys.append(SAMPLE_DKG_PUB_KEY_2);

    // wrongName
    Json::Value genPolyWrongName = c.generateDKGPoly("poly", 2);
    REQUIRE(genPolyWrongName["status"].asInt() != 0);

666
    Json::Value verifVectWrongName = c.getVerificationVector("poly", 2);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
667 668 669 670 671 672 673 674 675
    REQUIRE(verifVectWrongName["status"].asInt() != 0);

    Json::Value secretSharesWrongName = c.getSecretShareV2("poly", publicKeys, 2, 2);
    REQUIRE(secretSharesWrongName["status"].asInt() != 0);

    // wrong_t
    Json::Value genPolyWrong_t = c.generateDKGPoly(polyName, 33);
    REQUIRE(genPolyWrong_t["status"].asInt() != 0);

676
    Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    REQUIRE(verifVectWrong_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);

    //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));

696 697 698
    Json::Value verifVect = c.getVerificationVector(polyName, 2);
    REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2));
    REQUIRE(verifVect == c.getVerificationVector(polyName, 2));
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
699 700 701 702 703

    Json::Value verificationWrongSkeys = c.dkgVerificationV2("", "", "", 2, 2, 1);
    REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
TEST_CASE_METHOD(TestFixture, "DKG API V2 ZMQ test", "[dkg-api-v2-zmq]") {
    auto client = make_shared<ZMQClient>(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem",
                                         "./sgx_data/cert_data/rootCA.key");

    string polyName = SAMPLE_POLY_NAME;

    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);

    // wrongName
    REQUIRE(!client->generateDKGPoly("poly", 2));

    REQUIRE_THROWS(client->getVerificationVector("poly", 2));

    REQUIRE_THROWS(client->getSecretShare("poly", publicKeys, 2, 2));

    // wrong_t
    REQUIRE(!client->generateDKGPoly(polyName, 33));

    REQUIRE_THROWS(client->getVerificationVector(polyName, 0));

    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));

    //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));

    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));
}

kladko's avatar
kladko committed
750
TEST_CASE_METHOD(TestFixture, "PolyExists test", "[dkg-poly-exists]") {
kladko's avatar
kladko committed
751
    HttpClient client(RPC_ENDPOINT);
kladko's avatar
kladko committed
752
    StubClient c(client, JSONRPC_CLIENT_V2);
753

kladko's avatar
kladko committed
754
    string polyName = SAMPLE_POLY_NAME;
kladko's avatar
kladko committed
755
    PRINT_SRC_LINE
kladko's avatar
kladko committed
756
    Json::Value genPoly = c.generateDKGPoly(polyName, 2);
757
    REQUIRE(genPoly["status"] == 0);
758

kladko's avatar
kladko committed
759
    PRINT_SRC_LINE
kladko's avatar
kladko committed
760
    Json::Value polyExists = c.isPolyExists(polyName);
761
    REQUIRE(polyExists["status"] == 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
762
    REQUIRE(polyExists["IsExist"].asBool());
763

kladko's avatar
kladko committed
764
    PRINT_SRC_LINE
kladko's avatar
kladko committed
765
    Json::Value polyDoesNotExist = c.isPolyExists("Vasya");
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
766
    REQUIRE(!polyDoesNotExist["IsExist"].asBool());
767
}
768

769 770 771 772 773 774 775 776 777 778 779 780 781 782
TEST_CASE_METHOD(TestFixture, "PolyExistsZmq test", "[dkg-poly-exists-zmq]") {
    auto client = make_shared<ZMQClient>(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));

    bool polyExists = client->isPolyExists(polyName);
    REQUIRE(polyExists);

    bool polyDoesNotExist = client->isPolyExists("Vasya");
    REQUIRE(!polyDoesNotExist);
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
TEST_CASE_METHOD(TestFixture, "AES_DKG V2 test", "[aes-dkg-v2]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    int n = 2, t = 2;
    Json::Value ethKeys[n];
    Json::Value verifVects[n];
    Json::Value pubEthKeys;
    Json::Value secretShares[n];
    Json::Value pubBLSKeys[n];
    Json::Value blsSigShares[n];
    vector <string> pubShares(n);
    vector <string> polyNames(n);

    int schainID = TestUtils::randGen();
    int dkgID = TestUtils::randGen();
    for (uint8_t i = 0; i < n; i++) {
        PRINT_SRC_LINE
        ethKeys[i] = c.generateECDSAKey();
        REQUIRE(ethKeys[i]["status"] == 0);
        string polyName =
                "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
        REQUIRE(ethKeys[i]["status"] == 0);
        auto response = c.generateDKGPoly(polyName, t);
        REQUIRE(response["status"] == 0);

        polyNames[i] = polyName;
        PRINT_SRC_LINE
811
        verifVects[i] = c.getVerificationVector(polyName, t);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
        REQUIRE(verifVects[i]["status"] == 0);

        pubEthKeys.append(ethKeys[i]["publicKey"]);
    }

    for (uint8_t i = 0; i < n; i++) {
        PRINT_SRC_LINE
        secretShares[i] = c.getSecretShareV2(polyNames[i], pubEthKeys, t, n);
        REQUIRE(secretShares[i]["status"] == 0);

        for (uint8_t k = 0; k < t; k++)
            for (uint8_t j = 0; j < 4; j++) {
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
                pubShares[i] += TestUtils::convertDecToHex(pubShare);
            }
    }

    int k = 0;
    vector <string> secShares(n);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
            secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
            PRINT_SRC_LINE
kladko's avatar
kladko committed
837 838
            Json::Value verif = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n,
                                                    j);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
839 840 841 842 843 844 845 846 847 848 849 850 851
            REQUIRE(verif["status"] == 0);
            bool res = verif["result"].asBool();
            k++;
            REQUIRE(res);
        }

    Json::Value complaintResponse = c.complaintResponse(polyNames[1], t, n, 0);
    REQUIRE(complaintResponse["status"] == 0);

    string dhKey = complaintResponse["dhKey"].asString();
    string shareG2 = complaintResponse["share*G2"].asString();
    string secretShare = secretShares[1]["secretShare"].asString().substr(0, 192);

kladko's avatar
kladko committed
852
    vector<char> message(65, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
853 854 855 856 857 858 859

    SAFE_CHAR_BUF(encr_sshare, BUF_LEN)
    strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128);

    SAFE_CHAR_BUF(common_key, BUF_LEN);
    REQUIRE(sessionKeyRecoverDH(dhKey.c_str(), encr_sshare, common_key) == 0);

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
860 861 862 863 864
    uint8_t key_to_hash[33];
    uint64_t len;
    REQUIRE( hex2carray(common_key, &len, key_to_hash, 64) );

    auto hashed_key = cryptlite::sha256::hash_hex(string((char*)key_to_hash, 32));
865 866 867 868

    SAFE_CHAR_BUF(derived_key, 33)

    uint64_t key_length;
kladko's avatar
kladko committed
869
    REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t *) derived_key, 33));
870

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
871 872 873
    SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN)
    strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1);

874
    REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
875 876 877 878 879 880 881 882 883 884 885

    mpz_t hex_share;
    mpz_init(hex_share);
    mpz_set_str(hex_share, message.data(), 16);

    libff::alt_bn128_Fr share(hex_share);
    libff::alt_bn128_G2 decrypted_share_G2 = share * libff::alt_bn128_G2::one();
    decrypted_share_G2.to_affine_coordinates();

    mpz_clear(hex_share);

kladko's avatar
kladko committed
886
    REQUIRE(convertG2ToString(decrypted_share_G2) == shareG2);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900

    Json::Value verificationVectorMult = complaintResponse["verificationVectorMult"];

    libff::alt_bn128_G2 verificationValue = libff::alt_bn128_G2::zero();
    for (int i = 0; i < t; ++i) {
        libff::alt_bn128_G2 value;
        value.Z = libff::alt_bn128_Fq2::one();
        value.X.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][0].asCString());
        value.X.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][1].asCString());
        value.Y.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][2].asCString());
        value.Y.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][3].asCString());
        verificationValue = verificationValue + value;
    }
    verificationValue.to_affine_coordinates();
kladko's avatar
kladko committed
901
    REQUIRE(verificationValue == decrypted_share_G2);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
902 903 904 905 906

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

907
    auto hash_arr = make_shared < array < uint8_t, 32 > > ();
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
908 909 910 911

    uint64_t binLen;

    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
912
        throw SGXException(TEST_INVALID_HEX, "Invalid hash");
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
913 914 915 916 917 918 919
    }

    map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;

    for (int i = 0; i < t; i++) {
        string endName = polyNames[i].substr(4);
        string blsName = "BLS_KEY" + polyNames[i].substr(4);
kladko's avatar
kladko committed
920
        auto response = c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i],
921
                                                t, n);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
        REQUIRE(response["status"] == 0);

        PRINT_SRC_LINE
        pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
        REQUIRE(pubBLSKeys[i]["status"] == 0);

        string hash = SAMPLE_HASH;
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
        REQUIRE(blsSigShares[i]["status"] == 0);

        shared_ptr <string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
        BLSSigShare sig(sig_share_ptr, i + 1, t, n);
        sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));

        vector <string> pubKey_vect;
        for (uint8_t j = 0; j < 4; j++) {
            pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
        }
        BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKey_vect), t, n);
        PRINT_SRC_LINE
        REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));

        coeffs_pkeys_map[i + 1] = make_shared<BLSPublicKeyShare>(pubKey);
    }

    shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
    BLSPublicKey
    common_public(make_shared < map < size_t, shared_ptr < BLSPublicKeyShare >>>(coeffs_pkeys_map), t, n);
    REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
}

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
TEST_CASE_METHOD(TestFixture, "AES_DKG V2 ZMQ test", "[aes-dkg-v2-zmq]") {
    auto client = make_shared<ZMQClient>(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem",
                                         "./sgx_data/cert_data/rootCA.key");

    int n = 2, t = 2;
    vector<string> ethKeys(n);
    Json::Value verifVects[n];
    Json::Value pubEthKeys;
    vector<string> secretShares(n);
    Json::Value pubBLSKeys[n];
    vector<string> blsSigShares(n);
    vector<string> pubShares(n);
    vector<string> polyNames(n);

    int schainID = TestUtils::randGen();
    int dkgID = TestUtils::randGen();
    for (uint8_t i = 0; i < n; i++) {
        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);
            }
        }
    }

    int k = 0;
    vector <string> secShares(n);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i].substr(192 * j, 192);
            secShares[i] += secretShares[j].substr(192 * i, 192);
            REQUIRE(client->dkgVerification(pubShares[i], ethKeys[j], secretShare, t, n, j));
            k++;
        }

    auto complaintResponse = client->complaintResponse(polyNames[1], t, n, 0);

    string dhKey = std::get<0>(complaintResponse);
    string shareG2 = std::get<1>(complaintResponse);
    string secretShare = secretShares[1].substr(0, 192);

    vector<char> message(65, 0);

    SAFE_CHAR_BUF(encr_sshare, BUF_LEN)
    strncpy(encr_sshare, pubEthKeys[0].asString().c_str(), 128);

    SAFE_CHAR_BUF(common_key, BUF_LEN);
    REQUIRE(sessionKeyRecoverDH(dhKey.c_str(), encr_sshare, common_key) == 0);

    uint8_t key_to_hash[33];
    uint64_t len;
    REQUIRE( hex2carray(common_key, &len, key_to_hash, 64) );

    auto hashed_key = cryptlite::sha256::hash_hex(string((char*)key_to_hash, 32));

    SAFE_CHAR_BUF(derived_key, 33)

    uint64_t key_length;
    REQUIRE(hex2carray(&hashed_key[0], &key_length, (uint8_t *) derived_key, 33));

    SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN)
    strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1);

    REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0);

    mpz_t hex_share;
    mpz_init(hex_share);
    mpz_set_str(hex_share, message.data(), 16);

    libff::alt_bn128_Fr share(hex_share);
    libff::alt_bn128_G2 decrypted_share_G2 = share * libff::alt_bn128_G2::one();
    decrypted_share_G2.to_affine_coordinates();

    mpz_clear(hex_share);

    REQUIRE(convertG2ToString(decrypted_share_G2) == shareG2);

    Json::Value verificationVectorMult = std::get<2>(complaintResponse);

    libff::alt_bn128_G2 verificationValue = libff::alt_bn128_G2::zero();
    for (int i = 0; i < t; ++i) {
        libff::alt_bn128_G2 value;
        value.Z = libff::alt_bn128_Fq2::one();
        value.X.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][0].asCString());
        value.X.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][1].asCString());
        value.Y.c0 = libff::alt_bn128_Fq(verificationVectorMult[i][2].asCString());
        value.Y.c1 = libff::alt_bn128_Fq(verificationVectorMult[i][3].asCString());
        verificationValue = verificationValue + value;
    }
    verificationValue.to_affine_coordinates();
    REQUIRE(verificationValue == decrypted_share_G2);

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

    auto hash_arr = make_shared < array < uint8_t, 32 > > ();

    uint64_t binLen;

    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
        throw SGXException(TEST_INVALID_HEX, "Invalid hash");
    }

    map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;

    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));

        pubBLSKeys[i] = client->getBLSPublicKey(blsName);

        string hash = SAMPLE_HASH;
        blsSigShares[i] = client->blsSignMessageHash(blsName, hash, t, n);
        REQUIRE(blsSigShares[i].length() > 0);

        shared_ptr <string> sig_share_ptr = make_shared<string>(blsSigShares[i]);
        BLSSigShare sig(sig_share_ptr, i + 1, t, n);
        sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));

        vector <string> pubKey_vect;
        for (uint8_t j = 0; j < 4; j++) {
            pubKey_vect.push_back(pubBLSKeys[i][j].asString());
        }
        BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKey_vect), t, n);
        REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));

        coeffs_pkeys_map[i + 1] = make_shared<BLSPublicKeyShare>(pubKey);
    }

    shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
    BLSPublicKey
    common_public(make_shared < map < size_t, shared_ptr < BLSPublicKeyShare >>>(coeffs_pkeys_map), t, n);
    REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
}

kladko's avatar
kladko committed
1103
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
1104
    int errStatus = 0;
1105
    vector<char> errMsg(BUF_LEN, 0);
kladko's avatar
kladko committed
1106
    uint64_t encLen;
kladko's avatar
kladko committed
1107
    string key = SAMPLE_AES_KEY;
kladko's avatar
kladko committed
1108
    vector <uint8_t> encrypted_key(BUF_LEN, 0);
svetaro's avatar
svetaro committed
1109

kladko's avatar
kladko committed
1110
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1111
    auto status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen);
svetaro's avatar
svetaro committed
1112

kladko's avatar
kladko committed
1113
    REQUIRE(status == 0);
kladko's avatar
kladko committed
1114
    REQUIRE(errStatus == 0);
1115

kladko's avatar
kladko committed
1116
    vector<char> decr_key(BUF_LEN, 0);
kladko's avatar
kladko committed
1117
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1118
    status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data());
svetaro's avatar
svetaro committed
1119

kladko's avatar
kladko committed
1120
    REQUIRE(status == 0);
1121
    REQUIRE(key.compare(decr_key.data()) == 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1122
    REQUIRE(errStatus == 0);
kladko's avatar
kladko committed
1123
    sleep(3);
1124 1125
}

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
TEST_CASE_METHOD(TestFixture, "Exportable / non-exportable keys", "[exportable-nonexportable-keys]") {
    int errStatus = 0;
    vector<char> errMsg(BUF_LEN, 0);
    vector <uint8_t> encPrivKey(BUF_LEN, 0);
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);

    uint64_t encLen = 0;
    int exportable = 0;

    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), &exportable, encPrivKey.data(), &encLen, pubKeyX.data(),
                                          pubKeyY.data());

    vector<char> 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 <uint8_t> 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<char> 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);
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1176 1177 1178 1179
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls", "[many-threads-crypto-v2]") {
    vector <thread> threads;
    int num_threads = 4;
    for (int i = 0; i < num_threads; i++) {
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1180
        threads.push_back(thread(TestUtils::sendRPCRequestV2));
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1181 1182 1183 1184 1185 1186 1187
    }

    for (auto &thread : threads) {
        thread.join();
    }
}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls zmq", "[many-threads-crypto-v2-zmq]") {
    vector <thread> 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();
    }
}

1200
TEST_CASE_METHOD(TestFixture, "First run", "[first-run]") {
kladko's avatar
kladko committed
1201 1202 1203 1204 1205 1206

    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
    try {
        PRINT_SRC_LINE
        auto keyName = genECDSAKeyAPI(c);
kladko's avatar
kladko committed
1207 1208 1209
        ofstream namefile("/tmp/keyname");
        namefile << keyName;

kladko's avatar
kladko committed
1210
        PRINT_SRC_LINE
kladko's avatar
kladko committed
1211
    } catch (JsonRpcException &e) {
kladko's avatar
kladko committed
1212 1213 1214 1215
        cerr << e.what() << endl;
        throw;
    }

kladko's avatar
kladko committed
1216
    sleep(3);
1217 1218 1219
}

TEST_CASE_METHOD(TestFixtureNoReset, "Second run", "[second-run]") {
kladko's avatar
kladko committed
1220 1221 1222 1223 1224

    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
    try {
        PRINT_SRC_LINE
kladko's avatar
kladko committed
1225 1226 1227 1228
        string keyName;
        ifstream namefile("/tmp/keyname");
        getline(namefile, keyName);

kladko's avatar
kladko committed
1229 1230 1231 1232 1233 1234 1235 1236
        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;
    }
1237
}
1238

1239 1240 1241 1242 1243 1244
TEST_CASE_METHOD(TestFixture, "Test decryption share for threshold encryption", "[te-decryption-share]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    std::string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
    std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0";
1245
    c.importBLSKeyShare(key_str, name);
1246 1247 1248 1249 1250

    // the same key writtn in decimal
    libff::alt_bn128_Fr key = libff::alt_bn128_Fr(
            "6507625568967977077291849236396320012317305261598035438182864059942098934847");

1251 1252
    libff::alt_bn128_G2 decryption_value1 = libff::alt_bn128_G2::random_element();
    libff::alt_bn128_G2 decryption_value2 = libff::alt_bn128_G2::random_element();
1253

1254 1255
    decryption_value1.to_affine_coordinates();
    decryption_value2.to_affine_coordinates();
1256

1257 1258
    auto decrytion_value_str1 = convertG2ToString( decryption_value1, ':' );
    auto decrytion_value_str2 = convertG2ToString( decryption_value2, ':' );
1259

1260 1261 1262
    Json::Value publicDecryptionValues;
    publicDecryptionValues["publicDecryptionValues"][0] = decrytion_value_str1;
    publicDecryptionValues["publicDecryptionValues"][1] = decrytion_value_str2;
1263

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    auto decryptionShares = c.getDecryptionShares( name, publicDecryptionValues );

    auto decryption_share1 = decryptionShares["decryptionShares"][0];
    auto decryption_share2 = decryptionShares["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 );
1288 1289
}

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
TEST_CASE_METHOD(TestFixture, "Test decryption share for threshold encryption via zmq", "[te-decryption-share-zmq]") {
    auto client = make_shared<ZMQClient>(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem",
                                         "./sgx_data/cert_data/rootCA.key");

    std::string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
    std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0";
    client->importBLSKeyShare(key_str, name);

    // the same key writtn in decimal
    libff::alt_bn128_Fr key = libff::alt_bn128_Fr(
            "6507625568967977077291849236396320012317305261598035438182864059942098934847");

1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    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();

    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() );
kladko's avatar
kladko committed
1327

1328
    REQUIRE( share1 == key * decryption_value1 );
1329

1330 1331
    libff::alt_bn128_G2 share2;
    share2.Z = libff::alt_bn128_Fq2::one();
1332

1333 1334 1335 1336
    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() );
1337

1338
    REQUIRE( share2 == key * decryption_value2 );
1339 1340 1341
}

TEST_CASE_METHOD(TestFixtureZMQSign, "ZMQ-ecdsa", "[zmq-ecdsa]") {
kladko's avatar
kladko committed
1342 1343 1344
    HttpClient htp(RPC_ENDPOINT);
    StubClient c(htp, JSONRPC_CLIENT_V2);

1345
    auto client = make_shared<ZMQClient>(ZMQ_IP, ZMQ_PORT, true, "./sgx_data/cert_data/rootCA.pem",
kladko's avatar
kladko committed
1346
                                         "./sgx_data/cert_data/rootCA.key");
kladko's avatar
kladko committed
1347 1348 1349

    string keyName = "";

kladko's avatar
kladko committed
1350 1351
    PRINT_SRC_LINE
    keyName = genECDSAKeyAPI(c);
kladko's avatar
kladko committed
1352
    int end = 10000000;
kladko's avatar
kladko committed
1353 1354
    string sh = string(SAMPLE_HASH);

kladko's avatar
kladko committed
1355
    std::vector <std::thread> workers;
kladko's avatar
kladko committed
1356

kladko's avatar
kladko committed
1357
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1358

kladko's avatar
kladko committed
1359
    for (int j = 0; j < 2; j++) {
kladko's avatar
kladko committed
1360 1361 1362
        workers.push_back(std::thread([client, sh, keyName, end, j]() {
            CHECK_STATE(client);
            for (int i = (j * 2000); i < (j * 2000) + 1000; i++) {
kladko's avatar
kladko committed
1363

kladko's avatar
kladko committed
1364 1365 1366 1367 1368 1369 1370 1371
                auto hash = sh.substr(0, sh.size() - 8) + to_string(end + i);

                auto sig = client->ecdsaSignMessageHash(16, keyName, hash);
                REQUIRE(sig.size() > 10);
            }

        }));
    };
kladko's avatar
kladko committed
1372

kladko's avatar
kladko committed
1373 1374
    std::for_each(workers.begin(), workers.end(), [](
            std::thread &t) { t.join(); });
kladko's avatar
kladko committed
1375
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1376

kladko's avatar
kladko committed
1377 1378
}

1379
TEST_CASE_METHOD(TestFixtureNoResetFromBackup, "Backup restore", "[backup-restore]") {}