Пример #1
0
    def handle_homomorphic_builtin_function_call(self, ast: FunctionCallExpr,
                                                 func: BuiltinFunction):
        # First - same as non-homomorphic - check that argument types conform to op signature
        if not func.is_eq():
            for arg, t in zip(ast.args, func.input_types()):
                if not arg.instanceof_data_type(t):
                    raise TypeMismatchException(t,
                                                arg.annotated_type.type_name,
                                                arg)

        homomorphic_func = func.select_homomorphic_overload(
            ast.args, ast.analysis)
        if homomorphic_func is None:
            raise TypeException(
                f'Operation \'{func.op}\' requires all arguments to be accessible, '
                f'i.e. @all or provably equal to @me', ast)

        # We could perform homomorphic operations on-chain by using some Solidity arbitrary precision math library.
        # For now, keep it simple and evaluate homomorphic operations in Python and check the result in the circuit.
        func.is_private = True

        ast.annotated_type = homomorphic_func.output_type()
        func.homomorphism = ast.annotated_type.homomorphism
        expected_arg_types = homomorphic_func.input_types()

        # Check that the argument types are correct
        ast.args[:] = map(lambda arg, arg_pt: self.get_rhs(arg, arg_pt),
                          ast.args, expected_arg_types)
Пример #2
0
    def handle_builtin_function_call(self, ast: FunctionCallExpr,
                                     func: BuiltinFunction):
        if func.is_parenthesis():
            ast.annotated_type = ast.args[0].annotated_type
            return

        all_args_all_or_me = all(
            map(lambda x: x.annotated_type.is_accessible(ast.analysis),
                ast.args))
        is_public_ite = func.is_ite() and ast.args[0].annotated_type.is_public(
        )
        if all_args_all_or_me or is_public_ite:
            self.handle_unhom_builtin_function_call(ast, func)
        else:
            self.handle_homomorphic_builtin_function_call(ast, func)
Пример #3
0
 def visitAssignmentExpr(self, ctx: SolidityParser.AssignmentExprContext):
     if not self.is_expr_stmt(ctx):
         raise SyntaxException('Assignments are only allowed as statements', ctx, self.code)
     lhs = self.visit(ctx.lhs)
     rhs = self.visit(ctx.rhs)
     assert ctx.op.text[-1] == '='
     op = ctx.op.text[:-1] if ctx.op.text != '=' else ''
     if op:
         # If the assignment contains an additional operator -> replace lhs = rhs with lhs = lhs 'op' rhs
         rhs = FunctionCallExpr(BuiltinFunction(op).override(line=ctx.op.line, column=ctx.op.column), [self.visit(ctx.lhs), rhs])
         rhs.line = ctx.rhs.start.line
         rhs.column = ctx.rhs.start.column + 1
     return ast.AssignmentStatement(lhs, rhs, op)
Пример #4
0
    def _handle_crement_expr(self, ctx, kind: str):
        if not self.is_expr_stmt(ctx):
            raise SyntaxException(f'{kind}-crement expressions are only allowed as statements', ctx, self.code)
        op = '+' if ctx.op.text == '++' else '-'

        one = NumberLiteralExpr(1)
        one.line = ctx.op.line
        one.column = ctx.op.column + 1

        fct = FunctionCallExpr(BuiltinFunction(op).override(line=ctx.op.line, column=ctx.op.column), [self.visit(ctx.expr), one])
        fct.line = ctx.op.line
        fct.column = ctx.op.column + 1

        return ast.AssignmentStatement(self.visit(ctx.expr), fct, f'{kind}{ctx.op.text}')
Пример #5
0
 def visitIteExpr(self, ctx: SolidityParser.IteExprContext):
     f = BuiltinFunction('ite')
     cond = self.visit(ctx.cond)
     then_expr = self.visit(ctx.then_expr)
     else_expr = self.visit(ctx.else_expr)
     return FunctionCallExpr(f, [cond, then_expr, else_expr])
Пример #6
0
 def _visitBinaryExpr(self, ctx):
     lhs = self.visit(ctx.lhs)
     rhs = self.visit(ctx.rhs)
     f = BuiltinFunction(ctx.op.text).override(line=ctx.op.line, column=ctx.op.column)
     return FunctionCallExpr(f, [lhs, rhs])
Пример #7
0
 def visitBitwiseNotExpr(self, ctx: SolidityParser.BitwiseNotExprContext):
     f = BuiltinFunction('~').override(line=ctx.start.line, column=ctx.start.column)
     expr = self.visit(ctx.expr)
     return FunctionCallExpr(f, [expr])
Пример #8
0
 def visitSignExpr(self, ctx: SolidityParser.SignExprContext):
     f = BuiltinFunction('sign' + ctx.op.text).override(line=ctx.op.line, column=ctx.op.column)
     expr = self.visit(ctx.expr)
     return FunctionCallExpr(f, [expr])
Пример #9
0
 def visitParenthesisExpr(self, ctx: SolidityParser.ParenthesisExprContext):
     f = BuiltinFunction('parenthesis').override(line=ctx.start.line, column=ctx.start.column)
     expr = self.visit(ctx.expr)
     return FunctionCallExpr(f, [expr])
Пример #10
0
 def test_builtin_code(self):
     f = BuiltinFunction('+')
     c = FunctionCallExpr(f, [NumberLiteralExpr(0), NumberLiteralExpr(0)])
     self.assertEqual(c.code(), '0 + 0')
