Example #1
0
    def __init__(self, runtime):
        self.k = 4
        self.runtime = runtime
        self.ramdom_shares = [
            0 for i in range(self.k * int(math.log(self.k, 2)))
        ]
        self.triggers = [
            Share(self.runtime, Zp)
            for i in range(self.k * int(math.log(self.k, 2)))
        ]
        self.p = find_prime(2**256, blum=True)
        print self.p

        for i in range(self.k * int(math.log(self.k, 2))):

            r = runtime.prss_share_random(Zp)
            u = r * r
            open_u = runtime.open(u)
            open_u.addCallback(self.calculate_share, r, i)

        list = [
            self.triggers[i] for i in range(self.k * int(math.log(self.k, 2)))
        ]
        result = gather_shares(list)
        result.addCallback(self.preprocess_ready)
Example #2
0
def eval_poly(runtime):
    print "Starting protocol"
    start_time = time()

    modulus = find_prime(2**65, blum=True)
    Zp = GF(modulus)

    # In this example we just let Player 1 share the input values.
    if runtime.id == 1:
        x = runtime.shamir_share([1], Zp, 17)
        a = runtime.shamir_share([1], Zp, 42)
        b = runtime.shamir_share([1], Zp, -5)
        c = runtime.shamir_share([1], Zp, 87)
    else:
        x = runtime.shamir_share([1], Zp)
        a = runtime.shamir_share([1], Zp)
        b = runtime.shamir_share([1], Zp)
        c = runtime.shamir_share([1], Zp)

    # Evaluate the polynomial.
    p = a * (x * x) + b * x + c

    sign = (p < 0) * -1 + (p > 0) * 1
    output = runtime.open(sign)
    output.addCallback(done, start_time, runtime)
def share_all(runtime):
    share_rounds = 0  # How many rounds to share all inputs
    for party in nodes_per_party:
        share_rounds = max(share_rounds, len(nodes_per_party[party]))

    # Share the inputs in rounds
    shares = {}  # will contain the shares.

    l = runtime.options.bit_length
    k = runtime.options.security_parameter
    Zp = GF(find_prime(2**65, blum=True))

    this_party_input = nodes_per_party[int(id)]
    for i in range(share_rounds):
        print "share round " + str(i) + "/" + str(share_rounds)
        value_to_share = 0
        if i < len(this_party_input):
            value_to_share = values[this_party_input[i]]
            value_to_share = INFINITY if value_to_share == float(
                "inf") else value_to_share

        round_shares = runtime.shamir_share(parties_list, Zp, value_to_share)
        for index in range(len(round_shares)):
            party = parties_list[index]
            sharing_party_inputs = nodes_per_party[int(party)]
            if i < len(sharing_party_inputs):
                shares[sharing_party_inputs[i]] = round_shares[index]

    return shares
Example #4
0
 def mpc_share_guess(self, guess):
     # For the comparison protocol to work, we need a field modulus
     # bigger than 2**(l+1) + 2**(l+k+1), where the bit length of
     # the input numbers is l and k is the security parameter.
     # Further more, the prime must be a Blum prime (a prime p such
     # that p % 4 == 3 holds). The find_prime function lets us find
     # a suitable prime.
     l = self.runtime.options.bit_length
     k = self.runtime.options.security_parameter
     Zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))
     # We must secret share our input with the other parties. They
     # will do the same and we end up with three variables
     # We can only share between the remaining player, don't wait
     # for a dead person's input.
     # TODO: only require the living players to respond.
     alive_player_array = self.alive_players()
     if not self.lives[self.runtime.id - 1] > 0:
         print "sorry you're dead ignoring your input  %s " % self.runtime.id
         return self.runtime.shamir_share(alive_player_array, Zp, None)
     else:
         print "you're alive  your player num  %s " % self.runtime.id
         print "alive  mcp %s " % alive_player_array
         if self.is_player:
             print "in 1,2 "
             g1, g2 = self.runtime.shamir_share([1, 2], Zp, guess)
         else:
             print "in 3"
             g1, g2 = self.runtime.shamir_share([1, 2], Zp)
     return [g1, g2]
