Beispiel #1
0
 def test_get_transaction_invalid(self, _make_id):
     tx_hash = "0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
     # case 1: when tx_hash is invalid - no prefixed
     self.assertRaises(DataTypeException, self.icon_service.get_transaction,
                       remove_0x_prefix(tx_hash))
     # case 2: when tx_hash is invalid - wrong prefixed
     self.assertRaises(DataTypeException, self.icon_service.get_transaction,
                       add_cx_prefix(remove_0x_prefix(tx_hash)))
     # case 3: when tx_hash is invalid - too short
     self.assertRaises(DataTypeException, self.icon_service.get_transaction,
                       tx_hash[:15])
Beispiel #2
0
    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 test_get_transaction_by_hash(self):
     # case 0: when tx_hash is valid
     result = self.icon_service.get_transaction(self.tx_hash)
     self.assertTrue(result)
     # case 1: when tx_hash is invalid - no prefixed
     self.assertRaises(DataTypeException, self.icon_service.get_transaction,
                       remove_0x_prefix(self.tx_hash))
     # case 2: when tx_hash is invalid - wrong prefixed
     self.assertRaises(DataTypeException, self.icon_service.get_transaction,
                       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,
                       self.tx_hash[:15])
     # case 4: when tx_hash is invalid - not exist
     self.assertRaises(JSONRPCException, self.icon_service.get_transaction,
                       self.tx_hash_invalid)
    def __init__(self, from_: str, to: str, value: int, step_limit: int, nid: int, nonce: int, version: int,
                 timestamp: int, data: str):
        Transaction.__init__(self, from_, to, value, step_limit, nid, nonce, version, timestamp)

        if is_0x_prefixed(data) and is_lowercase_hex_string(remove_0x_prefix(data)):
            self.__data = data
        else:
            raise DataTypeException("Message data should be hex string prefixed with '0x'.")
Beispiel #5
0
def is_hex_block_hash(value) -> bool:
    """
    Checks the value - a parameter is valid.
    Hash value of a block starts with '0x' and 64 digits hex string

    :param value: hash value of a block, hexadecimal digits. type(str)
    :return: type(bool)
    """
    return is_str(value) and is_0x_prefixed(value) and len(remove_0x_prefix(value)) == 64
Beispiel #6
0
    def get_total_supply(self):
        """
        Returns total ICX coin supply that has been issued
        Delegates to icx_getTotalSupply RPC method

        :return: Total number of ICX coins issued
        """
        result = self.__provider.make_request('icx_getTotalSupply')
        return int(remove_0x_prefix(result), 16)
Beispiel #7
0
def is_T_HASH(value):
    """T_HASH is data type which is 64-digit hexadecimal string prefixed with `0x`."""
    try:
        if is_0x_prefixed(value) and len(remove_0x_prefix(value)) == 64:
            return True
        else:
            raise DataTypeException("This hash value is unrecognized.")
    except ValueError:
        raise DataTypeException("This hash value is unrecognized.")
Beispiel #8
0
    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)
Beispiel #9
0
def convert_common_data_on_transaction(transaction: dict):
    """
    Convert common fields in the transaction such as value, fee, nid, stepLimit, timestamp, nonce, method, version, data.
    Used in validating a transaction list in a block or validating a single transaction.

    1. Fields such as value, fee, nid, stepLimit, timestamp, and nonce have to be converted to an integer.
    2. Fields such as timestamp and nonce have a different type of the value by the version as V2 or V3.
        - If the version V3, the data type is hex string prefixed with '0x'.
        - If the version V2, the data type is a string but the meaning is an integer.
    3. The field 'method' has to be removed.
    4. The field 'version' has to be added number 2 if the version is 2 or if 3, has to be converted to an integer.
    5. If the field 'dataType' is 'deploy', the field 'content' has to be converted to bytes.
       Or if 'message', the field 'data' has to be converted to an integer.

    :param transaction: data about the single transaction
    """

    # List of Fields which have to be converted to int
    int_fields = ["value", "fee", "nid", "stepLimit"]

    for int_field in int_fields:
        if int_field in transaction:
            transaction[int_field] = convert_hex_str_to_int(
                transaction[int_field])

    odd_fields = ["timestamp", "nonce"]

    for odd_field in odd_fields:
        if odd_field in transaction:
            if is_integer(transaction[odd_field]):
                pass
            elif is_0x_prefixed(transaction[odd_field]):
                transaction[odd_field] = convert_hex_str_to_int(
                    transaction[odd_field])
            else:
                transaction[odd_field] = int(transaction[odd_field])

    if "method" in transaction:
        del transaction["method"]

    if "version" in transaction and convert_hex_str_to_int(
            transaction["version"]) >= 3:
        transaction["version"] = convert_hex_str_to_int(transaction["version"])
    else:
        transaction["version"] = 2

    if "dataType" in transaction:
        if transaction["dataType"] == "deploy":
            transaction["data"]["content"] = convert_hex_str_to_bytes(
                transaction["data"]["content"])
        elif transaction["dataType"] == "message":
            transaction["data"] = bytearray.fromhex(
                remove_0x_prefix(transaction["data"])).decode()
