Ejemplo n.º 1
0
def create_shares_for_messages(setup, m_1, m_2, hierarchical=True):
    messages = {}
    computed_shares = []
    functions = []
    if hierarchical:
        for message in [m_1, m_2]:
            field_size = read_field_size(setup)
            data, _, thresholds = read_data(setup)
            shareholder_ids = [tuple(x) for x in data.values]
            person_ids, vector_of_shares = shareholder_share_list_to_lists(
                shareholder_ids)
            # put those lists into lexicographic order
            shareholders, _ = sort_coordinates(person_ids, vector_of_shares)
            r = len(shareholders)
            degree_of_function = thresholds[-1] - 1

            random_function = generate_function(degree_of_function, message,
                                                field_size)
            functions.append(random_function)
            derivatives = calc_derivative_vector(random_function,
                                                 degree_of_function,
                                                 field_size)
            for (i, j) in shareholders:
                computed_shares.append(
                    calc_function(derivatives[j], i, field_size))
        for i, (i, j) in enumerate(shareholders):
            messages[(i, j)] = (computed_shares[i - 1],
                                computed_shares[i + r - 1])
        return messages, message, functions
    else:
        for message in [m_1, m_2]:
            field_size = read_field_size(setup, False)
            shareholders = read_shares(setup, double=True)
            shareholder_ids = list(shareholder[0]
                                   for shareholder in shareholders)
            # put those lists into lexicographic order
            r = len(shareholder_ids)
            degree_of_function = int(setup.split(",")[0]) - 1

            random_function = generate_function(degree_of_function, message,
                                                field_size)
            functions.append(random_function)
            for i in shareholder_ids:
                computed_shares.append(
                    calc_function(random_function, i, field_size))
        for id in shareholder_ids:
            messages[id] = (computed_shares[id - 1],
                            computed_shares[id + r - 1])
        return messages, message, [[[0, 0]], [[0, 0]]]
def test_pre_mult(setup):
    outer_field_size = read_field_size(setup)
    triple, shareholders_, alpha_s, beta_s = pre_mult(setup)
    gammas = {}
    for i_, value in enumerate(triple):
        gammas["s_{}_{}".format(shareholders_[i_][0], shareholders_[i_][1])] = triple[value][2]

    alphas = {}
    for i_, value in enumerate(triple):
        alphas["s_{}_{}".format(shareholders_[i_][0], shareholders_[i_][1])] = triple[value][0]
    a, a_f, _, _, _ = reconstruct(setup, random_subset=False, subset=alphas, print_statements=False)
    if sum(alpha_s) % outer_field_size == a:
        print("Alpha reconstructs correctly")
    else:
        print("Not this time....", sum(alpha_s), alpha_s, a)

    betas = {}
    for i_, value in enumerate(triple):
        betas["s_{}_{}".format(shareholders_[i_][0], shareholders_[i_][1])] = triple[value][1]
    b, b_f, _, _, _ = reconstruct(setup, random_subset=False, subset=betas, print_statements=False)
    if sum(beta_s) % outer_field_size == b:
        print("Beta reconstructs correctly")
    p = multiply_polynomials(a_f, b_f, outer_field_size)
    derivatives_p = calc_derivative_vector(p, len(triple)-1, outer_field_size)
    results = []
    for shareholder in shareholders_:
        results.append(calc_function(derivatives_p[shareholder[1]], shareholder[0], outer_field_size))
    print("Results:", results, gammas)
    for i, gamma in enumerate(gammas):
        assert gammas[gamma] == results[i], "{}: computed gamma-values are incorrect ({} != {})"\
            .format(gamma, gammas[gamma], results[i])
        print("{}, gamma share = {}, result of shareholder in p(x) = {} (correct)".format(gamma, gammas[gamma], results[i]))
    print("\n")
    return triple, shareholders_, a, b
Ejemplo n.º 3
0
def compute_subshares_for_other_shareholders(field_size, function_dict,
                                             level_structure, new_shares,
                                             partial_shares):
    for i, shareholder in enumerate(function_dict):
        # for each sh take function of shareholder as current function
        current_function = function_dict[shareholder]
        for j, new_shareholder in enumerate(new_shares):
            # for each new sh calc all needed derivatives of current function
            derivatives = calc_derivative_vector(current_function,
                                                 level_structure[-1][1],
                                                 field_size)
            splitted_id = new_shareholder.split("_")
            try:
                # get the indices => the i and j value for calculation
                i_index = int(splitted_id[1])
                j_index = int(splitted_id[2])
                # calculate the result for the j'th derivative of the current function for value i
                # save all results in a matrix where each column corresponds to the results of one new shareholder
                partial_shares[i][j] = int(
                    calc_function(derivatives[j_index], int(i_index),
                                  field_size))
                if debug:
                    print(
                        "Save {} to position [{}][{}] (row defines old shareholder {}, column new sh {}), "
                        "fct is {} ({}. derivative of {})".format(
                            int(partial_shares[i][j]), i, j, shareholder,
                            new_shareholder, derivatives[j_index], j_index,
                            derivatives[0]))
            except ValueError as e:
                raise ValueError(
                    "Error in accessing index of shareholder,"
                    "format should be 's_i_j' for ID (i,j)\n{}".format(
                        repr(e)))
def rand_shares_calculation(field_size, shareholders, polynomial):
    computed_shares = []

    # print("Function: ", print_function(polynomial, printed=False))
    for (i, _) in shareholders:
        computed_shares.append(calc_function(polynomial, i, field_size))
    # print("Computed shares ", computed_shares)
    return computed_shares
