Beispiel #1
0
    def __init__(self, ctx, *args):
        assert isinstance(ctx, NativeABIContract)
        assert len(self.args) == len(args), \
            "%s called with wrong number of args" % self.__class__.__name__

        # topic0 sha3(EventName + signature)
        topics = [self.event_id()]

        indexed_args = []
        non_indexed_args = []
        for val, arg in zip(args, self.args):
            if arg['indexed']:
                indexed_args.append((arg['type'], val))
            else:
                non_indexed_args.append((arg['type'], val))

        assert len(indexed_args) <= 3
        # topics 1-n
        for typ, val in indexed_args:
            topics.append(big_endian_to_int(abi.encode_abi([typ], [val])))
        # remaining non indexed data
        data = abi.encode_abi([a[0] for a in non_indexed_args], [a[1] for a in non_indexed_args])

        # add log
        ctx._ext.log(ctx.address, topics, data)
Beispiel #2
0
def ethereum_event(eventid, eventabi, eventdata, contract_address):
    event_types = [
        param['type']
        for param in eventabi['inputs']
    ]

    event_data = [
        eventdata[param['name']]
        for param in eventabi['inputs']
        if not param['indexed']
    ]

    event_topics = [eventid] + [
        encode_single(param['type'], eventdata[param['name']])
        for param in eventabi['inputs']
        if param['indexed']
    ]

    event_data = encode_abi(event_types, event_data)

    event = {
        'topics': event_topics,
        'data': event_data,
        'address': contract_address,
    }
    return event
Beispiel #3
0
 def abi_args_signature(self, args):
     """
     Given the calling `args` for the function call, abi encode them.
     """
     if len(self.input_types) != len(args):
         raise ValueError("Expected {0} arguments, only got {1}".format(len(self.input_types), len(args)))  # NOQA
     scrubbed_args = tuple(clean_args(*zip(self.input_types, args)))
     return abi.encode_abi(self.input_types, scrubbed_args)
Beispiel #4
0
 def _db_encode_type(cls, value_type, val):
     if value_type in ('string', 'bytes', 'binary', 'address'):
         assert len(val) <= 32
         assert isinstance(val, bytes)
         return big_endian_to_int(val)
     data = abi.encode_abi([value_type], [val])
     assert len(data) <= 32
     return big_endian_to_int(data)
Beispiel #5
0
def run_abi_test(params, mode):
    types, args = params['types'], params['args']
    out = abi.encode_abi(types, args)
    assert abi.decode_abi(types, out) == args
    if mode == FILL:
        params['result'] = encode_hex(out)
        return params
    elif mode == VERIFY:
        assert params['result'] == encode_hex(out)
    elif mode == TIME:
        x = time.time()
        abi.encode_abi(types, args)
        y = time.time()
        abi.decode_abi(out, args)
        return {
            'encoding': y - x,
            'decoding': time.time() - y
        }
Beispiel #6
0
 def create_contract(self, from_, code, gas, sig=None, args=None):
     '''
     Create a contract on the blockchain from compiled EVM code. Returns the
     transaction hash.
     '''
     from_ = from_ or self.eth_coinbase()
     if sig is not None and args is not None:
          types = sig[sig.find('(') + 1: sig.find(')')].split(',')
          encoded_params = encode_abi(types, args)
          code += encoded_params.encode('hex')
     return self.eth_sendTransaction(from_address=from_, gas=gas, data=code)
Beispiel #7
0
def abi_encode_return_vals(method, vals):
    assert issubclass(method.im_class, NativeABIContract)
    return_types = method.im_class._get_method_abi(method)['return_types']
    # encode return value to list
    if isinstance(return_types, list):
        assert isinstance(vals, (list, tuple)) and len(vals) == len(return_types)
    elif vals is None:
        assert return_types is None
        return ''
    else:
        vals = (vals, )
        return_types = (return_types, )
    return abi.encode_abi(return_types, vals)
