TestUtils.cpp 26.7 KB
Newer Older
kladko's avatar
kladko committed
1
/*
2
    Copyright (C) 2019-Present SKALE Labs
kladko's avatar
kladko committed
3

4
    This file is part of sgxwallet.
kladko's avatar
kladko 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.
kladko's avatar
kladko committed
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.
kladko's avatar
kladko committed
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/>.
kladko's avatar
kladko committed
18

19 20 21
    @file TestUtils.cpp
    @author Stan Kladko
    @date 2020
kladko's avatar
kladko committed
22
*/
23

kladko's avatar
kladko committed
24 25 26 27 28
#include <dkg/dkg.h>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <dkg/dkg.h>
#include "sgxwallet_common.h"
29
#include "third_party/intel/create_enclave.h"
kladko's avatar
kladko committed
30
#include "secure_enclave_u.h"
31
#include "third_party/intel/sgx_detect.h"
32
#include "third_party/spdlog/spdlog.h"
kladko's avatar
kladko committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include <gmp.h>
#include <sgx_urts.h>
#include <stdio.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <sgx_tcrypto.h>

#include "BLSCrypto.h"
#include "ServerInit.h"
#include "DKGCrypto.h"
#include "SGXException.h"
#include "LevelDB.h"
#include "SGXWalletServer.hpp"

#include "catch.hpp"
#include "BLSSigShare.h"
#include "BLSSigShareSet.h"
#include "BLSPublicKeyShare.h"
#include "BLSPublicKey.h"
#include "SEKManager.h"
#include <thread>
#include "common.h"
#include "stubclient.h"
#include "SGXRegistrationServer.h"
#include "SGXWalletServer.h"
#include "sgxwallet.h"
#include "testw.h"
#include "TestUtils.h"

using namespace jsonrpc;
using namespace std;

default_random_engine TestUtils::randGen((unsigned int) time(0));

string TestUtils::stringFromFr(libff::alt_bn128_Fr &el) {
    mpz_t t;
    mpz_init(t);
    el.as_bigint().to_mpz(t);
    char arr[mpz_sizeinbase(t, 10) + 2];
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
71
    mpz_get_str(arr, 10, t);
kladko's avatar
kladko committed
72 73
    mpz_clear(t);

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
74
    return string(arr);
kladko's avatar
kladko committed
75 76 77 78 79 80 81 82 83 84 85 86
}


string TestUtils::convertDecToHex(string dec, int numBytes) {
    mpz_t num;
    mpz_init(num);
    mpz_set_str(num, dec.c_str(), 10);
    vector<char> tmp(mpz_sizeinbase(num, 16) + 2, 0);
    char *hex = mpz_get_str(tmp.data(), 16, num);
    string result = hex;
    int n_zeroes = numBytes * 2 - result.length();
    result.insert(0, n_zeroes, '0');
kladko's avatar
kladko committed
87
    mpz_clear(num);
kladko's avatar
kladko committed
88 89 90 91 92 93 94 95 96 97 98
    return result;
}

void TestUtils::resetDB() {
    CHECK_STATE(system("bash -c \"rm -rf " SGXDATA_FOLDER "* \"") == 0);
}

shared_ptr <string> TestUtils::encryptTestKey() {
    const char *key = TEST_BLS_KEY_SHARE;
    int errStatus = -1;
    vector<char> errMsg(BUF_LEN, 0);;
99
    string encryptedKeyHex = encryptBLSKeyShare2Hex(&errStatus, errMsg.data(), key);
kladko's avatar
kladko committed
100

101
    CHECK_STATE(!encryptedKeyHex.empty());
kladko's avatar
kladko committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    CHECK_STATE(errStatus == 0);

    return make_shared<string>(encryptedKeyHex);
}

vector <libff::alt_bn128_Fr> TestUtils::splitStringToFr(const char *coeffs, const char symbol) {
    string str(coeffs);
    string delim;
    delim.push_back(symbol);
    vector <libff::alt_bn128_Fr> tokens;
    size_t prev = 0, pos = 0;
    do {
        pos = str.find(delim, prev);
        if (pos == string::npos) pos = str.length();
        string token = str.substr(prev, pos - prev);
        if (!token.empty()) {
            libff::alt_bn128_Fr coeff(token.c_str());
            tokens.push_back(coeff);
        }
        prev = pos + delim.length();
    } while (pos < str.length() && prev < str.length());

    return tokens;
}