Example #5
0
    def __init__(self, runtime):
        # Save the Runtime for later use
        self.runtime = runtime
        self.k = 256
        self.b = 2
        self.threshold = 1

        self.matrix = [[0 for x in range(self.k + 1)]
                       for y in range(self.k + 1)]
        self.openmatrix = [[0 for x in range(self.k + 1)]
                           for y in range(self.k + 1)]
        self.prefix = 0

        # This is the value we will use in the protocol.
        self.target = 3

        Zp = GF(find_prime(2**64))

        if runtime.id == 1:
            a = runtime.shamir_share([1], Zp, self.target)
        else:
            a = runtime.shamir_share([1], Zp)
        self.a = a
        '''
	for i in range(self.k + 1):
		if runtime.id == 1:
	    		self.matrix[0][i] = self.runtime.shamir_share([1], Zp, self.b**i)
		else:
	    		self.matrix[0][i] = self.runtime.shamir_share([1], Zp)

	'''

        #self.matrix[0][1] = TriplesHyperinvertibleMatricesMixin.single_share_random(1,self.threshold,Zp)
        if runtime.id == 1:
            self.matrix[0][0] = self.runtime.shamir_share([1], Zp, 0)
            self.matrix[0][1] = self.runtime.shamir_share([1], Zp, self.b)
        else:
            self.matrix[0][0] = self.runtime.shamir_share([1], Zp)
            self.matrix[0][1] = self.runtime.shamir_share([1], Zp)
        for i in range(2, self.k + 1):
            self.matrix[0][i] = self.matrix[0][i - 1] * self.matrix[0][1]

#record_stop()

        for i in range(self.k + 1):
            self.openmatrix[0][i] = self.runtime.open(self.matrix[0][i])

        self.matrix[1][0] = self.a
        self.matrix[1][1] = self.matrix[1][0] * self.matrix[0][1]

        self.prefix = self.runtime.open(a - self.matrix[0][1])

        list1 = [self.prefix, a, self.matrix[1][1]]
        list1 = list1 + [self.matrix[0][i] for i in range(1, self.k + 1)]
        print len(list1)
        #results = list1

        results = gather_shares(list1)
        results.addCallback(self.preprocess_ready)
Example #6
0
    def __init__(self, runtime):
        # Save the Runtime for later use
        self.runtime = runtime

        # This is the value we will use in the protocol.
        self.millions = rand.randint(1, 200)
        print "I am Millionaire %d and I am worth %d millions." \
            % (runtime.id, self.millions)

        # For the comparison protocol to work, we need a field modulus
        # bigger than 2**(l+1) + 2**(l+k+1), where the bit length of
        # the input numbers is l and k is the security parameter.
        # Further more, the prime must be a Blum prime (a prime p such
        # that p % 4 == 3 holds). The find_prime function lets us find
        # a suitable prime.
        l = runtime.options.bit_length
        k = runtime.options.security_parameter
        Zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))

        # We must secret share our input with the other parties. They
        # will do the same and we end up with three variables
        m1, m2, m3 = runtime.shamir_share([1, 2, 3], Zp, self.millions)

        # Now that everybody has secret shared their inputs we can
        # compare them. We compare the worth of the first millionaire
        # with the two others, and compare those two millionaires with
        # each other.
        m1_ge_m2 = m1 >= m2
        m1_ge_m3 = m1 >= m3
        m2_ge_m3 = m2 >= m3

        # The results are secret shared, so we must open them before
        # we can do anything usefull with them.
        open_m1_ge_m2 = runtime.open(m1_ge_m2)
        open_m1_ge_m3 = runtime.open(m1_ge_m3)
        open_m2_ge_m3 = runtime.open(m2_ge_m3)

        # We will now gather the results and call the
        # self.results_ready method when they have all been received.
        results = gather_shares([open_m1_ge_m2, open_m1_ge_m3, open_m2_ge_m3])
        results.addCallback(self.results_ready)

        # We can add more callbacks to the callback chain in results.
        # These are called in sequence when self.results_ready is
        # finished. The first callback acts like a barrier and makes
        # all players wait on each other.
        #
        # The callbacks are always called with an argument equal to
        # the return value of the preceeding callback. We do not need
        # the argument (which is None since self.results_ready does
        # not return anything), so we throw it away using a lambda
        # expressions which ignores its first argument.
        runtime.schedule_callback(results, lambda _: runtime.synchronize())
        # The next callback shuts the runtime down, killing the
        # connections between the players.
        runtime.schedule_callback(results, lambda _: runtime.shutdown())
Example #7
0
def main():
     # Parse command line arguments.
    parser = OptionParser(usage=__doc__)

    parser.add_option("--modulus",
                     help="lower limit for modulus (can be an expression)")

    parser.set_defaults(modulus=2**65)

    Runtime.add_options(parser)

    options, args = parser.parse_args()
    if len(args)==2:
        number = int(args[1])
    else:
        number = None

    if len(args) == 0:
        parser.error("you must specify a config file")

    Zp = GF(find_prime(options.modulus, blum=True))

    # Load configuration file.
    id, players = load_config(args[0])

    runtime_class = make_runtime_class(mixins=[ComparisonToft07Mixin])
    pre_runtime = create_runtime(id, players, 1, options, runtime_class)

    def run(runtime):
        print "Connected."

        # Players 1 and 2 are doing a sharing over the field Zp.
        # Our input is number (None for other players).
        if runtime.id == 3:
            print "I have no number"
        else:
            print "My number: %d." % number
        (x, y) = runtime.shamir_share([1, 2], Zp, number)

        # Do the secret computation.
        result = divide(x, y, 10) # 10 bits for the result.

        # Now open the result so we can see it.
        dprint("The two numbers divided are: %s", runtime.open(result))

        result.addCallback(lambda _: runtime.shutdown())

    pre_runtime.addCallback(run)

    # Start the Twisted event loop.
    reactor.run()
