Ejemplo n.º 1
0
def check_proof_multi(commitment, proof, x, ys, setup):
    """
    Check a proof for a Kate commitment for an evaluation f(x w^i) = y_i
    """
    n = len(ys)
    root_of_unity = get_root_of_unity(n)
    
    # Interpolate at a coset. Note because it is a coset, not the subgroup, we have to multiply the
    # polynomial coefficients by x^i
    interpolation_polynomial = fft(ys, MODULUS, root_of_unity, True)
    interpolation_polynomial = [div(c, pow(x, i, MODULUS)) for i, c in enumerate(interpolation_polynomial)]

    # Verify the pairing equation
    #
    # e([commitment - interpolation_polynomial(s)], [1]) = e([proof],  [s^n - x^n])
    #    equivalent to
    # e([commitment - interpolation_polynomial]^(-1), [1]) * e([proof],  [s^n - x^n]) = 1_T
    #

    xn_minus_yn = b.add(setup[1][n], b.multiply(b.neg(b.G2), pow(x, n, MODULUS)))
    commitment_minus_interpolation = b.add(commitment, b.neg(lincomb(
        setup[0][:len(interpolation_polynomial)], interpolation_polynomial, b.add, b.Z1)))
    pairing_check = b.pairing(b.G2, b.neg(commitment_minus_interpolation), False)
    pairing_check *= b.pairing(xn_minus_yn, proof, False)
    pairing = b.final_exponentiate(pairing_check)
    return pairing == b.FQ12.one()
Ejemplo n.º 2
0
    def _CoreAggregateVerify(cls, PKs: Sequence[BLSPubkey],
                             messages: Sequence[bytes],
                             signature: BLSSignature, DST: bytes) -> bool:
        try:
            if len(PKs) != len(messages):
                raise ValidationError(
                    'len(PKs) != len(messages): got len(PKs)=%s, len(messages)=%s'
                    % (len(PKs), len(messages)))
            if len(PKs) < 1:
                raise ValidationError(
                    'Insufficient number of PKs: should be greater than'
                    ' or equal to 1, got %d' % len(PKs))
            signature_point = signature_to_G2(signature)
            aggregate = FQ12.one()
            for pk, message in zip(PKs, messages):
                pubkey_point = pubkey_to_G1(pk)
                message_point = hash_to_G2(message, DST, cls.xmd_hash_function)
                aggregate *= pairing(message_point,
                                     pubkey_point,
                                     final_exponentiate=False)
            aggregate *= pairing(signature_point,
                                 neg(G1),
                                 final_exponentiate=False)
            return final_exponentiate(aggregate) == FQ12.one()

        except (ValidationError, ValueError, AssertionError):
            return False
Ejemplo n.º 3
0
    def _CoreVerify(cls, PK: BLSPubkey, message: bytes,
                    signature: BLSSignature, DST: bytes) -> bool:
        try:
            # Inputs validation
            assert cls._is_valid_pubkey(PK)
            assert cls._is_valid_message(message)
            assert cls._is_valid_signature(signature)

            # Procedure
            assert cls.KeyValidate(PK)
            signature_point = signature_to_G2(signature)
            if not subgroup_check(signature_point):
                return False
            final_exponentiation = final_exponentiate(
                pairing(
                    signature_point,
                    G1,
                    final_exponentiate=False,
                ) * pairing(
                    hash_to_G2(message, DST, cls.xmd_hash_function),
                    neg(pubkey_to_G1(PK)),
                    final_exponentiate=False,
                ))
            return final_exponentiation == FQ12.one()
        except (ValidationError, ValueError, AssertionError):
            return False
Ejemplo n.º 4
0
def verify_multiple(pubkeys: Sequence[BLSPubkey], messages: Sequence[bytes],
                    signature: BLSSignature, domain: int) -> bool:
    len_msgs = len(messages)

    if len(pubkeys) != len_msgs:
        raise ValidationError(
            "len(pubkeys) (%s) should be equal to len(messages) (%s)" %
            (len(pubkeys), len_msgs))

    try:
        o = FQ12([1] + [0] * 11)
        for m_pubs in set(messages):
            # aggregate the pubs
            group_pub = Z1
            for i in range(len_msgs):
                if messages[i] == m_pubs:
                    group_pub = add(group_pub, decompress_G1(pubkeys[i]))

            o *= pairing(hash_to_G2(m_pubs, domain),
                         group_pub,
                         final_exponentiate=False)
        o *= pairing(decompress_G2(signature),
                     neg(G1),
                     final_exponentiate=False)

        final_exponentiation = final_exponentiate(o)
        return final_exponentiation == FQ12.one()
    except (ValidationError, ValueError, AssertionError):
        return False