vector <string> TestUtils::splitStringTest(const char *coeffs, const char symbol) {
    string str(coeffs);
    string delim;
    delim.push_back(symbol);
    vector <string> g2Strings;
    size_t prev = 0, pos = 0;
    do {
        pos = str.find(delim, prev);
        if (pos == string::npos) pos = str.length();
        string token = str.substr(prev, pos - prev);
        if (!token.empty()) {
            string coeff(token.c_str());
            g2Strings.push_back(coeff);
        }
        prev = pos + delim.length();
    } while (pos < str.length() && prev < str.length());

    return g2Strings;
}

libff::alt_bn128_G2 TestUtils::vectStringToG2(const vector <string> &G2_str_vect) {
    libff::alt_bn128_G2 coeff = libff::alt_bn128_G2::zero();
    coeff.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str());
    coeff.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str());
    coeff.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str());
    coeff.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str());
    coeff.Z.c0 = libff::alt_bn128_Fq::one();
    coeff.Z.c1 = libff::alt_bn128_Fq::zero();

    return coeff;
}

void TestUtils::sendRPCRequest() {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

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

kladko's avatar
kladko committed
173 174 175 176
    static atomic<int> counter(1);

    int schainID = counter.fetch_add(1);
    int dkgID = counter.fetch_add(1);
kladko's avatar
kladko committed
177 178 179 180 181

    int testCount = 1;

    if (getenv("NIGHTLY_TESTS")) {
        testCount = 10;
kladko's avatar
kladko committed
182
    }
kladko's avatar
kladko committed
183

kladko's avatar
kladko committed
184
    for (uint8_t i = 0; i < n; i++) {
kladko's avatar
kladko committed
185
        usleep(100000);
kladko's avatar
kladko committed
186
        ethKeys[i] = c.generateECDSAKey();
kladko's avatar
kladko committed
187

kladko's avatar
kladko committed
188
        for (int i2 = 0; i2 < testCount; i2++) {
kladko's avatar
kladko committed
189 190 191 192 193 194
            auto keyName = ethKeys[i]["keyName"].asString();
            Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH);
            CHECK_STATE(sig["status"].asInt() == 0);
        }


kladko's avatar
kladko committed
195 196 197 198 199 200
        CHECK_STATE(ethKeys[i]["status"] == 0);
        string polyName =
                "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
        auto response = c.generateDKGPoly(polyName, t);
        CHECK_STATE(response["status"] == 0);
        polyNames[i] = polyName;
kladko's avatar
kladko committed
201

kladko's avatar
kladko committed
202
        for (int i3 = 0; i3 <= testCount; i3++) {
kladko's avatar
kladko committed
203 204 205
            verifVects[i] = c.getVerificationVector(polyName, t, n);
            CHECK_STATE(verifVects[i]["status"] == 0);
        }
kladko's avatar
kladko committed
206 207 208 209 210

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

    for (uint8_t i = 0; i < n; i++) {
kladko's avatar
kladko committed
211
        usleep(100000);
kladko's avatar
kladko committed
212
        for (int i4 = 0; i4 <= testCount; i4++) {
kladko's avatar
kladko committed
213 214
            secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n);
        }
kladko's avatar
kladko committed
215 216
        for (uint8_t k = 0; k < t; k++) {
            for (uint8_t j = 0; j < 4; j++) {
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
217
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
kladko's avatar
kladko committed
218 219 220 221 222 223 224 225 226 227 228
                pubShares[i] += convertDecToHex(pubShare);
            }
        }
    }

    vector <string> secShares(n);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
            secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
kladko's avatar
kladko committed
229
            usleep(100000);
kladko's avatar
kladko committed
230
            for (int i5 = 0; i5 <= testCount; i5++) {
kladko's avatar
kladko committed
231 232 233 234
                Json::Value verif = c.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n,
                                                      j);
                CHECK_STATE(verif["status"] == 0);
            }
kladko's avatar
kladko committed
235 236 237 238 239 240 241 242
        }

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

    auto hash_arr = make_shared < array < uint8_t, 32 >> ();
    uint64_t binLen;
243
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
244 245 246 247 248
        throw SGXException(INVALID_HEX, "Invalid hash");
    }

    map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
249 250 251 252 253
    Json::Value publicShares;
    for (int i = 0; i < n; ++i) {
        publicShares["publicShares"][i] = pubShares[i];
    }