Beispiel #8
0
    def _encode_function(self, signature, param_values):

        prefix = utils.big_endian_to_int(utils.sha3(signature)[:4])

        if signature.find('(') == -1:
            raise RuntimeError('Invalid function signature. Missing "(" and/or ")"...')

        if signature.find(')') - signature.find('(') == 1:
            return utils.encode_int(prefix)

        types = signature[signature.find('(') + 1: signature.find(')')].split(',')
        encoded_params = encode_abi(types, param_values)
        return utils.zpad(utils.encode_int(prefix), 4) + encoded_params
Beispiel #9
0
def abi_data(sig, data):
    prefix = get_prefix(sig)
    data_abi = hex(prefix).rstrip('L')
    logger.debug("ABI prefix: %s" % data_abi)

    types = sig.split(':')[1][1:-1].split(',')
    logger.debug("ABI types: %s" % types)

    for i, s in enumerate(data):
        if isinstance(data[i], (str, unicode)) and data[i][:2] == "0x":
            data[i] = unhex(data[i])
    logger.debug("ABI data: %s" % data)

    data_abi += abi.encode_abi(types, data).encode('hex')
    logger.debug("ABI encoded: %s" % data_abi)

    return data_abi
Beispiel #10
0
def abi_data(fun_name, sig, data):
    types = []
    prefix = get_prefix(fun_name, sig)
    data_abi = hex(prefix).rstrip('L')

    for i, s in enumerate(sig):
        if s == 's':
            types.append('string')
        elif s == 'a':
            types.append('int256[]')
        else:
            if isinstance(data[i], (str, unicode)) and data[i][:2] == "0x":
                data[i] = unhex(data[i])
            types.append('int256')
    data_abi += abi.encode_abi(types, data).encode('hex')

    logger.debug("ABI data: %s" % data_abi)
    return data_abi
Beispiel #11
0
def ethereum_event(eventid, eventabi, eventdata, contract_address):
    event_types = [param['type'] for param in eventabi['inputs']]

    event_data = [
        eventdata[param['name']] for param in eventabi['inputs']
        if not param['indexed']
    ]

    event_topics = [eventid] + [
        encode_single(param['type'], eventdata[param['name']])
        for param in eventabi['inputs'] if param['indexed']
    ]

    event_data = encode_abi(event_types, event_data)

    event = {
        'topics': event_topics,
        'data': event_data,
        'address': contract_address,
    }
    return event
Beispiel #12
0
def test_event():
    event_abi = [{
        'name':
        'Test',
        'anonymous':
        False,
        'inputs': [
            {
                'indexed': False,
                'name': 'a',
                'type': 'int256'
            },
            {
                'indexed': False,
                'name': 'b',
                'type': 'int256'
            },
        ],
        'type':
        'event',
    }]

    contract_abi = ContractTranslator(event_abi)

    normalized_name = normalize_name('Test')
    encode_types = ['int256', 'int256']
    id_ = event_id(normalized_name, encode_types)

    topics = [id_]
    data = encode_abi(encode_types, [1, 2])

    result = contract_abi.decode_event(topics, data)

    assert result['_event_type'] == b'Test'
    assert result['a'] == 1
    assert result['b'] == 2
Beispiel #13
0
def test_encode_decode_int():
    int8 = ('int', '8', [])
    int32 = ('int', '32', [])
    int256 = ('int', '256', [])

    int8_values = [
        1,
        -1,
        127,
        -128,
    ]
    int32_values = [
        1,
        -1,
        127,
        -128,
        2**31 - 1,
        -2**31,
    ]
    int256_values = [
        1,
        -1,
        127,
        -128,
        2**31 - 1,
        -2**31,
        2**255 - 1,
        -2**255,
    ]

    for value in int8_values:
        assert encode_abi(['int8'], [value]) == encode_single(int8, value)
        assert decode_abi(['int8'], encode_abi(['int8'], [value]))[0] == value

    for value in int32_values:
        assert encode_abi(['int32'], [value]) == encode_single(int32, value)
        assert decode_abi(['int32'], encode_abi(['int32'],
                                                [value]))[0] == value

    for value in int256_values:
        assert encode_abi(['int256'], [value]) == encode_single(int256, value)
        assert decode_abi(['int256'], encode_abi(['int256'],
                                                 [value]))[0] == value
