testw.cpp 38.2 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 17
    You should have received a copy of the GNU Affero General Public License
    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"
kladkogex's avatar
kladkogex committed
40
#include "ServerInit.h"
41
#include "DKGCrypto.h"
42
#include "SGXException.h"
kladkogex's avatar
kladkogex committed
43 44
#include "LevelDB.h"
#include "SGXWalletServer.hpp"
45

kladko's avatar
kladko committed
46
#define CATCH_CONFIG_MAIN
47

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

kladko's avatar
kladko committed
58
#include "SGXRegistrationServer.h"
59
#include "SGXWalletServer.h"
kladko's avatar
kladko committed
60
#include "ZMQClient.h"
kladko's avatar
kladko committed
61 62
#include "sgxwallet.h"
#include "TestUtils.h"
kladko's avatar
kladko committed
63 64
#include "testw.h"

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


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

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

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

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

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

99 100 101
class TestFixtureNoResetFromBackup {
public:
    TestFixtureNoResetFromBackup() {
kladko's avatar
kladko committed
102
        setFullOptions(L_INFO, false, true, true);
103
        initAll(L_INFO, false, true, false);
104 105 106
    }

    ~TestFixtureNoResetFromBackup() {
kladko's avatar
q  
kladko committed
107
        exitZMQServer();
108 109 110 111 112
        TestUtils::destroyEnclave();
    }
};


113 114 115 116
class TestFixtureNoReset {
public:
    TestFixtureNoReset() {
        setOptions(L_INFO, false, true);
117
        initAll(L_INFO, false, true, false);
118 119 120
    }

    ~TestFixtureNoReset() {
kladko's avatar
q  
kladko committed
121
        exitZMQServer();
122 123 124 125
        TestUtils::destroyEnclave();
    }
};

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
126 127 128
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
129
    vector <uint8_t> encrPrivKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
130 131 132
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);

kladko's avatar
kladko committed
133
    uint64_t encLen = 0;
kladko's avatar
kladko committed
134
    PRINT_SRC_LINE
kladko's avatar
kladko committed
135
    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen,
kladko's avatar
kladko committed
136 137
                                             pubKeyX.data(),
                                             pubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
138 139 140 141 142 143 144 145
    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
146

kladko's avatar
kladko committed
147
    for (int i = 0; i < 50; i++) {
kladko's avatar
kladko committed
148
        PRINT_SRC_LINE
kladko's avatar
kladko committed
149
        status = trustedEcdsaSign(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen,
150
                                     hex.data(),
kladko's avatar
kladko committed
151 152
                                     signatureR.data(),
                                     signatureS.data(), &signatureV, 16);
153 154
        REQUIRE(status == SGX_SUCCESS);
        REQUIRE(errStatus == SGX_SUCCESS);
kladko's avatar
kladko committed
155
    }
156

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
157 158
}

kladko's avatar
kladko committed
159

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
160 161 162
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
163
    vector <uint8_t> encrPrivKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
164 165
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);
kladko's avatar
kladko committed
166
    uint64_t encLen = 0;
kladko's avatar
kladko committed
167
    PRINT_SRC_LINE
kladko's avatar
kladko committed
168
    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen,
kladko's avatar
kladko committed
169 170
                                             pubKeyX.data(),
                                             pubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
171 172 173 174 175

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

kladko's avatar
kladko committed
176

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
177 178 179
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
180
    vector <uint8_t> encPrivKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
181 182
    vector<char> pubKeyX(BUF_LEN, 0);
    vector<char> pubKeyY(BUF_LEN, 0);
kladko's avatar
kladko committed
183 184

    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
185

kladko's avatar
kladko committed
186
    PRINT_SRC_LINE
kladko's avatar
kladko committed
187
    auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(),
kladko's avatar
kladko committed
188
                                             pubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
189 190 191 192 193 194 195

    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
196
    PRINT_SRC_LINE
kladko's avatar
kladko committed
197
    status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen,
kladko's avatar
kladko committed
198 199
                                         receivedPubKeyX.data(),
                                         receivedPubKeyY.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
200 201 202 203
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);
}

kladko's avatar
kladko committed
204