Beispiel #10
0
def is_T_BIN_DATA(value):
    """
    T_BIN_DATA is data type which is hexadeciamal string prefixed with `0x`
    and length is even.
    """
    try:
        if is_0x_prefixed(value) and len(remove_0x_prefix(value)) % 2 == 0:
            return True
        else:
            raise DataTypeException("This value is not T_BIN_DATA data type.")
    except ValueError:
        raise DataTypeException("This value is not T_BIN_DATA data type.")
Beispiel #11
0
    def test_get_block_by_hash(self, _make_id):
        with requests_mock.Mocker() as m:
            block_hash = "0x033f8d96045eb8301fd17cf078c28ae58a3ba329f6ada5cf128ee56dc2af26f7"
            expected_request = {
                'id': 1234,
                'jsonrpc': '2.0',
                'method': 'icx_getBlockByHash',
                'params': {
                    'hash': block_hash
                }
            }

            response_json = {
                "jsonrpc": "2.0",
                "result": {
                    "version": "0.1a",
                    "prev_block_hash": "cf43b3fd45981431a0e64f79d07bfcf703e064b73b802c5f32834eec72142190",
                    "merkle_tree_root_hash": "375540830d475a73b704cf8dee9fa9eba2798f9d2af1fa55a85482e48daefd3b",
                    "time_stamp": 1516819217223222,
                    "confirmed_transaction_list": [
                        {
                            "from": "hx54f7853dc6481b670caf69c5a27c7c8fe5be8269",
                            "to": "hx49a23bd156932485471f582897bf1bec5f875751",
                            "value": "0x56bc75e2d63100000",
                            "fee": "0x2386f26fc10000",
                            "nonce": "0x1",
                            "tx_hash": "375540830d475a73b704cf8dee9fa9eba2798f9d2af1fa55a85482e48daefd3b",
                            "signature": "bjarKeF3izGy469dpSciP3TT9caBQVYgHdaNgjY+8wJTOVSFm4o/ODXycFOdXUJcIwqvcE9If8x6Zmgt//XmkQE=",
                            "method": "icx_sendTransaction"
                        }
                    ],
                    "block_hash": "3add53134014e940f6f6010173781c4d8bd677d9931a697f962483e04a685e5c",
                    "height": 1,
                    "peer_id": "hx7e1a1ece096ef3fa44ac9692394c2e11d0017e4a",
                    "signature": "liAIa7aPYvBRdZAdBz6zt2Gc9vVo/4+gkDz5uscS8Mw+B5gkp6zQeHhD5sNpyWcIsq5c9OxwOCUaBp0vu8eAgwE=",
                    "next_leader": ""
                },
                "id": 1234
            }

            # case 0: when hash value of latest block is valid
            m.post(self.matcher, json=response_json)
            result = self.icon_service.get_block(block_hash)
            actual_request = json.loads(m._adapter.last_request.text)
            self.assertEqual(expected_request, actual_request)
            self.assertTrue(result)

            # case 1: when hash value is invalid not prefixed with `0x`
            invalid_hash = remove_0x_prefix(block_hash)
            self.assertRaises(DataTypeException, self.icon_service.get_block, invalid_hash)
Beispiel #12
0
    def get_balance(self, address: str):
        """
        Returns the ICX balance of the given EOA or SCORE.
        Delegates to icx_getBalance RPC method.

        :param address: An address of EOA or SCORE. type(str)
        :return: Number of ICX coins
        """
        if is_score_address(address) or is_wallet_address(address):
            params = {'address': address}
            result = self.__provider.make_request('icx_getBalance', params)
            return int(remove_0x_prefix(result), 16)
        else:
            raise AddressException("Address is wrong.")
    def get_total_supply(self, full_response: bool = False) -> Union[dict, int]:
        """
        Returns total ICX coin supply that has been issued
        Delegates to icx_getTotalSupply RPC method

        :param full_response: Boolean to check whether get naive dict or refined data from server
        :return: Total number of ICX coins issued
        """

        result = self.__provider.make_request('icx_getTotalSupply', full_response=full_response)

        if full_response:
            return result
        else:
            return int(remove_0x_prefix(result), 16)
Beispiel #14
0
    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 get_balance(self, address: str, full_response: bool = False) -> Union[dict, int]:
        """
        Returns the ICX balance of the given EOA or SCORE.
        Delegates to icx_getBalance RPC method.

        :param address: An address of EOA or SCORE. type(str)
        :param full_response: Boolean to check whether get naive dict or refined data from server
        :return: Number of ICX coins
        """
        if is_score_address(address) or is_wallet_address(address):
            params = {'address': address}

            result = self.__provider.make_request('icx_getBalance', params, full_response)

            if full_response:
                return result
            else:
                return int(remove_0x_prefix(result), 16)
        else:
            raise AddressException("Address is wrong.")
Beispiel #16
0
def convert_hex_str_to_bytes(value: str) -> bytes:
    """Converts hex string prefixed with '0x' into bytes."""
    if is_str(value):
        return bytes.fromhex(remove_0x_prefix(value))
    else:
        raise DataTypeException("Data type should be string.")
Beispiel #17
0
 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
Beispiel #18
0
def convert_hex_str_to_int(value: str):
    """Converts hex string prefixed with '0x' into int."""
    if is_str(value):
        return int(remove_0x_prefix(value), 16)
    else:
        raise DataTypeException("Data type should be string.")