Exemple #1
0
    def get_compiled_contracts(self, source_file_paths, import_remappings):
        try:
            from viper import compiler
        except ImportError:
            raise ImportError(
                'viper needs to be installed to use ViperBackend' +
                ' as compiler backend.'
            )

        self.logger.debug("Compiler Settings: %s", pprint.pformat(self.compiler_settings))

        compiled_contracts = []

        for contract_path in source_file_paths:
            code = open(contract_path).read()
            abi = compiler.mk_full_signature(code)
            bytecode = '0x' + compiler.compile(code).hex()
            bytecode_runtime = '0x' + compiler.compile(code, bytecode_runtime=True).hex()
            compiled_contracts.append({
                'name': os.path.basename(contract_path).split('.')[0],
                'abi': abi,
                'bytecode': bytecode,
                'bytecode_runtime': bytecode_runtime,
                'linkrefs': [],
                'linkrefs_runtime': [],
                'source_path': contract_path
            })

        return compiled_contracts
Exemple #2
0
def test_as_wei_fail(bad_code):
    if isinstance(bad_code, tuple):
        with raises(bad_code[1]):
            compiler.compile(bad_code[0])
    else:
        with raises(VariableDeclarationException):
            compiler.compile(bad_code)
Exemple #3
0
def must_fail(code, exception_type):
    success = False
    try:
        compiler.compile(code)
    except exception_type as e:
        print(e)
        success = True
    assert success
Exemple #4
0
def test_logging_fail(bad_code):

    if isinstance(bad_code, tuple):
        with raises(bad_code[1]):
            compiler.compile(bad_code[0])
    else:
        with raises(TypeMismatchException):
            compiler.compile(bad_code)
def test_undef_toplevel():
    code = """
@public
def foo():
    x = bar(55)
    """
    with raises(StructureException) as ex:
        compiler.compile(code)
    assert "Not a top-level function: bar" in str(ex.value)
Exemple #6
0
def test_bytecode_runtime():
    code = """
@public
def a() -> bool:
    return true
    """

    bytecode = compiler.compile(code)
    bytecode_runtime = compiler.compile(code, bytecode_runtime=True)

    assert len(bytecode) > len(bytecode_runtime)
    assert bytecode_runtime in bytecode
def test_undef_suggestion():
    code = """
@public
def bar(x: num) -> num:
    return 3 * x

@public
def foo() -> num:
    return bar(20)
    """
    with raises(StructureException) as ex:
        compiler.compile(code)
    assert "Not a top-level function: bar" in str(ex.value)
    assert "Did you mean self.bar?" in str(ex.value)
def compile_to_bytecode(code: str):
    try:
        result = '0x' + compiler.compile(code).hex()
    except Exception as e:
        return jsonify(error=get_error(e)), 400

    return jsonify(result=result)
Exemple #9
0
 def contract(self,
              sourcecode,
              args=[],
              sender=k0,
              value=0,
              language=None,
              l=None,
              startgas=STARTGAS,
              gasprice=GASPRICE):
     assert not (l and language)
     language = l or language
     if language == 'evm':
         assert len(args) == 0
         return self.tx(sender=sender,
                        to=b'',
                        value=value,
                        data=sourcecode,
                        startgas=startgas,
                        gasprice=gasprice)
     else:
         compiler = languages[language]
         interface = compiler.mk_full_signature(sourcecode)
         ct = ContractTranslator(interface)
         code = compiler.compile(sourcecode) + (
             ct.encode_constructor_arguments(args) if args else b'')
         addr = self.tx(sender=sender,
                        to=b'',
                        value=value,
                        data=code,
                        startgas=startgas,
                        gasprice=gasprice)
         return ABIContract(self, ct, addr)
Exemple #10
0
def compile_all(code: str):
    try:
        result_abi = compiler.mk_full_signature(code)
    except Exception as e:
        return jsonify(error=get_error(e)), 400

    try:
        result_ir = optimizer.optimize(parse_to_lll(code))
    except Exception as e:
        return jsonify(error=get_error(e)), 400

    try:
        result_bytecode = '0x' + compiler.compile(code).hex()
    except Exception as e:
        return jsonify(error=get_error(e)), 400

    return jsonify(result_abi=result_abi,
                   result_ir=str(result_ir),
                   result_bytecode=result_bytecode)
