Example #1
0
    def __init__(self, val, sig=None):
        """
        Constructor, see :py:func:`Var.__init__`

        :param val: Value for the variable; accepts floats or ints (interpr
        :param sig: See :py:func:`Var.__init__`
        """
        if isinstance(val, float): val = int(val * (1 << VarFxp.res) + 0.5)
        Var.__init__(self, val, sig)
Example #2
0
def ggh_hash_packed(plain_packed):
    bits = [
        Var(bit, True) for bit in unpackin([pl.value for pl in plain_packed])
    ]
    for bit in bits:
        bit.assert_bit()
    out = ggh_hash(bits)
    return packout(out)
Example #3
0
    def __mul__(self, other):
        if isinstance(other, VarFxp):
            i1 = self.value if self.value < vc_p / 2 else self.value - vc_p
            i2 = other.value if other.value < vc_p / 2 else other.value - vc_p
            reti = (i1 * i2 + (1 << (VarFxp.res - 1))) >> VarFxp.res
            ret = VarFxp(reti, True)

            diff = Var.__add__((1 << VarFxp.res) * ret, -Var.__mul__(
                self, other))  # mul error: should be in [-2^f,2^f]
            (diff + (1 << VarFxp.res)).assert_positive(VarFxp.res + 1)
            ((1 << VarFxp.res) - diff).assert_positive(VarFxp.res + 1)

            return ret
        elif isinstance(other, Var) or isinstance(other, int) or isinstance(
                other, long):
            return VarFxp.fromvar_noconv(Var.__mul__(self, other))
        else:
            return NotImplemented
Example #4
0
def input_bit_array(bits, nm=None):
    """
    Imports bitstring as a single input of the program. This checks that all provided values are actually bits.

    :param bits: String consisting of (at most 253) 0s and 1s (starting with most significant)
    :param nm: Name of input variable (None for automatic)
    :return: Array of bits
    """

    assert len(bits) <= 253

    bvals = [Var(int(bit), True) for bit in bits]
    for bit in bvals:
        bit.assert_bit()
    io = Var(
        sum([(1 << (len(bits) - ix - 1)) * v.value
             for (ix, v) in enumerate(bvals)]), nm)
    (io - sum([(1 << (len(bits) - ix - 1)) * v
               for (ix, v) in enumerate(bvals)])).assert_zero()

    return bvals
Example #5
0
def output_bit_array(bits, nm=None):
    """
    Exports bitstring as a single output of the QAP. This does not check that all provided values are actually bits;
    use :py:func:`pysnark.runtime.Var.assert_bit` for that.

    :param bits: Array of Vars representing bits
    :param nm: Name of output variable (None for automatic)
    :return: Bitstring representing the value
    """

    Var(
        sum([(1 << (len(bits) - ix - 1)) * v.value
             for (ix, v) in enumerate(bits)]), nm)
    return "".join([str(bit.value) for bit in bits])
Example #6
0
def lin_comb_pub(cofs, vals):
    """
    Returns linear combination of given values with given coefficients. This
    can be executed more efficiently than computing the sum by hand but
    introduces an additional equation to the program.

    :param cofs: Array of integer coefficients
    :param vals: Array of variable values
    :return: Variable representing the linear combination
    """

    ret = Var(sum([c * v.value for (c, v) in zip(cofs, vals)]), True)

    if qape != None:
        print >> qape, "*  =", " ".join([
            (c * v).strsig() for (c, v) in zip(cofs, vals)
        ]), (-1 * ret).strsig()

    return ret
Example #7
0
    def __div__(self, other):
        """
        Fixed-point division. This is an expensive operation: it costs approximately :py:func:`maxden` equations
        :param other: Other fixed-point number
        :return: Result of division
        """
        if isinstance(other, VarFxp):
            assert other.value.bit_length() <= VarFxp.maxden

            reti = int(
                float(self.value) * (1 << VarFxp.res) / float(other.value) +
                0.5)
            ret = VarFxp(reti, True)

            df = Var.__mul__(self, 1 << VarFxp.res) - Var.__mul__(
                ret, other)  # division error: should be in [-other,other]
            Var.__add__(other, -df).assert_positive(VarFxp.maxden)
            Var.__add__(other, df).assert_positive(VarFxp.maxden + 1)

            return ret
        else:
            return NotImplemented
