def signTransaction(self, transaction_dict, private_key): if not isinstance(transaction_dict, Mapping): raise TypeError("transaction_dict must be dict-like, got %r" % transaction_dict) # check and set default if 'useLocal' not in transaction_dict: transaction_dict.setdefault('useLocal', False) if 'extra' not in transaction_dict: transaction_dict.setdefault('extra', "") user_local = "0" if transaction_dict["useLocal"]: user_local = "1" sign_str = transaction_dict["chainId"] + '-' + remove_0x_prefix(transaction_dict["from"].lower()) + '-' + \ remove_0x_prefix(transaction_dict["to"].lower()) + '-' + transaction_dict["nonce"] + '-' + \ user_local + '-' + transaction_dict["value"] + '-' + \ remove_0x_prefix(transaction_dict["input"].lower()) sign_str = sign_str + '-' if transaction_dict["extra"] != '': sign_str = sign_str + transaction_dict["extra"] sign_bytes = to_bytes(text=sign_str) res = eth_utils_keccak(sign_bytes) sign_hash = self.account.signHash(to_hex(res), private_key=private_key) transaction_dict["sig"] = to_hex(sign_hash.signature) pk = keys.PrivateKey(private_key) transaction_dict["pub"] = "0x04" + pk.public_key.to_hex()[2:] return transaction_dict
def signTransaction(self, transaction_dict, private_key): if not isinstance(transaction_dict, Mapping): raise TypeError("transaction_dict must be dict-like, got %r" % transaction_dict) sign_str = transaction_dict["chainId"] + remove_0x_prefix(transaction_dict["from"].lower()) + \ remove_0x_prefix(transaction_dict["to"].lower()) + transaction_dict["nonce"] + \ transaction_dict["value"] + remove_0x_prefix(transaction_dict["input"].lower()) sign_bytes = to_bytes(text=sign_str) res = eth_utils_keccak(sign_bytes) sign_hash = self.account.signHash(to_hex(res), private_key=private_key) print("sign_hash=", sign_hash) transaction_dict["sig"] = to_hex(sign_hash.signature) pk = keys.PrivateKey(private_key) transaction_dict["pub"] = "0x04" + pk.public_key.to_hex()[2:] return transaction_dict
def abi_bytes_to_hex(abi_type, type_str, data): if abi_type.base != 'bytes' or abi_type.is_array: return bytes_data = hexstr_if_str(to_bytes, data) if abi_type.sub is None: return type_str, to_hex(bytes_data) num_bytes = abi_type.sub if len(bytes_data) > num_bytes: raise ValueError( "This value was expected to be at most %d bytes, but instead was %d: %r" % ((num_bytes, len(bytes_data), data))) padded = bytes_data.ljust(num_bytes, b'\0') return type_str, to_hex(padded)
def encode_abi(w3: "Web3", abi: ABIFunction, arguments: Sequence[Any], data: Optional[HexStr] = None) -> HexStr: argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, w3.codec, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " f"ABI type. Expected types are: {', '.join(argument_types)}") normalizers = [ abi_ens_resolver(w3), abi_address_to_hex, abi_bytes_to_bytes, abi_string_to_text, ] normalized_arguments = map_abi_data( normalizers, argument_types, arguments, ) encoded_arguments = w3.codec.encode_abi( argument_types, normalized_arguments, ) if data: return to_hex(HexBytes(data) + encoded_arguments) else: return encode_hex(encoded_arguments)
def encode_abi(web3, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), )) normalizers = [ abi_ens_resolver(web3), abi_address_to_hex, abi_bytes_to_bytes, abi_string_to_text, ] normalized_arguments = map_abi_data( normalizers, argument_types, arguments, ) encoded_arguments = eth_abi_encode_abi( argument_types, normalized_arguments, ) if data: return to_hex(HexBytes(data) + encoded_arguments) else: return encode_hex(encoded_arguments)
def abi_bytes_to_hex(abi_type, data): base, sub, arrlist = process_type(abi_type) if base == 'bytes' and not arrlist: bytes_data = hexstr_if_str(to_bytes, data) if not sub: return abi_type, to_hex(bytes_data) else: num_bytes = int(sub) if len(bytes_data) <= num_bytes: padded = bytes_data.ljust(num_bytes, b'\0') return abi_type, to_hex(padded) else: raise ValueError( "This value was expected to be at most %d bytes, but instead was %d: %r" % ( (num_bytes, len(bytes_data), data) ) )
def test_conversion_round_trip(value): intermediate_value = to_hex(value) result_value = to_int(hexstr=intermediate_value) error_msg = "Expected: {0!r}, Result: {1!r}, Intermediate: {2!r}".format( value, result_value, intermediate_value, ) assert result_value == value, error_msg
def sign_munger( self, account: Union[Address, ChecksumAddress, ENS], data: Union[int, bytes] = None, hexstr: HexStr = None, text: str = None ) -> Tuple[Union[Address, ChecksumAddress, ENS], HexStr]: message_hex = to_hex(data, hexstr=hexstr, text=text) return (account, message_hex)
def signTransaction(transaction_dict, private_key): FULL_NODE_HOSTS = 'http://192.168.1.13:8089' provider = HTTPProvider (FULL_NODE_HOSTS) web3 = Web3 (provider) if not isinstance(transaction_dict, Mapping): raise TypeError("transaction_dict must be dict-like, got %r" % transaction_dict) sign_str = transaction_dict["chainId"] + remove_0x_prefix(transaction_dict["from"].lower()) + \ remove_0x_prefix(transaction_dict["to"].lower()) + transaction_dict["nonce"] + \ transaction_dict["value"] + remove_0x_prefix(transaction_dict["input"].lower()) sign_bytes = to_bytes(text=sign_str) res = eth_utils_keccak(sign_bytes) sign_hash = web3.eth.account.signHash(to_hex(res), private_key=private_key) transaction_dict["sig"] = to_hex(sign_hash.signature) pk = keys.PrivateKey(private_key) transaction_dict["pub"] = "0x04" + pk.public_key.to_hex()[2:] print(transaction_dict) return transaction_dict
def sign(self, account: Union[Address, ChecksumAddress, ENS], data: bytes = None, hexstr: HexStr = None, text: str = None) -> HexStr: message_hex = to_hex(data, hexstr=hexstr, text=text) return self.web3.manager.request_blocking( "eth_sign", [account, message_hex], )
def sign(self, account: Union[Address, ChecksumAddress, ENS], data: Optional[Union[int, bytes]] = None, hexstr: Optional[HexStr] = None, text: Optional[str] = None) -> HexStr: message_hex = to_hex(data, hexstr=hexstr, text=text) return self.web3.manager.request_blocking( RPC.eth_sign, [account, message_hex], )
def waitForTransactionReceipt(self, transaction_hash, timeout=120): try: return wait_for_transaction_receipt(self.web3, transaction_hash, timeout) except Timeout: raise TimeExhausted( "Transaction {} is not in the chain, after {} seconds".format( to_hex(transaction_hash), timeout, ) )
def signTransaction(transaction_dict, private_key): FULL_NODE_HOSTS = 'http://192.168.1.13:8089' provider = HTTPProvider(FULL_NODE_HOSTS) web3 = Web3(provider) if not isinstance(transaction_dict, Mapping): raise TypeError("transaction_dict must be dict-like, got %r" % transaction_dict) sign_str = transaction_dict["chainId"] + remove_0x_prefix(transaction_dict["from"].lower()) + \ remove_0x_prefix(transaction_dict["to"].lower()) + transaction_dict["nonce"] + \ transaction_dict["value"] + remove_0x_prefix(transaction_dict["input"].lower()) sign_bytes = to_bytes(text=sign_str) res = eth_utils_keccak(sign_bytes) sign_hash = web3.eth.account.signHash(to_hex(res), private_key=private_key) transaction_dict["sig"] = to_hex(sign_hash.signature) # pk = keys.PrivateKey(private_key) # transaction_dict["pub"] = "0x04" + pk.public_key.to_hex()[2:] transaction_dict[ "pub"] = "0x043d85aa2a649fa5fd421988cebff58d7173f7b563b8a9594e92bcf3e9f5e43037c3463121af51aacc8a8cf2d8cfcc6fa717b774fc0aceec04d7185c87e279c1f6" return transaction_dict
def waitForTransactionReceipt( self, transaction_hash: _Hash32, timeout: int=120, poll_latency: float=0.1 ) -> TxReceipt: try: return wait_for_transaction_receipt(self.web3, transaction_hash, timeout, poll_latency) except Timeout: raise TimeExhausted( "Transaction {} is not in the chain, after {} seconds".format( to_hex(transaction_hash), timeout, ) )
def _encode_data_in_transaction(self, *args, **kwargs): constructor_abi = get_constructor_abi(self.abi) if constructor_abi: if not args: args = tuple() if not kwargs: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) data = add_0x_prefix( encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode) ) else: data = to_hex(self.bytecode) return data
def _encode_data_in_transaction(self, *args, **kwargs): constructor_abi = get_constructor_abi(self.abi) if constructor_abi: if not args: args = tuple() if not kwargs: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) data = add_0x_prefix( encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode) ) else: data = to_hex(self.bytecode) return data
def _encode_constructor_data(cls, args=None, kwargs=None): constructor_abi = get_constructor_abi(cls.abi) if constructor_abi: if args is None: args = tuple() if kwargs is None: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode) ) else: deploy_data = to_hex(cls.bytecode) return deploy_data
def _encode_constructor_data(cls, args=None, kwargs=None): constructor_abi = get_constructor_abi(cls.abi) if constructor_abi: if args is None: args = tuple() if kwargs is None: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode) ) else: deploy_data = to_hex(cls.bytecode) return deploy_data
def _encode_constructor_data(cls, args=None, kwargs=None): constructor_abi = get_constructor_abi(cls.abi) if constructor_abi: if args is None: args = tuple() if kwargs is None: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode) ) else: if args is not None or kwargs is not None: msg = "Constructor args were provided, but no constructor function was provided." raise TypeError(msg) deploy_data = to_hex(cls.bytecode) return deploy_data
def encode_abi(web3, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), ) ) try: normalizers = [ abi_ens_resolver(web3), abi_address_to_hex, abi_bytes_to_bytes, abi_string_to_text, ] normalized_arguments = map_abi_data( normalizers, argument_types, arguments, ) encoded_arguments = eth_abi_encode_abi( argument_types, normalized_arguments, ) except EncodingError as e: raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type: {0}".format(str(e)) ) if data: return to_hex(HexBytes(data) + encoded_arguments) else: return encode_hex(encoded_arguments)
def toHex( primitive: Primitives = None, hexstr: HexStr = None, text: str = None ) -> HexStr: return to_hex(primitive, hexstr, text)
def test_to_hex(value, expected): assert to_hex(value) == expected
def to_hex_if_bytes(val): if isinstance(val, (bytes, bytearray)): return to_hex(val) else: return val
# print('new account => {0}'.format(new_account)) accounts = w3.eth.accounts print('accounts => {0}'.format(accounts)) balance = w3.eth.getBalance(accounts[0], 'latest') print('balance before tx => {0}'.format(balance)) blockNumber = 0 while True: bn = w3.eth.blockNumber print('block number => {0}'.format(bn)) transaction = {'from': accounts[0], 'to': accounts[0], 'value': 100} gas = get_buffered_gas_estimate(w3, transaction) gas_price = w3.eth.gasPrice # log_debug_print("use gas ", gas, "gasPrice", gas_price) transaction['gas'] = int(gas * 1) # transaction['gasPrice'] = int(gas_price * 1) tx_hash = w3.eth.sendTransaction(transaction) print('tx hash => {0}'.format(to_hex(tx_hash))) if bn > blockNumber: blockNumber = bn balance = w3.eth.getBalance(accounts[0], 'latest') print('balance after tx => {0}'.format(balance)) time.sleep(0.2)
def sign(self, account, data=None, hexstr=None, text=None): message_hex = to_hex(data, hexstr=hexstr, text=text) return self.web3.manager.request_blocking( "eth_sign", [account, message_hex], )
def sign(self, account, data=None, hexstr=None, text=None): message_hex = to_hex(data, hexstr=hexstr, text=text) return self.web3.manager.request_blocking( "eth_sign", [account, message_hex], )
def test_bytes_that_start_with_0x(): sneaky_bytes = b'0x\xde\xad' assert to_hex(sneaky_bytes) == '0x3078dead'