DKGUtils.cpp 13.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 71 72 73 74 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 101 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 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 403 404 405 406 407 408 409 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 490 491 492 493 494 495 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
/*
    Copyright (C) 2019-Present SKALE Labs

    This file is part of sgxwallet.

    sgxwallet is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    sgxwallet is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

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

    @file DKGUtils.cpp
    @author Stan Kladko
    @date 2019
*/

#include "DKGUtils.h"

#ifdef USER_SPACE
#include <gmp.h>
#else

#include <../tgmp-build/include/sgx_tgmp.h>

#endif

#include <../SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <../SCIPR/libff/algebra/fields/fp.hpp>

#include <../SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp>

#include "EnclaveConstants.h"
#include <cstdio>
#include <stdio.h>
#include "EnclaveCommon.h"
#include "DHDkg.h"


using namespace std;

string stringFromFr(const libff::alt_bn128_Fr &_el) {

    string ret = "";
    mpz_t t;
    mpz_init(t);

    try {
        _el.as_bigint().to_mpz(t);

        SAFE_CHAR_BUF(arr, BUF_LEN);

        char *tmp = mpz_get_str(arr, 10, t);


        ret = string(tmp);

    } catch (exception &e) {
        LOG_ERROR(e.what());
        goto clean;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        goto clean;
    }

    clean:

    mpz_clear(t);

    return ret;
}

template<class T>
string ConvertToString(const T &field_elem, int base = 10) {

    string ret;

    mpz_t t;
    mpz_init(t);

    try {

        field_elem.as_bigint().to_mpz(t);

        SAFE_CHAR_BUF(arr, BUF_LEN);

        char *tmp = mpz_get_str(arr, base, t);

        ret = string(tmp);

        goto clean;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        goto clean;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        goto clean;
    }

    clean:
    mpz_clear(t);
    return ret;

}

string ConvertG2ToString(const libff::alt_bn128_G2 &elem, int base = 10, const string &delim = ":") {

    string result = "";

    try {

        result += ConvertToString(elem.X.c0);
        result += delim;
        result += ConvertToString(elem.X.c1);
        result += delim;
        result += ConvertToString(elem.Y.c0);
        result += delim;
        result += ConvertToString(elem.Y.c1);

        return result;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return result;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return result;
    }

    return result;
}

vector <libff::alt_bn128_Fr> SplitStringToFr(const char *coeffs, const char symbol) {
    vector <libff::alt_bn128_Fr> result;
    string str(coeffs);
    string delim;

    CHECK_ARG_CLEAN(coeffs);

    try {

        delim.push_back(symbol);

        size_t prev = 0, pos = 0;
        do {
            pos = str.find(delim, prev);
            if (pos == string::npos) pos = str.length();
            string token = str.substr(prev, pos - prev);
            if (!token.empty()) {
                libff::alt_bn128_Fr coeff(token.c_str());
                result.push_back(coeff);
            }
            prev = pos + delim.length();
        } while (pos < str.length() && prev < str.length());

        return result;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return result;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return result;
    }

    clean:
    return result;
}

int gen_dkg_poly(char *secret, unsigned _t) {

    int status = 1;
    string result;

    CHECK_ARG_CLEAN(secret);

    try {
        for (size_t i = 0; i < _t; ++i) {
            libff::alt_bn128_Fr cur_coef = libff::alt_bn128_Fr::random_element();

            while (i == _t - 1 && cur_coef == libff::alt_bn128_Fr::zero()) {
                cur_coef = libff::alt_bn128_Fr::random_element();
            }
            result += stringFromFr(cur_coef);
            result += ":";
        }
        strncpy(secret, result.c_str(), result.length() + 1);

        if (strlen(secret) == 0) {
            return status;
        }

        status = 0;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return status;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return status;
    }

    clean:
    return status;
}

libff::alt_bn128_Fr PolynomialValue(const vector <libff::alt_bn128_Fr> &pol, libff::alt_bn128_Fr point, unsigned _t) {

    libff::alt_bn128_Fr result = libff::alt_bn128_Fr::zero();

    try {

        libff::alt_bn128_Fr pow = libff::alt_bn128_Fr::one();
        for (unsigned i = 0; i < pol.size(); ++i) {
            result += pol.at(i) * pow;
            pow *= point;
        }

        return result;
    } catch (exception &e) {
        LOG_ERROR(e.what());
        return result;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return result;
    }

    return result;
}