205
/* Do later
kladko's avatar
kladko committed
206
TEST_CASE_METHOD("BLS key encrypt/decrypt", "[bls-key-encrypt-decrypt]") {
207
    resetDB();
208
    setOptions(false, false, false, true);
209
    initAll(0, false, true);
210 211 212 213 214 215 216

    //init_enclave();

    int errStatus = -1;

    vector<char> errMsg(BUF_LEN, 0);

kladko's avatar
kladko committed
217
    char *encryptedKey = TestUtils::encryptTestKey();
218 219 220 221 222 223 224 225 226 227 228 229
    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
230

231 232 233 234 235 236

}

*/


kladko's avatar
kladko committed
237
string genECDSAKeyAPI(StubClient &_c) {
kladko's avatar
kladko committed
238 239 240 241 242 243 244
    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
245
TEST_CASE_METHOD(TestFixture, "ECDSA key gen API", "[ecdsa-key-gen-api]") {
kladko's avatar
kladko committed
246
    HttpClient client(RPC_ENDPOINT);
kladko's avatar
kladko committed
247
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
248

kladko's avatar
kladko committed
249 250
    for (int i = 0; i <= 20; i++) {
        try {
kladko's avatar
kladko committed
251
            PRINT_SRC_LINE
kladko's avatar
kladko committed
252
            auto keyName = genECDSAKeyAPI(c);
kladko's avatar
kladko committed
253
            PRINT_SRC_LINE
kladko's avatar
kladko committed
254
            Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH);
kladko's avatar
kladko committed
255
            REQUIRE(sig["status"].asInt() == 0);
kladko's avatar
kladko committed
256
            Json::Value getPubKey = c.getPublicECDSAKey(keyName);
kladko's avatar
kladko committed
257 258 259
            REQUIRE(getPubKey["status"].asInt() == 0);
        } catch (JsonRpcException &e) {
            cerr << e.what() << endl;
260 261 262 263
            throw;
        }
    }

kladko's avatar
kladko committed
264 265 266
    auto keyName = genECDSAKeyAPI(c);


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


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

kladko's avatar
kladko committed
287
TEST_CASE_METHOD(TestFixture, "BLS key encrypt", "[bls-key-encrypt]") {
kladko's avatar
kladko committed
288
    auto key = TestUtils::encryptTestKey();
kladko's avatar
kladko committed
289 290 291
    REQUIRE(key != nullptr);
}

svetaro's avatar
svetaro committed
292

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
293
TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") {
kladko's avatar
kladko committed
294
    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
295 296 297
    vector<char> errMsg(BUF_LEN, 0);

    int errStatus = 0;
kladko's avatar
kladko committed
298
    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
299

kladko's avatar
kladko committed
300
    PRINT_SRC_LINE
kladko's avatar
kladko committed
301
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
302 303 304
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
305
    vector<char> secret(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
306 307
    vector<char> errMsg1(BUF_LEN, 0);

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

kladko's avatar
kladko committed
311 312
    REQUIRE(status == SGX_SUCCESS);
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
313
}
314

kladko's avatar
kladko committed
315

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
316
TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares]") {
kladko's avatar
kladko committed
317
    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
318 319 320
    vector<char> errMsg(BUF_LEN, 0);

    int errStatus = 0;
kladko's avatar
kladko committed
321
    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
322 323

    unsigned t = 32, n = 32;
kladko's avatar
kladko committed
324
    PRINT_SRC_LINE
kladko's avatar
kladko committed
325
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
326
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
327
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
328 329 330 331 332

    vector<char> errMsg1(BUF_LEN, 0);

    char colon = ':';
    vector<char> pubShares(10000, 0);
kladko's avatar
kladko committed
333
    PRINT_SRC_LINE
kladko's avatar
kladko committed
334
    status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(),
kladko's avatar
kladko committed
335
                                       encryptedDKGSecret.data(), encLen, pubShares.data(), t, n);
336
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
337
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
338

kladko's avatar
kladko committed
339 340
    vector <string> g2Strings = splitString(pubShares.data(), ',');
    vector <libff::alt_bn128_G2> pubSharesG2;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