kladko's avatar
kladko committed
254 255 256

    Json::Value blsPublicKeys;

kladko's avatar
kladko committed
257
    for (int i6 = 0; i6 <= testCount; i6++) {
kladko's avatar
kladko committed
258
        blsPublicKeys = c.calculateAllBLSPublicKeys(publicShares, t, n);
kladko's avatar
kladko committed
259 260
        CHECK_STATE(blsPublicKeys["status"] == 0);
    }
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
261

kladko's avatar
kladko committed
262 263 264 265 266
    for (int i = 0; i < t; i++) {
        string endName = polyNames[i].substr(4);
        string blsName = "BLS_KEY" + polyNames[i].substr(4);
        string secretShare = secretShares[i]["secretShare"].asString();

kladko's avatar
kladko committed
267 268 269

        auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i],
                                                  t, n);
kladko's avatar
kladko committed
270
        CHECK_STATE(response["status"] == 0);
kladko's avatar
kladko committed
271

kladko's avatar
kladko committed
272
        for (int i7 = 0; i7 <= testCount; i7++) {
kladko's avatar
kladko committed
273 274
            pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
        }
kladko's avatar
kladko committed
275 276
        CHECK_STATE(pubBLSKeys[i]["status"] == 0);

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
277 278 279 280 281 282 283
        libff::alt_bn128_G2 publicKey(libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][0].asCString()),
                                      libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][1].asCString())),
                                      libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][2].asCString()),
                                      libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][3].asCString())),
                                      libff::alt_bn128_Fq2::one());

        string public_key_str = convertG2ToString(publicKey);
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
284

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
285
        CHECK_STATE(public_key_str == blsPublicKeys["publicKeys"][i].asString());
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
286

kladko's avatar
kladko committed
287
        string hash = SAMPLE_HASH;
288
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
kladko's avatar
kladko committed
289 290 291 292 293 294 295
        CHECK_STATE(blsSigShares[i]["status"] == 0);

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

296
    sigShareSet.merge();
kladko's avatar
kladko committed
297 298
}

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
void TestUtils::sendRPCRequestV2() {
    HttpClient client(RPC_ENDPOINT);
    StubClient c(client, JSONRPC_CLIENT_V2);

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

    static atomic<int> counter(1);

    int schainID = counter.fetch_add(1);
    int dkgID = counter.fetch_add(1);
    for (uint8_t i = 0; i < n; i++) {
        ethKeys[i] = c.generateECDSAKey();
        CHECK_STATE(ethKeys[i]["status"] == 0);
        string polyName =
                "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);
        auto response = c.generateDKGPoly(polyName, t);
        CHECK_STATE(response["status"] == 0);
        polyNames[i] = polyName;
        verifVects[i] = c.getVerificationVector(polyName, t, n);
        CHECK_STATE(verifVects[i]["status"] == 0);

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

    for (uint8_t i = 0; i < n; i++) {
        secretShares[i] = c.getSecretShareV2(polyNames[i], pubEthKeys, t, n);
        for (uint8_t k = 0; k < t; k++) {
            for (uint8_t j = 0; j < 4; j++) {
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
                pubShares[i] += convertDecToHex(pubShare);
            }
        }
    }

    vector <string> secShares(n);

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

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

    auto hash_arr = make_shared < array < uint8_t, 32 >> ();
    uint64_t binLen;
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
        throw SGXException(INVALID_HEX, "Invalid hash");
    }

    map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;

    Json::Value publicShares;
    for (int i = 0; i < n; ++i) {
        publicShares["publicShares"][i] = pubShares[i];
    }

    Json::Value blsPublicKeys = c.calculateAllBLSPublicKeys(publicShares, t, n);
    CHECK_STATE(blsPublicKeys["status"] == 0);

    for (int i = 0; i < t; i++) {
        string endName = polyNames[i].substr(4);
        string blsName = "BLS_KEY" + polyNames[i].substr(4);
        string secretShare = secretShares[i]["secretShare"].asString();

        auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t, n);
        CHECK_STATE(response["status"] == 0);
        pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
        CHECK_STATE(pubBLSKeys[i]["status"] == 0);

        libff::alt_bn128_G2 publicKey(libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][0].asCString()),
                                      libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][1].asCString())),
                                      libff::alt_bn128_Fq2(libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][2].asCString()),
                                      libff::alt_bn128_Fq(pubBLSKeys[i]["blsPublicKeyShare"][3].asCString())),
                                      libff::alt_bn128_Fq2::one());

        string public_key_str = convertG2ToString(publicKey);

        CHECK_STATE(public_key_str == blsPublicKeys["publicKeys"][i].asString());

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

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

    sigShareSet.merge();
}