Example #8
0
#   [email protected] to obtain a commercial license.
#
# This license extends only to copyright and does not include or grant any
# patent license or other license whatsoever.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import sys

from pysnark.runtime import Var

import pysnark.prove

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print "*** Usage: ", sys.argv[0], "val"
        sys.exit(2)

    inv = Var(int(sys.argv[1]), "in")
    print "The cube of", int(sys.argv[1]), "is", (inv*inv*inv).val("out")
Example #9
0
import pysnark.prove

if __name__ == '__main__':
    f = open('data.txt', 'r')
    success = 1
    bids = []
    commits = []
    maxBid = 0

    #Read bids and commitments from file data.txt
    for i in range(0, 10):
        x = int(f.readline())
        y = int(f.readline())
        #Verify commit y=sha256(x)
        s = sha256()
        s.update(str(x))
        if y <> int(s.hexdigest(), 16):
            success = 0
            break
#Append bids as witnesses and commits as public variables
        bids.append(x)
        commits.append(Var(int(y), 'C' + str(i)))
        #Check for the winning bid
        if maxBid < x:
            maxBid = x
    #Var(maxBid, 'Winner')
    s = sha256()
    s.update(str(maxBid))
    Var(int(s.hexdigest(), 16), 'HighestCommit')
    Var(success, 'Valid')
Example #10
0
    if len(sys.argv) == 2: sys.exit(0)

    # hash tree authentication

    if len(sys.argv) == 4 and sys.argv[3] == "--single":
        enterfn("hashtree_" + str(level) + "_single")
    elif len(sys.argv) == 4:
        print "*** Usage:", sys.argv[2], "<file> <pos> [--single]"
        sys.exit(2)
    else:
        ggh_hash_packed = subqap("ggh")(ggh_hash_packed)
        enterfn("hashtree_" + str(level))

    posi = int(sys.argv[2])
    pos = Var(posi, "pos")
    pos.assert_smaller(fsz)

    # read level 0

    quo, rem = pos.divmod(912, posi.bit_length() - 9)

    l0file = open(fname + ".l0")
    l0file.seek(2 * (quo.value * 912))
    bits = map(lambda x: Var(x, True), list(hextobits(l0file.read(2 * 912))))
    bits = bits + [Var(0, True) for _ in xrange(7296 - len(bits))]
    for bit in bits:
        bit.assert_bit(
        )  # TODO: ggh_hash_packed also assert bits, but this does not ensure that packin's input are bits!
    l0file.close()
Example #11
0
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from pysnark.runtime import Var
from pysnark.lib.array import Array

import pysnark.prove

if __name__ == '__main__':
    # simple array demo

    arr = Array([3, 4, 5, 6])
    print "array", arr, arr[2], arr[Var(2)]
    arr[2] = 1
    print "array", arr, arr[2], arr[Var(2)]

    # use array as matrix

    arr = Array([Array([1, 2]), Array([3, 4]), Array([5, 6])])
    print "matrix", arr
    print "matrix get row", arr, arr[1], arr[Var(1)]
    arr[Var(2)] = Array([7, 8])
    # arr[Var(1)][Var(1)] = 99  <- does not work because arr[Var(1)] copies the object
    arr[Var(1), Var(1)] = 99
    arr[2, 0] = 0
    print "matrix get el", arr, arr[Var(1), Var(1)]
Example #12
0
        while True:
            bit1 = str.next()
            bit2 = str.next()
            bit3 = str.next()
            bit4 = str.next()
            val = bit1 * 8 + bit2 * 4 + bit3 * 2 + bit4
            yield chr(val - 10 + ord('A') if val >= 10 else val + ord('0'))
    except StopIteration:
        pass


if __name__ == '__main__':
    bits = readhexbits(sys.stdin)

    hexin = []
    try:
        for _ in xrange(7296):
            hexin.append(bits.next())
    except StopIteration:
        hexin.extend([0] * (7296 - len(hexin)))

    #inpack = Var.vars(packin(hexin), "in")
    #print "in", inpack
    #print "out", Var.vals(ggh_hash_packed(inpack), "out")

    ins = [Var(x) for x in hexin]
    outs = ggh_hash(ins)
    print "out", len(outs), outs[:10], outs[-10:]

    exportcomm(ins, "in")
    exportcomm(outs, "out")