Example #8
0
def main(runtime):
    global tv, Zp
    tv = runtime
    k = tv.options.security_parameter
    l = tv.options.bit_length
    ln = len(tv.players).bit_length()
    Zp = GF(find_prime(2**(l + k + ln + 1), blum=True))
    yield declareReturn(tv, Zp)

    shareZp = lambda x: Share(tv, Zp, Zp(x))
    t = 12
    for i in xrange(t):
        a = secret_index(shareZp(i), t)
        a = yield map(tv.open, a)
        print i, map(lambda v: int(v.value), a)
    tv.shutdown()
Example #9
0
    def __init__(self, runtime, k):
        self.k = k
        self.runtime = runtime
        self.inputs = [0 for _ in range(self.k)]
        self.p = find_prime(2**256, blum=True)
        self.Zp = GF(self.p)
        self.open_value = [0 for _ in range(self.k)]
        self.precomputed_powers = [[0 for _ in range(self.k)]
                                   for _ in range(self.k)]

        # load -1/1 shares from file
        self.load_input_from_file(self.k, self.p)

        for i in range(self.k):
            self.open_value[i] = self.runtime.open(self.inputs[i])
        #print self.open_value
        result = gather_shares(self.open_value)
        result.addCallback(self.create_output)
Example #10
0
    def __init__(self, runtime):
        self.k = 2048
        self.runtime = runtime
        self.ramdom_shares = [
            0 for i in range(self.k * int(math.log(self.k, 2)))
        ]
        self.triggers = [
            Share(self.runtime, Zp)
            for i in range(self.k * int(math.log(self.k, 2)))
        ]
        self.input = [0 for i in range(self.k)]
        self.p = find_prime(2**256, blum=True)
        print "begin allocating input shares(Party 1 will generate these shares)"

        for i in range(self.k):
            if runtime.id == 1:
                self.input[i] = self.runtime.shamir_share([1], Zp, i)
            else:
                self.input[i] = self.runtime.shamir_share([1], Zp)
        '''
	for i in range(self.k * int(math.log(self.k,2))):
		if runtime.id == 1:
			self.ramdom_shares[i] = self.runtime.shamir_share([1], Zp,randint(0, 1))			
		else:
			self.ramdom_shares[i] = self.runtime.shamir_share([1], Zp)
	'''
        print "begin generating random 1/-1 shares"
        for i in range(self.k * int(math.log(self.k, 2))):

            r = runtime.prss_share_random(Zp)
            u = r * r
            open_u = self.runtime.open(u)
            open_u.addCallback(self.calculate_share, r, i)

        list = [self.input[i] for i in range(self.k)]
        list = list + [
            self.triggers[i] for i in range(self.k * int(math.log(self.k, 2)))
        ]
        result = gather_shares(list)

        result.addCallback(self.preprocess_ready)
Example #11
0
    def __init__(self, runtime):
        # Save the Runtime for later use
        self.runtime = runtime
	self.k = 64
	self.b = 2
	self.threshold = 1

	self.matrix = [[0 for x in range(self.k + 1)] for y in range(self.k + 1)]
	self.resultmatrix = [[0 for x in range(self.k + 1)] for y in range(self.k + 1)]

	self.openmatrix =[[0 for x in range(self.k + 1)] for y in range(self.k + 1)]
	


	#self.powersum = [0 for x in range(self.k + 1)]
        # This is the value we will use in the protocol.
        self.target = [i for i in range(self.k)]
	#self.target = [7]

	self.Zp = GF(find_prime(2**64))

	self.calculate_powersum(self.target[0],0)