kladko's avatar
kladko committed
403 404 405 406 407 408 409
void TestUtils::destroyEnclave() {
    if (eid != 0) {
        sgx_destroy_enclave(eid);
        eid = 0;
    }
}

kladko's avatar
kladko committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
void TestUtils::doDKG(StubClient &c, int n, int t,
           vector<string>& _ecdsaKeyNames, vector<string>& _blsKeyNames,
           int schainID, int dkgID) {
    Json::Value ethKeys[n];
    Json::Value verifVects[n];
    Json::Value pubEthKeys;
    Json::Value secretShares[n];
    Json::Value pubBLSKeys[n];
    Json::Value blsSigShares[n];
    vector<string> pubShares(n);
    vector<string> polyNames(n);

    _ecdsaKeyNames.clear();
    _blsKeyNames.clear();

    for (uint8_t i = 0; i < n; i++) {
        ethKeys[i] = c.generateECDSAKey();

        CHECK_STATE(ethKeys[i]["status"] == 0);

        auto keyName = ethKeys[i]["keyName"].asString();
        CHECK_STATE(keyName.size() == ECDSA_KEY_NAME_SIZE);

        _ecdsaKeyNames.push_back(keyName);

        string polyName =
                "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);

        Json::Value response = c.generateDKGPoly(polyName, t);
        CHECK_STATE(response["status"] == 0);
        polyNames[i] = polyName;
        verifVects[i] = c.getVerificationVector(polyName, t, n);
        CHECK_STATE(verifVects[i]["status"] == 0);
        pubEthKeys.append(ethKeys[i]["publicKey"]);
    }

    for (uint8_t i = 0; i < n; i++) {
        secretShares[i] = c.getSecretShare(polyNames[i], pubEthKeys, t, n);
        CHECK_STATE(secretShares[i]["status"] == 0);
        for (uint8_t k = 0; k < t; k++) {
            for (uint8_t j = 0; j < 4; j++) {
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
                CHECK_STATE(pubShare.length() > 60);
                pubShares[i] += TestUtils::convertDecToHex(pubShare);
            }
        }
    }

    int k = 0;

    vector<string> secShares(n);

    vector<string> pSharesBad(pubShares);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
            secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
            Json::Value response = c.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n,
                                                     j);
            CHECK_STATE(response["status"] == 0);

            bool res = response["result"].asBool();
            CHECK_STATE(res);

            k++;

            pSharesBad[i][0] = 'q';
            Json::Value wrongVerif = c.dkgVerification(pSharesBad[i], ethKeys[j]["keyName"].asString(), secretShare, t,
                                                       n, j);
            res = wrongVerif["result"].asBool();
            CHECK_STATE(!res);
        }

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

    auto hash_arr = make_shared<array<uint8_t, 32 >>();
    uint64_t binLen;
490
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
491 492 493 494 495
        throw SGXException(INVALID_HEX, "Invalid hash");
    }

    map<size_t, shared_ptr<BLSPublicKeyShare>> pubKeyShares;

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    for (int i = 0; i < n; i++) {
        string endName = polyNames[i].substr(4);
        string blsName = "BLS_KEY" + polyNames[i].substr(4);
        _blsKeyNames.push_back(blsName);
        string secretShare = secretShares[i]["secretShare"].asString();

        auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
                                              n);
        CHECK_STATE(response["status"] == 0);
        pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
        CHECK_STATE(pubBLSKeys[i]["status"] == 0);
    }

    for (int i = 0; i < t; i++) {
        vector<string> pubKeyVect;
        for (uint8_t j = 0; j < 4; j++) {
            pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
        }
        BLSPublicKeyShare pubKey(make_shared<vector<string >>(pubKeyVect), t, n);

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

    // create pub key

    BLSPublicKey blsPublicKey(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare >>>(pubKeyShares), t,
                              n);

    // sign verify a sample sig

    for (int i = 0; i < t; i++) {

        string blsName = "BLS_KEY" + polyNames[i].substr(4);
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
        CHECK_STATE(blsSigShares[i]["status"] == 0);
        shared_ptr<string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
        BLSSigShare sig(sig_share_ptr, i + 1, t, n);
        sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));

        auto pubKey = pubKeyShares[i+1];

        CHECK_STATE(pubKey->VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
    }

    shared_ptr<BLSSignature> commonSig = sigShareSet.merge();

    CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig, t, n));

    for (auto&& i : _ecdsaKeyNames)
        cerr << i << endl;

    for (auto&& i : _blsKeyNames)
        cerr << i << endl;
}