Ejemplo n.º 5
0
    def _CoreAggregateVerify(cls, PKs: Sequence[BLSPubkey],
                             messages: Sequence[bytes],
                             signature: BLSSignature, DST: bytes) -> bool:
        try:
            # Inputs validation
            for pk in PKs:
                assert cls._is_valid_pubkey(pk)
            for message in messages:
                assert cls._is_valid_message(message)
            assert len(PKs) == len(messages)
            assert cls._is_valid_signature(signature)

            # Preconditions
            assert len(PKs) >= 1

            # Procedure
            signature_point = signature_to_G2(signature)
            if not subgroup_check(signature_point):
                return False
            aggregate = FQ12.one()
            for pk, message in zip(PKs, messages):
                assert cls.KeyValidate(pk)
                pubkey_point = pubkey_to_G1(pk)
                message_point = hash_to_G2(message, DST, cls.xmd_hash_function)
                aggregate *= pairing(message_point,
                                     pubkey_point,
                                     final_exponentiate=False)
            aggregate *= pairing(signature_point,
                                 neg(G1),
                                 final_exponentiate=False)
            return final_exponentiate(aggregate) == FQ12.one()

        except (ValidationError, ValueError, AssertionError):
            return False
Ejemplo n.º 6
0
def check_proof_single(commitment, proof, x, y, setup):
    """
    Check a proof for a Kate commitment for an evaluation f(x) = y
    """
    # Verify the pairing equation
    #
    # e([commitment - y], [1]) = e([proof],  [s - x])
    #    equivalent to
    # e([commitment - y]^(-1), [1]) * e([proof],  [s - x]) = 1_T
    #

    s_minus_x = b.add(setup[1][1], b.multiply(b.neg(b.G2), x))
    commitment_minus_y = b.add(commitment, b.multiply(b.neg(b.G1), y))

    pairing_check = b.pairing(b.G2, b.neg(commitment_minus_y), False)
    pairing_check *= b.pairing(s_minus_x, proof, False)
    pairing = b.final_exponentiate(pairing_check)

    return pairing == b.FQ12.one()
Ejemplo n.º 7
0
def verify_proof(proof, commitment_root, indices, values, setup):
    # Regenerate the same r value as above
    r = int.from_bytes(
        hash(str([commitment_root[0].n] + indices).encode('utf-8')),
        'big') % b.curve_order
    #print("r", r)
    commitments, witness = proof
    # We're making a big pairing check that essentially checks the equation:
    # sum [(P_i - y_i) * r_i * Z(everything except x_i)] = w * Z(everything) = sum [Q_i * r_i * Z(everything)]
    # where Z(set) = product: (X - s) for s in set
    pairing_check = b.FQ12.one()
    for i, (c, index, v) in enumerate(zip(commitments, indices, values)):
        for d in range(DEPTH):
            rfactor = pow(r, i * DEPTH + d, MODULUS)
            position_of_leaf = index // WIDTH**(DEPTH - d - 1)
            # Position of this leaf in the data
            sub_index = position_of_leaf % WIDTH
            #print('d', d, 'i', index, 'rfactor', rfactor, 'pos', position_of_leaf)
            # P_i
            comm = c[d - 1] if d else commitment_root
            comm = (comm[0], comm[1], b.FQ.one())
            leaf = hash_point_to_field(c[d]) if d < DEPTH - 1 else v
            #print('comm', comm, 'subindex', sub_index, 'leaf', leaf)
            # (P_i - y_i) * r_i
            comm_minus_leaf_times_r = b.multiply(
                b.add(comm, b.multiply(b.G1, MODULUS - leaf)), rfactor)
            # Z(everything except x_i)
            Z_comm = b.multiply(setup[3][sub_index],
                                field.inv(LAGRANGE_POLYS[sub_index][-1]))
            # Add the product into the pairing
            pairing_check *= b.pairing(Z_comm, comm_minus_leaf_times_r, False)
    # Z(everything)
    global_Z_comm = b.add(setup[1][WIDTH], b.neg(setup[1][0]))
    # Subtract out sum [Q_i * r_i * Z(everything)]
    pairing_check *= b.pairing(b.neg(global_Z_comm),
                               (witness[0], witness[1], b.FQ.one()), False)
    o = b.final_exponentiate(pairing_check)
    assert o == b.FQ12.one(), o
    return o == b.FQ12.one()