Example #12
0
def main(runtime):
    print "################\n"
    print(dir(runtime))
    print "################\n"
    global tv, Zp
    tv = runtime
    k = tv.options.security_parameter
    l = tv.options.bit_length
    ln = len(tv.players).bit_length()
    Zp = GF(find_prime(2**(l + k + ln + 1), blum=True))
    print "Galois"
    print Zp(0)
    yield declareReturn(tv, Zp)
    for n in xrange(10,11):
        a = random_derangement_3(n)
        #a = random_unit_vector(n)
        print("############################## STEP", n ,"\n")
        #a = random_permutation(n)
        a = yield map(tv.open, a)
        #print "finito!"
        print map(lambda v:int(v.value), a) #time/object - this is the function that prints the values on the terminal
    tv.shutdown()
    def share(self):
        self.shares = {}

        l = self.runtime.options.bit_length
        k = self.runtime.options.security_parameter
        Zp = GF(find_prime(2**65, blum=True))

        this_party_input = self.party_inputs[self.id]

        # Share in rounds
        for i in range(self.share_rounds):
            value_to_share = 0
            if i < len(this_party_input):
                value_to_share = self.input_map[this_party_input[i]]

            round_shares = self.runtime.shamir_share(self.parties_list, Zp,
                                                     value_to_share)
            for index in range(len(round_shares)):
                party = self.parties_list[index]
                party_inputs = self.party_inputs[party]
                if i < len(party_inputs):
                    self.shares[party_inputs[i]] = round_shares[index]
Example #14
0
 def run(self, runtime):
 
     l = 512
     k = 64
     
     print "Generating field... "
     
     self.zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))
     self.runtime = runtime
     
     p = range(1, runtime.num_players + 1)
     
     print "Sharing values... "
     
     add_shares = runtime.input(p, self.zp, self.address)
     rep_shares = runtime.input(p, self.zp, self.representative)
     
     n = len(rep_shares)
     
     for i in range(0, n - 1):
        
         for j in range(0, n - i - 1): 
             
             c = rep_shares[j] < rep_shares[j + 1]
             
             p, q = pair_sort(rep_shares[j], rep_shares[j + 1], c)
             
             rep_shares[j] = p
             rep_shares[j + 1] = q 
             
             r, s = pair_sort(add_shares[j], add_shares[j + 1], c)
                 
             add_shares[j] = r
             add_shares[j + 1] = s
             
     
     gather_shares([ self.runtime.open(x) for x in add_shares ]).addCallback(self.done)
Example #15
0
    def __init__(self, runtime):
        # Save the Runtime for later use
        self.runtime = runtime
        lives = [True for p in runtime.players]
        self.alive = lives
        print "Player's lives %s " % self.alive
        print "You are Player %d " % (runtime.id)
        print "There are %d player in this game." % (len(runtime.players))
        sys.stdout.write(RED)
        sec_num = input(
            "Enter a secret number for you opponent to guess (1 - 20): ")
        sys.stdout.write(RESET)
        print "Your secret is: ", sec_num
        # This is the value we will use in the protocol.
        self.sec_num = sec_num
        # This is also a secret shared value we will use in the protocol.
        self.guess = self.obtain_guess()
        print "Your number attack is %d" % self.guess

        # For the comparison protocol to work, we need a field modulus
        # bigger than 2**(l+1) + 2**(l+k+1), where the bit length of
        # the input numbers is l and k is the security parameter.
        # Further more, the prime must be a Blum prime (a prime p such
        # that p % 4 == 3 holds). The find_prime function lets us find
        # a suitable prime.
        l = runtime.options.bit_length
        k = runtime.options.security_parameter
        Zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))

        # We must secret share our input with the other parties. They
        # will do the same and we end up with three variables
        self.s1, self.s2, self.s3 = runtime.shamir_share([1, 2, 3], Zp,
                                                         self.sec_num)
        g1, g2, g3 = runtime.shamir_share([1, 2, 3], Zp, self.guess)
        results = self.calc_round_results(g1, g2, g3)
        results.addCallback(self.round_ready)
        runtime.schedule_callback(results, lambda _: self.run_round())
Example #16
0
    def __init__(self, runtime, k):
        self.k = k
        self.runtime = runtime
        self.inputs = [0 for _ in range(self.k)]
        self.p = find_prime(2**256, blum=True)
        self.Zp = GF(self.p)
        self.a_minus_b = [0 for _ in range(self.k)]
        self.precomputed_powers = [[0 for _ in range(self.k)]
                                   for _ in range(self.k)]

        # load -1/1 shares from file
        self.load_input_from_file(self.k, self.p)

        for i in range(self.k):
            #TODO: here for testing we use same random b, in the future we need to change this to:
            #self.load_share_from_file(self.k,self.p,i)
            self.load_share_from_file(self.k, self.p, i)

        for i in range(self.k):
            self.a_minus_b[i] = self.runtime.open(
                self.inputs[i] - self.precomputed_powers[i][0])
        #print self.a_minus_b
        result = gather_shares(self.a_minus_b)
        result.addCallback(self.create_output)
