Example #1
0
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)
Example #3
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 #4
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 #5
0
File: util.py Project: lu562/viff
    def setUp(self):
        """Configure and connect three Runtimes.

        .. warning::
        
           Subclasses that override this method *must* remember to do
           a super-call to it. Otherwise the runtimes wont be
           connected and :meth:`tearDown` wont work.
        """
        # Our standard 65 bit Blum prime
        self.Zp = GF(30916444023318367583)

        configs = self.generate_configs(self.num_players, self.threshold)
        self.protocols = {}

        # initialize the dictionary of random generators
        seed = rand.random()
        self.shared_rand = dict([(player_id, Random(seed))
                  for player_id in range(1, self.num_players + 1)])

        # This will be a list of Deferreds which will trigger when the
        # virtual connections between the players are closed.
        self.close_sentinels = []

        self.runtimes = []
        for id in reversed(range(1, self.num_players+1)):
            _, players = load_config(configs[id])
            self.create_loopback_runtime(id, players)

        if isinstance(reactor, ViffReactor):
            def set_loop_call(runtimes):
                self.i = 0

                # This loop call should ensure the queues of the parties are
                # processed in a more or less fair manner. This is necessary
                # because we have only one reactor for all parties here.
                def loop_call():
                    i = self.i
                    for j in range(len(runtimes)):
                        self.i = (self.i + 1) % len(runtimes)
                        runtimes[(i + j) % len(runtimes)].process_deferred_queue()

                reactor.setLoopCall(loop_call)

            gatherResults(self.runtimes).addCallback(set_loop_call)
Example #6
0
from viff.field import GF
from viff.runtime import Runtime, Share, start
from viff.config import load_config
from viff.inlinecb import viffinlinecb, returnValue, declareReturnNop
from gmpy2 import is_prime
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--tableau", help="Filename for tableau.")
parser.set_defaults(tableau="default")
Runtime.add_options(parser)
options, args = parser.parse_args()
if len(args) < 2:
    parser.error("You must specify a config file and a certificate filename.")
else:
    id, players = load_config(args[0])
    certificate_filename = args[1]


def load_tableau(filename):
    T = []
    comment_sign = "#"
    separator = "\t"
    for line in open(os.path.join("data", filename + ".teau"), "r"):
        # strip whitespace and comments
        tmp = string.split(line, comment_sign)[0]
        tmp = string.strip(tmp)
        if tmp and not tmp.startswith(comment_sign):
            # skip comments and empty lines.
            parsed_line = string.split(tmp, separator)
            T.append(map(int, parsed_line))
Example #7
0
File: main.py Project: njlr/Mixer

parser = OptionParser(usage="usage: %prog config address")

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()
Example #8
0
#
# You should have received a copy of the GNU Lesser General Public
# License along with VIFF. If not, see <http://www.gnu.org/licenses/>.

import sys

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

from viff.field import GF256
from viff.runtime import create_runtime
from viff.config import load_config
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)
Example #9
0
# License along with VIFF. If not, see <http://www.gnu.org/licenses/>.

import sys

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)
MPC STAGE
"""

value_map = {}  # holds outputs and intermidiate values between iterations

print "MPC Stage"
time1 = time()

# Initialize Viff
parser = OptionParser()
parser.set_defaults(modulus=2**65)

Runtime.add_options(parser)
options, args = parser.parse_args()
config_file = args[0]
id, parties = load_config(config_file)
parties_list = [p for p in parties]


# Sharing the inputs
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))
Example #11
0
parser.set_defaults(modulus=2**65, threshold=1, count=10,
                    runtime="PassiveRuntime", mixins="", num_players=2, prss=True,
                    operation="mul", parallel=True, fake=False,
                    args="", needed_data="")

print "*" * 64

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

(options, args) = parser.parse_args()

if not args:
    parser.error("you must specify a config file")

id, players = load_config(args[0]) #@ReservedAssignment

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)