Exemple #11
0
def install_prerequisite_and_casper():
    # Install RLP decoder library
    rlp_decoder_address = inject_tx(
        '0xf90237808506fc23ac00830330888080b902246102128061000e60003961022056600060007f010000000000000000000000000000000000000000000000000000000000000060003504600060c082121515585760f882121561004d5760bf820336141558576001905061006e565b600181013560f783036020035260005160f6830301361415585760f6820390505b5b368112156101c2577f010000000000000000000000000000000000000000000000000000000000000081350483602086026040015260018501945060808112156100d55760018461044001526001828561046001376001820191506021840193506101bc565b60b881121561014357608081038461044001526080810360018301856104600137608181141561012e5760807f010000000000000000000000000000000000000000000000000000000000000060018401350412151558575b607f81038201915060608103840193506101bb565b60c08112156101b857600182013560b782036020035260005160388112157f010000000000000000000000000000000000000000000000000000000000000060018501350402155857808561044001528060b6838501038661046001378060b6830301830192506020810185019450506101ba565bfe5b5b5b5061006f565b601f841315155857602060208502016020810391505b6000821215156101fc578082604001510182826104400301526020820391506101d8565b808401610420528381018161044003f350505050505b6000f31b2d4f'
    )

    # Install sig hasher
    c.tx(t.k9, '0x6e7406512b244843c1171840dfcd3d7532d979fe', 7291200000000000)
    sighasher_address = inject_tx(
        '0xf9016d808506fc23ac0083026a508080b9015a6101488061000e6000396101565660007f01000000000000000000000000000000000000000000000000000000000000006000350460f8811215610038576001915061003f565b60f6810391505b508060005b368312156100c8577f01000000000000000000000000000000000000000000000000000000000000008335048391506080811215610087576001840193506100c2565b60b881121561009d57607f8103840193506100c1565b60c08112156100c05760b68103600185013560b783036020035260005101840193505b5b5b50610044565b81810360388112156100f4578060c00160005380836001378060010160002060e052602060e0f3610143565b61010081121561010557600161011b565b6201000081121561011757600261011a565b60035b5b8160005280601f038160f701815382856020378282600101018120610140526020610140f350505b505050505b6000f31b2d4f'
    )

    # Install purity checker
    global purity_checker_address
    purity_checker_address = inject_tx(
        '0xf90467808506fc23ac00830583c88080b904546104428061000e60003961045056600061033f537c0100000000000000000000000000000000000000000000000000000000600035047f80010000000000000000000000000000000000000030ffff1c0e00000000000060205263a1903eab8114156103f7573659905901600090523660048237600435608052506080513b806020015990590160009052818152602081019050905060a0526080513b600060a0516080513c6080513b8060200260200159905901600090528181526020810190509050610100526080513b806020026020015990590160009052818152602081019050905061016052600060005b602060a05103518212156103c957610100601f8360a051010351066020518160020a161561010a57fe5b80606013151561011e57607f811315610121565b60005b1561014f5780607f036101000a60018460a0510101510482602002610160510152605e8103830192506103b2565b60f18114801561015f5780610164565b60f282145b905080156101725780610177565b60f482145b9050156103aa5760028212151561019e5760606001830360200261010051015112156101a1565b60005b156101bc57607f6001830360200261010051015113156101bf565b60005b156101d157600282036102605261031e565b6004821215156101f057600360018303602002610100510151146101f3565b60005b1561020d57605a6002830360200261010051015114610210565b60005b1561022b57606060038303602002610100510151121561022e565b60005b1561024957607f60038303602002610100510151131561024c565b60005b1561025e57600482036102605261031d565b60028212151561027d57605a6001830360200261010051015114610280565b60005b1561029257600282036102605261031c565b6002821215156102b157609060018303602002610100510151146102b4565b60005b156102c657600282036102605261031b565b6002821215156102e65760806001830360200261010051015112156102e9565b60005b156103035760906001830360200261010051015112610306565b60005b1561031857600282036102605261031a565bfe5b5b5b5b5b604060405990590160009052600081526102605160200261016051015181602001528090502054156103555760016102a052610393565b60306102605160200261010051015114156103755760016102a052610392565b60606102605160200261010051015114156103915760016102a0525b5b5b6102a051151561039f57fe5b6001830192506103b1565b6001830192505b5b8082602002610100510152600182019150506100e0565b50506001604060405990590160009052600081526080518160200152809050205560016102e05260206102e0f35b63c23697a8811415610440573659905901600090523660048237600435608052506040604059905901600090526000815260805181602001528090502054610300526020610300f35b505b6000f31b2d4f'
    )

    # Check that the RLP decoding library and the sig hashing library are "pure"
    assert utils.big_endian_to_int(
        c.tx(t.k0, purity_checker_address, 0,
             ct.encode('submit', [rlp_decoder_address]))) == 1
    assert utils.big_endian_to_int(
        c.tx(t.k0, purity_checker_address, 0,
             ct.encode('submit', [sighasher_address]))) == 1

    k1_valcode_addr = c.tx(t.k0, "", 0, mk_validation_code(t.a0))
    assert utils.big_endian_to_int(
        c.tx(t.k0, purity_checker_address, 0,
             ct.encode('submit', [k1_valcode_addr]))) == 1
    c.mine()

    # Install Casper
    casper_code = open('simple_casper.v.py').read().replace('0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6', utils.checksum_encode(k1_valcode_addr)) \
                                               .replace('0x476c2cA9a7f3B16FeCa86512276271FAf63B6a24', utils.checksum_encode(sighasher_address)) \
                                               .replace('0xD7a3BD6C9eA32efF147d067f907AE6b22d436F91', utils.checksum_encode(purity_checker_address))
    print('Casper code length', len(compiler.compile(casper_code)))
    casper_instance = c.contract(casper_code,
                                 language='viper',
                                 startgas=4300000)
    print('Gas consumed to launch Casper', c.head_state.receipts[-1].gas_used)
    c.mine()
    return casper_instance