Example #17
0
def share_all(runtime):
    # Map node names by party id
    party_inputs = {p: [] for p in parties}
    for input_name in input_map:
        party = int(input_name[1:input_name.index("_")])
        party_inputs.get(party).append(input_name)

    # Sort the node names consistently in each party
    share_rounds = 0  # How many rounds to share all inputs
    for party in party_inputs:
        party_inputs[party].sort()
        share_rounds = max(share_rounds, len(party_inputs[party]))

    # Share the inputs in rounds
    shares = {}  # will contain the shares.

    l = runtime.options.bit_length
    k = runtime.options.security_parameter
    Zp = GF(find_prime(2**65, blum=True))

    this_party_input = party_inputs[id]
    for i in range(share_rounds):
        value_to_share = 0
        if i < len(this_party_input):
            value_to_share = input_map[this_party_input[i]]
            value_to_share = INFINITY if value_to_share == float(
                "inf") else value_to_share

        round_shares = runtime.shamir_share(parties_list, Zp, value_to_share)
        for index in range(len(round_shares)):
            party = parties_list[index]
            sharing_party_inputs = party_inputs[party]
            if i < len(sharing_party_inputs):
                shares[sharing_party_inputs[i]] = round_shares[index]

    return shares
Example #18
0
def main(rt):
    global tv, Zp, S, C
    tv = rt
    k = tv.options.security_parameter
    l = tv.options.bit_length
    ln = len(tv.players).bit_length()
    Zp = GF(find_prime(2**(l + k + ln + 1), blum=True))
    yield declareReturn(tv, Zp) 
    transactions = load_file(tv.options.file + ".data")
    attributes = load_file(tv.options.file + ".info")[0]
    n = len(attributes[1:])
    S = [[[Share(tv, Zp, Zp(int(t[i]==j))) 
            for t in transactions] 
            for j in xrange(attributes[1:][i])] 
            for i in xrange(n)]
    C = attributes[0] % n
    T = [Share(tv, Zp, Zp(1))] * len(transactions)
    tree = yield id3(T, frozenset(xrange(n)).difference([C]))
    print "Tree = ", tree
    height = lambda t: max(map(height, t[1]))+1 if isinstance(t,tuple) else 0
    print "Tree height = ", height(tree)
    size = lambda t: sum(map(size, t[1]))+1 if isinstance(t,tuple) else 1
    print "Tree size = ", size(tree)
    tv.shutdown()
Example #19
0
 def __init__(self, runtime):
     self.Zp = GF(find_prime(2**64))
     self.runtime = runtime
     self.last_time = time()
     self.share_next(0)
Example #20
0
if not args:
    parser.error("you must specify a config file")

id, players = load_config(args[0])

if not 1 <= options.threshold <= len(players):
    parser.error("threshold out of range")

if options.fake:
    print "Using fake field elements"
    Field = FakeGF
else:
    Field = GF

Zp = Field(find_prime(options.modulus))
print "Using field elements (%d bit modulus)" % log(Zp.modulus, 2)

count = options.count
print "I am player %d, will %s %d numbers" % (id, options.operation, count)

# Identify the base runtime class.
if options.runtime == "OrlandiRuntime" and not OrlandiRuntime:
    print "Error: The following modules did not load correctly:"
    if not commitment:
        print "commitment"
    if not pypaillier:
        print "pypaillier"
    if not OrlandiRuntime:
        print "OrlandiRuntime"
    exit(1)
Example #21
0
    def __init__(self, runtime):
        # Save the Runtime for later use
        self.runtime = runtime
        # to start with there are no hits
        # we will record the ship hits here.
        self.hit_list = []
        self.total_num_ships = 1
        # there are only two actual players, the other
        # "players" are only there to run MPC.
        self.is_player = (runtime.id == 1 or runtime.id == 2)

        lives = [0 for p in runtime.players]
        # Only two player are actually playing
        # the other's are just for MPC
        lives[0] = 3 
        lives[1] = 3 

        self.p1_lives_prev = 3
        self.p2_lives_prev = 3

        self.lives = lives
        print "Player's lives %s " % self.lives
        print "You are Player %d " % (runtime.id) 
        print "There are %d player in this game." % (len(runtime.players))
        # we only play with two players, the others are only for MPC

        if self.is_player:
          sys.stdout.write(RED)
          ship1 = input("Enter your ship 1: ")
          ship2 = input("Enter your ship 2: ")
          ship3 = input("Enter your ship 3: ")
          sys.stdout.write(RESET)
          # This is the value we will use in the protocol.
          self.ship1 = ship1
          self.ship2 = ship2
          self.ship3 = ship3

        # For the comparison protocol to work, we need a field modulus
        # bigger than 2**(l+1) + 2**(l+k+1), where the bit length of
        # the input numbers is l and k is the security parameter.
        # Further more, the prime must be a Blum prime (a prime p such
        # that p % 4 == 3 holds). The find_prime function lets us find
        # a suitable prime.
        l = runtime.options.bit_length
        k = runtime.options.security_parameter
        Zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))

        # We must secret share our ships with the other parties. They
        # will do the same and we end up secretly having each other's
        # ships.
        if self.is_player:
          print "I'm player 1 2 get my secret ships as"
          print "ship 1 %s " % self.ship1
          print "ship 2 %s " % self.ship2
          print "ship 3 %s " % self.ship3
          self.p1_ship1, self.p2_ship1 = runtime.shamir_share([1, 2], Zp, self.ship1)
          self.p1_ship2, self.p2_ship2 = runtime.shamir_share([1, 2], Zp, self.ship2)
          self.p1_ship3, self.p2_ship3 = runtime.shamir_share([1, 2], Zp, self.ship3)
        else:
          print "I'm here just to help with MPC. I don't affect this game."
          self.p1_ship1, self.p2_ship1 = runtime.shamir_share([1, 2], Zp)
          self.p1_ship2, self.p2_ship2 = runtime.shamir_share([1, 2], Zp)
          self.p1_ship3, self.p2_ship3 = runtime.shamir_share([1, 2], Zp)
        ## TODO: we don't neat a board for our first design.
        # self.p1_board, self.p2_board = self.init_secret_board(l, k, Zp)

        #print "printin p1 %s" % self.p1_board
        #print "printing p2 %s" % self.p2_board
        # now we have secret shared the ships, and the board 
        # the ships will not change, but we will have to update the
        # board and the guess for each round, as we will never learn
        # about the ships values, but only that we hit one, or didn't
        # hit one.

        # get back the array of the board with the ships in place.
        # results = self.place_ships_on_board()
        # start the game loop
        self.run_round()
                  help="number of comparisons")

