def vcrun(f, fp=True, cb1=None, cb2=None): """ Verifiable computation entry point. Adding this to the end of the verifiable computation will load configurations, set up communication, and run the given function f. The qap_wrapper decorator should be applied to f, and f is assumed to give as public output the computation result. """ parser = OptionParser() Runtime.add_options(parser) if cb1: cb1(parser) # callback to add custom options to parser options, args = parser.parse_args() if len(args) < 1: parser.error("you must specify a config file") myid, players = load_config(args[0]) if cb2: cb2(options, args[1:]) # handle parsing results if fp: from viff.comparison import Toft07Runtime from viff.division import DivisionSH12Mixin runtime_class = make_runtime_class(mixins=[ DivisionSH12Mixin, ProbabilisticEqualityMixin, Toft07Runtime ]) pre_runtime = create_runtime(myid, players, options.threshold, options, runtime_class) pre_runtime.addCallback(vc_init) else: pre_runtime = create_runtime(myid, players, options.threshold, options) pre_runtime.addCallback(vc_init) def callf(runtime): ret = f(runtime) retsh = [] for_each_in(Share, lambda x: retsh.append(x), ret) def printAndExit(runtime, vals): valsrev = list(reversed(vals)) retc = for_each_in(Share, lambda x: valsrev.pop(), ret) print "[ Verifiable computation result", retc, "]" if runtime.__class__.__name__ != "LocalRuntime": time.sleep(1) runtime.shutdown() return runtime if retsh != []: # print all returned values and then shut down gather_shares(retsh).addCallback( lambda x: printAndExit(runtime, x)) else: if runtime.__class__.__name__ != "LocalRuntime": time.sleep(1) runtime.shutdown() return runtime pre_runtime.addCallback(callf) reactor.run()
def __init__(self, input_map, config_file, options=None): self.config_file = config_file self.options = options self.id, self.parties = load_config(self.config_file) self.parties_list = [p for p in self.parties] self.input_map = input_map self.map_inputs_to_parties() runtime_class = make_runtime_class(mixins=[ComparisonToft07Mixin]) self.pre_runtime = create_runtime(self.id, self.parties, 1, self.options, runtime_class)
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()
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()
a_b = rt.open(rt.convert_bit_share(a, GF256)) b_b = rt.open(rt.convert_bit_share(b, GF256)) c_b = rt.open(rt.convert_bit_share(c, GF256)) x_b = rt.open(rt.convert_bit_share(x, GF256)) y_b = rt.open(rt.convert_bit_share(y, GF256)) z_b = rt.open(rt.convert_bit_share(z, GF256)) def check(result, variable, expected): if result == expected: print "%s: %s (correct)" % (variable, result) else: print "%s: %s (incorrect, expected %d)" \ % (variable, result, expected) a_b.addCallback(check, "a_b", GF256(0)) b_b.addCallback(check, "b_b", GF256(0)) c_b.addCallback(check, "c_b", GF256(0)) x_b.addCallback(check, "x_b", GF256(1)) y_b.addCallback(check, "y_b", GF256(1)) z_b.addCallback(check, "z_b", GF256(1)) rt.wait_for(a_b, b_b, c_b, x_b, y_b, z_b) pre_runtime = create_runtime(id, players, (len(players) -1)//2, runtime_class=Toft05Runtime) pre_runtime.addCallback(protocol) reactor.run()
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) dprint("c%d: %s", runtime.id, c) a = runtime.open(a) b = runtime.open(b) c = runtime.open(c) dprint("### opened a: %s ###", a) dprint("### opened b: %s ###", b) dprint("### opened c: %s ###", c) runtime.wait_for(a, b, c) pre_runtime = create_runtime(id, players, 1, runtime_class=PaillierRuntime) pre_runtime.addCallback(protocol) print "#### Starting reactor ###" reactor.run()
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]) def invert(rt): aes = AES(rt, 192, use_exponentiation=options.exponentiation) bytes = [Share(rt, GF256, GF256(random.randint(0, 255))) for i in range(options.count)] start = time.time() done = gather_shares([aes.invert(byte) for byte in bytes]) def finish(_): duration = time.time() - start print "Finished after %.3f s." % duration print "Time per inversion: %.3f ms" % (1000 * duration / options.count) rt.shutdown() done.addCallback(finish) rt = create_runtime(id, players, 1, options) rt.addCallback(invert) reactor.run()
id, players = load_config(sys.argv[1]) 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, c = runtime.prss_share([1, 2, 3], GF256, input) a = runtime.open(a) b = runtime.open(b) c = runtime.open(c) dprint("### opened a: %s ###", a) dprint("### opened b: %s ###", b) dprint("### opened c: %s ###", c) runtime.wait_for(a, b, c) pre_runtime = create_runtime(id, players, 1) pre_runtime.addCallback(protocol) print "#### Starting reactor ###" reactor.run()
# which uses four secure multiplications. We can rewrite # this to use only one secure multiplication: ai, aj = array[i], array[j] b_ai_aj = b * (ai - aj) array[i] = ai - b_ai_aj array[j] = aj + b_ai_aj bitonic_sort(0, len(array), ascending=True) return array # Run doctests if options.test: import doctest #pragma NO COVER doctest.testmod(verbose=True) #pragma NO COVER # Load configuration file. id, players = load_config(args[0]) # Create a deferred Runtime and ask it to run our protocol when ready. pre_runtime = create_runtime(id, players, 1, options, runtime_class=Toft07Runtime) pre_runtime.addCallback(Protocol) # Start the Twisted event loop. reactor.run()
c = protocol.NoisyEnc(params, sk, 1, rand.randint(0, delta)) end = default_timer() cs.append(c) cTimes.append(end - start) for time in cTimes: print "NoisyEnc took {0}".format(time) for cVal in cs: print "NoisyEnc returned type {0}, value {1}".format(type(cVal),cVal) plt.plot(cTimes, cTimes[::-1]) plt.savefig("graphs/plot{0}-b{1}.png".format(runtime.id, b)) plt.close() b *= 2 delta = (2**b) - 1 print "Sk[0] = {0}".format(sks[0].signed()) prod = protocol.AggrDec(params, sks[0], 1, cs) print "Aggrdec: {0}".format(prod) runtime.shutdown() def errorHandler(failure): print "Error handler: {0}".format(failure) theRuntime = create_runtime(id, players, 1) # Not sure if the value 1 is correct here. Can't figure it out from documentation, it might need to be (n * t) theRuntime.addCallback(doPsa) theRuntime.addErrback(errorHandler) reactor.run()
for i in range(self.k * int(math.log(self.k, 2))): open_1 = self.runtime.open(self.ramdom_shares[i]) open_1.addCallback(self.plainprint) def plainprint(self, result): print result def errorHandler(failure): print("Error: %s" % failure) # Parse command line arguments. parser = OptionParser() Toft05Runtime.add_options(parser) options, args = parser.parse_args() if len(args) == 0: parser.error("you must specify a config file") else: id, players = load_config(args[0]) # Create a deferred Runtime and ask it to run our protocol when ready. pre_runtime = create_runtime(id, players, 1, options, ActiveRuntime) pre_runtime.addCallback(Protocol) pre_runtime.addErrback(errorHandler) # Start the Twisted event loop. reactor.run()
rand = dict([(i, random.Random(i)) for i in players]) inputs = [] for i in range(count): input = dict([(j, rand[j].randint(0, pow(2, l))) for j in players]) inputs.append(input) # Fixed input for easier debugging inputs.append({1: 20, 2: 25, 3: 0}) print "I am player %d, will compare %d numbers" % (id, len(inputs)) bits = [] for input in inputs: x, y, z = rt.shamir_share([1, 2, 3], Zp, input[id]) bit = rt.open(x >= y) bit.addCallback(lambda b: b == GF256(1)) bit.addCallback(lambda b, x, y: "%3d >= %3d: %-5s (%s)" \ % (x, y, b, b == (x >= y)), input[1], input[2]) dprint("%s", bit) bits.append(bit) results = gatherResults(bits) results.addCallback(lambda _: rt.shutdown()) pre_runtime = create_runtime(id, players, 1, runtime_class=Toft05Runtime) pre_runtime.addCallback(protocol) reactor.run()
print "Preprocessing done..." print "Making %d comparisons" % count record_start() bits = [] while len(shares) > 1: a = shares.pop(0) b = shares.pop(0) c = rt.greater_than_equal_online(a, b, preproc.pop(), Zp) bits.append(c) stop = DeferredList(bits) stop.addCallback(record_stop) stop.addCallback(finish) # TODO: it would be nice it the results were checked # automatically, but it needs to be done without adding # overhead to the benchmark. # We want to wait until all numbers have been shared and # preprocessing has been performed dl = gatherResults(shares + pseudoPreproc) dl.addCallback(run_test) pre_runtime = create_runtime(id, players, (len(players) -1)//2, options, Toft07Runtime) pre_runtime.addCallback(protocol) print "#### Starting reactor ###" reactor.run()
import sys import viff.reactor viff.reactor.install() from twisted.internet import reactor from twisted.internet.defer import gatherResults from viff.field import GF from viff.runtime import create_runtime from viff.config import load_config from viff.util import dprint id, players = load_config(sys.argv[1]) print "I am player %d" % id Z31 = GF(31) def protocol(rt): elements = [rt.open(rt.prss_share_random(Z31)) for _ in range(10)] result = gatherResults(elements) dprint("bits: %s", result) rt.wait_for(result) pre_runtime = create_runtime(id, players, (len(players) -1)//2) pre_runtime.addCallback(protocol) reactor.run()
p2_hit_s1 = results[1] p1_hit_s2 = results[2] p2_hit_s2 = results[3] p1_hit_s3 = results[4] p2_hit_s3 = results[5] if p1_hit_s1 or p1_hit_s2 or p1_hit_s3: self.lives[0] = self.lives[0] - 1 if p2_hit_s1 or p2_hit_s2 or p2_hit_s3: self.lives[1] = self.lives[1] - 1 # Parse command line arguments. parser = OptionParser() Toft05Runtime.add_options(parser) options, args = parser.parse_args() if len(args) == 0: parser.error("you must specify a config file") else: id, players = load_config(args[0]) # print players # print options # Create a deferred Runtime and ask it to run our protocol when ready. runtime_class = make_runtime_class( mixins=[Toft05Runtime, ProbabilisticEqualityMixin]) pre_runtime = create_runtime(id, players, 1, options, runtime_class) pre_runtime.addCallback(Protocol) # Start the Twisted event loop. reactor.run()
# Parse command line arguments. parser = OptionParser(usage=__doc__) parser.add_option("--modulus", help="lower limit for modulus (can be an expression)") parser.add_option("-n", "--number", type="int", help="number to compare") parser.set_defaults(modulus=2**65, number=None) 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)) # Load configuration file. id, players = load_config(args[0]) runtime_class = make_runtime_class(mixins=[ProbabilisticEqualityMixin]) pre_runtime = create_runtime(id, players, 1, options, runtime_class) pre_runtime.addCallback(Protocol) # Start the Twisted event loop. reactor.run()
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) dprint("c%d: %s", runtime.id, c) a = runtime.open(a) b = runtime.open(b) c = runtime.open(c) dprint("### opened a: %s ###", a) dprint("### opened b: %s ###", b) dprint("### opened c: %s ###", c) runtime.wait_for(a, b, c) pre_runtime = create_runtime(id, players, 1, runtime_class=PaillierRuntime) pre_runtime.addCallback(protocol) print "#### Starting reactor ###" reactor.run()
from viff.field import GF from viff.runtime import create_runtime, Runtime from viff.config import load_config parser = OptionParser() parser.add_option("-c", "--count", type="int", default=100, help="number of multiplications") Runtime.add_options(parser) (options, args) = parser.parse_args() Zp = GF(1031) id, players = load_config(args[0]) def protocol(rt): def got_result(result): print "Product:", result rt.shutdown() x = rt.prss_share_random(Zp) for _ in xrange(options.count): x = x * x x = rt.open(x) x.addCallback(got_result) pre_runtime = create_runtime(id, players, 1, options) pre_runtime.addCallback(protocol) reactor.run()
def results_ready(opened_results): print "Results Ready" for i in range(len(opened_results)): node_name = results[i] value_map[node_name] = opened_results[ i] if opened_results[i] < INFINITY else float("inf") gathered = gather_shares(gathered) gathered.addCallback(results_ready) runtime.schedule_callback(gathered, lambda _: runtime.shutdown()) print "Opening" except: import traceback traceback.print_exc() # Intialize Runtime runtime_class = make_runtime_class(mixins=[ComparisonToft07Mixin]) pre_runtime = create_runtime(id, parties, 1, options, runtime_class) pre_runtime.addCallback(begin_MPC) # Start the Twisted event loop. reactor.run() print "Evaluated!!" time2 = time() print "MPC TIME: " + str(time2 - time1) print "TOTAL TIME: " + str(time2 - time_)
preproc = rt.preprocess(program_desc) def fin(_): print "Finished preprocessing after %f sec." % (time.time() - start) return rt preproc.addCallback(fin) rt.schedule_complex_callback(preproc, share_key) else: share_key(rt) if options.active: from viff.active import ActiveRuntime runtime_class = ActiveRuntime else: from viff.passive import PassiveRuntime runtime_class = PassiveRuntime try: threshold = len(players) - len(players[id].keys.keys()[0]) except IndexError: print >>sys.stderr, "PRSS keys in config file missing." sys.exit(1) rt = create_runtime(id, players, threshold, options, runtime_class) if options.preproc: rt.addCallback(preprocess) else: rt.addCallback(share_key) reactor.run()
# 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 == self.runtime.id: print " Millionaire %d (%d millions)" % (id, self.millions) else: print " Millionaire %d" % id # Parse command line arguments. parser = OptionParser() Toft05Runtime.add_options(parser) options, args = parser.parse_args() if len(args) == 0: parser.error("you must specify a config file") else: id, players = load_config(args[0]) # Create a deferred Runtime and ask it to run our protocol when ready. pre_runtime = create_runtime(id, players, 1, options, Toft05Runtime) pre_runtime.addCallback(Protocol) # Start the Twisted event loop. reactor.run()
output = runtime.open(output) dprint("output %s", output) actual = runtime.open(arr[9 * 3 + 2]) dprint("actual %s", actual) print "Time taken: %.2f sec" % (time() - start_time) runtime.wait_for(output) # runtime.schedule_callback(results, lambda _: runtime.synchronize()) # runtime.schedule_callback(results, lambda _: runtime.shutdown()) def errorHandler(failure): print "Error: %s" % failure # Create a runtime runtime_class = make_runtime_class(runtime_class=Toft05Runtime, mixins=[ProbabilisticEqualityMixin]) pre_runtime = create_runtime(id, players, 1, None, runtime_class) pre_runtime.addCallback(protocol) # This error handler will enable debugging by capturing # any exceptions and print them on Standard Out. pre_runtime.addErrback(errorHandler) print "#### Starting reactor ###" reactor.run()
from viff.util import dprint id, players = load_config(sys.argv[1]) 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, c = runtime.prss_share([1, 2, 3], GF256, input) a = runtime.open(a) b = runtime.open(b) c = runtime.open(c) dprint("### opened a: %s ###", a) dprint("### opened b: %s ###", b) dprint("### opened c: %s ###", c) runtime.wait_for(a, b, c) pre_runtime = create_runtime(id, players, 1) pre_runtime.addCallback(protocol) print "#### Starting reactor ###" reactor.run()
import viff.reactor viff.reactor.install() from twisted.internet import reactor from twisted.internet.defer import gatherResults from viff.math.field import GF from viff.runtime import create_runtime from viff.config import load_config from viff.utils.util import dprint id, players = load_config(sys.argv[1]) print "I am player %d" % id Z31 = GF(31) def protocol(rt): elements = [rt.open(rt.prss_share_random(Z31)) for _ in range(10)] result = gatherResults(elements) dprint("bits: %s", result) rt.wait_for(result) pre_runtime = create_runtime(id, players, (len(players) - 1) // 2) pre_runtime.addCallback(protocol) reactor.run()
# ai = b * array[j] + (1-b) * array[i] # aj = b * array[i] + (1-b) * array[j] # # which uses four secure multiplications. We can rewrite # this to use only one secure multiplication: ai, aj = array[i], array[j] b_ai_aj = b * (ai - aj) array[i] = ai - b_ai_aj array[j] = aj + b_ai_aj bitonic_sort(0, len(array), ascending=True) return array # Run doctests if options.test: import doctest # pragma NO COVER doctest.testmod(verbose=True) # pragma NO COVER # Load configuration file. id, players = load_config(args[0]) # Create a deferred Runtime and ask it to run our protocol when ready. pre_runtime = create_runtime(id, players, 1, options, runtime_class=Toft07Runtime) pre_runtime.addCallback(Protocol) # Start the Twisted event loop. reactor.run()
actual_mixins = [mixins[mixin] for mixin in options.mixins.split(',')] # Identify the operation and it mixin dependencies. operation = operations[options.operation][0] actual_mixins += operations[options.operation][1] operation_arity = operations[options.operation][2] print "Using the base runtime: %s." % base_runtime_class if actual_mixins: print "With the following mixins:" for mixin in actual_mixins: print "- %s" % mixin.__name__ runtime_class = make_runtime_class(base_runtime_class, actual_mixins) pre_runtime = create_runtime(id, players, options.threshold, options, runtime_class) def update_args(runtime, options): args = {} if options.args: for arg in options.args.split(','): id, value = arg.split('=') args[id] = long(value) runtime.set_args(args) return runtime pre_runtime.addCallback(update_args, options) if options.parallel:
if low + 1 < high: mid = (low + high) // 2 if options.verbose: debug(low, mid, high) result = rt.open(buyer_bids[mid] >= seller_bids[mid]) result.addCallback(output, "%s >= %s: %%s" % (B[mid], S[mid])) result.addCallback(branch, low, mid, high) return result else: if options.verbose: debug(low, mid, high) return low def check_result(result): expected = max([i for i, (b, s) in enumerate(zip(B, S)) if b > s]) if result == expected: print "Result: %d (correct)" % result else: print "Result: %d (incorrect, expected %d)" % (result, expected) result = branch(0, 0, len(seller_bids), 0) result.addCallback(check_result) result.addCallback(lambda _: reactor.stop()) pre_runtime = create_runtime(id, players, t, options) pre_runtime.addCallback(auction) reactor.run()
options, args = parser.parse_args() if len(args) != 3: parser.error("Wrong number of arguments. Use config, target address, output file") parser = OptionParser() options, args = parser.parse_args() id, players = load_config(args[0]) address = args[1] out = args[2] protocol = Protocol(id, address, random.SystemRandom().getrandbits(32), out) pre_runtime = create_runtime(id, players, (len(players) - 1)//2, runtime_class=Toft07Runtime) pre_runtime.addCallback(protocol.run) pre_runtime.addErrback(errorHandler) reactor.run()
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 == self.runtime.id: print " Millionaire %d (%d millions)" % (id, self.millions) else: print " Millionaire %d" % id # Parse command line arguments. parser = OptionParser() Toft05Runtime.add_options(parser) options, args = parser.parse_args() if len(args) == 0: parser.error("you must specify a config file") else: id, players = load_config(args[0]) # Create a deferred Runtime and ask it to run our protocol when ready. pre_runtime = create_runtime(id, players, 1, options, Toft05Runtime) pre_runtime.addCallback(Protocol) # Start the Twisted event loop. reactor.run()