Пример #11
0
 def test_builtin_arity(self):
     f = BuiltinFunction('+')
     self.assertEqual(f.arity(), 2)
Пример #12
0
 def join(then_idf, else_idf):
     """Return new temporary HybridArgumentIdf with value cond ? then_idf : else_idf."""
     rhs = FunctionCallExpr(BuiltinFunction('ite'), [true_cond_for_other_branch.clone(), then_idf, else_idf]).as_type(val.t)
     return create_val_for_name_and_expr_fct(key.name, rhs)
Пример #13
0
    def handle_builtin_function_call(self, ast: FunctionCallExpr,
                                     func: BuiltinFunction):
        # handle special cases
        if func.is_ite():
            cond_t = ast.args[0].annotated_type

            # Ensure that condition is boolean
            if not cond_t.type_name.implicitly_convertible_to(
                    TypeName.bool_type()):
                raise TypeMismatchException(TypeName.bool_type(),
                                            cond_t.type_name, ast.args[0])

            res_t = ast.args[1].annotated_type.type_name.combined_type(
                ast.args[2].annotated_type.type_name, True)

            if cond_t.is_private():
                # Everything is turned private
                func.is_private = True
                a = res_t.annotate(Expression.me_expr())
            else:
                p = ast.args[1].annotated_type.combined_privacy(
                    ast.analysis, ast.args[2].annotated_type)
                a = res_t.annotate(p)
            ast.args[1] = self.get_rhs(ast.args[1], a)
            ast.args[2] = self.get_rhs(ast.args[2], a)

            ast.annotated_type = a
            return
        elif func.is_parenthesis():
            ast.annotated_type = ast.args[0].annotated_type
            return

        # Check that argument types conform to op signature
        parameter_types = func.input_types()
        if not func.is_eq():
            for arg, t in zip(ast.args, parameter_types):
                if not arg.instanceof_data_type(t):
                    raise TypeMismatchException(t,
                                                arg.annotated_type.type_name,
                                                arg)

        t1 = ast.args[0].annotated_type.type_name
        t2 = None if len(
            ast.args) == 1 else ast.args[1].annotated_type.type_name

        if len(ast.args) == 1:
            arg_t = 'lit' if ast.args[
                0].annotated_type.type_name.is_literal else t1
        else:
            assert len(ast.args) == 2
            is_eq_with_tuples = func.is_eq() and isinstance(t1, TupleType)
            arg_t = t1.combined_type(t2, convert_literals=is_eq_with_tuples)

        # Infer argument and output types
        if arg_t == 'lit':
            res = func.op_func(
                *[arg.annotated_type.type_name.value for arg in ast.args])
            if isinstance(res, bool):
                assert func.output_type() == TypeName.bool_type()
                out_t = BooleanLiteralType(res)
            else:
                assert func.output_type() == TypeName.number_type()
                out_t = NumberLiteralType(res)
            if func.is_eq():
                arg_t = t1.to_abstract_type().combined_type(
                    t2.to_abstract_type(), True)
        elif func.output_type() == TypeName.bool_type():
            out_t = TypeName.bool_type()
        else:
            out_t = arg_t

        assert arg_t is not None and (arg_t != 'lit' or not func.is_eq())

        private_args = any(map(self.has_private_type, ast.args))
        if private_args:
            assert arg_t != 'lit'
            if func.can_be_private():
                if func.is_shiftop():
                    if not ast.args[1].annotated_type.type_name.is_literal:
                        raise TypeException(
                            'Private shift expressions must use a constant (literal) shift amount',
                            ast.args[1])
                    if ast.args[1].annotated_type.type_name.value < 0:
                        raise TypeException('Cannot shift by negative amount',
                                            ast.args[1])
                if func.is_bitop() or func.is_shiftop():
                    for arg in ast.args:
                        if arg.annotated_type.type_name.elem_bitwidth == 256:
                            raise TypeException(
                                'Private bitwise and shift operations are only supported for integer types < 256 bit, '
                                'please use a smaller type', arg)

                if func.is_arithmetic():
                    for a in ast.args:
                        if a.annotated_type.type_name.elem_bitwidth == 256:
                            issue_compiler_warning(
                                func, 'Possible field prime overflow',
                                'Private arithmetic 256bit operations overflow at FIELD_PRIME.\n'
                                'If you need correct overflow behavior, use a smaller integer type.'
                            )
                            break
                elif func.is_comp():
                    for a in ast.args:
                        if a.annotated_type.type_name.elem_bitwidth == 256:
                            issue_compiler_warning(
                                func, 'Possible private comparison failure',
                                'Private 256bit comparison operations will fail for values >= 2^252.\n'
                                'If you cannot guarantee that the value stays in range, you must use '
                                'a smaller integer type to ensure correctness.'
                            )
                            break

                func.is_private = True
                p = Expression.me_expr()
            else:
                raise TypeException(
                    f'Operation \'{func.op}\' does not support private operands',
                    ast)
        else:
            p = None

        if arg_t != 'lit':
            # Add implicit casts for arguments
            arg_pt = arg_t.annotate(p)
            if func.is_shiftop() and p is not None:
                ast.args[0] = self.get_rhs(ast.args[0], arg_pt)
            else:
                ast.args[:] = map(
                    lambda argument: self.get_rhs(argument, arg_pt), ast.args)

        ast.annotated_type = out_t.annotate(p)