Exemple #12
0
def compile():
    source = request.form.get('source', '')
    try:
        abi = compiler.mk_full_signature(source)
        abi_code = 200
    except Exception as e:
        abi = str(e)
        abi_code = 500
    try:
        json_abi = json.dumps(compiler.mk_full_signature(source))
        json_abi_code = 200
    except Exception as e:
        json_abi = str(e)
        json_abi_code = 500
    try:
        bytecode = '0x' + compiler.compile(source).hex()
        bytecode_code = 200
    except Exception as e:
        bytecode = str(e)
        bytecode_code = 500
    try:
        ir = optimizer.optimize(parse_to_lll(source))
        ir = str(ir)
        ir_code = 200
    except Exception as e:
        ir = str(e)
        ir_code = 500

    r_dict = {
        'result': {
            'abi': abi,
            'abi_code': abi_code,
            'json': json_abi,
            'json_code': json_abi_code,
            'bytecode': bytecode,
            'bytecode_code': bytecode_code,
            'lll': ir,
            'lll_code': ir_code
        }
    }
    return make_response(jsonify(r_dict), 200)
Exemple #13
0
def casper_chain(test_chain, casper_config, casper_code, casper_ct,
                 dependency_transactions, sig_hasher_address,
                 purity_checker_address, base_sender_privkey):
    init_transactions = []
    nonce = 0
    # Create transactions for instantiating RLP decoder, sig hasher and purity checker,
    # plus transactions for feeding the one-time accounts that generate those transactions
    for tx in dependency_transactions:
        fund_gas_tx = Transaction(nonce, GAS_PRICE, 500000, tx.sender,
                                  tx.startgas * tx.gasprice + tx.value,
                                  '').sign(base_sender_privkey)
        init_transactions.append(fund_gas_tx)
        init_transactions.append(tx)
        nonce += 1

    for tx in init_transactions:
        if test_chain.head_state.gas_used + tx.startgas > test_chain.head_state.gas_limit:
            test_chain.mine(1)
        test_chain.direct_tx(tx)

    test_chain.mine(1)

    # NOTE: bytecode cannot be compiled before RLP Decoder is deployed to chain
    # otherwise, viper compiler cannot properly embed RLP decoder address
    casper_bytecode = compiler.compile(casper_code)

    init_args = casper_ct.encode_constructor_arguments([
        casper_config["epoch_length"], casper_config["withdrawal_delay"],
        casper_config["owner"], sig_hasher_address, purity_checker_address,
        casper_config["base_interest_factor"],
        casper_config["base_penalty_factor"], casper_config["min_deposit_size"]
    ])

    deploy_code = casper_bytecode + (init_args)
    casper_tx = Transaction(nonce, GAS_PRICE, 5000000, b'', 0,
                            deploy_code).sign(base_sender_privkey)
    test_chain.direct_tx(casper_tx)
    test_chain.mine(1)
    return test_chain