Beispiel #14
0
 def abi_args_signature(self, args):
     """
     Given the calling `args` for the function call, abi encode them.
     """
     return abi.encode_abi(self.input_types, args)
Beispiel #15
0
def test_abi_encode_signed_int():
    assert abi.decode_abi(['int8'], abi.encode_abi(['int8'], [1]))[0] == 1
    assert abi.decode_abi(['int8'], abi.encode_abi(['int8'], [-1]))[0] == -1
# -*- coding: utf-8 -*-

from ethereum.abi import encode_abi, encode_int


def encode_calldata(arg_types, args):
    args = encode_abi(arg_types, args)
    return args.hex()


if __name__ == '__main__':
    print(encode_abi(['uint256'], [12345]))
Beispiel #17
0
def abi_encode_args(method, args):
    "encode args for method: method_id|data"
    assert issubclass(method.im_class, NativeABIContract), method.im_class
    m_abi = method.im_class._get_method_abi(method)
    return zpad(encode_int(m_abi['id']), 4) + abi.encode_abi(m_abi['arg_types'], args)
Beispiel #18
0
def encode_calldata(func_name, arg_types, args):
    mid = method_id(func_name, arg_types)
    function_selector = zpad(encode_int(mid), 4)
    args = encode_abi(arg_types, args)
    return "0x" + function_selector.hex() + args.hex()
Beispiel #19
0
def test_abi_encode_signed_int():
    assert abi.decode_abi(['int8'], abi.encode_abi(['int8'], [1]))[0] == 1
    assert abi.decode_abi(['int8'], abi.encode_abi(['int8'], [-1]))[0] == -1
Beispiel #20
0
def test_abi_encode_var_sized_array():
    abi.encode_abi(['address[]'], [['\x00' * 20] * 3])
Beispiel #21
0
def test_abi_encode_var_sized_array():
    abi.encode_abi(['address[]'], [[b'\x00' * 20] * 3])
def encode_calldata(arg_types, args):
    args = encode_abi(arg_types, args)
    return args.hex()
Beispiel #23
0
def test_encode_decode_bool():
    assert decode_abi(['bool'], encode_abi(['bool'], [True]))[0] is True
    assert decode_abi(['bool'], encode_abi(['bool'], [False]))[0] is False
Beispiel #24
0
 def testAddress(self):
     addr = '407d73d8a49eeb85d32cf465507dd71d507100c1'
     enc = encode_abi(['address'], [
         str(bytearray.fromhex('407d73d8a49eeb85d32cf465507dd71d507100c1'))
     ]).encode('hex')
     self.assertEqual(enc[-40:], addr)
Beispiel #25
0
def test_abi_encode_fixed_size_array():
    abi.encode_abi(['uint16[2]'], [[5, 6]])
Beispiel #26
0
 def testEncodeAbi(self):
     enc = encode_abi(['uint32', 'uint32[]', 'bytes10', 'bytes'], [
         int(0x123), [int(0x456), int(0x789)], "1234567890", "Hello, world!"
     ]).encode('hex')
     data = "00000000000000000000000000000000000000000000000000000000000001230000000000000000000000000000000000000000000000000000000000000080313233343536373839300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000004560000000000000000000000000000000000000000000000000000000000000789000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20776f726c642100000000000000000000000000000000000000"
     self.assertEqual(enc, data)
Beispiel #27
0
def test_abi_encode_fixed_size_array():
    abi.encode_abi(['uint16[2]'], [[5, 6]])
Beispiel #28
0
def abi_encode_args(method, args):
    "encode args for method: method_id|data"
    assert issubclass(method.im_class, NativeABIContract), method.im_class
    m_abi = method.im_class._get_method_abi(method)
    return zpad(encode_int(m_abi['id']), 4) + abi.encode_abi(
        m_abi['arg_types'], args)