void calc_secret_shares(const char *decrypted_coeffs,
                        char *secret_shares,      // calculates secret shares in base 10 to a string secret_shares,
                        unsigned _t, unsigned _n) {                                                 // separated by ":"

    // calculate for each node a list of secret values that will be used for verification
    string result;
    char symbol = ':';

    CHECK_ARG_CLEAN(decrypted_coeffs);
    CHECK_ARG_CLEAN(secret_shares);
    CHECK_ARG_CLEAN(_n > 0);
    CHECK_ARG_CLEAN(_t <= _n);

    try {

        vector <libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_coeffs, symbol);

        for (size_t i = 0; i < _n; ++i) {
            libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(i + 1), _t);
            result += ConvertToString(secret_share);
            result += ":";
        }
        strncpy(secret_shares, result.c_str(), result.length() + 1);

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return;
    }

    clean:
    ;
}

int calc_secret_share(const char *decrypted_coeffs, char *s_share,
                      unsigned _t, unsigned _n, unsigned ind) {
    int result = 1;

    CHECK_ARG_CLEAN(decrypted_coeffs);
    CHECK_ARG_CLEAN(s_share);
    CHECK_ARG_CLEAN(_n > 0);
    CHECK_ARG_CLEAN(_t <= _n);

    try {
        char symbol = ':';
        vector <libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_coeffs, symbol);
        if (poly.size() != _t) {
            return result;
        }

        libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(ind), _t);
        string cur_share = ConvertToString(secret_share, 16);
        int n_zeroes = 64 - cur_share.size();
        cur_share.insert(0, n_zeroes, '0');

        strncpy(s_share, cur_share.c_str(), cur_share.length() + 1);
        result = 0;
        return result;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return result;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return result;
    }

    clean:
    return result;
}


int calc_secret_shareG2(const char *s_share, char *s_shareG2) {

    int result = 1;

    mpz_t share;
    mpz_init(share);

    CHECK_ARG_CLEAN(s_share);
    CHECK_ARG_CLEAN(s_shareG2);

    try {


        if (mpz_set_str(share, s_share, 16) == -1) {
            goto clean;
        }

        SAFE_CHAR_BUF(arr, BUF_LEN);

        char *share_str = mpz_get_str(arr, 10, share);

        libff::alt_bn128_Fr secret_share(share_str);

        libff::alt_bn128_G2 secret_shareG2 = secret_share * libff::alt_bn128_G2::one();

        secret_shareG2.to_affine_coordinates();

        string secret_shareG2_str = ConvertG2ToString(secret_shareG2);

        strncpy(s_shareG2, secret_shareG2_str.c_str(), secret_shareG2_str.length() + 1);
        result = 0;
        goto clean;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        goto clean;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        goto clean;
    }

    clean:

    mpz_clear(share);
    return result;

}

int calc_public_shares(const char *decrypted_coeffs, char *public_shares,
                       unsigned _t) {

    // calculate for each node a list of public shares
    int ret = 1;
    string result;
    char symbol = ':';

    CHECK_ARG_CLEAN(decrypted_coeffs);
    CHECK_ARG_CLEAN(public_shares);
    CHECK_ARG_CLEAN(_t > 0);

    try {

        vector <libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_coeffs, symbol);
        if (poly.size() != _t) {
            return ret;
        }
        for (size_t i = 0; i < _t; ++i) {
            libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one();
            pub_share.to_affine_coordinates();
            string pub_share_str = ConvertG2ToString(pub_share);
            result += pub_share_str + ",";
        }
        strncpy(public_shares, result.c_str(), result.length());
        ret = 0;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        ret = 1;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        ret = 1;
    }

    clean:
    return ret;
}

string ConvertHexToDec(string hex_str) {

    mpz_t dec;
    mpz_init(dec);

    string ret = "";

    try {

        if (mpz_set_str(dec, hex_str.c_str(), 16) == -1) {
            goto clean;
        }

        char arr[mpz_sizeinbase(dec, 10) + 2];
        char *result = mpz_get_str(arr, 10, dec);
        CHECK_ARG_CLEAN(result);
        ret = result;
    } catch (exception &e) {
        LOG_ERROR(e.what());
        goto clean;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        goto clean;
    }

    clean:
    mpz_clear(dec);
    return ret;
}