parser.set_defaults(modulus="30916444023318367583",
                    count=100)

# Add standard VIFF options.
Runtime.add_options(parser)

(options, args) = parser.parse_args()

if len(args) == 0:
    parser.error("you must specify a config file")

id, players = load_config(args[0])

Zp = GF(find_prime(options.modulus, blum=True))

print Zp.modulus

# TODO: better q-prime...must depend on prime
qprime = 3001
Zq = GF(long(qprime))
#Zq = Zp

count = options.count
print "I am player %d, will compare %d numbers" % (id, count)


def protocol(rt):
    print "Testing online requirements for Toft07 comparison"
    l = rt.options.bit_length
Example #23
0
# player configuration file.

import sys

import viff.reactor
viff.reactor.install()
from twisted.internet import reactor

from viff.field import GF
from viff.runtime import create_runtime
from viff.paillier import PaillierRuntime
from viff.config import load_config
from viff.util import dprint, find_prime

id, players = load_config(sys.argv[1])
Zp = GF(find_prime(2**64))
input = int(sys.argv[2])

print "I am player %d and will input %s" % (id, input)


def protocol(runtime):
    print "-" * 64
    print "Program started"
    print

    a, b = runtime.share([1, 2], Zp, input)
    c = a * b

    dprint("a%d: %s", runtime.id, a)
    dprint("b%d: %s", runtime.id, b)
Example #24
0
    def __init__(self, runtime):
        # Save the Runtime for later use
        self.runtime = runtime
        # to start with there are no hits
        # we will record the ship hits here.
        self.hit_list = []
        self.my_coords = SHIPS
        self.p1_shares = defaultdict(list)
        self.p2_shares = defaultdict(list)

        # there are only two actual players, the other
        # "players" are only there to run MPC.
        self.is_player = (runtime.id == 1 or runtime.id == 2)

        lives = [0 for p in runtime.players]
        # Only two player are actually playing
        # the other's are just for MPC
        lives[0] = 3
        lives[1] = 3

        self.p1_lives_prev = 3
        self.p2_lives_prev = 3

        self.lives = lives
        print "Player's lives %s " % self.lives
        print "You are Player %d " % (runtime.id)
        print "There are %d player in this game." % (len(runtime.players))
        # we only play with two players, the others are only for MPC

        if self.is_player:
            sys.stdout.write(RED)
            print(
                "Enter the coordinates of your ships, in tuple form, "
                "(e.g.: v, 0, 0) for a ship starting at x: 0, y: 0, and facing downwards."
                "(e.g.: h, 5, 6) for a ship starting at x: 5, y: 6, and facing right"
            )
            for shipname in SHIPS:
                coords = input("{}: ".format(shipname))

                length = len(SHIPS[shipname])
                coordinates = [None for _ in range(length)]
                starting = str(coords[1]) + str(coords[2])
                coordinates[0] = starting

                if coords[0] == 'v':
                    for x in range(1, length):
                        coordinates[x] = str(coords[1]) + str(coords[2] + x)
                else:
                    for x in range(1, length):
                        coordinates[x] = str(coords[1] + x) + str(coords[2])

                final_coordinates = []
                for x in coordinates:
                    final_coordinates.append(int(x))

                self.my_coords[shipname] = tuple(final_coordinates)
            sys.stdout.write(RESET)

        # For the comparison protocol to work, we need a field modulus
        # bigger than 2**(l+1) + 2**(l+k+1), where the bit length of
        # the input numbers is l and k is the security parameter.
        # Further more, the prime must be a Blum prime (a prime p such
        # that p % 4 == 3 holds). The find_prime function lets us find
        # a suitable prime.
        l = runtime.options.bit_length
        k = runtime.options.security_parameter
        Zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))

        # We must secret share our ships with the other parties. They
        # will do the same and we end up secretly having each other's
        # ships.
        if self.is_player:
            print "I'm player 1 2 get my secret ships as"
        else:
            print "I'm here just to help with MPC. I don't affect this game."

        for shipname, coordinates in self.my_coords.items():
            if runtime.id in (1, 2):
                print '{} {}'.format(shipname, coordinates)
            for xy in coordinates:
                p1_shares, p2_shares = runtime.shamir_share([1, 2],
                                                            Zp,
                                                            number=xy)
                self.p1_shares[shipname].append(p1_shares)
                self.p2_shares[shipname].append(p2_shares)

        # TODO: we don't neat a board for our first design.
        # self.p1_board, self.p2_board = self.init_secret_board(l, k, Zp)

        # print "printin p1 %s" % self.p1_board
        # print "printing p2 %s" % self.p2_board
        # now we have secret shared the ships, and the board
        # the ships will not change, but we will have to update the
        # board and the guess for each round, as we will never learn
        # about the ships values, but only that we hit one, or didn't
        # hit one.

        # get back the array of the board with the ships in place.
        # results = self.place_ships_on_board()
        # start the game loop
        self.run_round()