void TestUtils::doDKGV2(StubClient &c, int n, int t,
           vector<string>& _ecdsaKeyNames, vector<string>& _blsKeyNames,
           int schainID, int dkgID) {
    Json::Value ethKeys[n];
    Json::Value verifVects[n];
    Json::Value pubEthKeys;
    Json::Value secretShares[n];
    Json::Value pubBLSKeys[n];
    Json::Value blsSigShares[n];
    vector<string> pubShares(n);
    vector<string> polyNames(n);

    _ecdsaKeyNames.clear();
    _blsKeyNames.clear();

    for (uint8_t i = 0; i < n; i++) {
        ethKeys[i] = c.generateECDSAKey();

        CHECK_STATE(ethKeys[i]["status"] == 0);

        auto keyName = ethKeys[i]["keyName"].asString();
        CHECK_STATE(keyName.size() == ECDSA_KEY_NAME_SIZE);

        _ecdsaKeyNames.push_back(keyName);

        string polyName =
                "POLY:SCHAIN_ID:" + to_string(schainID) + ":NODE_ID:" + to_string(i) + ":DKG_ID:" + to_string(dkgID);

        Json::Value response = c.generateDKGPoly(polyName, t);
        CHECK_STATE(response["status"] == 0);
        polyNames[i] = polyName;
        verifVects[i] = c.getVerificationVector(polyName, t, n);
        CHECK_STATE(verifVects[i]["status"] == 0);
        pubEthKeys.append(ethKeys[i]["publicKey"]);
    }

    for (uint8_t i = 0; i < n; i++) {
        secretShares[i] = c.getSecretShareV2(polyNames[i], pubEthKeys, t, n);
        CHECK_STATE(secretShares[i]["status"] == 0);
        for (uint8_t k = 0; k < t; k++) {
            for (uint8_t j = 0; j < 4; j++) {
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
                CHECK_STATE(pubShare.length() > 60);
                pubShares[i] += TestUtils::convertDecToHex(pubShare);
            }
        }
    }

    int k = 0;

    vector<string> secShares(n);

    vector<string> pSharesBad(pubShares);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            string secretShare = secretShares[i]["secretShare"].asString().substr(192 * j, 192);
            secShares[i] += secretShares[j]["secretShare"].asString().substr(192 * i, 192);
            Json::Value response = c.dkgVerificationV2(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n,
                                                     j);
            CHECK_STATE(response["status"] == 0);

            bool res = response["result"].asBool();
            CHECK_STATE(res);

            k++;

            pSharesBad[i][0] = 'q';
            Json::Value wrongVerif = c.dkgVerificationV2(pSharesBad[i], ethKeys[j]["keyName"].asString(), secretShare, t,
                                                       n, j);
            res = wrongVerif["result"].asBool();
            CHECK_STATE(!res);
        }

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

    auto hash_arr = make_shared<array<uint8_t, 32 >>();
    uint64_t binLen;
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
        throw SGXException(INVALID_HEX, "Invalid hash");
    }

    map<size_t, shared_ptr<BLSPublicKeyShare>> pubKeyShares;

kladko's avatar
kladko 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
    for (int i = 0; i < n; i++) {
        string endName = polyNames[i].substr(4);
        string blsName = "BLS_KEY" + polyNames[i].substr(4);
        _blsKeyNames.push_back(blsName);
        string secretShare = secretShares[i]["secretShare"].asString();

        auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
                                              n);
        CHECK_STATE(response["status"] == 0);
        pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
        CHECK_STATE(pubBLSKeys[i]["status"] == 0);
    }

    for (int i = 0; i < t; i++) {
        vector<string> pubKeyVect;
        for (uint8_t j = 0; j < 4; j++) {
            pubKeyVect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
        }
        BLSPublicKeyShare pubKey(make_shared<vector<string >>(pubKeyVect), t, n);

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

    // create pub key

    BLSPublicKey blsPublicKey(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare >>>(pubKeyShares), t,
                              n);

    // sign verify a sample sig

    for (int i = 0; i < t; i++) {

        string blsName = "BLS_KEY" + polyNames[i].substr(4);
670
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
kladko's avatar
kladko committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
        CHECK_STATE(blsSigShares[i]["status"] == 0);
        shared_ptr<string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
        BLSSigShare sig(sig_share_ptr, i + 1, t, n);
        sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));

        auto pubKey = pubKeyShares[i+1];

        CHECK_STATE(pubKey->VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
    }

    shared_ptr<BLSSignature> commonSig = sigShareSet.merge();

    CHECK_STATE(blsPublicKey.VerifySigWithHelper(hash_arr, commonSig, t, n));

    for (auto&& i : _ecdsaKeyNames)
        cerr << i << endl;

    for (auto&& i : _blsKeyNames)
        cerr << i << endl;
