def decode_event(self, log_topics, log_data): """ Return a dictionary representation the log. Note: This function won't work with anonymous events. Args: log_topics (List[bin]): The log's indexed arguments. log_data (bin): The encoded non-indexed arguments. """ # https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector-and-argument-encoding # topics[0]: keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")") # If the event is declared as anonymous the topics[0] is not generated; if not len(log_topics) or log_topics[0] not in self.event_data: raise ValueError('Unknown log type') event_id_ = log_topics[0] event = self.event_data[event_id_] # data: abi_serialise(EVENT_NON_INDEXED_ARGS) # EVENT_NON_INDEXED_ARGS is the series of EVENT_ARGS that are not # indexed, abi_serialise is the ABI serialisation function used for # returning a series of typed values from a function. unindexed_types = [ type_ for type_, indexed in zip(event['types'], event['indexed']) if not indexed ] unindexed_args = decode_abi(unindexed_types, log_data) # topics[n]: EVENT_INDEXED_ARGS[n - 1] # EVENT_INDEXED_ARGS is the series of EVENT_ARGS that are indexed indexed_count = 1 # skip topics[0] result = {} for name, type_, indexed in zip(event['names'], event['types'], event['indexed']): if indexed: topic_bytes = utils.zpad( utils.encode_int(log_topics[indexed_count]), 32, ) indexed_count += 1 value = decode_single(process_type(type_), topic_bytes) else: value = unindexed_args.pop(0) result[name] = value result['_event_type'] = utils.to_string(event['name']) return result
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
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
def encode_function_call(self, function_name, args): """ Return the encoded function call. Args: function_name (str): One of the existing functions described in the contract interface. args (List[object]): The function arguments that wll be encoded and used in the contract execution in the vm. Return: bin: The encoded function name and arguments so that it can be used with the evm to execute a funcion call, the binary string follows the Ethereum Contract ABI. """ if function_name not in self.function_data: raise ValueError('Unkown function {}'.format(function_name)) description = self.function_data[function_name] function_selector = zpad(encode_int(description['prefix']), 4) arguments = encode_abi(description['encode_types'], args) return function_selector + arguments
def encode_single(typ, arg): # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements,too-many-locals ''' Encode `arg` as `typ`. `arg` will be encoded in a best effort manner, were necessary the function will try to correctly define the underlying binary representation (ie. decoding a hex-encoded address/hash). Args: typ (Tuple[(str, int, list)]): A 3-tuple defining the `arg` type. The first element defines the type name. The second element defines the type length in bits. The third element defines if it's an array type. Together the first and second defines the elementary type, the third element must be present but is ignored. Valid type names are: - uint - int - bool - ufixed - fixed - string - bytes - hash - address arg (object): The object to be encoded, it must be a python object compatible with the `typ`. Raises: ValueError: when an invalid `typ` is supplied. ValueOutOfBounds: when `arg` cannot be encoded as `typ` because of the binary contraints. Note: This function don't work with array types, for that use the `enc` function. ''' base, sub, _ = typ if base == 'uint': sub = int(sub) if not (0 < sub <= 256 and sub % 8 == 0): raise ValueError('invalid unsigned integer bit length {}'.format(sub)) try: i = decint(arg, signed=False) except EncodingError: # arg is larger than 2**256 raise ValueOutOfBounds(repr(arg)) if not 0 <= i < 2 ** sub: raise ValueOutOfBounds(repr(arg)) value_encoded = int_to_big_endian(i) return zpad(value_encoded, 32) if base == 'int': sub = int(sub) bits = sub - 1 if not (0 < sub <= 256 and sub % 8 == 0): raise ValueError('invalid integer bit length {}'.format(sub)) try: i = decint(arg, signed=True) except EncodingError: # arg is larger than 2**255 raise ValueOutOfBounds(repr(arg)) if not -2 ** bits <= i < 2 ** bits: raise ValueOutOfBounds(repr(arg)) value = i % 2 ** sub # convert negative to "equivalent" positive value_encoded = int_to_big_endian(value) return zpad(value_encoded, 32) if base == 'bool': if arg is True: value_encoded = int_to_big_endian(1) elif arg is False: value_encoded = int_to_big_endian(0) else: raise ValueError('%r is not bool' % arg) return zpad(value_encoded, 32) if base == 'ufixed': sub = str(sub) # pylint: disable=redefined-variable-type high_str, low_str = sub.split('x') high = int(high_str) low = int(low_str) if not (0 < high + low <= 256 and high % 8 == 0 and low % 8 == 0): raise ValueError('invalid unsigned fixed length {}'.format(sub)) if not 0 <= arg < 2 ** high: raise ValueOutOfBounds(repr(arg)) float_point = arg * 2 ** low fixed_point = int(float_point) return zpad(int_to_big_endian(fixed_point), 32) if base == 'fixed': sub = str(sub) # pylint: disable=redefined-variable-type high_str, low_str = sub.split('x') high = int(high_str) low = int(low_str) bits = high - 1 if not (0 < high + low <= 256 and high % 8 == 0 and low % 8 == 0): raise ValueError('invalid unsigned fixed length {}'.format(sub)) if not -2 ** bits <= arg < 2 ** bits: raise ValueOutOfBounds(repr(arg)) float_point = arg * 2 ** low fixed_point = int(float_point) value = fixed_point % 2 ** 256 return zpad(int_to_big_endian(value), 32) if base == 'string': if isinstance(arg, utils.unicode): arg = arg.encode('utf8') else: try: arg.decode('utf8') except UnicodeDecodeError: raise ValueError('string must be utf8 encoded') if len(sub): # fixed length if not 0 <= len(arg) <= int(sub): raise ValueError('invalid string length {}'.format(sub)) if not 0 <= int(sub) <= 32: raise ValueError('invalid string length {}'.format(sub)) return rzpad(arg, 32) if not 0 <= len(arg) < TT256: raise Exception('Integer invalid or out of range: %r' % arg) length_encoded = zpad(int_to_big_endian(len(arg)), 32) value_encoded = rzpad(arg, utils.ceil32(len(arg))) return length_encoded + value_encoded if base == 'bytes': if not is_string(arg): raise EncodingError('Expecting string: %r' % arg) arg = utils.to_string(arg) # py2: force unicode into str if len(sub): # fixed length if not 0 <= len(arg) <= int(sub): raise ValueError('string must be utf8 encoded') if not 0 <= int(sub) <= 32: raise ValueError('string must be utf8 encoded') return rzpad(arg, 32) if not 0 <= len(arg) < TT256: raise Exception('Integer invalid or out of range: %r' % arg) length_encoded = zpad(int_to_big_endian(len(arg)), 32) value_encoded = rzpad(arg, utils.ceil32(len(arg))) return length_encoded + value_encoded if base == 'hash': if not (int(sub) and int(sub) <= 32): raise EncodingError('too long: %r' % arg) if isnumeric(arg): return zpad(encode_int(arg), 32) if len(arg) == int(sub): return zpad(arg, 32) if len(arg) == int(sub) * 2: return zpad(decode_hex(arg), 32) raise EncodingError('Could not parse hash: %r' % arg) if base == 'address': assert sub == '' if isnumeric(arg): return zpad(encode_int(arg), 32) if len(arg) == 20: return zpad(arg, 32) if len(arg) == 40: return zpad(decode_hex(arg), 32) if len(arg) == 42 and arg[:2] == '0x': return zpad(decode_hex(arg[2:]), 32) raise EncodingError('Could not parse address: %r' % arg) raise EncodingError('Unhandled type: %r %r' % (base, sub))