Example #25
0
import sys

import viff.reactor
viff.reactor.install()
from twisted.internet import reactor
from viff.aes import bit_decompose
from viff.field import GF
from viff.runtime import create_runtime
from viff.config import load_config
from viff.util import dprint, find_prime

# Load the configuration from the player configuration files.
id, players = load_config(sys.argv[1])
input = int(sys.argv[2])
# Initialize the field we do arithmetic over.
Zp = GF(find_prime(2**256))

# Read input from the commandline.


def protocol(runtime):
    print "-" * 64

    print "Program started"

    if runtime.id == 1:
        s1 = runtime.input([1], Zp, input)
    else:
        s1 = runtime.input([1], Zp, None)

    print "entry"
Example #26
0
 def __init__(self, runtime):
     self.Zp = GF(find_prime(2 ** 64))
     self.runtime = runtime
     self.last_time = time()
     self.share_next(0)
Example #27
0
if not args:
    parser.error("you must specify a config file")

id, players = load_config(args[0])

if not 1 <= options.threshold <= len(players):
    parser.error("threshold out of range")

if options.fake:
    print "Using fake field elements"
    Field = FakeGF
else:
    Field = GF


Zp = Field(find_prime(options.modulus))
print "Using field elements (%d bit modulus)" % log(Zp.modulus, 2)


count = options.count
print "I am player %d, will %s %d numbers" % (id, options.operation, count)


# Identify the base runtime class.
if options.runtime == "OrlandiRuntime" and not OrlandiRuntime:
    print "Error: The following modules did not load correctly:"
    if not commitment:
        print "commitment"
    if not pypaillier:
        print "pypaillier"
    if not OrlandiRuntime:
Example #28
0
    def __init__(self, runtime):

        # CHANGEABLE VARIABLES
        #*******************

        self.rounds = 1
        self.decrypt_benchmark_active = True
        self.decrypt_rounds = 1
        self.bits_N = 32
        self.m = 2
        self.cyphertext = 0
        self.bound1 = 12
        self.bound2_p1 = 15000
        self.bound2_p2 = 17500
        self.bound2_p3 = 20000

        # VARIABLES NOT TO BE CHANGED
        #*******************

        self.time1 = time.clock()
        self.time2 = 0
        self.completed_rounds = 0
        self.times = []
        self.correct_decryptions = 0
        self.decrypt_time1 = 0
        self.decrypt_time2 = 0
        self.decrypt_times = []
        self.decrypt_tries = 0
        self.runtime = runtime
        self.bit_length = int(self.bits_N / 2) - 2
        self.numeric_length = int((2**self.bit_length) / 4)
        self.prime_list_b1 = self.get_primes(2, self.bound1)

        print "bit_length = " + str(self.bit_length)
        print "numeric_length = " + str(self.numeric_length)

        if self.runtime.id == 1:
            self.prime_list_b2 = self.get_primes(self.bound1, self.bound2_p1)
        elif self.runtime.id == 2:
            self.prime_list_b2 = self.get_primes(self.bound2_p1,
                                                 self.bound2_p2)
        else:
            self.prime_list_b2 = self.get_primes(self.bound2_p2,
                                                 self.bound2_p3)

        print "length of list b2 = " + str(len(self.prime_list_b2))

        self.prime_pointer = 0

        self.function_count = [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        ]
        self.function_count_names = [
            "generate_p", "generate_q", "trial_division_p",
            "check_trial_division_p", "trial_division_q",
            "check_trial_division_q", "check_n", "primality_test_N",
            "check_primality_test_N", "generate_g", "check_g", "check_v",
            "generate_z", "check_z", "generate_l", "generate_d",
            "check_decrypt"
        ]

        l = int(self.bits_N * 3.5)
        k = runtime.options.security_parameter

        self.Zp = GF(find_prime(2**(l + 1) + 2**(l + k + 1), blum=True))
        print "Zp:"
        print self.Zp.modulus

        self.generate_p()