341
    for (u_int64_t i = 0; i < g2Strings.size(); i++) {
kladko's avatar
kladko committed
342
        vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
343

kladko's avatar
kladko committed
344
        pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr));
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
345 346 347
    }

    vector<char> secret(BUF_LEN, 0);
kladko's avatar
kladko committed
348
    PRINT_SRC_LINE
kladko's avatar
kladko committed
349
    status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen,
kladko's avatar
kladko committed
350
                                        (uint8_t *) secret.data());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
351
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
352
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
353 354 355

    signatures::Dkg dkgObj(t, n);

kladko's avatar
kladko committed
356 357
    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
358 359 360 361 362 363
    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
364

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
365 366 367 368 369
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
370
    uint64_t encLen = 0;
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
371

kladko's avatar
kladko committed
372
    vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
kladko's avatar
kladko committed
373
    PRINT_SRC_LINE
kladko's avatar
kladko committed
374
    auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
375
    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
376
    REQUIRE(errStatus == SGX_SUCCESS);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
377

kladko's avatar
kladko committed
378
    vector <uint8_t> encrPRDHKey(BUF_LEN, 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
379 380 381 382

    string pub_keyB = SAMPLE_PUBLIC_KEY_B;

    vector<char> s_shareG2(BUF_LEN, 0);
kladko's avatar
kladko committed
383
    PRINT_SRC_LINE
384 385 386
    status = trustedGetEncryptedSecretShare(eid, &errStatus,errMsg.data(),
                                            encryptedDKGSecret.data(), encLen,
                                            encrPRDHKey.data(), &encLen,
kladko's avatar
kladko committed
387 388 389
                                               result.data(),
                                               s_shareG2.data(),
                                               (char *) pub_keyB.data(), 2, 2, 1);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
390 391

    REQUIRE(status == SGX_SUCCESS);
kladko's avatar
kladko committed
392
    REQUIRE(errStatus == SGX_SUCCESS);
svetaro's avatar
svetaro committed
393 394
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
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
    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);
}