690
}
691 692 693 694 695 696 697 698 699 700 701 702 703 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 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771

int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key) {

    int ret = -1;

    SAFE_CHAR_BUF(pb_keyB_x, 65);
    SAFE_CHAR_BUF(pb_keyB_y, 65);

    mpz_t skey;
    mpz_init(skey);
    point pub_keyB = point_init();
    point session_key = point_init();

    pb_keyB_x[64] = 0;
    strncpy(pb_keyB_x, sshare, 64);
    strncpy(pb_keyB_y, sshare + 64, 64);
    pb_keyB_y[64] = 0;


    if (!common_key) {
        mpz_clear(skey);
        point_clear(pub_keyB);
        point_clear(session_key);

        return  ret;
    }

    common_key[0] = 0;

    if (!skey_str) {
        mpz_clear(skey);
        point_clear(pub_keyB);
        point_clear(session_key);

        return  ret;
    }

    if (!sshare) {
        mpz_clear(skey);
        point_clear(pub_keyB);
        point_clear(session_key);

        return  ret;
    }

    if (mpz_set_str(skey, skey_str, 16) == -1) {
        mpz_clear(skey);
        point_clear(pub_keyB);
        point_clear(session_key);

        return  ret;
    }

    domain_parameters curve;
    curve = domain_parameters_init();
    domain_parameters_load_curve(curve, secp256k1);

    if (point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y) != 0) {
        return ret;
    }

    point_multiplication(session_key, skey, pub_keyB, curve);

    SAFE_CHAR_BUF(arr_x, BUF_LEN);

    mpz_get_str(arr_x, 16, session_key->x);
    int n_zeroes = 64 - strlen(arr_x);
    for (int i = 0; i < n_zeroes; i++) {
        common_key[i] = '0';
    }
    strncpy(common_key + n_zeroes, arr_x, strlen(arr_x));

    ret = 0;

    mpz_clear(skey);
    point_clear(pub_keyB);
    point_clear(session_key);

    return  ret;
}

772
int xorDecryptDH(char *key, const char *cypher, vector<char>& message) {
773 774 775 776 777 778 779 780 781 782 783

    int ret = -1;

    if (!cypher) {
        return ret;
    }

    if (!key) {
        return ret;
    }

784
    if (!message.data()) {
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
        return ret;
    }

    SAFE_CHAR_BUF(msg_bin,33)

    SAFE_CHAR_BUF(key_bin,33)

    uint64_t key_length;
    if (!hex2carray(key, &key_length, (uint8_t*) key_bin, 33)) {
        return ret;
    }

    uint64_t cypher_length;

    SAFE_CHAR_BUF(cypher_bin, 33);
    if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) {
        return ret;
    }

    for (int i = 0; i < 32; i++) {
        msg_bin[i] = cypher_bin[i] ^ key_bin[i];
    }

808
    message = carray2Hex((unsigned char*) msg_bin, 32);
809 810 811 812 813

    ret = 0;

    return ret;
}
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849

int xorDecryptDHV2(char *key, const char *cypher, vector<char>& message) {

    int ret = -1;

    if (!cypher) {
        return ret;
    }

    if (!key) {
        return ret;
    }

    if (!message.data()) {
        return ret;
    }

    SAFE_CHAR_BUF(msg_bin,33)

    uint64_t cypher_length;

    SAFE_CHAR_BUF(cypher_bin, 33);
    if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) {
        return ret;
    }

    for (int i = 0; i < 32; i++) {
        msg_bin[i] = cypher_bin[i] ^ (uint8_t)key[i];
    }

    message = carray2Hex((unsigned char*) msg_bin, 32);

    ret = 0;

    return ret;
}