Ejemplo n.º 8
0
Archivo: bls.py Proyecto: jvmaia/py-evm
def verify(message: bytes, pubkey: int, signature: bytes, domain: int) -> bool:
    try:
        final_exponentiation = final_exponentiate(
            pairing(
                FQP_point_to_FQ2_point(decompress_G2(signature)),
                G1,
                final_exponentiate=False,
            ) * pairing(
                FQP_point_to_FQ2_point(hash_to_G2(message, domain)),
                neg(decompress_G1(pubkey)),
                final_exponentiate=False,
            ))
        return final_exponentiation == FQ12.one()
    except (ValidationError, ValueError, AssertionError):
        return False
Ejemplo n.º 9
0
def verify(message_hash: Hash32, pubkey: BLSPubkey, signature: BLSSignature,
           domain: int) -> bool:
    try:
        final_exponentiation = final_exponentiate(
            pairing(
                signature_to_G2(signature),
                G1,
                final_exponentiate=False,
            ) * pairing(
                hash_to_G2(message_hash, domain),
                neg(pubkey_to_G1(pubkey)),
                final_exponentiate=False,
            ))
        return final_exponentiation == FQ12.one()
    except (ValidationError, ValueError, AssertionError):
        return False
Ejemplo n.º 10
0
 def _CoreVerify(PK: BLSPubkey, message: bytes, signature: BLSSignature,
                 DST: bytes) -> bool:
     try:
         signature_point = signature_to_G2(signature)
         final_exponentiation = final_exponentiate(
             pairing(
                 signature_point,
                 G1,
                 final_exponentiate=False,
             ) * pairing(
                 hash_to_G2(message, DST),
                 neg(pubkey_to_G1(PK)),
                 final_exponentiate=False,
             ))
         return final_exponentiation == FQ12.one()
     except (ValidationError, ValueError, AssertionError):
         return False
Ejemplo n.º 11
0
    def _CoreAggregateVerify(pairs: Sequence[Tuple[BLSPubkey, bytes]],
                             signature: BLSSignature, DST: bytes) -> bool:
        try:
            signature_point = signature_to_G2(signature)
            accumulator = FQ12.one()
            for pk, message in pairs:
                pubkey_point = pubkey_to_G1(pk)
                message_point = hash_to_G2(message, DST)
                accumulator *= pairing(message_point,
                                       pubkey_point,
                                       final_exponentiate=False)
            accumulator *= pairing(signature_point,
                                   neg(G1),
                                   final_exponentiate=False)
            return final_exponentiate(accumulator) == FQ12.one()

        except (ValidationError, ValueError, AssertionError):
            return False
Ejemplo n.º 12
0
 def _CoreVerify(cls, PK: BLSPubkey, message: bytes,
                 signature: BLSSignature, DST: bytes) -> bool:
     try:
         assert BaseG2Ciphersuite.KeyValidate(PK)
         signature_point = signature_to_G2(signature)
         final_exponentiation = final_exponentiate(
             pairing(
                 signature_point,
                 G1,
                 final_exponentiate=False,
             ) * pairing(
                 hash_to_G2(message, DST, cls.xmd_hash_function),
                 neg(pubkey_to_G1(PK)),
                 final_exponentiate=False,
             ))
         return final_exponentiation == FQ12.one()
     except (ValidationError, ValueError, AssertionError):
         return False
Ejemplo n.º 13
0
def _fft(vals, modulus, roots_of_unity):
    if len(vals) <= 4 and type(vals[0]) != tuple:
        #return vals
        return _simple_ft(vals, modulus, roots_of_unity)
    elif len(vals) == 1 and type(vals[0]) == tuple:
        return vals
    L = _fft(vals[::2], modulus, roots_of_unity[::2])
    R = _fft(vals[1::2], modulus, roots_of_unity[::2])
    o = [0 for i in vals]
    for i, (x, y) in enumerate(zip(L, R)):
        y_times_root = b.multiply(
            y,
            roots_of_unity[i]) if type(y) == tuple else y * roots_of_unity[i]
        o[i] = b.add(
            x,
            y_times_root) if type(x) == tuple else (x + y_times_root) % modulus
        o[i + len(L)] = b.add(x, b.neg(y_times_root)) if type(
            x) == tuple else (x - y_times_root) % modulus
    return o