def test_block_success(good_code):
    assert compiler.compile(good_code) is not None
def test_variable_decleration_exception(bad_code):
    with raises(VariableDeclarationException):
        compiler.compile(bad_code)
def test_variable_decleration_exception(bad_code):
    with raises(NonPayableViolationException):
        compiler.compile(bad_code)
Exemple #17
0
def test_compilation_fails_with_exception(bad_code, exception_type):
    with raises(exception_type):
        compiler.compile(bad_code)
Exemple #18
0
def test_compilation_succeeds(good_code):
    assert compiler.compile(good_code) is not None
Exemple #19
0
def test_fail_(bad_code):

    with raises(VariableDeclarationException):
        compiler.compile(bad_code)
Exemple #20
0
def test_valid_blockscope(good_code):
    assert compiler.compile(good_code) is not None
    'type': 'function',
    'constant': False,
    'inputs': [{
        'name': 'addr',
        'type': 'address'
    }],
    'outputs': [{
        'name': 'out',
        'type': 'bool'
    }]
}]
viper_rlp_decoder_address = viper_rlp_decoder_tx.creates
sig_hasher_address = sig_hasher_tx.creates

casper_code = open('simple_casper.v.py').read()
casper_bytecode = compiler.compile(casper_code)
casper_abi = compiler.mk_full_signature(casper_code)
casper_ct = ContractTranslator(casper_abi)


def custom_chain(tester,
                 alloc={},
                 genesis_gas_limit=4712388,
                 min_gas_limit=5000,
                 startgas=3141592):
    # alloc
    for i in range(9):
        alloc[utils.int_to_addr(i)] = {'balance': 1}
    # genesis
    from ethereum.genesis_helpers import mk_basic_state
    header = {
Exemple #22
0
def test_range_success(good_code):
    assert compiler.compile(good_code) is not None
Exemple #23
0
def test_exponent_success(good_code):
    assert compiler.compile(good_code) is not None
    "base_penalty_factor": 0.002
}

viper_rlp_decoder_tx = rlp.hex_decode("0xf90237808506fc23ac00830330888080b902246102128061000e60003961022056600060007f010000000000000000000000000000000000000000000000000000000000000060003504600060c082121515585760f882121561004d5760bf820336141558576001905061006e565b600181013560f783036020035260005160f6830301361415585760f6820390505b5b368112156101c2577f010000000000000000000000000000000000000000000000000000000000000081350483602086026040015260018501945060808112156100d55760018461044001526001828561046001376001820191506021840193506101bc565b60b881121561014357608081038461044001526080810360018301856104600137608181141561012e5760807f010000000000000000000000000000000000000000000000000000000000000060018401350412151558575b607f81038201915060608103840193506101bb565b60c08112156101b857600182013560b782036020035260005160388112157f010000000000000000000000000000000000000000000000000000000000000060018501350402155857808561044001528060b6838501038661046001378060b6830301830192506020810185019450506101ba565bfe5b5b5b5061006f565b601f841315155857602060208502016020810391505b6000821215156101fc578082604001510182826104400301526020820391506101d8565b808401610420528381018161044003f350505050505b6000f31b2d4f", Transaction)

sig_hasher_tx = rlp.hex_decode("0xf9016d808506fc23ac0083026a508080b9015a6101488061000e6000396101565660007f01000000000000000000000000000000000000000000000000000000000000006000350460f8811215610038576001915061003f565b60f6810391505b508060005b368312156100c8577f01000000000000000000000000000000000000000000000000000000000000008335048391506080811215610087576001840193506100c2565b60b881121561009d57607f8103840193506100c1565b60c08112156100c05760b68103600185013560b783036020035260005101840193505b5b5b50610044565b81810360388112156100f4578060c00160005380836001378060010160002060e052602060e0f3610143565b61010081121561010557600161011b565b6201000081121561011757600261011a565b60035b5b8160005280601f038160f701815382856020378282600101018120610140526020610140f350505b505050505b6000f31b2d4f", Transaction)