Example #29
0
parser.add_option("-q",
                  "--quiet",
                  action="store_false",
                  help="little output after each iteration")

parser.set_defaults(modulus="30916444023318367583", verbose=False, count=4000)

# Add standard VIFF options.
Runtime.add_options(parser)

(options, args) = parser.parse_args()

if len(args) == 0:
    parser.error("you must specify a config file")

Zp = GF(find_prime(options.modulus, blum=True))
id, players = load_config(args[0])

print "I am player %d" % id

l = options.bit_length
t = (len(players) - 1) // 2
n = len(players)

# Shares of seller and buyer bids. Assume that each bidder and seller
# has secret shared the bids and encrypted them for each player. These
# have then been read, decrypted and summed up...

random.seed(0)

# Generate random bids -- we could generate numbers up to 2**l, but
Example #30
0
def main(runtime):
    tv = runtime

    # This is the value we will use in the protocol.
    millions = rand.randint(1, 200)
    print "I am Millionaire %d and I am worth %d millions." \
        % (tv.id, millions)

    # For the comparison protocol to work, we need a sufficiently
    # large field modulus.
    k = tv.options.security_parameter
    l = tv.options.bit_length
    ln = len(tv.players).bit_length()
    Zp = GF(find_prime(2**(l + k + ln + 1), blum=True))
    yield declareReturnNop(tv, Zp)

    # We must secret share our input with the other parties. They
    # will do the same and we end up with three variables
    m1, m2, m3 = tv.shamir_share([1, 2, 3], Zp, millions)

    # Now that everybody has secret shared their inputs we can
    # compare them. We compare the worth of the first millionaire
    # with the two others, and compare those two millionaires with
    # each other.
    m1_ge_m2 = m1 >= m2
    m1_ge_m3 = m1 >= m3
    m2_ge_m3 = m2 >= m3

    # The results are secret shared, so we must open them before
    # we can do anything usefull with them.
    open_m1_ge_m2 = tv.open(m1_ge_m2)
    open_m1_ge_m3 = tv.open(m1_ge_m3)
    open_m2_ge_m3 = tv.open(m2_ge_m3)

    # We will now gather the results.
    m1_ge_m2, m1_ge_m3, m2_ge_m3 = yield open_m1_ge_m2, open_m1_ge_m3, open_m2_ge_m3

    # We can establish the correct order of Millionaires 2 and 3.
    if m2_ge_m3:
        comparison = [3, 2]
    else:
        comparison = [2, 3]

    # We only have to insert Millionaire 1 in the correct spot.
    if m1_ge_m2 and m1_ge_m3:
        # Millionaire 1 is largest.
        comparison = comparison + [1]
    elif not m1_ge_m2 and not m1_ge_m3:
        # Millionaire 1 is smallest.
        comparison = [1] + comparison
    else:
        # Millionaire 1 is between the others.
        comparison = [comparison[0], 1, comparison[1]]

    print "From poorest to richest:"
    for id in comparison:
        if id == tv.id:
            print "  Millionaire %d (%d millions)" % (id, millions)
        else:
            print "  Millionaire %d" % id

    tv.shutdown()
Example #31
0
def record_stop():

    stop = time.time()
    print
    print "Total time used: %.3f sec" % (stop - start)
    '''
    if runtime.id == 1:
        f = open('time.txt', 'w')
        f.write(stop-start)
        f.close()
    '''
    print "*" * 64
    #return x


Zp = GF(find_prime(2**256, blum=True))


class Protocol:
    def __init__(self, runtime):
        self.k = 2048
        self.runtime = runtime
        self.ramdom_shares = [
            0 for i in range(self.k * int(math.log(self.k, 2)))
        ]
        self.triggers = [
            Share(self.runtime, Zp)
            for i in range(self.k * int(math.log(self.k, 2)))
        ]
        self.input = [0 for i in range(self.k)]
        self.p = find_prime(2**256, blum=True)