def rand_shares_calculation(field_size, shareholders, thresholds, conjunctive):
    computed_shares = []
    degree_of_function = thresholds[-1] - 1
    secret = np.random.randint(0, field_size)
    if conjunctive:
        random_function = generate_function(degree_of_function, secret, field_size)
    else:
        random_function = generate_function(degree_of_function, np.random.randint(0, field_size), field_size)
        random_function[-1][0] = secret
    # print("Function: ", random_function)
    derivatives = calc_derivative_vector(random_function, degree_of_function, field_size)
    for (i, j) in shareholders:
        computed_shares.append(calc_function(derivatives[j], i, field_size))
    return computed_shares, secret
def calculate_shares(coefficients, field_size, list_of_people_per_level,
                     print_statements, thresholds, conjunctive):
    derivatives = calc_derivative_vector(coefficients, (thresholds[-1] - 1),
                                         field_size)
    t = thresholds[-1]
    # create a dict of shareholder:value pairs
    share_dict = {}
    # needed to check if the function needs to be derived
    old_j = 0
    person_number = 1
    for level, number in enumerate(list_of_people_per_level):
        # we need to derive only if we calculate values for a new level
        j = int(thresholds[level])
        # for the disjunctive setup, we don't need t_-1 = 0 -> skip
        j_disjunctive = int(thresholds[level + 1])
        while j > old_j:
            # if threshold is bigger than current j, we need to derive n times
            # to get the correct derivative to work with
            old_j += 1
            if print_statements and conjunctive:
                print("The {}. derivative of the function is \t{}".format(
                    old_j, print_function(derivatives[old_j], printed=False)))
        if conjunctive:
            current_function = derivatives[j]
        else:
            current_function = derivatives[t - j_disjunctive]
        # calculate values and append to the share_dict dict for each shareholder
        for person in range(1, int(number) + 1):
            if conjunctive:
                shareholder = ("s_{}_{}".format(person_number,
                                                thresholds[level]))
            else:
                shareholder = ("s_{}_{}".format(
                    person_number, thresholds[-1] - thresholds[level + 1]))

            if person == 1 and print_statements and conjunctive:
                print(
                    "With this function we calculate shares for the following shareholders:"
                )
            # calculate the value for the shareholder
            result = calc_function(current_function, person_number, field_size)
            person_number += 1
            if print_statements:
                print("Shareholder {}'s share is {}".format(
                    shareholder, result))
            share_dict[shareholder] = result
    return share_dict
def compute_all_partial_shares_reset(field_size, function_dict, n_prime, number_of_shares):
    partial_shares = np.zeros((number_of_shares, n_prime))
    # calculate the values with the formula from the paper
    # ( f^(j)_(k)(i) for all new shareholders (i,j) for all k)
    for i, shareholder in enumerate(function_dict):
        current_function = function_dict[shareholder]
        for j in range(1, n_prime + 1):
            try:

                # actual calculation by saving the result of
                # the j'th derivative of the k'th function for value i to the matrix
                partial_shares[i][j - 1] = int(calc_function(current_function, j, field_size))
            # if something goes wrong with the format of the shareholders
            except ValueError as e:
                print("Error in accessing index of shareholder,"
                      "format should be 's_i_j' for ID (i,j)\n{}".format(repr(e)))
                raise
    return partial_shares
def compute_all_partial_shares_renew(field_size, function_dict, number_of_shares, shareholder_ids, shareholders):
    # create a matrix to store the values calculated in the renew
    partial_shares = np.zeros((number_of_shares + 1, len(shareholder_ids)))
    # sanity check, should never cause problems
    assert (len(partial_shares) == len(partial_shares[0]) + 1), 'Wrong format of the matrix of partial results ' \
                                                                'for the new share values.'
    # write the old share values to the first row of the matrix
    for ind, value in enumerate(shareholders):
        partial_shares[0][ind] = shareholders[value[0] - 1][1]
    # calculate the other values with the formula from the paper
    # ( f^(j)_(k)(i) for all new shareholders (i,j) for all k)
    for i, shareholder in enumerate(function_dict):
        current_function = function_dict[shareholder]
        for j, shareholder_id in enumerate(shareholder_ids):
            try:
                # actual calculation by saving the result of the k'th function for value i to the matrix
                partial_shares[i + 1][j] = int(calc_function(current_function, shareholder_id, field_size))
            # if something goes wrong with the format of the shareholders
            except ValueError as e:
                print("Error in accessing index of shareholder,\n{}".format(repr(e)))
                raise
    return partial_shares
def compute_and_add_results(field_size, function_dict, new_shares,
                            partial_shares, thresholds):
    for i, shareholder in enumerate(function_dict):
        current_function = function_dict[shareholder]
        for j, other_shareholder in enumerate(new_shares):
            # get all needed derivatives of the current function
            derivatives = calc_derivative_vector(current_function,
                                                 thresholds[-1], field_size)
            splitted_id = other_shareholder.split("_")
            try:
                # get the indices of the ID (i,j) of current new shareholder
                i_index = int(splitted_id[1])
                j_index = int(splitted_id[2])
                # actual calculation by saving the result of
                # the j'th derivative of the k'th function for value i to the matrix
                partial_shares[i + 1][j] = int(
                    calc_function(derivatives[j_index], int(i_index),
                                  field_size))
            # if something goes wrong with the format of the shareholders
            except ValueError as e:
                print("Error in accessing index of shareholder,"
                      "format should be 's_i_j' for ID (i,j)\n{}".format(
                          repr(e)))
                raise