Example #13
0
 kmdata = Var.vars(
     [[0, 34, 0, 11], [0, 34, 0, 11], [0, 34, 0, 11], [0, 34, 0, 11],
      [0, 34, 0, 11], [0, 34, 0, 11], [0, 34, 0, 11], [0, 34, 0, 11],
      [1, 34, 0, 11], [0, 33, 0, 11], [0, 33, 0, 11], [0, 33, 1, 11],
      [0, 33, 1, 10], [0, 33, 0, 9], [1, 33, 0, 9], [0, 32, 0, 9],
      [0, 32, 0, 9], [0, 32, 0, 9], [0, 32, 0, 9], [1, 32, 0, 9],
      [0, 31, 0, 9], [0, 31, 0, 9], [0, 31, 0, 9], [1, 31, 0, 9],
      [0, 30, 0, 9], [0, 30, 0, 9], [1, 30, 0, 9], [0, 29, 1, 9],
      [0, 29, 0, 8], [0, 29, 0, 8], [0, 29, 0, 8], [0, 29, 1, 8],
      [0, 29, 0, 7], [0, 29, 0, 7], [0, 29, 0, 7], [1, 29, 0, 7],
      [1, 28, 0, 7], [0, 27, 0, 7], [0, 27, 0, 7], [0, 27, 0, 7],
      [1, 27, 0, 7], [0, 26, 0, 7], [0, 26, 0, 7], [0, 26, 0, 7],
      [0, 26, 0, 7], [0, 26, 1, 7], [1, 26, 0, 6], [0, 25, 0, 6],
      [0, 25, 0, 6], [0, 25, 0, 6], [1, 25, 0, 6], [0, 24, 0, 6],
      [0, 24, 0, 6], [0, 24, 0, 6], [0, 24, 0, 6], [0, 24, 0, 6],
      [0, 24, 0, 6], [0, 24, 0, 6], [0, 24, 0, 6], [0, 24, 0, 6],
      [0, 24, 0, 6], [0, 24, 0, 6], [0, 24, 1, 6], [1, 24, 0, 5],
      [0, 23, 0, 5], [1, 23, 0, 5], [1, 22, 1, 5], [1, 21, 0, 4],
      [0, 20, 0, 4], [0, 20, 0, 4], [0, 20, 0, 4], [0, 20, 0, 4],
      [0, 20, 0, 4], [0, 20, 0, 4], [0, 20, 0, 4], [1, 20, 0, 4],
      [0, 19, 0, 4], [0, 19, 0, 4], [0, 19, 1, 4], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3], [0, 19, 0, 3],
      [0, 19, 0, 3], [0, 19, 0, 3], [0, 18, 0, 3], [0, 17, 0, 3],
      [0, 17, 0, 3], [0, 17, 0, 2], [0, 17, 0, 2], [0, 17, 0, 2],
      [0, 17, 0, 2], [0, 17, 0, 2], [0, 15, 0, 2], [0, 15, 0, 2],
      [0, 15, 0, 2], [0, 14, 0, 2], [0, 13, 0, 2], [0, 13, 0, 2],
      [0, 12, 0, 2], [0, 12, 0, 2], [0, 12, 0, 2], [0, 12, 0, 2],
      [0, 12, 0, 2], [0, 11, 0, 2], [0, 11, 0, 2], [0, 10, 0, 2],
      [0, 10, 0, 1], [0, 10, 0, 1], [0, 10, 0, 1], [0, 10, 0, 1],
      [0, 9, 0, 1], [0, 9, 0, 1], [0, 9, 0, 1], [0, 8, 0, 1], [0, 7, 0, 1],
      [0, 6, 0, 1], [0, 5, 0, 1], [0, 5, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1],
      [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1],
      [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1],
      [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1], [0, 4, 0, 1],
      [0, 4, 0, 1], [0, 4, 0, 1]], "kmdata", 2)
Example #14
0
 def __add__(self, other):
     if isinstance(other, VarFxp):
         return VarFxp.fromvar_noconv(Var.__add__(self, other))
     else:
         return VarFxp.fromvar_noconv(
             Var.__add__(self, other * (1 << VarFxp.res)))
Example #15
0
 def val(self, nm=None):
     Var.val(self)
     return self.floatval()
Example #16
0
 def __neg__(self):
     return VarFxp.fromvar_noconv(Var.__neg__(self))