int Verification(char *public_shares, mpz_t decr_secret_share, int _t, int ind) {

    string pub_shares_str = public_shares;
    vector <libff::alt_bn128_G2> pub_shares;
    uint64_t share_length = 256;
    uint8_t coord_length = 64;
    int ret = 0;

    CHECK_ARG_CLEAN(public_shares);

    try {

        for (int i = 0; i < _t; i++) {
            libff::alt_bn128_G2 pub_share;

            uint64_t pos0 = share_length * i;
            string x_c0_str = ConvertHexToDec(pub_shares_str.substr(pos0, coord_length));
            string x_c1_str = ConvertHexToDec(pub_shares_str.substr(pos0 + coord_length, coord_length));
            string y_c0_str = ConvertHexToDec(pub_shares_str.substr(pos0 + 2 * coord_length, coord_length));
            string y_c1_str = ConvertHexToDec(pub_shares_str.substr(pos0 + 3 * coord_length, coord_length));
            if (x_c0_str == "" || x_c1_str == "" || y_c0_str == "" || y_c1_str == "") {
                ret = 2;
                return ret;
            }
            pub_share.X.c0 = libff::alt_bn128_Fq(x_c0_str.c_str());
            pub_share.X.c1 = libff::alt_bn128_Fq(x_c1_str.c_str());
            pub_share.Y.c0 = libff::alt_bn128_Fq(y_c0_str.c_str());
            pub_share.Y.c1 = libff::alt_bn128_Fq(y_c1_str.c_str());
            pub_share.Z = libff::alt_bn128_Fq2::one();

            pub_shares.push_back(pub_share);
        }

        libff::alt_bn128_G2 val = libff::alt_bn128_G2::zero();
        for (int i = 0; i < _t; ++i) {
            val = val + power(libff::alt_bn128_Fr(ind + 1), i) * pub_shares.at(i);
        }

        SAFE_CHAR_BUF(arr, BUF_LEN);
        char *tmp = mpz_get_str(arr, 10, decr_secret_share);

        libff::alt_bn128_Fr sshare(tmp);

        libff::alt_bn128_G2 val2 = sshare * libff::alt_bn128_G2::one();

        memset(public_shares, 0, strlen(public_shares));
        strncpy(public_shares, tmp, strlen(tmp));

        val.to_affine_coordinates();
        val2.to_affine_coordinates();
        strncpy(public_shares, ConvertToString(val.X.c0).c_str(), ConvertToString(val.X.c0).length());
        strncpy(public_shares + ConvertToString(val.X.c0).length(), ":", 1);
        strncpy(public_shares + ConvertToString(val.X.c0).length() + 1, ConvertToString(val2.X.c0).c_str(),
                ConvertToString(val2.X.c0).length());

        ret = (val == sshare * libff::alt_bn128_G2::one());

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return ret;

    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return ret;
    }

    clean:
    return ret;
}

int calc_bls_public_key(char *skey_hex, char *pub_key) {
    mpz_t skey;
    mpz_init(skey);

    int ret = 1;

    CHECK_ARG_CLEAN(skey_hex);
    CHECK_ARG_CLEAN(pub_key);

    try {

        if (mpz_set_str(skey, skey_hex, 16) == -1) {
            mpz_clear(skey);
            return 1;
        }

        char skey_dec[mpz_sizeinbase(skey, 10) + 2];
        mpz_get_str(skey_dec, 10, skey);

        libff::alt_bn128_Fr bls_skey(skey_dec);

        libff::alt_bn128_G2 public_key = bls_skey * libff::alt_bn128_G2::one();
        public_key.to_affine_coordinates();

        string result = ConvertG2ToString(public_key);

        strncpy(pub_key, result.c_str(), result.length());

        mpz_clear(skey);

        return 0;

    } catch (exception &e) {
        LOG_ERROR(e.what());
        return 1;
    } catch (...) {
        LOG_ERROR("Unknown throwable");
        return 1;
    }

    clean:
    mpz_clear(skey);
    return ret;
}