svetaro's avatar
svetaro committed
425

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/*
 * ( "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
443

kladko's avatar
kladko committed
444 445 446 447 448


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

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

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

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

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

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

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

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
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);
}

488 489 490
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
491

492
    std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0";
kladko's avatar
kladko committed
493 494
    libff::alt_bn128_Fr key = libff::alt_bn128_Fr(
            "6507625568967977077291849236396320012317305261598035438182864059942098934847");
495
    std::string key_str = TestUtils::stringFromFr(key);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
496 497 498 499 500 501 502 503 504
    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);

505
    REQUIRE(c.deleteBlsKey(name)["deleted"] == true);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
506
}
kladko's avatar
kladko committed
507

508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
TEST_CASE_METHOD(TestFixture, "Import ECDSA Key", "[import-ecdsa-key]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    std::string name = "NEK:abcdef";
    auto response = c.importECDSAKey("6507625568967977077291849236396320012317305261598035438182864059942098934847", name);
    REQUIRE(response["status"] != 0);

    string key_str = "0xe632f7fde2c90a073ec43eaa90dca7b82476bf28815450a11191484934b9c3f";
    response = c.importECDSAKey(key_str, name);
    REQUIRE(response["status"] == 0);

    REQUIRE(c.ecdsaSignMessageHash(16, name, SAMPLE_HASH)["status"] == 0);
}

523 524 525
TEST_CASE_METHOD(TestFixture, "Backup Key", "[backup-key]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
526
    std::ifstream sek_file("sgx_data/sgxwallet_backup_key.txt");
527 528 529 530 531 532 533
    REQUIRE(sek_file.good());

    std::string sek;
    sek_file >> sek;

    REQUIRE(sek.size() == 32);
}
kladko's avatar
kladko committed
534

kladko's avatar
kladko committed
535
TEST_CASE_METHOD(TestFixture, "Get ServerStatus", "[get-server-status]") {
kladko's avatar
kladko committed
536
    HttpClient client(RPC_ENDPOINT);
537
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
538 539
    REQUIRE(c.getServerStatus()["status"] == 0);
}
540

541 542 543
TEST_CASE_METHOD(TestFixture, "Get ServerVersion", "[get-server-version]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
kladko's avatar
kladko committed
544
    REQUIRE(c.getServerVersion()["version"] == SGXWalletServer::getVersion());
545 546
}

kladko's avatar
kladko committed
547

kladko's avatar
kladko committed
548
TEST_CASE_METHOD(TestFixtureHTTPS, "Cert request sign", "[cert-sign]") {
kladko's avatar
kladko committed
549 550 551 552 553 554

    PRINT_SRC_LINE

    REQUIRE_NOTHROW(SGXRegistrationServer::getServer());

    PRINT_SRC_LINE
kladko's avatar
kladko committed
555 556 557 558 559 560 561 562 563

    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
564 565
    PRINT_SRC_LINE

kladko's avatar
kladko committed
566
    auto result = SGXRegistrationServer::getServer()->SignCertificate(ss.str());
kladko's avatar
kladko committed
567 568

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


kladko's avatar
kladko committed
571
    PRINT_SRC_LINE
kladko's avatar
kladko committed
572 573 574
    result = SGXRegistrationServer::getServer()->SignCertificate("Haha");

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

kladko's avatar
kladko committed
577
TEST_CASE_METHOD(TestFixture, "DKG API test", "[dkg-api]") {
kladko's avatar
kladko committed
578
    HttpClient client(RPC_ENDPOINT);
kladko's avatar
kladko committed
579
    StubClient c(client, JSONRPC_CLIENT_V2);
580

kladko's avatar
kladko committed
581 582
    string polyName = SAMPLE_POLY_NAME;

kladko's avatar
kladko committed
583
    PRINT_SRC_LINE
kladko's avatar
kladko committed
584
    Json::Value genPoly = c.generateDKGPoly(polyName, 2);
585
    REQUIRE(genPoly["status"].asInt() == 0);
kladko's avatar
kladko committed
586 587

    Json::Value publicKeys;
kladko's avatar
kladko committed
588 589
    publicKeys.append(SAMPLE_DKG_PUB_KEY_1);
    publicKeys.append(SAMPLE_DKG_PUB_KEY_2);
kladko's avatar
kladko committed
590 591 592 593

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

kladko's avatar
kladko committed
595 596
    Json::Value verifVectWrongName = c.getVerificationVector("poly", 2, 2);
    REQUIRE(verifVectWrongName["status"].asInt() != 0);
597

kladko's avatar
kladko committed
598 599
    Json::Value secretSharesWrongName = c.getSecretShare("poly", publicKeys, 2, 2);
    REQUIRE(secretSharesWrongName["status"].asInt() != 0);
600

kladko's avatar
kladko committed
601 602 603
    // wrong_t
    Json::Value genPolyWrong_t = c.generateDKGPoly(polyName, 33);
    REQUIRE(genPolyWrong_t["status"].asInt() != 0);
604

kladko's avatar
kladko committed
605 606
    Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1, 2);
    REQUIRE(verifVectWrong_t["status"].asInt() != 0);
607

kladko's avatar
kladko committed
608 609
    Json::Value secretSharesWrong_t = c.getSecretShare(polyName, publicKeys, 3, 3);
    REQUIRE(secretSharesWrong_t["status"].asInt() != 0);
610

kladko's avatar
kladko committed
611 612 613
    // wrong_n
    Json::Value verifVectWrong_n = c.getVerificationVector(polyName, 2, 1);
    REQUIRE(verifVectWrong_n["status"].asInt() != 0);
614

kladko's avatar
kladko committed
615
    Json::Value publicKeys1;
kladko's avatar
kladko committed
616
    publicKeys1.append(SAMPLE_DKG_PUB_KEY_1);
kladko's avatar
kladko committed
617 618
    Json::Value secretSharesWrong_n = c.getSecretShare(polyName, publicKeys1, 2, 1);
    REQUIRE(secretSharesWrong_n["status"].asInt() != 0);
619

kladko's avatar
kladko committed
620 621 622
    //wrong number of publicKeys
    Json::Value secretSharesWrongPkeys = c.getSecretShare(polyName, publicKeys, 2, 3);
    REQUIRE(secretSharesWrongPkeys["status"].asInt() != 0);
623

kladko's avatar
kladko committed
624 625
    //wrong verif
    Json::Value Skeys = c.getSecretShare(polyName, publicKeys, 2, 2);
626 627 628
    REQUIRE_NOTHROW(c.getSecretShare(polyName, publicKeys, 2, 2));
    REQUIRE(Skeys == c.getSecretShare(polyName, publicKeys, 2, 2));

kladko's avatar
kladko committed
629
    Json::Value verifVect = c.getVerificationVector(polyName, 2, 2);
630 631 632
    REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2, 2));
    REQUIRE(verifVect == c.getVerificationVector(polyName, 2, 2));

kladko's avatar
kladko committed
633 634 635
    Json::Value verificationWrongSkeys = c.dkgVerification("", "", "", 2, 2, 1);
    REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
}
636

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
TEST_CASE_METHOD(TestFixture, "DKG API V2 test", "[dkg-api-v2]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

    string polyName = SAMPLE_POLY_NAME;

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

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

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

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

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

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

    Json::Value verifVectWrong_t = c.getVerificationVector(polyName, 1, 2);
    REQUIRE(verifVectWrong_t["status"].asInt() != 0);

    Json::Value secretSharesWrong_t = c.getSecretShareV2(polyName, publicKeys, 3, 3);
    REQUIRE(secretSharesWrong_t["status"].asInt() != 0);

    // wrong_n
    Json::Value verifVectWrong_n = c.getVerificationVector(polyName, 2, 1);
    REQUIRE(verifVectWrong_n["status"].asInt() != 0);

    Json::Value publicKeys1;
    publicKeys1.append(SAMPLE_DKG_PUB_KEY_1);
    Json::Value secretSharesWrong_n = c.getSecretShareV2(polyName, publicKeys1, 2, 1);
    REQUIRE(secretSharesWrong_n["status"].asInt() != 0);

    //wrong number of publicKeys
    Json::Value secretSharesWrongPkeys = c.getSecretShareV2(polyName, publicKeys, 2, 3);
    REQUIRE(secretSharesWrongPkeys["status"].asInt() != 0);

    //wrong verif
    Json::Value Skeys = c.getSecretShareV2(polyName, publicKeys, 2, 2);
    REQUIRE_NOTHROW(c.getSecretShare(polyName, publicKeys, 2, 2));
    REQUIRE(Skeys == c.getSecretShare(polyName, publicKeys, 2, 2));

    Json::Value verifVect = c.getVerificationVector(polyName, 2, 2);
    REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2, 2));
    REQUIRE(verifVect == c.getVerificationVector(polyName, 2, 2));

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

kladko's avatar
kladko committed
697
TEST_CASE_METHOD(TestFixture, "PolyExists test", "[dkg-poly-exists]") {
kladko's avatar
kladko committed
698
    HttpClient client(RPC_ENDPOINT);
kladko's avatar
kladko committed
699
    StubClient c(client, JSONRPC_CLIENT_V2);
700

kladko's avatar
kladko committed
701
    string polyName = SAMPLE_POLY_NAME;
kladko's avatar
kladko committed
702
    PRINT_SRC_LINE
kladko's avatar
kladko committed
703
    Json::Value genPoly = c.generateDKGPoly(polyName, 2);
704
    REQUIRE(genPoly["status"] == 0);
705

kladko's avatar
kladko committed
706
    PRINT_SRC_LINE
kladko's avatar
kladko committed
707
    Json::Value polyExists = c.isPolyExists(polyName);
708
    REQUIRE(polyExists["status"] == 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
709
    REQUIRE(polyExists["IsExist"].asBool());
710

kladko's avatar
kladko committed
711
    PRINT_SRC_LINE
kladko's avatar
kladko committed
712
    Json::Value polyDoesNotExist = c.isPolyExists("Vasya");
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
713
    REQUIRE(!polyDoesNotExist["IsExist"].asBool());
714
}
715

kladko's avatar
kladko committed
716
TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
kladko's avatar
kladko committed
717
    HttpClient client(RPC_ENDPOINT);
kladko's avatar
kladko committed
718
    StubClient c(client, JSONRPC_CLIENT_V2);
719

kladko's avatar
kladko committed
720
    int n = 2, t = 2;
kladko's avatar
kladko committed
721
    Json::Value ethKeys[n];
kladko's avatar
kladko committed
722
    Json::Value verifVects[n];
kladko's avatar
kladko committed
723 724 725
    Json::Value pubEthKeys;
    Json::Value secretShares[n];
    Json::Value pubBLSKeys[n];
kladko's avatar
kladko committed
726
    Json::Value blsSigShares[n];
kladko's avatar
kladko committed
727 728
    vector <string> pubShares(n);
    vector <string> polyNames(n);
kladko's avatar
kladko committed
729

kladko's avatar
kladko committed
730 731
    int schainID = TestUtils::randGen();
    int dkgID = TestUtils::randGen();
kladko's avatar
kladko committed
732
    for (uint8_t i = 0; i < n; i++) {
kladko's avatar
kladko committed
733
        PRINT_SRC_LINE
kladko's avatar
kladko committed
734
        ethKeys[i] = c.generateECDSAKey();
735
        REQUIRE(ethKeys[i]["status"] == 0);
kladko's avatar
kladko committed
736
        string polyName =
kladko's avatar
kladko committed
737
                "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
kladko's avatar
kladko committed
738
        REQUIRE(ethKeys[i]["status"] == 0);
739 740 741
        auto response = c.generateDKGPoly(polyName, t);
        REQUIRE(response["status"] == 0);

kladko's avatar
kladko committed
742
        polyNames[i] = polyName;
kladko's avatar
kladko committed
743
        PRINT_SRC_LINE
kladko's avatar
kladko committed
744
        verifVects[i] = c.getVerificationVector(polyName, t, n);
745
        REQUIRE(verifVects[i]["status"] == 0);
746

kladko's avatar
kladko committed
747
        pubEthKeys.append(ethKeys[i]["publicKey"]);
kladko's avatar
kladko committed
748
    }
749

kladko's avatar
kladko committed
750
    for (uint8_t i = 0; i < n; i++) {
kladko's avatar
kladko committed
751
        PRINT_SRC_LINE
kladko's avatar
kladko committed
752
        secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n);
kladko's avatar
kladko committed
753
        REQUIRE(secretShares[i]["status"] == 0);
754

kladko's avatar
kladko committed
755 756
        for (uint8_t k = 0; k < t; k++)
            for (uint8_t j = 0; j < 4; j++) {
kladko's avatar
kladko committed
757
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
kladko's avatar
kladko committed
758
                pubShares[i] += TestUtils::convertDecToHex(pubShare);
kladko's avatar
kladko committed
759
            }
760 761
    }

kladko's avatar
kladko committed
762
    int k = 0;
kladko's avatar
kladko committed
763
    vector <string> secShares(n);
kladko's avatar
kladko committed
764 765 766 767

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
kladko's avatar
kladko committed
768
            secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
kladko's avatar
kladko committed
769
            PRINT_SRC_LINE
kladko's avatar
kladko committed
770
            Json::Value verif = c.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
771
            REQUIRE(verif["status"] == 0);
kladko's avatar
kladko committed
772 773 774 775 776
            bool res = verif["result"].asBool();
            k++;
            REQUIRE(res);
        }

777
    Json::Value complaintResponse = c.complaintResponse(polyNames[1], t, n, 0);
kladko's avatar
kladko committed
778 779
    REQUIRE(complaintResponse["status"] == 0);

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

784
    vector<char> message (65, 0);
785 786 787 788 789 790 791 792 793 794 795 796 797 798

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

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

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

    REQUIRE(xorDecryptDH(common_key, encr_sshare_check, message) == 0);

    mpz_t hex_share;
    mpz_init(hex_share);
799
    mpz_set_str(hex_share, message.data(), 16);
800 801 802 803 804 805 806 807 808

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

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    Json::Value verificationVectorMult = complaintResponse["verificationVectorMult"];

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

kladko's avatar
kladko committed
824
    BLSSigShareSet sigShareSet(t, n);
825

kladko's avatar
kladko committed
826
    string hash = SAMPLE_HASH;
827

828
    auto hash_arr = make_shared < array < uint8_t, 32 > >();
kladko's avatar
kladko committed
829

kladko's avatar
kladko committed
830
    uint64_t binLen;
kladko's avatar
kladko committed
831

832
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
833
        throw SGXException(TEST_INVALID_HEX, "Invalid hash");
kladko's avatar
kladko committed
834
    }
835

kladko's avatar
kladko committed
836
    map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
kladko's avatar
kladko committed
837 838

    for (int i = 0; i < t; i++) {
kladko's avatar
kladko committed
839 840
        string endName = polyNames[i].substr(4);
        string blsName = "BLS_KEY" + polyNames[i].substr(4);
kladko's avatar
kladko committed
841 842
        auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
                                              n);
843
        REQUIRE(response["status"] == 0);
844

kladko's avatar
kladko committed
845
        PRINT_SRC_LINE
846
        pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
kladko's avatar
kladko committed
847
        REQUIRE(pubBLSKeys[i]["status"] == 0);
848

kladko's avatar
kladko committed
849
        string hash = SAMPLE_HASH;
850
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
kladko's avatar
kladko committed
851
        REQUIRE(blsSigShares[i]["status"] == 0);
852

kladko's avatar
kladko committed
853
        shared_ptr <string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
kladko's avatar
kladko committed
854 855 856
        BLSSigShare sig(sig_share_ptr, i + 1, t, n);
        sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));

kladko's avatar
kladko committed
857
        vector <string> pubKey_vect;
kladko's avatar
kladko committed
858 859 860
        for (uint8_t j = 0; j < 4; j++) {
            pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
        }
kladko's avatar
kladko committed
861
        BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKey_vect), t, n);
kladko's avatar
kladko committed
862
        PRINT_SRC_LINE
kladko's avatar
kladko committed
863 864
        REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));

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

kladko's avatar
kladko committed
868 869 870 871
    shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
    BLSPublicKey
    common_public(make_shared < map < size_t, shared_ptr < BLSPublicKeyShare >>>(coeffs_pkeys_map), t,
            n);
kladko's avatar
kladko committed
872
    REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
873
}
874

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 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
TEST_CASE_METHOD(TestFixture, "AES_DKG V2 test", "[aes-dkg-v2]") {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

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

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

        polyNames[i] = polyName;
        PRINT_SRC_LINE
        verifVects[i] = c.getVerificationVector(polyName, t, n);
        REQUIRE(verifVects[i]["status"] == 0);

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

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

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

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

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
            secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
            PRINT_SRC_LINE
            Json::Value verif = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
            REQUIRE(verif["status"] == 0);
            bool res = verif["result"].asBool();
            k++;
            REQUIRE(res);
        }

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

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

    vector<char> message (65, 0);

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

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

951 952 953 954 955 956 957
    auto hashed_key = cryptlite::sha256::hash_hex(string(common_key, 64));

    SAFE_CHAR_BUF(derived_key, 33)

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

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
958 959 960
    SAFE_CHAR_BUF(encr_sshare_check, BUF_LEN)
    strncpy(encr_sshare_check, secretShare.c_str(), ECDSA_SKEY_LEN - 1);

961
    REQUIRE(xorDecryptDHV2(derived_key, encr_sshare_check, message) == 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
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

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

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

    mpz_clear(hex_share);

    REQUIRE( convertG2ToString(decrypted_share_G2) == shareG2 );

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

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

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

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

    uint64_t binLen;

    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
999
        throw SGXException(TEST_INVALID_HEX, "Invalid hash");
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1000 1001 1002 1003 1004 1005 1006
    }

    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);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1007
        auto response = c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
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
                                              n);
        REQUIRE(response["status"] == 0);

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

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

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

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

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

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

kladko's avatar
kladko committed
1040
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
1041
    int errStatus = 0;
1042
    vector<char> errMsg(BUF_LEN, 0);
kladko's avatar
kladko committed
1043
    uint64_t encLen;
kladko's avatar
kladko committed
1044
    string key = SAMPLE_AES_KEY;
kladko's avatar
kladko committed
1045
    vector <uint8_t> encrypted_key(BUF_LEN, 0);
svetaro's avatar
svetaro committed
1046

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

kladko's avatar
kladko committed
1050
    REQUIRE(status == 0);
kladko's avatar
kladko committed
1051
    REQUIRE(errStatus == 0);
1052

kladko's avatar
kladko committed
1053
    vector<char> decr_key(BUF_LEN, 0);
kladko's avatar
kladko committed
1054
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1055
    status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data());
svetaro's avatar
svetaro committed
1056

kladko's avatar
kladko committed
1057
    REQUIRE(status == 0);
1058
    REQUIRE(key.compare(decr_key.data()) == 0);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1059
    REQUIRE(errStatus == 0);
1060 1061
}

kladko's avatar
kladko committed
1062

kladko's avatar
kladko committed
1063
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypto]") {
kladko's avatar
kladko committed
1064
    vector <thread> threads;
kladko's avatar
kladko committed
1065
    int num_threads = 16;
kladko's avatar
kladko committed
1066
    for (int i = 0; i < num_threads; i++) {
kladko's avatar
kladko committed
1067
        threads.push_back(thread(TestUtils::sendRPCRequest));
kladko's avatar
kladko committed
1068 1069 1070 1071 1072 1073
    }

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

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1075 1076 1077 1078
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
1079
        threads.push_back(thread(TestUtils::sendRPCRequestV2));
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
1080 1081 1082 1083 1084 1085 1086
    }

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

1087
TEST_CASE_METHOD(TestFixture, "First run", "[first-run]") {
kladko's avatar
kladko committed
1088 1089 1090 1091 1092 1093

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

kladko's avatar
kladko committed
1097 1098 1099 1100 1101 1102 1103 1104
        PRINT_SRC_LINE
    } catch (JsonRpcException & e)
    {
        cerr << e.what() << endl;
        throw;
    }


1105 1106 1107
}

TEST_CASE_METHOD(TestFixtureNoReset, "Second run", "[second-run]") {
kladko's avatar
kladko committed
1108 1109 1110 1111 1112

    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);
    try {
        PRINT_SRC_LINE
kladko's avatar
kladko committed
1113 1114 1115 1116
        string keyName;
        ifstream namefile("/tmp/keyname");
        getline(namefile, keyName);

kladko's avatar
kladko committed
1117 1118 1119 1120 1121 1122 1123 1124
        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;
    }
1125
}
1126

kladko's avatar
kladko committed
1127

kladko's avatar
kladko committed
1128

kladko's avatar
kladko committed
1129
TEST_CASE_METHOD(TestFixture, "ZMQ-ecdsa", "[zmq-ecdsa]") {
kladko's avatar
kladko committed
1130 1131 1132 1133 1134 1135

    HttpClient htp(RPC_ENDPOINT);
    StubClient c(htp, JSONRPC_CLIENT_V2);

    string ip = ZMQ_IP;

kladko's avatar
kladko committed
1136
    auto client = make_shared<ZMQClient>(ip, ZMQ_PORT);
kladko's avatar
kladko committed
1137 1138 1139

    string keyName = "";

kladko's avatar
kladko committed
1140 1141
    PRINT_SRC_LINE
    keyName = genECDSAKeyAPI(c);
kladko's avatar
kladko committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151



    int end = 100000;
    string sh = string(SAMPLE_HASH);





kladko's avatar
kladko committed
1152
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1153 1154 1155 1156 1157
    for (int i = 1; i < 10000; i++) {

        auto hash = sh.substr(0, sh.size() - 6) + to_string(end + i);

        auto sig = client->ecdsaSignMessageHash(16, keyName, hash);
kladko's avatar
kladko committed
1158
        REQUIRE(sig.size() > 10);
kladko's avatar
kladko committed
1159
    }
kladko's avatar
kladko committed
1160

kladko's avatar
kladko committed
1161
    PRINT_SRC_LINE
kladko's avatar
kladko committed
1162

kladko's avatar
kladko committed
1163 1164 1165
}


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