def test_is_hex_string_prefixed_with_0x(self): """Unit test for checking whether hex string with 0x or not. """ def is_hex_string_prefixed_with_0x(value: str): if is_0x_prefixed(value) and is_lowercase_hex_string( remove_0x_prefix(value)): return True else: return False # 0x74657374 valid_value1 = add_0x_prefix("test".encode().hex()) self.assertTrue(is_hex_string_prefixed_with_0x(valid_value1)) # 74657374 invalid_value1 = remove_0x_prefix(valid_value1) self.assertFalse(is_hex_string_prefixed_with_0x(invalid_value1)) self.assertFalse( is_hex_string_prefixed_with_0x(add_cx_prefix(invalid_value1))) invalid_value2 = "Abcd" self.assertFalse(is_hex_string_prefixed_with_0x(invalid_value2)) self.assertFalse( is_hex_string_prefixed_with_0x(add_0x_prefix(invalid_value2))) invalid_value3 = "123aAc" self.assertFalse(is_hex_string_prefixed_with_0x(invalid_value3)) self.assertFalse( is_hex_string_prefixed_with_0x(add_0x_prefix(invalid_value3)))
def get_block(self, value): """ If param is height, 1. Returns block information by block height 2. Delegates to icx_getBlockByHeight RPC method Or block hash, 1. Returns block information by block hash 2. Delegates to icx_getBlockByHash RPC method Or string value same as `latest`, 1. Returns the last block information 2. Delegates to icx_getLastBlock RPC method :param value: Integer of a block height or hash of a block prefixed with '0x' or `latest` :return result: Block data """ # by height if is_block_height(value): params = {'height': add_0x_prefix(hex(value))} result = self.__provider.make_request('icx_getBlockByHeight', params) # by hash elif is_hex_block_hash(value): params = {'hash': value} result = self.__provider.make_request('icx_getBlockByHash', params) # by value elif is_predefined_block_value(value): result = self.__provider.make_request('icx_getLastBlock') else: raise DataTypeException("It's unrecognized block reference:{0!r}.".format(value)) return result
def keyinfo(self, conf: dict): """Show a keystore information with the the specified path and password. :param conf: keyinfo command configuration """ password = conf.get('password', None) password = self._check_keyinfo(password) try: wallet = KeyWallet.load(conf['path'], password) key_info = { "address": wallet.get_address(), "publicKey": convert_bytes_to_hex_str(wallet.public_key) } if conf['privateKey']: key_info['privateKey'] = add_0x_prefix(wallet.get_private_key()) print(json.dumps(key_info, indent=4)) return key_info except KeyStoreException as e: print(e.args[0])
def generate_data_value(transaction): """ Generates data value in transaction from the other data like content_type, content, method or params by data types such as deploy, call, message. """ if transaction.data_type == "deploy": # Content's data type is bytes and return value is hex string prefixed with '0x'. data = { "contentType": transaction.content_type, "content": add_0x_prefix(transaction.content.hex()) } # Params is an optional property. if transaction.params: data["params"] = convert_params_value_to_hex_str( transaction.params) elif transaction.data_type == "call": data = {"method": transaction.method} # Params is an optional property. if transaction.params: data["params"] = convert_params_value_to_hex_str( transaction.params) else: # When data type is message data = add_0x_prefix(transaction.data.encode().hex()) return data
def get_block(self, value: Union[int, str], full_response: bool = False) -> dict: """ If param is height, 1. Returns block information by block height 2. Delegates to icx_getBlockByHeight RPC method Or block hash, 1. Returns block information by block hash 2. Delegates to icx_getBlockByHash RPC method Or string value same as `latest`, 1. Returns the last block information 2. Delegates to icx_getLastBlock RPC method :param value: Integer of a block height or hash of a block prefixed with '0x' or `latest` :param full_response: Boolean to check whether get naive dict or refined data from server :return result: Block data """ # by height if is_block_height(value): params = {'height': add_0x_prefix(hex(value))} result = self.__provider.make_request('icx_getBlockByHeight', params, full_response) # by hash elif is_hex_block_hash(value): params = {'hash': value} result = self.__provider.make_request('icx_getBlockByHash', params, full_response) # by value elif is_predefined_block_value(value): result = self.__provider.make_request('icx_getLastBlock', full_response=full_response) else: raise DataTypeException( "It's unrecognized block reference:{0!r}.".format(value)) if not full_response: convert_block(result) return result
def test_get_block_by_hash(self): # case 0: when hash value of latest block is valid result = self.icon_service.get_block(self.valid_hash) self.assertTrue(result) # case 1: when hash value of the previous of latest block is valid if result["prev_block_hash"]: valid_hash_prev = add_0x_prefix(result["prev_block_hash"]) result = self.icon_service.get_block(valid_hash_prev) self.assertTrue(result) # case 2: when hash value is invalid not prefixed with `0x` invalid_hash = remove_0x_prefix(self.valid_hash) self.assertRaises(DataTypeException, self.icon_service.get_block, invalid_hash) # case 2: when block hash is wrong invalid_hash = "0x033f8d96045eb8301fd17cf078c28ae58a3ba329f6ada5cf128ee56dc2af26f7" self.assertRaises(JSONRPCException, self.icon_service.get_block, invalid_hash)
def test_validate_transaction(self): result = self.icon_service.get_transaction_result(self.tx_hash) self.assertTrue(is_transaction_result(result)) # case 1: when tx_hash is invalid - no prefixed self.assertRaises(DataTypeException, self.icon_service.get_transaction_result, remove_0x_prefix(self.tx_hash)) # case 2: when tx_hash is invalid - wrong prefixed self.assertRaises(DataTypeException, self.icon_service.get_transaction_result, add_cx_prefix(remove_0x_prefix(self.tx_hash))) # case 3: when tx_hash is invalid - too short self.assertRaises(DataTypeException, self.icon_service.get_transaction_result, self.tx_hash[:15]) # case 4: when tx_hash is invalid - not exist tx_hash_invalid = add_0x_prefix(os.urandom(32).hex()) self.assertRaises(JSONRPCException, self.icon_service.get_transaction_result, tx_hash_invalid)
def convert_block(data: dict) -> Optional[dict]: """ Convert block data into the right format. It supports data about a block made not only from JSON RPC V3 but also from V2. 1. If the genesis block, don't convert data because we can not know what data format it is. 2. Transaction list on a block has to be converted by the method 'convert_common_data_on_transaction' for each transaction. You can check what to do on the method in the docstring of the function 'convert_transaction'. 3. The field name 'tx_hash' on the transaction made from JSON RPC V2 has to be converted to 'txHash'. Furthermore, the value of the field has to be prefixed with '0x'. :param data: data about the block """ # Genesis block if data["height"] == 0: return data for transaction in data["confirmed_transaction_list"]: convert_common_data_on_transaction(transaction) if "tx_hash" in transaction: transaction["txHash"] = add_0x_prefix(transaction["tx_hash"]) del transaction["tx_hash"]
def convert_bytes_to_hex_str(value: bytes) -> str: """Converts bytes to hex string prefixed with '0x'.""" if is_bytes(value): return add_0x_prefix(value.hex()) else: raise DataTypeException("Data type should be bytes.")
def setUpClass(cls): cls.icon_service = IconService( HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST, VERSION_FOR_TEST)) result = cls.icon_service.get_block("latest") cls.valid_hash = add_0x_prefix(result["block_hash"])
def get_block(self, value: Union[int, str], full_response: bool = False, block_version: str = DEFAULT_BLOCK_VERSION) -> dict: """ If param is height, 1. Returns block information by block height 2-1. Delegates to icx_getBlockByHeight RPC method (When Block Version is 0.1a) 2-2. Delegates to icx_getBlock RPC method (When Block Version is 0.3) Or block hash, 1. Returns block information by block hash 2-1. Delegates to icx_getBlockByHash RPC method (When Block Version is 0.1a) 2-2. Delegates to icx_getBlock RPC method (When Block Version is 0.3) Or string value same as `latest`, 1. Returns the last block information 2-1. Delegates to icx_getLastBlock RPC method (When Block Version is 0.1a) 2-2. Delegates to icx_getBlock RPC method (When Block Version is 0.3) :param value: Integer of a block height or hash of a block prefixed with '0x' or `latest` :param full_response: Boolean to check whether get naive dict or refined data from server :param block_version: returning block format version :return result: Block data """ # Nested method of returning right name of API method def return_infos_by_block_version(_prev_method: str) -> Tuple[str, Any, bool]: """ Returns API method name, block template, bool of full print by block version :param _prev_method: previous API methods. For instance, icx_getBlockByHeight, icx_getBlockByHash and icx_getLastBlock :return: method name, block template, bool of full print """ new_method = "icx_getBlock" if block_version == self.DEFAULT_BLOCK_VERSION: return _prev_method, BLOCK_0_1a, False else: return new_method, BLOCK_0_3, True # by height if is_block_height(value): params = {'height': add_0x_prefix(hex(value))} prev_method = 'icx_getBlockByHeight' # by hash elif is_hex_block_hash(value): params = {'hash': value} prev_method = 'icx_getBlockByHash' # last block elif is_predefined_block_value(value): params = None prev_method = 'icx_getLastBlock' else: raise DataTypeException("It's unrecognized block reference:{0!r}.".format(value)) method, block_template, full_print = return_infos_by_block_version(prev_method) result = self.__provider.make_request(method, params, full_response) if not full_response: block_template = get_block_template_to_convert_transactions_for_genesis(result, block_template) result = convert(result, block_template, full_print) return result
def convert_int_to_hex_str(value: int): """Converts an integer to hex string prefixed with '0x'.""" if is_integer(value): return add_0x_prefix(hex(value)) else: raise DataTypeException("Data type should be integer.")
def get_timestamp(): """Get epoch time""" return add_0x_prefix(hex(int(time() * 10**6)))
def setUpClass(cls): cls.icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3)) result = cls.icon_service.get_block("latest") cls.valid_hash = add_0x_prefix(result["block_hash"])