TestUtils.cpp 16.1 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 87 88 89 90 91 92 93 94 95 96 97 98 99 100
}


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

    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);;
101
    string encryptedKeyHex = encryptBLSKeyShare2Hex(&errStatus, errMsg.data(), key);
kladko's avatar
kladko committed
102

103
    CHECK_STATE(!encryptedKeyHex.empty());
kladko's avatar
kladko committed
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 173 174
    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
175 176 177 178
    static atomic<int> counter(1);

    int schainID = counter.fetch_add(1);
    int dkgID = counter.fetch_add(1);
kladko's avatar
kladko committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    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.getSecretShare(polyNames[i], pubEthKeys, t, n);
        for (uint8_t k = 0; k < t; k++) {
            for (uint8_t j = 0; j < 4; j++) {
Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
197
                string pubShare = verifVects[i]["verificationVector"][k][j].asString();
kladko's avatar
kladko committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
                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.dkgVerification(pubShares[i], ethKeys[j]["keyName"].asString(), secretShare, t, n, j);
            CHECK_STATE(verif["status"] == 0);
        }

    BLSSigShareSet sigShareSet(t, n);

    string hash = SAMPLE_HASH;

    auto hash_arr = make_shared < array < uint8_t, 32 >> ();
    uint64_t binLen;
219
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
220 221 222 223 224
        throw SGXException(INVALID_HEX, "Invalid hash");
    }

    map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
225 226 227 228 229 230 231 232
    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);

kladko's avatar
kladko committed
233 234 235 236 237 238 239 240 241 242
    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);

Oleh Nikolaiev's avatar
Oleh Nikolaiev committed
243 244 245 246 247 248 249
        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
250

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

kladko's avatar
kladko committed
253
        string hash = SAMPLE_HASH;
254
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
kladko's avatar
kladko committed
255 256 257 258 259 260 261
        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));
    }

262
    sigShareSet.merge();
kladko's avatar
kladko committed
263 264 265 266 267 268 269 270 271
}

void TestUtils::destroyEnclave() {
    if (eid != 0) {
        sgx_destroy_enclave(eid);
        eid = 0;
    }
}

kladko's avatar
kladko committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 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
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;
352
    if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
kladko's avatar
kladko committed
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
        throw SGXException(INVALID_HEX, "Invalid hash");
    }

    map<size_t, shared_ptr<BLSPublicKeyShare>> pubKeyShares;

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

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

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

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

    // create pub key

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

    // sign verify a sample sig

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

        string blsName = "BLS_KEY" + polyNames[i].substr(4);
391
        blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
kladko's avatar
kladko committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
        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;
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 490 491 492

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

493
int xorDecryptDH(char *key, const char *cypher, vector<char>& message) {
494 495 496 497 498 499 500 501 502 503 504

    int ret = -1;

    if (!cypher) {
        return ret;
    }

    if (!key) {
        return ret;
    }

505
    if (!message.data()) {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
        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];
    }

529
    message = carray2Hex((unsigned char*) msg_bin, 32);
530 531 532 533 534

    ret = 0;

    return ret;
}