Ejemplo n.º 14
0
 def execute(cls, stack: MichelsonStack, stdout: List[str],
             context: AbstractContext):
     a = cast(
         Union[IntType, NatType, BLS12_381_FrType, BLS12_381_G1Type,
               BLS12_381_G2Type], stack.pop1())
     res_type, = dispatch_types(type(a),
                                mapping={
                                    (IntType, ): (IntType, ),
                                    (NatType, ): (IntType, ),
                                    (BLS12_381_FrType, ):
                                    (BLS12_381_FrType, ),
                                    (BLS12_381_G1Type, ):
                                    (BLS12_381_G1Type, ),
                                    (BLS12_381_G2Type, ):
                                    (BLS12_381_G2Type, )
                                })
     if issubclass(res_type, IntType):
         res = IntType.from_value(-int(a))
     else:
         res = res_type.from_point(bls12_381.neg(a.to_point()))
     stack.push(res)
     stdout.append(format_stdout(cls.prim, [a], [res]))
     return cls()
Ejemplo n.º 15
0
        if ex:
            ex = False
            fin = creator(wow[i]["Name"], "D", wow[i]["Sign"])
            r.sendline(fin)
            continue
        res1 = hasher(b"D")
        res2 = hasher(b"R")

        tt = (res2 * inverse(res1, cv)) % cv
        sigs = signature_to_G2(bytes.fromhex(wow[i]["Sign"]))
        sigs = multiply(sigs, tt)
        # do this part only if you want fake flag
        if cnt == 0:
            sigs = add(sigs, G2)
        if cnt == 1:
            sigs = add(sigs, neg(G2))
        # end
        cnt += 1
        sig = G2_to_signature(sigs).hex()
        wow[i]["Sign"] = sig
        wow[i]["Vote"] = "R"

    fin = creator(wow[i]["Name"], "R", wow[i]["Sign"])
    pub = pubkey_to_G1(bytes.fromhex(wow[i]["PK"]))
    sig = signature_to_G2(bytes.fromhex(wow[i]["Sign"]))
    print("sig check2", i, subgroup_check(sig))

    r.sendline(fin)

checker(wow, b"R")
checker(wow, b"D")
Ejemplo n.º 16
0
def verify(message: bytes, pubkey: int, signature: bytes, domain: int) -> bool:
    final_exponentiation = final_exponentiate(
        pairing(FQP_point_to_FQ2_point(decompress_G2(signature)), G1, False) *
        pairing(FQP_point_to_FQ2_point(hash_to_G2(message, domain)),
                neg(decompress_G1(pubkey)), False))
    return final_exponentiation == FQ12.one()
Ejemplo n.º 17
0
 def neg(xxx: G1Point) -> G1Point:
     return bls12_381.neg(xxx)
Ejemplo n.º 18
0
 def neg(self) -> "WrappedCurvePoint":
     return self.__class__(neg(self.py_ecc_object))
Ejemplo n.º 19
0
def singlechecker(agg_pk, agg_sig, msg):
    final_exp = final_exponentiate(
        pairing(agg_sig, G1, final_exponentiate=False) * pairing(
            multiply(G2, hasher(msg)), neg(agg_pk), final_exponentiate=False))
    isok = (final_exp == FQ12.one())
    return isok
Ejemplo n.º 20
0
ny["Sign"] = G2_to_signature(
    multiply(multiply(signature_to_G2(unhex(ny["Sign"])), invert(m1, order)),
             m2)).hex()
ny["Vote"] = "R"
assert bls.Verify(unhex(ny["PK"]), ny["Vote"].encode(), unhex(ny["Sign"]))
result[idx] = ny

xored_flag = unhex(connect(result).decode())

fake_result = result[:]
w = fake_result[idx + 1]
ny = fake_result[idx]
ny["Sign"] = G2_to_signature(
    add(signature_to_G2(unhex(ny["Sign"])),
        multiply(signature_to_G2(unhex(w["Sign"])), 2))).hex()
w["Sign"] = G2_to_signature(neg(signature_to_G2(unhex(w["Sign"])))).hex()
assert bls.Verify(bls._AggregatePKs([unhex(ny["PK"]),
                                     unhex(w["PK"])]), b'R',
                  bls.Aggregate([unhex(ny["Sign"]),
                                 unhex(w["Sign"])]))
fake_result[idx] = ny
fake_result[idx + 1] = w

fake_flag = connect(fake_result)

flag = bytexor(fake_flag, xored_flag)

print(flag)

assert flag == b'inctf{BLS_574nd5_f0r_B0n3h_Lynn_Sh4ch4m}'