purity_checker_tx = rlp.hex_decode("0xf90467808506fc23ac00830583c88080b904546104428061000e60003961045056600061033f537c0100000000000000000000000000000000000000000000000000000000600035047f80010000000000000000000000000000000000000030ffff1c0e00000000000060205263a1903eab8114156103f7573659905901600090523660048237600435608052506080513b806020015990590160009052818152602081019050905060a0526080513b600060a0516080513c6080513b8060200260200159905901600090528181526020810190509050610100526080513b806020026020015990590160009052818152602081019050905061016052600060005b602060a05103518212156103c957610100601f8360a051010351066020518160020a161561010a57fe5b80606013151561011e57607f811315610121565b60005b1561014f5780607f036101000a60018460a0510101510482602002610160510152605e8103830192506103b2565b60f18114801561015f5780610164565b60f282145b905080156101725780610177565b60f482145b9050156103aa5760028212151561019e5760606001830360200261010051015112156101a1565b60005b156101bc57607f6001830360200261010051015113156101bf565b60005b156101d157600282036102605261031e565b6004821215156101f057600360018303602002610100510151146101f3565b60005b1561020d57605a6002830360200261010051015114610210565b60005b1561022b57606060038303602002610100510151121561022e565b60005b1561024957607f60038303602002610100510151131561024c565b60005b1561025e57600482036102605261031d565b60028212151561027d57605a6001830360200261010051015114610280565b60005b1561029257600282036102605261031c565b6002821215156102b157609060018303602002610100510151146102b4565b60005b156102c657600282036102605261031b565b6002821215156102e65760806001830360200261010051015112156102e9565b60005b156103035760906001830360200261010051015112610306565b60005b1561031857600282036102605261031a565bfe5b5b5b5b5b604060405990590160009052600081526102605160200261016051015181602001528090502054156103555760016102a052610393565b60306102605160200261010051015114156103755760016102a052610392565b60606102605160200261010051015114156103915760016102a0525b5b5b6102a051151561039f57fe5b6001830192506103b1565b6001830192505b5b8082602002610100510152600182019150506100e0565b50506001604060405990590160009052600081526080518160200152809050205560016102e05260206102e0f35b63c23697a8811415610440573659905901600090523660048237600435608052506040604059905901600090526000815260805181602001528090502054610300526020610300f35b505b6000f31b2d4f", Transaction)

purity_checker_address = purity_checker_tx.creates
purity_checker_abi = [{'name': 'check(address)', 'type': 'function', 'constant': True, 'inputs': [{'name': 'addr', 'type': 'address'}], 'outputs': [{'name': 'out', 'type': 'bool'}]}, {'name': 'submit(address)', 'type': 'function', 'constant': False, 'inputs': [{'name': 'addr', 'type': 'address'}], 'outputs': [{'name': 'out', 'type': 'bool'}]}]
viper_rlp_decoder_address = viper_rlp_decoder_tx.creates
sig_hasher_address = sig_hasher_tx.creates

casper_code = open('simple_casper.v.py').read()
casper_bytecode = compiler.compile(casper_code)
casper_abi = compiler.mk_full_signature(casper_code)
casper_ct = ContractTranslator(casper_abi)

def custom_chain(tester, alloc={}, genesis_gas_limit=4712388, min_gas_limit=5000, startgas=3141592):
    # alloc
    for i in range(9):
        alloc[utils.int_to_addr(i)] = {'balance': 1}
    # genesis
    from ethereum.genesis_helpers import mk_basic_state
    header = {
        "number": 0, "gas_limit": genesis_gas_limit,
        "gas_used": 0, "timestamp": 1467446877, "difficulty": 1,
        "uncles_hash": '0x'+utils.encode_hex(utils.sha3(rlp.encode([])))
    }
    genesis = mk_basic_state(alloc, header, tester.get_env(None))
Exemple #25
0
def test_exponent_fail(bad_code):

    with raises(TypeMismatchException):
        compiler.compile(bad_code)
Exemple #26
0
def get_urs_bytecode(shard_id):
    global _urs_bytecode
    if not _urs_bytecode:
        _urs_bytecode = compiler.compile(get_urs_code(shard_id))
    return _urs_bytecode
Exemple #27
0
def test_nested_list_fail(bad_code):

    with raises(TypeMismatchException):
        compiler.compile(bad_code)
def test_as_wei_fail(bad_code):
    with raises(TypeMismatchException):
        compiler.compile(bad_code)
Exemple #29
0
def test_nested_list_sucess(good_code):
    assert compiler.compile(good_code) is not None
def test_as_wei_success(good_code):
    assert compiler.compile(good_code) is not None
Exemple #31
0
def test_tuple_return_fail(bad_code):

    with raises(StructureException):
            compiler.compile(bad_code)